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.
22 #include <libdcp/mono_picture_asset.h>
23 #include <libdcp/stereo_picture_asset.h>
24 #include <libdcp/sound_asset.h>
25 #include <libdcp/reel.h>
26 #include <libdcp/dcp.h>
27 #include <libdcp/cpl.h>
29 #include "compose.hpp"
33 #include "dcp_video_frame.h"
34 #include "dcp_content_type.h"
36 #include "audio_mapping.h"
40 #include "md5_digester.h"
45 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
46 #define LOG_TIMING(...) _film->log()->microsecond_log (String::compose (__VA_ARGS__), Log::TYPE_TIMING);
47 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_WARNING);
49 /* OS X strikes again */
57 using boost::shared_ptr;
58 using boost::weak_ptr;
60 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
62 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
65 , _first_nonexistant_frame (0)
68 , _queued_full_in_memory (0)
69 , _last_written_frame (-1)
70 , _last_written_eyes (EYES_RIGHT)
76 /* Remove any old DCP */
77 boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
79 shared_ptr<Job> job = _job.lock ();
82 job->sub (_("Checking existing image data"));
83 check_existing_picture_mxf ();
85 /* Create our picture asset in a subdirectory, named according to those
86 film's parameters which affect the video output. We will hard-link
87 it into the DCP later.
90 if (_film->three_d ()) {
91 _picture_asset.reset (new libdcp::StereoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
93 _picture_asset.reset (new libdcp::MonoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
96 _picture_asset->set_edit_rate (_film->video_frame_rate ());
97 _picture_asset->set_size (_film->frame_size ());
98 _picture_asset->set_interop (_film->interop ());
100 if (_film->encrypted ()) {
101 _picture_asset->set_key (_film->key ());
104 _picture_asset_writer = _picture_asset->start_write (_first_nonexistant_frame > 0);
106 if (_film->audio_channels ()) {
107 _sound_asset.reset (new libdcp::SoundAsset (_film->directory (), _film->audio_mxf_filename ()));
108 _sound_asset->set_edit_rate (_film->video_frame_rate ());
109 _sound_asset->set_channels (_film->audio_channels ());
110 _sound_asset->set_sampling_rate (_film->audio_frame_rate ());
111 _sound_asset->set_interop (_film->interop ());
113 if (_film->encrypted ()) {
114 _sound_asset->set_key (_film->key ());
117 /* Write the sound asset into the film directory so that we leave the creation
118 of the DCP directory until the last minute.
120 _sound_asset_writer = _sound_asset->start_write ();
123 _thread = new boost::thread (boost::bind (&Writer::thread, this));
125 job->sub (_("Encoding image data"));
130 terminate_thread (false);
134 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
136 boost::mutex::scoped_lock lock (_mutex);
138 while (_queued_full_in_memory > _maximum_frames_in_memory) {
139 /* The queue is too big; wait until that is sorted out */
140 _full_condition.wait (lock);
144 qi.type = QueueItem::FULL;
145 qi.encoded = encoded;
148 if (_film->three_d() && eyes == EYES_BOTH) {
149 /* 2D material in a 3D DCP; fake the 3D */
151 _queue.push_back (qi);
152 ++_queued_full_in_memory;
153 qi.eyes = EYES_RIGHT;
154 _queue.push_back (qi);
155 ++_queued_full_in_memory;
158 _queue.push_back (qi);
159 ++_queued_full_in_memory;
162 /* Now there's something to do: wake anything wait()ing on _empty_condition */
163 _empty_condition.notify_all ();
167 Writer::fake_write (int frame, Eyes eyes)
169 boost::mutex::scoped_lock lock (_mutex);
171 while (_queued_full_in_memory > _maximum_frames_in_memory) {
172 /* The queue is too big; wait until that is sorted out */
173 _full_condition.wait (lock);
176 FILE* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
177 libdcp::FrameInfo info (ifi);
181 qi.type = QueueItem::FAKE;
184 if (_film->three_d() && eyes == EYES_BOTH) {
186 _queue.push_back (qi);
187 qi.eyes = EYES_RIGHT;
188 _queue.push_back (qi);
191 _queue.push_back (qi);
194 /* Now there's something to do: wake anything wait()ing on _empty_condition */
195 _empty_condition.notify_all ();
198 /** This method is not thread safe */
200 Writer::write (shared_ptr<const AudioBuffers> audio)
203 _sound_asset_writer->write (audio->data(), audio->frames());
207 /** This must be called from Writer::thread() with an appropriate lock held */
209 Writer::have_sequenced_image_at_queue_head ()
211 if (_queue.empty ()) {
217 /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
219 if (_queue.front().eyes == EYES_BOTH) {
221 return _queue.front().frame == (_last_written_frame + 1);
226 if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
230 if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
243 boost::mutex::scoped_lock lock (_mutex);
247 if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
248 /* We've got something to do: go and do it */
252 /* Nothing to do: wait until something happens which may indicate that we do */
253 LOG_TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
254 _empty_condition.wait (lock);
255 LOG_TIMING (N_("writer wakes with a queue of %1"), _queue.size());
258 if (_finish && _queue.empty()) {
262 /* Write any frames that we can write; i.e. those that are in sequence. */
263 while (have_sequenced_image_at_queue_head ()) {
264 QueueItem qi = _queue.front ();
266 if (qi.type == QueueItem::FULL && qi.encoded) {
267 --_queued_full_in_memory;
272 case QueueItem::FULL:
274 LOG_GENERAL (N_("Writer FULL-writes %1 to MXF"), qi.frame);
276 qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
279 libdcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size());
280 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
281 _last_written[qi.eyes] = qi.encoded;
285 case QueueItem::FAKE:
286 LOG_GENERAL (N_("Writer FAKE-writes %1 to MXF"), qi.frame);
287 _picture_asset_writer->fake_write (qi.size);
288 _last_written[qi.eyes].reset ();
291 case QueueItem::REPEAT:
293 LOG_GENERAL (N_("Writer REPEAT-writes %1 to MXF"), qi.frame);
294 libdcp::FrameInfo fin = _picture_asset_writer->write (
295 _last_written[qi.eyes]->data(),
296 _last_written[qi.eyes]->size()
299 _last_written[qi.eyes]->write_info (_film, qi.frame, qi.eyes, fin);
306 _last_written_frame = qi.frame;
307 _last_written_eyes = qi.eyes;
309 if (_film->length()) {
310 shared_ptr<Job> job = _job.lock ();
312 int total = _film->time_to_video_frames (_film->length ());
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.
319 job->set_progress (float (_full_written + _fake_written + _repeat_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_asset_writer->finalize ();
395 if (_sound_asset_writer) {
396 _sound_asset_writer->finalize ();
399 int const frames = _last_written_frame + 1;
401 _picture_asset->set_duration (frames);
403 /* Hard-link the video MXF into the DCP */
404 boost::filesystem::path video_from;
405 video_from /= _film->internal_video_mxf_dir();
406 video_from /= _film->internal_video_mxf_filename();
408 boost::filesystem::path video_to;
409 video_to /= _film->dir (_film->dcp_name());
410 video_to /= _film->video_mxf_filename ();
412 boost::system::error_code ec;
413 boost::filesystem::create_hard_link (video_from, video_to, ec);
415 /* hard link failed; copy instead */
416 boost::filesystem::copy_file (video_from, video_to);
417 LOG_WARNING_NC ("Hard-link failed; fell back to copying");
420 /* And update the asset */
422 _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
423 _picture_asset->set_file_name (_film->video_mxf_filename ());
425 /* Move the audio MXF into the DCP */
428 boost::filesystem::path audio_to;
429 audio_to /= _film->dir (_film->dcp_name ());
430 audio_to /= _film->audio_mxf_filename ();
432 boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
435 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
439 _sound_asset->set_directory (_film->dir (_film->dcp_name ()));
440 _sound_asset->set_duration (frames);
443 libdcp::DCP dcp (_film->dir (_film->dcp_name()));
445 shared_ptr<libdcp::CPL> cpl (
447 _film->dir (_film->dcp_name()),
449 _film->dcp_content_type()->libdcp_kind (),
451 _film->video_frame_rate ()
457 cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
460 shared_ptr<libdcp::SubtitleAsset> ()
464 shared_ptr<Job> job = _job.lock ();
467 job->sub (_("Computing image digest"));
468 _picture_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
471 job->sub (_("Computing audio digest"));
472 _sound_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
475 libdcp::XMLMetadata meta;
476 meta.issuer = Config::instance()->dcp_issuer ();
477 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
478 meta.set_issue_date_now ();
479 dcp.write_xml (_film->interop (), meta, _film->is_signed() ? make_signer () : shared_ptr<const libdcp::Signer> ());
482 N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT; %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk
486 /** Tell the writer that frame `f' should be a repeat of the frame before it */
488 Writer::repeat (int f, Eyes e)
490 boost::mutex::scoped_lock lock (_mutex);
492 while (_queued_full_in_memory > _maximum_frames_in_memory) {
493 /* The queue is too big; wait until that is sorted out */
494 _full_condition.wait (lock);
498 qi.type = QueueItem::REPEAT;
500 if (_film->three_d() && e == EYES_BOTH) {
502 _queue.push_back (qi);
503 qi.eyes = EYES_RIGHT;
504 _queue.push_back (qi);
507 _queue.push_back (qi);
510 /* Now there's something to do: wake anything wait()ing on _empty_condition */
511 _empty_condition.notify_all ();
515 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
517 /* Read the frame info as written */
518 FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
520 LOG_GENERAL ("Existing frame %1 has no info file", f);
524 libdcp::FrameInfo info (ifi);
526 if (info.size == 0) {
527 LOG_GENERAL ("Existing frame %1 has no info file", f);
531 /* Read the data from the MXF and hash it */
532 dcpomatic_fseek (mxf, info.offset, SEEK_SET);
533 EncodedData data (info.size);
534 size_t const read = fread (data.data(), 1, data.size(), mxf);
535 if (read != static_cast<size_t> (data.size ())) {
536 LOG_GENERAL ("Existing frame %1 is incomplete", f);
540 MD5Digester digester;
541 digester.add (data.data(), data.size());
542 if (digester.get() != info.hash) {
543 LOG_GENERAL ("Existing frame %1 failed hash check", f);
551 Writer::check_existing_picture_mxf ()
553 /* Try to open the existing MXF */
554 boost::filesystem::path p;
555 p /= _film->internal_video_mxf_dir ();
556 p /= _film->internal_video_mxf_filename ();
557 FILE* mxf = fopen_boost (p, "rb");
559 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno);
564 for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
570 shared_ptr<Job> job = _job.lock ();
574 job->set_progress (float (_first_nonexistant_frame) / N);
577 if (_film->three_d ()) {
578 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
581 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
585 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
590 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
591 ++_first_nonexistant_frame;
597 /** @param frame Frame index.
598 * @return true if we can fake-write this frame.
601 Writer::can_fake_write (int frame) const
603 /* We have to do a proper write of the first frame so that we can set up the JPEG2000
604 parameters in the MXF writer.
606 return (frame != 0 && frame < _first_nonexistant_frame);
610 operator< (QueueItem const & a, QueueItem const & b)
612 if (a.frame != b.frame) {
613 return a.frame < b.frame;
616 return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
620 operator== (QueueItem const & a, QueueItem const & b)
622 return a.frame == b.frame && a.eyes == b.eyes;