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