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