4066710e7e90936c5dbd86ca9d74293c4fc11c64
[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         , _latency_history_count (0)
88         , _dropped (0)
89         , _closed_captions_dialog (new ClosedCaptionsDialog(p, this))
90         , _outline_content (false)
91         , _eyes (EYES_LEFT)
92         , _pad_black (false)
93 #ifdef DCPOMATIC_VARIANT_SWAROOP
94         , _in_watermark (false)
95         , _background_image (false)
96 #endif
97         , _state_timer ("viewer")
98         , _gets (0)
99 {
100         switch (Config::instance()->video_view_type()) {
101         case Config::VIDEO_VIEW_OPENGL:
102                 _video_view = new GLVideoView (p);
103                 break;
104         case Config::VIDEO_VIEW_SIMPLE:
105                 _video_view = new SimpleVideoView (this, p);
106                 break;
107         }
108
109         /* XXX: maybe this should be proxied through the VideoView */
110         _video_view->get()->Bind (wxEVT_SIZE, boost::bind (&FilmViewer::video_view_sized, this));
111         _timer.Bind  (wxEVT_TIMER, boost::bind (&FilmViewer::timer, this));
112
113         set_film (shared_ptr<Film> ());
114
115         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
116         config_changed (Config::SOUND_OUTPUT);
117 }
118
119 FilmViewer::~FilmViewer ()
120 {
121         stop ();
122 }
123
124 void
125 FilmViewer::set_film (shared_ptr<Film> film)
126 {
127         if (_film == film) {
128                 return;
129         }
130
131         _film = film;
132         _video_position = DCPTime ();
133         _player_video.first.reset ();
134         _player_video.second = DCPTime ();
135
136         _frame.reset ();
137         _closed_captions_dialog->clear ();
138
139         if (!_film) {
140                 _player.reset ();
141                 recreate_butler ();
142                 _frame.reset ();
143                 refresh_view ();
144                 return;
145         }
146
147         try {
148                 _player.reset (new Player (_film, _film->playlist ()));
149                 _player->set_fast ();
150                 if (_dcp_decode_reduction) {
151                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
152                 }
153         } catch (bad_alloc &) {
154                 error_dialog (_video_view->get(), _("There is not enough free memory to do that."));
155                 _film.reset ();
156                 return;
157         }
158
159         _player->set_always_burn_open_subtitles ();
160         _player->set_play_referenced ();
161
162         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
163         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
164
165         /* Keep about 1 second's worth of history samples */
166         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
167
168         recreate_butler ();
169
170         calculate_sizes ();
171         slow_refresh ();
172 }
173
174 void
175 FilmViewer::recreate_butler ()
176 {
177         bool const was_running = stop ();
178         _butler.reset ();
179
180         if (!_film) {
181                 return;
182         }
183
184         AudioMapping map = AudioMapping (_film->audio_channels(), _audio_channels);
185
186         if (_audio_channels != 2 || _film->audio_channels() < 3) {
187                 for (int i = 0; i < min (_film->audio_channels(), _audio_channels); ++i) {
188                         map.set (i, i, 1);
189                 }
190         } else {
191                 /* Special case: stereo output, at least 3 channel input.
192                    Map so that Lt = L(-3dB) + Ls(-3dB) + C(-6dB) + Lfe(-10dB)
193                                Rt = R(-3dB) + Rs(-3dB) + C(-6dB) + Lfe(-10dB)
194                 */
195                 map.set (dcp::LEFT,   0, 1 / sqrt(2)); // L -> Lt
196                 map.set (dcp::RIGHT,  1, 1 / sqrt(2)); // R -> Rt
197                 map.set (dcp::CENTRE, 0, 1 / 2.0); // C -> Lt
198                 map.set (dcp::CENTRE, 1, 1 / 2.0); // C -> Rt
199                 map.set (dcp::LFE,    0, 1 / sqrt(10)); // Lfe -> Lt
200                 map.set (dcp::LFE,    1, 1 / sqrt(10)); // Lfe -> Rt
201                 map.set (dcp::LS,     0, 1 / sqrt(2)); // Ls -> Lt
202                 map.set (dcp::RS,     1, 1 / sqrt(2)); // Rs -> Rt
203         }
204
205         _butler.reset (new Butler(_player, map, _audio_channels, bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), false, true));
206         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
207                 _butler->disable_audio ();
208         }
209
210         _closed_captions_dialog->set_film_and_butler (_film, _butler);
211
212         if (was_running) {
213                 start ();
214         }
215 }
216
217 void
218 FilmViewer::refresh_view ()
219 {
220         _state_timer.set ("refresh-view");
221         _video_view->get()->Refresh ();
222         _video_view->get()->Update ();
223         _state_timer.unset ();
224 }
225
226 void
227 FilmViewer::get ()
228 {
229         DCPOMATIC_ASSERT (_butler);
230         ++_gets;
231
232         do {
233                 Butler::Error e;
234                 _player_video = _butler->get_video (&e);
235                 if (!_player_video.first && e == Butler::AGAIN) {
236                         signal_manager->when_idle (boost::bind(&FilmViewer::get, this));
237                         return;
238                 }
239         } while (
240                 _player_video.first &&
241                 _film->three_d() &&
242                 _eyes != _player_video.first->eyes() &&
243                 _player_video.first->eyes() != EYES_BOTH
244                 );
245
246         _butler->rethrow ();
247
248         display_player_video ();
249 }
250
251 void
252 FilmViewer::display_player_video ()
253 {
254         if (!_player_video.first) {
255                 _frame.reset ();
256                 refresh_view ();
257                 return;
258         }
259
260         if (_playing && (time() - _player_video.second) > one_video_frame()) {
261                 /* Too late; just drop this frame before we try to get its image (which will be the time-consuming
262                    part if this frame is J2K).
263                 */
264                 _video_position = _player_video.second;
265                 ++_dropped;
266                 return;
267         }
268
269         /* In an ideal world, what we would do here is:
270          *
271          * 1. convert to XYZ exactly as we do in the DCP creation path.
272          * 2. convert back to RGB for the preview display, compensating
273          *    for the monitor etc. etc.
274          *
275          * but this is inefficient if the source is RGB.  Since we don't
276          * (currently) care too much about the precise accuracy of the preview's
277          * colour mapping (and we care more about its speed) we try to short-
278          * circuit this "ideal" situation in some cases.
279          *
280          * The content's specified colour conversion indicates the colourspace
281          * which the content is in (according to the user).
282          *
283          * PlayerVideo::image (bound to PlayerVideo::force) will take the source
284          * image and convert it (from whatever the user has said it is) to RGB.
285          */
286
287         _state_timer.set ("get image");
288
289         /* XXX: do we need to store _frame? */
290         _frame = _player_video.first->image (bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), false, true);
291         _video_view->set_image (_frame);
292
293         _state_timer.set ("ImageChanged");
294         ImageChanged (_player_video.first);
295         _state_timer.unset ();
296
297         _video_position = _player_video.second;
298         _inter_position = _player_video.first->inter_position ();
299         _inter_size = _player_video.first->inter_size ();
300
301         refresh_view ();
302
303         _closed_captions_dialog->update (time());
304 }
305
306 void
307 FilmViewer::timer ()
308 {
309         if (!_film || !_playing) {
310                 return;
311         }
312
313         get ();
314         PositionChanged ();
315         DCPTime const next = _video_position + one_video_frame();
316
317         if (next >= _film->length()) {
318                 stop ();
319                 Finished ();
320                 return;
321         }
322
323         LOG_DEBUG_PLAYER("%1 -> %2; delay %3", next.seconds(), time().seconds(), max((next.seconds() - time().seconds()) * 1000, 1.0));
324         _timer.Start (max ((next.seconds() - time().seconds()) * 1000, 1.0), wxTIMER_ONE_SHOT);
325
326         if (_butler) {
327                 _butler->rethrow ();
328         }
329 }
330
331 bool
332 #ifdef DCPOMATIC_VARIANT_SWAROOP
333 XXX
334 FilmViewer::maybe_draw_background_image (wxPaintDC& dc)
335 {
336         optional<boost::filesystem::path> bg = Config::instance()->player_background_image();
337         if (bg) {
338                 wxImage image (std_to_wx(bg->string()));
339                 wxBitmap bitmap (image);
340                 dc.DrawBitmap (bitmap, max(0, (_panel_size.width - image.GetSize().GetWidth()) / 2), max(0, (_panel_size.height - image.GetSize().GetHeight()) / 2));
341                 return true;
342         }
343
344         return false;
345 }
346 #else
347 FilmViewer::maybe_draw_background_image (wxPaintDC &)
348 {
349         return false;
350 }
351 #endif
352
353 void
354 FilmViewer::set_outline_content (bool o)
355 {
356         _outline_content = o;
357         refresh_view ();
358 }
359
360 void
361 FilmViewer::set_eyes (Eyes e)
362 {
363         _eyes = e;
364         slow_refresh ();
365 }
366
367 void
368 FilmViewer::video_view_sized ()
369 {
370         calculate_sizes ();
371         if (!quick_refresh()) {
372                 slow_refresh ();
373         }
374         PositionChanged ();
375 }
376
377 void
378 FilmViewer::calculate_sizes ()
379 {
380         if (!_film || !_player) {
381                 return;
382         }
383
384         Ratio const * container = _film->container ();
385
386         float const view_ratio = float(_video_view->get()->GetSize().x) / _video_view->get()->GetSize().y;
387         float const film_ratio = container ? container->ratio () : 1.78;
388
389         if (view_ratio < film_ratio) {
390                 /* panel is less widscreen than the film; clamp width */
391                 _out_size.width = _video_view->get()->GetSize().x;
392                 _out_size.height = lrintf (_out_size.width / film_ratio);
393         } else {
394                 /* panel is more widescreen than the film; clamp height */
395                 _out_size.height = _video_view->get()->GetSize().y;
396                 _out_size.width = lrintf (_out_size.height * film_ratio);
397         }
398
399         /* Catch silly values */
400         _out_size.width = max (64, _out_size.width);
401         _out_size.height = max (64, _out_size.height);
402
403         /* Make OpenGL happy; XXX: only do this in GLVideoView? Is the round-to-4 constraint a thing? */
404         _out_size.width &= ~3;
405         _out_size.height &= ~3;
406
407         _player->set_video_container_size (_out_size);
408 }
409
410 void
411 FilmViewer::start ()
412 {
413         if (!_film) {
414                 return;
415         }
416
417         optional<bool> v = PlaybackPermitted ();
418         if (v && !*v) {
419                 /* Computer says no */
420                 return;
421         }
422
423         if (_audio.isStreamOpen()) {
424                 _audio.setStreamTime (_video_position.seconds());
425                 _audio.startStream ();
426         }
427
428         _playing = true;
429         _dropped = 0;
430         timer ();
431         Started (position());
432 }
433
434 bool
435 FilmViewer::stop ()
436 {
437         if (_audio.isStreamRunning()) {
438                 /* stop stream and discard any remaining queued samples */
439                 _audio.abortStream ();
440         }
441
442         if (!_playing) {
443                 return false;
444         }
445
446         _playing = false;
447         Stopped (position());
448         return true;
449 }
450
451 void
452 FilmViewer::player_change (ChangeType type, int property, bool frequent)
453 {
454         if (type != CHANGE_TYPE_DONE || frequent) {
455                 return;
456         }
457
458         if (_coalesce_player_changes) {
459                 _pending_player_changes.push_back (property);
460                 return;
461         }
462
463         calculate_sizes ();
464         bool refreshed = false;
465         if (
466                 property == VideoContentProperty::CROP ||
467                 property == VideoContentProperty::SCALE ||
468                 property == VideoContentProperty::FADE_IN ||
469                 property == VideoContentProperty::FADE_OUT ||
470                 property == VideoContentProperty::COLOUR_CONVERSION ||
471                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
472                 property == PlayerProperty::FILM_CONTAINER
473                 ) {
474                 refreshed = quick_refresh ();
475         }
476
477         if (!refreshed) {
478                 slow_refresh ();
479         }
480         PositionChanged ();
481 }
482
483 void
484 FilmViewer::film_change (ChangeType type, Film::Property p)
485 {
486         if (type == CHANGE_TYPE_DONE && p == Film::AUDIO_CHANNELS) {
487                 recreate_butler ();
488         }
489 }
490
491 /** Re-get the current frame slowly by seeking */
492 void
493 FilmViewer::slow_refresh ()
494 {
495         seek (_video_position, true);
496 }
497
498 /** Try to re-get the current frame quickly by resetting the metadata
499  *  in the PlayerVideo that we used last time.
500  *  @return true if this was possible, false if not.
501  */
502 bool
503 FilmViewer::quick_refresh ()
504 {
505         if (!_player_video.first) {
506                 return false;
507         }
508
509         if (!_player_video.first->reset_metadata (_film, _player->video_container_size(), _film->frame_size())) {
510                 return false;
511         }
512
513         display_player_video ();
514         return true;
515 }
516
517 void
518 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
519 {
520         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
521         if (dt) {
522                 seek (*dt, accurate);
523         }
524 }
525
526 void
527 FilmViewer::set_coalesce_player_changes (bool c)
528 {
529         _coalesce_player_changes = c;
530
531         if (!c) {
532                 BOOST_FOREACH (int i, _pending_player_changes) {
533                         player_change (CHANGE_TYPE_DONE, i, false);
534                 }
535                 _pending_player_changes.clear ();
536         }
537 }
538
539 void
540 FilmViewer::seek (DCPTime t, bool accurate)
541 {
542         if (!_butler) {
543                 return;
544         }
545
546         if (t < DCPTime ()) {
547                 t = DCPTime ();
548         }
549
550         if (t >= _film->length ()) {
551                 t = _film->length ();
552         }
553
554         bool const was_running = stop ();
555
556         _closed_captions_dialog->clear ();
557         _butler->seek (t, accurate);
558         get ();
559
560         if (was_running) {
561                 start ();
562         }
563
564         PositionChanged ();
565 }
566
567 void
568 FilmViewer::config_changed (Config::Property p)
569 {
570 #ifdef DCPOMATIC_VARIANT_SWAROOP
571         if (p == Config::PLAYER_BACKGROUND_IMAGE) {
572                 refresh_view ();
573                 return;
574         }
575 #endif
576
577         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
578                 return;
579         }
580
581         if (_audio.isStreamOpen ()) {
582                 _audio.closeStream ();
583         }
584
585         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
586                 unsigned int st = 0;
587                 if (Config::instance()->sound_output()) {
588                         while (st < _audio.getDeviceCount()) {
589                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
590                                         break;
591                                 }
592                                 ++st;
593                         }
594                         if (st == _audio.getDeviceCount()) {
595                                 st = _audio.getDefaultOutputDevice();
596                         }
597                 } else {
598                         st = _audio.getDefaultOutputDevice();
599                 }
600
601                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
602
603                 RtAudio::StreamParameters sp;
604                 sp.deviceId = st;
605                 sp.nChannels = _audio_channels;
606                 sp.firstChannel = 0;
607                 try {
608                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
609 #ifdef DCPOMATIC_USE_RTERROR
610                 } catch (RtError& e) {
611 #else
612                 } catch (RtAudioError& e) {
613 #endif
614                         error_dialog (
615                                 _video_view->get(),
616                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
617                                 );
618                 }
619                 recreate_butler ();
620
621         } else {
622                 _audio_channels = 0;
623                 recreate_butler ();
624         }
625 }
626
627 DCPTime
628 FilmViewer::uncorrected_time () const
629 {
630         if (_audio.isStreamRunning ()) {
631                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
632         }
633
634         return _video_position;
635 }
636
637 DCPTime
638 FilmViewer::time () const
639 {
640         if (_audio.isStreamRunning ()) {
641                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
642                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
643         }
644
645         return _video_position;
646 }
647
648 int
649 FilmViewer::audio_callback (void* out_p, unsigned int frames)
650 {
651         while (true) {
652                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
653                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
654                         /* There was an underrun or this audio is on time; carry on */
655                         break;
656                 }
657                 /* The audio we just got was (very) late; drop it and get some more. */
658         }
659
660         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
661         if (lm) {
662                 _latency_history.push_back (_audio.getStreamLatency ());
663                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
664                         _latency_history.pop_front ();
665                 }
666         }
667
668         return 0;
669 }
670
671 Frame
672 FilmViewer::average_latency () const
673 {
674         boost::mutex::scoped_lock lm (_latency_history_mutex);
675         if (_latency_history.empty()) {
676                 return 0;
677         }
678
679         Frame total = 0;
680         BOOST_FOREACH (Frame i, _latency_history) {
681                 total += i;
682         }
683
684         return total / _latency_history.size();
685 }
686
687 void
688 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
689 {
690         _dcp_decode_reduction = reduction;
691         if (_player) {
692                 _player->set_dcp_decode_reduction (reduction);
693         }
694 }
695
696 optional<int>
697 FilmViewer::dcp_decode_reduction () const
698 {
699         return _dcp_decode_reduction;
700 }
701
702 DCPTime
703 FilmViewer::one_video_frame () const
704 {
705         return DCPTime::from_frames (1, _film->video_frame_rate());
706 }
707
708 /** Open a dialog box showing our film's closed captions */
709 void
710 FilmViewer::show_closed_captions ()
711 {
712         _closed_captions_dialog->Show();
713 }
714
715 void
716 FilmViewer::seek_by (DCPTime by, bool accurate)
717 {
718         seek (_video_position + by, accurate);
719 }
720
721 void
722 FilmViewer::set_pad_black (bool p)
723 {
724         _pad_black = p;
725 }