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