be555ad91f556beb19937d4585408af0d6f44e7d
[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_get ()
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 (get(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         _video_position = DCPTime ();
160         _player_video.first.reset ();
161         _player_video.second = DCPTime ();
162
163         _video_view->set_image (shared_ptr<Image>());
164         _closed_captions_dialog->clear ();
165
166         if (!_film) {
167                 _player.reset ();
168                 recreate_butler ();
169                 refresh_view ();
170                 return;
171         }
172
173         try {
174                 _player.reset (new Player (_film, _film->playlist ()));
175                 _player->set_fast ();
176                 if (_dcp_decode_reduction) {
177                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
178                 }
179         } catch (bad_alloc &) {
180                 error_dialog (_video_view->get(), _("There is not enough free memory to do that."));
181                 _film.reset ();
182                 return;
183         }
184
185         _player->set_always_burn_open_subtitles ();
186         _player->set_play_referenced ();
187
188         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
189         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
190
191         /* Keep about 1 second's worth of history samples */
192         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
193
194         recreate_butler ();
195
196         calculate_sizes ();
197         slow_refresh ();
198 }
199
200 void
201 FilmViewer::recreate_butler ()
202 {
203         suspend ();
204         _butler.reset ();
205
206         if (!_film) {
207                 resume ();
208                 return;
209         }
210
211         _butler.reset(
212                 new Butler(
213                         _player,
214                         Config::instance()->audio_mapping(_audio_channels),
215                         _audio_channels,
216                         bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24),
217                         false,
218                         true
219                         )
220                 );
221
222         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
223                 _butler->disable_audio ();
224         }
225
226         _closed_captions_dialog->set_film_and_butler (_film, _butler);
227
228         resume ();
229 }
230
231 void
232 FilmViewer::refresh_view ()
233 {
234         _state_timer.set ("update-view");
235         _video_view->update ();
236         _state_timer.unset ();
237 }
238
239 /** Try to get a frame from the butler and display it.
240  *  @param lazy true to return false quickly if no video is available quickly (i.e. we are waiting for the butler).
241  *  false to ask the butler to block until it has video (unless it is suspended).
242  *  @return true on success, false if we did nothing because it would have taken too long.
243  */
244 bool
245 FilmViewer::get (bool lazy)
246 {
247         DCPOMATIC_ASSERT (_butler);
248         ++_gets;
249
250         do {
251                 Butler::Error e;
252                 _player_video = _butler->get_video (!lazy, &e);
253                 if (!_player_video.first && e == Butler::AGAIN) {
254                         if (lazy) {
255                                 /* No video available; return saying we failed */
256                                 return false;
257                         } else {
258                                 /* Player was suspended; come back later */
259                                 signal_manager->when_idle (boost::bind(&FilmViewer::get, this, false));
260                                 return false;
261                         }
262                 }
263         } while (
264                 _player_video.first &&
265                 _film->three_d() &&
266                 _eyes != _player_video.first->eyes() &&
267                 _player_video.first->eyes() != EYES_BOTH
268                 );
269
270         try {
271                 _butler->rethrow ();
272         } catch (DecodeError& e) {
273                 error_dialog (_video_view->get(), e.what());
274         }
275
276         display_player_video ();
277         PositionChanged ();
278
279         return true;
280 }
281
282 void
283 FilmViewer::display_player_video ()
284 {
285         if (!_player_video.first) {
286                 _video_view->set_image (shared_ptr<Image>());
287                 refresh_view ();
288                 return;
289         }
290
291         if (_playing && !_suspended && (time() - _player_video.second) > one_video_frame()) {
292                 /* Too late; just drop this frame before we try to get its image (which will be the time-consuming
293                    part if this frame is J2K).
294                 */
295                 _video_position = _player_video.second;
296                 ++_dropped;
297                 return;
298         }
299
300         /* In an ideal world, what we would do here is:
301          *
302          * 1. convert to XYZ exactly as we do in the DCP creation path.
303          * 2. convert back to RGB for the preview display, compensating
304          *    for the monitor etc. etc.
305          *
306          * but this is inefficient if the source is RGB.  Since we don't
307          * (currently) care too much about the precise accuracy of the preview's
308          * colour mapping (and we care more about its speed) we try to short-
309          * circuit this "ideal" situation in some cases.
310          *
311          * The content's specified colour conversion indicates the colourspace
312          * which the content is in (according to the user).
313          *
314          * PlayerVideo::image (bound to PlayerVideo::force) will take the source
315          * image and convert it (from whatever the user has said it is) to RGB.
316          */
317
318         _state_timer.set ("get image");
319
320         _video_view->set_image (
321                 _player_video.first->image(bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), false, true)
322                 );
323
324         _state_timer.set ("ImageChanged");
325         ImageChanged (_player_video.first);
326         _state_timer.unset ();
327
328         _video_position = _player_video.second;
329         _inter_position = _player_video.first->inter_position ();
330         _inter_size = _player_video.first->inter_size ();
331
332         refresh_view ();
333
334         _closed_captions_dialog->update (time());
335 }
336
337 void
338 FilmViewer::set_outline_content (bool o)
339 {
340         _outline_content = o;
341         refresh_view ();
342 }
343
344 void
345 FilmViewer::set_eyes (Eyes e)
346 {
347         _eyes = e;
348         slow_refresh ();
349 }
350
351 void
352 FilmViewer::video_view_sized ()
353 {
354         calculate_sizes ();
355         if (!quick_refresh()) {
356                 slow_refresh ();
357         }
358         PositionChanged ();
359 }
360
361 void
362 FilmViewer::calculate_sizes ()
363 {
364         if (!_film || !_player) {
365                 return;
366         }
367
368         Ratio const * container = _film->container ();
369
370         float const view_ratio = float(_video_view->get()->GetSize().x) / _video_view->get()->GetSize().y;
371         float const film_ratio = container ? container->ratio () : 1.78;
372
373         if (view_ratio < film_ratio) {
374                 /* panel is less widscreen than the film; clamp width */
375                 _out_size.width = _video_view->get()->GetSize().x;
376                 _out_size.height = lrintf (_out_size.width / film_ratio);
377         } else {
378                 /* panel is more widescreen than the film; clamp height */
379                 _out_size.height = _video_view->get()->GetSize().y;
380                 _out_size.width = lrintf (_out_size.height * film_ratio);
381         }
382
383         /* Catch silly values */
384         _out_size.width = max (64, _out_size.width);
385         _out_size.height = max (64, _out_size.height);
386
387         _player->set_video_container_size (_out_size);
388 }
389
390 void
391 FilmViewer::suspend ()
392 {
393         ++_suspended;
394         if (_audio.isStreamRunning()) {
395                 _audio.abortStream();
396         }
397 }
398
399 void
400 FilmViewer::resume ()
401 {
402         --_suspended;
403         if (_playing && !_suspended) {
404                 if (_audio.isStreamOpen()) {
405                         _audio.setStreamTime (_video_position.seconds());
406                         _audio.startStream ();
407                 }
408                 timer ();
409         }
410 }
411
412 void
413 FilmViewer::start ()
414 {
415         if (!_film) {
416                 return;
417         }
418
419         optional<bool> v = PlaybackPermitted ();
420         if (v && !*v) {
421                 /* Computer says no */
422                 return;
423         }
424
425         if (_audio.isStreamOpen()) {
426                 _audio.setStreamTime (_video_position.seconds());
427                 _audio.startStream ();
428         }
429
430         _playing = true;
431         _dropped = 0;
432         _video_view->start ();
433         Started (position());
434 }
435
436 bool
437 FilmViewer::stop ()
438 {
439         if (_audio.isStreamRunning()) {
440                 /* stop stream and discard any remaining queued samples */
441                 _audio.abortStream ();
442         }
443
444         if (!_playing) {
445                 return false;
446         }
447
448         _playing = false;
449         Stopped (position());
450         return true;
451 }
452
453 void
454 FilmViewer::player_change (ChangeType type, int property, bool frequent)
455 {
456         if (type != CHANGE_TYPE_DONE || frequent) {
457                 return;
458         }
459
460         if (_coalesce_player_changes) {
461                 _pending_player_changes.push_back (property);
462                 return;
463         }
464
465         calculate_sizes ();
466         bool refreshed = false;
467         if (
468                 property == VideoContentProperty::CROP ||
469                 property == VideoContentProperty::SCALE ||
470                 property == VideoContentProperty::FADE_IN ||
471                 property == VideoContentProperty::FADE_OUT ||
472                 property == VideoContentProperty::COLOUR_CONVERSION ||
473                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
474                 property == PlayerProperty::FILM_CONTAINER
475                 ) {
476                 refreshed = quick_refresh ();
477         }
478
479         if (!refreshed) {
480                 slow_refresh ();
481         }
482         PositionChanged ();
483 }
484
485 void
486 FilmViewer::film_change (ChangeType type, Film::Property p)
487 {
488         if (type == CHANGE_TYPE_DONE && p == Film::AUDIO_CHANNELS) {
489                 recreate_butler ();
490         }
491 }
492
493 /** Re-get the current frame slowly by seeking */
494 void
495 FilmViewer::slow_refresh ()
496 {
497         seek (_video_position, true);
498 }
499
500 /** Try to re-get the current frame quickly by resetting the metadata
501  *  in the PlayerVideo that we used last time.
502  *  @return true if this was possible, false if not.
503  */
504 bool
505 FilmViewer::quick_refresh ()
506 {
507         if (!_player_video.first) {
508                 return false;
509         }
510
511         if (!_player_video.first->reset_metadata (_film, _player->video_container_size(), _film->frame_size())) {
512                 return false;
513         }
514
515         display_player_video ();
516         return true;
517 }
518
519 void
520 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
521 {
522         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
523         if (dt) {
524                 seek (*dt, accurate);
525         }
526 }
527
528 void
529 FilmViewer::set_coalesce_player_changes (bool c)
530 {
531         _coalesce_player_changes = c;
532
533         if (!c) {
534                 BOOST_FOREACH (int i, _pending_player_changes) {
535                         player_change (CHANGE_TYPE_DONE, i, false);
536                 }
537                 _pending_player_changes.clear ();
538         }
539 }
540
541 void
542 FilmViewer::seek (DCPTime t, bool accurate)
543 {
544         if (!_butler) {
545                 return;
546         }
547
548         if (t < DCPTime ()) {
549                 t = DCPTime ();
550         }
551
552         if (t >= _film->length ()) {
553                 t = _film->length ();
554         }
555
556         suspend ();
557
558         _closed_captions_dialog->clear ();
559         _butler->seek (t, accurate);
560
561         if (!_playing) {
562                 request_idle_get ();
563         } else {
564                 /* Make sure we get a frame so that _video_position is set up before we resume */
565                 while (!get(true)) {}
566         }
567
568         resume ();
569 }
570
571 void
572 FilmViewer::config_changed (Config::Property p)
573 {
574 #ifdef DCPOMATIC_VARIANT_SWAROOP
575         if (p == Config::PLAYER_BACKGROUND_IMAGE) {
576                 refresh_view ();
577                 return;
578         }
579 #endif
580
581         if (p == Config::AUDIO_MAPPING) {
582                 recreate_butler ();
583                 return;
584         }
585
586         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
587                 return;
588         }
589
590         if (_audio.isStreamOpen ()) {
591                 _audio.closeStream ();
592         }
593
594         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
595                 unsigned int st = 0;
596                 if (Config::instance()->sound_output()) {
597                         while (st < _audio.getDeviceCount()) {
598                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
599                                         break;
600                                 }
601                                 ++st;
602                         }
603                         if (st == _audio.getDeviceCount()) {
604                                 st = _audio.getDefaultOutputDevice();
605                         }
606                 } else {
607                         st = _audio.getDefaultOutputDevice();
608                 }
609
610                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
611
612                 RtAudio::StreamParameters sp;
613                 sp.deviceId = st;
614                 sp.nChannels = _audio_channels;
615                 sp.firstChannel = 0;
616                 try {
617                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
618 #ifdef DCPOMATIC_USE_RTERROR
619                 } catch (RtError& e) {
620 #else
621                 } catch (RtAudioError& e) {
622 #endif
623                         error_dialog (
624                                 _video_view->get(),
625                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
626                                 );
627                 }
628                 recreate_butler ();
629
630         } else {
631                 _audio_channels = 0;
632                 recreate_butler ();
633         }
634 }
635
636 DCPTime
637 FilmViewer::uncorrected_time () const
638 {
639         if (_audio.isStreamRunning ()) {
640                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
641         }
642
643         return _video_position;
644 }
645
646 DCPTime
647 FilmViewer::time () const
648 {
649         if (_audio.isStreamRunning ()) {
650                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
651                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
652         }
653
654         return _video_position;
655 }
656
657 int
658 FilmViewer::audio_callback (void* out_p, unsigned int frames)
659 {
660         while (true) {
661                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
662                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
663                         /* There was an underrun or this audio is on time; carry on */
664                         break;
665                 }
666                 /* The audio we just got was (very) late; drop it and get some more. */
667         }
668
669         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
670         if (lm) {
671                 _latency_history.push_back (_audio.getStreamLatency ());
672                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
673                         _latency_history.pop_front ();
674                 }
675         }
676
677         return 0;
678 }
679
680 Frame
681 FilmViewer::average_latency () const
682 {
683         boost::mutex::scoped_lock lm (_latency_history_mutex);
684         if (_latency_history.empty()) {
685                 return 0;
686         }
687
688         Frame total = 0;
689         BOOST_FOREACH (Frame i, _latency_history) {
690                 total += i;
691         }
692
693         return total / _latency_history.size();
694 }
695
696 void
697 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
698 {
699         _dcp_decode_reduction = reduction;
700         if (_player) {
701                 _player->set_dcp_decode_reduction (reduction);
702         }
703 }
704
705 optional<int>
706 FilmViewer::dcp_decode_reduction () const
707 {
708         return _dcp_decode_reduction;
709 }
710
711 DCPTime
712 FilmViewer::one_video_frame () const
713 {
714         return DCPTime::from_frames (1, _film ? _film->video_frame_rate() : 24);
715 }
716
717 /** Open a dialog box showing our film's closed captions */
718 void
719 FilmViewer::show_closed_captions ()
720 {
721         _closed_captions_dialog->Show();
722 }
723
724 void
725 FilmViewer::seek_by (DCPTime by, bool accurate)
726 {
727         seek (_video_position + by, accurate);
728 }
729
730 void
731 FilmViewer::set_pad_black (bool p)
732 {
733         _pad_black = p;
734 }