c1d04be03f05e5d9f4a88d6de7f85a13409e773f
[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         , _dropped (0)
90         , _closed_captions_dialog (new ClosedCaptionsDialog(p, this))
91         , _outline_content (false)
92         , _eyes (EYES_LEFT)
93         , _pad_black (false)
94 #ifdef DCPOMATIC_VARIANT_SWAROOP
95         , _background_image (false)
96 #endif
97         , _state_timer ("viewer")
98         , _gets (0)
99         , _idle_get (false)
100 {
101         switch (Config::instance()->video_view_type()) {
102         case Config::VIDEO_VIEW_OPENGL:
103                 _video_view = new GLVideoView (this, p);
104                 break;
105         case Config::VIDEO_VIEW_SIMPLE:
106                 _video_view = new SimpleVideoView (this, p);
107                 break;
108         }
109
110         _video_view->Sized.connect (boost::bind(&FilmViewer::video_view_sized, this));
111
112         set_film (shared_ptr<Film> ());
113
114         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
115         config_changed (Config::SOUND_OUTPUT);
116 }
117
118 FilmViewer::~FilmViewer ()
119 {
120         stop ();
121 }
122
123 /** Ask for ::get() to be called next time we are idle */
124 void
125 FilmViewer::request_idle_display_next_frame ()
126 {
127         if (_idle_get) {
128                 return;
129         }
130
131         _idle_get = true;
132         DCPOMATIC_ASSERT (signal_manager);
133         signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
134 }
135
136 void
137 FilmViewer::idle_handler ()
138 {
139         if (!_idle_get) {
140                 return;
141         }
142
143         if (_video_view->display_next_frame(true)) {
144                 _idle_get = false;
145         } else {
146                 /* get() could not complete quickly so we'll try again later */
147                 signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
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.reset ();
165                 recreate_butler ();
166                 refresh_view ();
167                 return;
168         }
169
170         try {
171                 _player.reset (new Player (_film, _film->playlist ()));
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         /* 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::refresh_view ()
231 {
232         _state_timer.set ("update-view");
233         _video_view->update ();
234         _state_timer.unset ();
235 }
236
237 void
238 FilmViewer::set_outline_content (bool o)
239 {
240         _outline_content = o;
241         refresh_view ();
242 }
243
244 void
245 FilmViewer::set_eyes (Eyes e)
246 {
247         _eyes = e;
248         slow_refresh ();
249 }
250
251 void
252 FilmViewer::video_view_sized ()
253 {
254         calculate_sizes ();
255         if (!quick_refresh()) {
256                 slow_refresh ();
257         }
258 }
259
260 void
261 FilmViewer::calculate_sizes ()
262 {
263         if (!_film || !_player) {
264                 return;
265         }
266
267         Ratio const * container = _film->container ();
268
269         float const view_ratio = float(_video_view->get()->GetSize().x) / _video_view->get()->GetSize().y;
270         float const film_ratio = container ? container->ratio () : 1.78;
271
272         if (view_ratio < film_ratio) {
273                 /* panel is less widscreen than the film; clamp width */
274                 _out_size.width = _video_view->get()->GetSize().x;
275                 _out_size.height = lrintf (_out_size.width / film_ratio);
276         } else {
277                 /* panel is more widescreen than the film; clamp height */
278                 _out_size.height = _video_view->get()->GetSize().y;
279                 _out_size.width = lrintf (_out_size.height * film_ratio);
280         }
281
282         /* Catch silly values */
283         _out_size.width = max (64, _out_size.width);
284         _out_size.height = max (64, _out_size.height);
285
286         _player->set_video_container_size (_out_size);
287 }
288
289 void
290 FilmViewer::suspend ()
291 {
292         ++_suspended;
293         if (_audio.isStreamRunning()) {
294                 _audio.abortStream();
295         }
296 }
297
298 void
299 FilmViewer::resume ()
300 {
301         --_suspended;
302         if (_playing && !_suspended) {
303                 if (_audio.isStreamOpen()) {
304                         _audio.setStreamTime (_video_view->position().seconds());
305                         _audio.startStream ();
306                 }
307                 _video_view->start ();
308         }
309 }
310
311 void
312 FilmViewer::start ()
313 {
314         if (!_film) {
315                 return;
316         }
317
318         optional<bool> v = PlaybackPermitted ();
319         if (v && !*v) {
320                 /* Computer says no */
321                 return;
322         }
323
324         if (_audio.isStreamOpen()) {
325                 _audio.setStreamTime (_video_view->position().seconds());
326                 _audio.startStream ();
327         }
328
329         _dropped = 0;
330         _playing = true;
331         _video_view->start ();
332         Started (position());
333 }
334
335 bool
336 FilmViewer::stop ()
337 {
338         if (_audio.isStreamRunning()) {
339                 /* stop stream and discard any remaining queued samples */
340                 _audio.abortStream ();
341         }
342
343         if (!_playing) {
344                 return false;
345         }
346
347         _playing = false;
348         _video_view->stop ();
349         Stopped (position());
350         return true;
351 }
352
353 void
354 FilmViewer::player_change (ChangeType type, int property, bool frequent)
355 {
356         if (type != CHANGE_TYPE_DONE || frequent) {
357                 return;
358         }
359
360         if (_coalesce_player_changes) {
361                 _pending_player_changes.push_back (property);
362                 return;
363         }
364
365         calculate_sizes ();
366         bool refreshed = false;
367         if (
368                 property == VideoContentProperty::CROP ||
369                 property == VideoContentProperty::SCALE ||
370                 property == VideoContentProperty::FADE_IN ||
371                 property == VideoContentProperty::FADE_OUT ||
372                 property == VideoContentProperty::COLOUR_CONVERSION ||
373                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
374                 property == PlayerProperty::FILM_CONTAINER
375                 ) {
376                 refreshed = quick_refresh ();
377         }
378
379         if (!refreshed) {
380                 slow_refresh ();
381         }
382 }
383
384 void
385 FilmViewer::film_change (ChangeType type, Film::Property p)
386 {
387         if (type != CHANGE_TYPE_DONE) {
388                 return;
389         }
390
391         if (p == Film::AUDIO_CHANNELS) {
392                 recreate_butler ();
393         } else if (p == Film::VIDEO_FRAME_RATE) {
394                 _video_view->set_video_frame_rate (_film->video_frame_rate());
395         }
396 }
397
398 void
399 FilmViewer::film_length_change ()
400 {
401         _video_view->set_length (_film->length());
402 }
403
404 /** Re-get the current frame slowly by seeking */
405 void
406 FilmViewer::slow_refresh ()
407 {
408         seek (_video_view->position(), true);
409 }
410
411 /** Try to re-get the current frame quickly by resetting the metadata
412  *  in the PlayerVideo that we used last time.
413  *  @return true if this was possible, false if not.
414  */
415 bool
416 FilmViewer::quick_refresh ()
417 {
418         if (!_video_view->_player_video.first) {
419                 return false;
420         }
421
422         if (!_video_view->_player_video.first->reset_metadata (_film, _player->video_container_size(), _film->frame_size())) {
423                 return false;
424         }
425
426         _video_view->display_player_video ();
427         return true;
428 }
429
430 void
431 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
432 {
433         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
434         if (dt) {
435                 seek (*dt, accurate);
436         }
437 }
438
439 void
440 FilmViewer::set_coalesce_player_changes (bool c)
441 {
442         _coalesce_player_changes = c;
443
444         if (!c) {
445                 BOOST_FOREACH (int i, _pending_player_changes) {
446                         player_change (CHANGE_TYPE_DONE, i, false);
447                 }
448                 _pending_player_changes.clear ();
449         }
450 }
451
452 void
453 FilmViewer::seek (DCPTime t, bool accurate)
454 {
455         if (!_butler) {
456                 return;
457         }
458
459         if (t < DCPTime ()) {
460                 t = DCPTime ();
461         }
462
463         if (t >= _film->length ()) {
464                 t = _film->length ();
465         }
466
467         suspend ();
468
469         _closed_captions_dialog->clear ();
470         _butler->seek (t, accurate);
471
472         if (!_playing) {
473                 request_idle_display_next_frame ();
474         } else {
475                 while (!_video_view->display_next_frame(false)) {}
476         }
477
478         resume ();
479 }
480
481 void
482 FilmViewer::config_changed (Config::Property p)
483 {
484 #ifdef DCPOMATIC_VARIANT_SWAROOP
485         if (p == Config::PLAYER_BACKGROUND_IMAGE) {
486                 refresh_view ();
487                 return;
488         }
489 #endif
490
491         if (p == Config::AUDIO_MAPPING) {
492                 recreate_butler ();
493                 return;
494         }
495
496         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
497                 return;
498         }
499
500         if (_audio.isStreamOpen ()) {
501                 _audio.closeStream ();
502         }
503
504         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
505                 unsigned int st = 0;
506                 if (Config::instance()->sound_output()) {
507                         while (st < _audio.getDeviceCount()) {
508                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
509                                         break;
510                                 }
511                                 ++st;
512                         }
513                         if (st == _audio.getDeviceCount()) {
514                                 st = _audio.getDefaultOutputDevice();
515                         }
516                 } else {
517                         st = _audio.getDefaultOutputDevice();
518                 }
519
520                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
521
522                 RtAudio::StreamParameters sp;
523                 sp.deviceId = st;
524                 sp.nChannels = _audio_channels;
525                 sp.firstChannel = 0;
526                 try {
527                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
528 #ifdef DCPOMATIC_USE_RTERROR
529                 } catch (RtError& e) {
530 #else
531                 } catch (RtAudioError& e) {
532 #endif
533                         error_dialog (
534                                 _video_view->get(),
535                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
536                                 );
537                 }
538                 recreate_butler ();
539
540         } else {
541                 _audio_channels = 0;
542                 recreate_butler ();
543         }
544 }
545
546 DCPTime
547 FilmViewer::uncorrected_time () const
548 {
549         if (_audio.isStreamRunning ()) {
550                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
551         }
552
553         return _video_view->position();
554 }
555
556 optional<DCPTime>
557 FilmViewer::audio_time () const
558 {
559         if (!_audio.isStreamRunning()) {
560                 return optional<DCPTime>();
561         }
562
563         return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
564                 DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
565 }
566
567 DCPTime
568 FilmViewer::time () const
569 {
570         return audio_time().get_value_or(_video_view->position());
571 }
572
573 int
574 FilmViewer::audio_callback (void* out_p, unsigned int frames)
575 {
576         while (true) {
577                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
578                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
579                         /* There was an underrun or this audio is on time; carry on */
580                         break;
581                 }
582                 /* The audio we just got was (very) late; drop it and get some more. */
583         }
584
585         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
586         if (lm) {
587                 _latency_history.push_back (_audio.getStreamLatency ());
588                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
589                         _latency_history.pop_front ();
590                 }
591         }
592
593         return 0;
594 }
595
596 Frame
597 FilmViewer::average_latency () const
598 {
599         boost::mutex::scoped_lock lm (_latency_history_mutex);
600         if (_latency_history.empty()) {
601                 return 0;
602         }
603
604         Frame total = 0;
605         BOOST_FOREACH (Frame i, _latency_history) {
606                 total += i;
607         }
608
609         return total / _latency_history.size();
610 }
611
612 void
613 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
614 {
615         _dcp_decode_reduction = reduction;
616         if (_player) {
617                 _player->set_dcp_decode_reduction (reduction);
618         }
619 }
620
621 optional<int>
622 FilmViewer::dcp_decode_reduction () const
623 {
624         return _dcp_decode_reduction;
625 }
626
627 DCPTime
628 FilmViewer::one_video_frame () const
629 {
630         return DCPTime::from_frames (1, _film ? _film->video_frame_rate() : 24);
631 }
632
633 /** Open a dialog box showing our film's closed captions */
634 void
635 FilmViewer::show_closed_captions ()
636 {
637         _closed_captions_dialog->Show();
638 }
639
640 void
641 FilmViewer::seek_by (DCPTime by, bool accurate)
642 {
643         seek (_video_view->position() + by, accurate);
644 }
645
646 void
647 FilmViewer::set_pad_black (bool p)
648 {
649         _pad_black = p;
650 }
651
652 /* May be called from a non-UI thread */
653 void
654 FilmViewer::emit_finished ()
655 {
656         emit (boost::bind(boost::ref(Finished)));
657 }
658