Various timing hacks and development.
[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         _video_view->clear ();
160
161         _video_view->set_image (shared_ptr<Image>());
162         _closed_captions_dialog->clear ();
163
164         if (!_film) {
165                 _player.reset ();
166                 recreate_butler ();
167                 refresh_view ();
168                 return;
169         }
170
171         try {
172                 _player.reset (new Player (_film, _film->playlist ()));
173                 _player->set_fast ();
174                 if (_dcp_decode_reduction) {
175                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
176                 }
177         } catch (bad_alloc &) {
178                 error_dialog (_video_view->get(), _("There is not enough free memory to do that."));
179                 _film.reset ();
180                 return;
181         }
182
183         _player->set_always_burn_open_subtitles ();
184         _player->set_play_referenced ();
185
186         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
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         _playing = true;
330         _dropped = 0;
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         Stopped (position());
349         return true;
350 }
351
352 void
353 FilmViewer::player_change (ChangeType type, int property, bool frequent)
354 {
355         if (type != CHANGE_TYPE_DONE || frequent) {
356                 return;
357         }
358
359         if (_coalesce_player_changes) {
360                 _pending_player_changes.push_back (property);
361                 return;
362         }
363
364         calculate_sizes ();
365         bool refreshed = false;
366         if (
367                 property == VideoContentProperty::CROP ||
368                 property == VideoContentProperty::SCALE ||
369                 property == VideoContentProperty::FADE_IN ||
370                 property == VideoContentProperty::FADE_OUT ||
371                 property == VideoContentProperty::COLOUR_CONVERSION ||
372                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
373                 property == PlayerProperty::FILM_CONTAINER
374                 ) {
375                 refreshed = quick_refresh ();
376         }
377
378         if (!refreshed) {
379                 slow_refresh ();
380         }
381 }
382
383 void
384 FilmViewer::film_change (ChangeType type, Film::Property p)
385 {
386         if (type == CHANGE_TYPE_DONE && p == Film::AUDIO_CHANNELS) {
387                 recreate_butler ();
388         }
389 }
390
391 /** Re-get the current frame slowly by seeking */
392 void
393 FilmViewer::slow_refresh ()
394 {
395         seek (_video_view->position(), true);
396 }
397
398 /** Try to re-get the current frame quickly by resetting the metadata
399  *  in the PlayerVideo that we used last time.
400  *  @return true if this was possible, false if not.
401  */
402 bool
403 FilmViewer::quick_refresh ()
404 {
405         if (!_video_view->_player_video.first) {
406                 return false;
407         }
408
409         if (!_video_view->_player_video.first->reset_metadata (_film, _player->video_container_size(), _film->frame_size())) {
410                 return false;
411         }
412
413         _video_view->display_player_video ();
414         return true;
415 }
416
417 void
418 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
419 {
420         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
421         if (dt) {
422                 seek (*dt, accurate);
423         }
424 }
425
426 void
427 FilmViewer::set_coalesce_player_changes (bool c)
428 {
429         _coalesce_player_changes = c;
430
431         if (!c) {
432                 BOOST_FOREACH (int i, _pending_player_changes) {
433                         player_change (CHANGE_TYPE_DONE, i, false);
434                 }
435                 _pending_player_changes.clear ();
436         }
437 }
438
439 void
440 FilmViewer::seek (DCPTime t, bool accurate)
441 {
442         if (!_butler) {
443                 return;
444         }
445
446         if (t < DCPTime ()) {
447                 t = DCPTime ();
448         }
449
450         if (t >= _film->length ()) {
451                 t = _film->length ();
452         }
453
454         suspend ();
455
456         _closed_captions_dialog->clear ();
457         _butler->seek (t, accurate);
458
459         if (!_playing) {
460                 request_idle_display_next_frame ();
461         } else {
462                 while (!_video_view->display_next_frame(false)) {}
463         }
464
465         resume ();
466 }
467
468 void
469 FilmViewer::config_changed (Config::Property p)
470 {
471 #ifdef DCPOMATIC_VARIANT_SWAROOP
472         if (p == Config::PLAYER_BACKGROUND_IMAGE) {
473                 refresh_view ();
474                 return;
475         }
476 #endif
477
478         if (p == Config::AUDIO_MAPPING) {
479                 recreate_butler ();
480                 return;
481         }
482
483         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
484                 return;
485         }
486
487         if (_audio.isStreamOpen ()) {
488                 _audio.closeStream ();
489         }
490
491         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
492                 unsigned int st = 0;
493                 if (Config::instance()->sound_output()) {
494                         while (st < _audio.getDeviceCount()) {
495                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
496                                         break;
497                                 }
498                                 ++st;
499                         }
500                         if (st == _audio.getDeviceCount()) {
501                                 st = _audio.getDefaultOutputDevice();
502                         }
503                 } else {
504                         st = _audio.getDefaultOutputDevice();
505                 }
506
507                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
508
509                 RtAudio::StreamParameters sp;
510                 sp.deviceId = st;
511                 sp.nChannels = _audio_channels;
512                 sp.firstChannel = 0;
513                 try {
514                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
515 #ifdef DCPOMATIC_USE_RTERROR
516                 } catch (RtError& e) {
517 #else
518                 } catch (RtAudioError& e) {
519 #endif
520                         error_dialog (
521                                 _video_view->get(),
522                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
523                                 );
524                 }
525                 recreate_butler ();
526
527         } else {
528                 _audio_channels = 0;
529                 recreate_butler ();
530         }
531 }
532
533 DCPTime
534 FilmViewer::uncorrected_time () const
535 {
536         if (_audio.isStreamRunning ()) {
537                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
538         }
539
540         return _video_view->position();
541 }
542
543 DCPTime
544 FilmViewer::time () const
545 {
546         if (_audio.isStreamRunning ()) {
547                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
548                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
549         }
550
551         return _video_view->position();
552 }
553
554 int
555 FilmViewer::audio_callback (void* out_p, unsigned int frames)
556 {
557         while (true) {
558                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
559                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
560                         /* There was an underrun or this audio is on time; carry on */
561                         break;
562                 }
563                 /* The audio we just got was (very) late; drop it and get some more. */
564         }
565
566         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
567         if (lm) {
568                 _latency_history.push_back (_audio.getStreamLatency ());
569                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
570                         _latency_history.pop_front ();
571                 }
572         }
573
574         return 0;
575 }
576
577 Frame
578 FilmViewer::average_latency () const
579 {
580         boost::mutex::scoped_lock lm (_latency_history_mutex);
581         if (_latency_history.empty()) {
582                 return 0;
583         }
584
585         Frame total = 0;
586         BOOST_FOREACH (Frame i, _latency_history) {
587                 total += i;
588         }
589
590         return total / _latency_history.size();
591 }
592
593 void
594 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
595 {
596         _dcp_decode_reduction = reduction;
597         if (_player) {
598                 _player->set_dcp_decode_reduction (reduction);
599         }
600 }
601
602 optional<int>
603 FilmViewer::dcp_decode_reduction () const
604 {
605         return _dcp_decode_reduction;
606 }
607
608 DCPTime
609 FilmViewer::one_video_frame () const
610 {
611         return DCPTime::from_frames (1, _film ? _film->video_frame_rate() : 24);
612 }
613
614 /** Open a dialog box showing our film's closed captions */
615 void
616 FilmViewer::show_closed_captions ()
617 {
618         _closed_captions_dialog->Show();
619 }
620
621 void
622 FilmViewer::seek_by (DCPTime by, bool accurate)
623 {
624         seek (_video_view->position() + by, accurate);
625 }
626
627 void
628 FilmViewer::set_pad_black (bool p)
629 {
630         _pad_black = p;
631 }
632
633 /* XXX_b: comment */
634 int
635 FilmViewer::time_until_next_frame () const
636 {
637         DCPTime const next = position() + one_video_frame();
638         std::cout << to_string(next) << " " << to_string(time()) << " " << ((next.seconds() - time().seconds()) * 1000) << "\n";
639         if (next < time()) {
640                 return 0;
641         }
642         return (next.seconds() - time().seconds()) * 1000;
643 }