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