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_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
59 /* OS X strikes again */
67 using boost::shared_ptr;
68 using boost::weak_ptr;
69 using boost::dynamic_pointer_cast;
71 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
73 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
76 , _first_nonexistant_frame (0)
79 , _queued_full_in_memory (0)
80 , _last_written_frame (-1)
81 , _last_written_eyes (EYES_RIGHT)
86 /* Remove any old DCP */
87 boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
89 shared_ptr<Job> job = _job.lock ();
90 DCPOMATIC_ASSERT (job);
92 job->sub (_("Checking existing image data"));
93 check_existing_picture_mxf ();
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 _picture_mxf->set_size (_film->frame_size ());
108 if (_film->encrypted ()) {
109 _picture_mxf->set_key (_film->key ());
112 _picture_mxf_writer = _picture_mxf->start_write (
113 _film->internal_video_mxf_dir() / _film->internal_video_mxf_filename(),
114 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
115 _first_nonexistant_frame > 0
118 if (_film->audio_channels ()) {
119 _sound_mxf.reset (new dcp::SoundMXF (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ()));
121 if (_film->encrypted ()) {
122 _sound_mxf->set_key (_film->key ());
125 /* Write the sound MXF into the film directory so that we leave the creation
126 of the DCP directory until the last minute.
128 _sound_mxf_writer = _sound_mxf->start_write (_film->directory() / _film->audio_mxf_filename(), _film->interop() ? dcp::INTEROP : dcp::SMPTE);
131 /* Check that the signer is OK if we need one */
132 if (_film->is_signed() && !Config::instance()->signer()->valid ()) {
133 throw InvalidSignerError ();
136 _thread = new boost::thread (boost::bind (&Writer::thread, this));
138 job->sub (_("Encoding image data"));
143 terminate_thread (false);
147 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
149 boost::mutex::scoped_lock lock (_mutex);
151 while (_queued_full_in_memory > _maximum_frames_in_memory) {
152 /* The queue is too big; wait until that is sorted out */
153 _full_condition.wait (lock);
157 qi.type = QueueItem::FULL;
158 qi.encoded = encoded;
161 if (_film->three_d() && eyes == EYES_BOTH) {
162 /* 2D material in a 3D DCP; fake the 3D */
164 _queue.push_back (qi);
165 ++_queued_full_in_memory;
166 qi.eyes = EYES_RIGHT;
167 _queue.push_back (qi);
168 ++_queued_full_in_memory;
171 _queue.push_back (qi);
172 ++_queued_full_in_memory;
175 /* Now there's something to do: wake anything wait()ing on _empty_condition */
176 _empty_condition.notify_all ();
180 Writer::fake_write (int frame, Eyes eyes)
182 boost::mutex::scoped_lock lock (_mutex);
184 while (_queued_full_in_memory > _maximum_frames_in_memory) {
185 /* The queue is too big; wait until that is sorted out */
186 _full_condition.wait (lock);
189 FILE* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
190 dcp::FrameInfo info (ifi);
194 qi.type = QueueItem::FAKE;
197 if (_film->three_d() && eyes == EYES_BOTH) {
199 _queue.push_back (qi);
200 qi.eyes = EYES_RIGHT;
201 _queue.push_back (qi);
204 _queue.push_back (qi);
207 /* Now there's something to do: wake anything wait()ing on _empty_condition */
208 _empty_condition.notify_all ();
211 /** This method is not thread safe */
213 Writer::write (shared_ptr<const AudioBuffers> audio)
215 if (_sound_mxf_writer) {
216 _sound_mxf_writer->write (audio->data(), audio->frames());
220 /** This must be called from Writer::thread() with an appropriate lock held */
222 Writer::have_sequenced_image_at_queue_head ()
224 if (_queue.empty ()) {
230 /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
232 if (_queue.front().eyes == EYES_BOTH) {
234 return _queue.front().frame == (_last_written_frame + 1);
239 if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
243 if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
256 boost::mutex::scoped_lock lock (_mutex);
260 if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
261 /* We've got something to do: go and do it */
265 /* Nothing to do: wait until something happens which may indicate that we do */
266 LOG_TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
267 _empty_condition.wait (lock);
268 LOG_TIMING (N_("writer wakes with a queue of %1"), _queue.size());
271 if (_finish && _queue.empty()) {
275 /* Write any frames that we can write; i.e. those that are in sequence. */
276 while (have_sequenced_image_at_queue_head ()) {
277 QueueItem qi = _queue.front ();
279 if (qi.type == QueueItem::FULL && qi.encoded) {
280 --_queued_full_in_memory;
285 case QueueItem::FULL:
287 LOG_GENERAL (N_("Writer FULL-writes %1 to MXF"), qi.frame);
289 qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
292 dcp::FrameInfo fin = _picture_mxf_writer->write (qi.encoded->data(), qi.encoded->size());
293 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
294 _last_written[qi.eyes] = qi.encoded;
298 case QueueItem::FAKE:
299 LOG_GENERAL (N_("Writer FAKE-writes %1 to MXF"), qi.frame);
300 _picture_mxf_writer->fake_write (qi.size);
301 _last_written[qi.eyes].reset ();
307 _last_written_frame = qi.frame;
308 _last_written_eyes = qi.eyes;
310 shared_ptr<Job> job = _job.lock ();
311 DCPOMATIC_ASSERT (job);
312 int64_t total = _film->length().frames (_film->video_frame_rate ());
313 if (_film->three_d ()) {
314 /* _full_written and so on are incremented for each eye, so we need to double the total
315 frames to get the correct progress.
320 job->set_progress (float (_full_written + _fake_written) / total);
324 while (_queued_full_in_memory > _maximum_frames_in_memory) {
325 /* Too many frames in memory which can't yet be written to the stream.
326 Write some FULL frames to disk.
329 /* Find one from the back of the queue */
331 list<QueueItem>::reverse_iterator i = _queue.rbegin ();
332 while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
336 DCPOMATIC_ASSERT (i != _queue.rend());
344 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
345 _last_written_frame + 1,
346 _last_written_eyes, qi.frame
349 qi.encoded->write (_film, qi.frame, qi.eyes);
352 --_queued_full_in_memory;
355 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
356 _full_condition.notify_all ();
365 Writer::terminate_thread (bool can_throw)
367 boost::mutex::scoped_lock lock (_mutex);
373 _empty_condition.notify_all ();
374 _full_condition.notify_all ();
393 terminate_thread (true);
395 _picture_mxf_writer->finalize ();
396 if (_sound_mxf_writer) {
397 _sound_mxf_writer->finalize ();
400 /* Hard-link the video MXF into the DCP */
401 boost::filesystem::path video_from;
402 video_from /= _film->internal_video_mxf_dir();
403 video_from /= _film->internal_video_mxf_filename();
405 boost::filesystem::path video_to;
406 video_to /= _film->dir (_film->dcp_name());
407 video_to /= _film->video_mxf_filename ();
409 boost::system::error_code ec;
410 boost::filesystem::create_hard_link (video_from, video_to, ec);
412 LOG_WARNING_NC ("Hard-link failed; copying instead");
413 boost::filesystem::copy_file (video_from, video_to, ec);
415 LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
416 throw FileError (ec.message(), video_from);
420 _picture_mxf->set_file (video_to);
422 /* Move the audio MXF into the DCP */
425 boost::filesystem::path audio_to;
426 audio_to /= _film->dir (_film->dcp_name ());
427 audio_to /= _film->audio_mxf_filename ();
429 boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
432 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
436 _sound_mxf->set_file (audio_to);
439 dcp::DCP dcp (_film->dir (_film->dcp_name()));
441 shared_ptr<dcp::CPL> cpl (
444 _film->dcp_content_type()->libdcp_kind ()
450 shared_ptr<dcp::Reel> reel (new dcp::Reel ());
452 shared_ptr<dcp::MonoPictureMXF> mono = dynamic_pointer_cast<dcp::MonoPictureMXF> (_picture_mxf);
454 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
458 shared_ptr<dcp::StereoPictureMXF> stereo = dynamic_pointer_cast<dcp::StereoPictureMXF> (_picture_mxf);
460 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
465 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_mxf, 0)));
466 dcp.add (_sound_mxf);
469 if (_subtitle_content) {
470 _subtitle_content->write_xml (_film->dir (_film->dcp_name ()) / _film->subtitle_xml_filename ());
471 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
472 new dcp::ReelSubtitleAsset (
474 dcp::Fraction (_film->video_frame_rate(), 1),
475 _picture_mxf->intrinsic_duration (),
480 dcp.add (_subtitle_content);
485 shared_ptr<Job> job = _job.lock ();
486 DCPOMATIC_ASSERT (job);
488 job->sub (_("Computing image digest"));
489 _picture_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
492 job->sub (_("Computing audio digest"));
493 _sound_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
496 dcp::XMLMetadata meta;
497 meta.issuer = Config::instance()->dcp_issuer ();
498 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
499 meta.set_issue_date_now ();
501 shared_ptr<const dcp::Signer> signer;
502 if (_film->is_signed ()) {
503 signer = Config::instance()->signer ();
504 /* We did check earlier, but check again here to be on the safe side */
505 if (!signer->valid ()) {
506 throw InvalidSignerError ();
510 dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
513 N_("Wrote %1 FULL, %2 FAKE, %3 pushed to disk"), _full_written, _fake_written, _pushed_to_disk
518 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
520 /* Read the frame info as written */
521 FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
523 LOG_GENERAL ("Existing frame %1 has no info file", f);
527 dcp::FrameInfo info (ifi);
529 if (info.size == 0) {
530 LOG_GENERAL ("Existing frame %1 has no info file", f);
534 /* Read the data from the MXF and hash it */
535 dcpomatic_fseek (mxf, info.offset, SEEK_SET);
536 EncodedData data (info.size);
537 size_t const read = fread (data.data(), 1, data.size(), mxf);
538 if (read != static_cast<size_t> (data.size ())) {
539 LOG_GENERAL ("Existing frame %1 is incomplete", f);
543 MD5Digester digester;
544 digester.add (data.data(), data.size());
545 if (digester.get() != info.hash) {
546 LOG_GENERAL ("Existing frame %1 failed hash check", f);
554 Writer::check_existing_picture_mxf ()
556 /* Try to open the existing MXF */
557 boost::filesystem::path p;
558 p /= _film->internal_video_mxf_dir ();
559 p /= _film->internal_video_mxf_filename ();
560 FILE* mxf = fopen_boost (p, "rb");
562 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno);
567 for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
573 shared_ptr<Job> job = _job.lock ();
574 DCPOMATIC_ASSERT (job);
577 job->set_progress (float (_first_nonexistant_frame) / N);
580 if (_film->three_d ()) {
581 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
584 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
588 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
593 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
594 ++_first_nonexistant_frame;
600 /** @param frame Frame index.
601 * @return true if we can fake-write this frame.
604 Writer::can_fake_write (int frame) const
606 /* We have to do a proper write of the first frame so that we can set up the JPEG2000
607 parameters in the MXF writer.
609 return (frame != 0 && frame < _first_nonexistant_frame);
613 Writer::write (PlayerSubtitles subs)
615 if (subs.text.empty ()) {
619 if (!_subtitle_content) {
620 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), _film->subtitle_language ()));
623 for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
624 _subtitle_content->add (*i);
629 Writer::write (list<shared_ptr<Font> > fonts)
631 if (fonts.empty ()) {
635 if (!_subtitle_content) {
636 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), _film->subtitle_language ()));
639 for (list<shared_ptr<Font> >::const_iterator i = fonts.begin(); i != fonts.end(); ++i) {
640 /* XXX: this LiberationSans-Regular needs to be a path to a DCP-o-matic-distributed copy */
641 _subtitle_content->add_font ((*i)->id, (*i)->file.get_value_or ("LiberationSans-Regular.ttf").leaf().string ());
646 operator< (QueueItem const & a, QueueItem const & b)
648 if (a.frame != b.frame) {
649 return a.frame < b.frame;
652 return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
656 operator== (QueueItem const & a, QueueItem const & b)
658 return a.frame == b.frame && a.eyes == b.eyes;