Fix crash on cancellation of encodes during check of image data; allow cancellation...
[dcpomatic.git] / src / lib / writer.cc
1 /*
2     Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "writer.h"
21 #include "compose.hpp"
22 #include "film.h"
23 #include "ratio.h"
24 #include "log.h"
25 #include "dcp_video.h"
26 #include "dcp_content_type.h"
27 #include "audio_mapping.h"
28 #include "config.h"
29 #include "job.h"
30 #include "cross.h"
31 #include "audio_buffers.h"
32 #include "md5_digester.h"
33 #include "data.h"
34 #include "version.h"
35 #include "font.h"
36 #include "util.h"
37 #include <dcp/mono_picture_asset.h>
38 #include <dcp/stereo_picture_asset.h>
39 #include <dcp/sound_asset.h>
40 #include <dcp/sound_asset_writer.h>
41 #include <dcp/reel.h>
42 #include <dcp/reel_mono_picture_asset.h>
43 #include <dcp/reel_stereo_picture_asset.h>
44 #include <dcp/reel_sound_asset.h>
45 #include <dcp/reel_subtitle_asset.h>
46 #include <dcp/dcp.h>
47 #include <dcp/cpl.h>
48 #include <dcp/certificate_chain.h>
49 #include <dcp/interop_subtitle_asset.h>
50 #include <dcp/smpte_subtitle_asset.h>
51 #include <boost/foreach.hpp>
52 #include <fstream>
53 #include <cerrno>
54
55 #include "i18n.h"
56
57 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
58 #define LOG_DEBUG_ENCODE(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_DEBUG_ENCODE);
59 #define LOG_TIMING(...) _film->log()->microsecond_log (String::compose (__VA_ARGS__), Log::TYPE_TIMING);
60 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_WARNING);
61 #define LOG_WARNING(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_WARNING);
62 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
63
64 /* OS X strikes again */
65 #undef set_key
66
67 using std::make_pair;
68 using std::pair;
69 using std::string;
70 using std::list;
71 using std::cout;
72 using boost::shared_ptr;
73 using boost::weak_ptr;
74 using boost::dynamic_pointer_cast;
75
76 Writer::Writer (shared_ptr<const Film> film, weak_ptr<Job> j)
77         : _film (film)
78         , _job (j)
79         , _first_nonexistant_frame (0)
80         , _thread (0)
81         , _finish (false)
82         , _queued_full_in_memory (0)
83         , _last_written_frame (-1)
84         , _last_written_eyes (EYES_RIGHT)
85         , _maximum_frames_in_memory (0)
86         , _full_written (0)
87         , _fake_written (0)
88         , _repeat_written (0)
89         , _pushed_to_disk (0)
90 {
91         /* Remove any old DCP */
92         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
93
94         shared_ptr<Job> job = _job.lock ();
95         DCPOMATIC_ASSERT (job);
96
97         /* Create our picture asset in a subdirectory, named according to those
98            film's parameters which affect the video output.  We will hard-link
99            it into the DCP later.
100         */
101
102         if (_film->three_d ()) {
103                 _picture_asset.reset (new dcp::StereoPictureAsset (dcp::Fraction (_film->video_frame_rate (), 1)));
104         } else {
105                 _picture_asset.reset (new dcp::MonoPictureAsset (dcp::Fraction (_film->video_frame_rate (), 1)));
106         }
107
108         _picture_asset->set_size (_film->frame_size ());
109
110         if (_film->encrypted ()) {
111                 _picture_asset->set_key (_film->key ());
112         }
113
114         _picture_asset->set_file (
115                 _film->internal_video_asset_dir() / _film->internal_video_asset_filename()
116                 );
117
118         job->sub (_("Checking existing image data"));
119         check_existing_picture_asset ();
120
121         _picture_asset_writer = _picture_asset->start_write (
122                 _film->internal_video_asset_dir() / _film->internal_video_asset_filename(),
123                 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
124                 _first_nonexistant_frame > 0
125                 );
126
127         if (_film->audio_channels ()) {
128                 _sound_asset.reset (
129                         new dcp::SoundAsset (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ())
130                         );
131
132                 if (_film->encrypted ()) {
133                         _sound_asset->set_key (_film->key ());
134                 }
135
136                 /* Write the sound asset into the film directory so that we leave the creation
137                    of the DCP directory until the last minute.
138                 */
139                 _sound_asset_writer = _sound_asset->start_write (
140                         _film->directory() / audio_asset_filename (_sound_asset),
141                         _film->interop() ? dcp::INTEROP : dcp::SMPTE
142                         );
143         }
144
145         /* Check that the signer is OK if we need one */
146         if (_film->is_signed() && !Config::instance()->signer_chain()->valid ()) {
147                 throw InvalidSignerError ();
148         }
149
150         job->sub (_("Encoding image data"));
151
152         /* Do this last; if something after this line were to throw an exception
153            (say if Job::sub was interrupted by cancel) this thread would never
154            get properly cleaned up but the Writer object would go away underneath
155            it.
156         */
157         _thread = new boost::thread (boost::bind (&Writer::thread, this));
158 }
159
160 Writer::~Writer ()
161 {
162         terminate_thread (false);
163 }
164
165 void
166 Writer::write (Data encoded, int frame, Eyes eyes)
167 {
168         boost::mutex::scoped_lock lock (_state_mutex);
169
170         while (_queued_full_in_memory > _maximum_frames_in_memory) {
171                 /* The queue is too big; wait until that is sorted out */
172                 _full_condition.wait (lock);
173         }
174
175         QueueItem qi;
176         qi.type = QueueItem::FULL;
177         qi.encoded = encoded;
178         qi.frame = frame;
179
180         if (_film->three_d() && eyes == EYES_BOTH) {
181                 /* 2D material in a 3D DCP; fake the 3D */
182                 qi.eyes = EYES_LEFT;
183                 _queue.push_back (qi);
184                 ++_queued_full_in_memory;
185                 qi.eyes = EYES_RIGHT;
186                 _queue.push_back (qi);
187                 ++_queued_full_in_memory;
188         } else {
189                 qi.eyes = eyes;
190                 _queue.push_back (qi);
191                 ++_queued_full_in_memory;
192         }
193
194         /* Now there's something to do: wake anything wait()ing on _empty_condition */
195         _empty_condition.notify_all ();
196 }
197
198 void
199 Writer::repeat (int frame, Eyes eyes)
200 {
201         boost::mutex::scoped_lock lock (_state_mutex);
202
203         while (_queued_full_in_memory > _maximum_frames_in_memory) {
204                 /* The queue is too big; wait until that is sorted out */
205                 _full_condition.wait (lock);
206         }
207
208         QueueItem qi;
209         qi.type = QueueItem::REPEAT;
210         qi.frame = frame;
211         if (_film->three_d() && eyes == EYES_BOTH) {
212                 qi.eyes = EYES_LEFT;
213                 _queue.push_back (qi);
214                 qi.eyes = EYES_RIGHT;
215                 _queue.push_back (qi);
216         } else {
217                 qi.eyes = eyes;
218                 _queue.push_back (qi);
219         }
220
221         /* Now there's something to do: wake anything wait()ing on _empty_condition */
222         _empty_condition.notify_all ();
223 }
224
225 void
226 Writer::fake_write (int frame, Eyes eyes)
227 {
228         boost::mutex::scoped_lock lock (_state_mutex);
229
230         while (_queued_full_in_memory > _maximum_frames_in_memory) {
231                 /* The queue is too big; wait until that is sorted out */
232                 _full_condition.wait (lock);
233         }
234
235         FILE* file = fopen_boost (_film->info_file (), "rb");
236         if (!file) {
237                 throw ReadFileError (_film->info_file ());
238         }
239         dcp::FrameInfo info = read_frame_info (file, frame, eyes);
240         fclose (file);
241
242         QueueItem qi;
243         qi.type = QueueItem::FAKE;
244         qi.size = info.size;
245         qi.frame = frame;
246         if (_film->three_d() && eyes == EYES_BOTH) {
247                 qi.eyes = EYES_LEFT;
248                 _queue.push_back (qi);
249                 qi.eyes = EYES_RIGHT;
250                 _queue.push_back (qi);
251         } else {
252                 qi.eyes = eyes;
253                 _queue.push_back (qi);
254         }
255
256         /* Now there's something to do: wake anything wait()ing on _empty_condition */
257         _empty_condition.notify_all ();
258 }
259
260 /** This method is not thread safe */
261 void
262 Writer::write (shared_ptr<const AudioBuffers> audio)
263 {
264         if (_sound_asset_writer) {
265                 _sound_asset_writer->write (audio->data(), audio->frames());
266         }
267 }
268
269 /** This must be called from Writer::thread() with an appropriate lock held */
270 bool
271 Writer::have_sequenced_image_at_queue_head ()
272 {
273         if (_queue.empty ()) {
274                 return false;
275         }
276
277         _queue.sort ();
278
279         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
280
281         if (_queue.front().eyes == EYES_BOTH) {
282                 /* 2D */
283                 return _queue.front().frame == (_last_written_frame + 1);
284         }
285
286         /* 3D */
287
288         if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
289                 return true;
290         }
291
292         if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
293                 return true;
294         }
295
296         return false;
297 }
298
299 void
300 Writer::write_frame_info (int frame, Eyes eyes, dcp::FrameInfo info) const
301 {
302         FILE* file = 0;
303         if (boost::filesystem::exists (_film->info_file ())) {
304                 file = fopen_boost (_film->info_file(), "r+b");
305         } else {
306                 file = fopen_boost (_film->info_file(), "wb");
307         }
308         if (!file) {
309                 throw OpenFileError (_film->info_file ());
310         }
311         dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
312         fwrite (&info.offset, sizeof (info.offset), 1, file);
313         fwrite (&info.size, sizeof (info.size), 1, file);
314         fwrite (info.hash.c_str(), 1, info.hash.size(), file);
315         fclose (file);
316 }
317
318 void
319 Writer::thread ()
320 try
321 {
322         while (true)
323         {
324                 boost::mutex::scoped_lock lock (_state_mutex);
325
326                 while (true) {
327
328                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
329                                 /* We've got something to do: go and do it */
330                                 break;
331                         }
332
333                         /* Nothing to do: wait until something happens which may indicate that we do */
334                         LOG_TIMING (N_("writer-sleep queue=%1"), _queue.size());
335                         _empty_condition.wait (lock);
336                         LOG_TIMING (N_("writer-wake queue=%1"), _queue.size());
337                 }
338
339                 if (_finish && _queue.empty()) {
340                         return;
341                 }
342
343                 /* We stop here if we have been asked to finish, and if either the queue
344                    is empty or we do not have a sequenced image at its head (if this is the
345                    case we will never terminate as no new frames will be sent once
346                    _finish is true).
347                 */
348                 if (_finish && (!have_sequenced_image_at_queue_head() || _queue.empty())) {
349                         /* (Hopefully temporarily) log anything that was not written */
350                         if (!_queue.empty() && !have_sequenced_image_at_queue_head()) {
351                                 LOG_WARNING (N_("Finishing writer with a left-over queue of %1:"), _queue.size());
352                                 for (list<QueueItem>::const_iterator i = _queue.begin(); i != _queue.end(); ++i) {
353                                         if (i->type == QueueItem::FULL) {
354                                                 LOG_WARNING (N_("- type FULL, frame %1, eyes %2"), i->frame, i->eyes);
355                                         } else {
356                                                 LOG_WARNING (N_("- type FAKE, size %1, frame %2, eyes %3"), i->size, i->frame, i->eyes);
357                                         }
358                                 }
359                                 LOG_WARNING (N_("Last written frame %1, last written eyes %2"), _last_written_frame, _last_written_eyes);
360                         }
361                         return;
362                 }
363                 /* Write any frames that we can write; i.e. those that are in sequence. */
364                 while (have_sequenced_image_at_queue_head ()) {
365                         QueueItem qi = _queue.front ();
366                         _queue.pop_front ();
367                         if (qi.type == QueueItem::FULL && qi.encoded) {
368                                 --_queued_full_in_memory;
369                         }
370
371                         lock.unlock ();
372                         switch (qi.type) {
373                         case QueueItem::FULL:
374                         {
375                                 LOG_DEBUG_ENCODE (N_("Writer FULL-writes %1 (%2)"), qi.frame, qi.eyes);
376                                 if (!qi.encoded) {
377                                         qi.encoded = Data (_film->j2c_path (qi.frame, qi.eyes, false));
378                                 }
379
380                                 dcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data().get (), qi.encoded->size());
381                                 write_frame_info (qi.frame, qi.eyes, fin);
382                                 _last_written[qi.eyes] = qi.encoded;
383                                 ++_full_written;
384                                 break;
385                         }
386                         case QueueItem::FAKE:
387                                 LOG_DEBUG_ENCODE (N_("Writer FAKE-writes %1"), qi.frame);
388                                 _picture_asset_writer->fake_write (qi.size);
389                                 _last_written[qi.eyes].reset ();
390                                 ++_fake_written;
391                                 break;
392                         case QueueItem::REPEAT:
393                                 LOG_DEBUG_ENCODE (N_("Writer REPEAT-writes %1"), qi.frame);
394                                 dcp::FrameInfo fin = _picture_asset_writer->write (
395                                         _last_written[qi.eyes]->data().get(),
396                                         _last_written[qi.eyes]->size()
397                                         );
398                                 write_frame_info (qi.frame, qi.eyes, fin);
399                                 ++_repeat_written;
400                                 break;
401                         }
402                         lock.lock ();
403
404                         _last_written_frame = qi.frame;
405                         _last_written_eyes = qi.eyes;
406
407                         shared_ptr<Job> job = _job.lock ();
408                         DCPOMATIC_ASSERT (job);
409                         int64_t total = _film->length().frames_round (_film->video_frame_rate ());
410                         if (_film->three_d ()) {
411                                 /* _full_written and so on are incremented for each eye, so we need to double the total
412                                    frames to get the correct progress.
413                                 */
414                                 total *= 2;
415                         }
416                         if (total) {
417                                 job->set_progress (float (_full_written + _fake_written + _repeat_written) / total);
418                         }
419                 }
420
421                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
422                         /* Too many frames in memory which can't yet be written to the stream.
423                            Write some FULL frames to disk.
424                         */
425
426                         /* Find one from the back of the queue */
427                         _queue.sort ();
428                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
429                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
430                                 ++i;
431                         }
432
433                         DCPOMATIC_ASSERT (i != _queue.rend());
434                         ++_pushed_to_disk;
435                         lock.unlock ();
436
437                         /* i is valid here, even though we don't hold a lock on the mutex,
438                            since list iterators are unaffected by insertion and only this
439                            thread could erase the last item in the list.
440                         */
441
442                         LOG_GENERAL (
443                                 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
444                                 _last_written_frame + 1,
445                                 _last_written_eyes, i->frame
446                                 );
447
448                         i->encoded->write_via_temp (_film->j2c_path (i->frame, i->eyes, true), _film->j2c_path (i->frame, i->eyes, false));
449
450                         lock.lock ();
451                         i->encoded.reset ();
452                         --_queued_full_in_memory;
453                 }
454
455                 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
456                 _full_condition.notify_all ();
457         }
458 }
459 catch (...)
460 {
461         store_current ();
462 }
463
464 void
465 Writer::terminate_thread (bool can_throw)
466 {
467         boost::mutex::scoped_lock lock (_state_mutex);
468         if (_thread == 0) {
469                 return;
470         }
471
472         _finish = true;
473         _empty_condition.notify_all ();
474         _full_condition.notify_all ();
475         lock.unlock ();
476
477         _thread->join ();
478         if (can_throw) {
479                 rethrow ();
480         }
481
482         delete _thread;
483         _thread = 0;
484 }
485
486 void
487 Writer::finish ()
488 {
489         if (!_thread) {
490                 return;
491         }
492
493         terminate_thread (true);
494
495         _picture_asset_writer->finalize ();
496         if (_sound_asset_writer) {
497                 _sound_asset_writer->finalize ();
498         }
499
500         /* Hard-link the video asset into the DCP */
501         boost::filesystem::path video_from = _picture_asset->file ();
502
503         boost::filesystem::path video_to;
504         video_to /= _film->dir (_film->dcp_name());
505         video_to /= video_asset_filename (_picture_asset);
506
507         boost::system::error_code ec;
508         boost::filesystem::create_hard_link (video_from, video_to, ec);
509         if (ec) {
510                 LOG_WARNING_NC ("Hard-link failed; copying instead");
511                 boost::filesystem::copy_file (video_from, video_to, ec);
512                 if (ec) {
513                         LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
514                         throw FileError (ec.message(), video_from);
515                 }
516         }
517
518         _picture_asset->set_file (video_to);
519
520         /* Move the audio asset into the DCP */
521
522         if (_sound_asset) {
523                 boost::filesystem::path audio_to;
524                 audio_to /= _film->dir (_film->dcp_name ());
525                 audio_to /= audio_asset_filename (_sound_asset);
526
527                 boost::filesystem::rename (_film->file (audio_asset_filename (_sound_asset)), audio_to, ec);
528                 if (ec) {
529                         throw FileError (
530                                 String::compose (_("could not move audio asset into the DCP (%1)"), ec.value ()), audio_asset_filename (_sound_asset)
531                                 );
532                 }
533
534                 _sound_asset->set_file (audio_to);
535         }
536
537         dcp::DCP dcp (_film->dir (_film->dcp_name()));
538
539         shared_ptr<dcp::CPL> cpl (
540                 new dcp::CPL (
541                         _film->dcp_name(),
542                         _film->dcp_content_type()->libdcp_kind ()
543                         )
544                 );
545
546         dcp.add (cpl);
547
548         shared_ptr<dcp::Reel> reel (new dcp::Reel ());
549
550         shared_ptr<dcp::MonoPictureAsset> mono = dynamic_pointer_cast<dcp::MonoPictureAsset> (_picture_asset);
551         if (mono) {
552                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
553         }
554
555         shared_ptr<dcp::StereoPictureAsset> stereo = dynamic_pointer_cast<dcp::StereoPictureAsset> (_picture_asset);
556         if (stereo) {
557                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
558         }
559
560         if (_sound_asset) {
561                 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_asset, 0)));
562         }
563
564         if (_subtitle_asset) {
565                 boost::filesystem::path liberation;
566                 try {
567                         liberation = shared_path () / "LiberationSans-Regular.ttf";
568                 } catch (boost::filesystem::filesystem_error& e) {
569                         /* Hack: try the debian/ubuntu location if getting the shared path failed */
570                         liberation = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf";
571                 }
572
573                 /* Add all the fonts to the subtitle content */
574                 BOOST_FOREACH (shared_ptr<Font> i, _fonts) {
575                         _subtitle_asset->add_font (i->id(), i->file().get_value_or (liberation));
576                 }
577
578                 if (dynamic_pointer_cast<dcp::InteropSubtitleAsset> (_subtitle_asset)) {
579                         boost::filesystem::path directory = _film->dir (_film->dcp_name ()) / _subtitle_asset->id ();
580                         boost::filesystem::create_directories (directory);
581                         _subtitle_asset->write (directory / ("sub_" + _subtitle_asset->id() + ".xml"));
582                 } else {
583                         _subtitle_asset->write (
584                                 _film->dir (_film->dcp_name ()) / ("sub_" + _subtitle_asset->id() + ".mxf")
585                                 );
586                 }
587
588                 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
589                                    new dcp::ReelSubtitleAsset (
590                                            _subtitle_asset,
591                                            dcp::Fraction (_film->video_frame_rate(), 1),
592                                            _picture_asset->intrinsic_duration (),
593                                            0
594                                            )
595                                    ));
596         }
597
598         cpl->add (reel);
599
600         shared_ptr<Job> job = _job.lock ();
601         DCPOMATIC_ASSERT (job);
602
603         job->sub (_("Computing image digest"));
604         _picture_asset->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
605
606         if (_sound_asset) {
607                 job->sub (_("Computing audio digest"));
608                 _sound_asset->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
609         }
610
611         dcp::XMLMetadata meta;
612         meta.creator = Config::instance()->dcp_creator ();
613         if (meta.creator.empty ()) {
614                 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
615         }
616         meta.issuer = Config::instance()->dcp_issuer ();
617         if (meta.issuer.empty ()) {
618                 meta.issuer = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
619         }
620         meta.set_issue_date_now ();
621
622         cpl->set_metadata (meta);
623
624         shared_ptr<const dcp::CertificateChain> signer;
625         if (_film->is_signed ()) {
626                 signer = Config::instance()->signer_chain ();
627                 /* We did check earlier, but check again here to be on the safe side */
628                 if (!signer->valid ()) {
629                         throw InvalidSignerError ();
630                 }
631         }
632
633         dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
634
635         LOG_GENERAL (
636                 N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT, %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk
637                 );
638 }
639
640 bool
641 Writer::check_existing_picture_asset_frame (FILE* asset, int f, Eyes eyes)
642 {
643         /* Read the frame info as written */
644         FILE* file = fopen_boost (_film->info_file (), "rb");
645         if (!file) {
646                 LOG_GENERAL ("Existing frame %1 has no info file", f);
647                 return false;
648         }
649
650         dcp::FrameInfo info = read_frame_info (file, f, eyes);
651         fclose (file);
652         if (info.size == 0) {
653                 LOG_GENERAL ("Existing frame %1 has no info file", f);
654                 return false;
655         }
656
657         /* Read the data from the asset and hash it */
658         dcpomatic_fseek (asset, info.offset, SEEK_SET);
659         Data data (info.size);
660         size_t const read = fread (data.data().get(), 1, data.size(), asset);
661         if (read != static_cast<size_t> (data.size ())) {
662                 LOG_GENERAL ("Existing frame %1 is incomplete", f);
663                 return false;
664         }
665
666         MD5Digester digester;
667         digester.add (data.data().get(), data.size());
668         if (digester.get() != info.hash) {
669                 LOG_GENERAL ("Existing frame %1 failed hash check", f);
670                 return false;
671         }
672
673         return true;
674 }
675
676 void
677 Writer::check_existing_picture_asset ()
678 {
679         /* Try to open the existing asset */
680         FILE* asset = fopen_boost (_picture_asset->file(), "rb");
681         if (!asset) {
682                 LOG_GENERAL ("Could not open existing asset at %1 (errno=%2)", _picture_asset->file().string(), errno);
683                 return;
684         }
685
686         while (true) {
687
688                 shared_ptr<Job> job = _job.lock ();
689                 DCPOMATIC_ASSERT (job);
690
691                 job->set_progress_unknown ();
692
693                 if (_film->three_d ()) {
694                         if (!check_existing_picture_asset_frame (asset, _first_nonexistant_frame, EYES_LEFT)) {
695                                 break;
696                         }
697                         if (!check_existing_picture_asset_frame (asset, _first_nonexistant_frame, EYES_RIGHT)) {
698                                 break;
699                         }
700                 } else {
701                         if (!check_existing_picture_asset_frame (asset, _first_nonexistant_frame, EYES_BOTH)) {
702                                 break;
703                         }
704                 }
705
706                 LOG_DEBUG_ENCODE ("Have existing frame %1", _first_nonexistant_frame);
707                 ++_first_nonexistant_frame;
708         }
709
710         fclose (asset);
711 }
712
713 /** @param frame Frame index.
714  *  @return true if we can fake-write this frame.
715  */
716 bool
717 Writer::can_fake_write (int frame) const
718 {
719         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
720            parameters in the asset writer.
721         */
722         return (frame != 0 && frame < _first_nonexistant_frame);
723 }
724
725 void
726 Writer::write (PlayerSubtitles subs)
727 {
728         if (subs.text.empty ()) {
729                 return;
730         }
731
732         if (!_subtitle_asset) {
733                 string lang = _film->subtitle_language ();
734                 if (lang.empty ()) {
735                         lang = "Unknown";
736                 }
737                 if (_film->interop ()) {
738                         shared_ptr<dcp::InteropSubtitleAsset> s (new dcp::InteropSubtitleAsset ());
739                         s->set_movie_title (_film->name ());
740                         s->set_language (lang);
741                         s->set_reel_number ("1");
742                         _subtitle_asset = s;
743                 } else {
744                         shared_ptr<dcp::SMPTESubtitleAsset> s (new dcp::SMPTESubtitleAsset ());
745                         s->set_content_title_text (_film->name ());
746                         s->set_language (lang);
747                         s->set_edit_rate (dcp::Fraction (_film->video_frame_rate (), 1));
748                         s->set_time_code_rate (_film->video_frame_rate ());
749                         _subtitle_asset = s;
750                 }
751         }
752
753         for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
754                 _subtitle_asset->add (*i);
755         }
756 }
757
758 void
759 Writer::write (list<shared_ptr<Font> > fonts)
760 {
761         /* Just keep a list of fonts and we'll deal with them in ::finish */
762         copy (fonts.begin (), fonts.end (), back_inserter (_fonts));
763 }
764
765 bool
766 operator< (QueueItem const & a, QueueItem const & b)
767 {
768         if (a.frame != b.frame) {
769                 return a.frame < b.frame;
770         }
771
772         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
773 }
774
775 bool
776 operator== (QueueItem const & a, QueueItem const & b)
777 {
778         return a.frame == b.frame && a.eyes == b.eyes;
779 }
780
781 void
782 Writer::set_encoder_threads (int threads)
783 {
784         _maximum_frames_in_memory = lrint (threads * 1.1);
785 }
786
787 long
788 Writer::frame_info_position (int frame, Eyes eyes) const
789 {
790         static int const info_size = 48;
791
792         switch (eyes) {
793         case EYES_BOTH:
794                 return frame * info_size;
795         case EYES_LEFT:
796                 return frame * info_size * 2;
797         case EYES_RIGHT:
798                 return frame * info_size * 2 + info_size;
799         default:
800                 DCPOMATIC_ASSERT (false);
801         }
802
803         DCPOMATIC_ASSERT (false);
804 }
805
806 dcp::FrameInfo
807 Writer::read_frame_info (FILE* file, int frame, Eyes eyes) const
808 {
809         dcp::FrameInfo info;
810         dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
811         fread (&info.offset, sizeof (info.offset), 1, file);
812         fread (&info.size, sizeof (info.size), 1, file);
813
814         char hash_buffer[33];
815         fread (hash_buffer, 1, 32, file);
816         hash_buffer[32] = '\0';
817         info.hash = hash_buffer;
818
819         return info;
820 }