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);
48 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
50 /* OS X strikes again */
58 using boost::shared_ptr;
59 using boost::weak_ptr;
61 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
63 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
66 , _first_nonexistant_frame (0)
69 , _queued_full_in_memory (0)
70 , _last_written_frame (-1)
71 , _last_written_eyes (EYES_RIGHT)
77 /* Remove any old DCP */
78 boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
80 shared_ptr<Job> job = _job.lock ();
83 job->sub (_("Checking existing image data"));
84 check_existing_picture_mxf ();
86 /* Create our picture asset in a subdirectory, named according to those
87 film's parameters which affect the video output. We will hard-link
88 it into the DCP later.
91 if (_film->three_d ()) {
92 _picture_asset.reset (new libdcp::StereoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
94 _picture_asset.reset (new libdcp::MonoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
97 _picture_asset->set_edit_rate (_film->video_frame_rate ());
98 _picture_asset->set_size (_film->frame_size ());
99 _picture_asset->set_interop (_film->interop ());
101 if (_film->encrypted ()) {
102 _picture_asset->set_key (_film->key ());
105 _picture_asset_writer = _picture_asset->start_write (_first_nonexistant_frame > 0);
107 if (_film->audio_channels ()) {
108 _sound_asset.reset (new libdcp::SoundAsset (_film->directory (), _film->audio_mxf_filename ()));
109 _sound_asset->set_edit_rate (_film->video_frame_rate ());
110 _sound_asset->set_channels (_film->audio_channels ());
111 _sound_asset->set_sampling_rate (_film->audio_frame_rate ());
112 _sound_asset->set_interop (_film->interop ());
114 if (_film->encrypted ()) {
115 _sound_asset->set_key (_film->key ());
118 /* Write the sound asset into the film directory so that we leave the creation
119 of the DCP directory until the last minute.
121 _sound_asset_writer = _sound_asset->start_write ();
124 _thread = new boost::thread (boost::bind (&Writer::thread, this));
126 job->sub (_("Encoding image data"));
131 terminate_thread (false);
135 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
137 boost::mutex::scoped_lock lock (_mutex);
139 while (_queued_full_in_memory > _maximum_frames_in_memory) {
140 /* The queue is too big; wait until that is sorted out */
141 _full_condition.wait (lock);
145 qi.type = QueueItem::FULL;
146 qi.encoded = encoded;
149 if (_film->three_d() && eyes == EYES_BOTH) {
150 /* 2D material in a 3D DCP; fake the 3D */
152 _queue.push_back (qi);
153 ++_queued_full_in_memory;
154 qi.eyes = EYES_RIGHT;
155 _queue.push_back (qi);
156 ++_queued_full_in_memory;
159 _queue.push_back (qi);
160 ++_queued_full_in_memory;
163 /* Now there's something to do: wake anything wait()ing on _empty_condition */
164 _empty_condition.notify_all ();
168 Writer::fake_write (int frame, Eyes eyes)
170 boost::mutex::scoped_lock lock (_mutex);
172 while (_queued_full_in_memory > _maximum_frames_in_memory) {
173 /* The queue is too big; wait until that is sorted out */
174 _full_condition.wait (lock);
177 FILE* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
178 libdcp::FrameInfo info (ifi);
182 qi.type = QueueItem::FAKE;
185 if (_film->three_d() && eyes == EYES_BOTH) {
187 _queue.push_back (qi);
188 qi.eyes = EYES_RIGHT;
189 _queue.push_back (qi);
192 _queue.push_back (qi);
195 /* Now there's something to do: wake anything wait()ing on _empty_condition */
196 _empty_condition.notify_all ();
199 /** This method is not thread safe */
201 Writer::write (shared_ptr<const AudioBuffers> audio)
204 _sound_asset_writer->write (audio->data(), audio->frames());
208 /** This must be called from Writer::thread() with an appropriate lock held */
210 Writer::have_sequenced_image_at_queue_head ()
212 if (_queue.empty ()) {
218 /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
220 if (_queue.front().eyes == EYES_BOTH) {
222 return _queue.front().frame == (_last_written_frame + 1);
227 if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
231 if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
244 boost::mutex::scoped_lock lock (_mutex);
248 if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
249 /* We've got something to do: go and do it */
253 /* Nothing to do: wait until something happens which may indicate that we do */
254 LOG_TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
255 _empty_condition.wait (lock);
256 LOG_TIMING (N_("writer wakes with a queue of %1"), _queue.size());
259 if (_finish && _queue.empty()) {
263 /* Write any frames that we can write; i.e. those that are in sequence. */
264 while (have_sequenced_image_at_queue_head ()) {
265 QueueItem qi = _queue.front ();
267 if (qi.type == QueueItem::FULL && qi.encoded) {
268 --_queued_full_in_memory;
273 case QueueItem::FULL:
275 LOG_GENERAL (N_("Writer FULL-writes %1 to MXF"), qi.frame);
277 qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
280 libdcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size());
281 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
282 _last_written[qi.eyes] = qi.encoded;
286 case QueueItem::FAKE:
287 LOG_GENERAL (N_("Writer FAKE-writes %1 to MXF"), qi.frame);
288 _picture_asset_writer->fake_write (qi.size);
289 _last_written[qi.eyes].reset ();
292 case QueueItem::REPEAT:
294 LOG_GENERAL (N_("Writer REPEAT-writes %1 to MXF"), qi.frame);
295 libdcp::FrameInfo fin = _picture_asset_writer->write (
296 _last_written[qi.eyes]->data(),
297 _last_written[qi.eyes]->size()
300 _last_written[qi.eyes]->write_info (_film, qi.frame, qi.eyes, fin);
307 _last_written_frame = qi.frame;
308 _last_written_eyes = qi.eyes;
310 if (_film->length()) {
311 shared_ptr<Job> job = _job.lock ();
313 int total = _film->time_to_video_frames (_film->length ());
314 if (_film->three_d ()) {
315 /* _full_written and so on are incremented for each eye, so we need to double the total
316 frames to get the correct progress.
320 job->set_progress (float (_full_written + _fake_written + _repeat_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 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_asset_writer->finalize ();
396 if (_sound_asset_writer) {
397 _sound_asset_writer->finalize ();
400 int const frames = _last_written_frame + 1;
402 _picture_asset->set_duration (frames);
404 /* Hard-link the video MXF into the DCP */
405 boost::filesystem::path video_from;
406 video_from /= _film->internal_video_mxf_dir();
407 video_from /= _film->internal_video_mxf_filename();
409 boost::filesystem::path video_to;
410 video_to /= _film->dir (_film->dcp_name());
411 video_to /= _film->video_mxf_filename ();
413 boost::system::error_code ec;
414 boost::filesystem::create_hard_link (video_from, video_to, ec);
416 LOG_WARNING_NC ("Hard-link failed; copying instead");
417 boost::filesystem::copy_file (video_from, video_to, ec);
419 LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
420 throw FileError (ec.message(), video_from);
424 /* And update the asset */
426 _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
427 _picture_asset->set_file_name (_film->video_mxf_filename ());
429 /* Move the audio MXF into the DCP */
432 boost::filesystem::path audio_to;
433 audio_to /= _film->dir (_film->dcp_name ());
434 audio_to /= _film->audio_mxf_filename ();
436 boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
439 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
443 _sound_asset->set_directory (_film->dir (_film->dcp_name ()));
444 _sound_asset->set_duration (frames);
447 libdcp::DCP dcp (_film->dir (_film->dcp_name()));
449 shared_ptr<libdcp::CPL> cpl (
451 _film->dir (_film->dcp_name()),
453 _film->dcp_content_type()->libdcp_kind (),
455 _film->video_frame_rate ()
461 cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
464 shared_ptr<libdcp::SubtitleAsset> ()
468 shared_ptr<Job> job = _job.lock ();
471 job->sub (_("Computing image digest"));
472 _picture_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
475 job->sub (_("Computing audio digest"));
476 _sound_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
479 libdcp::XMLMetadata meta;
480 meta.issuer = Config::instance()->dcp_issuer ();
481 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
482 meta.set_issue_date_now ();
483 dcp.write_xml (_film->interop (), meta, _film->is_signed() ? make_signer () : shared_ptr<const libdcp::Signer> ());
486 N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT; %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk
490 /** Tell the writer that frame `f' should be a repeat of the frame before it */
492 Writer::repeat (int f, Eyes e)
494 boost::mutex::scoped_lock lock (_mutex);
496 while (_queued_full_in_memory > _maximum_frames_in_memory) {
497 /* The queue is too big; wait until that is sorted out */
498 _full_condition.wait (lock);
502 qi.type = QueueItem::REPEAT;
504 if (_film->three_d() && e == EYES_BOTH) {
506 _queue.push_back (qi);
507 qi.eyes = EYES_RIGHT;
508 _queue.push_back (qi);
511 _queue.push_back (qi);
514 /* Now there's something to do: wake anything wait()ing on _empty_condition */
515 _empty_condition.notify_all ();
519 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
521 /* Read the frame info as written */
522 FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
524 LOG_GENERAL ("Existing frame %1 has no info file", f);
528 libdcp::FrameInfo info (ifi);
530 if (info.size == 0) {
531 LOG_GENERAL ("Existing frame %1 has no info file", f);
535 /* Read the data from the MXF and hash it */
536 dcpomatic_fseek (mxf, info.offset, SEEK_SET);
537 EncodedData data (info.size);
538 size_t const read = fread (data.data(), 1, data.size(), mxf);
539 if (read != static_cast<size_t> (data.size ())) {
540 LOG_GENERAL ("Existing frame %1 is incomplete", f);
544 MD5Digester digester;
545 digester.add (data.data(), data.size());
546 if (digester.get() != info.hash) {
547 LOG_GENERAL ("Existing frame %1 failed hash check", f);
555 Writer::check_existing_picture_mxf ()
557 /* Try to open the existing MXF */
558 boost::filesystem::path p;
559 p /= _film->internal_video_mxf_dir ();
560 p /= _film->internal_video_mxf_filename ();
561 FILE* mxf = fopen_boost (p, "rb");
563 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno);
568 for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
574 shared_ptr<Job> job = _job.lock ();
578 job->set_progress (float (_first_nonexistant_frame) / N);
581 if (_film->three_d ()) {
582 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
585 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
589 if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
594 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
595 ++_first_nonexistant_frame;
601 /** @param frame Frame index.
602 * @return true if we can fake-write this frame.
605 Writer::can_fake_write (int frame) const
607 /* We have to do a proper write of the first frame so that we can set up the JPEG2000
608 parameters in the MXF writer.
610 return (frame != 0 && frame < _first_nonexistant_frame);
614 operator< (QueueItem const & a, QueueItem const & b)
616 if (a.frame != b.frame) {
617 return a.frame < b.frame;
620 return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
624 operator== (QueueItem const & a, QueueItem const & b)
626 return a.frame == b.frame && a.eyes == b.eyes;