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