Don't start thread in constructor. (Writer)
[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
153 void
154 Writer::start ()
155 {
156         _thread = new boost::thread (boost::bind (&Writer::thread, this));
157 }
158
159 Writer::~Writer ()
160 {
161         terminate_thread (false);
162 }
163
164 void
165 Writer::write (Data encoded, int frame, Eyes eyes)
166 {
167         boost::mutex::scoped_lock lock (_state_mutex);
168
169         while (_queued_full_in_memory > _maximum_frames_in_memory) {
170                 /* The queue is too big; wait until that is sorted out */
171                 _full_condition.wait (lock);
172         }
173
174         QueueItem qi;
175         qi.type = QueueItem::FULL;
176         qi.encoded = encoded;
177         qi.frame = frame;
178
179         if (_film->three_d() && eyes == EYES_BOTH) {
180                 /* 2D material in a 3D DCP; fake the 3D */
181                 qi.eyes = EYES_LEFT;
182                 _queue.push_back (qi);
183                 ++_queued_full_in_memory;
184                 qi.eyes = EYES_RIGHT;
185                 _queue.push_back (qi);
186                 ++_queued_full_in_memory;
187         } else {
188                 qi.eyes = eyes;
189                 _queue.push_back (qi);
190                 ++_queued_full_in_memory;
191         }
192
193         /* Now there's something to do: wake anything wait()ing on _empty_condition */
194         _empty_condition.notify_all ();
195 }
196
197 void
198 Writer::repeat (int frame, Eyes eyes)
199 {
200         boost::mutex::scoped_lock lock (_state_mutex);
201
202         while (_queued_full_in_memory > _maximum_frames_in_memory) {
203                 /* The queue is too big; wait until that is sorted out */
204                 _full_condition.wait (lock);
205         }
206
207         QueueItem qi;
208         qi.type = QueueItem::REPEAT;
209         qi.frame = frame;
210         if (_film->three_d() && eyes == EYES_BOTH) {
211                 qi.eyes = EYES_LEFT;
212                 _queue.push_back (qi);
213                 qi.eyes = EYES_RIGHT;
214                 _queue.push_back (qi);
215         } else {
216                 qi.eyes = eyes;
217                 _queue.push_back (qi);
218         }
219
220         /* Now there's something to do: wake anything wait()ing on _empty_condition */
221         _empty_condition.notify_all ();
222 }
223
224 void
225 Writer::fake_write (int frame, Eyes eyes)
226 {
227         boost::mutex::scoped_lock lock (_state_mutex);
228
229         while (_queued_full_in_memory > _maximum_frames_in_memory) {
230                 /* The queue is too big; wait until that is sorted out */
231                 _full_condition.wait (lock);
232         }
233
234         FILE* file = fopen_boost (_film->info_file (), "rb");
235         if (!file) {
236                 throw ReadFileError (_film->info_file ());
237         }
238         dcp::FrameInfo info = read_frame_info (file, frame, eyes);
239         fclose (file);
240
241         QueueItem qi;
242         qi.type = QueueItem::FAKE;
243         qi.size = info.size;
244         qi.frame = frame;
245         if (_film->three_d() && eyes == EYES_BOTH) {
246                 qi.eyes = EYES_LEFT;
247                 _queue.push_back (qi);
248                 qi.eyes = EYES_RIGHT;
249                 _queue.push_back (qi);
250         } else {
251                 qi.eyes = eyes;
252                 _queue.push_back (qi);
253         }
254
255         /* Now there's something to do: wake anything wait()ing on _empty_condition */
256         _empty_condition.notify_all ();
257 }
258
259 /** This method is not thread safe */
260 void
261 Writer::write (shared_ptr<const AudioBuffers> audio)
262 {
263         if (_sound_asset_writer) {
264                 _sound_asset_writer->write (audio->data(), audio->frames());
265         }
266 }
267
268 /** This must be called from Writer::thread() with an appropriate lock held */
269 bool
270 Writer::have_sequenced_image_at_queue_head ()
271 {
272         if (_queue.empty ()) {
273                 return false;
274         }
275
276         _queue.sort ();
277
278         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
279
280         if (_queue.front().eyes == EYES_BOTH) {
281                 /* 2D */
282                 return _queue.front().frame == (_last_written_frame + 1);
283         }
284
285         /* 3D */
286
287         if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
288                 return true;
289         }
290
291         if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
292                 return true;
293         }
294
295         return false;
296 }
297
298 void
299 Writer::write_frame_info (int frame, Eyes eyes, dcp::FrameInfo info) const
300 {
301         FILE* file = 0;
302         if (boost::filesystem::exists (_film->info_file ())) {
303                 file = fopen_boost (_film->info_file(), "r+b");
304         } else {
305                 file = fopen_boost (_film->info_file(), "wb");
306         }
307         if (!file) {
308                 throw OpenFileError (_film->info_file ());
309         }
310         dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
311         fwrite (&info.offset, sizeof (info.offset), 1, file);
312         fwrite (&info.size, sizeof (info.size), 1, file);
313         fwrite (info.hash.c_str(), 1, info.hash.size(), file);
314         fclose (file);
315 }
316
317 void
318 Writer::thread ()
319 try
320 {
321         while (true)
322         {
323                 boost::mutex::scoped_lock lock (_state_mutex);
324
325                 while (true) {
326
327                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
328                                 /* We've got something to do: go and do it */
329                                 break;
330                         }
331
332                         /* Nothing to do: wait until something happens which may indicate that we do */
333                         LOG_TIMING (N_("writer-sleep queue=%1"), _queue.size());
334                         _empty_condition.wait (lock);
335                         LOG_TIMING (N_("writer-wake queue=%1"), _queue.size());
336                 }
337
338                 if (_finish && _queue.empty()) {
339                         return;
340                 }
341
342                 /* We stop here if we have been asked to finish, and if either the queue
343                    is empty or we do not have a sequenced image at its head (if this is the
344                    case we will never terminate as no new frames will be sent once
345                    _finish is true).
346                 */
347                 if (_finish && (!have_sequenced_image_at_queue_head() || _queue.empty())) {
348                         /* (Hopefully temporarily) log anything that was not written */
349                         if (!_queue.empty() && !have_sequenced_image_at_queue_head()) {
350                                 LOG_WARNING (N_("Finishing writer with a left-over queue of %1:"), _queue.size());
351                                 for (list<QueueItem>::const_iterator i = _queue.begin(); i != _queue.end(); ++i) {
352                                         if (i->type == QueueItem::FULL) {
353                                                 LOG_WARNING (N_("- type FULL, frame %1, eyes %2"), i->frame, i->eyes);
354                                         } else {
355                                                 LOG_WARNING (N_("- type FAKE, size %1, frame %2, eyes %3"), i->size, i->frame, i->eyes);
356                                         }
357                                 }
358                                 LOG_WARNING (N_("Last written frame %1, last written eyes %2"), _last_written_frame, _last_written_eyes);
359                         }
360                         return;
361                 }
362                 /* Write any frames that we can write; i.e. those that are in sequence. */
363                 while (have_sequenced_image_at_queue_head ()) {
364                         QueueItem qi = _queue.front ();
365                         _queue.pop_front ();
366                         if (qi.type == QueueItem::FULL && qi.encoded) {
367                                 --_queued_full_in_memory;
368                         }
369
370                         lock.unlock ();
371                         switch (qi.type) {
372                         case QueueItem::FULL:
373                         {
374                                 LOG_DEBUG_ENCODE (N_("Writer FULL-writes %1 (%2)"), qi.frame, qi.eyes);
375                                 if (!qi.encoded) {
376                                         qi.encoded = Data (_film->j2c_path (qi.frame, qi.eyes, false));
377                                 }
378
379                                 dcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data().get (), qi.encoded->size());
380                                 write_frame_info (qi.frame, qi.eyes, fin);
381                                 _last_written[qi.eyes] = qi.encoded;
382                                 ++_full_written;
383                                 break;
384                         }
385                         case QueueItem::FAKE:
386                                 LOG_DEBUG_ENCODE (N_("Writer FAKE-writes %1"), qi.frame);
387                                 _picture_asset_writer->fake_write (qi.size);
388                                 _last_written[qi.eyes].reset ();
389                                 ++_fake_written;
390                                 break;
391                         case QueueItem::REPEAT:
392                                 LOG_DEBUG_ENCODE (N_("Writer REPEAT-writes %1"), qi.frame);
393                                 dcp::FrameInfo fin = _picture_asset_writer->write (
394                                         _last_written[qi.eyes]->data().get(),
395                                         _last_written[qi.eyes]->size()
396                                         );
397                                 write_frame_info (qi.frame, qi.eyes, fin);
398                                 ++_repeat_written;
399                                 break;
400                         }
401                         lock.lock ();
402
403                         _last_written_frame = qi.frame;
404                         _last_written_eyes = qi.eyes;
405
406                         shared_ptr<Job> job = _job.lock ();
407                         DCPOMATIC_ASSERT (job);
408                         int64_t total = _film->length().frames_round (_film->video_frame_rate ());
409                         if (_film->three_d ()) {
410                                 /* _full_written and so on are incremented for each eye, so we need to double the total
411                                    frames to get the correct progress.
412                                 */
413                                 total *= 2;
414                         }
415                         if (total) {
416                                 job->set_progress (float (_full_written + _fake_written + _repeat_written) / total);
417                         }
418                 }
419
420                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
421                         /* Too many frames in memory which can't yet be written to the stream.
422                            Write some FULL frames to disk.
423                         */
424
425                         /* Find one from the back of the queue */
426                         _queue.sort ();
427                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
428                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
429                                 ++i;
430                         }
431
432                         DCPOMATIC_ASSERT (i != _queue.rend());
433                         ++_pushed_to_disk;
434                         lock.unlock ();
435
436                         /* i is valid here, even though we don't hold a lock on the mutex,
437                            since list iterators are unaffected by insertion and only this
438                            thread could erase the last item in the list.
439                         */
440
441                         LOG_GENERAL (
442                                 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
443                                 _last_written_frame + 1,
444                                 _last_written_eyes, i->frame
445                                 );
446
447                         i->encoded->write_via_temp (_film->j2c_path (i->frame, i->eyes, true), _film->j2c_path (i->frame, i->eyes, false));
448
449                         lock.lock ();
450                         i->encoded.reset ();
451                         --_queued_full_in_memory;
452                 }
453
454                 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
455                 _full_condition.notify_all ();
456         }
457 }
458 catch (...)
459 {
460         store_current ();
461 }
462
463 void
464 Writer::terminate_thread (bool can_throw)
465 {
466         boost::mutex::scoped_lock lock (_state_mutex);
467         if (_thread == 0) {
468                 return;
469         }
470
471         _finish = true;
472         _empty_condition.notify_all ();
473         _full_condition.notify_all ();
474         lock.unlock ();
475
476         _thread->join ();
477         if (can_throw) {
478                 rethrow ();
479         }
480
481         delete _thread;
482         _thread = 0;
483 }
484
485 void
486 Writer::finish ()
487 {
488         if (!_thread) {
489                 return;
490         }
491
492         terminate_thread (true);
493
494         _picture_asset_writer->finalize ();
495         if (_sound_asset_writer) {
496                 _sound_asset_writer->finalize ();
497         }
498
499         /* Hard-link the video asset into the DCP */
500         boost::filesystem::path video_from = _picture_asset->file ();
501
502         boost::filesystem::path video_to;
503         video_to /= _film->dir (_film->dcp_name());
504         video_to /= video_asset_filename (_picture_asset);
505
506         boost::system::error_code ec;
507         boost::filesystem::create_hard_link (video_from, video_to, ec);
508         if (ec) {
509                 LOG_WARNING_NC ("Hard-link failed; copying instead");
510                 boost::filesystem::copy_file (video_from, video_to, ec);
511                 if (ec) {
512                         LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
513                         throw FileError (ec.message(), video_from);
514                 }
515         }
516
517         _picture_asset->set_file (video_to);
518
519         /* Move the audio asset into the DCP */
520
521         if (_sound_asset) {
522                 boost::filesystem::path audio_to;
523                 audio_to /= _film->dir (_film->dcp_name ());
524                 audio_to /= audio_asset_filename (_sound_asset);
525
526                 boost::filesystem::rename (_film->file (audio_asset_filename (_sound_asset)), audio_to, ec);
527                 if (ec) {
528                         throw FileError (
529                                 String::compose (_("could not move audio asset into the DCP (%1)"), ec.value ()), audio_asset_filename (_sound_asset)
530                                 );
531                 }
532
533                 _sound_asset->set_file (audio_to);
534         }
535
536         dcp::DCP dcp (_film->dir (_film->dcp_name()));
537
538         shared_ptr<dcp::CPL> cpl (
539                 new dcp::CPL (
540                         _film->dcp_name(),
541                         _film->dcp_content_type()->libdcp_kind ()
542                         )
543                 );
544
545         dcp.add (cpl);
546
547         shared_ptr<dcp::Reel> reel (new dcp::Reel ());
548
549         shared_ptr<dcp::MonoPictureAsset> mono = dynamic_pointer_cast<dcp::MonoPictureAsset> (_picture_asset);
550         if (mono) {
551                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
552         }
553
554         shared_ptr<dcp::StereoPictureAsset> stereo = dynamic_pointer_cast<dcp::StereoPictureAsset> (_picture_asset);
555         if (stereo) {
556                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
557         }
558
559         if (_sound_asset) {
560                 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_asset, 0)));
561         }
562
563         if (_subtitle_asset) {
564                 boost::filesystem::path liberation;
565                 try {
566                         liberation = shared_path () / "LiberationSans-Regular.ttf";
567                 } catch (boost::filesystem::filesystem_error& e) {
568                         /* Hack: try the debian/ubuntu location if getting the shared path failed */
569                         liberation = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf";
570                 }
571
572                 /* Add all the fonts to the subtitle content */
573                 BOOST_FOREACH (shared_ptr<Font> i, _fonts) {
574                         _subtitle_asset->add_font (i->id(), i->file().get_value_or (liberation));
575                 }
576
577                 if (dynamic_pointer_cast<dcp::InteropSubtitleAsset> (_subtitle_asset)) {
578                         boost::filesystem::path directory = _film->dir (_film->dcp_name ()) / _subtitle_asset->id ();
579                         boost::filesystem::create_directories (directory);
580                         _subtitle_asset->write (directory / ("sub_" + _subtitle_asset->id() + ".xml"));
581                 } else {
582                         _subtitle_asset->write (
583                                 _film->dir (_film->dcp_name ()) / ("sub_" + _subtitle_asset->id() + ".mxf")
584                                 );
585                 }
586
587                 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
588                                    new dcp::ReelSubtitleAsset (
589                                            _subtitle_asset,
590                                            dcp::Fraction (_film->video_frame_rate(), 1),
591                                            _picture_asset->intrinsic_duration (),
592                                            0
593                                            )
594                                    ));
595         }
596
597         cpl->add (reel);
598
599         shared_ptr<Job> job = _job.lock ();
600         DCPOMATIC_ASSERT (job);
601
602         job->sub (_("Computing image digest"));
603         _picture_asset->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
604
605         if (_sound_asset) {
606                 job->sub (_("Computing audio digest"));
607                 _sound_asset->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
608         }
609
610         dcp::XMLMetadata meta;
611         meta.creator = Config::instance()->dcp_creator ();
612         if (meta.creator.empty ()) {
613                 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
614         }
615         meta.issuer = Config::instance()->dcp_issuer ();
616         if (meta.issuer.empty ()) {
617                 meta.issuer = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
618         }
619         meta.set_issue_date_now ();
620
621         cpl->set_metadata (meta);
622
623         shared_ptr<const dcp::CertificateChain> signer;
624         if (_film->is_signed ()) {
625                 signer = Config::instance()->signer_chain ();
626                 /* We did check earlier, but check again here to be on the safe side */
627                 if (!signer->valid ()) {
628                         throw InvalidSignerError ();
629                 }
630         }
631
632         dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
633
634         LOG_GENERAL (
635                 N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT, %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk
636                 );
637 }
638
639 bool
640 Writer::check_existing_picture_asset_frame (FILE* asset, int f, Eyes eyes)
641 {
642         /* Read the frame info as written */
643         FILE* file = fopen_boost (_film->info_file (), "rb");
644         if (!file) {
645                 LOG_GENERAL ("Existing frame %1 has no info file", f);
646                 return false;
647         }
648
649         dcp::FrameInfo info = read_frame_info (file, f, eyes);
650         fclose (file);
651         if (info.size == 0) {
652                 LOG_GENERAL ("Existing frame %1 has no info file", f);
653                 return false;
654         }
655
656         /* Read the data from the asset and hash it */
657         dcpomatic_fseek (asset, info.offset, SEEK_SET);
658         Data data (info.size);
659         size_t const read = fread (data.data().get(), 1, data.size(), asset);
660         if (read != static_cast<size_t> (data.size ())) {
661                 LOG_GENERAL ("Existing frame %1 is incomplete", f);
662                 return false;
663         }
664
665         MD5Digester digester;
666         digester.add (data.data().get(), data.size());
667         if (digester.get() != info.hash) {
668                 LOG_GENERAL ("Existing frame %1 failed hash check", f);
669                 return false;
670         }
671
672         return true;
673 }
674
675 void
676 Writer::check_existing_picture_asset ()
677 {
678         /* Try to open the existing asset */
679         FILE* asset = fopen_boost (_picture_asset->file(), "rb");
680         if (!asset) {
681                 LOG_GENERAL ("Could not open existing asset at %1 (errno=%2)", _picture_asset->file().string(), errno);
682                 return;
683         }
684
685         while (true) {
686
687                 shared_ptr<Job> job = _job.lock ();
688                 DCPOMATIC_ASSERT (job);
689
690                 job->set_progress_unknown ();
691
692                 if (_film->three_d ()) {
693                         if (!check_existing_picture_asset_frame (asset, _first_nonexistant_frame, EYES_LEFT)) {
694                                 break;
695                         }
696                         if (!check_existing_picture_asset_frame (asset, _first_nonexistant_frame, EYES_RIGHT)) {
697                                 break;
698                         }
699                 } else {
700                         if (!check_existing_picture_asset_frame (asset, _first_nonexistant_frame, EYES_BOTH)) {
701                                 break;
702                         }
703                 }
704
705                 LOG_DEBUG_ENCODE ("Have existing frame %1", _first_nonexistant_frame);
706                 ++_first_nonexistant_frame;
707         }
708
709         fclose (asset);
710 }
711
712 /** @param frame Frame index.
713  *  @return true if we can fake-write this frame.
714  */
715 bool
716 Writer::can_fake_write (int frame) const
717 {
718         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
719            parameters in the asset writer.
720         */
721         return (frame != 0 && frame < _first_nonexistant_frame);
722 }
723
724 void
725 Writer::write (PlayerSubtitles subs)
726 {
727         if (subs.text.empty ()) {
728                 return;
729         }
730
731         if (!_subtitle_asset) {
732                 string lang = _film->subtitle_language ();
733                 if (lang.empty ()) {
734                         lang = "Unknown";
735                 }
736                 if (_film->interop ()) {
737                         shared_ptr<dcp::InteropSubtitleAsset> s (new dcp::InteropSubtitleAsset ());
738                         s->set_movie_title (_film->name ());
739                         s->set_language (lang);
740                         s->set_reel_number ("1");
741                         _subtitle_asset = s;
742                 } else {
743                         shared_ptr<dcp::SMPTESubtitleAsset> s (new dcp::SMPTESubtitleAsset ());
744                         s->set_content_title_text (_film->name ());
745                         s->set_language (lang);
746                         s->set_edit_rate (dcp::Fraction (_film->video_frame_rate (), 1));
747                         s->set_time_code_rate (_film->video_frame_rate ());
748                         _subtitle_asset = s;
749                 }
750         }
751
752         for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
753                 _subtitle_asset->add (*i);
754         }
755 }
756
757 void
758 Writer::write (list<shared_ptr<Font> > fonts)
759 {
760         /* Just keep a list of fonts and we'll deal with them in ::finish */
761         copy (fonts.begin (), fonts.end (), back_inserter (_fonts));
762 }
763
764 bool
765 operator< (QueueItem const & a, QueueItem const & b)
766 {
767         if (a.frame != b.frame) {
768                 return a.frame < b.frame;
769         }
770
771         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
772 }
773
774 bool
775 operator== (QueueItem const & a, QueueItem const & b)
776 {
777         return a.frame == b.frame && a.eyes == b.eyes;
778 }
779
780 void
781 Writer::set_encoder_threads (int threads)
782 {
783         _maximum_frames_in_memory = lrint (threads * 1.1);
784 }
785
786 long
787 Writer::frame_info_position (int frame, Eyes eyes) const
788 {
789         static int const info_size = 48;
790
791         switch (eyes) {
792         case EYES_BOTH:
793                 return frame * info_size;
794         case EYES_LEFT:
795                 return frame * info_size * 2;
796         case EYES_RIGHT:
797                 return frame * info_size * 2 + info_size;
798         default:
799                 DCPOMATIC_ASSERT (false);
800         }
801
802         DCPOMATIC_ASSERT (false);
803 }
804
805 dcp::FrameInfo
806 Writer::read_frame_info (FILE* file, int frame, Eyes eyes) const
807 {
808         dcp::FrameInfo info;
809         dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
810         fread (&info.offset, sizeof (info.offset), 1, file);
811         fread (&info.size, sizeof (info.size), 1, file);
812
813         char hash_buffer[33];
814         fread (hash_buffer, 1, 32, file);
815         hash_buffer[32] = '\0';
816         info.hash = hash_buffer;
817
818         return info;
819 }