2 Copyright (C) 2012-2014 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 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
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 job->sub (_("Checking existing image data"));
96 check_existing_picture_mxf ();
98 /* Create our picture asset in a subdirectory, named according to those
99 film's parameters which affect the video output. We will hard-link
100 it into the DCP later.
103 if (_film->three_d ()) {
104 _picture_mxf.reset (new dcp::StereoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
106 _picture_mxf.reset (new dcp::MonoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
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* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
194 throw ReadFileError (_film->info_path (frame, eyes));
196 dcp::FrameInfo info (ifi);
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;
442 video_from /= _film->internal_video_mxf_dir();
443 video_from /= _film->internal_video_mxf_filename();
445 boost::filesystem::path video_to;
446 video_to /= _film->dir (_film->dcp_name());
447 video_to /= _film->video_mxf_filename ();
449 boost::system::error_code ec;
450 boost::filesystem::create_hard_link (video_from, video_to, ec);
452 LOG_WARNING_NC ("Hard-link failed; copying instead");
453 boost::filesystem::copy_file (video_from, video_to, ec);
455 LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
456 throw FileError (ec.message(), video_from);
460 _picture_mxf->set_file (video_to);
462 /* Move the audio MXF into the DCP */
465 boost::filesystem::path audio_to;
466 audio_to /= _film->dir (_film->dcp_name ());
467 audio_to /= _film->audio_mxf_filename ();
469 boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
472 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
476 _sound_mxf->set_file (audio_to);
479 dcp::DCP dcp (_film->dir (_film->dcp_name()));
481 shared_ptr<dcp::CPL> cpl (
484 _film->dcp_content_type()->libdcp_kind ()
490 shared_ptr<dcp::Reel> reel (new dcp::Reel ());
492 shared_ptr<dcp::MonoPictureMXF> mono = dynamic_pointer_cast<dcp::MonoPictureMXF> (_picture_mxf);
494 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
498 shared_ptr<dcp::StereoPictureMXF> stereo = dynamic_pointer_cast<dcp::StereoPictureMXF> (_picture_mxf);
500 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
505 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_mxf, 0)));
506 dcp.add (_sound_mxf);
509 if (_subtitle_content) {
510 _subtitle_content->write_xml (_film->dir (_film->dcp_name ()) / _film->subtitle_xml_filename ());
511 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
512 new dcp::ReelSubtitleAsset (
514 dcp::Fraction (_film->video_frame_rate(), 1),
515 _picture_mxf->intrinsic_duration (),
520 dcp.add (_subtitle_content);
525 shared_ptr<Job> job = _job.lock ();
526 DCPOMATIC_ASSERT (job);
528 job->sub (_("Computing image digest"));
529 _picture_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
532 job->sub (_("Computing audio digest"));
533 _sound_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
536 dcp::XMLMetadata meta;
537 meta.issuer = Config::instance()->dcp_issuer ();
538 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
539 meta.set_issue_date_now ();
541 shared_ptr<const dcp::Signer> signer;
542 if (_film->is_signed ()) {
543 signer = Config::instance()->signer ();
544 /* We did check earlier, but check again here to be on the safe side */
545 if (!signer->valid ()) {
546 throw InvalidSignerError ();
550 dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
553 N_("Wrote %1 FULL, %2 FAKE, %3 pushed to disk"), _full_written, _fake_written, _pushed_to_disk
558 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
560 /* Read the frame info as written */
561 FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
563 LOG_GENERAL ("Existing frame %1 has no info file", f);
567 dcp::FrameInfo info (ifi);
569 if (info.size == 0) {
570 LOG_GENERAL ("Existing frame %1 has no info file", f);
574 /* Read the data from the MXF and hash it */
575 dcpomatic_fseek (mxf, info.offset, SEEK_SET);
576 EncodedData data (info.size);
577 size_t const read = fread (data.data(), 1, data.size(), mxf);
578 if (read != static_cast<size_t> (data.size ())) {
579 LOG_GENERAL ("Existing frame %1 is incomplete", f);
583 MD5Digester digester;
584 digester.add (data.data(), data.size());
585 if (digester.get() != info.hash) {
586 LOG_GENERAL ("Existing frame %1 failed hash check", f);
594 Writer::check_existing_picture_mxf ()
596 /* Try to open the existing MXF */
597 boost::filesystem::path p;
598 p /= _film->internal_video_mxf_dir ();
599 p /= _film->internal_video_mxf_filename ();
600 FILE* mxf = fopen_boost (p, "rb");
602 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno);
607 for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
613 shared_ptr<Job> job = _job.lock ();
614 DCPOMATIC_ASSERT (job);
617 job->set_progress (float (_first_nonexistant_frame) / N);
620 if (_film->three_d ()) {
621 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
624 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
628 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
633 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
634 ++_first_nonexistant_frame;
640 /** @param frame Frame index.
641 * @return true if we can fake-write this frame.
644 Writer::can_fake_write (int frame) const
646 /* We have to do a proper write of the first frame so that we can set up the JPEG2000
647 parameters in the MXF writer.
649 return (frame != 0 && frame < _first_nonexistant_frame);
653 Writer::write (PlayerSubtitles subs)
655 if (subs.text.empty ()) {
659 if (!_subtitle_content) {
660 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), _film->subtitle_language ()));
663 for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
664 _subtitle_content->add (*i);
669 Writer::write (list<shared_ptr<Font> > fonts)
671 if (fonts.empty ()) {
675 if (!_subtitle_content) {
676 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), _film->subtitle_language ()));
679 for (list<shared_ptr<Font> >::const_iterator i = fonts.begin(); i != fonts.end(); ++i) {
680 /* XXX: this LiberationSans-Regular needs to be a path to a DCP-o-matic-distributed copy */
681 _subtitle_content->add_font ((*i)->id, (*i)->file.get_value_or ("LiberationSans-Regular.ttf").leaf().string ());
686 operator< (QueueItem const & a, QueueItem const & b)
688 if (a.frame != b.frame) {
689 return a.frame < b.frame;
692 return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
696 operator== (QueueItem const & a, QueueItem const & b)
698 return a.frame == b.frame && a.eyes == b.eyes;