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