Assorted C++11/formatting cleanups.
[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 = new GLVideoView (this, p);
100                 break;
101         case Config::VIDEO_VIEW_SIMPLE:
102                 _video_view = new 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(&FilmViewer::too_many_frames_dropped, this));
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                 );
227
228         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
229                 _butler->disable_audio ();
230         }
231
232         _closed_captions_dialog->set_butler (_butler);
233
234         resume ();
235 }
236
237
238 void
239 FilmViewer::set_outline_content (bool o)
240 {
241         _outline_content = o;
242         _video_view->update ();
243 }
244
245
246 void
247 FilmViewer::set_outline_subtitles (optional<dcpomatic::Rect<double>> rect)
248 {
249         _outline_subtitles = rect;
250         _video_view->update ();
251 }
252
253
254 void
255 FilmViewer::set_eyes (Eyes e)
256 {
257         _video_view->set_eyes (e);
258         slow_refresh ();
259 }
260
261
262 void
263 FilmViewer::video_view_sized ()
264 {
265         calculate_sizes ();
266         if (!quick_refresh()) {
267                 slow_refresh ();
268         }
269 }
270
271
272 void
273 FilmViewer::calculate_sizes ()
274 {
275         if (!_film || !_player) {
276                 return;
277         }
278
279         auto const container = _film->container ();
280
281         auto const view_ratio = float(_video_view->get()->GetSize().x) / _video_view->get()->GetSize().y;
282         auto const film_ratio = container ? container->ratio () : 1.78;
283
284         if (view_ratio < film_ratio) {
285                 /* panel is less widscreen than the film; clamp width */
286                 _out_size.width = _video_view->get()->GetSize().x;
287                 _out_size.height = lrintf (_out_size.width / film_ratio);
288         } else {
289                 /* panel is more widescreen than the film; clamp height */
290                 _out_size.height = _video_view->get()->GetSize().y;
291                 _out_size.width = lrintf (_out_size.height * film_ratio);
292         }
293
294         /* Catch silly values */
295         _out_size.width = max (64, _out_size.width);
296         _out_size.height = max (64, _out_size.height);
297
298         _player->set_video_container_size (_out_size);
299 }
300
301
302 void
303 FilmViewer::suspend ()
304 {
305         ++_suspended;
306         if (_audio.isStreamRunning()) {
307                 _audio.abortStream();
308         }
309 }
310
311
312 void
313 FilmViewer::resume ()
314 {
315         DCPOMATIC_ASSERT (_suspended > 0);
316         --_suspended;
317         if (_playing && !_suspended) {
318                 if (_audio.isStreamOpen()) {
319                         _audio.setStreamTime (_video_view->position().seconds());
320                         _audio.startStream ();
321                 }
322                 _video_view->start ();
323         }
324 }
325
326
327 void
328 FilmViewer::start ()
329 {
330         if (!_film) {
331                 return;
332         }
333
334         auto v = PlaybackPermitted ();
335         if (v && !*v) {
336                 /* Computer says no */
337                 return;
338         }
339
340         /* We are about to set up the audio stream from the position of the video view.
341            If there is `lazy' seek in progress we need to wait for it to go through so that
342            _video_view->position() gives us a sensible answer.
343          */
344         while (_idle_get) {
345                 idle_handler ();
346         }
347
348         /* Take the video view's idea of position as our `playhead' and start the
349            audio stream (which is the timing reference) there.
350          */
351         if (_audio.isStreamOpen()) {
352                 _audio.setStreamTime (_video_view->position().seconds());
353                 _audio.startStream ();
354         }
355
356         _playing = true;
357         /* Calling start() below may directly result in Stopped being emitted, and if that
358          * happens we want it to come after the Started signal, so do that first.
359          */
360         Started (position());
361         _video_view->start ();
362 }
363
364
365 bool
366 FilmViewer::stop ()
367 {
368         if (_audio.isStreamRunning()) {
369                 /* stop stream and discard any remaining queued samples */
370                 _audio.abortStream ();
371         }
372
373         if (!_playing) {
374                 return false;
375         }
376
377         _playing = false;
378         _video_view->stop ();
379         Stopped (position());
380
381         _video_view->rethrow ();
382         return true;
383 }
384
385
386 void
387 FilmViewer::player_change (ChangeType type, int property, bool frequent)
388 {
389         if (type != ChangeType::DONE || frequent) {
390                 return;
391         }
392
393         if (_coalesce_player_changes) {
394                 _pending_player_changes.push_back (property);
395                 return;
396         }
397
398         player_change ({property});
399 }
400
401
402 void
403 FilmViewer::player_change (vector<int> properties)
404 {
405         calculate_sizes ();
406
407         bool try_quick_refresh = false;
408         bool update_ccap_tracks = false;
409
410         for (auto i: properties) {
411                 if (
412                         i == VideoContentProperty::CROP ||
413                         i == VideoContentProperty::SCALE ||
414                         i == VideoContentProperty::FADE_IN ||
415                         i == VideoContentProperty::FADE_OUT ||
416                         i == VideoContentProperty::COLOUR_CONVERSION ||
417                         i == PlayerProperty::VIDEO_CONTAINER_SIZE ||
418                         i == PlayerProperty::FILM_CONTAINER
419                    ) {
420                         try_quick_refresh = true;
421                 }
422
423                 if (i == TextContentProperty::USE || i == TextContentProperty::TYPE || i == TextContentProperty::DCP_TRACK) {
424                         update_ccap_tracks = true;
425                 }
426         }
427
428         if (!try_quick_refresh || !quick_refresh()) {
429                 slow_refresh ();
430         }
431
432         if (update_ccap_tracks) {
433                 _closed_captions_dialog->update_tracks (_film);
434         }
435 }
436
437
438 void
439 FilmViewer::film_change (ChangeType type, Film::Property p)
440 {
441         if (type != ChangeType::DONE) {
442                 return;
443         }
444
445         if (p == Film::Property::AUDIO_CHANNELS) {
446                 recreate_butler ();
447         } else if (p == Film::Property::VIDEO_FRAME_RATE) {
448                 _video_view->set_video_frame_rate (_film->video_frame_rate());
449         } else if (p == Film::Property::THREE_D) {
450                 _video_view->set_three_d (_film->three_d());
451         } else if (p == Film::Property::CONTENT) {
452                 _closed_captions_dialog->update_tracks (_film);
453         }
454 }
455
456
457 void
458 FilmViewer::film_length_change ()
459 {
460         _video_view->set_length (_film->length());
461 }
462
463
464 /** Re-get the current frame slowly by seeking */
465 void
466 FilmViewer::slow_refresh ()
467 {
468         seek (_video_view->position(), true);
469 }
470
471
472 /** Try to re-get the current frame quickly by resetting the metadata
473  *  in the PlayerVideo that we used last time.
474  *  @return true if this was possible, false if not.
475  */
476 bool
477 FilmViewer::quick_refresh ()
478 {
479         if (!_video_view || !_film || !_player) {
480                 return true;
481         }
482         return _video_view->reset_metadata (_film, _player->video_container_size());
483 }
484
485
486 void
487 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
488 {
489         auto dt = _player->content_time_to_dcp (content, t);
490         if (dt) {
491                 seek (*dt, accurate);
492         }
493 }
494
495
496 void
497 FilmViewer::set_coalesce_player_changes (bool c)
498 {
499         _coalesce_player_changes = c;
500
501         if (!c) {
502                 player_change (_pending_player_changes);
503                 _pending_player_changes.clear ();
504         }
505 }
506
507
508 void
509 FilmViewer::seek (DCPTime t, bool accurate)
510 {
511         if (!_butler) {
512                 return;
513         }
514
515         if (t < DCPTime()) {
516                 t = DCPTime ();
517         }
518
519         if (t >= _film->length()) {
520                 t = _film->length() - one_video_frame();
521         }
522
523         suspend ();
524
525         _closed_captions_dialog->clear ();
526         _butler->seek (t, accurate);
527
528         if (!_playing) {
529                 /* We're not playing, so let the GUI thread get on and
530                    come back later to get the next frame after the seek.
531                 */
532                 request_idle_display_next_frame ();
533         } else {
534                 /* We're going to start playing again straight away
535                    so wait for the seek to finish.
536                 */
537                 while (_video_view->display_next_frame(false) == VideoView::AGAIN) {}
538         }
539
540         resume ();
541 }
542
543
544 void
545 FilmViewer::config_changed (Config::Property p)
546 {
547         if (p == Config::AUDIO_MAPPING) {
548                 recreate_butler ();
549                 return;
550         }
551
552         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
553                 return;
554         }
555
556         if (_audio.isStreamOpen ()) {
557                 _audio.closeStream ();
558         }
559
560         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
561                 unsigned int st = 0;
562                 if (Config::instance()->sound_output()) {
563                         while (st < _audio.getDeviceCount()) {
564                                 try {
565                                         if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
566                                                 break;
567                                         }
568                                 } catch (RtAudioError&) {
569                                         /* Something went wrong with that device so we don't want to use it anyway */
570                                 }
571                                 ++st;
572                         }
573                         if (st == _audio.getDeviceCount()) {
574                                 st = _audio.getDefaultOutputDevice();
575                         }
576                 } else {
577                         st = _audio.getDefaultOutputDevice();
578                 }
579
580                 try {
581                         _audio_channels = _audio.getDeviceInfo(st).outputChannels;
582                         RtAudio::StreamParameters sp;
583                         sp.deviceId = st;
584                         sp.nChannels = _audio_channels;
585                         sp.firstChannel = 0;
586                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
587                 } catch (RtAudioError& e) {
588                         _audio_channels = 0;
589                         error_dialog (
590                                 _video_view->get(),
591                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
592                                 );
593                 }
594                 recreate_butler ();
595
596         } else {
597                 _audio_channels = 0;
598                 recreate_butler ();
599         }
600 }
601
602
603 DCPTime
604 FilmViewer::uncorrected_time () const
605 {
606         if (_audio.isStreamRunning()) {
607                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
608         }
609
610         return _video_view->position();
611 }
612
613
614 optional<DCPTime>
615 FilmViewer::audio_time () const
616 {
617         if (!_audio.isStreamRunning()) {
618                 return {};
619         }
620
621         return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
622                 DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
623 }
624
625
626 DCPTime
627 FilmViewer::time () const
628 {
629         return audio_time().get_value_or(_video_view->position());
630 }
631
632
633 int
634 FilmViewer::audio_callback (void* out_p, unsigned int frames)
635 {
636         while (true) {
637                 auto t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
638                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
639                         /* There was an underrun or this audio is on time; carry on */
640                         break;
641                 }
642                 /* The audio we just got was (very) late; drop it and get some more. */
643         }
644
645         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
646         if (lm) {
647                 _latency_history.push_back (_audio.getStreamLatency ());
648                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
649                         _latency_history.pop_front ();
650                 }
651         }
652
653         return 0;
654 }
655
656
657 Frame
658 FilmViewer::average_latency () const
659 {
660         boost::mutex::scoped_lock lm (_latency_history_mutex);
661         if (_latency_history.empty()) {
662                 return 0;
663         }
664
665         Frame total = 0;
666         for (auto i: _latency_history) {
667                 total += i;
668         }
669
670         return total / _latency_history.size();
671 }
672
673
674 void
675 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
676 {
677         _dcp_decode_reduction = reduction;
678         if (_player) {
679                 _player->set_dcp_decode_reduction (reduction);
680         }
681 }
682
683
684 optional<int>
685 FilmViewer::dcp_decode_reduction () const
686 {
687         return _dcp_decode_reduction;
688 }
689
690
691 DCPTime
692 FilmViewer::one_video_frame () const
693 {
694         return DCPTime::from_frames (1, _film ? _film->video_frame_rate() : 24);
695 }
696
697
698 /** Open a dialog box showing our film's closed captions */
699 void
700 FilmViewer::show_closed_captions ()
701 {
702         _closed_captions_dialog->Show();
703 }
704
705
706 void
707 FilmViewer::seek_by (DCPTime by, bool accurate)
708 {
709         seek (_video_view->position() + by, accurate);
710 }
711
712
713 void
714 FilmViewer::set_pad_black (bool p)
715 {
716         _pad_black = p;
717 }
718
719
720 /** Called when a player has finished the current film.
721  *  May be called from a non-UI thread.
722  */
723 void
724 FilmViewer::finished ()
725 {
726         emit (boost::bind(&FilmViewer::ui_finished, this));
727 }
728
729
730 /** Called by finished() in the UI thread */
731 void
732 FilmViewer::ui_finished ()
733 {
734         stop ();
735         Finished ();
736 }
737
738
739 int
740 FilmViewer::dropped () const
741 {
742         return _video_view->dropped ();
743 }
744
745
746 int
747 FilmViewer::errored () const
748 {
749         return _video_view->errored ();
750 }
751
752
753 int
754 FilmViewer::gets () const
755 {
756         return _video_view->gets ();
757 }
758
759
760 void
761 FilmViewer::image_changed (shared_ptr<PlayerVideo> pv)
762 {
763         emit (boost::bind(boost::ref(ImageChanged), pv));
764 }
765
766
767 void
768 FilmViewer::too_many_frames_dropped ()
769 {
770         if (!Config::instance()->nagged(Config::NAG_TOO_MANY_DROPPED_FRAMES)) {
771                 stop ();
772         }
773
774         NagDialog::maybe_nag (
775                 panel(),
776                 Config::NAG_TOO_MANY_DROPPED_FRAMES,
777                 _("The player is dropping a lot of frames, so playback may not be accurate.\n\n"
778                   "<b>This does not necessarily mean that the DCP you are playing is defective!</b>\n\n"
779                   "You may be able to improve player performance by:\n"
780                   "• choosing 'decode at half resolution' or 'decode at quarter resolution' from the View menu\n"
781                   "• using a more powerful computer.\n"
782                  )
783                 );
784 }