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