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"
35 #include <dcp/mono_picture_mxf.h>
36 #include <dcp/stereo_picture_mxf.h>
37 #include <dcp/sound_mxf.h>
38 #include <dcp/sound_mxf_writer.h>
40 #include <dcp/reel_mono_picture_asset.h>
41 #include <dcp/reel_stereo_picture_asset.h>
42 #include <dcp/reel_sound_asset.h>
43 #include <dcp/reel_subtitle_asset.h>
46 #include <dcp/signer.h>
47 #include <dcp/interop_subtitle_content.h>
53 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
54 #define LOG_TIMING(...) _film->log()->microsecond_log (String::compose (__VA_ARGS__), Log::TYPE_TIMING);
55 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_WARNING);
56 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
58 /* OS X strikes again */
66 using boost::shared_ptr;
67 using boost::weak_ptr;
68 using boost::dynamic_pointer_cast;
70 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
72 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
75 , _first_nonexistant_frame (0)
78 , _queued_full_in_memory (0)
79 , _last_written_frame (-1)
80 , _last_written_eyes (EYES_RIGHT)
85 /* Remove any old DCP */
86 boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
88 shared_ptr<Job> job = _job.lock ();
91 job->sub (_("Checking existing image data"));
92 check_existing_picture_mxf ();
94 /* Create our picture asset in a subdirectory, named according to those
95 film's parameters which affect the video output. We will hard-link
96 it into the DCP later.
99 if (_film->three_d ()) {
100 _picture_mxf.reset (new dcp::StereoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
102 _picture_mxf.reset (new dcp::MonoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
105 _picture_mxf->set_size (_film->frame_size ());
107 if (_film->encrypted ()) {
108 _picture_mxf->set_key (_film->key ());
111 _picture_mxf_writer = _picture_mxf->start_write (
112 _film->internal_video_mxf_dir() / _film->internal_video_mxf_filename(),
113 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
114 _first_nonexistant_frame > 0
117 if (_film->audio_channels ()) {
118 _sound_mxf.reset (new dcp::SoundMXF (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ()));
120 if (_film->encrypted ()) {
121 _sound_mxf->set_key (_film->key ());
124 /* Write the sound MXF into the film directory so that we leave the creation
125 of the DCP directory until the last minute.
127 _sound_mxf_writer = _sound_mxf->start_write (_film->directory() / _film->audio_mxf_filename(), _film->interop() ? dcp::INTEROP : dcp::SMPTE);
130 /* Check that the signer is OK if we need one */
131 if (_film->is_signed() && !Config::instance()->signer()->valid ()) {
132 throw InvalidSignerError ();
135 _thread = new boost::thread (boost::bind (&Writer::thread, this));
137 job->sub (_("Encoding image data"));
142 terminate_thread (false);
146 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
148 boost::mutex::scoped_lock lock (_mutex);
150 while (_queued_full_in_memory > _maximum_frames_in_memory) {
151 /* The queue is too big; wait until that is sorted out */
152 _full_condition.wait (lock);
156 qi.type = QueueItem::FULL;
157 qi.encoded = encoded;
160 if (_film->three_d() && eyes == EYES_BOTH) {
161 /* 2D material in a 3D DCP; fake the 3D */
163 _queue.push_back (qi);
164 ++_queued_full_in_memory;
165 qi.eyes = EYES_RIGHT;
166 _queue.push_back (qi);
167 ++_queued_full_in_memory;
170 _queue.push_back (qi);
171 ++_queued_full_in_memory;
174 /* Now there's something to do: wake anything wait()ing on _empty_condition */
175 _empty_condition.notify_all ();
179 Writer::fake_write (int frame, Eyes eyes)
181 boost::mutex::scoped_lock lock (_mutex);
183 while (_queued_full_in_memory > _maximum_frames_in_memory) {
184 /* The queue is too big; wait until that is sorted out */
185 _full_condition.wait (lock);
188 FILE* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
189 dcp::FrameInfo info (ifi);
193 qi.type = QueueItem::FAKE;
196 if (_film->three_d() && eyes == EYES_BOTH) {
198 _queue.push_back (qi);
199 qi.eyes = EYES_RIGHT;
200 _queue.push_back (qi);
203 _queue.push_back (qi);
206 /* Now there's something to do: wake anything wait()ing on _empty_condition */
207 _empty_condition.notify_all ();
210 /** This method is not thread safe */
212 Writer::write (shared_ptr<const AudioBuffers> audio)
214 if (_sound_mxf_writer) {
215 _sound_mxf_writer->write (audio->data(), audio->frames());
219 /** This must be called from Writer::thread() with an appropriate lock held */
221 Writer::have_sequenced_image_at_queue_head ()
223 if (_queue.empty ()) {
229 /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
231 if (_queue.front().eyes == EYES_BOTH) {
233 return _queue.front().frame == (_last_written_frame + 1);
238 if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
242 if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
255 boost::mutex::scoped_lock lock (_mutex);
259 if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
260 /* We've got something to do: go and do it */
264 /* Nothing to do: wait until something happens which may indicate that we do */
265 LOG_TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
266 _empty_condition.wait (lock);
267 LOG_TIMING (N_("writer wakes with a queue of %1"), _queue.size());
270 if (_finish && _queue.empty()) {
274 /* Write any frames that we can write; i.e. those that are in sequence. */
275 while (have_sequenced_image_at_queue_head ()) {
276 QueueItem qi = _queue.front ();
278 if (qi.type == QueueItem::FULL && qi.encoded) {
279 --_queued_full_in_memory;
284 case QueueItem::FULL:
286 LOG_GENERAL (N_("Writer FULL-writes %1 to MXF"), qi.frame);
288 qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
291 dcp::FrameInfo fin = _picture_mxf_writer->write (qi.encoded->data(), qi.encoded->size());
292 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
293 _last_written[qi.eyes] = qi.encoded;
297 case QueueItem::FAKE:
298 LOG_GENERAL (N_("Writer FAKE-writes %1 to MXF"), qi.frame);
299 _picture_mxf_writer->fake_write (qi.size);
300 _last_written[qi.eyes].reset ();
306 _last_written_frame = qi.frame;
307 _last_written_eyes = qi.eyes;
309 shared_ptr<Job> job = _job.lock ();
311 int64_t total = _film->length().frames (_film->video_frame_rate ());
312 if (_film->three_d ()) {
313 /* _full_written and so on are incremented for each eye, so we need to double the total
314 frames to get the correct progress.
319 job->set_progress (float (_full_written + _fake_written) / total);
323 while (_queued_full_in_memory > _maximum_frames_in_memory) {
324 /* Too many frames in memory which can't yet be written to the stream.
325 Write some FULL frames to disk.
328 /* Find one from the back of the queue */
330 list<QueueItem>::reverse_iterator i = _queue.rbegin ();
331 while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
335 assert (i != _queue.rend());
343 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
344 _last_written_frame + 1,
345 _last_written_eyes, qi.frame
348 qi.encoded->write (_film, qi.frame, qi.eyes);
351 --_queued_full_in_memory;
354 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
355 _full_condition.notify_all ();
364 Writer::terminate_thread (bool can_throw)
366 boost::mutex::scoped_lock lock (_mutex);
372 _empty_condition.notify_all ();
373 _full_condition.notify_all ();
392 terminate_thread (true);
394 _picture_mxf_writer->finalize ();
395 if (_sound_mxf_writer) {
396 _sound_mxf_writer->finalize ();
399 /* Hard-link the video MXF into the DCP */
400 boost::filesystem::path video_from;
401 video_from /= _film->internal_video_mxf_dir();
402 video_from /= _film->internal_video_mxf_filename();
404 boost::filesystem::path video_to;
405 video_to /= _film->dir (_film->dcp_name());
406 video_to /= _film->video_mxf_filename ();
408 boost::system::error_code ec;
409 boost::filesystem::create_hard_link (video_from, video_to, ec);
411 LOG_WARNING_NC ("Hard-link failed; copying instead");
412 boost::filesystem::copy_file (video_from, video_to, ec);
414 LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
415 throw FileError (ec.message(), video_from);
419 _picture_mxf->set_file (video_to);
421 /* Move the audio MXF into the DCP */
424 boost::filesystem::path audio_to;
425 audio_to /= _film->dir (_film->dcp_name ());
426 audio_to /= _film->audio_mxf_filename ();
428 boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
431 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
435 _sound_mxf->set_file (audio_to);
438 dcp::DCP dcp (_film->dir (_film->dcp_name()));
440 shared_ptr<dcp::CPL> cpl (
443 _film->dcp_content_type()->libdcp_kind ()
449 shared_ptr<dcp::Reel> reel (new dcp::Reel ());
451 shared_ptr<dcp::MonoPictureMXF> mono = dynamic_pointer_cast<dcp::MonoPictureMXF> (_picture_mxf);
453 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
457 shared_ptr<dcp::StereoPictureMXF> stereo = dynamic_pointer_cast<dcp::StereoPictureMXF> (_picture_mxf);
459 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
464 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_mxf, 0)));
465 dcp.add (_sound_mxf);
468 if (_subtitle_content) {
469 _subtitle_content->write_xml (_film->dir (_film->dcp_name ()) / _film->subtitle_xml_filename ());
470 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
471 new dcp::ReelSubtitleAsset (
473 dcp::Fraction (_film->video_frame_rate(), 1),
474 _picture_mxf->intrinsic_duration (),
479 dcp.add (_subtitle_content);
484 shared_ptr<Job> job = _job.lock ();
487 job->sub (_("Computing image digest"));
488 _picture_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
491 job->sub (_("Computing audio digest"));
492 _sound_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
495 dcp::XMLMetadata meta;
496 meta.issuer = Config::instance()->dcp_issuer ();
497 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
498 meta.set_issue_date_now ();
500 shared_ptr<const dcp::Signer> signer;
501 if (_film->is_signed ()) {
502 signer = Config::instance()->signer ();
503 /* We did check earlier, but check again here to be on the safe side */
504 if (!signer->valid ()) {
505 throw InvalidSignerError ();
509 dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
512 N_("Wrote %1 FULL, %2 FAKE, %3 pushed to disk"), _full_written, _fake_written, _pushed_to_disk
517 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
519 /* Read the frame info as written */
520 FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
522 LOG_GENERAL ("Existing frame %1 has no info file", f);
526 dcp::FrameInfo info (ifi);
528 if (info.size == 0) {
529 LOG_GENERAL ("Existing frame %1 has no info file", f);
533 /* Read the data from the MXF and hash it */
534 dcpomatic_fseek (mxf, info.offset, SEEK_SET);
535 EncodedData data (info.size);
536 size_t const read = fread (data.data(), 1, data.size(), mxf);
537 if (read != static_cast<size_t> (data.size ())) {
538 LOG_GENERAL ("Existing frame %1 is incomplete", f);
542 MD5Digester digester;
543 digester.add (data.data(), data.size());
544 if (digester.get() != info.hash) {
545 LOG_GENERAL ("Existing frame %1 failed hash check", f);
553 Writer::check_existing_picture_mxf ()
555 /* Try to open the existing MXF */
556 boost::filesystem::path p;
557 p /= _film->internal_video_mxf_dir ();
558 p /= _film->internal_video_mxf_filename ();
559 FILE* mxf = fopen_boost (p, "rb");
561 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno);
566 for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
572 shared_ptr<Job> job = _job.lock ();
576 job->set_progress (float (_first_nonexistant_frame) / N);
579 if (_film->three_d ()) {
580 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
583 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
587 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
592 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
593 ++_first_nonexistant_frame;
599 /** @param frame Frame index.
600 * @return true if we can fake-write this frame.
603 Writer::can_fake_write (int frame) const
605 /* We have to do a proper write of the first frame so that we can set up the JPEG2000
606 parameters in the MXF writer.
608 return (frame != 0 && frame < _first_nonexistant_frame);
612 Writer::write (PlayerSubtitles subs)
614 if (subs.text.empty ()) {
618 if (!_subtitle_content) {
619 _subtitle_content.reset (new dcp::InteropSubtitleContent (_film->name(), subs.language));
622 for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
623 _subtitle_content->add (*i);
628 operator< (QueueItem const & a, QueueItem const & b)
630 if (a.frame != b.frame) {
631 return a.frame < b.frame;
634 return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
638 operator== (QueueItem const & a, QueueItem const & b)
640 return a.frame == b.frame && a.eyes == b.eyes;