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