Remove PositionChanged in favour of consumers having their own GUI-thread timers.
[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
112         set_film (shared_ptr<Film> ());
113
114         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
115         config_changed (Config::SOUND_OUTPUT);
116 }
117
118 FilmViewer::~FilmViewer ()
119 {
120         stop ();
121 }
122
123 /** Ask for ::get() to be called next time we are idle */
124 void
125 FilmViewer::request_idle_get ()
126 {
127         if (_idle_get) {
128                 return;
129         }
130
131         _idle_get = true;
132         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->get(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         _video_position = DCPTime ();
160         _video_view->clear ();
161
162         _video_view->set_image (shared_ptr<Image>());
163         _closed_captions_dialog->clear ();
164
165         if (!_film) {
166                 _player.reset ();
167                 recreate_butler ();
168                 refresh_view ();
169                 return;
170         }
171
172         try {
173                 _player.reset (new Player (_film, _film->playlist ()));
174                 _player->set_fast ();
175                 if (_dcp_decode_reduction) {
176                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
177                 }
178         } catch (bad_alloc &) {
179                 error_dialog (_video_view->get(), _("There is not enough free memory to do that."));
180                 _film.reset ();
181                 return;
182         }
183
184         _player->set_always_burn_open_subtitles ();
185         _player->set_play_referenced ();
186
187         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
188         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
189
190         /* Keep about 1 second's worth of history samples */
191         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
192
193         recreate_butler ();
194
195         calculate_sizes ();
196         slow_refresh ();
197 }
198
199 void
200 FilmViewer::recreate_butler ()
201 {
202         suspend ();
203         _butler.reset ();
204
205         if (!_film) {
206                 resume ();
207                 return;
208         }
209
210         _butler.reset(
211                 new Butler(
212                         _player,
213                         Config::instance()->audio_mapping(_audio_channels),
214                         _audio_channels,
215                         bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24),
216                         false,
217                         true
218                         )
219                 );
220
221         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
222                 _butler->disable_audio ();
223         }
224
225         _closed_captions_dialog->set_film_and_butler (_film, _butler);
226
227         resume ();
228 }
229
230 void
231 FilmViewer::refresh_view ()
232 {
233         _state_timer.set ("update-view");
234         _video_view->update ();
235         _state_timer.unset ();
236 }
237
238 void
239 FilmViewer::set_outline_content (bool o)
240 {
241         _outline_content = o;
242         refresh_view ();
243 }
244
245 void
246 FilmViewer::set_eyes (Eyes e)
247 {
248         _eyes = e;
249         slow_refresh ();
250 }
251
252 void
253 FilmViewer::video_view_sized ()
254 {
255         calculate_sizes ();
256         if (!quick_refresh()) {
257                 slow_refresh ();
258         }
259 }
260
261 void
262 FilmViewer::calculate_sizes ()
263 {
264         if (!_film || !_player) {
265                 return;
266         }
267
268         Ratio const * container = _film->container ();
269
270         float const view_ratio = float(_video_view->get()->GetSize().x) / _video_view->get()->GetSize().y;
271         float const film_ratio = container ? container->ratio () : 1.78;
272
273         if (view_ratio < film_ratio) {
274                 /* panel is less widscreen than the film; clamp width */
275                 _out_size.width = _video_view->get()->GetSize().x;
276                 _out_size.height = lrintf (_out_size.width / film_ratio);
277         } else {
278                 /* panel is more widescreen than the film; clamp height */
279                 _out_size.height = _video_view->get()->GetSize().y;
280                 _out_size.width = lrintf (_out_size.height * film_ratio);
281         }
282
283         /* Catch silly values */
284         _out_size.width = max (64, _out_size.width);
285         _out_size.height = max (64, _out_size.height);
286
287         _player->set_video_container_size (_out_size);
288 }
289
290 void
291 FilmViewer::suspend ()
292 {
293         ++_suspended;
294         if (_audio.isStreamRunning()) {
295                 _audio.abortStream();
296         }
297 }
298
299 void
300 FilmViewer::resume ()
301 {
302         --_suspended;
303         if (_playing && !_suspended) {
304                 if (_audio.isStreamOpen()) {
305                         _audio.setStreamTime (_video_position.seconds());
306                         _audio.startStream ();
307                 }
308                 _video_view->start ();
309         }
310 }
311
312 void
313 FilmViewer::start ()
314 {
315         if (!_film) {
316                 return;
317         }
318
319         optional<bool> v = PlaybackPermitted ();
320         if (v && !*v) {
321                 /* Computer says no */
322                 return;
323         }
324
325         if (_audio.isStreamOpen()) {
326                 _audio.setStreamTime (_video_position.seconds());
327                 _audio.startStream ();
328         }
329
330         _playing = true;
331         _dropped = 0;
332         _video_view->start ();
333         Started (position());
334 }
335
336 bool
337 FilmViewer::stop ()
338 {
339         if (_audio.isStreamRunning()) {
340                 /* stop stream and discard any remaining queued samples */
341                 _audio.abortStream ();
342         }
343
344         if (!_playing) {
345                 return false;
346         }
347
348         _playing = false;
349         Stopped (position());
350         return true;
351 }
352
353 void
354 FilmViewer::player_change (ChangeType type, int property, bool frequent)
355 {
356         if (type != CHANGE_TYPE_DONE || frequent) {
357                 return;
358         }
359
360         if (_coalesce_player_changes) {
361                 _pending_player_changes.push_back (property);
362                 return;
363         }
364
365         calculate_sizes ();
366         bool refreshed = false;
367         if (
368                 property == VideoContentProperty::CROP ||
369                 property == VideoContentProperty::SCALE ||
370                 property == VideoContentProperty::FADE_IN ||
371                 property == VideoContentProperty::FADE_OUT ||
372                 property == VideoContentProperty::COLOUR_CONVERSION ||
373                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
374                 property == PlayerProperty::FILM_CONTAINER
375                 ) {
376                 refreshed = quick_refresh ();
377         }
378
379         if (!refreshed) {
380                 slow_refresh ();
381         }
382 }
383
384 void
385 FilmViewer::film_change (ChangeType type, Film::Property p)
386 {
387         if (type == CHANGE_TYPE_DONE && p == Film::AUDIO_CHANNELS) {
388                 recreate_butler ();
389         }
390 }
391
392 /** Re-get the current frame slowly by seeking */
393 void
394 FilmViewer::slow_refresh ()
395 {
396         seek (_video_position, true);
397 }
398
399 /** Try to re-get the current frame quickly by resetting the metadata
400  *  in the PlayerVideo that we used last time.
401  *  @return true if this was possible, false if not.
402  */
403 bool
404 FilmViewer::quick_refresh ()
405 {
406         if (!_video_view->_player_video.first) {
407                 return false;
408         }
409
410         if (!_video_view->_player_video.first->reset_metadata (_film, _player->video_container_size(), _film->frame_size())) {
411                 return false;
412         }
413
414         _video_view->display_player_video ();
415         return true;
416 }
417
418 void
419 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
420 {
421         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
422         if (dt) {
423                 seek (*dt, accurate);
424         }
425 }
426
427 void
428 FilmViewer::set_coalesce_player_changes (bool c)
429 {
430         _coalesce_player_changes = c;
431
432         if (!c) {
433                 BOOST_FOREACH (int i, _pending_player_changes) {
434                         player_change (CHANGE_TYPE_DONE, i, false);
435                 }
436                 _pending_player_changes.clear ();
437         }
438 }
439
440 void
441 FilmViewer::seek (DCPTime t, bool accurate)
442 {
443         if (!_butler) {
444                 return;
445         }
446
447         if (t < DCPTime ()) {
448                 t = DCPTime ();
449         }
450
451         if (t >= _film->length ()) {
452                 t = _film->length ();
453         }
454
455         suspend ();
456
457         _closed_captions_dialog->clear ();
458         _butler->seek (t, accurate);
459
460         if (!_playing) {
461                 request_idle_get ();
462         }
463
464         resume ();
465 }
466
467 void
468 FilmViewer::config_changed (Config::Property p)
469 {
470 #ifdef DCPOMATIC_VARIANT_SWAROOP
471         if (p == Config::PLAYER_BACKGROUND_IMAGE) {
472                 refresh_view ();
473                 return;
474         }
475 #endif
476
477         if (p == Config::AUDIO_MAPPING) {
478                 recreate_butler ();
479                 return;
480         }
481
482         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
483                 return;
484         }
485
486         if (_audio.isStreamOpen ()) {
487                 _audio.closeStream ();
488         }
489
490         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
491                 unsigned int st = 0;
492                 if (Config::instance()->sound_output()) {
493                         while (st < _audio.getDeviceCount()) {
494                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
495                                         break;
496                                 }
497                                 ++st;
498                         }
499                         if (st == _audio.getDeviceCount()) {
500                                 st = _audio.getDefaultOutputDevice();
501                         }
502                 } else {
503                         st = _audio.getDefaultOutputDevice();
504                 }
505
506                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
507
508                 RtAudio::StreamParameters sp;
509                 sp.deviceId = st;
510                 sp.nChannels = _audio_channels;
511                 sp.firstChannel = 0;
512                 try {
513                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
514 #ifdef DCPOMATIC_USE_RTERROR
515                 } catch (RtError& e) {
516 #else
517                 } catch (RtAudioError& e) {
518 #endif
519                         error_dialog (
520                                 _video_view->get(),
521                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
522                                 );
523                 }
524                 recreate_butler ();
525
526         } else {
527                 _audio_channels = 0;
528                 recreate_butler ();
529         }
530 }
531
532 DCPTime
533 FilmViewer::uncorrected_time () const
534 {
535         if (_audio.isStreamRunning ()) {
536                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
537         }
538
539         return _video_position;
540 }
541
542 DCPTime
543 FilmViewer::time () const
544 {
545         if (_audio.isStreamRunning ()) {
546                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
547                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
548         }
549
550         return _video_position;
551 }
552
553 int
554 FilmViewer::audio_callback (void* out_p, unsigned int frames)
555 {
556         while (true) {
557                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
558                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
559                         /* There was an underrun or this audio is on time; carry on */
560                         break;
561                 }
562                 /* The audio we just got was (very) late; drop it and get some more. */
563         }
564
565         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
566         if (lm) {
567                 _latency_history.push_back (_audio.getStreamLatency ());
568                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
569                         _latency_history.pop_front ();
570                 }
571         }
572
573         return 0;
574 }
575
576 Frame
577 FilmViewer::average_latency () const
578 {
579         boost::mutex::scoped_lock lm (_latency_history_mutex);
580         if (_latency_history.empty()) {
581                 return 0;
582         }
583
584         Frame total = 0;
585         BOOST_FOREACH (Frame i, _latency_history) {
586                 total += i;
587         }
588
589         return total / _latency_history.size();
590 }
591
592 void
593 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
594 {
595         _dcp_decode_reduction = reduction;
596         if (_player) {
597                 _player->set_dcp_decode_reduction (reduction);
598         }
599 }
600
601 optional<int>
602 FilmViewer::dcp_decode_reduction () const
603 {
604         return _dcp_decode_reduction;
605 }
606
607 DCPTime
608 FilmViewer::one_video_frame () const
609 {
610         return DCPTime::from_frames (1, _film ? _film->video_frame_rate() : 24);
611 }
612
613 /** Open a dialog box showing our film's closed captions */
614 void
615 FilmViewer::show_closed_captions ()
616 {
617         _closed_captions_dialog->Show();
618 }
619
620 void
621 FilmViewer::seek_by (DCPTime by, bool accurate)
622 {
623         seek (_video_position + by, accurate);
624 }
625
626 void
627 FilmViewer::set_pad_black (bool p)
628 {
629         _pad_black = p;
630 }
631
632 /* XXX_b: comment */
633 int
634 FilmViewer::time_until_next_frame () const
635 {
636         DCPTime const next = position() + one_video_frame();
637         return max ((next.seconds() - time().seconds()) * 1000, 1.0);
638 }