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