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