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