2 Copyright (C) 2013-2021 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
6 DCP-o-matic is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 DCP-o-matic is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>.
22 #include "atmos_decoder.h"
23 #include "audio_buffers.h"
24 #include "audio_content.h"
25 #include "audio_decoder.h"
26 #include "audio_processor.h"
27 #include "compose.hpp"
29 #include "content_audio.h"
30 #include "content_video.h"
31 #include "constants.h"
32 #include "dcp_content.h"
33 #include "dcp_decoder.h"
34 #include "dcpomatic_log.h"
36 #include "decoder_factory.h"
37 #include "ffmpeg_content.h"
39 #include "frame_rate_change.h"
41 #include "image_decoder.h"
44 #include "maths_util.h"
47 #include "player_video.h"
50 #include "raw_image_proxy.h"
51 #include "render_text.h"
53 #include "text_content.h"
54 #include "text_decoder.h"
56 #include "video_decoder.h"
58 #include <dcp/reel_closed_caption_asset.h>
59 #include <dcp/reel_picture_asset.h>
60 #include <dcp/reel_sound_asset.h>
61 #include <dcp/reel_subtitle_asset.h>
71 using std::dynamic_pointer_cast;
74 using std::make_shared;
78 using std::shared_ptr;
81 using boost::optional;
82 using boost::scoped_ptr;
83 #if BOOST_VERSION >= 106100
84 using namespace boost::placeholders;
86 using namespace dcpomatic;
89 int const PlayerProperty::VIDEO_CONTAINER_SIZE = 700;
90 int const PlayerProperty::PLAYLIST = 701;
91 int const PlayerProperty::FILM_CONTAINER = 702;
92 int const PlayerProperty::FILM_VIDEO_FRAME_RATE = 703;
93 int const PlayerProperty::DCP_DECODE_REDUCTION = 704;
94 int const PlayerProperty::PLAYBACK_LENGTH = 705;
95 int const PlayerProperty::IGNORE_VIDEO = 706;
96 int const PlayerProperty::IGNORE_AUDIO = 707;
97 int const PlayerProperty::IGNORE_TEXT = 708;
98 int const PlayerProperty::ALWAYS_BURN_OPEN_SUBTITLES = 709;
99 int const PlayerProperty::PLAY_REFERENCED = 710;
102 Player::Player (shared_ptr<const Film> film, Image::Alignment subtitle_alignment)
105 , _ignore_video(false)
106 , _ignore_audio(false)
107 , _ignore_text(false)
108 , _always_burn_open_subtitles(false)
110 , _tolerant (film->tolerant())
111 , _play_referenced(false)
112 , _audio_merger(film->audio_frame_rate())
113 , _subtitle_alignment (subtitle_alignment)
119 Player::Player (shared_ptr<const Film> film, shared_ptr<const Playlist> playlist_)
121 , _playlist (playlist_)
123 , _ignore_video(false)
124 , _ignore_audio(false)
125 , _ignore_text(false)
126 , _always_burn_open_subtitles(false)
128 , _tolerant (film->tolerant())
129 , _play_referenced(false)
130 , _audio_merger(film->audio_frame_rate())
137 Player::full_size(VideoType type) const
140 case VideoType::MAIN:
142 auto film = _film.lock();
143 DCPOMATIC_ASSERT(film);
144 return film->frame_size();
146 case VideoType::SIGN_LANGUAGE:
149 DCPOMATIC_ASSERT(false);
158 set_video_container_size(VideoType::MAIN, full_size(VideoType::MAIN));
159 set_video_container_size(VideoType::SIGN_LANGUAGE, full_size(VideoType::SIGN_LANGUAGE));
161 _black_image[VideoType::SIGN_LANGUAGE] = make_shared<Image>(AV_PIX_FMT_RGB24, dcp::Size(SIGN_LANGUAGE_WIDTH, SIGN_LANGUAGE_HEIGHT), Image::Alignment::PADDED);
163 film_change(ChangeType::DONE, FilmProperty::AUDIO_PROCESSOR);
166 seek (DCPTime (), true);
173 auto film = _film.lock();
174 DCPOMATIC_ASSERT(film);
176 _film_changed_connection = film->Change.connect(bind(&Player::film_change, this, _1, _2));
177 /* The butler must hear about this first, so since we are proxying this through to the butler we must
180 _playlist_change_connection = playlist()->Change.connect (bind (&Player::playlist_change, this, _1), boost::signals2::at_front);
181 _playlist_content_change_connection = playlist()->ContentChange.connect (bind(&Player::playlist_content_change, this, _1, _3, _4));
185 Player::Player(Player&& other)
187 , _playlist(std::move(other._playlist))
188 , _suspended(other._suspended.load())
189 , _pieces(std::move(other._pieces))
190 , _video_container_size(other._video_container_size)
191 , _black_image(std::move(other._black_image))
192 , _ignore_video(other._ignore_video.load())
193 , _ignore_audio(other._ignore_audio.load())
194 , _ignore_text(other._ignore_text.load())
195 , _always_burn_open_subtitles(other._always_burn_open_subtitles.load())
196 , _fast(other._fast.load())
197 , _tolerant(other._tolerant)
198 , _play_referenced(other._play_referenced.load())
199 , _next_video_time(other._next_video_time)
200 , _next_audio_time(other._next_audio_time)
201 , _dcp_decode_reduction(other._dcp_decode_reduction.load())
202 , _last_video(std::move(other._last_video))
203 , _audio_merger(std::move(other._audio_merger))
204 , _shuffler(std::move(other._shuffler))
205 , _delay(std::move(other._delay))
206 , _stream_states(std::move(other._stream_states))
207 , _black(std::move(other._black))
208 , _silent(std::move(other._silent))
209 , _active_texts(std::move(other._active_texts))
210 , _audio_processor(std::move(other._audio_processor))
211 , _disable_audio_processor(other._disable_audio_processor)
212 , _playback_length(other._playback_length.load())
213 , _subtitle_alignment(other._subtitle_alignment)
220 Player::operator=(Player&& other)
222 if (this == &other) {
226 _film = std::move(other._film);
227 _playlist = std::move(other._playlist);
228 _suspended = other._suspended.load();
229 _pieces = std::move(other._pieces);
230 _video_container_size = other._video_container_size;
231 _black_image = std::move(other._black_image);
232 _ignore_video = other._ignore_video.load();
233 _ignore_audio = other._ignore_audio.load();
234 _ignore_text = other._ignore_text.load();
235 _always_burn_open_subtitles = other._always_burn_open_subtitles.load();
236 _fast = other._fast.load();
237 _tolerant = other._tolerant;
238 _play_referenced = other._play_referenced.load();
239 _next_video_time = other._next_video_time;
240 _next_audio_time = other._next_audio_time;
241 _dcp_decode_reduction = other._dcp_decode_reduction.load();
242 _last_video = std::move(other._last_video);
243 _audio_merger = std::move(other._audio_merger);
244 _shuffler = std::move(other._shuffler);
245 _delay = std::move(other._delay);
246 _stream_states = std::move(other._stream_states);
247 _black = std::move(other._black);
248 _silent = std::move(other._silent);
249 _active_texts = std::move(other._active_texts);
250 _audio_processor = std::move(other._audio_processor);
251 _disable_audio_processor = other._disable_audio_processor;
252 _playback_length = other._playback_length.load();
253 _subtitle_alignment = other._subtitle_alignment;
262 have_video(shared_ptr<const Content> content, VideoType type)
264 return static_cast<bool>(content->video)
265 && content->video->use()
266 && content->can_be_played()
267 && content->video->type() == type;
272 have_audio (shared_ptr<const Content> content)
274 return content->has_mapped_audio() && content->can_be_played();
279 Player::setup_pieces ()
281 boost::mutex::scoped_lock lm (_mutex);
283 auto old_pieces = _pieces;
286 auto film = _film.lock();
291 _playback_length = _playlist ? _playlist->length(film) : film->length();
293 auto playlist_content = playlist()->content();
294 bool const have_threed = std::any_of(
295 playlist_content.begin(),
296 playlist_content.end(),
297 [](shared_ptr<const Content> c) {
298 return c->video && (c->video->frame_type() == VideoFrameType::THREE_D_LEFT || c->video->frame_type() == VideoFrameType::THREE_D_RIGHT);
303 _shuffler.reset(new Shuffler());
304 _shuffler->Video.connect(bind(&Player::video, this, _1, _2));
307 for (auto content: playlist()->content()) {
309 if (!content->paths_valid()) {
313 if (_ignore_video && _ignore_audio && content->text.empty()) {
314 /* We're only interested in text and this content has none */
318 shared_ptr<Decoder> old_decoder;
319 for (auto j: old_pieces) {
320 if (j->content == content) {
321 old_decoder = j->decoder;
326 auto decoder = decoder_factory(film, content, _fast, _tolerant, old_decoder);
327 DCPOMATIC_ASSERT (decoder);
329 FrameRateChange frc(film, content);
331 if (decoder->video && _ignore_video) {
332 decoder->video->set_ignore (true);
335 if (decoder->audio && _ignore_audio) {
336 decoder->audio->set_ignore (true);
340 for (auto i: decoder->text) {
341 i->set_ignore (true);
345 auto dcp = dynamic_pointer_cast<DCPDecoder> (decoder);
347 dcp->set_decode_referenced (_play_referenced);
348 if (_play_referenced) {
349 dcp->set_forced_reduction (_dcp_decode_reduction);
353 auto piece = make_shared<Piece>(content, decoder, frc);
354 _pieces.push_back (piece);
356 if (decoder->video) {
358 /* We need a Shuffler to cope with 3D L/R video data arriving out of sequence */
359 decoder->video->Data.connect (bind(&Shuffler::video, _shuffler.get(), weak_ptr<Piece>(piece), _1));
361 decoder->video->Data.connect (bind(&Player::video, this, weak_ptr<Piece>(piece), _1));
365 if (decoder->audio) {
366 decoder->audio->Data.connect (bind (&Player::audio, this, weak_ptr<Piece> (piece), _1, _2));
369 auto j = decoder->text.begin();
371 while (j != decoder->text.end()) {
372 (*j)->BitmapStart.connect (
373 bind(&Player::bitmap_text_start, this, weak_ptr<Piece>(piece), weak_ptr<const TextContent>((*j)->content()), _1)
375 (*j)->PlainStart.connect (
376 bind(&Player::plain_text_start, this, weak_ptr<Piece>(piece), weak_ptr<const TextContent>((*j)->content()), _1)
379 bind(&Player::subtitle_stop, this, weak_ptr<Piece>(piece), weak_ptr<const TextContent>((*j)->content()), _1)
385 if (decoder->atmos) {
386 decoder->atmos->Data.connect (bind(&Player::atmos, this, weak_ptr<Piece>(piece), _1));
390 _stream_states.clear ();
391 for (auto i: _pieces) {
392 if (i->content->has_mapped_audio()) {
393 for (auto j: i->content->audio->streams()) {
394 _stream_states[j] = StreamState(i);
399 auto ignore_overlap = [](shared_ptr<VideoContent> v) {
400 return v && v->use() && v->frame_type() != VideoFrameType::THREE_D_LEFT && v->frame_type() != VideoFrameType::THREE_D_RIGHT;
403 for (auto piece = _pieces.begin(); piece != _pieces.end(); ++piece) {
404 if (ignore_overlap((*piece)->content->video)) {
405 /* Look for content later in the content list with in-use video that overlaps this */
406 auto const period = (*piece)->content->period(film);
407 for (auto later_piece = std::next(piece); later_piece != _pieces.end(); ++later_piece) {
408 if (ignore_overlap((*later_piece)->content->video)) {
409 if (auto overlap = (*later_piece)->content->period(film).overlap(period)) {
410 (*piece)->ignore_video.push_back(*overlap);
417 for (auto piece = _pieces.begin(); piece != _pieces.end(); ++piece) {
418 if ((*piece)->content->atmos) {
419 /* Look for content later in the content list with ATMOS that overlaps this */
420 auto const period = (*piece)->content->period(film);
421 for (auto later_piece = std::next(piece); later_piece != _pieces.end(); ++later_piece) {
422 if ((*later_piece)->content->atmos) {
423 if (auto overlap = (*later_piece)->content->period(film).overlap(period)) {
424 (*piece)->ignore_atmos.push_back(*overlap);
431 _have_sign_language = contains_sign_language(playlist_content);
433 _black[VideoType::MAIN] = Empty(film, playlist(), bind(&have_video, _1, VideoType::MAIN), _playback_length);
434 if (_have_sign_language) {
435 _black[VideoType::SIGN_LANGUAGE] = Empty(film, playlist(), bind(&have_video, _1, VideoType::SIGN_LANGUAGE), _playback_length);
437 _silent = Empty(film, playlist(), bind(&have_audio, _1), _playback_length);
439 _next_video_time[VideoType::MAIN] = _next_video_time[VideoType::SIGN_LANGUAGE] = boost::none;
440 _next_audio_time = boost::none;
445 Player::playlist_content_change (ChangeType type, int property, bool frequent)
447 auto film = _film.lock();
452 if (property == VideoContentProperty::CROP) {
453 if (type == ChangeType::DONE) {
454 boost::mutex::scoped_lock lm (_mutex);
455 for (auto const& i: _delay) {
456 i.first->reset_metadata(film, video_container_size(VideoType::MAIN));
460 if (type == ChangeType::PENDING) {
461 /* The player content is probably about to change, so we can't carry on
462 until that has happened and we've rebuilt our pieces. Stop pass()
463 and seek() from working until then.
466 } else if (type == ChangeType::DONE) {
467 /* A change in our content has gone through. Re-build our pieces. */
470 } else if (type == ChangeType::CANCELLED) {
475 Change (type, property, frequent);
480 Player::set_video_container_size(VideoType type, dcp::Size size)
482 ChangeSignaller<Player, int> cc(this, PlayerProperty::VIDEO_CONTAINER_SIZE);
484 if (size == video_container_size(type)) {
489 boost::mutex::scoped_lock lm(_video_container_size_mutex);
490 _video_container_size[type] = size;
493 boost::mutex::scoped_lock lm(_black_image_mutex);
494 _black_image[type] = make_shared<Image>(AV_PIX_FMT_RGB24, _video_container_size[type], Image::Alignment::PADDED);
495 _black_image[type]->make_black();
501 Player::playlist_change (ChangeType type)
503 if (type == ChangeType::DONE) {
506 Change (type, PlayerProperty::PLAYLIST, false);
511 Player::film_change(ChangeType type, FilmProperty p)
513 /* Here we should notice Film properties that affect our output, and
514 alert listeners that our output now would be different to how it was
515 last time we were run.
518 auto film = _film.lock();
523 if (p == FilmProperty::CONTAINER) {
524 Change (type, PlayerProperty::FILM_CONTAINER, false);
525 } else if (p == FilmProperty::VIDEO_FRAME_RATE) {
526 /* Pieces contain a FrameRateChange which contains the DCP frame rate,
527 so we need new pieces here.
529 if (type == ChangeType::DONE) {
532 Change (type, PlayerProperty::FILM_VIDEO_FRAME_RATE, false);
533 } else if (p == FilmProperty::AUDIO_PROCESSOR) {
534 if (type == ChangeType::DONE && film->audio_processor ()) {
535 boost::mutex::scoped_lock lm (_mutex);
536 _audio_processor = film->audio_processor()->clone(film->audio_frame_rate());
538 } else if (p == FilmProperty::AUDIO_CHANNELS) {
539 if (type == ChangeType::DONE) {
540 boost::mutex::scoped_lock lm (_mutex);
541 _audio_merger.clear ();
547 shared_ptr<PlayerVideo>
548 Player::black_player_video_frame(VideoType type, Eyes eyes) const
550 boost::mutex::scoped_lock lm(_black_image_mutex);
552 auto const image = _black_image[type];
554 return std::make_shared<PlayerVideo> (
555 make_shared<const RawImageProxy>(image),
563 PresetColourConversion::all().front().conversion,
565 std::weak_ptr<Content>(),
566 boost::optional<dcpomatic::ContentTime>(),
573 Player::dcp_to_content_video (shared_ptr<const Piece> piece, DCPTime t) const
575 auto film = _film.lock();
576 DCPOMATIC_ASSERT(film);
578 auto s = t - piece->content->position ();
579 s = min (piece->content->length_after_trim(film), s);
580 s = max (DCPTime(), s + DCPTime (piece->content->trim_start(), piece->frc));
582 /* It might seem more logical here to convert s to a ContentTime (using the FrameRateChange)
583 then convert that ContentTime to frames at the content's rate. However this fails for
584 situations like content at 29.9978733fps, DCP at 30fps. The accuracy of the Time type is not
585 enough to distinguish between the two with low values of time (e.g. 3200 in Time units).
587 Instead we convert the DCPTime using the DCP video rate then account for any skip/repeat.
589 return s.frames_floor (piece->frc.dcp) / piece->frc.factor ();
594 Player::content_video_to_dcp (shared_ptr<const Piece> piece, Frame f) const
596 /* See comment in dcp_to_content_video */
597 auto const d = DCPTime::from_frames (f * piece->frc.factor(), piece->frc.dcp) - DCPTime(piece->content->trim_start(), piece->frc);
598 return d + piece->content->position();
603 Player::dcp_to_resampled_audio (shared_ptr<const Piece> piece, DCPTime t) const
605 auto film = _film.lock();
606 DCPOMATIC_ASSERT(film);
608 auto s = t - piece->content->position ();
609 s = min (piece->content->length_after_trim(film), s);
610 /* See notes in dcp_to_content_video */
611 return max (DCPTime(), DCPTime(piece->content->trim_start(), piece->frc) + s).frames_floor(film->audio_frame_rate());
616 Player::resampled_audio_to_dcp (shared_ptr<const Piece> piece, Frame f) const
618 auto film = _film.lock();
619 DCPOMATIC_ASSERT(film);
621 /* See comment in dcp_to_content_video */
622 return DCPTime::from_frames(f, film->audio_frame_rate())
623 - DCPTime (piece->content->trim_start(), piece->frc)
624 + piece->content->position();
629 Player::dcp_to_content_time (shared_ptr<const Piece> piece, DCPTime t) const
631 auto film = _film.lock();
632 DCPOMATIC_ASSERT(film);
634 auto s = t - piece->content->position ();
635 s = min (piece->content->length_after_trim(film), s);
636 return max (ContentTime (), ContentTime (s, piece->frc) + piece->content->trim_start());
641 Player::content_time_to_dcp (shared_ptr<const Piece> piece, ContentTime t) const
643 return max (DCPTime(), DCPTime(t - piece->content->trim_start(), piece->frc) + piece->content->position());
647 vector<shared_ptr<Font>>
648 Player::get_subtitle_fonts ()
650 boost::mutex::scoped_lock lm (_mutex);
652 vector<shared_ptr<Font>> fonts;
653 for (auto piece: _pieces) {
654 for (auto text: piece->content->text) {
655 auto text_fonts = text->fonts();
656 copy (text_fonts.begin(), text_fonts.end(), back_inserter(fonts));
664 /** Set this player never to produce any video data */
666 Player::set_ignore_video ()
668 ChangeSignaller<Player, int> cc(this, PlayerProperty::IGNORE_VIDEO);
669 _ignore_video = true;
675 Player::set_ignore_audio ()
677 ChangeSignaller<Player, int> cc(this, PlayerProperty::IGNORE_AUDIO);
678 _ignore_audio = true;
684 Player::set_ignore_text ()
686 ChangeSignaller<Player, int> cc(this, PlayerProperty::IGNORE_TEXT);
692 /** Set the player to always burn open texts into the image regardless of the content settings */
694 Player::set_always_burn_open_subtitles ()
696 ChangeSignaller<Player, int> cc(this, PlayerProperty::ALWAYS_BURN_OPEN_SUBTITLES);
697 _always_burn_open_subtitles = true;
701 /** Sets up the player to be faster, possibly at the expense of quality */
711 Player::set_play_referenced ()
713 ChangeSignaller<Player, int> cc(this, PlayerProperty::PLAY_REFERENCED);
714 _play_referenced = true;
719 pair<shared_ptr<Piece>, optional<DCPTime>>
720 Player::earliest_piece_and_time() const
722 auto film = _film.lock();
723 DCPOMATIC_ASSERT(film);
725 shared_ptr<Piece> earliest_content;
726 optional<DCPTime> earliest_time;
728 for (auto const& piece: _pieces) {
733 auto const t = content_time_to_dcp(piece, max(piece->decoder->position(), piece->content->trim_start()));
734 if (t > piece->content->end(film)) {
738 /* Given two choices at the same time, pick the one with texts so we see it before
741 if (!earliest_time || t < *earliest_time || (t == *earliest_time && !piece->decoder->text.empty())) {
743 earliest_content = piece;
748 return { earliest_content, earliest_time };
755 boost::mutex::scoped_lock lm (_mutex);
758 /* We can't pass in this state */
759 LOG_DEBUG_PLAYER_NC ("Player is suspended");
763 auto film = _film.lock();
765 if (_playback_length.load() == DCPTime() || !film) {
766 /* Special; just give one black frame */
767 use_video(black_player_video_frame(VideoType::MAIN, Eyes::BOTH), DCPTime(), one_video_frame());
768 use_video(black_player_video_frame(VideoType::SIGN_LANGUAGE, Eyes::BOTH), DCPTime(), one_video_frame());
772 /* Find the decoder or empty which is farthest behind where we are and make it emit some data */
774 shared_ptr<Piece> earliest_content;
775 optional<DCPTime> earliest_time;
776 std::tie(earliest_content, earliest_time) = earliest_piece_and_time();
787 optional<VideoType> black_type;
789 if (earliest_content) {
793 auto check_black = [this, &earliest_time, &which, &black_type](VideoType type) {
794 if (!_black[type].done() && !_ignore_video && (!earliest_time || _black[type].position() < *earliest_time)) {
795 earliest_time = _black[type].position();
801 check_black(VideoType::MAIN);
802 check_black(VideoType::SIGN_LANGUAGE);
804 if (!_silent.done() && !_ignore_audio && (!earliest_time || _silent.position() < *earliest_time)) {
805 earliest_time = _silent.position ();
812 LOG_DEBUG_PLAYER ("Calling pass() on %1", earliest_content->content->path(0));
813 earliest_content->done = earliest_content->decoder->pass ();
814 auto dcp = dynamic_pointer_cast<DCPContent>(earliest_content->content);
815 if (dcp && !_play_referenced) {
816 if (dcp->reference_video()) {
817 _next_video_time[earliest_content->content->video->type()] = dcp->end(film);
819 if (dcp->reference_audio()) {
820 /* We are skipping some referenced DCP audio content, so we need to update _next_audio_time
821 to `hide' the fact that no audio was emitted during the referenced DCP (though
822 we need to behave as though it was).
824 _next_audio_time = dcp->end(film);
831 DCPOMATIC_ASSERT(black_type);
832 auto& black = _black[*black_type];
833 LOG_DEBUG_PLAYER("Emit black for gap at %1", to_string(black.position()));
834 if (!_next_video_time[*black_type]) {
835 /* Deciding to emit black has the same effect as getting some video from the content
836 * when we are inaccurately seeking.
838 _next_video_time[*black_type] = black.position();
840 if (film->three_d()) {
841 use_video(black_player_video_frame(*black_type, Eyes::LEFT), black.position(), black.period_at_position().to);
842 use_video(black_player_video_frame(*black_type, Eyes::RIGHT), black.position(), black.period_at_position().to);
844 use_video(black_player_video_frame(*black_type, Eyes::BOTH), black.position(), black.period_at_position().to);
846 black.set_position(black.position() + one_video_frame());
851 LOG_DEBUG_PLAYER ("Emit silence for gap at %1", to_string(_silent.position()));
852 DCPTimePeriod period (_silent.period_at_position());
853 if (_next_audio_time) {
854 /* Sometimes the thing that happened last finishes fractionally before
855 or after this silence. Bodge the start time of the silence to fix it.
856 I think this is nothing to worry about since we will just add or
857 remove a little silence at the end of some content.
859 int64_t const error = labs(period.from.get() - _next_audio_time->get());
860 /* Let's not worry about less than a frame at 24fps */
861 int64_t const too_much_error = DCPTime::from_frames(1, 24).get();
862 if (error >= too_much_error) {
863 film->log()->log(String::compose("Silence starting before or after last audio by %1", error), LogEntry::TYPE_ERROR);
865 DCPOMATIC_ASSERT (error < too_much_error);
866 period.from = *_next_audio_time;
868 if (period.duration() > one_video_frame()) {
869 period.to = period.from + one_video_frame();
872 _silent.set_position (period.to);
880 /* Emit any audio that is ready */
882 /* Work out the time before which the audio is definitely all here. This is the earliest last_push_end of one
883 of our streams, or the position of the _silent. First, though we choose only streams that are less than
884 ignore_streams_behind seconds behind the furthest ahead (we assume that if a stream has fallen that far
885 behind it has finished). This is so that we don't withhold audio indefinitely awaiting data from a stream
886 that will never come, causing bugs like #2101.
888 constexpr int ignore_streams_behind = 5;
890 using state_pair = std::pair<AudioStreamPtr, StreamState>;
892 /* Find streams that have pushed */
893 std::vector<state_pair> have_pushed;
894 std::copy_if(_stream_states.begin(), _stream_states.end(), std::back_inserter(have_pushed), [](state_pair const& a) { return static_cast<bool>(a.second.last_push_end); });
896 /* Find the 'leading' stream (i.e. the one that pushed data most recently) */
897 auto latest_last_push_end = std::max_element(
900 [](state_pair const& a, state_pair const& b) { return a.second.last_push_end.get() < b.second.last_push_end.get(); }
903 std::map<AudioStreamPtr, StreamState> alive_stream_states;
905 if (latest_last_push_end != have_pushed.end()) {
906 LOG_DEBUG_PLAYER("Leading audio stream is in %1 at %2", latest_last_push_end->second.piece->content->path(0), to_string(latest_last_push_end->second.last_push_end.get()));
908 /* Now make a list of those streams that are less than ignore_streams_behind behind the leader */
909 for (auto const& i: _stream_states) {
910 if (!i.second.last_push_end || (latest_last_push_end->second.last_push_end.get() - i.second.last_push_end.get()) < dcpomatic::DCPTime::from_seconds(ignore_streams_behind)) {
911 alive_stream_states.insert(i);
913 LOG_DEBUG_PLAYER("Ignoring stream %1 because it is too far behind", i.second.piece->content->path(0));
918 auto pull_to = _playback_length.load();
919 for (auto const& i: alive_stream_states) {
920 auto position = i.second.last_push_end.get_value_or(i.second.piece->content->position());
921 if (!i.second.piece->done && position < pull_to) {
925 if (!_silent.done() && _silent.position() < pull_to) {
926 pull_to = _silent.position();
929 LOG_DEBUG_PLAYER("Emitting audio up to %1", to_string(pull_to));
930 auto audio = _audio_merger.pull (pull_to);
931 for (auto i = audio.begin(); i != audio.end(); ++i) {
932 if (_next_audio_time && i->second < *_next_audio_time) {
933 /* This new data comes before the last we emitted (or the last seek); discard it */
934 auto cut = discard_audio (i->first, i->second, *_next_audio_time);
939 } else if (_next_audio_time && i->second > *_next_audio_time) {
940 /* There's a gap between this data and the last we emitted; fill with silence */
941 fill_audio (DCPTimePeriod (*_next_audio_time, i->second));
944 emit_audio (i->first, i->second);
948 if (_next_video_time[VideoType::MAIN]) {
949 LOG_DEBUG_PLAYER("Done: emit video until end of film at %1", to_string(film->length()));
950 emit_video_until(VideoType::MAIN, film->length());
952 if (_next_video_time[VideoType::SIGN_LANGUAGE] && _have_sign_language) {
953 emit_video_until(VideoType::SIGN_LANGUAGE, film->length());
959 for (auto const& i: _delay) {
960 emit_video(i.first, i.second);
968 /** @return Open subtitles for the frame at the given time, converted to images */
969 optional<PositionImage>
970 Player::open_subtitles_for_frame (DCPTime time) const
972 auto film = _film.lock();
977 list<PositionImage> captions;
978 int const vfr = film->video_frame_rate();
979 auto const container = video_container_size(VideoType::MAIN);
983 _active_texts[TextType::OPEN_SUBTITLE].get_burnt(DCPTimePeriod(time, time + DCPTime::from_frames(1, vfr)), _always_burn_open_subtitles)
986 /* Bitmap subtitles */
987 for (auto i: j.bitmap) {
988 if (!i.image || i.image->size().width == 0 || i.image->size().height == 0) {
992 /* i.image will already have been scaled to fit video_container_size */
993 dcp::Size scaled_size(i.rectangle.width * container.width, i.rectangle.height * container.height);
999 lrint(container.width * i.rectangle.x),
1000 lrint(container.height * i.rectangle.y)
1006 /* String subtitles (rendered to an image) */
1007 if (!j.string.empty()) {
1008 auto s = render_text(j.string, container, time, vfr);
1009 copy_if(s.begin(), s.end(), back_inserter(captions), [](PositionImage const& image) {
1010 return image.image->size().width && image.image->size().height;
1016 if (captions.empty()) {
1020 return merge (captions, _subtitle_alignment);
1025 Player::emit_video_until(VideoType type, DCPTime time)
1027 LOG_DEBUG_PLAYER("emit_video_until %1; next video time is %2", to_string(time), to_string(_next_video_time[type].get_value_or({})));
1028 auto frame = [this, type](shared_ptr<PlayerVideo> pv, DCPTime time) {
1029 /* We need a delay to give a little wiggle room to ensure that relevant subtitles arrive at the
1030 player before the video that requires them.
1032 _delay.push_back(make_pair(pv, time));
1034 if (pv->eyes() == Eyes::BOTH || pv->eyes() == Eyes::RIGHT) {
1035 _next_video_time[type] = time + one_video_frame();
1038 if (_delay.size() < 3) {
1042 auto to_do = _delay.front();
1044 emit_video(to_do.first, to_do.second);
1047 auto const age_threshold = one_video_frame() * 2;
1049 while (_next_video_time[type].get_value_or({}) < time) {
1050 auto left = _last_video[type][Eyes::LEFT];
1051 auto right = _last_video[type][Eyes::RIGHT];
1052 auto both = _last_video[type][Eyes::BOTH];
1054 auto const next = _next_video_time[type].get_value_or({});
1059 (!both.first || (left.second >= both.second && right.second >= both.second)) &&
1060 (left.second - next) < age_threshold &&
1061 (right.second - next) < age_threshold
1063 frame(left.first, next);
1064 frame(right.first, next);
1065 } else if (both.first && (both.second - next) < age_threshold) {
1066 frame(both.first, next);
1067 LOG_DEBUG_PLAYER("Content %1 selected for DCP %2 (age %3)", to_string(both.second), to_string(next), to_string(both.second - next));
1069 auto film = _film.lock();
1070 if (film && film->three_d()) {
1071 frame(black_player_video_frame(type, Eyes::LEFT), next);
1072 frame(black_player_video_frame(type, Eyes::RIGHT), next);
1074 frame(black_player_video_frame(type, Eyes::BOTH), next);
1076 LOG_DEBUG_PLAYER("Black selected for DCP %1", to_string(next));
1083 Player::video (weak_ptr<Piece> weak_piece, ContentVideo video)
1089 auto piece = weak_piece.lock ();
1094 auto const content_video = piece->content->video;
1095 if (!content_video->use()) {
1099 auto film = _film.lock();
1104 vector<Eyes> eyes_to_emit;
1105 auto const type = content_video->type();
1107 if (!film->three_d()) {
1108 if (video.eyes == Eyes::RIGHT) {
1109 /* 2D film, 3D content: discard right */
1111 } else if (video.eyes == Eyes::LEFT) {
1112 /* 2D film, 3D content: emit left as "both" */
1113 video.eyes = Eyes::BOTH;
1114 eyes_to_emit = { Eyes::BOTH };
1117 if (video.eyes == Eyes::BOTH) {
1118 /* 3D film, 2D content; emit "both" for left and right */
1119 eyes_to_emit = { Eyes::LEFT, Eyes::RIGHT };
1123 if (eyes_to_emit.empty()) {
1124 eyes_to_emit = { video.eyes };
1127 /* Time of the frame we just received within the DCP */
1128 auto const time = content_time_to_dcp(piece, video.time);
1129 LOG_DEBUG_PLAYER("Received video frame %1 %2 eyes %3", to_string(video.time), to_string(time), static_cast<int>(video.eyes));
1131 if (time < piece->content->position()) {
1135 auto ignore_video = std::find_if(
1136 piece->ignore_video.begin(),
1137 piece->ignore_video.end(),
1138 [time](DCPTimePeriod period) { return period.contains(time); }
1140 if (ignore_video != piece->ignore_video.end()) {
1144 if (!_next_video_time[type]) {
1145 /* XXX: round to 24fps for SL? */
1146 _next_video_time[type] = time.round(film->video_frame_rate());
1149 auto scaled_size = content_video->scaled_size(film->frame_size());
1150 DCPOMATIC_ASSERT(scaled_size);
1152 for (auto eyes: eyes_to_emit) {
1154 std::make_shared<PlayerVideo>(
1156 content_video->actual_crop(),
1157 content_video->fade(film, video.time),
1160 video_container_size(type),
1162 content_video->pixel_quanta()
1164 video_container_size(type),
1168 content_video->colour_conversion(),
1169 content_video->range(),
1175 piece->content->end(film)
1181 Player::use_video(shared_ptr<PlayerVideo> pv, DCPTime time, DCPTime end)
1183 _last_video[pv->type()][pv->eyes()] = { pv, time };
1184 if (pv->eyes() != Eyes::LEFT) {
1185 emit_video_until(pv->type(), std::min(time + one_video_frame() / 2, end));
1191 Player::audio (weak_ptr<Piece> weak_piece, AudioStreamPtr stream, ContentAudio content_audio)
1197 DCPOMATIC_ASSERT (content_audio.audio->frames() > 0);
1199 auto piece = weak_piece.lock ();
1204 auto film = _film.lock();
1209 auto content = piece->content->audio;
1210 DCPOMATIC_ASSERT (content);
1212 int const rfr = content->resampled_frame_rate(film);
1214 /* Compute time in the DCP */
1215 auto time = resampled_audio_to_dcp (piece, content_audio.frame);
1217 /* And the end of this block in the DCP */
1218 auto end = time + DCPTime::from_frames(content_audio.audio->frames(), rfr);
1219 LOG_DEBUG_PLAYER("Received audio frame %1 covering %2 to %3 (%4)", content_audio.frame, to_string(time), to_string(end), piece->content->path(0).filename());
1221 /* Remove anything that comes before the start or after the end of the content */
1222 if (time < piece->content->position()) {
1223 auto cut = discard_audio (content_audio.audio, time, piece->content->position());
1225 /* This audio is entirely discarded */
1228 content_audio.audio = cut.first;
1230 } else if (time > piece->content->end(film)) {
1231 /* Discard it all */
1233 } else if (end > piece->content->end(film)) {
1234 Frame const remaining_frames = DCPTime(piece->content->end(film) - time).frames_round(rfr);
1235 if (remaining_frames == 0) {
1238 content_audio.audio = make_shared<AudioBuffers>(content_audio.audio, remaining_frames, 0);
1241 DCPOMATIC_ASSERT (content_audio.audio->frames() > 0);
1245 auto const fade_coeffs = content->fade (stream, content_audio.frame, content_audio.audio->frames(), rfr);
1246 if (content->gain() != 0 || !fade_coeffs.empty()) {
1247 auto gain_buffers = make_shared<AudioBuffers>(content_audio.audio);
1248 if (!fade_coeffs.empty()) {
1249 /* Apply both fade and gain */
1250 DCPOMATIC_ASSERT (fade_coeffs.size() == static_cast<size_t>(gain_buffers->frames()));
1251 auto const channels = gain_buffers->channels();
1252 auto const frames = fade_coeffs.size();
1253 auto data = gain_buffers->data();
1254 auto const gain = db_to_linear (content->gain());
1255 for (auto channel = 0; channel < channels; ++channel) {
1256 for (auto frame = 0U; frame < frames; ++frame) {
1257 data[channel][frame] *= gain * fade_coeffs[frame];
1261 /* Just apply gain */
1262 gain_buffers->apply_gain (content->gain());
1264 content_audio.audio = gain_buffers;
1269 content_audio.audio = remap(content_audio.audio, film->audio_channels(), stream->mapping());
1273 if (_audio_processor && !_disable_audio_processor) {
1274 content_audio.audio = _audio_processor->run(content_audio.audio, film->audio_channels());
1279 _audio_merger.push (content_audio.audio, time);
1280 DCPOMATIC_ASSERT (_stream_states.find (stream) != _stream_states.end ());
1281 _stream_states[stream].last_push_end = time + DCPTime::from_frames(content_audio.audio->frames(), film->audio_frame_rate());
1286 Player::bitmap_text_start (weak_ptr<Piece> weak_piece, weak_ptr<const TextContent> weak_content, ContentBitmapText subtitle)
1292 auto piece = weak_piece.lock ();
1293 auto content = weak_content.lock ();
1294 if (!piece || !content) {
1299 for (auto& sub: subtitle.subs)
1301 /* Apply content's subtitle offsets */
1302 sub.rectangle.x += content->x_offset ();
1303 sub.rectangle.y -= content->y_offset ();
1305 /* Apply a corrective translation to keep the subtitle centred after the scale that is coming up */
1306 sub.rectangle.x -= sub.rectangle.width * ((content->x_scale() - 1) / 2);
1307 sub.rectangle.y -= sub.rectangle.height * ((content->y_scale() - 1) / 2);
1309 /* Apply content's subtitle scale */
1310 sub.rectangle.width *= content->x_scale ();
1311 sub.rectangle.height *= content->y_scale ();
1313 auto image = sub.image;
1315 /* We will scale the subtitle up to fit _video_container_size */
1316 auto const container = video_container_size(VideoType::MAIN);
1317 int const width = sub.rectangle.width * container.width;
1318 int const height = sub.rectangle.height * container.height;
1319 if (width == 0 || height == 0) {
1323 dcp::Size scaled_size (width, height);
1324 ps.bitmap.push_back (BitmapText(image->scale(scaled_size, dcp::YUVToRGB::REC601, image->pixel_format(), Image::Alignment::PADDED, _fast), sub.rectangle));
1327 DCPTime from(content_time_to_dcp(piece, subtitle.from()));
1328 _active_texts[content->type()].add_from(weak_content, ps, from);
1333 Player::plain_text_start (weak_ptr<Piece> weak_piece, weak_ptr<const TextContent> weak_content, ContentStringText subtitle)
1339 auto piece = weak_piece.lock ();
1340 auto content = weak_content.lock ();
1341 auto film = _film.lock();
1342 if (!piece || !content || !film) {
1347 DCPTime const from (content_time_to_dcp (piece, subtitle.from()));
1349 if (from > piece->content->end(film)) {
1353 for (auto s: subtitle.subs) {
1354 s.set_h_position (s.h_position() + content->x_offset());
1355 s.set_v_position (s.v_position() + content->y_offset());
1356 float const xs = content->x_scale();
1357 float const ys = content->y_scale();
1358 float size = s.size();
1360 /* Adjust size to express the common part of the scaling;
1361 e.g. if xs = ys = 0.5 we scale size by 2.
1363 if (xs > 1e-5 && ys > 1e-5) {
1364 size *= 1 / min (1 / xs, 1 / ys);
1368 /* Then express aspect ratio changes */
1369 if (fabs (1.0 - xs / ys) > dcp::ASPECT_ADJUST_EPSILON) {
1370 s.set_aspect_adjust (xs / ys);
1373 s.set_in (dcp::Time(from.seconds(), 1000));
1374 ps.string.push_back (s);
1377 _active_texts[content->type()].add_from(weak_content, ps, from);
1382 Player::subtitle_stop (weak_ptr<Piece> weak_piece, weak_ptr<const TextContent> weak_content, ContentTime to)
1388 auto content = weak_content.lock ();
1393 if (!_active_texts[content->type()].have(weak_content)) {
1397 auto piece = weak_piece.lock ();
1398 auto film = _film.lock();
1399 if (!piece || !film) {
1403 DCPTime const dcp_to = content_time_to_dcp (piece, to);
1405 if (dcp_to > piece->content->end(film)) {
1409 auto from = _active_texts[content->type()].add_to(weak_content, dcp_to);
1411 bool const always = (content->type() == TextType::OPEN_SUBTITLE && _always_burn_open_subtitles);
1412 if (content->use() && !always && !content->burn()) {
1413 Text (from.first, content->type(), content->dcp_track().get_value_or(DCPTextTrack()), DCPTimePeriod(from.second, dcp_to));
1419 Player::seek (DCPTime time, bool accurate)
1421 boost::mutex::scoped_lock lm (_mutex);
1422 LOG_DEBUG_PLAYER("Seek to %1 (%2accurate)", to_string(time), accurate ? "" : "in");
1425 /* We can't seek in this state */
1429 auto film = _film.lock();
1435 _shuffler->clear ();
1440 if (_audio_processor) {
1441 _audio_processor->flush ();
1444 _audio_merger.clear ();
1445 std::for_each(_active_texts.begin(), _active_texts.end(), [](ActiveText& a) { a.clear(); });
1447 for (auto i: _pieces) {
1448 if (time < i->content->position()) {
1449 /* Before; seek to the start of the content. Even if this request is for an inaccurate seek
1450 we must seek this (following) content accurately, otherwise when we come to the end of the current
1451 content we may not start right at the beginning of the next, causing a gap (if the next content has
1452 been trimmed to a point between keyframes, or something).
1454 i->decoder->seek (dcp_to_content_time (i, i->content->position()), true);
1456 } else if (i->content->position() <= time && time < i->content->end(film)) {
1457 /* During; seek to position */
1458 i->decoder->seek (dcp_to_content_time (i, time), accurate);
1461 /* After; this piece is done */
1467 _next_video_time[VideoType::MAIN] = _next_video_time[VideoType::SIGN_LANGUAGE] = time;
1468 _next_audio_time = time;
1470 _next_video_time[VideoType::MAIN] = _next_video_time[VideoType::SIGN_LANGUAGE] = boost::none;
1471 _next_audio_time = boost::none;
1474 _black[VideoType::MAIN].set_position(time);
1475 _black[VideoType::SIGN_LANGUAGE].set_position(time);
1476 _silent.set_position (time);
1478 _last_video[VideoType::MAIN][Eyes::LEFT] = _last_video[VideoType::MAIN][Eyes::RIGHT] = _last_video[VideoType::MAIN][Eyes::BOTH] = {};
1479 _last_video[VideoType::SIGN_LANGUAGE][Eyes::LEFT] = _last_video[VideoType::SIGN_LANGUAGE][Eyes::RIGHT] = _last_video[VideoType::SIGN_LANGUAGE][Eyes::BOTH] = {};
1481 for (auto& state: _stream_states) {
1482 state.second.last_push_end = boost::none;
1488 Player::emit_video(shared_ptr<PlayerVideo> pv, DCPTime time)
1490 if (pv->type() == VideoType::MAIN) {
1491 if (pv->eyes() == Eyes::BOTH || pv->eyes() == Eyes::RIGHT) {
1492 std::for_each(_active_texts.begin(), _active_texts.end(), [time](ActiveText& a) { a.clear_before(time); });
1495 auto subtitles = open_subtitles_for_frame (time);
1497 pv->set_text (subtitles.get ());
1506 Player::emit_audio (shared_ptr<AudioBuffers> data, DCPTime time)
1508 auto film = _film.lock();
1509 DCPOMATIC_ASSERT(film);
1511 /* Log if the assert below is about to fail */
1512 if (_next_audio_time && labs(time.get() - _next_audio_time->get()) > 1) {
1513 film->log()->log(String::compose("Out-of-sequence emit %1 vs %2", to_string(time), to_string(*_next_audio_time)), LogEntry::TYPE_WARNING);
1516 /* This audio must follow on from the previous, allowing for half a sample (at 48kHz) leeway */
1517 DCPOMATIC_ASSERT (!_next_audio_time || labs(time.get() - _next_audio_time->get()) < 2);
1518 Audio(data, time, film->audio_frame_rate());
1519 _next_audio_time = time + DCPTime::from_frames(data->frames(), film->audio_frame_rate());
1524 Player::fill_audio (DCPTimePeriod period)
1526 auto film = _film.lock();
1527 DCPOMATIC_ASSERT(film);
1529 if (period.from == period.to) {
1533 DCPOMATIC_ASSERT (period.from < period.to);
1535 DCPTime t = period.from;
1536 while (t < period.to) {
1537 DCPTime block = min (DCPTime::from_seconds (0.5), period.to - t);
1538 Frame const samples = block.frames_round(film->audio_frame_rate());
1540 auto silence = make_shared<AudioBuffers>(film->audio_channels(), samples);
1541 silence->make_silent ();
1542 emit_audio (silence, t);
1550 Player::one_video_frame () const
1552 auto film = _film.lock();
1553 DCPOMATIC_ASSERT(film);
1555 return DCPTime::from_frames(1, film->video_frame_rate ());
1559 pair<shared_ptr<AudioBuffers>, DCPTime>
1560 Player::discard_audio (shared_ptr<const AudioBuffers> audio, DCPTime time, DCPTime discard_to) const
1562 auto film = _film.lock();
1563 DCPOMATIC_ASSERT(film);
1565 auto const discard_time = discard_to - time;
1566 auto const discard_frames = discard_time.frames_round(film->audio_frame_rate());
1567 auto remaining_frames = audio->frames() - discard_frames;
1568 if (remaining_frames <= 0) {
1569 return make_pair(shared_ptr<AudioBuffers>(), DCPTime());
1571 auto cut = make_shared<AudioBuffers>(audio, remaining_frames, discard_frames);
1572 return make_pair(cut, time + discard_time);
1577 Player::set_dcp_decode_reduction (optional<int> reduction)
1579 ChangeSignaller<Player, int> cc(this, PlayerProperty::DCP_DECODE_REDUCTION);
1581 if (reduction == _dcp_decode_reduction.load()) {
1586 _dcp_decode_reduction = reduction;
1592 Player::content_time_to_dcp (shared_ptr<const Content> content, ContentTime t) const
1594 boost::mutex::scoped_lock lm (_mutex);
1596 for (auto i: _pieces) {
1597 if (i->content == content) {
1598 return content_time_to_dcp (i, t);
1602 /* We couldn't find this content; perhaps things are being changed over */
1607 optional<ContentTime>
1608 Player::dcp_to_content_time (shared_ptr<const Content> content, DCPTime t) const
1610 boost::mutex::scoped_lock lm (_mutex);
1612 for (auto i: _pieces) {
1613 if (i->content == content) {
1614 return dcp_to_content_time (i, t);
1618 /* We couldn't find this content; perhaps things are being changed over */
1623 shared_ptr<const Playlist>
1624 Player::playlist () const
1626 auto film = _film.lock();
1631 return _playlist ? _playlist : film->playlist();
1636 Player::atmos (weak_ptr<Piece> weak_piece, ContentAtmos data)
1642 auto film = _film.lock();
1643 DCPOMATIC_ASSERT(film);
1645 auto piece = weak_piece.lock ();
1646 DCPOMATIC_ASSERT (piece);
1648 auto const vfr = film->video_frame_rate();
1650 DCPTime const dcp_time = DCPTime::from_frames(data.frame, vfr) - DCPTime(piece->content->trim_start(), FrameRateChange(vfr, vfr));
1651 if (dcp_time < piece->content->position() || dcp_time >= (piece->content->end(film))) {
1655 auto ignore_atmos = std::find_if(
1656 piece->ignore_atmos.begin(),
1657 piece->ignore_atmos.end(),
1658 [dcp_time](DCPTimePeriod period) { return period.contains(dcp_time); }
1660 if (ignore_atmos != piece->ignore_atmos.end()) {
1664 Atmos (data.data, dcp_time, data.metadata);
1669 Player::signal_change(ChangeType type, int property)
1671 Change(type, property, false);
1675 /** Must be called from the same thread that calls ::pass() */
1677 Player::set_disable_audio_processor()
1679 _disable_audio_processor = true;
1684 Player::frames_done() const
1686 auto film = _film.lock();
1687 DCPOMATIC_ASSERT(film);
1689 shared_ptr<Piece> earliest_content;
1690 optional<DCPTime> earliest_time;
1691 std::tie(earliest_content, earliest_time) = earliest_piece_and_time();
1693 return earliest_time.get_value_or({}).frames_round(film->video_frame_rate());
1698 Player::progress() const
1700 auto film = _film.lock();
1701 DCPOMATIC_ASSERT(film);
1703 shared_ptr<Piece> earliest_content;
1704 optional<DCPTime> earliest_time;
1705 std::tie(earliest_content, earliest_time) = earliest_piece_and_time();
1707 return static_cast<float>(earliest_time.get_value_or({}).get()) / film->length().get();