Fix some crashes.
[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         , _pad_black (false)
92 #ifdef DCPOMATIC_VARIANT_SWAROOP
93         , _background_image (false)
94 #endif
95         , _idle_get (false)
96 {
97         switch (Config::instance()->video_view_type()) {
98         case Config::VIDEO_VIEW_OPENGL:
99                 _video_view = new GLVideoView (this, p);
100                 break;
101         case Config::VIDEO_VIEW_SIMPLE:
102                 _video_view = new SimpleVideoView (this, p);
103                 break;
104         }
105
106         _video_view->Sized.connect (boost::bind(&FilmViewer::video_view_sized, this));
107
108         set_film (shared_ptr<Film> ());
109
110         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
111         config_changed (Config::SOUND_OUTPUT);
112 }
113
114 FilmViewer::~FilmViewer ()
115 {
116         stop ();
117 }
118
119 /** Ask for ::get() to be called next time we are idle */
120 void
121 FilmViewer::request_idle_display_next_frame ()
122 {
123         if (_idle_get) {
124                 return;
125         }
126
127         _idle_get = true;
128         DCPOMATIC_ASSERT (signal_manager);
129         signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
130 }
131
132 void
133 FilmViewer::idle_handler ()
134 {
135         if (!_idle_get) {
136                 return;
137         }
138
139         if (_video_view->display_next_frame(true)) {
140                 _idle_get = false;
141         } else {
142                 /* get() could not complete quickly so we'll try again later */
143                 signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
144         }
145 }
146
147 void
148 FilmViewer::set_film (shared_ptr<Film> film)
149 {
150         if (_film == film) {
151                 return;
152         }
153
154         _film = film;
155
156         _video_view->clear ();
157         _closed_captions_dialog->clear ();
158
159         if (!_film) {
160                 _player.reset ();
161                 recreate_butler ();
162                 _video_view->update ();
163                 return;
164         }
165
166         try {
167                 _player.reset (new Player (_film, _film->playlist ()));
168                 _player->set_fast ();
169                 if (_dcp_decode_reduction) {
170                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
171                 }
172         } catch (bad_alloc &) {
173                 error_dialog (_video_view->get(), _("There is not enough free memory to do that."));
174                 _film.reset ();
175                 return;
176         }
177
178         _player->set_always_burn_open_subtitles ();
179         _player->set_play_referenced ();
180
181         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
182         _film->LengthChange.connect (boost::bind(&FilmViewer::film_length_change, this));
183         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
184
185         /* Keep about 1 second's worth of history samples */
186         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
187
188         recreate_butler ();
189
190         calculate_sizes ();
191         slow_refresh ();
192 }
193
194 void
195 FilmViewer::recreate_butler ()
196 {
197         suspend ();
198         _butler.reset ();
199
200         if (!_film) {
201                 resume ();
202                 return;
203         }
204
205         _butler.reset(
206                 new Butler(
207                         _player,
208                         Config::instance()->audio_mapping(_audio_channels),
209                         _audio_channels,
210                         bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24),
211                         false,
212                         true
213                         )
214                 );
215
216         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
217                 _butler->disable_audio ();
218         }
219
220         _closed_captions_dialog->set_film_and_butler (_film, _butler);
221
222         resume ();
223 }
224
225 void
226 FilmViewer::set_outline_content (bool o)
227 {
228         _outline_content = o;
229         _video_view->update ();
230 }
231
232 void
233 FilmViewer::set_eyes (Eyes e)
234 {
235         _video_view->set_eyes (e);
236         slow_refresh ();
237 }
238
239 void
240 FilmViewer::video_view_sized ()
241 {
242         calculate_sizes ();
243         if (!quick_refresh()) {
244                 slow_refresh ();
245         }
246 }
247
248 void
249 FilmViewer::calculate_sizes ()
250 {
251         if (!_film || !_player) {
252                 return;
253         }
254
255         Ratio const * container = _film->container ();
256
257         float const view_ratio = float(_video_view->get()->GetSize().x) / _video_view->get()->GetSize().y;
258         float const film_ratio = container ? container->ratio () : 1.78;
259
260         if (view_ratio < film_ratio) {
261                 /* panel is less widscreen than the film; clamp width */
262                 _out_size.width = _video_view->get()->GetSize().x;
263                 _out_size.height = lrintf (_out_size.width / film_ratio);
264         } else {
265                 /* panel is more widescreen than the film; clamp height */
266                 _out_size.height = _video_view->get()->GetSize().y;
267                 _out_size.width = lrintf (_out_size.height * film_ratio);
268         }
269
270         /* Catch silly values */
271         _out_size.width = max (64, _out_size.width);
272         _out_size.height = max (64, _out_size.height);
273
274         _player->set_video_container_size (_out_size);
275 }
276
277 void
278 FilmViewer::suspend ()
279 {
280         ++_suspended;
281         if (_audio.isStreamRunning()) {
282                 _audio.abortStream();
283         }
284 }
285
286 void
287 FilmViewer::resume ()
288 {
289         --_suspended;
290         if (_playing && !_suspended) {
291                 if (_audio.isStreamOpen()) {
292                         _audio.setStreamTime (_video_view->position().seconds());
293                         _audio.startStream ();
294                 }
295                 _video_view->start ();
296         }
297 }
298
299 void
300 FilmViewer::start ()
301 {
302         if (!_film) {
303                 return;
304         }
305
306         optional<bool> v = PlaybackPermitted ();
307         if (v && !*v) {
308                 /* Computer says no */
309                 return;
310         }
311
312         if (_audio.isStreamOpen()) {
313                 _audio.setStreamTime (_video_view->position().seconds());
314                 _audio.startStream ();
315         }
316
317         _playing = true;
318         _video_view->start ();
319         Started (position());
320 }
321
322 bool
323 FilmViewer::stop ()
324 {
325         if (_audio.isStreamRunning()) {
326                 /* stop stream and discard any remaining queued samples */
327                 _audio.abortStream ();
328         }
329
330         if (!_playing) {
331                 return false;
332         }
333
334         _playing = false;
335         _video_view->stop ();
336         Stopped (position());
337
338         _video_view->rethrow ();
339         return true;
340 }
341
342 void
343 FilmViewer::player_change (ChangeType type, int property, bool frequent)
344 {
345         if (type != CHANGE_TYPE_DONE || frequent) {
346                 return;
347         }
348
349         if (_coalesce_player_changes) {
350                 _pending_player_changes.push_back (property);
351                 return;
352         }
353
354         calculate_sizes ();
355         bool refreshed = false;
356         if (
357                 property == VideoContentProperty::CROP ||
358                 property == VideoContentProperty::SCALE ||
359                 property == VideoContentProperty::FADE_IN ||
360                 property == VideoContentProperty::FADE_OUT ||
361                 property == VideoContentProperty::COLOUR_CONVERSION ||
362                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
363                 property == PlayerProperty::FILM_CONTAINER
364                 ) {
365                 refreshed = quick_refresh ();
366         }
367
368         if (!refreshed) {
369                 slow_refresh ();
370         }
371 }
372
373 void
374 FilmViewer::film_change (ChangeType type, Film::Property p)
375 {
376         if (type != CHANGE_TYPE_DONE) {
377                 return;
378         }
379
380         if (p == Film::AUDIO_CHANNELS) {
381                 recreate_butler ();
382         } else if (p == Film::VIDEO_FRAME_RATE) {
383                 _video_view->set_video_frame_rate (_film->video_frame_rate());
384         } else if (p == Film::THREE_D) {
385                 _video_view->set_three_d (_film->three_d());
386         }
387 }
388
389 void
390 FilmViewer::film_length_change ()
391 {
392         _video_view->set_length (_film->length());
393 }
394
395 /** Re-get the current frame slowly by seeking */
396 void
397 FilmViewer::slow_refresh ()
398 {
399         seek (_video_view->position(), true);
400 }
401
402 /** Try to re-get the current frame quickly by resetting the metadata
403  *  in the PlayerVideo that we used last time.
404  *  @return true if this was possible, false if not.
405  */
406 bool
407 FilmViewer::quick_refresh ()
408 {
409         if (!_video_view || !_film) {
410                 return true;
411         }
412         return _video_view->refresh_metadata (_film, _player->video_container_size(), _film->frame_size());
413 }
414
415 void
416 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
417 {
418         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
419         if (dt) {
420                 seek (*dt, accurate);
421         }
422 }
423
424 void
425 FilmViewer::set_coalesce_player_changes (bool c)
426 {
427         _coalesce_player_changes = c;
428
429         if (!c) {
430                 BOOST_FOREACH (int i, _pending_player_changes) {
431                         player_change (CHANGE_TYPE_DONE, i, false);
432                 }
433                 _pending_player_changes.clear ();
434         }
435 }
436
437 void
438 FilmViewer::seek (DCPTime t, bool accurate)
439 {
440         if (!_butler) {
441                 return;
442         }
443
444         if (t < DCPTime ()) {
445                 t = DCPTime ();
446         }
447
448         if (t >= _film->length ()) {
449                 t = _film->length ();
450         }
451
452         suspend ();
453
454         _closed_captions_dialog->clear ();
455         _butler->seek (t, accurate);
456
457         if (!_playing) {
458                 request_idle_display_next_frame ();
459         } else {
460                 while (!_video_view->display_next_frame(false)) {}
461         }
462
463         resume ();
464 }
465
466 void
467 FilmViewer::config_changed (Config::Property p)
468 {
469 #ifdef DCPOMATIC_VARIANT_SWAROOP
470         if (p == Config::PLAYER_BACKGROUND_IMAGE) {
471                 _video_view->update ();
472                 return;
473         }
474 #endif
475
476         if (p == Config::AUDIO_MAPPING) {
477                 recreate_butler ();
478                 return;
479         }
480
481         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
482                 return;
483         }
484
485         if (_audio.isStreamOpen ()) {
486                 _audio.closeStream ();
487         }
488
489         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
490                 unsigned int st = 0;
491                 if (Config::instance()->sound_output()) {
492                         while (st < _audio.getDeviceCount()) {
493                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
494                                         break;
495                                 }
496                                 ++st;
497                         }
498                         if (st == _audio.getDeviceCount()) {
499                                 st = _audio.getDefaultOutputDevice();
500                         }
501                 } else {
502                         st = _audio.getDefaultOutputDevice();
503                 }
504
505                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
506
507                 RtAudio::StreamParameters sp;
508                 sp.deviceId = st;
509                 sp.nChannels = _audio_channels;
510                 sp.firstChannel = 0;
511                 try {
512                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
513 #ifdef DCPOMATIC_USE_RTERROR
514                 } catch (RtError& e) {
515 #else
516                 } catch (RtAudioError& e) {
517 #endif
518                         error_dialog (
519                                 _video_view->get(),
520                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
521                                 );
522                 }
523                 recreate_butler ();
524
525         } else {
526                 _audio_channels = 0;
527                 recreate_butler ();
528         }
529 }
530
531 DCPTime
532 FilmViewer::uncorrected_time () const
533 {
534         if (_audio.isStreamRunning ()) {
535                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
536         }
537
538         return _video_view->position();
539 }
540
541 optional<DCPTime>
542 FilmViewer::audio_time () const
543 {
544         if (!_audio.isStreamRunning()) {
545                 return optional<DCPTime>();
546         }
547
548         return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
549                 DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
550 }
551
552 DCPTime
553 FilmViewer::time () const
554 {
555         return audio_time().get_value_or(_video_view->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_view->position() + by, accurate);
629 }
630
631 void
632 FilmViewer::set_pad_black (bool p)
633 {
634         _pad_black = p;
635 }
636
637 /** Called when a player has finished the current film.
638  *  May be called from a non-UI thread.
639  */
640 void
641 FilmViewer::finished ()
642 {
643         emit (boost::bind(&FilmViewer::ui_finished, this));
644 }
645
646 /** Called by finished() in the UI thread */
647 void
648 FilmViewer::ui_finished ()
649 {
650         stop ();
651         Finished ();
652 }
653
654 int
655 FilmViewer::dropped () const
656 {
657         return _video_view->dropped ();
658 }
659
660 int
661 FilmViewer::gets () const
662 {
663         return _video_view->gets ();
664 }
665
666