Fix various problems with the closed caption viewer not being updated properly.
[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 #include "lib/text_content.h"
51 extern "C" {
52 #include <libavutil/pixfmt.h>
53 }
54 #include <dcp/exceptions.h>
55 #include <wx/tglbtn.h>
56 #include <iostream>
57 #include <iomanip>
58
59 using std::string;
60 using std::pair;
61 using std::min;
62 using std::max;
63 using std::cout;
64 using std::list;
65 using std::bad_alloc;
66 using std::make_pair;
67 using std::exception;
68 using boost::shared_ptr;
69 using boost::dynamic_pointer_cast;
70 using boost::weak_ptr;
71 using boost::optional;
72 using dcp::Size;
73 using namespace dcpomatic;
74
75 static
76 int
77 rtaudio_callback (void* out, void *, unsigned int frames, double, RtAudioStreamStatus, void* data)
78 {
79         return reinterpret_cast<FilmViewer*>(data)->audio_callback (out, frames);
80 }
81
82 FilmViewer::FilmViewer (wxWindow* p)
83         : _coalesce_player_changes (false)
84         , _audio (DCPOMATIC_RTAUDIO_API)
85         , _audio_channels (0)
86         , _audio_block_size (1024)
87         , _playing (false)
88         , _suspended (0)
89         , _latency_history_count (0)
90         , _closed_captions_dialog (new ClosedCaptionsDialog(p, this))
91         , _outline_content (false)
92         , _pad_black (false)
93 #ifdef DCPOMATIC_VARIANT_SWAROOP
94         , _background_image (false)
95 #endif
96         , _idle_get (false)
97 {
98         switch (Config::instance()->video_view_type()) {
99         case Config::VIDEO_VIEW_OPENGL:
100                 _video_view = new GLVideoView (this, p);
101                 break;
102         case Config::VIDEO_VIEW_SIMPLE:
103                 _video_view = new SimpleVideoView (this, p);
104                 break;
105         }
106
107         _video_view->Sized.connect (boost::bind(&FilmViewer::video_view_sized, this));
108
109         set_film (shared_ptr<Film> ());
110
111         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
112         config_changed (Config::SOUND_OUTPUT);
113 }
114
115 FilmViewer::~FilmViewer ()
116 {
117         stop ();
118 }
119
120 /** Ask for ::get() to be called next time we are idle */
121 void
122 FilmViewer::request_idle_display_next_frame ()
123 {
124         if (_idle_get) {
125                 return;
126         }
127
128         _idle_get = true;
129         DCPOMATIC_ASSERT (signal_manager);
130         signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
131 }
132
133 void
134 FilmViewer::idle_handler ()
135 {
136         if (!_idle_get) {
137                 return;
138         }
139
140         if (_video_view->display_next_frame(true)) {
141                 _idle_get = false;
142         } else {
143                 /* get() could not complete quickly so we'll try again later */
144                 signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
145         }
146 }
147
148 void
149 FilmViewer::set_film (shared_ptr<Film> film)
150 {
151         if (_film == film) {
152                 return;
153         }
154
155         _film = film;
156
157         _video_view->clear ();
158         _closed_captions_dialog->clear ();
159
160         if (!_film) {
161                 _player.reset ();
162                 recreate_butler ();
163                 _video_view->update ();
164                 return;
165         }
166
167         try {
168                 _player.reset (new Player(_film));
169                 _player->set_fast ();
170                 if (_dcp_decode_reduction) {
171                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
172                 }
173         } catch (bad_alloc &) {
174                 error_dialog (_video_view->get(), _("There is not enough free memory to do that."));
175                 _film.reset ();
176                 return;
177         }
178
179         _player->set_always_burn_open_subtitles ();
180         _player->set_play_referenced ();
181
182         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
183         _film->ContentChange.connect (boost::bind(&FilmViewer::content_change, this, _1, _3));
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         film_change (CHANGE_TYPE_DONE, Film::VIDEO_FRAME_RATE);
188         film_change (CHANGE_TYPE_DONE, Film::THREE_D);
189         film_length_change ();
190
191         /* Keep about 1 second's worth of history samples */
192         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
193
194         recreate_butler ();
195
196         calculate_sizes ();
197         slow_refresh ();
198 }
199
200 void
201 FilmViewer::recreate_butler ()
202 {
203         suspend ();
204         _butler.reset ();
205
206         if (!_film) {
207                 resume ();
208                 return;
209         }
210
211         _butler.reset(
212                 new Butler(
213                         _player,
214                         Config::instance()->audio_mapping(_audio_channels),
215                         _audio_channels,
216                         bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24),
217                         false,
218                         true
219                         )
220                 );
221
222         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
223                 _butler->disable_audio ();
224         }
225
226         _closed_captions_dialog->set_butler (_butler);
227
228         resume ();
229 }
230
231 void
232 FilmViewer::set_outline_content (bool o)
233 {
234         _outline_content = o;
235         _video_view->update ();
236 }
237
238
239 void
240 FilmViewer::set_outline_subtitles (optional<dcpomatic::Rect<double> > rect)
241 {
242         _outline_subtitles = rect;
243         _video_view->update ();
244 }
245
246
247 void
248 FilmViewer::set_eyes (Eyes e)
249 {
250         _video_view->set_eyes (e);
251         slow_refresh ();
252 }
253
254 void
255 FilmViewer::video_view_sized ()
256 {
257         calculate_sizes ();
258         if (!quick_refresh()) {
259                 slow_refresh ();
260         }
261 }
262
263 void
264 FilmViewer::calculate_sizes ()
265 {
266         if (!_film || !_player) {
267                 return;
268         }
269
270         Ratio const * container = _film->container ();
271
272         float const view_ratio = float(_video_view->get()->GetSize().x) / _video_view->get()->GetSize().y;
273         float const film_ratio = container ? container->ratio () : 1.78;
274
275         if (view_ratio < film_ratio) {
276                 /* panel is less widscreen than the film; clamp width */
277                 _out_size.width = _video_view->get()->GetSize().x;
278                 _out_size.height = lrintf (_out_size.width / film_ratio);
279         } else {
280                 /* panel is more widescreen than the film; clamp height */
281                 _out_size.height = _video_view->get()->GetSize().y;
282                 _out_size.width = lrintf (_out_size.height * film_ratio);
283         }
284
285         /* Catch silly values */
286         _out_size.width = max (64, _out_size.width);
287         _out_size.height = max (64, _out_size.height);
288
289         _player->set_video_container_size (_out_size);
290 }
291
292 void
293 FilmViewer::suspend ()
294 {
295         ++_suspended;
296         if (_audio.isStreamRunning()) {
297                 _audio.abortStream();
298         }
299 }
300
301 void
302 FilmViewer::resume ()
303 {
304         DCPOMATIC_ASSERT (_suspended > 0);
305         --_suspended;
306         if (_playing && !_suspended) {
307                 if (_audio.isStreamOpen()) {
308                         _audio.setStreamTime (_video_view->position().seconds());
309                         _audio.startStream ();
310                 }
311                 _video_view->start ();
312         }
313 }
314
315 void
316 FilmViewer::start ()
317 {
318         if (!_film) {
319                 return;
320         }
321
322         optional<bool> v = PlaybackPermitted ();
323         if (v && !*v) {
324                 /* Computer says no */
325                 return;
326         }
327
328         /* We are about to set up the audio stream from the position of the video view.
329            If there is `lazy' seek in progress we need to wait for it to go through so that
330            _video_view->position() gives us a sensible answer.
331          */
332         while (_idle_get) {
333                 idle_handler ();
334         }
335
336         /* Take the video view's idea of position as our `playhead' and start the
337            audio stream (which is the timing reference) there.
338          */
339         if (_audio.isStreamOpen()) {
340                 _audio.setStreamTime (_video_view->position().seconds());
341                 _audio.startStream ();
342         }
343
344         _playing = true;
345         _video_view->start ();
346         Started (position());
347 }
348
349 bool
350 FilmViewer::stop ()
351 {
352         if (_audio.isStreamRunning()) {
353                 /* stop stream and discard any remaining queued samples */
354                 _audio.abortStream ();
355         }
356
357         if (!_playing) {
358                 return false;
359         }
360
361         _playing = false;
362         _video_view->stop ();
363         Stopped (position());
364
365         _video_view->rethrow ();
366         return true;
367 }
368
369 void
370 FilmViewer::player_change (ChangeType type, int property, bool frequent)
371 {
372         if (type != CHANGE_TYPE_DONE || frequent) {
373                 return;
374         }
375
376         if (_coalesce_player_changes) {
377                 _pending_player_changes.push_back (property);
378                 return;
379         }
380
381         calculate_sizes ();
382         bool refreshed = false;
383         if (
384                 property == VideoContentProperty::CROP ||
385                 property == VideoContentProperty::SCALE ||
386                 property == VideoContentProperty::FADE_IN ||
387                 property == VideoContentProperty::FADE_OUT ||
388                 property == VideoContentProperty::COLOUR_CONVERSION ||
389                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
390                 property == PlayerProperty::FILM_CONTAINER
391                 ) {
392                 refreshed = quick_refresh ();
393         }
394
395         if (!refreshed) {
396                 slow_refresh ();
397         }
398 }
399
400 void
401 FilmViewer::film_change (ChangeType type, Film::Property p)
402 {
403         if (type != CHANGE_TYPE_DONE) {
404                 return;
405         }
406
407         if (p == Film::AUDIO_CHANNELS) {
408                 recreate_butler ();
409         } else if (p == Film::VIDEO_FRAME_RATE) {
410                 _video_view->set_video_frame_rate (_film->video_frame_rate());
411         } else if (p == Film::THREE_D) {
412                 _video_view->set_three_d (_film->three_d());
413         } else if (p == Film::CONTENT) {
414                 _closed_captions_dialog->update_tracks (_film);
415         }
416 }
417
418 void
419 FilmViewer::film_length_change ()
420 {
421         _video_view->set_length (_film->length());
422 }
423
424 /** Re-get the current frame slowly by seeking */
425 void
426 FilmViewer::slow_refresh ()
427 {
428         seek (_video_view->position(), true);
429 }
430
431 /** Try to re-get the current frame quickly by resetting the metadata
432  *  in the PlayerVideo that we used last time.
433  *  @return true if this was possible, false if not.
434  */
435 bool
436 FilmViewer::quick_refresh ()
437 {
438         if (!_video_view || !_film || !_player) {
439                 return true;
440         }
441         return _video_view->refresh_metadata (_film, _player->video_container_size(), _film->frame_size());
442 }
443
444 void
445 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
446 {
447         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
448         if (dt) {
449                 seek (*dt, accurate);
450         }
451 }
452
453 void
454 FilmViewer::set_coalesce_player_changes (bool c)
455 {
456         _coalesce_player_changes = c;
457
458         if (!c) {
459                 BOOST_FOREACH (int i, _pending_player_changes) {
460                         player_change (CHANGE_TYPE_DONE, i, false);
461                 }
462                 _pending_player_changes.clear ();
463         }
464 }
465
466 void
467 FilmViewer::seek (DCPTime t, bool accurate)
468 {
469         if (!_butler) {
470                 return;
471         }
472
473         if (t < DCPTime ()) {
474                 t = DCPTime ();
475         }
476
477         if (t >= _film->length ()) {
478                 t = _film->length() - one_video_frame();
479         }
480
481         suspend ();
482
483         _closed_captions_dialog->clear ();
484         _butler->seek (t, accurate);
485
486         if (!_playing) {
487                 /* We're not playing, so let the GUI thread get on and
488                    come back later to get the next frame after the seek.
489                 */
490                 request_idle_display_next_frame ();
491         } else {
492                 /* We're going to start playing again straight away
493                    so wait for the seek to finish.
494                 */
495                 while (!_video_view->display_next_frame(false)) {}
496         }
497
498         resume ();
499 }
500
501 void
502 FilmViewer::config_changed (Config::Property p)
503 {
504 #ifdef DCPOMATIC_VARIANT_SWAROOP
505         if (p == Config::PLAYER_BACKGROUND_IMAGE) {
506                 _video_view->update ();
507                 return;
508         }
509 #endif
510
511         if (p == Config::AUDIO_MAPPING) {
512                 recreate_butler ();
513                 return;
514         }
515
516         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
517                 return;
518         }
519
520         if (_audio.isStreamOpen ()) {
521                 _audio.closeStream ();
522         }
523
524         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
525                 unsigned int st = 0;
526                 if (Config::instance()->sound_output()) {
527                         while (st < _audio.getDeviceCount()) {
528                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
529                                         break;
530                                 }
531                                 ++st;
532                         }
533                         if (st == _audio.getDeviceCount()) {
534                                 st = _audio.getDefaultOutputDevice();
535                         }
536                 } else {
537                         st = _audio.getDefaultOutputDevice();
538                 }
539
540                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
541
542                 RtAudio::StreamParameters sp;
543                 sp.deviceId = st;
544                 sp.nChannels = _audio_channels;
545                 sp.firstChannel = 0;
546                 try {
547                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
548 #ifdef DCPOMATIC_USE_RTERROR
549                 } catch (RtError& e) {
550 #else
551                 } catch (RtAudioError& e) {
552 #endif
553                         error_dialog (
554                                 _video_view->get(),
555                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
556                                 );
557                 }
558                 recreate_butler ();
559
560         } else {
561                 _audio_channels = 0;
562                 recreate_butler ();
563         }
564 }
565
566 DCPTime
567 FilmViewer::uncorrected_time () const
568 {
569         if (_audio.isStreamRunning ()) {
570                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
571         }
572
573         return _video_view->position();
574 }
575
576 optional<DCPTime>
577 FilmViewer::audio_time () const
578 {
579         if (!_audio.isStreamRunning()) {
580                 return optional<DCPTime>();
581         }
582
583         return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
584                 DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
585 }
586
587 DCPTime
588 FilmViewer::time () const
589 {
590         return audio_time().get_value_or(_video_view->position());
591 }
592
593 int
594 FilmViewer::audio_callback (void* out_p, unsigned int frames)
595 {
596         while (true) {
597                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
598                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
599                         /* There was an underrun or this audio is on time; carry on */
600                         break;
601                 }
602                 /* The audio we just got was (very) late; drop it and get some more. */
603         }
604
605         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
606         if (lm) {
607                 _latency_history.push_back (_audio.getStreamLatency ());
608                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
609                         _latency_history.pop_front ();
610                 }
611         }
612
613         return 0;
614 }
615
616 Frame
617 FilmViewer::average_latency () const
618 {
619         boost::mutex::scoped_lock lm (_latency_history_mutex);
620         if (_latency_history.empty()) {
621                 return 0;
622         }
623
624         Frame total = 0;
625         BOOST_FOREACH (Frame i, _latency_history) {
626                 total += i;
627         }
628
629         return total / _latency_history.size();
630 }
631
632 void
633 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
634 {
635         _dcp_decode_reduction = reduction;
636         if (_player) {
637                 _player->set_dcp_decode_reduction (reduction);
638         }
639 }
640
641 optional<int>
642 FilmViewer::dcp_decode_reduction () const
643 {
644         return _dcp_decode_reduction;
645 }
646
647 DCPTime
648 FilmViewer::one_video_frame () const
649 {
650         return DCPTime::from_frames (1, _film ? _film->video_frame_rate() : 24);
651 }
652
653 /** Open a dialog box showing our film's closed captions */
654 void
655 FilmViewer::show_closed_captions ()
656 {
657         _closed_captions_dialog->Show();
658 }
659
660 void
661 FilmViewer::seek_by (DCPTime by, bool accurate)
662 {
663         seek (_video_view->position() + by, accurate);
664 }
665
666 void
667 FilmViewer::set_pad_black (bool p)
668 {
669         _pad_black = p;
670 }
671
672 /** Called when a player has finished the current film.
673  *  May be called from a non-UI thread.
674  */
675 void
676 FilmViewer::finished ()
677 {
678         emit (boost::bind(&FilmViewer::ui_finished, this));
679 }
680
681 /** Called by finished() in the UI thread */
682 void
683 FilmViewer::ui_finished ()
684 {
685         stop ();
686         Finished ();
687 }
688
689 int
690 FilmViewer::dropped () const
691 {
692         return _video_view->dropped ();
693 }
694
695
696 int
697 FilmViewer::errored () const
698 {
699         return _video_view->errored ();
700 }
701
702
703 int
704 FilmViewer::gets () const
705 {
706         return _video_view->gets ();
707 }
708
709
710 void
711 FilmViewer::content_change (ChangeType type, int property)
712 {
713         if (type != CHANGE_TYPE_DONE) {
714                 return;
715         }
716
717         if (property == TextContentProperty::USE || property == TextContentProperty::TYPE || property == TextContentProperty::DCP_TRACK) {
718                 _closed_captions_dialog->update_tracks (_film);
719         }
720 }
721