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