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