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