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