2 Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
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.
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.
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.
21 #include "compose.hpp"
25 #include "dcp_video.h"
26 #include "dcp_content_type.h"
27 #include "audio_mapping.h"
31 #include "audio_buffers.h"
32 #include "md5_digester.h"
33 #include "encoded_data.h"
36 #include <dcp/mono_picture_mxf.h>
37 #include <dcp/stereo_picture_mxf.h>
38 #include <dcp/sound_mxf.h>
39 #include <dcp/sound_mxf_writer.h>
41 #include <dcp/reel_mono_picture_asset.h>
42 #include <dcp/reel_stereo_picture_asset.h>
43 #include <dcp/reel_sound_asset.h>
44 #include <dcp/reel_subtitle_asset.h>
47 #include <dcp/signer.h>
48 #include <dcp/interop_subtitle_content.h>
50 #include <boost/foreach.hpp>
56 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
57 #define LOG_TIMING(...) _film->log()->microsecond_log (String::compose (__VA_ARGS__), Log::TYPE_TIMING);
58 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_WARNING);
59 #define LOG_WARNING(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_WARNING);
60 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
61 #define LOG_DEBUG(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_DEBUG);
62 #define LOG_DEBUG_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_DEBUG);
64 /* OS X strikes again */
72 using boost::shared_ptr;
73 using boost::weak_ptr;
74 using boost::dynamic_pointer_cast;
76 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
79 , _first_nonexistant_frame (0)
82 , _queued_full_in_memory (0)
83 , _last_written_frame (-1)
84 , _last_written_eyes (EYES_RIGHT)
89 /* Remove any old DCP */
90 boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
92 shared_ptr<Job> job = _job.lock ();
93 DCPOMATIC_ASSERT (job);
95 /* Create our picture asset in a subdirectory, named according to those
96 film's parameters which affect the video output. We will hard-link
97 it into the DCP later.
100 if (_film->three_d ()) {
101 _picture_mxf.reset (new dcp::StereoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
103 _picture_mxf.reset (new dcp::MonoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
106 job->sub (_("Checking existing image data"));
107 check_existing_picture_mxf ();
109 _picture_mxf->set_size (_film->frame_size ());
111 if (_film->encrypted ()) {
112 _picture_mxf->set_key (_film->key ());
115 _picture_mxf_writer = _picture_mxf->start_write (
116 _film->internal_video_mxf_dir() / _film->internal_video_mxf_filename(),
117 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
118 _first_nonexistant_frame > 0
121 if (_film->audio_channels ()) {
122 _sound_mxf.reset (new dcp::SoundMXF (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ()));
124 if (_film->encrypted ()) {
125 _sound_mxf->set_key (_film->key ());
128 /* Write the sound MXF into the film directory so that we leave the creation
129 of the DCP directory until the last minute.
131 _sound_mxf_writer = _sound_mxf->start_write (_film->directory() / _film->audio_mxf_filename(), _film->interop() ? dcp::INTEROP : dcp::SMPTE);
134 /* Check that the signer is OK if we need one */
135 if (_film->is_signed() && !Config::instance()->signer()->valid ()) {
136 throw InvalidSignerError ();
139 _thread = new boost::thread (boost::bind (&Writer::thread, this));
141 job->sub (_("Encoding image data"));
146 terminate_thread (false);
150 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
152 boost::mutex::scoped_lock lock (_mutex);
154 while (_queued_full_in_memory > maximum_frames_in_memory ()) {
155 /* The queue is too big; wait until that is sorted out */
156 _full_condition.wait (lock);
160 qi.type = QueueItem::FULL;
161 qi.encoded = encoded;
164 if (_film->three_d() && eyes == EYES_BOTH) {
165 /* 2D material in a 3D DCP; fake the 3D */
167 _queue.push_back (qi);
168 ++_queued_full_in_memory;
169 qi.eyes = EYES_RIGHT;
170 _queue.push_back (qi);
171 ++_queued_full_in_memory;
174 _queue.push_back (qi);
175 ++_queued_full_in_memory;
178 /* Now there's something to do: wake anything wait()ing on _empty_condition */
179 _empty_condition.notify_all ();
183 Writer::fake_write (int frame, Eyes eyes)
185 boost::mutex::scoped_lock lock (_mutex);
187 while (_queued_full_in_memory > maximum_frames_in_memory ()) {
188 /* The queue is too big; wait until that is sorted out */
189 _full_condition.wait (lock);
192 FILE* file = fopen_boost (_film->info_file (), "rb");
194 throw ReadFileError (_film->info_file ());
196 dcp::FrameInfo info = read_frame_info (file, frame, eyes);
200 qi.type = QueueItem::FAKE;
203 if (_film->three_d() && eyes == EYES_BOTH) {
205 _queue.push_back (qi);
206 qi.eyes = EYES_RIGHT;
207 _queue.push_back (qi);
210 _queue.push_back (qi);
213 /* Now there's something to do: wake anything wait()ing on _empty_condition */
214 _empty_condition.notify_all ();
217 /** This method is not thread safe */
219 Writer::write (shared_ptr<const AudioBuffers> audio)
221 if (_sound_mxf_writer) {
222 _sound_mxf_writer->write (audio->data(), audio->frames());
226 /** This must be called from Writer::thread() with an appropriate lock held */
228 Writer::have_sequenced_image_at_queue_head ()
230 if (_queue.empty ()) {
236 /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
238 if (_queue.front().eyes == EYES_BOTH) {
240 return _queue.front().frame == (_last_written_frame + 1);
245 if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
249 if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
262 boost::mutex::scoped_lock lock (_mutex);
264 /* This is for debugging only */
265 bool done_something = false;
269 if (_finish || _queued_full_in_memory > maximum_frames_in_memory () || have_sequenced_image_at_queue_head ()) {
270 /* We've got something to do: go and do it */
274 /* Nothing to do: wait until something happens which may indicate that we do */
275 LOG_TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
276 _empty_condition.wait (lock);
277 LOG_TIMING (N_("writer wakes with a queue of %1"), _queue.size());
280 if (_finish && _queue.empty()) {
284 /* We stop here if we have been asked to finish, and if either the queue
285 is empty or we do not have a sequenced image at its head (if this is the
286 case we will never terminate as no new frames will be sent once
289 if (_finish && (!have_sequenced_image_at_queue_head() || _queue.empty())) {
290 done_something = true;
291 /* (Hopefully temporarily) log anything that was not written */
292 if (!_queue.empty() && !have_sequenced_image_at_queue_head()) {
293 LOG_WARNING (N_("Finishing writer with a left-over queue of %1:"), _queue.size());
294 for (list<QueueItem>::const_iterator i = _queue.begin(); i != _queue.end(); ++i) {
295 if (i->type == QueueItem::FULL) {
296 LOG_WARNING (N_("- type FULL, frame %1, eyes %2"), i->frame, i->eyes);
298 LOG_WARNING (N_("- type FAKE, size %1, frame %2, eyes %3"), i->size, i->frame, i->eyes);
301 LOG_WARNING (N_("Last written frame %1, last written eyes %2"), _last_written_frame, _last_written_eyes);
305 /* Write any frames that we can write; i.e. those that are in sequence. */
306 while (have_sequenced_image_at_queue_head ()) {
307 done_something = true;
308 QueueItem qi = _queue.front ();
310 if (qi.type == QueueItem::FULL && qi.encoded) {
311 --_queued_full_in_memory;
316 case QueueItem::FULL:
318 LOG_GENERAL (N_("Writer FULL-writes %1 to MXF"), qi.frame);
320 qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
323 dcp::FrameInfo fin = _picture_mxf_writer->write (qi.encoded->data(), qi.encoded->size());
324 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
325 _last_written[qi.eyes] = qi.encoded;
329 case QueueItem::FAKE:
330 LOG_GENERAL (N_("Writer FAKE-writes %1 to MXF"), qi.frame);
331 _picture_mxf_writer->fake_write (qi.size);
332 _last_written[qi.eyes].reset ();
338 _last_written_frame = qi.frame;
339 _last_written_eyes = qi.eyes;
341 shared_ptr<Job> job = _job.lock ();
342 DCPOMATIC_ASSERT (job);
343 int64_t total = _film->length().frames (_film->video_frame_rate ());
344 if (_film->three_d ()) {
345 /* _full_written and so on are incremented for each eye, so we need to double the total
346 frames to get the correct progress.
351 job->set_progress (float (_full_written + _fake_written) / total);
355 while (_queued_full_in_memory > maximum_frames_in_memory ()) {
356 done_something = true;
357 /* Too many frames in memory which can't yet be written to the stream.
358 Write some FULL frames to disk.
361 /* Find one from the back of the queue */
363 list<QueueItem>::reverse_iterator i = _queue.rbegin ();
364 while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
368 DCPOMATIC_ASSERT (i != _queue.rend());
376 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
377 _last_written_frame + 1,
378 _last_written_eyes, qi.frame
381 qi.encoded->write (_film, qi.frame, qi.eyes);
384 --_queued_full_in_memory;
387 if (!done_something) {
388 LOG_DEBUG_NC ("Writer loop ran without doing anything");
389 LOG_DEBUG ("_queued_full_in_memory=%1", _queued_full_in_memory);
390 LOG_DEBUG ("_queue_size=%1", _queue.size ());
391 LOG_DEBUG ("_finish=%1", _finish);
392 LOG_DEBUG ("_last_written_frame=%1", _last_written_frame);
395 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
396 _full_condition.notify_all ();
405 Writer::terminate_thread (bool can_throw)
407 boost::mutex::scoped_lock lock (_mutex);
413 _empty_condition.notify_all ();
414 _full_condition.notify_all ();
433 terminate_thread (true);
435 _picture_mxf_writer->finalize ();
436 if (_sound_mxf_writer) {
437 _sound_mxf_writer->finalize ();
440 /* Hard-link the video MXF into the DCP */
441 boost::filesystem::path video_from = _picture_mxf->file ();
443 boost::filesystem::path video_to;
444 video_to /= _film->dir (_film->dcp_name());
445 video_to /= _film->video_mxf_filename ();
447 boost::system::error_code ec;
448 boost::filesystem::create_hard_link (video_from, video_to, ec);
450 LOG_WARNING_NC ("Hard-link failed; copying instead");
451 boost::filesystem::copy_file (video_from, video_to, ec);
453 LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
454 throw FileError (ec.message(), video_from);
458 _picture_mxf->set_file (video_to);
460 /* Move the audio MXF into the DCP */
463 boost::filesystem::path audio_to;
464 audio_to /= _film->dir (_film->dcp_name ());
465 audio_to /= _film->audio_mxf_filename ();
467 boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
470 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
474 _sound_mxf->set_file (audio_to);
477 dcp::DCP dcp (_film->dir (_film->dcp_name()));
479 shared_ptr<dcp::CPL> cpl (
482 _film->dcp_content_type()->libdcp_kind ()
488 shared_ptr<dcp::Reel> reel (new dcp::Reel ());
490 shared_ptr<dcp::MonoPictureMXF> mono = dynamic_pointer_cast<dcp::MonoPictureMXF> (_picture_mxf);
492 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
496 shared_ptr<dcp::StereoPictureMXF> stereo = dynamic_pointer_cast<dcp::StereoPictureMXF> (_picture_mxf);
498 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
503 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_mxf, 0)));
504 dcp.add (_sound_mxf);
507 if (_subtitle_content) {
508 _subtitle_content->write_xml (_film->dir (_film->dcp_name ()) / _film->subtitle_xml_filename ());
509 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
510 new dcp::ReelSubtitleAsset (
512 dcp::Fraction (_film->video_frame_rate(), 1),
513 _picture_mxf->intrinsic_duration (),
518 dcp.add (_subtitle_content);
520 boost::filesystem::path const liberation = shared_path () / "LiberationSans-Regular.ttf";
522 /* Add all the fonts to the subtitle content and as assets to the DCP */
523 BOOST_FOREACH (shared_ptr<Font> i, _fonts) {
524 boost::filesystem::path const from = i->file.get_value_or (liberation);
525 _subtitle_content->add_font (i->id, from.leaf().string ());
527 boost::filesystem::path to = _film->dir (_film->dcp_name ()) / from.leaf();
529 boost::system::error_code ec;
530 boost::filesystem::copy_file (from, to, ec);
532 dcp.add (shared_ptr<dcp::Font> (new dcp::Font (to)));
534 LOG_WARNING_NC (String::compose ("Could not copy font %1 to DCP", from.string ()));
541 shared_ptr<Job> job = _job.lock ();
542 DCPOMATIC_ASSERT (job);
544 job->sub (_("Computing image digest"));
545 _picture_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
548 job->sub (_("Computing audio digest"));
549 _sound_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
552 dcp::XMLMetadata meta;
553 meta.issuer = Config::instance()->dcp_issuer ();
554 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
555 meta.set_issue_date_now ();
557 shared_ptr<const dcp::Signer> signer;
558 if (_film->is_signed ()) {
559 signer = Config::instance()->signer ();
560 /* We did check earlier, but check again here to be on the safe side */
561 if (!signer->valid ()) {
562 throw InvalidSignerError ();
566 dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
569 N_("Wrote %1 FULL, %2 FAKE, %3 pushed to disk"), _full_written, _fake_written, _pushed_to_disk
574 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
576 /* Read the frame info as written */
577 FILE* file = fopen_boost (_film->info_file (), "rb");
579 LOG_GENERAL ("Existing frame %1 has no info file", f);
583 dcp::FrameInfo info = read_frame_info (file, f, eyes);
585 if (info.size == 0) {
586 LOG_GENERAL ("Existing frame %1 has no info file", f);
590 /* Read the data from the MXF and hash it */
591 dcpomatic_fseek (mxf, info.offset, SEEK_SET);
592 EncodedData data (info.size);
593 size_t const read = fread (data.data(), 1, data.size(), mxf);
594 if (read != static_cast<size_t> (data.size ())) {
595 LOG_GENERAL ("Existing frame %1 is incomplete", f);
599 MD5Digester digester;
600 digester.add (data.data(), data.size());
601 if (digester.get() != info.hash) {
602 LOG_GENERAL ("Existing frame %1 failed hash check", f);
610 Writer::check_existing_picture_mxf ()
612 /* Try to open the existing MXF */
613 FILE* mxf = fopen_boost (_picture_mxf->file(), "rb");
615 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", _picture_mxf->file().string(), errno);
621 shared_ptr<Job> job = _job.lock ();
622 DCPOMATIC_ASSERT (job);
624 job->set_progress_unknown ();
626 if (_film->three_d ()) {
627 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
630 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
634 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
639 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
640 ++_first_nonexistant_frame;
646 /** @param frame Frame index.
647 * @return true if we can fake-write this frame.
650 Writer::can_fake_write (int frame) const
652 /* We have to do a proper write of the first frame so that we can set up the JPEG2000
653 parameters in the MXF writer.
655 return (frame != 0 && frame < _first_nonexistant_frame);
659 Writer::write (PlayerSubtitles subs)
661 if (subs.text.empty ()) {
665 if (!_subtitle_content) {
666 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), _film->subtitle_language ()));
669 for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
670 _subtitle_content->add (*i);
675 Writer::write (list<shared_ptr<Font> > fonts)
677 /* Just keep a list of fonts and we'll deal with them in ::finish */
678 copy (fonts.begin (), fonts.end (), back_inserter (_fonts));
682 operator< (QueueItem const & a, QueueItem const & b)
684 if (a.frame != b.frame) {
685 return a.frame < b.frame;
688 return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
692 operator== (QueueItem const & a, QueueItem const & b)
694 return a.frame == b.frame && a.eyes == b.eyes;
698 Writer::maximum_frames_in_memory () const
700 return Config::instance()->num_local_encoding_threads() + 4;