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