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