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