Separate out management of controls.
[dcpomatic.git] / src / wx / film_viewer.cc
1 /*
2     Copyright (C) 2012-2018 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 "lib/film.h"
31 #include "lib/ratio.h"
32 #include "lib/util.h"
33 #include "lib/job_manager.h"
34 #include "lib/image.h"
35 #include "lib/exceptions.h"
36 #include "lib/examine_content_job.h"
37 #include "lib/filter.h"
38 #include "lib/player.h"
39 #include "lib/player_video.h"
40 #include "lib/video_content.h"
41 #include "lib/video_decoder.h"
42 #include "lib/timer.h"
43 #include "lib/butler.h"
44 #include "lib/log.h"
45 #include "lib/config.h"
46 extern "C" {
47 #include <libavutil/pixfmt.h>
48 }
49 #include <dcp/exceptions.h>
50 #include <wx/tglbtn.h>
51 #include <iostream>
52 #include <iomanip>
53
54 using std::string;
55 using std::pair;
56 using std::min;
57 using std::max;
58 using std::cout;
59 using std::list;
60 using std::bad_alloc;
61 using std::make_pair;
62 using std::exception;
63 using boost::shared_ptr;
64 using boost::dynamic_pointer_cast;
65 using boost::weak_ptr;
66 using boost::optional;
67 using dcp::Size;
68
69 static
70 int
71 rtaudio_callback (void* out, void *, unsigned int frames, double, RtAudioStreamStatus, void* data)
72 {
73         return reinterpret_cast<FilmViewer*>(data)->audio_callback (out, frames);
74 }
75
76 FilmViewer::FilmViewer (wxWindow* p)
77         : _panel (new wxPanel (p))
78         , _coalesce_player_changes (false)
79         , _audio (DCPOMATIC_RTAUDIO_API)
80         , _audio_channels (0)
81         , _audio_block_size (1024)
82         , _playing (false)
83         , _latency_history_count (0)
84         , _dropped (0)
85         , _closed_captions_dialog (new ClosedCaptionsDialog(p))
86         , _outline_content (false)
87         , _eyes (EYES_LEFT)
88 {
89 #ifndef __WXOSX__
90         _panel->SetDoubleBuffered (true);
91 #endif
92
93         _panel->SetBackgroundStyle (wxBG_STYLE_PAINT);
94
95         _panel->Bind            (wxEVT_PAINT,               boost::bind (&FilmViewer::paint_panel,     this));
96         _panel->Bind            (wxEVT_SIZE,                boost::bind (&FilmViewer::panel_sized,     this, _1));
97         _timer.Bind             (wxEVT_TIMER,               boost::bind (&FilmViewer::timer,           this));
98
99         set_film (shared_ptr<Film> ());
100
101         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
102         config_changed (Config::SOUND_OUTPUT);
103 }
104
105 FilmViewer::~FilmViewer ()
106 {
107         stop ();
108 }
109
110 void
111 FilmViewer::set_film (shared_ptr<Film> film)
112 {
113         if (_film == film) {
114                 return;
115         }
116
117         _film = film;
118
119         FilmChanged ();
120
121         _frame.reset ();
122         _closed_captions_dialog->clear ();
123
124         if (!_film) {
125                 _player.reset ();
126                 recreate_butler ();
127                 _frame.reset ();
128                 refresh_panel ();
129                 return;
130         }
131
132         try {
133                 _player.reset (new Player (_film, _film->playlist ()));
134                 _player->set_fast ();
135                 if (_dcp_decode_reduction) {
136                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
137                 }
138         } catch (bad_alloc) {
139                 error_dialog (_panel, _("There is not enough free memory to do that."));
140                 _film.reset ();
141                 return;
142         }
143
144         _player->set_always_burn_open_subtitles ();
145         _player->set_play_referenced ();
146
147         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
148         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
149
150         /* Keep about 1 second's worth of history samples */
151         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
152
153         recreate_butler ();
154
155         calculate_sizes ();
156         slow_refresh ();
157 }
158
159 void
160 FilmViewer::recreate_butler ()
161 {
162         bool const was_running = stop ();
163         _butler.reset ();
164
165         if (!_film) {
166                 return;
167         }
168
169         AudioMapping map = AudioMapping (_film->audio_channels(), _audio_channels);
170
171         if (_audio_channels != 2 || _film->audio_channels() < 3) {
172                 for (int i = 0; i < min (_film->audio_channels(), _audio_channels); ++i) {
173                         map.set (i, i, 1);
174                 }
175         } else {
176                 /* Special case: stereo output, at least 3 channel input.
177                    Map so that Lt = L(-3dB) + Ls(-3dB) + C(-6dB) + Lfe(-10dB)
178                                Rt = R(-3dB) + Rs(-3dB) + C(-6dB) + Lfe(-10dB)
179                 */
180                 map.set (dcp::LEFT,   0, 1 / sqrt(2)); // L -> Lt
181                 map.set (dcp::RIGHT,  1, 1 / sqrt(2)); // R -> Rt
182                 map.set (dcp::CENTRE, 0, 1 / 2.0); // C -> Lt
183                 map.set (dcp::CENTRE, 1, 1 / 2.0); // C -> Rt
184                 map.set (dcp::LFE,    0, 1 / sqrt(10)); // Lfe -> Lt
185                 map.set (dcp::LFE,    1, 1 / sqrt(10)); // Lfe -> Rt
186                 map.set (dcp::LS,     0, 1 / sqrt(2)); // Ls -> Lt
187                 map.set (dcp::RS,     1, 1 / sqrt(2)); // Rs -> Rt
188         }
189
190         _butler.reset (new Butler (_player, _film->log(), map, _audio_channels));
191         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
192                 _butler->disable_audio ();
193         }
194
195         _closed_captions_dialog->set_butler (_butler);
196
197         if (was_running) {
198                 start ();
199         }
200 }
201
202 void
203 FilmViewer::refresh_panel ()
204 {
205         _panel->Refresh ();
206         _panel->Update ();
207 }
208
209 void
210 FilmViewer::get ()
211 {
212         DCPOMATIC_ASSERT (_butler);
213
214         do {
215                 Butler::Error e;
216                 _player_video = _butler->get_video (&e);
217                 if (!_player_video.first && e == Butler::AGAIN) {
218                         signal_manager->when_idle (boost::bind(&FilmViewer::get, this));
219                         return;
220                 }
221         } while (
222                 _player_video.first &&
223                 _film->three_d() &&
224                 (_eyes != _player_video.first->eyes())
225                 );
226
227         _butler->rethrow ();
228
229         display_player_video ();
230 }
231
232 void
233 FilmViewer::display_player_video ()
234 {
235         if (!_player_video.first) {
236                 _frame.reset ();
237                 refresh_panel ();
238                 return;
239         }
240
241         if (_playing && (time() - _player_video.second) > one_video_frame()) {
242                 /* Too late; just drop this frame before we try to get its image (which will be the time-consuming
243                    part if this frame is J2K).
244                 */
245                 _video_position = _player_video.second;
246                 ++_dropped;
247                 return;
248         }
249
250         /* In an ideal world, what we would do here is:
251          *
252          * 1. convert to XYZ exactly as we do in the DCP creation path.
253          * 2. convert back to RGB for the preview display, compensating
254          *    for the monitor etc. etc.
255          *
256          * but this is inefficient if the source is RGB.  Since we don't
257          * (currently) care too much about the precise accuracy of the preview's
258          * colour mapping (and we care more about its speed) we try to short-
259          * circuit this "ideal" situation in some cases.
260          *
261          * The content's specified colour conversion indicates the colourspace
262          * which the content is in (according to the user).
263          *
264          * PlayerVideo::image (bound to PlayerVideo::always_rgb) will take the source
265          * image and convert it (from whatever the user has said it is) to RGB.
266          */
267
268         _frame = _player_video.first->image (
269                 bind (&Log::dcp_log, _film->log().get(), _1, _2),
270                 bind (&PlayerVideo::always_rgb, _1),
271                 false, true
272                 );
273
274         ImageChanged (_player_video.first);
275
276         _video_position = _player_video.second;
277         _inter_position = _player_video.first->inter_position ();
278         _inter_size = _player_video.first->inter_size ();
279
280         refresh_panel ();
281
282         _closed_captions_dialog->update (time());
283 }
284
285 void
286 FilmViewer::timer ()
287 {
288         if (!_film || !_playing) {
289                 return;
290         }
291
292         get ();
293         PositionChanged ();
294         DCPTime const next = _video_position + one_video_frame();
295
296         if (next >= _film->length()) {
297                 stop ();
298         }
299
300         _timer.Start (max ((next.seconds() - time().seconds()) * 1000, 1.0), wxTIMER_ONE_SHOT);
301
302         if (_butler) {
303                 _butler->rethrow ();
304         }
305 }
306
307 void
308 FilmViewer::paint_panel ()
309 {
310         wxPaintDC dc (_panel);
311
312         if (!_frame || !_film || !_out_size.width || !_out_size.height || _out_size != _frame->size()) {
313                 dc.Clear ();
314                 return;
315         }
316
317         wxImage frame (_out_size.width, _out_size.height, _frame->data()[0], true);
318         wxBitmap frame_bitmap (frame);
319         dc.DrawBitmap (frame_bitmap, 0, 0);
320
321         if (_out_size.width < _panel_size.width) {
322                 wxPen p (_panel->GetParent()->GetBackgroundColour());
323                 wxBrush b (_panel->GetParent()->GetBackgroundColour());
324                 dc.SetPen (p);
325                 dc.SetBrush (b);
326                 dc.DrawRectangle (_out_size.width, 0, _panel_size.width - _out_size.width, _panel_size.height);
327         }
328
329         if (_out_size.height < _panel_size.height) {
330                 wxPen p (_panel->GetParent()->GetBackgroundColour());
331                 wxBrush b (_panel->GetParent()->GetBackgroundColour());
332                 dc.SetPen (p);
333                 dc.SetBrush (b);
334                 dc.DrawRectangle (0, _out_size.height, _panel_size.width, _panel_size.height - _out_size.height);
335         }
336
337         if (_outline_content) {
338                 wxPen p (wxColour (255, 0, 0), 2);
339                 dc.SetPen (p);
340                 dc.SetBrush (*wxTRANSPARENT_BRUSH);
341                 dc.DrawRectangle (_inter_position.x, _inter_position.y, _inter_size.width, _inter_size.height);
342         }
343 }
344
345 void
346 FilmViewer::set_outline_content (bool o)
347 {
348         _outline_content = o;
349         refresh_panel ();
350 }
351
352 void
353 FilmViewer::set_eyes (Eyes e)
354 {
355         _eyes = e;
356         slow_refresh ();
357 }
358
359 void
360 FilmViewer::panel_sized (wxSizeEvent& ev)
361 {
362         _panel_size.width = ev.GetSize().GetWidth();
363         _panel_size.height = ev.GetSize().GetHeight();
364
365         calculate_sizes ();
366         if (!quick_refresh()) {
367                 slow_refresh ();
368         }
369         PositionChanged ();
370 }
371
372 void
373 FilmViewer::calculate_sizes ()
374 {
375         if (!_film || !_player) {
376                 return;
377         }
378
379         Ratio const * container = _film->container ();
380
381         float const panel_ratio = _panel_size.ratio ();
382         float const film_ratio = container ? container->ratio () : 1.78;
383
384         if (panel_ratio < film_ratio) {
385                 /* panel is less widscreen than the film; clamp width */
386                 _out_size.width = _panel_size.width;
387                 _out_size.height = lrintf (_out_size.width / film_ratio);
388         } else {
389                 /* panel is more widescreen than the film; clamp height */
390                 _out_size.height = _panel_size.height;
391                 _out_size.width = lrintf (_out_size.height * film_ratio);
392         }
393
394         /* Catch silly values */
395         _out_size.width = max (64, _out_size.width);
396         _out_size.height = max (64, _out_size.height);
397
398         _player->set_video_container_size (_out_size);
399 }
400
401 void
402 FilmViewer::start ()
403 {
404         if (!_film) {
405                 return;
406         }
407
408         if (_audio.isStreamOpen()) {
409                 _audio.setStreamTime (_video_position.seconds());
410                 _audio.startStream ();
411         }
412
413         _playing = true;
414         _dropped = 0;
415         timer ();
416         Started ();
417 }
418
419 bool
420 FilmViewer::stop ()
421 {
422         if (_audio.isStreamRunning()) {
423                 /* stop stream and discard any remaining queued samples */
424                 _audio.abortStream ();
425         }
426
427         if (!_playing) {
428                 return false;
429         }
430
431         _playing = false;
432         Stopped ();
433         return true;
434 }
435
436 void
437 FilmViewer::go_to (DCPTime t)
438 {
439         if (t < DCPTime ()) {
440                 t = DCPTime ();
441         }
442
443         if (t >= _film->length ()) {
444                 t = _film->length ();
445         }
446
447         seek (t, true);
448         PositionChanged ();
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 (_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::set_position (DCPTime p)
519 {
520         _video_position = p;
521         seek (p, true);
522         PositionChanged ();
523 }
524
525 void
526 FilmViewer::set_position (shared_ptr<Content> content, ContentTime t)
527 {
528         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
529         if (dt) {
530                 set_position (*dt);
531         }
532 }
533
534 void
535 FilmViewer::set_coalesce_player_changes (bool c)
536 {
537         _coalesce_player_changes = c;
538
539         if (!c) {
540                 BOOST_FOREACH (int i, _pending_player_changes) {
541                         player_change (CHANGE_TYPE_DONE, i, false);
542                 }
543                 _pending_player_changes.clear ();
544         }
545 }
546
547 void
548 FilmViewer::seek (DCPTime t, bool accurate)
549 {
550         if (!_butler) {
551                 return;
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
565 void
566 FilmViewer::config_changed (Config::Property p)
567 {
568         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
569                 return;
570         }
571
572         if (_audio.isStreamOpen ()) {
573                 _audio.closeStream ();
574         }
575
576         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
577                 unsigned int st = 0;
578                 if (Config::instance()->sound_output()) {
579                         while (st < _audio.getDeviceCount()) {
580                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
581                                         break;
582                                 }
583                                 ++st;
584                         }
585                         if (st == _audio.getDeviceCount()) {
586                                 st = _audio.getDefaultOutputDevice();
587                         }
588                 } else {
589                         st = _audio.getDefaultOutputDevice();
590                 }
591
592                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
593
594                 RtAudio::StreamParameters sp;
595                 sp.deviceId = st;
596                 sp.nChannels = _audio_channels;
597                 sp.firstChannel = 0;
598                 try {
599                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
600 #ifdef DCPOMATIC_USE_RTERROR
601                 } catch (RtError& e) {
602 #else
603                 } catch (RtAudioError& e) {
604 #endif
605                         error_dialog (
606                                 _panel,
607                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
608                                 );
609                 }
610                 recreate_butler ();
611
612         } else {
613                 _audio_channels = 0;
614                 recreate_butler ();
615         }
616 }
617
618 DCPTime
619 FilmViewer::uncorrected_time () const
620 {
621         if (_audio.isStreamRunning ()) {
622                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
623         }
624
625         return _video_position;
626 }
627
628 DCPTime
629 FilmViewer::time () const
630 {
631         if (_audio.isStreamRunning ()) {
632                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
633                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
634         }
635
636         return _video_position;
637 }
638
639 int
640 FilmViewer::audio_callback (void* out_p, unsigned int frames)
641 {
642         while (true) {
643                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
644                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
645                         /* There was an underrun or this audio is on time; carry on */
646                         break;
647                 }
648                 /* The audio we just got was (very) late; drop it and get some more. */
649         }
650
651         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
652         if (lm) {
653                 _latency_history.push_back (_audio.getStreamLatency ());
654                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
655                         _latency_history.pop_front ();
656                 }
657         }
658
659         return 0;
660 }
661
662 Frame
663 FilmViewer::average_latency () const
664 {
665         boost::mutex::scoped_lock lm (_latency_history_mutex);
666         if (_latency_history.empty()) {
667                 return 0;
668         }
669
670         Frame total = 0;
671         BOOST_FOREACH (Frame i, _latency_history) {
672                 total += i;
673         }
674
675         return total / _latency_history.size();
676 }
677
678 void
679 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
680 {
681         _dcp_decode_reduction = reduction;
682         if (_player) {
683                 _player->set_dcp_decode_reduction (reduction);
684         }
685 }
686
687 optional<int>
688 FilmViewer::dcp_decode_reduction () const
689 {
690         return _dcp_decode_reduction;
691 }
692
693 DCPTime
694 FilmViewer::one_video_frame () const
695 {
696         return DCPTime::from_frames (1, _film->video_frame_rate());
697 }
698
699 void
700 FilmViewer::show_closed_captions ()
701 {
702         _closed_captions_dialog->Show();
703 }
704
705 void
706 FilmViewer::move (DCPTime by)
707 {
708         if (!_film) {
709                 return;
710         }
711
712         go_to (_video_position + by);
713 }