Handle pending player changes more efficiently.
[dcpomatic.git] / src / wx / film_viewer.cc
1 /*
2     Copyright (C) 2012-2019 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 /** @file  src/film_viewer.cc
22  *  @brief A wx widget to view a preview of a Film.
23  */
24
25 #include "film_viewer.h"
26 #include "playhead_to_timecode_dialog.h"
27 #include "playhead_to_frame_dialog.h"
28 #include "wx_util.h"
29 #include "closed_captions_dialog.h"
30 #include "gl_video_view.h"
31 #include "simple_video_view.h"
32 #include "lib/film.h"
33 #include "lib/ratio.h"
34 #include "lib/util.h"
35 #include "lib/job_manager.h"
36 #include "lib/image.h"
37 #include "lib/exceptions.h"
38 #include "lib/examine_content_job.h"
39 #include "lib/filter.h"
40 #include "lib/player.h"
41 #include "lib/player_video.h"
42 #include "lib/video_content.h"
43 #include "lib/video_decoder.h"
44 #include "lib/timer.h"
45 #include "lib/butler.h"
46 #include "lib/log.h"
47 #include "lib/config.h"
48 #include "lib/compose.hpp"
49 #include "lib/dcpomatic_log.h"
50 #include "lib/text_content.h"
51 extern "C" {
52 #include <libavutil/pixfmt.h>
53 }
54 #include <dcp/exceptions.h>
55 #include <wx/tglbtn.h>
56 #include <iostream>
57 #include <iomanip>
58
59 using std::string;
60 using std::pair;
61 using std::min;
62 using std::max;
63 using std::cout;
64 using std::list;
65 using std::bad_alloc;
66 using std::make_pair;
67 using std::exception;
68 using std::shared_ptr;
69 using std::dynamic_pointer_cast;
70 using std::vector;
71 using std::weak_ptr;
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 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 FilmViewer::FilmViewer (wxWindow* p)
87         : _coalesce_player_changes (false)
88         , _audio (DCPOMATIC_RTAUDIO_API)
89         , _audio_channels (0)
90         , _audio_block_size (1024)
91         , _playing (false)
92         , _suspended (0)
93         , _latency_history_count (0)
94         , _closed_captions_dialog (new ClosedCaptionsDialog(p, this))
95         , _outline_content (false)
96         , _pad_black (false)
97         , _idle_get (false)
98 {
99         switch (Config::instance()->video_view_type()) {
100         case Config::VIDEO_VIEW_OPENGL:
101                 _video_view = new GLVideoView (this, p);
102                 break;
103         case Config::VIDEO_VIEW_SIMPLE:
104                 _video_view = new SimpleVideoView (this, p);
105                 break;
106         }
107
108         _video_view->Sized.connect (boost::bind(&FilmViewer::video_view_sized, this));
109
110         set_film (shared_ptr<Film> ());
111
112         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
113         config_changed (Config::SOUND_OUTPUT);
114 }
115
116 FilmViewer::~FilmViewer ()
117 {
118         stop ();
119 }
120
121 /** Ask for ::get() 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 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 void
150 FilmViewer::set_film (shared_ptr<Film> film)
151 {
152         if (_film == film) {
153                 return;
154         }
155
156         _film = film;
157
158         _video_view->clear ();
159         _closed_captions_dialog->clear ();
160
161         if (!_film) {
162                 _player.reset ();
163                 recreate_butler ();
164                 _video_view->update ();
165                 return;
166         }
167
168         try {
169                 _player.reset (new Player(_film));
170                 _player->set_fast ();
171                 if (_dcp_decode_reduction) {
172                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
173                 }
174         } catch (bad_alloc &) {
175                 error_dialog (_video_view->get(), _("There is not enough free memory to do that."));
176                 _film.reset ();
177                 return;
178         }
179
180         _player->set_always_burn_open_subtitles ();
181         _player->set_play_referenced ();
182
183         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
184         _film->LengthChange.connect (boost::bind(&FilmViewer::film_length_change, this));
185         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
186
187         film_change (ChangeType::DONE, Film::Property::VIDEO_FRAME_RATE);
188         film_change (ChangeType::DONE, Film::Property::THREE_D);
189         film_length_change ();
190
191         /* Keep about 1 second's worth of history samples */
192         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
193
194         _closed_captions_dialog->update_tracks (_film);
195
196         recreate_butler ();
197
198         calculate_sizes ();
199         slow_refresh ();
200 }
201
202 void
203 FilmViewer::recreate_butler ()
204 {
205         suspend ();
206         _butler.reset ();
207
208         if (!_film) {
209                 resume ();
210                 return;
211         }
212
213         _butler.reset(
214                 new Butler(
215                         _film,
216                         _player,
217                         Config::instance()->audio_mapping(_audio_channels),
218                         _audio_channels,
219                         bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24),
220                         VideoRange::FULL,
221                         false,
222                         true
223                         )
224                 );
225
226         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
227                 _butler->disable_audio ();
228         }
229
230         _closed_captions_dialog->set_butler (_butler);
231
232         resume ();
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 void
259 FilmViewer::video_view_sized ()
260 {
261         calculate_sizes ();
262         if (!quick_refresh()) {
263                 slow_refresh ();
264         }
265 }
266
267 void
268 FilmViewer::calculate_sizes ()
269 {
270         if (!_film || !_player) {
271                 return;
272         }
273
274         Ratio const * container = _film->container ();
275
276         float const view_ratio = float(_video_view->get()->GetSize().x) / _video_view->get()->GetSize().y;
277         float const film_ratio = container ? container->ratio () : 1.78;
278
279         if (view_ratio < film_ratio) {
280                 /* panel is less widscreen than the film; clamp width */
281                 _out_size.width = _video_view->get()->GetSize().x;
282                 _out_size.height = lrintf (_out_size.width / film_ratio);
283         } else {
284                 /* panel is more widescreen than the film; clamp height */
285                 _out_size.height = _video_view->get()->GetSize().y;
286                 _out_size.width = lrintf (_out_size.height * film_ratio);
287         }
288
289         /* Catch silly values */
290         _out_size.width = max (64, _out_size.width);
291         _out_size.height = max (64, _out_size.height);
292
293         _player->set_video_container_size (_out_size);
294 }
295
296 void
297 FilmViewer::suspend ()
298 {
299         ++_suspended;
300         if (_audio.isStreamRunning()) {
301                 _audio.abortStream();
302         }
303 }
304
305 void
306 FilmViewer::resume ()
307 {
308         DCPOMATIC_ASSERT (_suspended > 0);
309         --_suspended;
310         if (_playing && !_suspended) {
311                 if (_audio.isStreamOpen()) {
312                         _audio.setStreamTime (_video_view->position().seconds());
313                         _audio.startStream ();
314                 }
315                 _video_view->start ();
316         }
317 }
318
319 void
320 FilmViewer::start ()
321 {
322         if (!_film) {
323                 return;
324         }
325
326         optional<bool> v = PlaybackPermitted ();
327         if (v && !*v) {
328                 /* Computer says no */
329                 return;
330         }
331
332         /* We are about to set up the audio stream from the position of the video view.
333            If there is `lazy' seek in progress we need to wait for it to go through so that
334            _video_view->position() gives us a sensible answer.
335          */
336         while (_idle_get) {
337                 idle_handler ();
338         }
339
340         /* Take the video view's idea of position as our `playhead' and start the
341            audio stream (which is the timing reference) there.
342          */
343         if (_audio.isStreamOpen()) {
344                 _audio.setStreamTime (_video_view->position().seconds());
345                 _audio.startStream ();
346         }
347
348         _playing = true;
349         /* Calling start() below may directly result in Stopped being emitted, and if that
350          * happens we want it to come after the Started signal, so do that first.
351          */
352         Started (position());
353         _video_view->start ();
354 }
355
356 bool
357 FilmViewer::stop ()
358 {
359         if (_audio.isStreamRunning()) {
360                 /* stop stream and discard any remaining queued samples */
361                 _audio.abortStream ();
362         }
363
364         if (!_playing) {
365                 return false;
366         }
367
368         _playing = false;
369         _video_view->stop ();
370         Stopped (position());
371
372         _video_view->rethrow ();
373         return true;
374 }
375
376 void
377 FilmViewer::player_change (ChangeType type, int property, bool frequent)
378 {
379         if (type != ChangeType::DONE || frequent) {
380                 return;
381         }
382
383         if (_coalesce_player_changes) {
384                 _pending_player_changes.push_back (property);
385                 return;
386         }
387
388         player_change ({property});
389 }
390
391 void
392 FilmViewer::player_change (vector<int> properties)
393 {
394         calculate_sizes ();
395
396         bool try_quick_refresh = false;
397         bool update_ccap_tracks = false;
398
399         for (auto i: properties) {
400                 if (
401                         i == VideoContentProperty::CROP ||
402                         i == VideoContentProperty::SCALE ||
403                         i == VideoContentProperty::FADE_IN ||
404                         i == VideoContentProperty::FADE_OUT ||
405                         i == VideoContentProperty::COLOUR_CONVERSION ||
406                         i == PlayerProperty::VIDEO_CONTAINER_SIZE ||
407                         i == PlayerProperty::FILM_CONTAINER
408                    ) {
409                         try_quick_refresh = true;
410                 }
411
412                 if (i == TextContentProperty::USE || i == TextContentProperty::TYPE || i == TextContentProperty::DCP_TRACK) {
413                         update_ccap_tracks = true;
414                 }
415         }
416
417         if (!try_quick_refresh || !quick_refresh()) {
418                 slow_refresh ();
419         }
420
421         if (update_ccap_tracks) {
422                 _closed_captions_dialog->update_tracks (_film);
423         }
424 }
425
426 void
427 FilmViewer::film_change (ChangeType type, Film::Property p)
428 {
429         if (type != ChangeType::DONE) {
430                 return;
431         }
432
433         if (p == Film::Property::AUDIO_CHANNELS) {
434                 recreate_butler ();
435         } else if (p == Film::Property::VIDEO_FRAME_RATE) {
436                 _video_view->set_video_frame_rate (_film->video_frame_rate());
437         } else if (p == Film::Property::THREE_D) {
438                 _video_view->set_three_d (_film->three_d());
439         } else if (p == Film::Property::CONTENT) {
440                 _closed_captions_dialog->update_tracks (_film);
441         }
442 }
443
444 void
445 FilmViewer::film_length_change ()
446 {
447         _video_view->set_length (_film->length());
448 }
449
450 /** Re-get the current frame slowly by seeking */
451 void
452 FilmViewer::slow_refresh ()
453 {
454         seek (_video_view->position(), true);
455 }
456
457 /** Try to re-get the current frame quickly by resetting the metadata
458  *  in the PlayerVideo that we used last time.
459  *  @return true if this was possible, false if not.
460  */
461 bool
462 FilmViewer::quick_refresh ()
463 {
464         if (!_video_view || !_film || !_player) {
465                 return true;
466         }
467         return _video_view->reset_metadata (_film, _player->video_container_size());
468 }
469
470 void
471 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
472 {
473         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
474         if (dt) {
475                 seek (*dt, accurate);
476         }
477 }
478
479 void
480 FilmViewer::set_coalesce_player_changes (bool c)
481 {
482         _coalesce_player_changes = c;
483
484         if (!c) {
485                 player_change (_pending_player_changes);
486                 _pending_player_changes.clear ();
487         }
488 }
489
490 void
491 FilmViewer::seek (DCPTime t, bool accurate)
492 {
493         if (!_butler) {
494                 return;
495         }
496
497         if (t < DCPTime ()) {
498                 t = DCPTime ();
499         }
500
501         if (t >= _film->length ()) {
502                 t = _film->length() - one_video_frame();
503         }
504
505         suspend ();
506
507         _closed_captions_dialog->clear ();
508         _butler->seek (t, accurate);
509
510         if (!_playing) {
511                 /* We're not playing, so let the GUI thread get on and
512                    come back later to get the next frame after the seek.
513                 */
514                 request_idle_display_next_frame ();
515         } else {
516                 /* We're going to start playing again straight away
517                    so wait for the seek to finish.
518                 */
519                 while (_video_view->display_next_frame(false) == VideoView::AGAIN) {}
520         }
521
522         resume ();
523 }
524
525 void
526 FilmViewer::config_changed (Config::Property p)
527 {
528         if (p == Config::AUDIO_MAPPING) {
529                 recreate_butler ();
530                 return;
531         }
532
533         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
534                 return;
535         }
536
537         if (_audio.isStreamOpen ()) {
538                 _audio.closeStream ();
539         }
540
541         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
542                 unsigned int st = 0;
543                 if (Config::instance()->sound_output()) {
544                         while (st < _audio.getDeviceCount()) {
545                                 try {
546                                         if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
547                                                 break;
548                                         }
549                                 } catch (RtAudioError&) {
550                                         /* Something went wrong with that device so we don't want to use it anyway */
551                                 }
552                                 ++st;
553                         }
554                         if (st == _audio.getDeviceCount()) {
555                                 st = _audio.getDefaultOutputDevice();
556                         }
557                 } else {
558                         st = _audio.getDefaultOutputDevice();
559                 }
560
561                 try {
562                         _audio_channels = _audio.getDeviceInfo(st).outputChannels;
563                         RtAudio::StreamParameters sp;
564                         sp.deviceId = st;
565                         sp.nChannels = _audio_channels;
566                         sp.firstChannel = 0;
567                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
568                 } catch (RtAudioError& e) {
569                         _audio_channels = 0;
570                         error_dialog (
571                                 _video_view->get(),
572                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
573                                 );
574                 }
575                 recreate_butler ();
576
577         } else {
578                 _audio_channels = 0;
579                 recreate_butler ();
580         }
581 }
582
583 DCPTime
584 FilmViewer::uncorrected_time () const
585 {
586         if (_audio.isStreamRunning ()) {
587                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
588         }
589
590         return _video_view->position();
591 }
592
593 optional<DCPTime>
594 FilmViewer::audio_time () const
595 {
596         if (!_audio.isStreamRunning()) {
597                 return optional<DCPTime>();
598         }
599
600         return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
601                 DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
602 }
603
604 DCPTime
605 FilmViewer::time () const
606 {
607         return audio_time().get_value_or(_video_view->position());
608 }
609
610 int
611 FilmViewer::audio_callback (void* out_p, unsigned int frames)
612 {
613         while (true) {
614                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
615                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
616                         /* There was an underrun or this audio is on time; carry on */
617                         break;
618                 }
619                 /* The audio we just got was (very) late; drop it and get some more. */
620         }
621
622         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
623         if (lm) {
624                 _latency_history.push_back (_audio.getStreamLatency ());
625                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
626                         _latency_history.pop_front ();
627                 }
628         }
629
630         return 0;
631 }
632
633 Frame
634 FilmViewer::average_latency () const
635 {
636         boost::mutex::scoped_lock lm (_latency_history_mutex);
637         if (_latency_history.empty()) {
638                 return 0;
639         }
640
641         Frame total = 0;
642         for (auto i: _latency_history) {
643                 total += i;
644         }
645
646         return total / _latency_history.size();
647 }
648
649 void
650 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
651 {
652         _dcp_decode_reduction = reduction;
653         if (_player) {
654                 _player->set_dcp_decode_reduction (reduction);
655         }
656 }
657
658 optional<int>
659 FilmViewer::dcp_decode_reduction () const
660 {
661         return _dcp_decode_reduction;
662 }
663
664 DCPTime
665 FilmViewer::one_video_frame () const
666 {
667         return DCPTime::from_frames (1, _film ? _film->video_frame_rate() : 24);
668 }
669
670 /** Open a dialog box showing our film's closed captions */
671 void
672 FilmViewer::show_closed_captions ()
673 {
674         _closed_captions_dialog->Show();
675 }
676
677 void
678 FilmViewer::seek_by (DCPTime by, bool accurate)
679 {
680         seek (_video_view->position() + by, accurate);
681 }
682
683 void
684 FilmViewer::set_pad_black (bool p)
685 {
686         _pad_black = p;
687 }
688
689 /** Called when a player has finished the current film.
690  *  May be called from a non-UI thread.
691  */
692 void
693 FilmViewer::finished ()
694 {
695         emit (boost::bind(&FilmViewer::ui_finished, this));
696 }
697
698 /** Called by finished() in the UI thread */
699 void
700 FilmViewer::ui_finished ()
701 {
702         stop ();
703         Finished ();
704 }
705
706 int
707 FilmViewer::dropped () const
708 {
709         return _video_view->dropped ();
710 }
711
712
713 int
714 FilmViewer::errored () const
715 {
716         return _video_view->errored ();
717 }
718
719
720 int
721 FilmViewer::gets () const
722 {
723         return _video_view->gets ();
724 }
725
726
727 void
728 FilmViewer::image_changed (shared_ptr<PlayerVideo> pv)
729 {
730         emit (boost::bind(boost::ref(ImageChanged), pv));
731 }
732