Fix black borders around the preview in some cases (#2331).
[dcpomatic.git] / src / wx / film_viewer.cc
1 /*
2     Copyright (C) 2012-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 /** @file  src/film_viewer.cc
23  *  @brief A wx widget to view a preview of a Film.
24  */
25
26
27 #include "closed_captions_dialog.h"
28 #include "film_viewer.h"
29 #include "gl_video_view.h"
30 #include "nag_dialog.h"
31 #include "playhead_to_frame_dialog.h"
32 #include "playhead_to_timecode_dialog.h"
33 #include "simple_video_view.h"
34 #include "wx_util.h"
35 #include "lib/butler.h"
36 #include "lib/compose.hpp"
37 #include "lib/config.h"
38 #include "lib/dcpomatic_log.h"
39 #include "lib/examine_content_job.h"
40 #include "lib/exceptions.h"
41 #include "lib/film.h"
42 #include "lib/filter.h"
43 #include "lib/image.h"
44 #include "lib/job_manager.h"
45 #include "lib/log.h"
46 #include "lib/player.h"
47 #include "lib/player_video.h"
48 #include "lib/ratio.h"
49 #include "lib/text_content.h"
50 #include "lib/timer.h"
51 #include "lib/util.h"
52 #include "lib/video_content.h"
53 #include "lib/video_decoder.h"
54 #include <dcp/exceptions.h>
55 #include <dcp/warnings.h>
56 extern "C" {
57 #include <libavutil/pixfmt.h>
58 }
59 LIBDCP_DISABLE_WARNINGS
60 #include <wx/tglbtn.h>
61 LIBDCP_ENABLE_WARNINGS
62 #include <iomanip>
63
64
65 using std::bad_alloc;
66 using std::dynamic_pointer_cast;
67 using std::make_shared;
68 using std::max;
69 using std::shared_ptr;
70 using std::string;
71 using std::vector;
72 using boost::optional;
73 #if BOOST_VERSION >= 106100
74 using namespace boost::placeholders;
75 #endif
76 using dcp::Size;
77 using namespace dcpomatic;
78
79
80 static
81 int
82 rtaudio_callback (void* out, void *, unsigned int frames, double, RtAudioStreamStatus, void* data)
83 {
84         return reinterpret_cast<FilmViewer*>(data)->audio_callback (out, frames);
85 }
86
87
88 FilmViewer::FilmViewer (wxWindow* p)
89         : _audio (DCPOMATIC_RTAUDIO_API)
90         , _closed_captions_dialog (new ClosedCaptionsDialog(p, this))
91 {
92 #if wxCHECK_VERSION(3, 1, 0)
93         switch (Config::instance()->video_view_type()) {
94         case Config::VIDEO_VIEW_OPENGL:
95                 _video_view = std::make_shared<GLVideoView>(this, p);
96                 break;
97         case Config::VIDEO_VIEW_SIMPLE:
98                 _video_view = std::make_shared<SimpleVideoView>(this, p);
99                 break;
100         }
101 #else
102         _video_view = std::make_shared<SimpleVideoView>(this, p);
103 #endif
104
105         _video_view->Sized.connect (boost::bind(&FilmViewer::video_view_sized, this));
106         _video_view->TooManyDropped.connect (boost::bind(boost::ref(TooManyDropped)));
107
108         set_film (shared_ptr<Film>());
109
110         _config_changed_connection = Config::instance()->Changed.connect(bind(&FilmViewer::config_changed, this, _1));
111         config_changed (Config::SOUND_OUTPUT);
112 }
113
114
115 FilmViewer::~FilmViewer ()
116 {
117         stop ();
118 }
119
120
121 /** Ask for ::idle_handler() to be called next time we are idle */
122 void
123 FilmViewer::request_idle_display_next_frame ()
124 {
125         if (_idle_get) {
126                 return;
127         }
128
129         _idle_get = true;
130         DCPOMATIC_ASSERT (signal_manager);
131         signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
132 }
133
134
135 void
136 FilmViewer::idle_handler ()
137 {
138         if (!_idle_get) {
139                 return;
140         }
141
142         if (_video_view->display_next_frame(true) == VideoView::AGAIN) {
143                 /* get() could not complete quickly so we'll try again later */
144                 signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
145         } else {
146                 _idle_get = false;
147         }
148 }
149
150
151 void
152 FilmViewer::set_film (shared_ptr<Film> film)
153 {
154         if (_film == film) {
155                 return;
156         }
157
158         _film = film;
159
160         _video_view->clear ();
161         _closed_captions_dialog->clear ();
162
163         if (!_film) {
164                 _player.reset ();
165                 recreate_butler ();
166                 _video_view->update ();
167                 return;
168         }
169
170         try {
171                 _player = make_shared<Player>(_film, _optimise_for_j2k ? Image::Alignment::COMPACT : Image::Alignment::PADDED);
172                 _player->set_fast ();
173                 if (_dcp_decode_reduction) {
174                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
175                 }
176         } catch (bad_alloc &) {
177                 error_dialog (_video_view->get(), _("There is not enough free memory to do that."));
178                 _film.reset ();
179                 return;
180         }
181
182         _player->set_always_burn_open_subtitles ();
183         _player->set_play_referenced ();
184
185         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
186         _film->LengthChange.connect (boost::bind(&FilmViewer::film_length_change, this));
187         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
188
189         film_change (ChangeType::DONE, Film::Property::VIDEO_FRAME_RATE);
190         film_change (ChangeType::DONE, Film::Property::THREE_D);
191         film_length_change ();
192
193         /* Keep about 1 second's worth of history samples */
194         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
195
196         _closed_captions_dialog->update_tracks (_film);
197
198         recreate_butler ();
199
200         calculate_sizes ();
201         slow_refresh ();
202 }
203
204
205 void
206 FilmViewer::recreate_butler ()
207 {
208         suspend ();
209         _butler.reset ();
210
211         if (!_film) {
212                 resume ();
213                 return;
214         }
215
216 #if wxCHECK_VERSION(3, 1, 0)
217         auto const j2k_gl_optimised = dynamic_pointer_cast<GLVideoView>(_video_view) && _optimise_for_j2k;
218 #else
219         auto const j2k_gl_optimised = false;
220 #endif
221
222         _butler = std::make_shared<Butler>(
223                 _film,
224                 _player,
225                 Config::instance()->audio_mapping(_audio_channels),
226                 _audio_channels,
227                 boost::bind(&PlayerVideo::force, AV_PIX_FMT_RGB24),
228                 VideoRange::FULL,
229                 j2k_gl_optimised ? Image::Alignment::COMPACT : Image::Alignment::PADDED,
230                 true,
231                 j2k_gl_optimised,
232                 (Config::instance()->sound() && _audio.isStreamOpen()) ? Butler::Audio::ENABLED : Butler::Audio::DISABLED
233                 );
234
235         _closed_captions_dialog->set_butler (_butler);
236
237         resume ();
238 }
239
240
241 void
242 FilmViewer::set_outline_content (bool o)
243 {
244         _outline_content = o;
245         _video_view->update ();
246 }
247
248
249 void
250 FilmViewer::set_outline_subtitles (optional<dcpomatic::Rect<double>> rect)
251 {
252         _outline_subtitles = rect;
253         _video_view->update ();
254 }
255
256
257 void
258 FilmViewer::set_eyes (Eyes e)
259 {
260         _video_view->set_eyes (e);
261         slow_refresh ();
262 }
263
264
265 void
266 FilmViewer::video_view_sized ()
267 {
268         calculate_sizes ();
269         if (!quick_refresh()) {
270                 slow_refresh ();
271         }
272 }
273
274
275 void
276 FilmViewer::calculate_sizes ()
277 {
278         if (!_film || !_player) {
279                 return;
280         }
281
282         auto const container = _film->container ();
283
284         auto const scale = dpi_scale_factor (_video_view->get());
285         int const video_view_width = std::round(_video_view->get()->GetSize().x * scale);
286         int const video_view_height = std::round(_video_view->get()->GetSize().y * scale);
287
288         auto const view_ratio = float(video_view_width) / video_view_height;
289         auto const film_ratio = container ? container->ratio () : 1.78;
290
291         dcp::Size out_size;
292         if (view_ratio < film_ratio) {
293                 /* panel is less widscreen than the film; clamp width */
294                 out_size.width = video_view_width;
295                 out_size.height = lrintf (out_size.width / film_ratio);
296         } else {
297                 /* panel is more widescreen than the film; clamp height */
298                 out_size.height = video_view_height;
299                 out_size.width = lrintf (out_size.height * film_ratio);
300         }
301
302         /* Catch silly values */
303         out_size.width = max (64, out_size.width);
304         out_size.height = max (64, out_size.height);
305
306         /* Make sure the video container sizes are always a multiple of 2 so that
307          * we don't get gaps with subsampled sources (e.g. YUV420)
308          */
309         if (out_size.width % 2) {
310                 out_size.width++;
311         }
312         if (out_size.height % 2) {
313                 out_size.height++;
314         }
315
316         _player->set_video_container_size (out_size);
317 }
318
319
320 void
321 FilmViewer::suspend ()
322 {
323         ++_suspended;
324         if (_audio.isStreamRunning()) {
325                 _audio.abortStream();
326         }
327 }
328
329
330 void
331 FilmViewer::start_audio_stream_if_open ()
332 {
333         if (_audio.isStreamOpen()) {
334                 _audio.setStreamTime (_video_view->position().seconds());
335                 try {
336                         _audio.startStream ();
337                 } catch (RtAudioError& e) {
338                         _audio_channels = 0;
339                         error_dialog (
340                                 _video_view->get(),
341                                 _("There was a problem starting audio playback.  Please try another audio output device in Preferences."), std_to_wx(e.what())
342                                 );
343                 }
344         }
345 }
346
347
348 void
349 FilmViewer::resume ()
350 {
351         DCPOMATIC_ASSERT (_suspended > 0);
352         --_suspended;
353         if (_playing && !_suspended) {
354                 start_audio_stream_if_open ();
355                 _video_view->start ();
356         }
357 }
358
359
360 void
361 FilmViewer::start ()
362 {
363         if (!_film) {
364                 return;
365         }
366
367         auto v = PlaybackPermitted ();
368         if (v && !*v) {
369                 /* Computer says no */
370                 return;
371         }
372
373         /* We are about to set up the audio stream from the position of the video view.
374            If there is `lazy' seek in progress we need to wait for it to go through so that
375            _video_view->position() gives us a sensible answer.
376          */
377         while (_idle_get) {
378                 idle_handler ();
379         }
380
381         /* Take the video view's idea of position as our `playhead' and start the
382            audio stream (which is the timing reference) there.
383          */
384         start_audio_stream_if_open ();
385
386         _playing = true;
387         /* Calling start() below may directly result in Stopped being emitted, and if that
388          * happens we want it to come after the Started signal, so do that first.
389          */
390         Started ();
391         _video_view->start ();
392 }
393
394
395 bool
396 FilmViewer::stop ()
397 {
398         if (_audio.isStreamRunning()) {
399                 /* stop stream and discard any remaining queued samples */
400                 _audio.abortStream ();
401         }
402
403         if (!_playing) {
404                 return false;
405         }
406
407         _playing = false;
408         _video_view->stop ();
409         Stopped ();
410
411         _video_view->rethrow ();
412         return true;
413 }
414
415
416 void
417 FilmViewer::player_change (ChangeType type, int property, bool frequent)
418 {
419         if (type != ChangeType::DONE || frequent) {
420                 return;
421         }
422
423         if (_coalesce_player_changes) {
424                 _pending_player_changes.push_back (property);
425                 return;
426         }
427
428         player_change ({property});
429 }
430
431
432 void
433 FilmViewer::player_change (vector<int> properties)
434 {
435         calculate_sizes ();
436
437         bool try_quick_refresh = false;
438         bool update_ccap_tracks = false;
439
440         for (auto i: properties) {
441                 if (
442                         i == VideoContentProperty::CROP ||
443                         i == VideoContentProperty::CUSTOM_RATIO ||
444                         i == VideoContentProperty::CUSTOM_SIZE ||
445                         i == VideoContentProperty::FADE_IN ||
446                         i == VideoContentProperty::FADE_OUT ||
447                         i == VideoContentProperty::COLOUR_CONVERSION ||
448                         i == PlayerProperty::VIDEO_CONTAINER_SIZE ||
449                         i == PlayerProperty::FILM_CONTAINER
450                    ) {
451                         try_quick_refresh = true;
452                 }
453
454                 if (i == TextContentProperty::USE || i == TextContentProperty::TYPE || i == TextContentProperty::DCP_TRACK) {
455                         update_ccap_tracks = true;
456                 }
457         }
458
459         if (!try_quick_refresh || !quick_refresh()) {
460                 slow_refresh ();
461         }
462
463         if (update_ccap_tracks) {
464                 _closed_captions_dialog->update_tracks (_film);
465         }
466 }
467
468
469 void
470 FilmViewer::film_change (ChangeType type, Film::Property p)
471 {
472         if (type != ChangeType::DONE) {
473                 return;
474         }
475
476         if (p == Film::Property::AUDIO_CHANNELS) {
477                 recreate_butler ();
478         } else if (p == Film::Property::VIDEO_FRAME_RATE) {
479                 _video_view->set_video_frame_rate (_film->video_frame_rate());
480         } else if (p == Film::Property::THREE_D) {
481                 _video_view->set_three_d (_film->three_d());
482         } else if (p == Film::Property::CONTENT) {
483                 _closed_captions_dialog->update_tracks (_film);
484         }
485 }
486
487
488 void
489 FilmViewer::film_length_change ()
490 {
491         _video_view->set_length (_film->length());
492 }
493
494
495 /** Re-get the current frame slowly by seeking */
496 void
497 FilmViewer::slow_refresh ()
498 {
499         seek (_video_view->position(), true);
500 }
501
502
503 /** Try to re-get the current frame quickly by resetting the metadata
504  *  in the PlayerVideo that we used last time.
505  *  @return true if this was possible, false if not.
506  */
507 bool
508 FilmViewer::quick_refresh ()
509 {
510         if (!_video_view || !_film || !_player) {
511                 return true;
512         }
513         return _video_view->reset_metadata (_film, _player->video_container_size());
514 }
515
516
517 void
518 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
519 {
520         auto dt = _player->content_time_to_dcp (content, t);
521         if (dt) {
522                 seek (*dt, accurate);
523         }
524 }
525
526
527 void
528 FilmViewer::set_coalesce_player_changes (bool c)
529 {
530         _coalesce_player_changes = c;
531
532         if (!c) {
533                 player_change (_pending_player_changes);
534                 _pending_player_changes.clear ();
535         }
536 }
537
538
539 void
540 FilmViewer::seek (DCPTime t, bool accurate)
541 {
542         if (!_butler) {
543                 return;
544         }
545
546         if (t < DCPTime()) {
547                 t = DCPTime ();
548         }
549
550         if (t >= _film->length()) {
551                 t = _film->length() - one_video_frame();
552         }
553
554         suspend ();
555
556         _closed_captions_dialog->clear ();
557         _butler->seek (t, accurate);
558
559         if (!_playing) {
560                 /* We're not playing, so let the GUI thread get on and
561                    come back later to get the next frame after the seek.
562                 */
563                 request_idle_display_next_frame ();
564         } else {
565                 /* We're going to start playing again straight away
566                    so wait for the seek to finish.
567                 */
568                 while (_video_view->display_next_frame(false) == VideoView::AGAIN) {}
569         }
570
571         resume ();
572 }
573
574
575 void
576 FilmViewer::config_changed (Config::Property p)
577 {
578         if (p == Config::AUDIO_MAPPING) {
579                 recreate_butler ();
580                 return;
581         }
582
583         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
584                 return;
585         }
586
587         if (_audio.isStreamOpen ()) {
588                 _audio.closeStream ();
589         }
590
591         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
592                 unsigned int st = 0;
593                 if (Config::instance()->sound_output()) {
594                         while (st < _audio.getDeviceCount()) {
595                                 try {
596                                         if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
597                                                 break;
598                                         }
599                                 } catch (RtAudioError&) {
600                                         /* Something went wrong with that device so we don't want to use it anyway */
601                                 }
602                                 ++st;
603                         }
604                         if (st == _audio.getDeviceCount()) {
605                                 st = _audio.getDefaultOutputDevice();
606                         }
607                 } else {
608                         st = _audio.getDefaultOutputDevice();
609                 }
610
611                 try {
612                         _audio_channels = _audio.getDeviceInfo(st).outputChannels;
613                         RtAudio::StreamParameters sp;
614                         sp.deviceId = st;
615                         sp.nChannels = _audio_channels;
616                         sp.firstChannel = 0;
617                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
618                 } catch (RtAudioError& e) {
619                         _audio_channels = 0;
620                         error_dialog (
621                                 _video_view->get(),
622                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
623                                 );
624                 }
625                 recreate_butler ();
626
627         } else {
628                 _audio_channels = 0;
629                 recreate_butler ();
630         }
631 }
632
633
634 DCPTime
635 FilmViewer::uncorrected_time () const
636 {
637         if (_audio.isStreamRunning()) {
638                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
639         }
640
641         return _video_view->position();
642 }
643
644
645 optional<DCPTime>
646 FilmViewer::audio_time () const
647 {
648         if (!_audio.isStreamRunning()) {
649                 return {};
650         }
651
652         return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
653                 DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
654 }
655
656
657 DCPTime
658 FilmViewer::time () const
659 {
660         return audio_time().get_value_or(_video_view->position());
661 }
662
663
664 int
665 FilmViewer::audio_callback (void* out_p, unsigned int frames)
666 {
667         while (true) {
668                 auto t = _butler->get_audio (Butler::Behaviour::NON_BLOCKING, reinterpret_cast<float*> (out_p), frames);
669                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
670                         /* There was an underrun or this audio is on time; carry on */
671                         break;
672                 }
673                 /* The audio we just got was (very) late; drop it and get some more. */
674         }
675
676         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
677         if (lm) {
678                 _latency_history.push_back (_audio.getStreamLatency ());
679                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
680                         _latency_history.pop_front ();
681                 }
682         }
683
684         return 0;
685 }
686
687
688 Frame
689 FilmViewer::average_latency () const
690 {
691         boost::mutex::scoped_lock lm (_latency_history_mutex);
692         if (_latency_history.empty()) {
693                 return 0;
694         }
695
696         Frame total = 0;
697         for (auto i: _latency_history) {
698                 total += i;
699         }
700
701         return total / _latency_history.size();
702 }
703
704
705 void
706 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
707 {
708         _dcp_decode_reduction = reduction;
709         if (_player) {
710                 _player->set_dcp_decode_reduction (reduction);
711         }
712 }
713
714
715 optional<int>
716 FilmViewer::dcp_decode_reduction () const
717 {
718         return _dcp_decode_reduction;
719 }
720
721
722 optional<ContentTime>
723 FilmViewer::position_in_content (shared_ptr<const Content> content) const
724 {
725         return _player->dcp_to_content_time (content, position());
726 }
727
728
729 DCPTime
730 FilmViewer::one_video_frame () const
731 {
732         return DCPTime::from_frames (1, _film ? _film->video_frame_rate() : 24);
733 }
734
735
736 /** Open a dialog box showing our film's closed captions */
737 void
738 FilmViewer::show_closed_captions ()
739 {
740         _closed_captions_dialog->Show();
741 }
742
743
744 void
745 FilmViewer::seek_by (DCPTime by, bool accurate)
746 {
747         seek (_video_view->position() + by, accurate);
748 }
749
750
751 void
752 FilmViewer::set_pad_black (bool p)
753 {
754         _pad_black = p;
755 }
756
757
758 /** Called when a player has finished the current film.
759  *  May be called from a non-UI thread.
760  */
761 void
762 FilmViewer::finished ()
763 {
764         emit (boost::bind(&FilmViewer::ui_finished, this));
765 }
766
767
768 /** Called by finished() in the UI thread */
769 void
770 FilmViewer::ui_finished ()
771 {
772         stop ();
773         Finished ();
774 }
775
776
777 int
778 FilmViewer::dropped () const
779 {
780         return _video_view->dropped ();
781 }
782
783
784 int
785 FilmViewer::errored () const
786 {
787         return _video_view->errored ();
788 }
789
790
791 int
792 FilmViewer::gets () const
793 {
794         return _video_view->gets ();
795 }
796
797
798 void
799 FilmViewer::image_changed (shared_ptr<PlayerVideo> pv)
800 {
801         emit (boost::bind(boost::ref(ImageChanged), pv));
802 }
803
804
805 void
806 FilmViewer::set_optimise_for_j2k (bool o)
807 {
808         _optimise_for_j2k = o;
809         _video_view->set_optimise_for_j2k (o);
810 }
811
812
813 void
814 FilmViewer::set_crop_guess (dcpomatic::Rect<float> crop)
815 {
816         if (crop != _crop_guess) {
817                 _crop_guess = crop;
818                 _video_view->update ();
819         }
820 }
821
822
823 void
824 FilmViewer::unset_crop_guess ()
825 {
826         _crop_guess = boost::none;
827         _video_view->update ();
828 }
829