Expand Player to support main and sign language video types.
[dcpomatic.git] / src / lib / player.cc
1 /*
2     Copyright (C) 2013-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
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.
10
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.
15
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/>.
18
19 */
20
21
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"
28 #include "config.h"
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"
35 #include "decoder.h"
36 #include "decoder_factory.h"
37 #include "ffmpeg_content.h"
38 #include "film.h"
39 #include "frame_rate_change.h"
40 #include "image.h"
41 #include "image_decoder.h"
42 #include "job.h"
43 #include "log.h"
44 #include "maths_util.h"
45 #include "piece.h"
46 #include "player.h"
47 #include "player_video.h"
48 #include "playlist.h"
49 #include "ratio.h"
50 #include "raw_image_proxy.h"
51 #include "render_text.h"
52 #include "shuffler.h"
53 #include "text_content.h"
54 #include "text_decoder.h"
55 #include "timer.h"
56 #include "video_decoder.h"
57 #include <dcp/reel.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>
62 #include <algorithm>
63 #include <iostream>
64 #include <stdint.h>
65
66 #include "i18n.h"
67
68
69 using std::copy;
70 using std::cout;
71 using std::dynamic_pointer_cast;
72 using std::list;
73 using std::make_pair;
74 using std::make_shared;
75 using std::max;
76 using std::min;
77 using std::pair;
78 using std::shared_ptr;
79 using std::vector;
80 using std::weak_ptr;
81 using boost::optional;
82 using boost::scoped_ptr;
83 #if BOOST_VERSION >= 106100
84 using namespace boost::placeholders;
85 #endif
86 using namespace dcpomatic;
87
88
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;
100
101
102 Player::Player (shared_ptr<const Film> film, Image::Alignment subtitle_alignment)
103         : _film (film)
104         , _suspended (0)
105         , _ignore_video(false)
106         , _ignore_audio(false)
107         , _ignore_text(false)
108         , _always_burn_open_subtitles(false)
109         , _fast(false)
110         , _tolerant (film->tolerant())
111         , _play_referenced(false)
112         , _audio_merger(film->audio_frame_rate())
113         , _subtitle_alignment (subtitle_alignment)
114 {
115         construct ();
116 }
117
118
119 Player::Player (shared_ptr<const Film> film, shared_ptr<const Playlist> playlist_)
120         : _film (film)
121         , _playlist (playlist_)
122         , _suspended (0)
123         , _ignore_video(false)
124         , _ignore_audio(false)
125         , _ignore_text(false)
126         , _always_burn_open_subtitles(false)
127         , _fast(false)
128         , _tolerant (film->tolerant())
129         , _play_referenced(false)
130         , _audio_merger(film->audio_frame_rate())
131 {
132         construct ();
133 }
134
135
136 dcp::Size
137 Player::full_size(VideoType type) const
138 {
139         switch (type) {
140         case VideoType::MAIN:
141         {
142                 auto film = _film.lock();
143                 DCPOMATIC_ASSERT(film);
144                 return film->frame_size();
145         }
146         case VideoType::SIGN_LANGUAGE:
147                 return { 480, 640 };
148         default:
149                 DCPOMATIC_ASSERT(false);
150         }
151 }
152
153
154 void
155 Player::construct ()
156 {
157         connect();
158         set_video_container_size(VideoType::MAIN, full_size(VideoType::MAIN));
159         set_video_container_size(VideoType::SIGN_LANGUAGE, full_size(VideoType::SIGN_LANGUAGE));
160
161         _black_image[VideoType::SIGN_LANGUAGE] = make_shared<Image>(AV_PIX_FMT_RGB24, dcp::Size(SIGN_LANGUAGE_WIDTH, SIGN_LANGUAGE_HEIGHT), Image::Alignment::PADDED);
162
163         film_change(ChangeType::DONE, FilmProperty::AUDIO_PROCESSOR);
164
165         setup_pieces ();
166         seek (DCPTime (), true);
167 }
168
169
170 void
171 Player::connect()
172 {
173         auto film = _film.lock();
174         DCPOMATIC_ASSERT(film);
175
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
178            be first.
179         */
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));
182 }
183
184
185 Player::Player(Player&& other)
186         : _film(other._film)
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)
214 {
215         connect();
216 }
217
218
219 Player&
220 Player::operator=(Player&& other)
221 {
222         if (this == &other) {
223                 return *this;
224         }
225
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;
254
255         connect();
256
257         return *this;
258 }
259
260
261 bool
262 have_video(shared_ptr<const Content> content, VideoType type)
263 {
264         return static_cast<bool>(content->video)
265                 && content->video->use()
266                 && content->can_be_played()
267                 && content->video->type() == type;
268 }
269
270
271 bool
272 have_audio (shared_ptr<const Content> content)
273 {
274         return content->has_mapped_audio() && content->can_be_played();
275 }
276
277
278 void
279 Player::setup_pieces ()
280 {
281         boost::mutex::scoped_lock lm (_mutex);
282
283         auto old_pieces = _pieces;
284         _pieces.clear ();
285
286         auto film = _film.lock();
287         if (!film) {
288                 return;
289         }
290
291         _playback_length = _playlist ? _playlist->length(film) : film->length();
292
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);
299                 });
300
301
302         if (have_threed) {
303                 _shuffler.reset(new Shuffler());
304                 _shuffler->Video.connect(bind(&Player::video, this, _1, _2));
305         }
306
307         for (auto content: playlist()->content()) {
308
309                 if (!content->paths_valid()) {
310                         continue;
311                 }
312
313                 if (_ignore_video && _ignore_audio && content->text.empty()) {
314                         /* We're only interested in text and this content has none */
315                         continue;
316                 }
317
318                 shared_ptr<Decoder> old_decoder;
319                 for (auto j: old_pieces) {
320                         if (j->content == content) {
321                                 old_decoder = j->decoder;
322                                 break;
323                         }
324                 }
325
326                 auto decoder = decoder_factory(film, content, _fast, _tolerant, old_decoder);
327                 DCPOMATIC_ASSERT (decoder);
328
329                 FrameRateChange frc(film, content);
330
331                 if (decoder->video && _ignore_video) {
332                         decoder->video->set_ignore (true);
333                 }
334
335                 if (decoder->audio && _ignore_audio) {
336                         decoder->audio->set_ignore (true);
337                 }
338
339                 if (_ignore_text) {
340                         for (auto i: decoder->text) {
341                                 i->set_ignore (true);
342                         }
343                 }
344
345                 auto dcp = dynamic_pointer_cast<DCPDecoder> (decoder);
346                 if (dcp) {
347                         dcp->set_decode_referenced (_play_referenced);
348                         if (_play_referenced) {
349                                 dcp->set_forced_reduction (_dcp_decode_reduction);
350                         }
351                 }
352
353                 auto piece = make_shared<Piece>(content, decoder, frc);
354                 _pieces.push_back (piece);
355
356                 if (decoder->video) {
357                         if (have_threed) {
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));
360                         } else {
361                                 decoder->video->Data.connect (bind(&Player::video, this, weak_ptr<Piece>(piece), _1));
362                         }
363                 }
364
365                 if (decoder->audio) {
366                         decoder->audio->Data.connect (bind (&Player::audio, this, weak_ptr<Piece> (piece), _1, _2));
367                 }
368
369                 auto j = decoder->text.begin();
370
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)
374                                 );
375                         (*j)->PlainStart.connect (
376                                 bind(&Player::plain_text_start, this, weak_ptr<Piece>(piece), weak_ptr<const TextContent>((*j)->content()), _1)
377                                 );
378                         (*j)->Stop.connect (
379                                 bind(&Player::subtitle_stop, this, weak_ptr<Piece>(piece), weak_ptr<const TextContent>((*j)->content()), _1)
380                                 );
381
382                         ++j;
383                 }
384
385                 if (decoder->atmos) {
386                         decoder->atmos->Data.connect (bind(&Player::atmos, this, weak_ptr<Piece>(piece), _1));
387                 }
388         }
389
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);
395                         }
396                 }
397         }
398
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;
401         };
402
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);
411                                         }
412                                 }
413                         }
414                 }
415         }
416
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);
425                                         }
426                                 }
427                         }
428                 }
429         }
430
431         _have_sign_language = contains_sign_language(playlist_content);
432
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);
436         }
437         _silent = Empty(film, playlist(), bind(&have_audio, _1), _playback_length);
438
439         _next_video_time[VideoType::MAIN] = _next_video_time[VideoType::SIGN_LANGUAGE] = boost::none;
440         _next_audio_time = boost::none;
441 }
442
443
444 void
445 Player::playlist_content_change (ChangeType type, int property, bool frequent)
446 {
447         auto film = _film.lock();
448         if (!film) {
449                 return;
450         }
451
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));
457                         }
458                 }
459         } else {
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.
464                         */
465                         ++_suspended;
466                 } else if (type == ChangeType::DONE) {
467                         /* A change in our content has gone through.  Re-build our pieces. */
468                         setup_pieces ();
469                         --_suspended;
470                 } else if (type == ChangeType::CANCELLED) {
471                         --_suspended;
472                 }
473         }
474
475         Change (type, property, frequent);
476 }
477
478
479 void
480 Player::set_video_container_size(VideoType type, dcp::Size size)
481 {
482         ChangeSignaller<Player, int> cc(this, PlayerProperty::VIDEO_CONTAINER_SIZE);
483
484         if (size == video_container_size(type)) {
485                 cc.abort();
486                 return;
487         }
488
489         boost::mutex::scoped_lock lm(_video_container_size_mutex);
490         _video_container_size[type] = size;
491
492         {
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();
496         }
497 }
498
499
500 void
501 Player::playlist_change (ChangeType type)
502 {
503         if (type == ChangeType::DONE) {
504                 setup_pieces ();
505         }
506         Change (type, PlayerProperty::PLAYLIST, false);
507 }
508
509
510 void
511 Player::film_change(ChangeType type, FilmProperty p)
512 {
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.
516         */
517
518         auto film = _film.lock();
519         if (!film) {
520                 return;
521         }
522
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.
528                 */
529                 if (type == ChangeType::DONE) {
530                         setup_pieces ();
531                 }
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());
537                 }
538         } else if (p == FilmProperty::AUDIO_CHANNELS) {
539                 if (type == ChangeType::DONE) {
540                         boost::mutex::scoped_lock lm (_mutex);
541                         _audio_merger.clear ();
542                 }
543         }
544 }
545
546
547 shared_ptr<PlayerVideo>
548 Player::black_player_video_frame(VideoType type, Eyes eyes) const
549 {
550         boost::mutex::scoped_lock lm(_black_image_mutex);
551
552         auto const image = _black_image[type];
553
554         return std::make_shared<PlayerVideo> (
555                 make_shared<const RawImageProxy>(image),
556                 Crop(),
557                 optional<double>(),
558                 image->size(),
559                 image->size(),
560                 type,
561                 eyes,
562                 Part::WHOLE,
563                 PresetColourConversion::all().front().conversion,
564                 VideoRange::FULL,
565                 std::weak_ptr<Content>(),
566                 boost::optional<dcpomatic::ContentTime>(),
567                 false
568         );
569 }
570
571
572 Frame
573 Player::dcp_to_content_video (shared_ptr<const Piece> piece, DCPTime t) const
574 {
575         auto film = _film.lock();
576         DCPOMATIC_ASSERT(film);
577
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));
581
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).
586
587            Instead we convert the DCPTime using the DCP video rate then account for any skip/repeat.
588         */
589         return s.frames_floor (piece->frc.dcp) / piece->frc.factor ();
590 }
591
592
593 DCPTime
594 Player::content_video_to_dcp (shared_ptr<const Piece> piece, Frame f) const
595 {
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();
599 }
600
601
602 Frame
603 Player::dcp_to_resampled_audio (shared_ptr<const Piece> piece, DCPTime t) const
604 {
605         auto film = _film.lock();
606         DCPOMATIC_ASSERT(film);
607
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());
612 }
613
614
615 DCPTime
616 Player::resampled_audio_to_dcp (shared_ptr<const Piece> piece, Frame f) const
617 {
618         auto film = _film.lock();
619         DCPOMATIC_ASSERT(film);
620
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();
625 }
626
627
628 ContentTime
629 Player::dcp_to_content_time (shared_ptr<const Piece> piece, DCPTime t) const
630 {
631         auto film = _film.lock();
632         DCPOMATIC_ASSERT(film);
633
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());
637 }
638
639
640 DCPTime
641 Player::content_time_to_dcp (shared_ptr<const Piece> piece, ContentTime t) const
642 {
643         return max (DCPTime(), DCPTime(t - piece->content->trim_start(), piece->frc) + piece->content->position());
644 }
645
646
647 vector<shared_ptr<Font>>
648 Player::get_subtitle_fonts ()
649 {
650         boost::mutex::scoped_lock lm (_mutex);
651
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));
657                 }
658         }
659
660         return fonts;
661 }
662
663
664 /** Set this player never to produce any video data */
665 void
666 Player::set_ignore_video ()
667 {
668         ChangeSignaller<Player, int> cc(this, PlayerProperty::IGNORE_VIDEO);
669         _ignore_video = true;
670         setup_pieces();
671 }
672
673
674 void
675 Player::set_ignore_audio ()
676 {
677         ChangeSignaller<Player, int> cc(this, PlayerProperty::IGNORE_AUDIO);
678         _ignore_audio = true;
679         setup_pieces();
680 }
681
682
683 void
684 Player::set_ignore_text ()
685 {
686         ChangeSignaller<Player, int> cc(this, PlayerProperty::IGNORE_TEXT);
687         _ignore_text = true;
688         setup_pieces();
689 }
690
691
692 /** Set the player to always burn open texts into the image regardless of the content settings */
693 void
694 Player::set_always_burn_open_subtitles ()
695 {
696         ChangeSignaller<Player, int> cc(this, PlayerProperty::ALWAYS_BURN_OPEN_SUBTITLES);
697         _always_burn_open_subtitles = true;
698 }
699
700
701 /** Sets up the player to be faster, possibly at the expense of quality */
702 void
703 Player::set_fast ()
704 {
705         _fast = true;
706         setup_pieces();
707 }
708
709
710 void
711 Player::set_play_referenced ()
712 {
713         ChangeSignaller<Player, int> cc(this, PlayerProperty::PLAY_REFERENCED);
714         _play_referenced = true;
715         setup_pieces();
716 }
717
718
719 pair<shared_ptr<Piece>, optional<DCPTime>>
720 Player::earliest_piece_and_time() const
721 {
722         auto film = _film.lock();
723         DCPOMATIC_ASSERT(film);
724
725         shared_ptr<Piece> earliest_content;
726         optional<DCPTime> earliest_time;
727
728         for (auto const& piece: _pieces) {
729                 if (piece->done) {
730                         continue;
731                 }
732
733                 auto const t = content_time_to_dcp(piece, max(piece->decoder->position(), piece->content->trim_start()));
734                 if (t > piece->content->end(film)) {
735                         piece->done = true;
736                 } else {
737
738                         /* Given two choices at the same time, pick the one with texts so we see it before
739                            the video.
740                         */
741                         if (!earliest_time || t < *earliest_time || (t == *earliest_time && !piece->decoder->text.empty())) {
742                                 earliest_time = t;
743                                 earliest_content = piece;
744                         }
745                 }
746         }
747
748         return { earliest_content, earliest_time };
749 }
750
751
752 bool
753 Player::pass ()
754 {
755         boost::mutex::scoped_lock lm (_mutex);
756
757         if (_suspended) {
758                 /* We can't pass in this state */
759                 LOG_DEBUG_PLAYER_NC ("Player is suspended");
760                 return false;
761         }
762
763         auto film = _film.lock();
764
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());
769                 return true;
770         }
771
772         /* Find the decoder or empty which is farthest behind where we are and make it emit some data */
773
774         shared_ptr<Piece> earliest_content;
775         optional<DCPTime> earliest_time;
776         std::tie(earliest_content, earliest_time) = earliest_piece_and_time();
777
778         bool done = false;
779
780         enum {
781                 NONE,
782                 CONTENT,
783                 BLACK,
784                 SILENT
785         } which = NONE;
786
787         optional<VideoType> black_type;
788
789         if (earliest_content) {
790                 which = CONTENT;
791         }
792
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();
796                         which = BLACK;
797                         black_type = type;
798                 }
799         };
800
801         check_black(VideoType::MAIN);
802         check_black(VideoType::SIGN_LANGUAGE);
803
804         if (!_silent.done() && !_ignore_audio && (!earliest_time || _silent.position() < *earliest_time)) {
805                 earliest_time = _silent.position ();
806                 which = SILENT;
807         }
808
809         switch (which) {
810         case CONTENT:
811         {
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);
818                         }
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).
823                                 */
824                                 _next_audio_time = dcp->end(film);
825                         }
826                 }
827                 break;
828         }
829         case BLACK:
830         {
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.
837                          */
838                         _next_video_time[*black_type] = black.position();
839                 }
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);
843                 } else {
844                         use_video(black_player_video_frame(*black_type, Eyes::BOTH), black.position(), black.period_at_position().to);
845                 }
846                 black.set_position(black.position() + one_video_frame());
847                 break;
848         }
849         case SILENT:
850         {
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.
858                         */
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);
864                         }
865                         DCPOMATIC_ASSERT (error < too_much_error);
866                         period.from = *_next_audio_time;
867                 }
868                 if (period.duration() > one_video_frame()) {
869                         period.to = period.from + one_video_frame();
870                 }
871                 fill_audio (period);
872                 _silent.set_position (period.to);
873                 break;
874         }
875         case NONE:
876                 done = true;
877                 break;
878         }
879
880         /* Emit any audio that is ready */
881
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.
887         */
888         constexpr int ignore_streams_behind = 5;
889
890         using state_pair = std::pair<AudioStreamPtr, StreamState>;
891
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); });
895
896         /* Find the 'leading' stream (i.e. the one that pushed data most recently) */
897         auto latest_last_push_end = std::max_element(
898                 have_pushed.begin(),
899                 have_pushed.end(),
900                 [](state_pair const& a, state_pair const& b) { return a.second.last_push_end.get() < b.second.last_push_end.get(); }
901                 );
902
903         std::map<AudioStreamPtr, StreamState> alive_stream_states;
904
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()));
907
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);
912                         } else {
913                                 LOG_DEBUG_PLAYER("Ignoring stream %1 because it is too far behind", i.second.piece->content->path(0));
914                         }
915                 }
916         }
917
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) {
922                         pull_to = position;
923                 }
924         }
925         if (!_silent.done() && _silent.position() < pull_to) {
926                 pull_to = _silent.position();
927         }
928
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);
935                         if (!cut.first) {
936                                 continue;
937                         }
938                         *i = cut;
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));
942                 }
943
944                 emit_audio (i->first, i->second);
945         }
946
947         if (done) {
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());
951                 }
952                 if (_next_video_time[VideoType::SIGN_LANGUAGE] && _have_sign_language) {
953                         emit_video_until(VideoType::SIGN_LANGUAGE, film->length());
954                 }
955
956                 if (_shuffler) {
957                         _shuffler->flush ();
958                 }
959                 for (auto const& i: _delay) {
960                         emit_video(i.first, i.second);
961                 }
962         }
963
964         return done;
965 }
966
967
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
971 {
972         auto film = _film.lock();
973         if (!film) {
974                 return {};
975         }
976
977         list<PositionImage> captions;
978         int const vfr = film->video_frame_rate();
979         auto const container = video_container_size(VideoType::MAIN);
980
981         for (
982                 auto j:
983                 _active_texts[TextType::OPEN_SUBTITLE].get_burnt(DCPTimePeriod(time, time + DCPTime::from_frames(1, vfr)), _always_burn_open_subtitles)
984                 ) {
985
986                 /* Bitmap subtitles */
987                 for (auto i: j.bitmap) {
988                         if (!i.image || i.image->size().width == 0 || i.image->size().height == 0) {
989                                 continue;
990                         }
991
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);
994
995                         captions.push_back (
996                                 PositionImage (
997                                         i.image,
998                                         Position<int> (
999                                                 lrint(container.width * i.rectangle.x),
1000                                                 lrint(container.height * i.rectangle.y)
1001                                                 )
1002                                         )
1003                                 );
1004                 }
1005
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;
1011                         });
1012
1013                 }
1014         }
1015
1016         if (captions.empty()) {
1017                 return {};
1018         }
1019
1020         return merge (captions, _subtitle_alignment);
1021 }
1022
1023
1024 void
1025 Player::emit_video_until(VideoType type, DCPTime time)
1026 {
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.
1031                 */
1032                 _delay.push_back(make_pair(pv, time));
1033
1034                 if (pv->eyes() == Eyes::BOTH || pv->eyes() == Eyes::RIGHT) {
1035                         _next_video_time[type] = time + one_video_frame();
1036                 }
1037
1038                 if (_delay.size() < 3) {
1039                         return;
1040                 }
1041
1042                 auto to_do = _delay.front();
1043                 _delay.pop_front();
1044                 emit_video(to_do.first, to_do.second);
1045         };
1046
1047         auto const age_threshold = one_video_frame() * 2;
1048
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];
1053
1054                 auto const next = _next_video_time[type].get_value_or({});
1055
1056                 if (
1057                         left.first &&
1058                         right.first &&
1059                         (!both.first || (left.second >= both.second && right.second >= both.second)) &&
1060                         (left.second - next) < age_threshold &&
1061                         (right.second - next) < age_threshold
1062                    ) {
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));
1068                 } else {
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);
1073                         } else {
1074                                 frame(black_player_video_frame(type, Eyes::BOTH), next);
1075                         }
1076                         LOG_DEBUG_PLAYER("Black selected for DCP %1", to_string(next));
1077                 }
1078         }
1079 }
1080
1081
1082 void
1083 Player::video (weak_ptr<Piece> weak_piece, ContentVideo video)
1084 {
1085         if (_suspended) {
1086                 return;
1087         }
1088
1089         auto piece = weak_piece.lock ();
1090         if (!piece) {
1091                 return;
1092         }
1093
1094         auto const content_video = piece->content->video;
1095         if (!content_video->use()) {
1096                 return;
1097         }
1098
1099         auto film = _film.lock();
1100         if (!film) {
1101                 return;
1102         }
1103
1104         vector<Eyes> eyes_to_emit;
1105         auto const type = content_video->type();
1106
1107         if (!film->three_d()) {
1108                 if (video.eyes == Eyes::RIGHT) {
1109                         /* 2D film, 3D content: discard right */
1110                         return;
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 };
1115                 }
1116         } else {
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 };
1120                 }
1121         }
1122
1123         if (eyes_to_emit.empty()) {
1124                 eyes_to_emit = { video.eyes };
1125         }
1126
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));
1130
1131         if (time < piece->content->position()) {
1132                 return;
1133         }
1134
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); }
1139                 );
1140         if (ignore_video != piece->ignore_video.end()) {
1141                 return;
1142         }
1143
1144         if (!_next_video_time[type]) {
1145                 /* XXX: round to 24fps for SL? */
1146                 _next_video_time[type] = time.round(film->video_frame_rate());
1147         }
1148
1149         auto scaled_size = content_video->scaled_size(film->frame_size());
1150         DCPOMATIC_ASSERT(scaled_size);
1151
1152         for (auto eyes: eyes_to_emit) {
1153                 use_video(
1154                         std::make_shared<PlayerVideo>(
1155                                 video.image,
1156                                 content_video->actual_crop(),
1157                                 content_video->fade(film, video.time),
1158                                 scale_for_display(
1159                                         *scaled_size,
1160                                         video_container_size(type),
1161                                         full_size(type),
1162                                         content_video->pixel_quanta()
1163                                         ),
1164                                 video_container_size(type),
1165                                 type,
1166                                 eyes,
1167                                 video.part,
1168                                 content_video->colour_conversion(),
1169                                 content_video->range(),
1170                                 piece->content,
1171                                 video.time,
1172                                 false
1173                                 ),
1174                         time,
1175                         piece->content->end(film)
1176                         );
1177         }
1178 }
1179
1180 void
1181 Player::use_video(shared_ptr<PlayerVideo> pv, DCPTime time, DCPTime end)
1182 {
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));
1186         }
1187 }
1188
1189
1190 void
1191 Player::audio (weak_ptr<Piece> weak_piece, AudioStreamPtr stream, ContentAudio content_audio)
1192 {
1193         if (_suspended) {
1194                 return;
1195         }
1196
1197         DCPOMATIC_ASSERT (content_audio.audio->frames() > 0);
1198
1199         auto piece = weak_piece.lock ();
1200         if (!piece) {
1201                 return;
1202         }
1203
1204         auto film = _film.lock();
1205         if (!film) {
1206                 return;
1207         }
1208
1209         auto content = piece->content->audio;
1210         DCPOMATIC_ASSERT (content);
1211
1212         int const rfr = content->resampled_frame_rate(film);
1213
1214         /* Compute time in the DCP */
1215         auto time = resampled_audio_to_dcp (piece, content_audio.frame);
1216
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());
1220
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());
1224                 if (!cut.first) {
1225                         /* This audio is entirely discarded */
1226                         return;
1227                 }
1228                 content_audio.audio = cut.first;
1229                 time = cut.second;
1230         } else if (time > piece->content->end(film)) {
1231                 /* Discard it all */
1232                 return;
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) {
1236                         return;
1237                 }
1238                 content_audio.audio = make_shared<AudioBuffers>(content_audio.audio, remaining_frames, 0);
1239         }
1240
1241         DCPOMATIC_ASSERT (content_audio.audio->frames() > 0);
1242
1243         /* Gain and fade */
1244
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];
1258                                 }
1259                         }
1260                 } else {
1261                         /* Just apply gain */
1262                         gain_buffers->apply_gain (content->gain());
1263                 }
1264                 content_audio.audio = gain_buffers;
1265         }
1266
1267         /* Remap */
1268
1269         content_audio.audio = remap(content_audio.audio, film->audio_channels(), stream->mapping());
1270
1271         /* Process */
1272
1273         if (_audio_processor && !_disable_audio_processor) {
1274                 content_audio.audio = _audio_processor->run(content_audio.audio, film->audio_channels());
1275         }
1276
1277         /* Push */
1278
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());
1282 }
1283
1284
1285 void
1286 Player::bitmap_text_start (weak_ptr<Piece> weak_piece, weak_ptr<const TextContent> weak_content, ContentBitmapText subtitle)
1287 {
1288         if (_suspended) {
1289                 return;
1290         }
1291
1292         auto piece = weak_piece.lock ();
1293         auto content = weak_content.lock ();
1294         if (!piece || !content) {
1295                 return;
1296         }
1297
1298         PlayerText ps;
1299         for (auto& sub: subtitle.subs)
1300         {
1301                 /* Apply content's subtitle offsets */
1302                 sub.rectangle.x += content->x_offset ();
1303                 sub.rectangle.y -= content->y_offset ();
1304
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);
1308
1309                 /* Apply content's subtitle scale */
1310                 sub.rectangle.width *= content->x_scale ();
1311                 sub.rectangle.height *= content->y_scale ();
1312
1313                 auto image = sub.image;
1314
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) {
1320                         return;
1321                 }
1322
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));
1325         }
1326
1327         DCPTime from(content_time_to_dcp(piece, subtitle.from()));
1328         _active_texts[content->type()].add_from(weak_content, ps, from);
1329 }
1330
1331
1332 void
1333 Player::plain_text_start (weak_ptr<Piece> weak_piece, weak_ptr<const TextContent> weak_content, ContentStringText subtitle)
1334 {
1335         if (_suspended) {
1336                 return;
1337         }
1338
1339         auto piece = weak_piece.lock ();
1340         auto content = weak_content.lock ();
1341         auto film = _film.lock();
1342         if (!piece || !content || !film) {
1343                 return;
1344         }
1345
1346         PlayerText ps;
1347         DCPTime const from (content_time_to_dcp (piece, subtitle.from()));
1348
1349         if (from > piece->content->end(film)) {
1350                 return;
1351         }
1352
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();
1359
1360                 /* Adjust size to express the common part of the scaling;
1361                    e.g. if xs = ys = 0.5 we scale size by 2.
1362                 */
1363                 if (xs > 1e-5 && ys > 1e-5) {
1364                         size *= 1 / min (1 / xs, 1 / ys);
1365                 }
1366                 s.set_size (size);
1367
1368                 /* Then express aspect ratio changes */
1369                 if (fabs (1.0 - xs / ys) > dcp::ASPECT_ADJUST_EPSILON) {
1370                         s.set_aspect_adjust (xs / ys);
1371                 }
1372
1373                 s.set_in (dcp::Time(from.seconds(), 1000));
1374                 ps.string.push_back (s);
1375         }
1376
1377         _active_texts[content->type()].add_from(weak_content, ps, from);
1378 }
1379
1380
1381 void
1382 Player::subtitle_stop (weak_ptr<Piece> weak_piece, weak_ptr<const TextContent> weak_content, ContentTime to)
1383 {
1384         if (_suspended) {
1385                 return;
1386         }
1387
1388         auto content = weak_content.lock ();
1389         if (!content) {
1390                 return;
1391         }
1392
1393         if (!_active_texts[content->type()].have(weak_content)) {
1394                 return;
1395         }
1396
1397         auto piece = weak_piece.lock ();
1398         auto film = _film.lock();
1399         if (!piece || !film) {
1400                 return;
1401         }
1402
1403         DCPTime const dcp_to = content_time_to_dcp (piece, to);
1404
1405         if (dcp_to > piece->content->end(film)) {
1406                 return;
1407         }
1408
1409         auto from = _active_texts[content->type()].add_to(weak_content, dcp_to);
1410
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));
1414         }
1415 }
1416
1417
1418 void
1419 Player::seek (DCPTime time, bool accurate)
1420 {
1421         boost::mutex::scoped_lock lm (_mutex);
1422         LOG_DEBUG_PLAYER("Seek to %1 (%2accurate)", to_string(time), accurate ? "" : "in");
1423
1424         if (_suspended) {
1425                 /* We can't seek in this state */
1426                 return;
1427         }
1428
1429         auto film = _film.lock();
1430         if (!film) {
1431                 return;
1432         }
1433
1434         if (_shuffler) {
1435                 _shuffler->clear ();
1436         }
1437
1438         _delay.clear ();
1439
1440         if (_audio_processor) {
1441                 _audio_processor->flush ();
1442         }
1443
1444         _audio_merger.clear ();
1445         std::for_each(_active_texts.begin(), _active_texts.end(), [](ActiveText& a) { a.clear(); });
1446
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).
1453                         */
1454                         i->decoder->seek (dcp_to_content_time (i, i->content->position()), true);
1455                         i->done = false;
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);
1459                         i->done = false;
1460                 } else {
1461                         /* After; this piece is done */
1462                         i->done = true;
1463                 }
1464         }
1465
1466         if (accurate) {
1467                 _next_video_time[VideoType::MAIN] = _next_video_time[VideoType::SIGN_LANGUAGE] = time;
1468                 _next_audio_time = time;
1469         } else {
1470                 _next_video_time[VideoType::MAIN] = _next_video_time[VideoType::SIGN_LANGUAGE] = boost::none;
1471                 _next_audio_time = boost::none;
1472         }
1473
1474         _black[VideoType::MAIN].set_position(time);
1475         _black[VideoType::SIGN_LANGUAGE].set_position(time);
1476         _silent.set_position (time);
1477
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] = {};
1480
1481         for (auto& state: _stream_states) {
1482                 state.second.last_push_end = boost::none;
1483         }
1484 }
1485
1486
1487 void
1488 Player::emit_video(shared_ptr<PlayerVideo> pv, DCPTime time)
1489 {
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); });
1493                 }
1494
1495                 auto subtitles = open_subtitles_for_frame (time);
1496                 if (subtitles) {
1497                         pv->set_text (subtitles.get ());
1498                 }
1499         }
1500
1501         Video (pv, time);
1502 }
1503
1504
1505 void
1506 Player::emit_audio (shared_ptr<AudioBuffers> data, DCPTime time)
1507 {
1508         auto film = _film.lock();
1509         DCPOMATIC_ASSERT(film);
1510
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);
1514         }
1515
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());
1520 }
1521
1522
1523 void
1524 Player::fill_audio (DCPTimePeriod period)
1525 {
1526         auto film = _film.lock();
1527         DCPOMATIC_ASSERT(film);
1528
1529         if (period.from == period.to) {
1530                 return;
1531         }
1532
1533         DCPOMATIC_ASSERT (period.from < period.to);
1534
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());
1539                 if (samples) {
1540                         auto silence = make_shared<AudioBuffers>(film->audio_channels(), samples);
1541                         silence->make_silent ();
1542                         emit_audio (silence, t);
1543                 }
1544                 t += block;
1545         }
1546 }
1547
1548
1549 DCPTime
1550 Player::one_video_frame () const
1551 {
1552         auto film = _film.lock();
1553         DCPOMATIC_ASSERT(film);
1554
1555         return DCPTime::from_frames(1, film->video_frame_rate ());
1556 }
1557
1558
1559 pair<shared_ptr<AudioBuffers>, DCPTime>
1560 Player::discard_audio (shared_ptr<const AudioBuffers> audio, DCPTime time, DCPTime discard_to) const
1561 {
1562         auto film = _film.lock();
1563         DCPOMATIC_ASSERT(film);
1564
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());
1570         }
1571         auto cut = make_shared<AudioBuffers>(audio, remaining_frames, discard_frames);
1572         return make_pair(cut, time + discard_time);
1573 }
1574
1575
1576 void
1577 Player::set_dcp_decode_reduction (optional<int> reduction)
1578 {
1579         ChangeSignaller<Player, int> cc(this, PlayerProperty::DCP_DECODE_REDUCTION);
1580
1581         if (reduction == _dcp_decode_reduction.load()) {
1582                 cc.abort();
1583                 return;
1584         }
1585
1586         _dcp_decode_reduction = reduction;
1587         setup_pieces();
1588 }
1589
1590
1591 optional<DCPTime>
1592 Player::content_time_to_dcp (shared_ptr<const Content> content, ContentTime t) const
1593 {
1594         boost::mutex::scoped_lock lm (_mutex);
1595
1596         for (auto i: _pieces) {
1597                 if (i->content == content) {
1598                         return content_time_to_dcp (i, t);
1599                 }
1600         }
1601
1602         /* We couldn't find this content; perhaps things are being changed over */
1603         return {};
1604 }
1605
1606
1607 optional<ContentTime>
1608 Player::dcp_to_content_time (shared_ptr<const Content> content, DCPTime t) const
1609 {
1610         boost::mutex::scoped_lock lm (_mutex);
1611
1612         for (auto i: _pieces) {
1613                 if (i->content == content) {
1614                         return dcp_to_content_time (i, t);
1615                 }
1616         }
1617
1618         /* We couldn't find this content; perhaps things are being changed over */
1619         return {};
1620 }
1621
1622
1623 shared_ptr<const Playlist>
1624 Player::playlist () const
1625 {
1626         auto film = _film.lock();
1627         if (!film) {
1628                 return {};
1629         }
1630
1631         return _playlist ? _playlist : film->playlist();
1632 }
1633
1634
1635 void
1636 Player::atmos (weak_ptr<Piece> weak_piece, ContentAtmos data)
1637 {
1638         if (_suspended) {
1639                 return;
1640         }
1641
1642         auto film = _film.lock();
1643         DCPOMATIC_ASSERT(film);
1644
1645         auto piece = weak_piece.lock ();
1646         DCPOMATIC_ASSERT (piece);
1647
1648         auto const vfr = film->video_frame_rate();
1649
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))) {
1652                 return;
1653         }
1654
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); }
1659                 );
1660         if (ignore_atmos != piece->ignore_atmos.end()) {
1661                 return;
1662         }
1663
1664         Atmos (data.data, dcp_time, data.metadata);
1665 }
1666
1667
1668 void
1669 Player::signal_change(ChangeType type, int property)
1670 {
1671         Change(type, property, false);
1672 }
1673
1674
1675 /** Must be called from the same thread that calls ::pass() */
1676 void
1677 Player::set_disable_audio_processor()
1678 {
1679         _disable_audio_processor = true;
1680 }
1681
1682
1683 Frame
1684 Player::frames_done() const
1685 {
1686         auto film = _film.lock();
1687         DCPOMATIC_ASSERT(film);
1688
1689         shared_ptr<Piece> earliest_content;
1690         optional<DCPTime> earliest_time;
1691         std::tie(earliest_content, earliest_time) = earliest_piece_and_time();
1692
1693         return earliest_time.get_value_or({}).frames_round(film->video_frame_rate());
1694 }
1695
1696
1697 float
1698 Player::progress() const
1699 {
1700         auto film = _film.lock();
1701         DCPOMATIC_ASSERT(film);
1702
1703         shared_ptr<Piece> earliest_content;
1704         optional<DCPTime> earliest_time;
1705         std::tie(earliest_content, earliest_time) = earliest_piece_and_time();
1706
1707         return static_cast<float>(earliest_time.get_value_or({}).get()) / film->length().get();
1708 }