FilmViewer API tidying.
[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::player_change (ChangeType type, int property, bool frequent)
438 {
439         if (type != CHANGE_TYPE_DONE || frequent) {
440                 return;
441         }
442
443         if (_coalesce_player_changes) {
444                 _pending_player_changes.push_back (property);
445                 return;
446         }
447
448         calculate_sizes ();
449         bool refreshed = false;
450         if (
451                 property == VideoContentProperty::CROP ||
452                 property == VideoContentProperty::SCALE ||
453                 property == VideoContentProperty::FADE_IN ||
454                 property == VideoContentProperty::FADE_OUT ||
455                 property == VideoContentProperty::COLOUR_CONVERSION ||
456                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
457                 property == PlayerProperty::FILM_CONTAINER
458                 ) {
459                 refreshed = quick_refresh ();
460         }
461
462         if (!refreshed) {
463                 slow_refresh ();
464         }
465         PositionChanged ();
466 }
467
468 void
469 FilmViewer::film_change (ChangeType type, Film::Property p)
470 {
471         if (type == CHANGE_TYPE_DONE && p == Film::AUDIO_CHANNELS) {
472                 recreate_butler ();
473         }
474 }
475
476 /** Re-get the current frame slowly by seeking */
477 void
478 FilmViewer::slow_refresh ()
479 {
480         seek (_video_position, true);
481 }
482
483 /** Try to re-get the current frame quickly by resetting the metadata
484  *  in the PlayerVideo that we used last time.
485  *  @return true if this was possible, false if not.
486  */
487 bool
488 FilmViewer::quick_refresh ()
489 {
490         if (!_player_video.first) {
491                 return false;
492         }
493
494         if (!_player_video.first->reset_metadata (_player->video_container_size(), _film->frame_size())) {
495                 return false;
496         }
497
498         display_player_video ();
499         return true;
500 }
501
502 void
503 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
504 {
505         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
506         if (dt) {
507                 seek (*dt, accurate);
508         }
509 }
510
511 void
512 FilmViewer::set_coalesce_player_changes (bool c)
513 {
514         _coalesce_player_changes = c;
515
516         if (!c) {
517                 BOOST_FOREACH (int i, _pending_player_changes) {
518                         player_change (CHANGE_TYPE_DONE, i, false);
519                 }
520                 _pending_player_changes.clear ();
521         }
522 }
523
524 void
525 FilmViewer::seek (DCPTime t, bool accurate)
526 {
527         if (!_butler) {
528                 return;
529         }
530
531         if (t < DCPTime ()) {
532                 t = DCPTime ();
533         }
534
535         if (t >= _film->length ()) {
536                 t = _film->length ();
537         }
538
539         bool const was_running = stop ();
540
541         _closed_captions_dialog->clear ();
542         _butler->seek (t, accurate);
543         get ();
544
545         if (was_running) {
546                 start ();
547         }
548
549         PositionChanged ();
550 }
551
552 void
553 FilmViewer::config_changed (Config::Property p)
554 {
555         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
556                 return;
557         }
558
559         if (_audio.isStreamOpen ()) {
560                 _audio.closeStream ();
561         }
562
563         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
564                 unsigned int st = 0;
565                 if (Config::instance()->sound_output()) {
566                         while (st < _audio.getDeviceCount()) {
567                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
568                                         break;
569                                 }
570                                 ++st;
571                         }
572                         if (st == _audio.getDeviceCount()) {
573                                 st = _audio.getDefaultOutputDevice();
574                         }
575                 } else {
576                         st = _audio.getDefaultOutputDevice();
577                 }
578
579                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
580
581                 RtAudio::StreamParameters sp;
582                 sp.deviceId = st;
583                 sp.nChannels = _audio_channels;
584                 sp.firstChannel = 0;
585                 try {
586                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
587 #ifdef DCPOMATIC_USE_RTERROR
588                 } catch (RtError& e) {
589 #else
590                 } catch (RtAudioError& e) {
591 #endif
592                         error_dialog (
593                                 _panel,
594                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
595                                 );
596                 }
597                 recreate_butler ();
598
599         } else {
600                 _audio_channels = 0;
601                 recreate_butler ();
602         }
603 }
604
605 DCPTime
606 FilmViewer::uncorrected_time () const
607 {
608         if (_audio.isStreamRunning ()) {
609                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
610         }
611
612         return _video_position;
613 }
614
615 DCPTime
616 FilmViewer::time () const
617 {
618         if (_audio.isStreamRunning ()) {
619                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
620                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
621         }
622
623         return _video_position;
624 }
625
626 int
627 FilmViewer::audio_callback (void* out_p, unsigned int frames)
628 {
629         while (true) {
630                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
631                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
632                         /* There was an underrun or this audio is on time; carry on */
633                         break;
634                 }
635                 /* The audio we just got was (very) late; drop it and get some more. */
636         }
637
638         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
639         if (lm) {
640                 _latency_history.push_back (_audio.getStreamLatency ());
641                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
642                         _latency_history.pop_front ();
643                 }
644         }
645
646         return 0;
647 }
648
649 Frame
650 FilmViewer::average_latency () const
651 {
652         boost::mutex::scoped_lock lm (_latency_history_mutex);
653         if (_latency_history.empty()) {
654                 return 0;
655         }
656
657         Frame total = 0;
658         BOOST_FOREACH (Frame i, _latency_history) {
659                 total += i;
660         }
661
662         return total / _latency_history.size();
663 }
664
665 void
666 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
667 {
668         _dcp_decode_reduction = reduction;
669         if (_player) {
670                 _player->set_dcp_decode_reduction (reduction);
671         }
672 }
673
674 optional<int>
675 FilmViewer::dcp_decode_reduction () const
676 {
677         return _dcp_decode_reduction;
678 }
679
680 DCPTime
681 FilmViewer::one_video_frame () const
682 {
683         return DCPTime::from_frames (1, _film->video_frame_rate());
684 }
685
686 /** Open a dialog box showing our film's closed captions */
687 void
688 FilmViewer::show_closed_captions ()
689 {
690         _closed_captions_dialog->Show();
691 }
692
693 void
694 FilmViewer::seek_by (DCPTime by, bool accurate)
695 {
696         seek (_video_position + by, accurate);
697 }