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>
54 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
55 #define LOG_TIMING(...) _film->log()->microsecond_log (String::compose (__VA_ARGS__), Log::TYPE_TIMING);
56 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_WARNING);
57 #define LOG_WARNING(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_WARNING);
58 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
59 #define LOG_DEBUG(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_DEBUG);
60 #define LOG_DEBUG_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_DEBUG);
62 /* OS X strikes again */
70 using boost::shared_ptr;
71 using boost::weak_ptr;
72 using boost::dynamic_pointer_cast;
74 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
77 , _first_nonexistant_frame (0)
80 , _queued_full_in_memory (0)
81 , _last_written_frame (-1)
82 , _last_written_eyes (EYES_RIGHT)
87 /* Remove any old DCP */
88 boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
90 shared_ptr<Job> job = _job.lock ();
91 DCPOMATIC_ASSERT (job);
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.
98 if (_film->three_d ()) {
99 _picture_mxf.reset (new dcp::StereoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
101 _picture_mxf.reset (new dcp::MonoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
104 job->sub (_("Checking existing image data"));
105 check_existing_picture_mxf ();
107 _picture_mxf->set_size (_film->frame_size ());
109 if (_film->encrypted ()) {
110 _picture_mxf->set_key (_film->key ());
113 _picture_mxf_writer = _picture_mxf->start_write (
114 _film->internal_video_mxf_dir() / _film->internal_video_mxf_filename(),
115 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
116 _first_nonexistant_frame > 0
119 if (_film->audio_channels ()) {
120 _sound_mxf.reset (new dcp::SoundMXF (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ()));
122 if (_film->encrypted ()) {
123 _sound_mxf->set_key (_film->key ());
126 /* Write the sound MXF into the film directory so that we leave the creation
127 of the DCP directory until the last minute.
129 _sound_mxf_writer = _sound_mxf->start_write (_film->directory() / _film->audio_mxf_filename(), _film->interop() ? dcp::INTEROP : dcp::SMPTE);
132 /* Check that the signer is OK if we need one */
133 if (_film->is_signed() && !Config::instance()->signer()->valid ()) {
134 throw InvalidSignerError ();
137 _thread = new boost::thread (boost::bind (&Writer::thread, this));
139 job->sub (_("Encoding image data"));
144 terminate_thread (false);
148 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
150 boost::mutex::scoped_lock lock (_mutex);
152 while (_queued_full_in_memory > maximum_frames_in_memory ()) {
153 /* The queue is too big; wait until that is sorted out */
154 _full_condition.wait (lock);
158 qi.type = QueueItem::FULL;
159 qi.encoded = encoded;
162 if (_film->three_d() && eyes == EYES_BOTH) {
163 /* 2D material in a 3D DCP; fake the 3D */
165 _queue.push_back (qi);
166 ++_queued_full_in_memory;
167 qi.eyes = EYES_RIGHT;
168 _queue.push_back (qi);
169 ++_queued_full_in_memory;
172 _queue.push_back (qi);
173 ++_queued_full_in_memory;
176 /* Now there's something to do: wake anything wait()ing on _empty_condition */
177 _empty_condition.notify_all ();
181 Writer::fake_write (int frame, Eyes eyes)
183 boost::mutex::scoped_lock lock (_mutex);
185 while (_queued_full_in_memory > maximum_frames_in_memory ()) {
186 /* The queue is too big; wait until that is sorted out */
187 _full_condition.wait (lock);
190 FILE* file = fopen_boost (_film->info_file (), "rb");
192 throw ReadFileError (_film->info_file ());
194 dcp::FrameInfo info = read_frame_info (file, frame, eyes);
198 qi.type = QueueItem::FAKE;
201 if (_film->three_d() && eyes == EYES_BOTH) {
203 _queue.push_back (qi);
204 qi.eyes = EYES_RIGHT;
205 _queue.push_back (qi);
208 _queue.push_back (qi);
211 /* Now there's something to do: wake anything wait()ing on _empty_condition */
212 _empty_condition.notify_all ();
215 /** This method is not thread safe */
217 Writer::write (shared_ptr<const AudioBuffers> audio)
219 if (_sound_mxf_writer) {
220 _sound_mxf_writer->write (audio->data(), audio->frames());
224 /** This must be called from Writer::thread() with an appropriate lock held */
226 Writer::have_sequenced_image_at_queue_head ()
228 if (_queue.empty ()) {
234 /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
236 if (_queue.front().eyes == EYES_BOTH) {
238 return _queue.front().frame == (_last_written_frame + 1);
243 if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
247 if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
260 boost::mutex::scoped_lock lock (_mutex);
262 /* This is for debugging only */
263 bool done_something = false;
267 if (_finish || _queued_full_in_memory > maximum_frames_in_memory () || have_sequenced_image_at_queue_head ()) {
268 /* We've got something to do: go and do it */
272 /* Nothing to do: wait until something happens which may indicate that we do */
273 LOG_TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
274 _empty_condition.wait (lock);
275 LOG_TIMING (N_("writer wakes with a queue of %1"), _queue.size());
278 if (_finish && _queue.empty()) {
282 /* We stop here if we have been asked to finish, and if either the queue
283 is empty or we do not have a sequenced image at its head (if this is the
284 case we will never terminate as no new frames will be sent once
287 if (_finish && (!have_sequenced_image_at_queue_head() || _queue.empty())) {
288 done_something = true;
289 /* (Hopefully temporarily) log anything that was not written */
290 if (!_queue.empty() && !have_sequenced_image_at_queue_head()) {
291 LOG_WARNING (N_("Finishing writer with a left-over queue of %1:"), _queue.size());
292 for (list<QueueItem>::const_iterator i = _queue.begin(); i != _queue.end(); ++i) {
293 if (i->type == QueueItem::FULL) {
294 LOG_WARNING (N_("- type FULL, frame %1, eyes %2"), i->frame, i->eyes);
296 LOG_WARNING (N_("- type FAKE, size %1, frame %2, eyes %3"), i->size, i->frame, i->eyes);
299 LOG_WARNING (N_("Last written frame %1, last written eyes %2"), _last_written_frame, _last_written_eyes);
303 /* Write any frames that we can write; i.e. those that are in sequence. */
304 while (have_sequenced_image_at_queue_head ()) {
305 done_something = true;
306 QueueItem qi = _queue.front ();
308 if (qi.type == QueueItem::FULL && qi.encoded) {
309 --_queued_full_in_memory;
314 case QueueItem::FULL:
316 LOG_GENERAL (N_("Writer FULL-writes %1 to MXF"), qi.frame);
318 qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
321 dcp::FrameInfo fin = _picture_mxf_writer->write (qi.encoded->data(), qi.encoded->size());
322 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
323 _last_written[qi.eyes] = qi.encoded;
327 case QueueItem::FAKE:
328 LOG_GENERAL (N_("Writer FAKE-writes %1 to MXF"), qi.frame);
329 _picture_mxf_writer->fake_write (qi.size);
330 _last_written[qi.eyes].reset ();
336 _last_written_frame = qi.frame;
337 _last_written_eyes = qi.eyes;
339 shared_ptr<Job> job = _job.lock ();
340 DCPOMATIC_ASSERT (job);
341 int64_t total = _film->length().frames (_film->video_frame_rate ());
342 if (_film->three_d ()) {
343 /* _full_written and so on are incremented for each eye, so we need to double the total
344 frames to get the correct progress.
349 job->set_progress (float (_full_written + _fake_written) / total);
353 while (_queued_full_in_memory > maximum_frames_in_memory ()) {
354 done_something = true;
355 /* Too many frames in memory which can't yet be written to the stream.
356 Write some FULL frames to disk.
359 /* Find one from the back of the queue */
361 list<QueueItem>::reverse_iterator i = _queue.rbegin ();
362 while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
366 DCPOMATIC_ASSERT (i != _queue.rend());
374 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
375 _last_written_frame + 1,
376 _last_written_eyes, qi.frame
379 qi.encoded->write (_film, qi.frame, qi.eyes);
382 --_queued_full_in_memory;
385 if (!done_something) {
386 LOG_DEBUG_NC ("Writer loop ran without doing anything");
387 LOG_DEBUG ("_queued_full_in_memory=%1", _queued_full_in_memory);
388 LOG_DEBUG ("_queue_size=%1", _queue.size ());
389 LOG_DEBUG ("_finish=%1", _finish);
390 LOG_DEBUG ("_last_written_frame=%1", _last_written_frame);
393 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
394 _full_condition.notify_all ();
403 Writer::terminate_thread (bool can_throw)
405 boost::mutex::scoped_lock lock (_mutex);
411 _empty_condition.notify_all ();
412 _full_condition.notify_all ();
431 terminate_thread (true);
433 _picture_mxf_writer->finalize ();
434 if (_sound_mxf_writer) {
435 _sound_mxf_writer->finalize ();
438 /* Hard-link the video MXF into the DCP */
439 boost::filesystem::path video_from = _picture_mxf->file ();
441 boost::filesystem::path video_to;
442 video_to /= _film->dir (_film->dcp_name());
443 video_to /= _film->video_mxf_filename ();
445 boost::system::error_code ec;
446 boost::filesystem::create_hard_link (video_from, video_to, ec);
448 LOG_WARNING_NC ("Hard-link failed; copying instead");
449 boost::filesystem::copy_file (video_from, video_to, ec);
451 LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
452 throw FileError (ec.message(), video_from);
456 _picture_mxf->set_file (video_to);
458 /* Move the audio MXF into the DCP */
461 boost::filesystem::path audio_to;
462 audio_to /= _film->dir (_film->dcp_name ());
463 audio_to /= _film->audio_mxf_filename ();
465 boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
468 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
472 _sound_mxf->set_file (audio_to);
475 dcp::DCP dcp (_film->dir (_film->dcp_name()));
477 shared_ptr<dcp::CPL> cpl (
480 _film->dcp_content_type()->libdcp_kind ()
486 shared_ptr<dcp::Reel> reel (new dcp::Reel ());
488 shared_ptr<dcp::MonoPictureMXF> mono = dynamic_pointer_cast<dcp::MonoPictureMXF> (_picture_mxf);
490 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
494 shared_ptr<dcp::StereoPictureMXF> stereo = dynamic_pointer_cast<dcp::StereoPictureMXF> (_picture_mxf);
496 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
501 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_mxf, 0)));
502 dcp.add (_sound_mxf);
505 if (_subtitle_content) {
506 _subtitle_content->write_xml (_film->dir (_film->dcp_name ()) / _film->subtitle_xml_filename ());
507 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
508 new dcp::ReelSubtitleAsset (
510 dcp::Fraction (_film->video_frame_rate(), 1),
511 _picture_mxf->intrinsic_duration (),
516 dcp.add (_subtitle_content);
521 shared_ptr<Job> job = _job.lock ();
522 DCPOMATIC_ASSERT (job);
524 job->sub (_("Computing image digest"));
525 _picture_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
528 job->sub (_("Computing audio digest"));
529 _sound_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
532 dcp::XMLMetadata meta;
533 meta.issuer = Config::instance()->dcp_issuer ();
534 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
535 meta.set_issue_date_now ();
537 shared_ptr<const dcp::Signer> signer;
538 if (_film->is_signed ()) {
539 signer = Config::instance()->signer ();
540 /* We did check earlier, but check again here to be on the safe side */
541 if (!signer->valid ()) {
542 throw InvalidSignerError ();
546 dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
549 N_("Wrote %1 FULL, %2 FAKE, %3 pushed to disk"), _full_written, _fake_written, _pushed_to_disk
554 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
556 /* Read the frame info as written */
557 FILE* file = fopen_boost (_film->info_file (), "rb");
559 LOG_GENERAL ("Existing frame %1 has no info file", f);
563 dcp::FrameInfo info = read_frame_info (file, f, eyes);
565 if (info.size == 0) {
566 LOG_GENERAL ("Existing frame %1 has no info file", f);
570 /* Read the data from the MXF and hash it */
571 dcpomatic_fseek (mxf, info.offset, SEEK_SET);
572 EncodedData data (info.size);
573 size_t const read = fread (data.data(), 1, data.size(), mxf);
574 if (read != static_cast<size_t> (data.size ())) {
575 LOG_GENERAL ("Existing frame %1 is incomplete", f);
579 MD5Digester digester;
580 digester.add (data.data(), data.size());
581 if (digester.get() != info.hash) {
582 LOG_GENERAL ("Existing frame %1 failed hash check", f);
590 Writer::check_existing_picture_mxf ()
592 /* Try to open the existing MXF */
593 FILE* mxf = fopen_boost (_picture_mxf->file(), "rb");
595 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", _picture_mxf->file().string(), errno);
601 shared_ptr<Job> job = _job.lock ();
602 DCPOMATIC_ASSERT (job);
604 job->set_progress_unknown ();
606 if (_film->three_d ()) {
607 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
610 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
614 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
619 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
620 ++_first_nonexistant_frame;
626 /** @param frame Frame index.
627 * @return true if we can fake-write this frame.
630 Writer::can_fake_write (int frame) const
632 /* We have to do a proper write of the first frame so that we can set up the JPEG2000
633 parameters in the MXF writer.
635 return (frame != 0 && frame < _first_nonexistant_frame);
639 Writer::write (PlayerSubtitles subs)
641 if (subs.text.empty ()) {
645 if (!_subtitle_content) {
646 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), _film->subtitle_language ()));
649 for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
650 _subtitle_content->add (*i);
655 Writer::write (list<shared_ptr<Font> > fonts)
657 if (fonts.empty ()) {
661 if (!_subtitle_content) {
662 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), _film->subtitle_language ()));
665 for (list<shared_ptr<Font> >::const_iterator i = fonts.begin(); i != fonts.end(); ++i) {
666 /* XXX: this LiberationSans-Regular needs to be a path to a DCP-o-matic-distributed copy */
667 _subtitle_content->add_font ((*i)->id, (*i)->file.get_value_or ("LiberationSans-Regular.ttf").leaf().string ());
672 operator< (QueueItem const & a, QueueItem const & b)
674 if (a.frame != b.frame) {
675 return a.frame < b.frame;
678 return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
682 operator== (QueueItem const & a, QueueItem const & b)
684 return a.frame == b.frame && a.eyes == b.eyes;
688 Writer::maximum_frames_in_memory () const
690 return Config::instance()->num_local_encoding_threads() + 4;