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