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