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