Remove ref_write mechanism and instead maintain state for each
[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 "referenced_reel_asset.h"
38 #include <dcp/mono_picture_asset.h>
39 #include <dcp/stereo_picture_asset.h>
40 #include <dcp/sound_asset.h>
41 #include <dcp/sound_asset_writer.h>
42 #include <dcp/reel.h>
43 #include <dcp/reel_mono_picture_asset.h>
44 #include <dcp/reel_stereo_picture_asset.h>
45 #include <dcp/reel_sound_asset.h>
46 #include <dcp/reel_subtitle_asset.h>
47 #include <dcp/dcp.h>
48 #include <dcp/cpl.h>
49 #include <dcp/certificate_chain.h>
50 #include <dcp/interop_subtitle_asset.h>
51 #include <dcp/smpte_subtitle_asset.h>
52 #include <boost/foreach.hpp>
53 #include <fstream>
54 #include <cerrno>
55 #include <iostream>
56
57 #include "i18n.h"
58
59 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_GENERAL);
60 #define LOG_GENERAL_NC(...) _film->log()->log (__VA_ARGS__, LogEntry::TYPE_GENERAL);
61 #define LOG_DEBUG_ENCODE(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_DEBUG_ENCODE);
62 #define LOG_TIMING(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_TIMING);
63 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, LogEntry::TYPE_WARNING);
64 #define LOG_WARNING(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_WARNING);
65 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_ERROR);
66
67 /* OS X strikes again */
68 #undef set_key
69
70 using std::make_pair;
71 using std::pair;
72 using std::string;
73 using std::list;
74 using std::cout;
75 using boost::shared_ptr;
76 using boost::weak_ptr;
77 using boost::dynamic_pointer_cast;
78
79 int const Writer::_info_size = 48;
80
81 Writer::Writer (shared_ptr<const Film> film, weak_ptr<Job> j)
82         : _film (film)
83         , _job (j)
84         , _thread (0)
85         , _finish (false)
86         , _queued_full_in_memory (0)
87         , _maximum_frames_in_memory (0)
88         , _full_written (0)
89         , _fake_written (0)
90         , _repeat_written (0)
91         , _pushed_to_disk (0)
92 {
93         /* Remove any old DCP */
94         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
95
96         shared_ptr<Job> job = _job.lock ();
97         DCPOMATIC_ASSERT (job);
98
99         BOOST_FOREACH (DCPTimePeriod p, _film->reels ()) {
100                 Reel reel;
101                 reel.period = p;
102
103                 /* Create our picture asset in a subdirectory, named according to those
104                    film's parameters which affect the video output.  We will hard-link
105                    it into the DCP later.
106                 */
107
108                 if (_film->three_d ()) {
109                         reel.picture_asset.reset (new dcp::StereoPictureAsset (dcp::Fraction (_film->video_frame_rate (), 1)));
110                 } else {
111                         reel.picture_asset.reset (new dcp::MonoPictureAsset (dcp::Fraction (_film->video_frame_rate (), 1)));
112                 }
113
114                 reel.picture_asset->set_size (_film->frame_size ());
115
116                 if (_film->encrypted ()) {
117                         reel.picture_asset->set_key (_film->key ());
118                 }
119
120                 reel.picture_asset->set_file (
121                         _film->internal_video_asset_dir() / _film->internal_video_asset_filename(p)
122                         );
123
124                 job->sub (_("Checking existing image data"));
125                 check_existing_picture_asset (reel);
126
127                 reel.picture_asset_writer = reel.picture_asset->start_write (
128                         _film->internal_video_asset_dir() / _film->internal_video_asset_filename(p),
129                         _film->interop() ? dcp::INTEROP : dcp::SMPTE,
130                         reel.first_nonexistant_frame > 0
131                         );
132
133                 if (_film->audio_channels ()) {
134                         reel.sound_asset.reset (
135                                 new dcp::SoundAsset (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ())
136                         );
137
138                         if (_film->encrypted ()) {
139                                 reel.sound_asset->set_key (_film->key ());
140                         }
141
142                         /* Write the sound asset into the film directory so that we leave the creation
143                            of the DCP directory until the last minute.
144                         */
145                         reel.sound_asset_writer = reel.sound_asset->start_write (
146                                 _film->directory() / audio_asset_filename (reel.sound_asset),
147                                 _film->interop() ? dcp::INTEROP : dcp::SMPTE
148                                 );
149                 }
150
151                 _reels.push_back (reel);
152         }
153
154         /* We can keep track of the current audio and subtitle reels easily because audio
155            and subs arrive to the Writer in sequence.  This is not so for video.
156         */
157         _audio_reel = _reels.begin ();
158         _subtitle_reel = _reels.begin ();
159
160         /* Check that the signer is OK if we need one */
161         if (_film->is_signed() && !Config::instance()->signer_chain()->valid ()) {
162                 throw InvalidSignerError ();
163         }
164
165         job->sub (_("Encoding image data"));
166 }
167
168 void
169 Writer::start ()
170 {
171         _thread = new boost::thread (boost::bind (&Writer::thread, this));
172 }
173
174 Writer::~Writer ()
175 {
176         terminate_thread (false);
177 }
178
179 /** Pass a video frame to the writer for writing to disk at some point.
180  *  This method can be called with frames out of order.
181  *  @param encoded JPEG2000-encoded data.
182  *  @param frame Frame index within the DCP.
183  *  @param eyes Eyes that this frame image is for.
184  */
185 void
186 Writer::write (Data encoded, Frame frame, Eyes eyes)
187 {
188         boost::mutex::scoped_lock lock (_state_mutex);
189
190         while (_queued_full_in_memory > _maximum_frames_in_memory) {
191                 /* The queue is too big; wait until that is sorted out */
192                 _full_condition.wait (lock);
193         }
194
195         QueueItem qi;
196         qi.type = QueueItem::FULL;
197         qi.encoded = encoded;
198         qi.reel = video_reel (frame);
199         qi.frame = frame - _reels[qi.reel].period.from.frames_floor (_film->video_frame_rate());
200
201         if (_film->three_d() && eyes == EYES_BOTH) {
202                 /* 2D material in a 3D DCP; fake the 3D */
203                 qi.eyes = EYES_LEFT;
204                 _queue.push_back (qi);
205                 ++_queued_full_in_memory;
206                 qi.eyes = EYES_RIGHT;
207                 _queue.push_back (qi);
208                 ++_queued_full_in_memory;
209         } else {
210                 qi.eyes = eyes;
211                 _queue.push_back (qi);
212                 ++_queued_full_in_memory;
213         }
214
215         /* Now there's something to do: wake anything wait()ing on _empty_condition */
216         _empty_condition.notify_all ();
217 }
218
219 /** Repeat the last frame that was written to a reel as a new frame.
220  *  @param frame Frame index within the DCP of the new (repeated) frame.
221  *  @param eyes Eyes that this repeated frame image is for.
222  */
223 void
224 Writer::repeat (Frame frame, Eyes eyes)
225 {
226         boost::mutex::scoped_lock lock (_state_mutex);
227
228         while (_queued_full_in_memory > _maximum_frames_in_memory) {
229                 /* The queue is too big; wait until that is sorted out */
230                 _full_condition.wait (lock);
231         }
232
233         QueueItem qi;
234         qi.type = QueueItem::REPEAT;
235         qi.reel = video_reel (frame);
236         qi.frame = frame - _reels[qi.reel].period.from.frames_floor (_film->video_frame_rate());
237         if (_film->three_d() && eyes == EYES_BOTH) {
238                 qi.eyes = EYES_LEFT;
239                 _queue.push_back (qi);
240                 qi.eyes = EYES_RIGHT;
241                 _queue.push_back (qi);
242         } else {
243                 qi.eyes = eyes;
244                 _queue.push_back (qi);
245         }
246
247         /* Now there's something to do: wake anything wait()ing on _empty_condition */
248         _empty_condition.notify_all ();
249 }
250
251 void
252 Writer::fake_write (Frame frame, Eyes eyes)
253 {
254         boost::mutex::scoped_lock lock (_state_mutex);
255
256         while (_queued_full_in_memory > _maximum_frames_in_memory) {
257                 /* The queue is too big; wait until that is sorted out */
258                 _full_condition.wait (lock);
259         }
260
261         size_t const reel = video_reel (frame);
262         Frame const reel_frame = frame - _reels[reel].period.from.frames_floor (_film->video_frame_rate());
263
264         FILE* file = fopen_boost (_film->info_file(_reels[reel].period), "rb");
265         if (!file) {
266                 throw ReadFileError (_film->info_file(_reels[reel].period));
267         }
268         dcp::FrameInfo info = read_frame_info (file, reel_frame, eyes);
269         fclose (file);
270
271         QueueItem qi;
272         qi.type = QueueItem::FAKE;
273         qi.size = info.size;
274         qi.reel = reel;
275         qi.frame = reel_frame;
276         if (_film->three_d() && eyes == EYES_BOTH) {
277                 qi.eyes = EYES_LEFT;
278                 _queue.push_back (qi);
279                 qi.eyes = EYES_RIGHT;
280                 _queue.push_back (qi);
281         } else {
282                 qi.eyes = eyes;
283                 _queue.push_back (qi);
284         }
285
286         /* Now there's something to do: wake anything wait()ing on _empty_condition */
287         _empty_condition.notify_all ();
288 }
289
290 /** Write one video frame's worth of audio frames to the DCP.
291  *  @param audio Audio data or 0 if there is no audio to be written here (i.e. it is referenced).
292  *  This method is not thread safe.
293  */
294 void
295 Writer::write (shared_ptr<const AudioBuffers> audio)
296 {
297         if (!_audio_reel->sound_asset_writer) {
298                 return;
299         }
300
301         if (audio) {
302                 DCPOMATIC_ASSERT (_audio_reel->sound_asset_writer);
303                 _audio_reel->sound_asset_writer->write (audio->data(), audio->frames());
304         }
305
306         ++_audio_reel->total_written_audio_frames;
307
308         /* written is in video frames, not audio frames */
309         if (_audio_reel->total_written_audio_frames >= _audio_reel->period.duration().frames_floor (_film->video_frame_rate())) {
310                 ++_audio_reel;
311         }
312 }
313
314 /** This must be called from Writer::thread() with an appropriate lock held */
315 bool
316 Writer::have_sequenced_image_at_queue_head ()
317 {
318         if (_queue.empty ()) {
319                 return false;
320         }
321
322         _queue.sort ();
323
324         QueueItem const & f = _queue.front();
325         Reel const & reel = _reels[f.reel];
326
327         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
328
329         if (f.eyes == EYES_BOTH) {
330                 /* 2D */
331                 return f.frame == (reel.last_written_video_frame + 1);
332         }
333
334         /* 3D */
335
336         if (reel.last_written_eyes == EYES_LEFT && f.frame == reel.last_written_video_frame && f.eyes == EYES_RIGHT) {
337                 return true;
338         }
339
340         if (reel.last_written_eyes == EYES_RIGHT && f.frame == (reel.last_written_video_frame + 1) && f.eyes == EYES_LEFT) {
341                 return true;
342         }
343
344         return false;
345 }
346
347 /** @param frame reel-relative frame */
348 void
349 Writer::write_frame_info (Reel const & reel, int frame, Eyes eyes, dcp::FrameInfo info) const
350 {
351         FILE* file = 0;
352         boost::filesystem::path info_file = _film->info_file (reel.period);
353         if (boost::filesystem::exists (info_file)) {
354                 file = fopen_boost (info_file, "r+b");
355         } else {
356                 file = fopen_boost (info_file, "wb");
357         }
358         if (!file) {
359                 throw OpenFileError (info_file);
360         }
361         dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
362         fwrite (&info.offset, sizeof (info.offset), 1, file);
363         fwrite (&info.size, sizeof (info.size), 1, file);
364         fwrite (info.hash.c_str(), 1, info.hash.size(), file);
365         fclose (file);
366 }
367
368 void
369 Writer::thread ()
370 try
371 {
372         while (true)
373         {
374                 boost::mutex::scoped_lock lock (_state_mutex);
375
376                 while (true) {
377
378                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
379                                 /* We've got something to do: go and do it */
380                                 break;
381                         }
382
383                         /* Nothing to do: wait until something happens which may indicate that we do */
384                         LOG_TIMING (N_("writer-sleep queue=%1"), _queue.size());
385                         _empty_condition.wait (lock);
386                         LOG_TIMING (N_("writer-wake queue=%1"), _queue.size());
387                 }
388
389                 if (_finish && _queue.empty()) {
390                         return;
391                 }
392
393                 /* We stop here if we have been asked to finish, and if either the queue
394                    is empty or we do not have a sequenced image at its head (if this is the
395                    case we will never terminate as no new frames will be sent once
396                    _finish is true).
397                 */
398                 if (_finish && (!have_sequenced_image_at_queue_head() || _queue.empty())) {
399                         /* (Hopefully temporarily) log anything that was not written */
400                         if (!_queue.empty() && !have_sequenced_image_at_queue_head()) {
401                                 LOG_WARNING (N_("Finishing writer with a left-over queue of %1:"), _queue.size());
402                                 for (list<QueueItem>::const_iterator i = _queue.begin(); i != _queue.end(); ++i) {
403                                         if (i->type == QueueItem::FULL) {
404                                                 LOG_WARNING (N_("- type FULL, frame %1, eyes %2"), i->frame, i->eyes);
405                                         } else {
406                                                 LOG_WARNING (N_("- type FAKE, size %1, frame %2, eyes %3"), i->size, i->frame, i->eyes);
407                                         }
408                                 }
409                         }
410                         return;
411                 }
412
413                 /* Write any frames that we can write; i.e. those that are in sequence. */
414                 while (have_sequenced_image_at_queue_head ()) {
415                         QueueItem qi = _queue.front ();
416                         _queue.pop_front ();
417                         if (qi.type == QueueItem::FULL && qi.encoded) {
418                                 --_queued_full_in_memory;
419                         }
420
421                         lock.unlock ();
422
423                         Reel& reel = _reels[qi.reel];
424
425                         switch (qi.type) {
426                         case QueueItem::FULL:
427                         {
428                                 LOG_DEBUG_ENCODE (N_("Writer FULL-writes %1 (%2)"), qi.frame, qi.eyes);
429                                 if (!qi.encoded) {
430                                         qi.encoded = Data (_film->j2c_path (qi.reel, qi.frame, qi.eyes, false));
431                                 }
432
433                                 dcp::FrameInfo fin = reel.picture_asset_writer->write (qi.encoded->data().get (), qi.encoded->size());
434                                 write_frame_info (reel, qi.frame, qi.eyes, fin);
435                                 reel.last_written[qi.eyes] = qi.encoded;
436                                 ++_full_written;
437                                 break;
438                         }
439                         case QueueItem::FAKE:
440                                 LOG_DEBUG_ENCODE (N_("Writer FAKE-writes %1"), qi.frame);
441                                 reel.picture_asset_writer->fake_write (qi.size);
442                                 ++_fake_written;
443                                 break;
444                         case QueueItem::REPEAT:
445                         {
446                                 LOG_DEBUG_ENCODE (N_("Writer REPEAT-writes %1"), qi.frame);
447                                 dcp::FrameInfo fin = reel.picture_asset_writer->write (
448                                         reel.last_written[qi.eyes]->data().get(),
449                                         reel.last_written[qi.eyes]->size()
450                                         );
451                                 write_frame_info (reel, qi.frame, qi.eyes, fin);
452                                 ++_repeat_written;
453                                 break;
454                         }
455                         }
456
457                         lock.lock ();
458
459                         reel.last_written_video_frame = qi.frame;
460                         reel.last_written_eyes = qi.eyes;
461
462                         shared_ptr<Job> job = _job.lock ();
463                         DCPOMATIC_ASSERT (job);
464                         int64_t total = _film->length().frames_round (_film->video_frame_rate ());
465                         if (_film->three_d ()) {
466                                 /* _full_written and so on are incremented for each eye, so we need to double the total
467                                    frames to get the correct progress.
468                                 */
469                                 total *= 2;
470                         }
471                         if (total) {
472                                 job->set_progress (float (_full_written + _fake_written + _repeat_written) / total);
473                         }
474                 }
475
476                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
477                         /* Too many frames in memory which can't yet be written to the stream.
478                            Write some FULL frames to disk.
479                         */
480
481                         /* Find one from the back of the queue */
482                         _queue.sort ();
483                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
484                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
485                                 ++i;
486                         }
487
488                         DCPOMATIC_ASSERT (i != _queue.rend());
489                         ++_pushed_to_disk;
490                         lock.unlock ();
491
492                         /* i is valid here, even though we don't hold a lock on the mutex,
493                            since list iterators are unaffected by insertion and only this
494                            thread could erase the last item in the list.
495                         */
496
497                         LOG_GENERAL ("Writer full; pushes %1 to disk", i->frame);
498
499                         i->encoded->write_via_temp (
500                                 _film->j2c_path (i->reel, i->frame, i->eyes, true),
501                                 _film->j2c_path (i->reel, i->frame, i->eyes, false)
502                                 );
503
504                         lock.lock ();
505                         i->encoded.reset ();
506                         --_queued_full_in_memory;
507                 }
508
509                 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
510                 _full_condition.notify_all ();
511         }
512 }
513 catch (...)
514 {
515         store_current ();
516 }
517
518 void
519 Writer::terminate_thread (bool can_throw)
520 {
521         boost::mutex::scoped_lock lock (_state_mutex);
522         if (_thread == 0) {
523                 return;
524         }
525
526         _finish = true;
527         _empty_condition.notify_all ();
528         _full_condition.notify_all ();
529         lock.unlock ();
530
531         DCPOMATIC_ASSERT (_thread->joinable ());
532         _thread->join ();
533         if (can_throw) {
534                 rethrow ();
535         }
536
537         delete _thread;
538         _thread = 0;
539 }
540
541 void
542 Writer::finish ()
543 {
544         if (!_thread) {
545                 return;
546         }
547
548         terminate_thread (true);
549
550         BOOST_FOREACH (Reel& i, _reels) {
551
552                 if (!i.picture_asset_writer->finalize ()) {
553                         /* Nothing was written to the picture asset */
554                         i.picture_asset.reset ();
555                 }
556
557                 if (i.sound_asset_writer && !i.sound_asset_writer->finalize ()) {
558                         /* Nothing was written to the sound asset */
559                         cout << "nothing written to reel @ " << i.period << "\n";
560                         i.sound_asset.reset ();
561                 } else {
562                         cout << "something written to reel @ " << i.period << "\n";
563                 }
564
565                 /* Hard-link any video asset file into the DCP */
566                 if (i.picture_asset) {
567                         boost::filesystem::path video_from = i.picture_asset->file ();
568                         boost::filesystem::path video_to;
569                         video_to /= _film->dir (_film->dcp_name());
570                         video_to /= video_asset_filename (i.picture_asset);
571
572                         boost::system::error_code ec;
573                         boost::filesystem::create_hard_link (video_from, video_to, ec);
574                         if (ec) {
575                                 LOG_WARNING_NC ("Hard-link failed; copying instead");
576                                 boost::filesystem::copy_file (video_from, video_to, ec);
577                                 if (ec) {
578                                         LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
579                                         throw FileError (ec.message(), video_from);
580                                 }
581                         }
582
583                         i.picture_asset->set_file (video_to);
584                 }
585
586                 /* Move the audio asset into the DCP */
587                 if (i.sound_asset) {
588                         boost::filesystem::path audio_to;
589                         audio_to /= _film->dir (_film->dcp_name ());
590                         audio_to /= audio_asset_filename (i.sound_asset);
591
592                         boost::system::error_code ec;
593                         boost::filesystem::rename (_film->file (audio_asset_filename (i.sound_asset)), audio_to, ec);
594                         if (ec) {
595                                 throw FileError (
596                                         String::compose (_("could not move audio asset into the DCP (%1)"), ec.value ()), audio_asset_filename (i.sound_asset)
597                                         );
598                         }
599
600                         i.sound_asset->set_file (audio_to);
601                 }
602         }
603
604         dcp::DCP dcp (_film->dir (_film->dcp_name()));
605
606         shared_ptr<dcp::CPL> cpl (
607                 new dcp::CPL (
608                         _film->dcp_name(),
609                         _film->dcp_content_type()->libdcp_kind ()
610                         )
611                 );
612
613         dcp.add (cpl);
614
615         BOOST_FOREACH (Reel& i, _reels) {
616                 shared_ptr<dcp::Reel> reel (new dcp::Reel ());
617
618                 shared_ptr<dcp::ReelPictureAsset> reel_picture_asset;
619
620                 if (i.picture_asset) {
621                         /* We have made a picture asset of our own.  Put it into the reel */
622                         shared_ptr<dcp::MonoPictureAsset> mono = dynamic_pointer_cast<dcp::MonoPictureAsset> (i.picture_asset);
623                         if (mono) {
624                                 reel_picture_asset.reset (new dcp::ReelMonoPictureAsset (mono, 0));
625                         }
626
627                         shared_ptr<dcp::StereoPictureAsset> stereo = dynamic_pointer_cast<dcp::StereoPictureAsset> (i.picture_asset);
628                         if (stereo) {
629                                 reel_picture_asset.reset (new dcp::ReelStereoPictureAsset (stereo, 0));
630                         }
631                 } else {
632                         /* We don't have a picture asset of our own; hopefully we have one to reference */
633                         BOOST_FOREACH (ReferencedReelAsset j, _reel_assets) {
634                                 shared_ptr<dcp::ReelPictureAsset> k = dynamic_pointer_cast<dcp::ReelPictureAsset> (j.asset);
635                                 if (k && j.period == i.period) {
636                                         reel_picture_asset = k;
637                                 }
638                         }
639                 }
640
641                 reel->add (reel_picture_asset);
642
643                 if (i.sound_asset) {
644                         /* We have made a sound asset of our own.  Put it into the reel */
645                         reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (i.sound_asset, 0)));
646                 } else {
647                         /* We don't have a sound asset of our own; hopefully we have one to reference */
648                         BOOST_FOREACH (ReferencedReelAsset j, _reel_assets) {
649                                 shared_ptr<dcp::ReelSoundAsset> k = dynamic_pointer_cast<dcp::ReelSoundAsset> (j.asset);
650                                 if (k && j.period == i.period) {
651                                         reel->add (k);
652                                 }
653                         }
654                 }
655
656                 if (i.subtitle_asset) {
657                         boost::filesystem::path liberation;
658                         try {
659                                 liberation = shared_path () / "LiberationSans-Regular.ttf";
660                         } catch (boost::filesystem::filesystem_error& e) {
661                                 /* Hack: try the debian/ubuntu location if getting the shared path failed */
662                                 liberation = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf";
663                         }
664
665                         /* Add all the fonts to the subtitle content */
666                         BOOST_FOREACH (shared_ptr<Font> j, _fonts) {
667                                 i.subtitle_asset->add_font (j->id(), j->file().get_value_or (liberation));
668                         }
669
670                         if (dynamic_pointer_cast<dcp::InteropSubtitleAsset> (i.subtitle_asset)) {
671                                 boost::filesystem::path directory = _film->dir (_film->dcp_name ()) / i.subtitle_asset->id ();
672                                 boost::filesystem::create_directories (directory);
673                                 i.subtitle_asset->write (directory / ("sub_" + i.subtitle_asset->id() + ".xml"));
674                         } else {
675
676                                 /* All our assets should be the same length; use the picture asset length here
677                                    as a reference to set the subtitle one.
678                                 */
679                                 dynamic_pointer_cast<dcp::SMPTESubtitleAsset>(i.subtitle_asset)->set_intrinsic_duration (
680                                         reel_picture_asset->intrinsic_duration ()
681                                         );
682
683                                 i.subtitle_asset->write (
684                                         _film->dir (_film->dcp_name ()) / ("sub_" + i.subtitle_asset->id() + ".mxf")
685                                         );
686                         }
687
688                         reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
689                                            new dcp::ReelSubtitleAsset (
690                                                    i.subtitle_asset,
691                                                    dcp::Fraction (_film->video_frame_rate(), 1),
692                                                    reel_picture_asset->intrinsic_duration (),
693                                                    0
694                                                    )
695                                            ));
696                 } else {
697                         /* We don't have a subtitle asset of our own; hopefully we have one to reference */
698                         BOOST_FOREACH (ReferencedReelAsset j, _reel_assets) {
699                                 shared_ptr<dcp::ReelSubtitleAsset> k = dynamic_pointer_cast<dcp::ReelSubtitleAsset> (j.asset);
700                                 if (k && j.period == i.period) {
701                                         reel->add (k);
702                                 }
703                         }
704                 }
705
706                 cpl->add (reel);
707
708                 shared_ptr<Job> job = _job.lock ();
709                 DCPOMATIC_ASSERT (job);
710
711                 job->sub (_("Computing image digest"));
712                 if (i.picture_asset) {
713                         i.picture_asset->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
714                 }
715
716                 if (i.sound_asset) {
717                         job->sub (_("Computing audio digest"));
718                         i.sound_asset->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
719                 }
720         }
721
722         dcp::XMLMetadata meta;
723         meta.creator = Config::instance()->dcp_creator ();
724         if (meta.creator.empty ()) {
725                 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
726         }
727         meta.issuer = Config::instance()->dcp_issuer ();
728         if (meta.issuer.empty ()) {
729                 meta.issuer = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
730         }
731         meta.set_issue_date_now ();
732
733         cpl->set_metadata (meta);
734
735         shared_ptr<const dcp::CertificateChain> signer;
736         if (_film->is_signed ()) {
737                 signer = Config::instance()->signer_chain ();
738                 /* We did check earlier, but check again here to be on the safe side */
739                 if (!signer->valid ()) {
740                         throw InvalidSignerError ();
741                 }
742         }
743
744         dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
745
746         LOG_GENERAL (
747                 N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT, %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk
748                 );
749 }
750
751 void
752 Writer::check_existing_picture_asset (Reel& reel)
753 {
754         /* Try to open the existing asset */
755         FILE* asset_file = fopen_boost (reel.picture_asset->file(), "rb");
756         if (!asset_file) {
757                 LOG_GENERAL ("Could not open existing asset at %1 (errno=%2)", reel.picture_asset->file().string(), errno);
758                 return;
759         }
760
761         /* Offset of the last dcp::FrameInfo in the info file */
762         int const n = (boost::filesystem::file_size (_film->info_file(reel.period)) / _info_size) - 1;
763
764         FILE* info_file = fopen_boost (_film->info_file(reel.period), "rb");
765         if (!info_file) {
766                 LOG_GENERAL_NC ("Could not open film info file");
767                 fclose (asset_file);
768                 return;
769         }
770
771         if (_film->three_d ()) {
772                 /* Start looking at the last left frame */
773                 reel.first_nonexistant_frame = n / 2;
774         } else {
775                 reel.first_nonexistant_frame = n;
776         }
777
778         bool ok = false;
779
780         while (!ok) {
781                 /* Read the data from the info file; for 3D we just check the left
782                    frames until we find a good one.
783                 */
784                 dcp::FrameInfo info = read_frame_info (info_file, reel.first_nonexistant_frame, _film->three_d () ? EYES_LEFT : EYES_BOTH);
785
786                 ok = true;
787
788                 /* Read the data from the asset and hash it */
789                 dcpomatic_fseek (asset_file, info.offset, SEEK_SET);
790                 Data data (info.size);
791                 size_t const read = fread (data.data().get(), 1, data.size(), asset_file);
792                 if (read != static_cast<size_t> (data.size ())) {
793                         LOG_GENERAL ("Existing frame %1 is incomplete", reel.first_nonexistant_frame);
794                         ok = false;
795                 } else {
796                         MD5Digester digester;
797                         digester.add (data.data().get(), data.size());
798                         if (digester.get() != info.hash) {
799                                 LOG_GENERAL ("Existing frame %1 failed hash check", reel.first_nonexistant_frame);
800                                 ok = false;
801                         }
802                 }
803
804                 if (!ok) {
805                         --reel.first_nonexistant_frame;
806                 }
807         }
808
809         if (!_film->three_d ()) {
810                 /* If we are doing 3D we might have found a good L frame with no R, so only
811                    do this if we're in 2D and we've just found a good B(oth) frame.
812                 */
813                 ++reel.first_nonexistant_frame;
814         }
815
816         fclose (asset_file);
817         fclose (info_file);
818 }
819
820 /** @param frame Frame index within the whole DCP.
821  *  @return true if we can fake-write this frame.
822  */
823 bool
824 Writer::can_fake_write (Frame frame) const
825 {
826         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
827            parameters in the asset writer.
828         */
829
830         Reel const & reel = _reels[video_reel(frame)];
831
832         /* Make frame relative to the start of the reel */
833         frame -= reel.period.from.frames_floor (_film->video_frame_rate());
834         return (frame != 0 && frame < reel.first_nonexistant_frame);
835 }
836
837 void
838 Writer::write (PlayerSubtitles subs)
839 {
840         if (subs.text.empty ()) {
841                 return;
842         }
843
844         if (_subtitle_reel->period.to < subs.from) {
845                 ++_subtitle_reel;
846         }
847
848         if (!_subtitle_reel->subtitle_asset) {
849                 string lang = _film->subtitle_language ();
850                 if (lang.empty ()) {
851                         lang = "Unknown";
852                 }
853                 if (_film->interop ()) {
854                         shared_ptr<dcp::InteropSubtitleAsset> s (new dcp::InteropSubtitleAsset ());
855                         s->set_movie_title (_film->name ());
856                         s->set_language (lang);
857                         s->set_reel_number ("1");
858                         _subtitle_reel->subtitle_asset = s;
859                 } else {
860                         shared_ptr<dcp::SMPTESubtitleAsset> s (new dcp::SMPTESubtitleAsset ());
861                         s->set_content_title_text (_film->name ());
862                         s->set_language (lang);
863                         s->set_edit_rate (dcp::Fraction (_film->video_frame_rate (), 1));
864                         s->set_reel_number (1);
865                         s->set_time_code_rate (_film->video_frame_rate ());
866                         s->set_start_time (dcp::Time ());
867                         _subtitle_reel->subtitle_asset = s;
868                 }
869         }
870
871         for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
872                 _subtitle_reel->subtitle_asset->add (*i);
873         }
874 }
875
876 void
877 Writer::write (list<shared_ptr<Font> > fonts)
878 {
879         /* Just keep a list of fonts and we'll deal with them in ::finish */
880         copy (fonts.begin (), fonts.end (), back_inserter (_fonts));
881 }
882
883 bool
884 operator< (QueueItem const & a, QueueItem const & b)
885 {
886         if (a.reel != b.reel) {
887                 return a.reel < b.reel;
888         }
889
890         if (a.frame != b.frame) {
891                 return a.frame < b.frame;
892         }
893
894         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
895 }
896
897 bool
898 operator== (QueueItem const & a, QueueItem const & b)
899 {
900         return a.reel == b.reel && a.frame == b.frame && a.eyes == b.eyes;
901 }
902
903 void
904 Writer::set_encoder_threads (int threads)
905 {
906         _maximum_frames_in_memory = lrint (threads * 1.1);
907 }
908
909 long
910 Writer::frame_info_position (int frame, Eyes eyes) const
911 {
912         switch (eyes) {
913         case EYES_BOTH:
914                 return frame * _info_size;
915         case EYES_LEFT:
916                 return frame * _info_size * 2;
917         case EYES_RIGHT:
918                 return frame * _info_size * 2 + _info_size;
919         default:
920                 DCPOMATIC_ASSERT (false);
921         }
922
923         DCPOMATIC_ASSERT (false);
924 }
925
926 dcp::FrameInfo
927 Writer::read_frame_info (FILE* file, int frame, Eyes eyes) const
928 {
929         dcp::FrameInfo info;
930         dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
931         fread (&info.offset, sizeof (info.offset), 1, file);
932         fread (&info.size, sizeof (info.size), 1, file);
933
934         char hash_buffer[33];
935         fread (hash_buffer, 1, 32, file);
936         hash_buffer[32] = '\0';
937         info.hash = hash_buffer;
938
939         return info;
940 }
941
942 void
943 Writer::write (ReferencedReelAsset asset)
944 {
945         _reel_assets.push_back (asset);
946 }
947
948 size_t
949 Writer::video_reel (int frame) const
950 {
951         DCPTime t = DCPTime::from_frames (frame, _film->video_frame_rate ());
952         size_t i = 0;
953         while (i < _reels.size() && !_reels[i].period.contains (t)) {
954                 ++i;
955         }
956
957         DCPOMATIC_ASSERT (i < _reels.size ());
958         return i;
959 }