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