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