2 Copyright (C) 2012-2015 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"
37 #include <dcp/mono_picture_asset.h>
38 #include <dcp/stereo_picture_asset.h>
39 #include <dcp/sound_asset.h>
40 #include <dcp/sound_asset_writer.h>
42 #include <dcp/reel_mono_picture_asset.h>
43 #include <dcp/reel_stereo_picture_asset.h>
44 #include <dcp/reel_sound_asset.h>
45 #include <dcp/reel_subtitle_asset.h>
48 #include <dcp/certificate_chain.h>
49 #include <dcp/interop_subtitle_asset.h>
50 #include <dcp/smpte_subtitle_asset.h>
51 #include <boost/foreach.hpp>
58 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
59 #define LOG_GENERAL_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_GENERAL);
60 #define LOG_DEBUG_ENCODE(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_DEBUG_ENCODE);
61 #define LOG_TIMING(...) _film->log()->microsecond_log (String::compose (__VA_ARGS__), Log::TYPE_TIMING);
62 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_WARNING);
63 #define LOG_WARNING(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_WARNING);
64 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
66 /* OS X strikes again */
74 using boost::shared_ptr;
75 using boost::weak_ptr;
76 using boost::dynamic_pointer_cast;
78 int const Writer::_info_size = 48;
80 Writer::Writer (shared_ptr<const Film> film, weak_ptr<Job> j)
83 , _first_nonexistant_frame (0)
86 , _queued_full_in_memory (0)
87 , _last_written_frame (-1)
88 , _last_written_eyes (EYES_RIGHT)
89 , _maximum_frames_in_memory (0)
95 /* Remove any old DCP */
96 boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
98 shared_ptr<Job> job = _job.lock ();
99 DCPOMATIC_ASSERT (job);
101 /* Create our picture asset in a subdirectory, named according to those
102 film's parameters which affect the video output. We will hard-link
103 it into the DCP later.
106 if (_film->three_d ()) {
107 _picture_asset.reset (new dcp::StereoPictureAsset (dcp::Fraction (_film->video_frame_rate (), 1)));
109 _picture_asset.reset (new dcp::MonoPictureAsset (dcp::Fraction (_film->video_frame_rate (), 1)));
112 _picture_asset->set_size (_film->frame_size ());
114 if (_film->encrypted ()) {
115 _picture_asset->set_key (_film->key ());
118 _picture_asset->set_file (
119 _film->internal_video_asset_dir() / _film->internal_video_asset_filename()
122 job->sub (_("Checking existing image data"));
123 check_existing_picture_asset ();
125 _picture_asset_writer = _picture_asset->start_write (
126 _film->internal_video_asset_dir() / _film->internal_video_asset_filename(),
127 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
128 _first_nonexistant_frame > 0
131 if (_film->audio_channels ()) {
133 new dcp::SoundAsset (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ())
136 if (_film->encrypted ()) {
137 _sound_asset->set_key (_film->key ());
140 /* Write the sound asset into the film directory so that we leave the creation
141 of the DCP directory until the last minute.
143 _sound_asset_writer = _sound_asset->start_write (
144 _film->directory() / audio_asset_filename (_sound_asset),
145 _film->interop() ? dcp::INTEROP : dcp::SMPTE
149 /* Check that the signer is OK if we need one */
150 if (_film->is_signed() && !Config::instance()->signer_chain()->valid ()) {
151 throw InvalidSignerError ();
154 job->sub (_("Encoding image data"));
160 _thread = new boost::thread (boost::bind (&Writer::thread, this));
165 terminate_thread (false);
169 Writer::write (Data encoded, int frame, Eyes eyes)
171 boost::mutex::scoped_lock lock (_state_mutex);
173 while (_queued_full_in_memory > _maximum_frames_in_memory) {
174 /* The queue is too big; wait until that is sorted out */
175 _full_condition.wait (lock);
179 qi.type = QueueItem::FULL;
180 qi.encoded = encoded;
183 if (_film->three_d() && eyes == EYES_BOTH) {
184 /* 2D material in a 3D DCP; fake the 3D */
186 _queue.push_back (qi);
187 ++_queued_full_in_memory;
188 qi.eyes = EYES_RIGHT;
189 _queue.push_back (qi);
190 ++_queued_full_in_memory;
193 _queue.push_back (qi);
194 ++_queued_full_in_memory;
197 /* Now there's something to do: wake anything wait()ing on _empty_condition */
198 _empty_condition.notify_all ();
202 Writer::repeat (int frame, Eyes eyes)
204 boost::mutex::scoped_lock lock (_state_mutex);
206 while (_queued_full_in_memory > _maximum_frames_in_memory) {
207 /* The queue is too big; wait until that is sorted out */
208 _full_condition.wait (lock);
212 qi.type = QueueItem::REPEAT;
214 if (_film->three_d() && eyes == EYES_BOTH) {
216 _queue.push_back (qi);
217 qi.eyes = EYES_RIGHT;
218 _queue.push_back (qi);
221 _queue.push_back (qi);
224 /* Now there's something to do: wake anything wait()ing on _empty_condition */
225 _empty_condition.notify_all ();
229 Writer::fake_write (int frame, Eyes eyes)
231 boost::mutex::scoped_lock lock (_state_mutex);
233 while (_queued_full_in_memory > _maximum_frames_in_memory) {
234 /* The queue is too big; wait until that is sorted out */
235 _full_condition.wait (lock);
238 FILE* file = fopen_boost (_film->info_file (), "rb");
240 throw ReadFileError (_film->info_file ());
242 dcp::FrameInfo info = read_frame_info (file, frame, eyes);
246 qi.type = QueueItem::FAKE;
249 if (_film->three_d() && eyes == EYES_BOTH) {
251 _queue.push_back (qi);
252 qi.eyes = EYES_RIGHT;
253 _queue.push_back (qi);
256 _queue.push_back (qi);
259 /* Now there's something to do: wake anything wait()ing on _empty_condition */
260 _empty_condition.notify_all ();
263 /** This method is not thread safe */
265 Writer::write (shared_ptr<const AudioBuffers> audio)
267 if (_sound_asset_writer) {
268 _sound_asset_writer->write (audio->data(), audio->frames());
272 /** This must be called from Writer::thread() with an appropriate lock held */
274 Writer::have_sequenced_image_at_queue_head ()
276 if (_queue.empty ()) {
282 /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
284 if (_queue.front().eyes == EYES_BOTH) {
286 return _queue.front().frame == (_last_written_frame + 1);
291 if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
295 if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
303 Writer::write_frame_info (int frame, Eyes eyes, dcp::FrameInfo info) const
306 if (boost::filesystem::exists (_film->info_file ())) {
307 file = fopen_boost (_film->info_file(), "r+b");
309 file = fopen_boost (_film->info_file(), "wb");
312 throw OpenFileError (_film->info_file ());
314 dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
315 fwrite (&info.offset, sizeof (info.offset), 1, file);
316 fwrite (&info.size, sizeof (info.size), 1, file);
317 fwrite (info.hash.c_str(), 1, info.hash.size(), file);
327 boost::mutex::scoped_lock lock (_state_mutex);
331 if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
332 /* We've got something to do: go and do it */
336 /* Nothing to do: wait until something happens which may indicate that we do */
337 LOG_TIMING (N_("writer-sleep queue=%1"), _queue.size());
338 _empty_condition.wait (lock);
339 LOG_TIMING (N_("writer-wake queue=%1"), _queue.size());
342 if (_finish && _queue.empty()) {
346 /* We stop here if we have been asked to finish, and if either the queue
347 is empty or we do not have a sequenced image at its head (if this is the
348 case we will never terminate as no new frames will be sent once
351 if (_finish && (!have_sequenced_image_at_queue_head() || _queue.empty())) {
352 /* (Hopefully temporarily) log anything that was not written */
353 if (!_queue.empty() && !have_sequenced_image_at_queue_head()) {
354 LOG_WARNING (N_("Finishing writer with a left-over queue of %1:"), _queue.size());
355 for (list<QueueItem>::const_iterator i = _queue.begin(); i != _queue.end(); ++i) {
356 if (i->type == QueueItem::FULL) {
357 LOG_WARNING (N_("- type FULL, frame %1, eyes %2"), i->frame, i->eyes);
359 LOG_WARNING (N_("- type FAKE, size %1, frame %2, eyes %3"), i->size, i->frame, i->eyes);
362 LOG_WARNING (N_("Last written frame %1, last written eyes %2"), _last_written_frame, _last_written_eyes);
366 /* Write any frames that we can write; i.e. those that are in sequence. */
367 while (have_sequenced_image_at_queue_head ()) {
368 QueueItem qi = _queue.front ();
370 if (qi.type == QueueItem::FULL && qi.encoded) {
371 --_queued_full_in_memory;
376 case QueueItem::FULL:
378 LOG_DEBUG_ENCODE (N_("Writer FULL-writes %1 (%2)"), qi.frame, qi.eyes);
380 qi.encoded = Data (_film->j2c_path (qi.frame, qi.eyes, false));
383 dcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data().get (), qi.encoded->size());
384 write_frame_info (qi.frame, qi.eyes, fin);
385 _last_written[qi.eyes] = qi.encoded;
389 case QueueItem::FAKE:
390 LOG_DEBUG_ENCODE (N_("Writer FAKE-writes %1"), qi.frame);
391 _picture_asset_writer->fake_write (qi.size);
392 _last_written[qi.eyes].reset ();
395 case QueueItem::REPEAT:
396 LOG_DEBUG_ENCODE (N_("Writer REPEAT-writes %1"), qi.frame);
397 dcp::FrameInfo fin = _picture_asset_writer->write (
398 _last_written[qi.eyes]->data().get(),
399 _last_written[qi.eyes]->size()
401 write_frame_info (qi.frame, qi.eyes, fin);
407 _last_written_frame = qi.frame;
408 _last_written_eyes = qi.eyes;
410 shared_ptr<Job> job = _job.lock ();
411 DCPOMATIC_ASSERT (job);
412 int64_t total = _film->length().frames_round (_film->video_frame_rate ());
413 if (_film->three_d ()) {
414 /* _full_written and so on are incremented for each eye, so we need to double the total
415 frames to get the correct progress.
420 job->set_progress (float (_full_written + _fake_written + _repeat_written) / total);
424 while (_queued_full_in_memory > _maximum_frames_in_memory) {
425 /* Too many frames in memory which can't yet be written to the stream.
426 Write some FULL frames to disk.
429 /* Find one from the back of the queue */
431 list<QueueItem>::reverse_iterator i = _queue.rbegin ();
432 while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
436 DCPOMATIC_ASSERT (i != _queue.rend());
440 /* i is valid here, even though we don't hold a lock on the mutex,
441 since list iterators are unaffected by insertion and only this
442 thread could erase the last item in the list.
446 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
447 _last_written_frame + 1,
448 _last_written_eyes, i->frame
451 i->encoded->write_via_temp (_film->j2c_path (i->frame, i->eyes, true), _film->j2c_path (i->frame, i->eyes, false));
455 --_queued_full_in_memory;
458 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
459 _full_condition.notify_all ();
468 Writer::terminate_thread (bool can_throw)
470 boost::mutex::scoped_lock lock (_state_mutex);
476 _empty_condition.notify_all ();
477 _full_condition.notify_all ();
496 terminate_thread (true);
498 _picture_asset_writer->finalize ();
499 if (_sound_asset_writer) {
500 _sound_asset_writer->finalize ();
503 /* Hard-link the video asset into the DCP */
504 boost::filesystem::path video_from = _picture_asset->file ();
506 boost::filesystem::path video_to;
507 video_to /= _film->dir (_film->dcp_name());
508 video_to /= video_asset_filename (_picture_asset);
510 boost::system::error_code ec;
511 boost::filesystem::create_hard_link (video_from, video_to, ec);
513 LOG_WARNING_NC ("Hard-link failed; copying instead");
514 boost::filesystem::copy_file (video_from, video_to, ec);
516 LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
517 throw FileError (ec.message(), video_from);
521 _picture_asset->set_file (video_to);
523 /* Move the audio asset into the DCP */
526 boost::filesystem::path audio_to;
527 audio_to /= _film->dir (_film->dcp_name ());
528 audio_to /= audio_asset_filename (_sound_asset);
530 boost::filesystem::rename (_film->file (audio_asset_filename (_sound_asset)), audio_to, ec);
533 String::compose (_("could not move audio asset into the DCP (%1)"), ec.value ()), audio_asset_filename (_sound_asset)
537 _sound_asset->set_file (audio_to);
540 dcp::DCP dcp (_film->dir (_film->dcp_name()));
542 shared_ptr<dcp::CPL> cpl (
545 _film->dcp_content_type()->libdcp_kind ()
551 shared_ptr<dcp::Reel> reel (new dcp::Reel ());
553 shared_ptr<dcp::MonoPictureAsset> mono = dynamic_pointer_cast<dcp::MonoPictureAsset> (_picture_asset);
555 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
558 shared_ptr<dcp::StereoPictureAsset> stereo = dynamic_pointer_cast<dcp::StereoPictureAsset> (_picture_asset);
560 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
564 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_asset, 0)));
567 if (_subtitle_asset) {
568 boost::filesystem::path liberation;
570 liberation = shared_path () / "LiberationSans-Regular.ttf";
571 } catch (boost::filesystem::filesystem_error& e) {
572 /* Hack: try the debian/ubuntu location if getting the shared path failed */
573 liberation = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf";
576 /* Add all the fonts to the subtitle content */
577 BOOST_FOREACH (shared_ptr<Font> i, _fonts) {
578 _subtitle_asset->add_font (i->id(), i->file().get_value_or (liberation));
581 if (dynamic_pointer_cast<dcp::InteropSubtitleAsset> (_subtitle_asset)) {
582 boost::filesystem::path directory = _film->dir (_film->dcp_name ()) / _subtitle_asset->id ();
583 boost::filesystem::create_directories (directory);
584 _subtitle_asset->write (directory / ("sub_" + _subtitle_asset->id() + ".xml"));
586 _subtitle_asset->write (
587 _film->dir (_film->dcp_name ()) / ("sub_" + _subtitle_asset->id() + ".mxf")
591 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
592 new dcp::ReelSubtitleAsset (
594 dcp::Fraction (_film->video_frame_rate(), 1),
595 _picture_asset->intrinsic_duration (),
603 shared_ptr<Job> job = _job.lock ();
604 DCPOMATIC_ASSERT (job);
606 job->sub (_("Computing image digest"));
607 _picture_asset->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
610 job->sub (_("Computing audio digest"));
611 _sound_asset->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
614 dcp::XMLMetadata meta;
615 meta.creator = Config::instance()->dcp_creator ();
616 if (meta.creator.empty ()) {
617 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
619 meta.issuer = Config::instance()->dcp_issuer ();
620 if (meta.issuer.empty ()) {
621 meta.issuer = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
623 meta.set_issue_date_now ();
625 cpl->set_metadata (meta);
627 shared_ptr<const dcp::CertificateChain> signer;
628 if (_film->is_signed ()) {
629 signer = Config::instance()->signer_chain ();
630 /* We did check earlier, but check again here to be on the safe side */
631 if (!signer->valid ()) {
632 throw InvalidSignerError ();
636 dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer);
639 N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT, %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk
644 Writer::check_existing_picture_asset ()
646 /* Try to open the existing asset */
647 FILE* asset_file = fopen_boost (_picture_asset->file(), "rb");
649 LOG_GENERAL ("Could not open existing asset at %1 (errno=%2)", _picture_asset->file().string(), errno);
653 /* Offset of the last dcp::FrameInfo in the info file */
654 int const n = (boost::filesystem::file_size (_film->info_file ()) / _info_size) - 1;
656 FILE* info_file = fopen_boost (_film->info_file (), "rb");
658 LOG_GENERAL_NC ("Could not open film info file");
663 if (_film->three_d ()) {
664 /* Start looking at the last left frame */
665 _first_nonexistant_frame = n / 2;
667 _first_nonexistant_frame = n;
673 /* Read the data from the info file; for 3D we just check the left
674 frames until we find a good one.
676 dcp::FrameInfo info = read_frame_info (info_file, _first_nonexistant_frame, _film->three_d () ? EYES_LEFT : EYES_BOTH);
680 /* Read the data from the asset and hash it */
681 dcpomatic_fseek (asset_file, info.offset, SEEK_SET);
682 Data data (info.size);
683 size_t const read = fread (data.data().get(), 1, data.size(), asset_file);
684 if (read != static_cast<size_t> (data.size ())) {
685 LOG_GENERAL ("Existing frame %1 is incomplete", _first_nonexistant_frame);
688 MD5Digester digester;
689 digester.add (data.data().get(), data.size());
690 if (digester.get() != info.hash) {
691 LOG_GENERAL ("Existing frame %1 failed hash check", _first_nonexistant_frame);
697 --_first_nonexistant_frame;
701 if (!_film->three_d ()) {
702 /* If we are doing 3D we might have found a good L frame with no R, so only
703 do this if we're in 2D and we've just found a good B(oth) frame.
705 ++_first_nonexistant_frame;
712 /** @param frame Frame index.
713 * @return true if we can fake-write this frame.
716 Writer::can_fake_write (int frame) const
718 /* We have to do a proper write of the first frame so that we can set up the JPEG2000
719 parameters in the asset writer.
721 return (frame != 0 && frame < _first_nonexistant_frame);
725 Writer::write (PlayerSubtitles subs)
727 if (subs.text.empty ()) {
731 if (!_subtitle_asset) {
732 string lang = _film->subtitle_language ();
736 if (_film->interop ()) {
737 shared_ptr<dcp::InteropSubtitleAsset> s (new dcp::InteropSubtitleAsset ());
738 s->set_movie_title (_film->name ());
739 s->set_language (lang);
740 s->set_reel_number ("1");
743 shared_ptr<dcp::SMPTESubtitleAsset> s (new dcp::SMPTESubtitleAsset ());
744 s->set_content_title_text (_film->name ());
745 s->set_language (lang);
746 s->set_edit_rate (dcp::Fraction (_film->video_frame_rate (), 1));
747 s->set_reel_number (1);
748 s->set_time_code_rate (_film->video_frame_rate ());
749 s->set_start_time (dcp::Time ());
754 for (list<dcp::SubtitleString>::const_iterator i = subs.text.begin(); i != subs.text.end(); ++i) {
755 _subtitle_asset->add (*i);
760 Writer::write (list<shared_ptr<Font> > fonts)
762 /* Just keep a list of fonts and we'll deal with them in ::finish */
763 copy (fonts.begin (), fonts.end (), back_inserter (_fonts));
767 operator< (QueueItem const & a, QueueItem const & b)
769 if (a.frame != b.frame) {
770 return a.frame < b.frame;
773 return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
777 operator== (QueueItem const & a, QueueItem const & b)
779 return a.frame == b.frame && a.eyes == b.eyes;
783 Writer::set_encoder_threads (int threads)
785 _maximum_frames_in_memory = lrint (threads * 1.1);
789 Writer::frame_info_position (int frame, Eyes eyes) const
793 return frame * _info_size;
795 return frame * _info_size * 2;
797 return frame * _info_size * 2 + _info_size;
799 DCPOMATIC_ASSERT (false);
802 DCPOMATIC_ASSERT (false);
806 Writer::read_frame_info (FILE* file, int frame, Eyes eyes) const
809 dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
810 fread (&info.offset, sizeof (info.offset), 1, file);
811 fread (&info.size, sizeof (info.size), 1, file);
813 char hash_buffer[33];
814 fread (hash_buffer, 1, 32, file);
815 hash_buffer[32] = '\0';
816 info.hash = hash_buffer;