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