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