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