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