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