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