Remove swaroop variant.
[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 #include "lib/text_content.h"
51 extern "C" {
52 #include <libavutil/pixfmt.h>
53 }
54 #include <dcp/exceptions.h>
55 #include <wx/tglbtn.h>
56 #include <iostream>
57 #include <iomanip>
58
59 using std::string;
60 using std::pair;
61 using std::min;
62 using std::max;
63 using std::cout;
64 using std::list;
65 using std::bad_alloc;
66 using std::make_pair;
67 using std::exception;
68 using boost::shared_ptr;
69 using boost::dynamic_pointer_cast;
70 using boost::weak_ptr;
71 using boost::optional;
72 #if BOOST_VERSION >= 106100
73 using namespace boost::placeholders;
74 #endif
75 using dcp::Size;
76 using namespace dcpomatic;
77
78 static
79 int
80 rtaudio_callback (void* out, void *, unsigned int frames, double, RtAudioStreamStatus, void* data)
81 {
82         return reinterpret_cast<FilmViewer*>(data)->audio_callback (out, frames);
83 }
84
85 FilmViewer::FilmViewer (wxWindow* p)
86         : _coalesce_player_changes (false)
87         , _audio (DCPOMATIC_RTAUDIO_API)
88         , _audio_channels (0)
89         , _audio_block_size (1024)
90         , _playing (false)
91         , _suspended (0)
92         , _latency_history_count (0)
93         , _closed_captions_dialog (new ClosedCaptionsDialog(p, this))
94         , _outline_content (false)
95         , _pad_black (false)
96         , _idle_get (false)
97 {
98         switch (Config::instance()->video_view_type()) {
99         case Config::VIDEO_VIEW_OPENGL:
100                 _video_view = new GLVideoView (this, p);
101                 break;
102         case Config::VIDEO_VIEW_SIMPLE:
103                 _video_view = new SimpleVideoView (this, p);
104                 break;
105         }
106
107         _video_view->Sized.connect (boost::bind(&FilmViewer::video_view_sized, this));
108
109         set_film (shared_ptr<Film> ());
110
111         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
112         config_changed (Config::SOUND_OUTPUT);
113 }
114
115 FilmViewer::~FilmViewer ()
116 {
117         stop ();
118 }
119
120 /** Ask for ::get() to be called next time we are idle */
121 void
122 FilmViewer::request_idle_display_next_frame ()
123 {
124         if (_idle_get) {
125                 return;
126         }
127
128         _idle_get = true;
129         DCPOMATIC_ASSERT (signal_manager);
130         signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
131 }
132
133 void
134 FilmViewer::idle_handler ()
135 {
136         if (!_idle_get) {
137                 return;
138         }
139
140         if (_video_view->display_next_frame(true)) {
141                 _idle_get = false;
142         } else {
143                 /* get() could not complete quickly so we'll try again later */
144                 signal_manager->when_idle (boost::bind(&FilmViewer::idle_handler, this));
145         }
146 }
147
148 void
149 FilmViewer::set_film (shared_ptr<Film> film)
150 {
151         if (_film == film) {
152                 return;
153         }
154
155         _film = film;
156
157         _video_view->clear ();
158         _closed_captions_dialog->clear ();
159
160         if (!_film) {
161                 _player.reset ();
162                 recreate_butler ();
163                 _video_view->update ();
164                 return;
165         }
166
167         try {
168                 _player.reset (new Player(_film));
169                 _player->set_fast ();
170                 if (_dcp_decode_reduction) {
171                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
172                 }
173         } catch (bad_alloc &) {
174                 error_dialog (_video_view->get(), _("There is not enough free memory to do that."));
175                 _film.reset ();
176                 return;
177         }
178
179         _player->set_always_burn_open_subtitles ();
180         _player->set_play_referenced ();
181
182         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
183         _film->ContentChange.connect (boost::bind(&FilmViewer::content_change, this, _1, _3));
184         _film->LengthChange.connect (boost::bind(&FilmViewer::film_length_change, this));
185         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
186
187         film_change (CHANGE_TYPE_DONE, Film::VIDEO_FRAME_RATE);
188         film_change (CHANGE_TYPE_DONE, Film::THREE_D);
189         film_length_change ();
190
191         /* Keep about 1 second's worth of history samples */
192         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
193
194         _closed_captions_dialog->update_tracks (_film);
195
196         recreate_butler ();
197
198         calculate_sizes ();
199         slow_refresh ();
200 }
201
202 void
203 FilmViewer::recreate_butler ()
204 {
205         suspend ();
206         _butler.reset ();
207
208         if (!_film) {
209                 resume ();
210                 return;
211         }
212
213         _butler.reset(
214                 new Butler(
215                         _player,
216                         Config::instance()->audio_mapping(_audio_channels),
217                         _audio_channels,
218                         bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24),
219                         VIDEO_RANGE_FULL,
220                         false,
221                         true
222                         )
223                 );
224
225         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
226                 _butler->disable_audio ();
227         }
228
229         _closed_captions_dialog->set_butler (_butler);
230
231         resume ();
232 }
233
234 void
235 FilmViewer::set_outline_content (bool o)
236 {
237         _outline_content = o;
238         _video_view->update ();
239 }
240
241
242 void
243 FilmViewer::set_outline_subtitles (optional<dcpomatic::Rect<double> > rect)
244 {
245         _outline_subtitles = rect;
246         _video_view->update ();
247 }
248
249
250 void
251 FilmViewer::set_eyes (Eyes e)
252 {
253         _video_view->set_eyes (e);
254         slow_refresh ();
255 }
256
257 void
258 FilmViewer::video_view_sized ()
259 {
260         calculate_sizes ();
261         if (!quick_refresh()) {
262                 slow_refresh ();
263         }
264 }
265
266 void
267 FilmViewer::calculate_sizes ()
268 {
269         if (!_film || !_player) {
270                 return;
271         }
272
273         Ratio const * container = _film->container ();
274
275         float const view_ratio = float(_video_view->get()->GetSize().x) / _video_view->get()->GetSize().y;
276         float const film_ratio = container ? container->ratio () : 1.78;
277
278         if (view_ratio < film_ratio) {
279                 /* panel is less widscreen than the film; clamp width */
280                 _out_size.width = _video_view->get()->GetSize().x;
281                 _out_size.height = lrintf (_out_size.width / film_ratio);
282         } else {
283                 /* panel is more widescreen than the film; clamp height */
284                 _out_size.height = _video_view->get()->GetSize().y;
285                 _out_size.width = lrintf (_out_size.height * film_ratio);
286         }
287
288         /* Catch silly values */
289         _out_size.width = max (64, _out_size.width);
290         _out_size.height = max (64, _out_size.height);
291
292         _player->set_video_container_size (_out_size);
293 }
294
295 void
296 FilmViewer::suspend ()
297 {
298         ++_suspended;
299         if (_audio.isStreamRunning()) {
300                 _audio.abortStream();
301         }
302 }
303
304 void
305 FilmViewer::resume ()
306 {
307         DCPOMATIC_ASSERT (_suspended > 0);
308         --_suspended;
309         if (_playing && !_suspended) {
310                 if (_audio.isStreamOpen()) {
311                         _audio.setStreamTime (_video_view->position().seconds());
312                         _audio.startStream ();
313                 }
314                 _video_view->start ();
315         }
316 }
317
318 void
319 FilmViewer::start ()
320 {
321         if (!_film) {
322                 return;
323         }
324
325         optional<bool> v = PlaybackPermitted ();
326         if (v && !*v) {
327                 /* Computer says no */
328                 return;
329         }
330
331         /* We are about to set up the audio stream from the position of the video view.
332            If there is `lazy' seek in progress we need to wait for it to go through so that
333            _video_view->position() gives us a sensible answer.
334          */
335         while (_idle_get) {
336                 idle_handler ();
337         }
338
339         /* Take the video view's idea of position as our `playhead' and start the
340            audio stream (which is the timing reference) there.
341          */
342         if (_audio.isStreamOpen()) {
343                 _audio.setStreamTime (_video_view->position().seconds());
344                 _audio.startStream ();
345         }
346
347         _playing = true;
348         _video_view->start ();
349         Started (position());
350 }
351
352 bool
353 FilmViewer::stop ()
354 {
355         if (_audio.isStreamRunning()) {
356                 /* stop stream and discard any remaining queued samples */
357                 _audio.abortStream ();
358         }
359
360         if (!_playing) {
361                 return false;
362         }
363
364         _playing = false;
365         _video_view->stop ();
366         Stopped (position());
367
368         _video_view->rethrow ();
369         return true;
370 }
371
372 void
373 FilmViewer::player_change (ChangeType type, int property, bool frequent)
374 {
375         if (type != CHANGE_TYPE_DONE || frequent) {
376                 return;
377         }
378
379         if (_coalesce_player_changes) {
380                 _pending_player_changes.push_back (property);
381                 return;
382         }
383
384         calculate_sizes ();
385         bool refreshed = false;
386         if (
387                 property == VideoContentProperty::CROP ||
388                 property == VideoContentProperty::SCALE ||
389                 property == VideoContentProperty::FADE_IN ||
390                 property == VideoContentProperty::FADE_OUT ||
391                 property == VideoContentProperty::COLOUR_CONVERSION ||
392                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
393                 property == PlayerProperty::FILM_CONTAINER
394                 ) {
395                 refreshed = quick_refresh ();
396         }
397
398         if (!refreshed) {
399                 slow_refresh ();
400         }
401 }
402
403 void
404 FilmViewer::film_change (ChangeType type, Film::Property p)
405 {
406         if (type != CHANGE_TYPE_DONE) {
407                 return;
408         }
409
410         if (p == Film::AUDIO_CHANNELS) {
411                 recreate_butler ();
412         } else if (p == Film::VIDEO_FRAME_RATE) {
413                 _video_view->set_video_frame_rate (_film->video_frame_rate());
414         } else if (p == Film::THREE_D) {
415                 _video_view->set_three_d (_film->three_d());
416         } else if (p == Film::CONTENT) {
417                 _closed_captions_dialog->update_tracks (_film);
418         }
419 }
420
421 void
422 FilmViewer::film_length_change ()
423 {
424         _video_view->set_length (_film->length());
425 }
426
427 /** Re-get the current frame slowly by seeking */
428 void
429 FilmViewer::slow_refresh ()
430 {
431         seek (_video_view->position(), true);
432 }
433
434 /** Try to re-get the current frame quickly by resetting the metadata
435  *  in the PlayerVideo that we used last time.
436  *  @return true if this was possible, false if not.
437  */
438 bool
439 FilmViewer::quick_refresh ()
440 {
441         if (!_video_view || !_film || !_player) {
442                 return true;
443         }
444         return _video_view->refresh_metadata (_film, _player->video_container_size(), _film->frame_size());
445 }
446
447 void
448 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
449 {
450         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
451         if (dt) {
452                 seek (*dt, accurate);
453         }
454 }
455
456 void
457 FilmViewer::set_coalesce_player_changes (bool c)
458 {
459         _coalesce_player_changes = c;
460
461         if (!c) {
462                 BOOST_FOREACH (int i, _pending_player_changes) {
463                         player_change (CHANGE_TYPE_DONE, i, false);
464                 }
465                 _pending_player_changes.clear ();
466         }
467 }
468
469 void
470 FilmViewer::seek (DCPTime t, bool accurate)
471 {
472         if (!_butler) {
473                 return;
474         }
475
476         if (t < DCPTime ()) {
477                 t = DCPTime ();
478         }
479
480         if (t >= _film->length ()) {
481                 t = _film->length() - one_video_frame();
482         }
483
484         suspend ();
485
486         _closed_captions_dialog->clear ();
487         _butler->seek (t, accurate);
488
489         if (!_playing) {
490                 /* We're not playing, so let the GUI thread get on and
491                    come back later to get the next frame after the seek.
492                 */
493                 request_idle_display_next_frame ();
494         } else {
495                 /* We're going to start playing again straight away
496                    so wait for the seek to finish.
497                 */
498                 while (!_video_view->display_next_frame(false)) {}
499         }
500
501         resume ();
502 }
503
504 void
505 FilmViewer::config_changed (Config::Property p)
506 {
507         if (p == Config::AUDIO_MAPPING) {
508                 recreate_butler ();
509                 return;
510         }
511
512         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
513                 return;
514         }
515
516         if (_audio.isStreamOpen ()) {
517                 _audio.closeStream ();
518         }
519
520         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
521                 unsigned int st = 0;
522                 if (Config::instance()->sound_output()) {
523                         while (st < _audio.getDeviceCount()) {
524                                 try {
525                                         if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
526                                                 break;
527                                         }
528                                 } catch (RtAudioError&) {
529                                         /* Something went wrong with that device so we don't want to use it anyway */
530                                 }
531                                 ++st;
532                         }
533                         if (st == _audio.getDeviceCount()) {
534                                 st = _audio.getDefaultOutputDevice();
535                         }
536                 } else {
537                         st = _audio.getDefaultOutputDevice();
538                 }
539
540                 try {
541                         _audio_channels = _audio.getDeviceInfo(st).outputChannels;
542                         RtAudio::StreamParameters sp;
543                         sp.deviceId = st;
544                         sp.nChannels = _audio_channels;
545                         sp.firstChannel = 0;
546                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
547                 } catch (RtAudioError& e) {
548                         _audio_channels = 0;
549                         error_dialog (
550                                 _video_view->get(),
551                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
552                                 );
553                 }
554                 recreate_butler ();
555
556         } else {
557                 _audio_channels = 0;
558                 recreate_butler ();
559         }
560 }
561
562 DCPTime
563 FilmViewer::uncorrected_time () const
564 {
565         if (_audio.isStreamRunning ()) {
566                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
567         }
568
569         return _video_view->position();
570 }
571
572 optional<DCPTime>
573 FilmViewer::audio_time () const
574 {
575         if (!_audio.isStreamRunning()) {
576                 return optional<DCPTime>();
577         }
578
579         return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
580                 DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
581 }
582
583 DCPTime
584 FilmViewer::time () const
585 {
586         return audio_time().get_value_or(_video_view->position());
587 }
588
589 int
590 FilmViewer::audio_callback (void* out_p, unsigned int frames)
591 {
592         while (true) {
593                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
594                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
595                         /* There was an underrun or this audio is on time; carry on */
596                         break;
597                 }
598                 /* The audio we just got was (very) late; drop it and get some more. */
599         }
600
601         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
602         if (lm) {
603                 _latency_history.push_back (_audio.getStreamLatency ());
604                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
605                         _latency_history.pop_front ();
606                 }
607         }
608
609         return 0;
610 }
611
612 Frame
613 FilmViewer::average_latency () const
614 {
615         boost::mutex::scoped_lock lm (_latency_history_mutex);
616         if (_latency_history.empty()) {
617                 return 0;
618         }
619
620         Frame total = 0;
621         BOOST_FOREACH (Frame i, _latency_history) {
622                 total += i;
623         }
624
625         return total / _latency_history.size();
626 }
627
628 void
629 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
630 {
631         _dcp_decode_reduction = reduction;
632         if (_player) {
633                 _player->set_dcp_decode_reduction (reduction);
634         }
635 }
636
637 optional<int>
638 FilmViewer::dcp_decode_reduction () const
639 {
640         return _dcp_decode_reduction;
641 }
642
643 DCPTime
644 FilmViewer::one_video_frame () const
645 {
646         return DCPTime::from_frames (1, _film ? _film->video_frame_rate() : 24);
647 }
648
649 /** Open a dialog box showing our film's closed captions */
650 void
651 FilmViewer::show_closed_captions ()
652 {
653         _closed_captions_dialog->Show();
654 }
655
656 void
657 FilmViewer::seek_by (DCPTime by, bool accurate)
658 {
659         seek (_video_view->position() + by, accurate);
660 }
661
662 void
663 FilmViewer::set_pad_black (bool p)
664 {
665         _pad_black = p;
666 }
667
668 /** Called when a player has finished the current film.
669  *  May be called from a non-UI thread.
670  */
671 void
672 FilmViewer::finished ()
673 {
674         emit (boost::bind(&FilmViewer::ui_finished, this));
675 }
676
677 /** Called by finished() in the UI thread */
678 void
679 FilmViewer::ui_finished ()
680 {
681         stop ();
682         Finished ();
683 }
684
685 int
686 FilmViewer::dropped () const
687 {
688         return _video_view->dropped ();
689 }
690
691
692 int
693 FilmViewer::errored () const
694 {
695         return _video_view->errored ();
696 }
697
698
699 int
700 FilmViewer::gets () const
701 {
702         return _video_view->gets ();
703 }
704
705
706 void
707 FilmViewer::content_change (ChangeType type, int property)
708 {
709         if (type != CHANGE_TYPE_DONE) {
710                 return;
711         }
712
713         if (property == TextContentProperty::USE || property == TextContentProperty::TYPE || property == TextContentProperty::DCP_TRACK) {
714                 _closed_captions_dialog->update_tracks (_film);
715         }
716 }
717
718
719 void
720 FilmViewer::image_changed (shared_ptr<PlayerVideo> pv)
721 {
722         emit (boost::bind(boost::ref(ImageChanged), pv));
723 }
724