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