Basic pass-through of font information when using DCP subtitles.
[dcpomatic.git] / src / lib / writer.cc
1 /*
2     Copyright (C) 2012-2014 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 <dcp/mono_picture_mxf.h>
37 #include <dcp/stereo_picture_mxf.h>
38 #include <dcp/sound_mxf.h>
39 #include <dcp/sound_mxf_writer.h>
40 #include <dcp/reel.h>
41 #include <dcp/reel_mono_picture_asset.h>
42 #include <dcp/reel_stereo_picture_asset.h>
43 #include <dcp/reel_sound_asset.h>
44 #include <dcp/reel_subtitle_asset.h>
45 #include <dcp/dcp.h>
46 #include <dcp/cpl.h>
47 #include <dcp/signer.h>
48 #include <dcp/interop_subtitle_content.h>
49 #include <fstream>
50 #include <cerrno>
51
52 #include "i18n.h"
53
54 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
55 #define LOG_TIMING(...) _film->log()->microsecond_log (String::compose (__VA_ARGS__), Log::TYPE_TIMING);
56 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_WARNING);
57 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
58
59 /* OS X strikes again */
60 #undef set_key
61
62 using std::make_pair;
63 using std::pair;
64 using std::string;
65 using std::list;
66 using std::cout;
67 using boost::shared_ptr;
68 using boost::weak_ptr;
69 using boost::dynamic_pointer_cast;
70
71 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
72
73 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
74         : _film (f)
75         , _job (j)
76         , _first_nonexistant_frame (0)
77         , _thread (0)
78         , _finish (false)
79         , _queued_full_in_memory (0)
80         , _last_written_frame (-1)
81         , _last_written_eyes (EYES_RIGHT)
82         , _full_written (0)
83         , _fake_written (0)
84         , _pushed_to_disk (0)
85 {
86         /* Remove any old DCP */
87         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
88
89         shared_ptr<Job> job = _job.lock ();
90         assert (job);
91
92         job->sub (_("Checking existing image data"));
93         check_existing_picture_mxf ();
94
95         /* Create our picture asset in a subdirectory, named according to those
96            film's parameters which affect the video output.  We will hard-link
97            it into the DCP later.
98         */
99
100         if (_film->three_d ()) {
101                 _picture_mxf.reset (new dcp::StereoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
102         } else {
103                 _picture_mxf.reset (new dcp::MonoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
104         }
105
106         _picture_mxf->set_size (_film->frame_size ());
107
108         if (_film->encrypted ()) {
109                 _picture_mxf->set_key (_film->key ());
110         }
111         
112         _picture_mxf_writer = _picture_mxf->start_write (
113                 _film->internal_video_mxf_dir() / _film->internal_video_mxf_filename(),
114                 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
115                 _first_nonexistant_frame > 0
116                 );
117
118         if (_film->audio_channels ()) {
119                 _sound_mxf.reset (new dcp::SoundMXF (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ()));
120
121                 if (_film->encrypted ()) {
122                         _sound_mxf->set_key (_film->key ());
123                 }
124         
125                 /* Write the sound MXF into the film directory so that we leave the creation
126                    of the DCP directory until the last minute.
127                 */
128                 _sound_mxf_writer = _sound_mxf->start_write (_film->directory() / _film->audio_mxf_filename(), _film->interop() ? dcp::INTEROP : dcp::SMPTE);
129         }
130
131         /* Check that the signer is OK if we need one */
132         if (_film->is_signed() && !Config::instance()->signer()->valid ()) {
133                 throw InvalidSignerError ();
134         }
135
136         _thread = new boost::thread (boost::bind (&Writer::thread, this));
137
138         job->sub (_("Encoding image data"));
139 }
140
141 Writer::~Writer ()
142 {
143         terminate_thread (false);
144 }
145
146 void
147 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
148 {
149         boost::mutex::scoped_lock lock (_mutex);
150
151         while (_queued_full_in_memory > _maximum_frames_in_memory) {
152                 /* The queue is too big; wait until that is sorted out */
153                 _full_condition.wait (lock);
154         }
155
156         QueueItem qi;
157         qi.type = QueueItem::FULL;
158         qi.encoded = encoded;
159         qi.frame = frame;
160
161         if (_film->three_d() && eyes == EYES_BOTH) {
162                 /* 2D material in a 3D DCP; fake the 3D */
163                 qi.eyes = EYES_LEFT;
164                 _queue.push_back (qi);
165                 ++_queued_full_in_memory;
166                 qi.eyes = EYES_RIGHT;
167                 _queue.push_back (qi);
168                 ++_queued_full_in_memory;
169         } else {
170                 qi.eyes = eyes;
171                 _queue.push_back (qi);
172                 ++_queued_full_in_memory;
173         }
174
175         /* Now there's something to do: wake anything wait()ing on _empty_condition */
176         _empty_condition.notify_all ();
177 }
178
179 void
180 Writer::fake_write (int frame, Eyes eyes)
181 {
182         boost::mutex::scoped_lock lock (_mutex);
183
184         while (_queued_full_in_memory > _maximum_frames_in_memory) {
185                 /* The queue is too big; wait until that is sorted out */
186                 _full_condition.wait (lock);
187         }
188         
189         FILE* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
190         dcp::FrameInfo info (ifi);
191         fclose (ifi);
192         
193         QueueItem qi;
194         qi.type = QueueItem::FAKE;
195         qi.size = info.size;
196         qi.frame = frame;
197         if (_film->three_d() && eyes == EYES_BOTH) {
198                 qi.eyes = EYES_LEFT;
199                 _queue.push_back (qi);
200                 qi.eyes = EYES_RIGHT;
201                 _queue.push_back (qi);
202         } else {
203                 qi.eyes = eyes;
204                 _queue.push_back (qi);
205         }
206
207         /* Now there's something to do: wake anything wait()ing on _empty_condition */
208         _empty_condition.notify_all ();
209 }
210
211 /** This method is not thread safe */
212 void
213 Writer::write (shared_ptr<const AudioBuffers> audio)
214 {
215         if (_sound_mxf_writer) {
216                 _sound_mxf_writer->write (audio->data(), audio->frames());
217         }
218 }
219
220 /** This must be called from Writer::thread() with an appropriate lock held */
221 bool
222 Writer::have_sequenced_image_at_queue_head ()
223 {
224         if (_queue.empty ()) {
225                 return false;
226         }
227
228         _queue.sort ();
229
230         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
231
232         if (_queue.front().eyes == EYES_BOTH) {
233                 /* 2D */
234                 return _queue.front().frame == (_last_written_frame + 1);
235         }
236
237         /* 3D */
238
239         if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
240                 return true;
241         }
242
243         if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
244                 return true;
245         }
246
247         return false;
248 }
249
250 void
251 Writer::thread ()
252 try
253 {
254         while (true)
255         {
256                 boost::mutex::scoped_lock lock (_mutex);
257
258                 while (true) {
259                         
260                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
261                                 /* We've got something to do: go and do it */
262                                 break;
263                         }
264
265                         /* Nothing to do: wait until something happens which may indicate that we do */
266                         LOG_TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
267                         _empty_condition.wait (lock);
268                         LOG_TIMING (N_("writer wakes with a queue of %1"), _queue.size());
269                 }
270
271                 if (_finish && _queue.empty()) {
272                         return;
273                 }
274
275                 /* Write any frames that we can write; i.e. those that are in sequence. */
276                 while (have_sequenced_image_at_queue_head ()) {
277                         QueueItem qi = _queue.front ();
278                         _queue.pop_front ();
279                         if (qi.type == QueueItem::FULL && qi.encoded) {
280                                 --_queued_full_in_memory;
281                         }
282
283                         lock.unlock ();
284                         switch (qi.type) {
285                         case QueueItem::FULL:
286                         {
287                                 LOG_GENERAL (N_("Writer FULL-writes %1 to MXF"), qi.frame);
288                                 if (!qi.encoded) {
289                                         qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
290                                 }
291
292                                 dcp::FrameInfo fin = _picture_mxf_writer->write (qi.encoded->data(), qi.encoded->size());
293                                 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
294                                 _last_written[qi.eyes] = qi.encoded;
295                                 ++_full_written;
296                                 break;
297                         }
298                         case QueueItem::FAKE:
299                                 LOG_GENERAL (N_("Writer FAKE-writes %1 to MXF"), qi.frame);
300                                 _picture_mxf_writer->fake_write (qi.size);
301                                 _last_written[qi.eyes].reset ();
302                                 ++_fake_written;
303                                 break;
304                         }
305                         lock.lock ();
306
307                         _last_written_frame = qi.frame;
308                         _last_written_eyes = qi.eyes;
309                         
310                         shared_ptr<Job> job = _job.lock ();
311                         assert (job);
312                         int64_t total = _film->length().frames (_film->video_frame_rate ());
313                         if (_film->three_d ()) {
314                                 /* _full_written and so on are incremented for each eye, so we need to double the total
315                                    frames to get the correct progress.
316                                 */
317                                 total *= 2;
318                         }
319                         if (total) {
320                                 job->set_progress (float (_full_written + _fake_written) / total);
321                         }
322                 }
323
324                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
325                         /* Too many frames in memory which can't yet be written to the stream.
326                            Write some FULL frames to disk.
327                         */
328
329                         /* Find one from the back of the queue */
330                         _queue.sort ();
331                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
332                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
333                                 ++i;
334                         }
335
336                         assert (i != _queue.rend());
337                         QueueItem qi = *i;
338
339                         ++_pushed_to_disk;
340                         
341                         lock.unlock ();
342
343                         LOG_GENERAL (
344                                 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
345                                 _last_written_frame + 1,
346                                 _last_written_eyes, qi.frame
347                                 );
348                         
349                         qi.encoded->write (_film, qi.frame, qi.eyes);
350                         lock.lock ();
351                         qi.encoded.reset ();
352                         --_queued_full_in_memory;
353                 }
354
355                 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
356                 _full_condition.notify_all ();
357         }
358 }
359 catch (...)
360 {
361         store_current ();
362 }
363
364 void
365 Writer::terminate_thread (bool can_throw)
366 {
367         boost::mutex::scoped_lock lock (_mutex);
368         if (_thread == 0) {
369                 return;
370         }
371         
372         _finish = true;
373         _empty_condition.notify_all ();
374         _full_condition.notify_all ();
375         lock.unlock ();
376
377         _thread->join ();
378         if (can_throw) {
379                 rethrow ();
380         }
381         
382         delete _thread;
383         _thread = 0;
384 }       
385
386 void
387 Writer::finish ()
388 {
389         if (!_thread) {
390                 return;
391         }
392         
393         terminate_thread (true);
394
395         _picture_mxf_writer->finalize ();
396         if (_sound_mxf_writer) {
397                 _sound_mxf_writer->finalize ();
398         }
399         
400         /* Hard-link the video MXF into the DCP */
401         boost::filesystem::path video_from;
402         video_from /= _film->internal_video_mxf_dir();
403         video_from /= _film->internal_video_mxf_filename();
404         
405         boost::filesystem::path video_to;
406         video_to /= _film->dir (_film->dcp_name());
407         video_to /= _film->video_mxf_filename ();
408
409         boost::system::error_code ec;
410         boost::filesystem::create_hard_link (video_from, video_to, ec);
411         if (ec) {
412                 LOG_WARNING_NC ("Hard-link failed; copying instead");
413                 boost::filesystem::copy_file (video_from, video_to, ec);
414                 if (ec) {
415                         LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
416                         throw FileError (ec.message(), video_from);
417                 }
418         }
419
420         _picture_mxf->set_file (video_to);
421
422         /* Move the audio MXF into the DCP */
423
424         if (_sound_mxf) {
425                 boost::filesystem::path audio_to;
426                 audio_to /= _film->dir (_film->dcp_name ());
427                 audio_to /= _film->audio_mxf_filename ();
428                 
429                 boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
430                 if (ec) {
431                         throw FileError (
432                                 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
433                                 );
434                 }
435
436                 _sound_mxf->set_file (audio_to);
437         }
438
439         dcp::DCP dcp (_film->dir (_film->dcp_name()));
440
441         shared_ptr<dcp::CPL> cpl (
442                 new dcp::CPL (
443                         _film->dcp_name(),
444                         _film->dcp_content_type()->libdcp_kind ()
445                         )
446                 );
447         
448         dcp.add (cpl);
449
450         shared_ptr<dcp::Reel> reel (new dcp::Reel ());
451
452         shared_ptr<dcp::MonoPictureMXF> mono = dynamic_pointer_cast<dcp::MonoPictureMXF> (_picture_mxf);
453         if (mono) {
454                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
455                 dcp.add (mono);
456         }
457
458         shared_ptr<dcp::StereoPictureMXF> stereo = dynamic_pointer_cast<dcp::StereoPictureMXF> (_picture_mxf);
459         if (stereo) {
460                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
461                 dcp.add (stereo);
462         }
463
464         if (_sound_mxf) {
465                 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_mxf, 0)));
466                 dcp.add (_sound_mxf);
467         }
468
469         if (_subtitle_content) {
470                 _subtitle_content->write_xml (_film->dir (_film->dcp_name ()) / _film->subtitle_xml_filename ());
471                 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
472                                    new dcp::ReelSubtitleAsset (
473                                            _subtitle_content,
474                                            dcp::Fraction (_film->video_frame_rate(), 1),
475                                            _picture_mxf->intrinsic_duration (),
476                                            0
477                                            )
478                                    ));
479                 
480                 dcp.add (_subtitle_content);
481         }
482         
483         cpl->add (reel);
484
485         shared_ptr<Job> job = _job.lock ();
486         assert (job);
487
488         job->sub (_("Computing image digest"));
489         _picture_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
490
491         if (_sound_mxf) {
492                 job->sub (_("Computing audio digest"));
493                 _sound_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
494         }
495
496         dcp::XMLMetadata meta;
497         meta.issuer = Config::instance()->dcp_issuer ();
498         meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
499         meta.set_issue_date_now ();
500
501         shared_ptr<const dcp::Signer> signer;
502         if (_film->is_signed ()) {
503                 signer = Config::instance()->signer ();
504                 /* We did check earlier, but check again here to be on the safe side */
505                 if (!signer->valid ()) {
506                         throw InvalidSignerError ();
507                 }
508         }
509
510         dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
511
512         LOG_GENERAL (
513                 N_("Wrote %1 FULL, %2 FAKE, %3 pushed to disk"), _full_written, _fake_written, _pushed_to_disk
514                 );
515 }
516
517 bool
518 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
519 {
520         /* Read the frame info as written */
521         FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
522         if (!ifi) {
523                 LOG_GENERAL ("Existing frame %1 has no info file", f);
524                 return false;
525         }
526         
527         dcp::FrameInfo info (ifi);
528         fclose (ifi);
529         if (info.size == 0) {
530                 LOG_GENERAL ("Existing frame %1 has no info file", f);
531                 return false;
532         }
533         
534         /* Read the data from the MXF and hash it */
535         dcpomatic_fseek (mxf, info.offset, SEEK_SET);
536         EncodedData data (info.size);
537         size_t const read = fread (data.data(), 1, data.size(), mxf);
538         if (read != static_cast<size_t> (data.size ())) {
539                 LOG_GENERAL ("Existing frame %1 is incomplete", f);
540                 return false;
541         }
542
543         MD5Digester digester;
544         digester.add (data.data(), data.size());
545         if (digester.get() != info.hash) {
546                 LOG_GENERAL ("Existing frame %1 failed hash check", f);
547                 return false;
548         }
549
550         return true;
551 }
552
553 void
554 Writer::check_existing_picture_mxf ()
555 {
556         /* Try to open the existing MXF */
557         boost::filesystem::path p;
558         p /= _film->internal_video_mxf_dir ();
559         p /= _film->internal_video_mxf_filename ();
560         FILE* mxf = fopen_boost (p, "rb");
561         if (!mxf) {
562                 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno);
563                 return;
564         }
565
566         int N = 0;
567         for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
568                 ++N;
569         }
570
571         while (true) {
572
573                 shared_ptr<Job> job = _job.lock ();
574                 assert (job);
575
576                 if (N > 0) {
577                         job->set_progress (float (_first_nonexistant_frame) / N);
578                 }
579
580                 if (_film->three_d ()) {
581                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
582                                 break;
583                         }
584                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
585                                 break;
586                         }
587                 } else {
588                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
589                                 break;
590                         }
591                 }
592
593                 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
594                 ++_first_nonexistant_frame;
595         }
596
597         fclose (mxf);
598 }
599
600 /** @param frame Frame index.
601  *  @return true if we can fake-write this frame.
602  */
603 bool
604 Writer::can_fake_write (int frame) const
605 {
606         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
607            parameters in the MXF writer.
608         */
609         return (frame != 0 && frame < _first_nonexistant_frame);
610 }
611
612 void
613 Writer::write (PlayerSubtitles subs)
614 {
615         if (subs.text.empty ()) {
616                 return;
617         }
618         
619         if (!_subtitle_content) {
620                 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), _film->subtitle_language ()));
621         }
622         
623         for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
624                 _subtitle_content->add (*i);
625         }
626 }
627
628 void
629 Writer::write (list<shared_ptr<Font> > fonts)
630 {
631         if (!_subtitle_content) {
632                 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), _film->subtitle_language ()));
633         }
634         
635         for (list<shared_ptr<Font> >::const_iterator i = fonts.begin(); i != fonts.end(); ++i) {
636                 /* XXX: this LiberationSans-Regular needs to be a path to a DCP-o-matic-distributed copy */
637                 _subtitle_content->add_font ((*i)->id, (*i)->file.get_value_or ("LiberationSans-Regular.ttf").leaf().string ());
638         }
639 }
640
641 bool
642 operator< (QueueItem const & a, QueueItem const & b)
643 {
644         if (a.frame != b.frame) {
645                 return a.frame < b.frame;
646         }
647
648         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
649 }
650
651 bool
652 operator== (QueueItem const & a, QueueItem const & b)
653 {
654         return a.frame == b.frame && a.eyes == b.eyes;
655 }