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"
37 #include <dcp/mono_picture_mxf.h>
38 #include <dcp/stereo_picture_mxf.h>
39 #include <dcp/sound_mxf.h>
40 #include <dcp/sound_mxf_writer.h>
42 #include <dcp/reel_mono_picture_asset.h>
43 #include <dcp/reel_stereo_picture_asset.h>
44 #include <dcp/reel_sound_asset.h>
45 #include <dcp/reel_subtitle_asset.h>
48 #include <dcp/signer.h>
49 #include <dcp/interop_subtitle_content.h>
51 #include <boost/foreach.hpp>
57 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
58 #define LOG_TIMING(...) _film->log()->microsecond_log (String::compose (__VA_ARGS__), Log::TYPE_TIMING);
59 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_WARNING);
60 #define LOG_WARNING(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_WARNING);
61 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
62 #define LOG_DEBUG(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_DEBUG);
63 #define LOG_DEBUG_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_DEBUG);
65 /* OS X strikes again */
73 using boost::shared_ptr;
74 using boost::weak_ptr;
75 using boost::dynamic_pointer_cast;
77 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
80 , _first_nonexistant_frame (0)
83 , _queued_full_in_memory (0)
84 , _last_written_frame (-1)
85 , _last_written_eyes (EYES_RIGHT)
86 , _maximum_frames_in_memory (0)
91 /* Remove any old DCP */
92 boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
94 shared_ptr<Job> job = _job.lock ();
95 DCPOMATIC_ASSERT (job);
97 /* Create our picture asset in a subdirectory, named according to those
98 film's parameters which affect the video output. We will hard-link
99 it into the DCP later.
102 if (_film->three_d ()) {
103 _picture_mxf.reset (new dcp::StereoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
105 _picture_mxf.reset (new dcp::MonoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
108 _picture_mxf->set_size (_film->frame_size ());
110 if (_film->encrypted ()) {
111 _picture_mxf->set_key (_film->key ());
114 _picture_mxf_writer = _picture_mxf->start_write (
115 _film->internal_video_mxf_dir() / _film->internal_video_mxf_filename(),
116 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
117 _first_nonexistant_frame > 0
120 if (_film->audio_channels ()) {
121 _sound_mxf.reset (new dcp::SoundMXF (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ()));
123 if (_film->encrypted ()) {
124 _sound_mxf->set_key (_film->key ());
127 /* Write the sound MXF into the film directory so that we leave the creation
128 of the DCP directory until the last minute.
130 _sound_mxf_writer = _sound_mxf->start_write (_film->directory() / audio_mxf_filename (_sound_mxf), _film->interop() ? dcp::INTEROP : dcp::SMPTE);
133 /* Check that the signer is OK if we need one */
134 if (_film->is_signed() && !Config::instance()->signer()->valid ()) {
135 throw InvalidSignerError ();
138 job->sub (_("Checking existing image data"));
139 check_existing_picture_mxf ();
141 _thread = new boost::thread (boost::bind (&Writer::thread, this));
143 job->sub (_("Encoding image data"));
148 terminate_thread (false);
152 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
154 boost::mutex::scoped_lock lock (_mutex);
156 while (_queued_full_in_memory > _maximum_frames_in_memory) {
157 /* The queue is too big; wait until that is sorted out */
158 _full_condition.wait (lock);
162 qi.type = QueueItem::FULL;
163 qi.encoded = encoded;
166 if (_film->three_d() && eyes == EYES_BOTH) {
167 /* 2D material in a 3D DCP; fake the 3D */
169 _queue.push_back (qi);
170 ++_queued_full_in_memory;
171 qi.eyes = EYES_RIGHT;
172 _queue.push_back (qi);
173 ++_queued_full_in_memory;
176 _queue.push_back (qi);
177 ++_queued_full_in_memory;
180 /* Now there's something to do: wake anything wait()ing on _empty_condition */
181 _empty_condition.notify_all ();
185 Writer::fake_write (int frame, Eyes eyes)
187 boost::mutex::scoped_lock lock (_mutex);
189 while (_queued_full_in_memory > _maximum_frames_in_memory) {
190 /* The queue is too big; wait until that is sorted out */
191 _full_condition.wait (lock);
194 FILE* file = fopen_boost (_film->info_file (), "rb");
196 throw ReadFileError (_film->info_file ());
198 dcp::FrameInfo info = read_frame_info (file, frame, eyes);
202 qi.type = QueueItem::FAKE;
205 if (_film->three_d() && eyes == EYES_BOTH) {
207 _queue.push_back (qi);
208 qi.eyes = EYES_RIGHT;
209 _queue.push_back (qi);
212 _queue.push_back (qi);
215 /* Now there's something to do: wake anything wait()ing on _empty_condition */
216 _empty_condition.notify_all ();
219 /** This method is not thread safe */
221 Writer::write (shared_ptr<const AudioBuffers> audio)
223 if (_sound_mxf_writer) {
224 _sound_mxf_writer->write (audio->data(), audio->frames());
228 /** This must be called from Writer::thread() with an appropriate lock held */
230 Writer::have_sequenced_image_at_queue_head ()
232 if (_queue.empty ()) {
238 /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
240 if (_queue.front().eyes == EYES_BOTH) {
242 return _queue.front().frame == (_last_written_frame + 1);
247 if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
251 if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
264 boost::mutex::scoped_lock lock (_mutex);
266 /* This is for debugging only */
267 bool done_something = false;
271 if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
272 /* We've got something to do: go and do it */
276 /* Nothing to do: wait until something happens which may indicate that we do */
277 LOG_TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
278 _empty_condition.wait (lock);
279 LOG_TIMING (N_("writer wakes with a queue of %1"), _queue.size());
282 if (_finish && _queue.empty()) {
286 /* We stop here if we have been asked to finish, and if either the queue
287 is empty or we do not have a sequenced image at its head (if this is the
288 case we will never terminate as no new frames will be sent once
291 if (_finish && (!have_sequenced_image_at_queue_head() || _queue.empty())) {
292 done_something = true;
293 /* (Hopefully temporarily) log anything that was not written */
294 if (!_queue.empty() && !have_sequenced_image_at_queue_head()) {
295 LOG_WARNING (N_("Finishing writer with a left-over queue of %1:"), _queue.size());
296 for (list<QueueItem>::const_iterator i = _queue.begin(); i != _queue.end(); ++i) {
297 if (i->type == QueueItem::FULL) {
298 LOG_WARNING (N_("- type FULL, frame %1, eyes %2"), i->frame, i->eyes);
300 LOG_WARNING (N_("- type FAKE, size %1, frame %2, eyes %3"), i->size, i->frame, i->eyes);
303 LOG_WARNING (N_("Last written frame %1, last written eyes %2"), _last_written_frame, _last_written_eyes);
307 /* Write any frames that we can write; i.e. those that are in sequence. */
308 while (have_sequenced_image_at_queue_head ()) {
309 done_something = true;
310 QueueItem qi = _queue.front ();
312 if (qi.type == QueueItem::FULL && qi.encoded) {
313 --_queued_full_in_memory;
318 case QueueItem::FULL:
320 LOG_GENERAL (N_("Writer FULL-writes %1 to MXF"), qi.frame);
322 qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
325 dcp::FrameInfo fin = _picture_mxf_writer->write (qi.encoded->data(), qi.encoded->size());
326 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
327 _last_written[qi.eyes] = qi.encoded;
331 case QueueItem::FAKE:
332 LOG_GENERAL (N_("Writer FAKE-writes %1 to MXF"), qi.frame);
333 _picture_mxf_writer->fake_write (qi.size);
334 _last_written[qi.eyes].reset ();
340 _last_written_frame = qi.frame;
341 _last_written_eyes = qi.eyes;
343 shared_ptr<Job> job = _job.lock ();
344 DCPOMATIC_ASSERT (job);
345 int64_t total = _film->length().frames (_film->video_frame_rate ());
346 if (_film->three_d ()) {
347 /* _full_written and so on are incremented for each eye, so we need to double the total
348 frames to get the correct progress.
353 job->set_progress (float (_full_written + _fake_written) / total);
357 while (_queued_full_in_memory > _maximum_frames_in_memory) {
358 done_something = true;
359 /* Too many frames in memory which can't yet be written to the stream.
360 Write some FULL frames to disk.
363 /* Find one from the back of the queue */
365 list<QueueItem>::reverse_iterator i = _queue.rbegin ();
366 while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
370 DCPOMATIC_ASSERT (i != _queue.rend());
374 /* i is valid here, even though we don't hold a lock on the mutex,
375 since list iterators are unaffected by insertion and only this
376 thread could erase the last item in the list.
380 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
381 _last_written_frame + 1,
382 _last_written_eyes, i->frame
385 i->encoded->write (_film, i->frame, i->eyes);
389 --_queued_full_in_memory;
392 if (!done_something) {
393 LOG_DEBUG_NC ("Writer loop ran without doing anything");
394 LOG_DEBUG ("_queued_full_in_memory=%1", _queued_full_in_memory);
395 LOG_DEBUG ("_queue_size=%1", _queue.size ());
396 LOG_DEBUG ("_finish=%1", _finish);
397 LOG_DEBUG ("_last_written_frame=%1", _last_written_frame);
400 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
401 _full_condition.notify_all ();
410 Writer::terminate_thread (bool can_throw)
412 boost::mutex::scoped_lock lock (_mutex);
418 _empty_condition.notify_all ();
419 _full_condition.notify_all ();
438 terminate_thread (true);
440 _picture_mxf_writer->finalize ();
441 if (_sound_mxf_writer) {
442 _sound_mxf_writer->finalize ();
445 /* Hard-link the video MXF into the DCP */
446 boost::filesystem::path video_from = _picture_mxf->file ();
448 boost::filesystem::path video_to;
449 video_to /= _film->dir (_film->dcp_name());
450 video_to /= video_mxf_filename (_picture_mxf);
452 boost::system::error_code ec;
453 boost::filesystem::create_hard_link (video_from, video_to, ec);
455 LOG_WARNING_NC ("Hard-link failed; copying instead");
456 boost::filesystem::copy_file (video_from, video_to, ec);
458 LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
459 throw FileError (ec.message(), video_from);
463 _picture_mxf->set_file (video_to);
465 /* Move the audio MXF into the DCP */
468 boost::filesystem::path audio_to;
469 audio_to /= _film->dir (_film->dcp_name ());
470 audio_to /= audio_mxf_filename (_sound_mxf);
472 boost::filesystem::rename (_film->file (audio_mxf_filename (_sound_mxf)), audio_to, ec);
475 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), audio_mxf_filename (_sound_mxf)
479 _sound_mxf->set_file (audio_to);
482 dcp::DCP dcp (_film->dir (_film->dcp_name()));
484 shared_ptr<dcp::CPL> cpl (
487 _film->dcp_content_type()->libdcp_kind ()
493 shared_ptr<dcp::Reel> reel (new dcp::Reel ());
495 shared_ptr<dcp::MonoPictureMXF> mono = dynamic_pointer_cast<dcp::MonoPictureMXF> (_picture_mxf);
497 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
501 shared_ptr<dcp::StereoPictureMXF> stereo = dynamic_pointer_cast<dcp::StereoPictureMXF> (_picture_mxf);
503 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
508 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_mxf, 0)));
509 dcp.add (_sound_mxf);
512 if (_subtitle_content) {
513 boost::filesystem::path const liberation = shared_path () / "LiberationSans-Regular.ttf";
515 /* Add all the fonts to the subtitle content and as assets to the DCP */
516 BOOST_FOREACH (shared_ptr<Font> i, _fonts) {
517 boost::filesystem::path const from = i->file.get_value_or (liberation);
518 _subtitle_content->add_font (i->id, from.leaf().string ());
520 boost::filesystem::path to = _film->dir (_film->dcp_name ()) / _subtitle_content->id ();
521 boost::filesystem::create_directories (to, ec);
523 throw FileError (_("Could not create directory"), to);
528 boost::system::error_code ec;
529 boost::filesystem::copy_file (from, to, ec);
531 throw FileError ("Could not copy font to DCP", from);
534 dcp.add (shared_ptr<dcp::Font> (new dcp::Font (to)));
537 _subtitle_content->write_xml (_film->dir (_film->dcp_name ()) / _subtitle_content->id () / subtitle_content_filename (_subtitle_content));
538 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
539 new dcp::ReelSubtitleAsset (
541 dcp::Fraction (_film->video_frame_rate(), 1),
542 _picture_mxf->intrinsic_duration (),
547 dcp.add (_subtitle_content);
552 shared_ptr<Job> job = _job.lock ();
553 DCPOMATIC_ASSERT (job);
555 job->sub (_("Computing image digest"));
556 _picture_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
559 job->sub (_("Computing audio digest"));
560 _sound_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
563 dcp::XMLMetadata meta;
564 meta.issuer = Config::instance()->dcp_issuer ();
565 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
566 meta.set_issue_date_now ();
568 shared_ptr<const dcp::Signer> signer;
569 if (_film->is_signed ()) {
570 signer = Config::instance()->signer ();
571 /* We did check earlier, but check again here to be on the safe side */
572 if (!signer->valid ()) {
573 throw InvalidSignerError ();
577 dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
580 N_("Wrote %1 FULL, %2 FAKE, %3 pushed to disk"), _full_written, _fake_written, _pushed_to_disk
585 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
587 /* Read the frame info as written */
588 FILE* file = fopen_boost (_film->info_file (), "rb");
590 LOG_GENERAL ("Existing frame %1 has no info file", f);
594 dcp::FrameInfo info = read_frame_info (file, f, eyes);
596 if (info.size == 0) {
597 LOG_GENERAL ("Existing frame %1 has no info file", f);
601 /* Read the data from the MXF and hash it */
602 dcpomatic_fseek (mxf, info.offset, SEEK_SET);
603 EncodedData data (info.size);
604 size_t const read = fread (data.data(), 1, data.size(), mxf);
605 if (read != static_cast<size_t> (data.size ())) {
606 LOG_GENERAL ("Existing frame %1 is incomplete", f);
610 MD5Digester digester;
611 digester.add (data.data(), data.size());
612 if (digester.get() != info.hash) {
613 LOG_GENERAL ("Existing frame %1 failed hash check", f);
621 Writer::check_existing_picture_mxf ()
623 /* Try to open the existing MXF */
624 FILE* mxf = fopen_boost (_picture_mxf->file(), "rb");
626 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", _picture_mxf->file().string(), errno);
632 shared_ptr<Job> job = _job.lock ();
633 DCPOMATIC_ASSERT (job);
635 job->set_progress_unknown ();
637 if (_film->three_d ()) {
638 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
641 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
645 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
650 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
651 ++_first_nonexistant_frame;
657 /** @param frame Frame index.
658 * @return true if we can fake-write this frame.
661 Writer::can_fake_write (int frame) const
663 /* We have to do a proper write of the first frame so that we can set up the JPEG2000
664 parameters in the MXF writer.
666 return (frame != 0 && frame < _first_nonexistant_frame);
670 Writer::write (PlayerSubtitles subs)
672 if (subs.text.empty ()) {
676 if (!_subtitle_content) {
677 string lang = _film->subtitle_language ();
681 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), lang));
684 for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
685 _subtitle_content->add (*i);
690 Writer::write (list<shared_ptr<Font> > fonts)
692 /* Just keep a list of fonts and we'll deal with them in ::finish */
693 copy (fonts.begin (), fonts.end (), back_inserter (_fonts));
697 operator< (QueueItem const & a, QueueItem const & b)
699 if (a.frame != b.frame) {
700 return a.frame < b.frame;
703 return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
707 operator== (QueueItem const & a, QueueItem const & b)
709 return a.frame == b.frame && a.eyes == b.eyes;
713 Writer::set_encoder_threads (int threads)
715 _maximum_frames_in_memory = rint (threads * 1.1);