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