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