Differentiate between stop and suspend in player.
[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         _timer.Bind (wxEVT_TIMER, boost::bind(&FilmViewer::timer, this));
112
113         set_film (shared_ptr<Film> ());
114
115         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
116         config_changed (Config::SOUND_OUTPUT);
117 }
118
119 FilmViewer::~FilmViewer ()
120 {
121         stop ();
122 }
123
124 /** Ask for ::get() to be called next time we are idle */
125 void
126 FilmViewer::request_idle_get ()
127 {
128         if (_idle_get) {
129                 return;
130         }
131
132         _idle_get = true;
133         DCPOMATIC_ASSERT (signal_manager);
134         signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
135 }
136
137 void
138 FilmViewer::idle_handler ()
139 {
140         if (!_idle_get) {
141                 return;
142         }
143
144         if (get(true)) {
145                 _idle_get = false;
146         } else {
147                 /* get() could not complete quickly so we'll try again later */
148                 signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
149         }
150 }
151
152 void
153 FilmViewer::set_film (shared_ptr<Film> film)
154 {
155         if (_film == film) {
156                 return;
157         }
158
159         _film = film;
160         _video_position = DCPTime ();
161         _player_video.first.reset ();
162         _player_video.second = DCPTime ();
163
164         _video_view->set_image (shared_ptr<Image>());
165         _closed_captions_dialog->clear ();
166
167         if (!_film) {
168                 _player.reset ();
169                 recreate_butler ();
170                 refresh_view ();
171                 return;
172         }
173
174         try {
175                 _player.reset (new Player (_film, _film->playlist ()));
176                 _player->set_fast ();
177                 if (_dcp_decode_reduction) {
178                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
179                 }
180         } catch (bad_alloc &) {
181                 error_dialog (_video_view->get(), _("There is not enough free memory to do that."));
182                 _film.reset ();
183                 return;
184         }
185
186         _player->set_always_burn_open_subtitles ();
187         _player->set_play_referenced ();
188
189         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
190         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
191
192         /* Keep about 1 second's worth of history samples */
193         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
194
195         recreate_butler ();
196
197         calculate_sizes ();
198         slow_refresh ();
199 }
200
201 void
202 FilmViewer::recreate_butler ()
203 {
204         suspend ();
205         _butler.reset ();
206
207         if (!_film) {
208                 resume ();
209                 return;
210         }
211
212         AudioMapping map = AudioMapping (_film->audio_channels(), _audio_channels);
213
214         if (_audio_channels != 2 || _film->audio_channels() < 3) {
215                 for (int i = 0; i < min (_film->audio_channels(), _audio_channels); ++i) {
216                         map.set (i, i, 1);
217                 }
218         } else {
219                 /* Special case: stereo output, at least 3 channel input.
220                    Map so that Lt = L(-3dB) + Ls(-3dB) + C(-6dB) + Lfe(-10dB)
221                                Rt = R(-3dB) + Rs(-3dB) + C(-6dB) + Lfe(-10dB)
222                 */
223                 if (_film->audio_channels() > 0) {
224                         map.set (dcp::LEFT,   0, 1 / sqrt(2)); // L -> Lt
225                 }
226                 if (_film->audio_channels() > 1) {
227                         map.set (dcp::RIGHT,  1, 1 / sqrt(2)); // R -> Rt
228                 }
229                 if (_film->audio_channels() > 2) {
230                         map.set (dcp::CENTRE, 0, 1 / 2.0); // C -> Lt
231                         map.set (dcp::CENTRE, 1, 1 / 2.0); // C -> Rt
232                 }
233                 if (_film->audio_channels() > 3) {
234                         map.set (dcp::LFE,    0, 1 / sqrt(10)); // Lfe -> Lt
235                         map.set (dcp::LFE,    1, 1 / sqrt(10)); // Lfe -> Rt
236                 }
237                 if (_film->audio_channels() > 4) {
238                         map.set (dcp::LS,     0, 1 / sqrt(2)); // Ls -> Lt
239                 }
240                 if (_film->audio_channels() > 5) {
241                         map.set (dcp::RS,     1, 1 / sqrt(2)); // Rs -> Rt
242                 }
243         }
244
245         _butler.reset (new Butler(_player, map, _audio_channels, bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), false, true));
246         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
247                 _butler->disable_audio ();
248         }
249
250         _closed_captions_dialog->set_film_and_butler (_film, _butler);
251
252         resume ();
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 && !_suspended && (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 || _suspended) {
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::suspend ()
440 {
441         ++_suspended;
442         if (_audio.isStreamRunning()) {
443                 _audio.abortStream();
444         }
445 }
446
447 void
448 FilmViewer::resume ()
449 {
450         --_suspended;
451         if (_playing && !_suspended) {
452                 if (_audio.isStreamOpen()) {
453                         _audio.setStreamTime (_video_position.seconds());
454                         _audio.startStream ();
455                 }
456                 timer ();
457         }
458 }
459
460 void
461 FilmViewer::start ()
462 {
463         if (!_film) {
464                 return;
465         }
466
467         optional<bool> v = PlaybackPermitted ();
468         if (v && !*v) {
469                 /* Computer says no */
470                 return;
471         }
472
473         if (_audio.isStreamOpen()) {
474                 _audio.setStreamTime (_video_position.seconds());
475                 _audio.startStream ();
476         }
477
478         _playing = true;
479         _dropped = 0;
480         timer ();
481         Started (position());
482 }
483
484 bool
485 FilmViewer::stop ()
486 {
487         if (_audio.isStreamRunning()) {
488                 /* stop stream and discard any remaining queued samples */
489                 _audio.abortStream ();
490         }
491
492         if (!_playing) {
493                 return false;
494         }
495
496         _playing = false;
497         Stopped (position());
498         return true;
499 }
500
501 void
502 FilmViewer::player_change (ChangeType type, int property, bool frequent)
503 {
504         if (type != CHANGE_TYPE_DONE || frequent) {
505                 return;
506         }
507
508         if (_coalesce_player_changes) {
509                 _pending_player_changes.push_back (property);
510                 return;
511         }
512
513         calculate_sizes ();
514         bool refreshed = false;
515         if (
516                 property == VideoContentProperty::CROP ||
517                 property == VideoContentProperty::SCALE ||
518                 property == VideoContentProperty::FADE_IN ||
519                 property == VideoContentProperty::FADE_OUT ||
520                 property == VideoContentProperty::COLOUR_CONVERSION ||
521                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
522                 property == PlayerProperty::FILM_CONTAINER
523                 ) {
524                 refreshed = quick_refresh ();
525         }
526
527         if (!refreshed) {
528                 slow_refresh ();
529         }
530         PositionChanged ();
531 }
532
533 void
534 FilmViewer::film_change (ChangeType type, Film::Property p)
535 {
536         if (type == CHANGE_TYPE_DONE && p == Film::AUDIO_CHANNELS) {
537                 recreate_butler ();
538         }
539 }
540
541 /** Re-get the current frame slowly by seeking */
542 void
543 FilmViewer::slow_refresh ()
544 {
545         seek (_video_position, true);
546 }
547
548 /** Try to re-get the current frame quickly by resetting the metadata
549  *  in the PlayerVideo that we used last time.
550  *  @return true if this was possible, false if not.
551  */
552 bool
553 FilmViewer::quick_refresh ()
554 {
555         if (!_player_video.first) {
556                 return false;
557         }
558
559         if (!_player_video.first->reset_metadata (_film, _player->video_container_size(), _film->frame_size())) {
560                 return false;
561         }
562
563         display_player_video ();
564         return true;
565 }
566
567 void
568 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
569 {
570         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
571         if (dt) {
572                 seek (*dt, accurate);
573         }
574 }
575
576 void
577 FilmViewer::set_coalesce_player_changes (bool c)
578 {
579         _coalesce_player_changes = c;
580
581         if (!c) {
582                 BOOST_FOREACH (int i, _pending_player_changes) {
583                         player_change (CHANGE_TYPE_DONE, i, false);
584                 }
585                 _pending_player_changes.clear ();
586         }
587 }
588
589 void
590 FilmViewer::seek (DCPTime t, bool accurate)
591 {
592         if (!_butler) {
593                 return;
594         }
595
596         if (t < DCPTime ()) {
597                 t = DCPTime ();
598         }
599
600         if (t >= _film->length ()) {
601                 t = _film->length ();
602         }
603
604         suspend ();
605
606         _closed_captions_dialog->clear ();
607         _butler->seek (t, accurate);
608
609         if (!_playing) {
610                 request_idle_get ();
611         } else {
612                 /* Make sure we get a frame so that _video_position is set up before we resume */
613                 while (!get(true)) {}
614         }
615
616         resume ();
617 }
618
619 void
620 FilmViewer::config_changed (Config::Property p)
621 {
622 #ifdef DCPOMATIC_VARIANT_SWAROOP
623         if (p == Config::PLAYER_BACKGROUND_IMAGE) {
624                 refresh_view ();
625                 return;
626         }
627 #endif
628
629         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
630                 return;
631         }
632
633         if (_audio.isStreamOpen ()) {
634                 _audio.closeStream ();
635         }
636
637         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
638                 unsigned int st = 0;
639                 if (Config::instance()->sound_output()) {
640                         while (st < _audio.getDeviceCount()) {
641                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
642                                         break;
643                                 }
644                                 ++st;
645                         }
646                         if (st == _audio.getDeviceCount()) {
647                                 st = _audio.getDefaultOutputDevice();
648                         }
649                 } else {
650                         st = _audio.getDefaultOutputDevice();
651                 }
652
653                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
654
655                 RtAudio::StreamParameters sp;
656                 sp.deviceId = st;
657                 sp.nChannels = _audio_channels;
658                 sp.firstChannel = 0;
659                 try {
660                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
661 #ifdef DCPOMATIC_USE_RTERROR
662                 } catch (RtError& e) {
663 #else
664                 } catch (RtAudioError& e) {
665 #endif
666                         error_dialog (
667                                 _video_view->get(),
668                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
669                                 );
670                 }
671                 recreate_butler ();
672
673         } else {
674                 _audio_channels = 0;
675                 recreate_butler ();
676         }
677 }
678
679 DCPTime
680 FilmViewer::uncorrected_time () const
681 {
682         if (_audio.isStreamRunning ()) {
683                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
684         }
685
686         return _video_position;
687 }
688
689 DCPTime
690 FilmViewer::time () const
691 {
692         if (_audio.isStreamRunning ()) {
693                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
694                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
695         }
696
697         return _video_position;
698 }
699
700 int
701 FilmViewer::audio_callback (void* out_p, unsigned int frames)
702 {
703         while (true) {
704                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
705                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
706                         /* There was an underrun or this audio is on time; carry on */
707                         break;
708                 }
709                 /* The audio we just got was (very) late; drop it and get some more. */
710         }
711
712         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
713         if (lm) {
714                 _latency_history.push_back (_audio.getStreamLatency ());
715                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
716                         _latency_history.pop_front ();
717                 }
718         }
719
720         return 0;
721 }
722
723 Frame
724 FilmViewer::average_latency () const
725 {
726         boost::mutex::scoped_lock lm (_latency_history_mutex);
727         if (_latency_history.empty()) {
728                 return 0;
729         }
730
731         Frame total = 0;
732         BOOST_FOREACH (Frame i, _latency_history) {
733                 total += i;
734         }
735
736         return total / _latency_history.size();
737 }
738
739 void
740 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
741 {
742         _dcp_decode_reduction = reduction;
743         if (_player) {
744                 _player->set_dcp_decode_reduction (reduction);
745         }
746 }
747
748 optional<int>
749 FilmViewer::dcp_decode_reduction () const
750 {
751         return _dcp_decode_reduction;
752 }
753
754 DCPTime
755 FilmViewer::one_video_frame () const
756 {
757         return DCPTime::from_frames (1, _film->video_frame_rate());
758 }
759
760 /** Open a dialog box showing our film's closed captions */
761 void
762 FilmViewer::show_closed_captions ()
763 {
764         _closed_captions_dialog->Show();
765 }
766
767 void
768 FilmViewer::seek_by (DCPTime by, bool accurate)
769 {
770         seek (_video_position + by, accurate);
771 }
772
773 void
774 FilmViewer::set_pad_black (bool p)
775 {
776         _pad_black = p;
777 }