Untested; allow viewing of subtitles or closed captions in the preview.
[dcpomatic.git] / src / wx / film_viewer.cc
1 /*
2     Copyright (C) 2012-2017 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 "lib/film.h"
30 #include "lib/ratio.h"
31 #include "lib/util.h"
32 #include "lib/job_manager.h"
33 #include "lib/image.h"
34 #include "lib/exceptions.h"
35 #include "lib/examine_content_job.h"
36 #include "lib/filter.h"
37 #include "lib/player.h"
38 #include "lib/player_video.h"
39 #include "lib/video_content.h"
40 #include "lib/video_decoder.h"
41 #include "lib/timer.h"
42 #include "lib/butler.h"
43 #include "lib/log.h"
44 #include "lib/config.h"
45 extern "C" {
46 #include <libavutil/pixfmt.h>
47 }
48 #include <dcp/exceptions.h>
49 #include <wx/tglbtn.h>
50 #include <iostream>
51 #include <iomanip>
52
53 using std::string;
54 using std::pair;
55 using std::min;
56 using std::max;
57 using std::cout;
58 using std::list;
59 using std::bad_alloc;
60 using std::make_pair;
61 using std::exception;
62 using boost::shared_ptr;
63 using boost::dynamic_pointer_cast;
64 using boost::weak_ptr;
65 using boost::optional;
66 using dcp::Size;
67
68 static
69 int
70 rtaudio_callback (void* out, void *, unsigned int frames, double, RtAudioStreamStatus, void* data)
71 {
72         return reinterpret_cast<FilmViewer*>(data)->audio_callback (out, frames);
73 }
74
75 FilmViewer::FilmViewer (wxWindow* p, bool outline_content, bool jump_to_selected)
76         : wxPanel (p)
77         , _panel (new wxPanel (this))
78         , _outline_content (0)
79         , _eye (0)
80         , _jump_to_selected (0)
81         , _slider (new wxSlider (this, wxID_ANY, 0, 0, 4096))
82         , _rewind_button (new wxButton (this, wxID_ANY, wxT("|<")))
83         , _back_button (new wxButton (this, wxID_ANY, wxT("<")))
84         , _forward_button (new wxButton (this, wxID_ANY, wxT(">")))
85         , _frame_number (new wxStaticText (this, wxID_ANY, wxT("")))
86         , _timecode (new wxStaticText (this, wxID_ANY, wxT("")))
87         , _play_button (new wxToggleButton (this, wxID_ANY, _("Play")))
88         , _coalesce_player_changes (false)
89         , _slider_being_moved (false)
90         , _was_running_before_slider (false)
91         , _audio (DCPOMATIC_RTAUDIO_API)
92         , _audio_channels (0)
93         , _audio_block_size (1024)
94         , _playing (false)
95         , _latency_history_count (0)
96         , _dropped (0)
97 {
98 #ifndef __WXOSX__
99         _panel->SetDoubleBuffered (true);
100 #endif
101
102         _panel->SetBackgroundStyle (wxBG_STYLE_PAINT);
103
104         _v_sizer = new wxBoxSizer (wxVERTICAL);
105         SetSizer (_v_sizer);
106
107         _v_sizer->Add (_panel, 1, wxEXPAND);
108
109         wxBoxSizer* view_options = new wxBoxSizer (wxHORIZONTAL);
110         if (outline_content) {
111                 _outline_content = new wxCheckBox (this, wxID_ANY, _("Outline content"));
112                 view_options->Add (_outline_content, 0, wxRIGHT | wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_GAP);
113         }
114
115         _eye = new wxChoice (this, wxID_ANY);
116         _eye->Append (_("Left"));
117         _eye->Append (_("Right"));
118         _eye->SetSelection (0);
119         view_options->Add (_eye, 0, wxLEFT | wxRIGHT | wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_GAP);
120
121         if (jump_to_selected) {
122                 _jump_to_selected = new wxCheckBox (this, wxID_ANY, _("Jump to selected content"));
123                 view_options->Add (_jump_to_selected, 0, wxLEFT | wxRIGHT | wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_GAP);
124         }
125
126         _captions = new wxChoice (this, wxID_ANY);
127         _captions->Append (_("Open captions (subtitles)"));
128         _captions->Append (_("Closed captions"));
129         _captions->SetSelection (0);
130         view_options->Add (_captions, 0, wxLEFT | wxRIGHT, DCPOMATIC_SIZER_GAP);
131
132         _v_sizer->Add (view_options, 0, wxALL, DCPOMATIC_SIZER_GAP);
133
134         wxBoxSizer* h_sizer = new wxBoxSizer (wxHORIZONTAL);
135
136         wxBoxSizer* time_sizer = new wxBoxSizer (wxVERTICAL);
137         time_sizer->Add (_frame_number, 0, wxEXPAND);
138         time_sizer->Add (_timecode, 0, wxEXPAND);
139
140         h_sizer->Add (_rewind_button, 0, wxALL, 2);
141         h_sizer->Add (_back_button, 0, wxALL, 2);
142         h_sizer->Add (time_sizer, 0, wxEXPAND);
143         h_sizer->Add (_forward_button, 0, wxALL, 2);
144         h_sizer->Add (_play_button, 0, wxEXPAND);
145         h_sizer->Add (_slider, 1, wxEXPAND);
146
147         _v_sizer->Add (h_sizer, 0, wxEXPAND | wxALL, 6);
148
149         _frame_number->SetMinSize (wxSize (84, -1));
150         _rewind_button->SetMinSize (wxSize (32, -1));
151         _back_button->SetMinSize (wxSize (32, -1));
152         _forward_button->SetMinSize (wxSize (32, -1));
153
154         _panel->Bind            (wxEVT_PAINT,             boost::bind (&FilmViewer::paint_panel,     this));
155         _panel->Bind            (wxEVT_SIZE,              boost::bind (&FilmViewer::panel_sized,     this, _1));
156         if (_outline_content) {
157                 _outline_content->Bind  (wxEVT_CHECKBOX, boost::bind (&FilmViewer::refresh_panel,   this));
158         }
159         _eye->Bind              (wxEVT_CHOICE,            boost::bind (&FilmViewer::slow_refresh,    this));
160         _captions->Bind         (wxEVT_CHOICE,            boost::bind (&FilmViewer::captions_changed, this));
161         _slider->Bind           (wxEVT_SCROLL_THUMBTRACK, boost::bind (&FilmViewer::slider_moved,    this, false));
162         _slider->Bind           (wxEVT_SCROLL_PAGEUP,     boost::bind (&FilmViewer::slider_moved,    this, true));
163         _slider->Bind           (wxEVT_SCROLL_PAGEDOWN,   boost::bind (&FilmViewer::slider_moved,    this, true));
164         _slider->Bind           (wxEVT_SCROLL_THUMBRELEASE, boost::bind (&FilmViewer::slider_released, this));
165         _play_button->Bind      (wxEVT_TOGGLEBUTTON,      boost::bind (&FilmViewer::play_clicked,    this));
166         _timer.Bind             (wxEVT_TIMER,             boost::bind (&FilmViewer::timer,           this));
167         _rewind_button->Bind    (wxEVT_LEFT_DOWN,         boost::bind (&FilmViewer::rewind_clicked,  this, _1));
168         _back_button->Bind      (wxEVT_LEFT_DOWN,         boost::bind (&FilmViewer::back_clicked,    this, _1));
169         _forward_button->Bind   (wxEVT_LEFT_DOWN,         boost::bind (&FilmViewer::forward_clicked, this, _1));
170         _frame_number->Bind     (wxEVT_LEFT_DOWN,         boost::bind (&FilmViewer::frame_number_clicked, this));
171         _timecode->Bind         (wxEVT_LEFT_DOWN,         boost::bind (&FilmViewer::timecode_clicked, this));
172         if (_jump_to_selected) {
173                 _jump_to_selected->Bind (wxEVT_CHECKBOX, boost::bind (&FilmViewer::jump_to_selected_clicked, this));
174                 _jump_to_selected->SetValue (Config::instance()->jump_to_selected ());
175         }
176
177         set_film (shared_ptr<Film> ());
178
179         JobManager::instance()->ActiveJobsChanged.connect (
180                 bind (&FilmViewer::active_jobs_changed, this, _2)
181                 );
182
183         setup_sensitivity ();
184
185         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
186         config_changed (Config::SOUND_OUTPUT);
187 }
188
189 FilmViewer::~FilmViewer ()
190 {
191         stop ();
192 }
193
194 void
195 FilmViewer::set_film (shared_ptr<Film> film)
196 {
197         if (_film == film) {
198                 return;
199         }
200
201         _film = film;
202
203         _frame.reset ();
204
205         update_position_slider ();
206         update_position_label ();
207
208         if (!_film) {
209                 _player.reset ();
210                 recreate_butler ();
211                 _frame.reset ();
212                 refresh_panel ();
213                 return;
214         }
215
216         try {
217                 _player.reset (new Player (_film, _film->playlist ()));
218                 _player->set_fast ();
219                 if (_dcp_decode_reduction) {
220                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
221                 }
222         } catch (bad_alloc) {
223                 error_dialog (this, _("There is not enough free memory to do that."));
224                 _film.reset ();
225                 return;
226         }
227
228         /* Start off burning in subtitles, as that's the initial setting of the dropdown */
229         _player->set_always_burn_captions (CAPTION_OPEN);
230         _player->set_play_referenced ();
231
232         _film->Changed.connect (boost::bind (&FilmViewer::film_changed, this, _1));
233         _player->Changed.connect (boost::bind (&FilmViewer::player_changed, this, _1, _2));
234
235         /* Keep about 1 second's worth of history samples */
236         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
237
238         recreate_butler ();
239
240         calculate_sizes ();
241         slow_refresh ();
242
243         setup_sensitivity ();
244 }
245
246 void
247 FilmViewer::recreate_butler ()
248 {
249         bool const was_running = stop ();
250         _butler.reset ();
251
252         if (!_film) {
253                 return;
254         }
255
256         AudioMapping map = AudioMapping (_film->audio_channels(), _audio_channels);
257
258         if (_audio_channels != 2 || _film->audio_channels() < 3) {
259                 for (int i = 0; i < min (_film->audio_channels(), _audio_channels); ++i) {
260                         map.set (i, i, 1);
261                 }
262         } else {
263                 /* Special case: stereo output, at least 3 channel input.
264                    Map so that Lt = L(-3dB) + Ls(-3dB) + C(-6dB) + Lfe(-10dB)
265                                Rt = R(-3dB) + Rs(-3dB) + C(-6dB) + Lfe(-10dB)
266                 */
267                 map.set (dcp::LEFT,   0, 1 / sqrt(2)); // L -> Lt
268                 map.set (dcp::RIGHT,  1, 1 / sqrt(2)); // R -> Rt
269                 map.set (dcp::CENTRE, 0, 1 / 2.0); // C -> Lt
270                 map.set (dcp::CENTRE, 1, 1 / 2.0); // C -> Rt
271                 map.set (dcp::LFE,    0, 1 / sqrt(10)); // Lfe -> Lt
272                 map.set (dcp::LFE,    1, 1 / sqrt(10)); // Lfe -> Rt
273                 map.set (dcp::LS,     0, 1 / sqrt(2)); // Ls -> Lt
274                 map.set (dcp::RS,     1, 1 / sqrt(2)); // Rs -> Rt
275         }
276
277         _butler.reset (new Butler (_player, _film->log(), map, _audio_channels));
278         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
279                 _butler->disable_audio ();
280         }
281
282         if (was_running) {
283                 start ();
284         }
285 }
286
287 void
288 FilmViewer::refresh_panel ()
289 {
290         _panel->Refresh ();
291         _panel->Update ();
292 }
293
294 void
295 FilmViewer::get ()
296 {
297         DCPOMATIC_ASSERT (_butler);
298
299         do {
300                 _player_video = _butler->get_video ();
301         } while (
302                 _film->three_d() &&
303                 ((_eye->GetSelection() == 0 && _player_video.first->eyes() == EYES_RIGHT) || (_eye->GetSelection() == 1 && _player_video.first->eyes() == EYES_LEFT))
304                 );
305
306         _butler->rethrow ();
307
308         display_player_video ();
309 }
310
311 void
312 FilmViewer::display_player_video ()
313 {
314         if (!_player_video.first) {
315                 _frame.reset ();
316                 refresh_panel ();
317                 return;
318         }
319
320         if (_playing && (time() - _player_video.second) > one_video_frame()) {
321                 /* Too late; just drop this frame before we try to get its image (which will be the time-consuming
322                    part if this frame is J2K).
323                 */
324                 _video_position = _player_video.second;
325                 ++_dropped;
326                 return;
327         }
328
329         /* In an ideal world, what we would do here is:
330          *
331          * 1. convert to XYZ exactly as we do in the DCP creation path.
332          * 2. convert back to RGB for the preview display, compensating
333          *    for the monitor etc. etc.
334          *
335          * but this is inefficient if the source is RGB.  Since we don't
336          * (currently) care too much about the precise accuracy of the preview's
337          * colour mapping (and we care more about its speed) we try to short-
338          * circuit this "ideal" situation in some cases.
339          *
340          * The content's specified colour conversion indicates the colourspace
341          * which the content is in (according to the user).
342          *
343          * PlayerVideo::image (bound to PlayerVideo::always_rgb) will take the source
344          * image and convert it (from whatever the user has said it is) to RGB.
345          */
346
347         _frame = _player_video.first->image (
348                 bind (&Log::dcp_log, _film->log().get(), _1, _2),
349                 bind (&PlayerVideo::always_rgb, _1),
350                 false, true
351                 );
352
353         ImageChanged (_player_video.first);
354
355         _video_position = _player_video.second;
356         _inter_position = _player_video.first->inter_position ();
357         _inter_size = _player_video.first->inter_size ();
358
359         refresh_panel ();
360 }
361
362 void
363 FilmViewer::timer ()
364 {
365         if (!_film || !_playing) {
366                 return;
367         }
368
369         get ();
370         update_position_label ();
371         update_position_slider ();
372         DCPTime const next = _video_position + one_video_frame();
373
374         if (next >= _film->length()) {
375                 stop ();
376         }
377
378         _timer.Start (max ((next.seconds() - time().seconds()) * 1000, 1.0), wxTIMER_ONE_SHOT);
379
380         if (_butler) {
381                 _butler->rethrow ();
382         }
383 }
384
385 void
386 FilmViewer::paint_panel ()
387 {
388         wxPaintDC dc (_panel);
389
390         if (!_frame || !_film || !_out_size.width || !_out_size.height || _out_size != _frame->size()) {
391                 dc.Clear ();
392                 return;
393         }
394
395         wxImage frame (_out_size.width, _out_size.height, _frame->data()[0], true);
396         wxBitmap frame_bitmap (frame);
397         dc.DrawBitmap (frame_bitmap, 0, 0);
398
399         if (_out_size.width < _panel_size.width) {
400                 wxPen p (GetBackgroundColour ());
401                 wxBrush b (GetBackgroundColour ());
402                 dc.SetPen (p);
403                 dc.SetBrush (b);
404                 dc.DrawRectangle (_out_size.width, 0, _panel_size.width - _out_size.width, _panel_size.height);
405         }
406
407         if (_out_size.height < _panel_size.height) {
408                 wxPen p (GetBackgroundColour ());
409                 wxBrush b (GetBackgroundColour ());
410                 dc.SetPen (p);
411                 dc.SetBrush (b);
412                 dc.DrawRectangle (0, _out_size.height, _panel_size.width, _panel_size.height - _out_size.height);
413         }
414
415         if (_outline_content && _outline_content->GetValue ()) {
416                 wxPen p (wxColour (255, 0, 0), 2);
417                 dc.SetPen (p);
418                 dc.SetBrush (*wxTRANSPARENT_BRUSH);
419                 dc.DrawRectangle (_inter_position.x, _inter_position.y, _inter_size.width, _inter_size.height);
420         }
421 }
422
423 /** @param page true if this was a PAGEUP/PAGEDOWN event for which we won't receive a THUMBRELEASE */
424 void
425 FilmViewer::slider_moved (bool page)
426 {
427         if (!_film) {
428                 return;
429         }
430
431         if (!page && !_slider_being_moved) {
432                 /* This is the first event of a drag; stop playback for the duration of the drag */
433                 _was_running_before_slider = stop ();
434                 _slider_being_moved = true;
435         }
436
437         DCPTime t (_slider->GetValue() * _film->length().get() / 4096);
438         t = t.round (_film->video_frame_rate());
439         /* Ensure that we hit the end of the film at the end of the slider */
440         if (t >= _film->length ()) {
441                 t = _film->length() - one_video_frame();
442         }
443         seek (t, false);
444         update_position_label ();
445 }
446
447 void
448 FilmViewer::slider_released ()
449 {
450         if (_was_running_before_slider) {
451                 /* Restart after a drag */
452                 start ();
453         }
454         _slider_being_moved = false;
455 }
456
457 void
458 FilmViewer::panel_sized (wxSizeEvent& ev)
459 {
460         _panel_size.width = ev.GetSize().GetWidth();
461         _panel_size.height = ev.GetSize().GetHeight();
462
463         calculate_sizes ();
464         if (!quick_refresh()) {
465                 slow_refresh ();
466         }
467         update_position_label ();
468         update_position_slider ();
469 }
470
471 void
472 FilmViewer::calculate_sizes ()
473 {
474         if (!_film || !_player) {
475                 return;
476         }
477
478         Ratio const * container = _film->container ();
479
480         float const panel_ratio = _panel_size.ratio ();
481         float const film_ratio = container ? container->ratio () : 1.78;
482
483         if (panel_ratio < film_ratio) {
484                 /* panel is less widscreen than the film; clamp width */
485                 _out_size.width = _panel_size.width;
486                 _out_size.height = lrintf (_out_size.width / film_ratio);
487         } else {
488                 /* panel is more widescreen than the film; clamp height */
489                 _out_size.height = _panel_size.height;
490                 _out_size.width = lrintf (_out_size.height * film_ratio);
491         }
492
493         /* Catch silly values */
494         _out_size.width = max (64, _out_size.width);
495         _out_size.height = max (64, _out_size.height);
496
497         _player->set_video_container_size (_out_size);
498 }
499
500 void
501 FilmViewer::play_clicked ()
502 {
503         check_play_state ();
504 }
505
506 void
507 FilmViewer::check_play_state ()
508 {
509         if (!_film || _film->video_frame_rate() == 0) {
510                 return;
511         }
512
513         if (_play_button->GetValue()) {
514                 start ();
515         } else {
516                 stop ();
517         }
518 }
519
520 void
521 FilmViewer::start ()
522 {
523         if (!_film) {
524                 return;
525         }
526
527         if (_audio.isStreamOpen()) {
528                 _audio.setStreamTime (_video_position.seconds());
529                 _audio.startStream ();
530         }
531
532         _playing = true;
533         _dropped = 0;
534         timer ();
535         _play_button->SetValue (true);
536 }
537
538 bool
539 FilmViewer::stop ()
540 {
541         if (_audio.isStreamRunning()) {
542                 /* stop stream and discard any remaining queued samples */
543                 _audio.abortStream ();
544         }
545
546         if (!_playing) {
547                 return false;
548         }
549
550         _playing = false;
551         _play_button->SetValue (false);
552         return true;
553 }
554
555 void
556 FilmViewer::update_position_slider ()
557 {
558         if (!_film) {
559                 _slider->SetValue (0);
560                 return;
561         }
562
563         DCPTime const len = _film->length ();
564
565         if (len.get ()) {
566                 int const new_slider_position = 4096 * _video_position.get() / len.get();
567                 if (new_slider_position != _slider->GetValue()) {
568                         _slider->SetValue (new_slider_position);
569                 }
570         }
571 }
572
573 void
574 FilmViewer::update_position_label ()
575 {
576         if (!_film) {
577                 _frame_number->SetLabel ("0");
578                 _timecode->SetLabel ("0:0:0.0");
579                 return;
580         }
581
582         double const fps = _film->video_frame_rate ();
583         /* Count frame number from 1 ... not sure if this is the best idea */
584         _frame_number->SetLabel (wxString::Format (wxT("%ld"), lrint (_video_position.seconds() * fps) + 1));
585         _timecode->SetLabel (time_to_timecode (_video_position, fps));
586 }
587
588 void
589 FilmViewer::active_jobs_changed (optional<string> j)
590 {
591         /* examine content is the only job which stops the viewer working */
592         bool const a = !j || *j != "examine_content";
593         _slider->Enable (a);
594         _play_button->Enable (a);
595 }
596
597 DCPTime
598 FilmViewer::nudge_amount (wxKeyboardState& ev)
599 {
600         DCPTime amount = one_video_frame ();
601
602         if (ev.ShiftDown() && !ev.ControlDown()) {
603                 amount = DCPTime::from_seconds (1);
604         } else if (!ev.ShiftDown() && ev.ControlDown()) {
605                 amount = DCPTime::from_seconds (10);
606         } else if (ev.ShiftDown() && ev.ControlDown()) {
607                 amount = DCPTime::from_seconds (60);
608         }
609
610         return amount;
611 }
612
613 void
614 FilmViewer::go_to (DCPTime t)
615 {
616         if (t < DCPTime ()) {
617                 t = DCPTime ();
618         }
619
620         if (t >= _film->length ()) {
621                 t = _film->length ();
622         }
623
624         seek (t, true);
625         update_position_label ();
626         update_position_slider ();
627 }
628
629 void
630 FilmViewer::rewind_clicked (wxMouseEvent& ev)
631 {
632         go_to(DCPTime());
633         ev.Skip();
634 }
635
636 void
637 FilmViewer::back_frame ()
638 {
639         if (!_film) {
640                 return;
641         }
642
643         go_to (_video_position - one_video_frame());
644 }
645
646 void
647 FilmViewer::forward_frame ()
648 {
649         if (!_film) {
650                 return;
651         }
652
653         go_to (_video_position + one_video_frame());
654 }
655
656 void
657 FilmViewer::back_clicked (wxKeyboardState& ev)
658 {
659         go_to (_video_position - nudge_amount (ev));
660 }
661
662 void
663 FilmViewer::forward_clicked (wxKeyboardState& ev)
664 {
665         go_to (_video_position + nudge_amount (ev));
666 }
667
668 void
669 FilmViewer::player_changed (int property, bool frequent)
670 {
671         if (frequent) {
672                 return;
673         }
674
675         if (_coalesce_player_changes) {
676                 _pending_player_changes.push_back (property);
677                 return;
678         }
679
680         calculate_sizes ();
681         bool refreshed = false;
682         if (
683                 property == VideoContentProperty::CROP ||
684                 property == VideoContentProperty::SCALE ||
685                 property == VideoContentProperty::FADE_IN ||
686                 property == VideoContentProperty::FADE_OUT ||
687                 property == VideoContentProperty::COLOUR_CONVERSION ||
688                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
689                 property == PlayerProperty::FILM_CONTAINER
690                 ) {
691                 refreshed = quick_refresh ();
692         }
693
694         if (!refreshed) {
695                 slow_refresh ();
696         }
697         update_position_label ();
698         update_position_slider ();
699 }
700
701 void
702 FilmViewer::setup_sensitivity ()
703 {
704         bool const c = _film && !_film->content().empty ();
705
706         _slider->Enable (c);
707         _rewind_button->Enable (c);
708         _back_button->Enable (c);
709         _forward_button->Enable (c);
710         _play_button->Enable (c);
711         if (_outline_content) {
712                 _outline_content->Enable (c);
713         }
714         _frame_number->Enable (c);
715         _timecode->Enable (c);
716         if (_jump_to_selected) {
717                 _jump_to_selected->Enable (c);
718         }
719
720         _eye->Enable (c && _film->three_d ());
721 }
722
723 void
724 FilmViewer::film_changed (Film::Property p)
725 {
726         if (p == Film::CONTENT || p == Film::THREE_D) {
727                 setup_sensitivity ();
728         } else if (p == Film::AUDIO_CHANNELS) {
729                 recreate_butler ();
730         }
731 }
732
733 void
734 FilmViewer::captions_changed ()
735 {
736         switch (_captions->GetSelection()) {
737         case 0:
738                 _player->set_always_burn_captions (CAPTION_OPEN);
739                 break;
740         case 1:
741                 _player->set_always_burn_captions (CAPTION_CLOSED);
742                 break;
743         }
744
745         slow_refresh ();
746 }
747
748 /** Re-get the current frame slowly by seeking */
749 void
750 FilmViewer::slow_refresh ()
751 {
752         seek (_video_position, true);
753 }
754
755 /** Try to re-get the current frame quickly by resetting the metadata
756  *  in the PlayerVideo that we used last time.
757  *  @return true if this was possible, false if not.
758  */
759 bool
760 FilmViewer::quick_refresh ()
761 {
762         if (!_player_video.first) {
763                 return false;
764         }
765
766         if (!_player_video.first->reset_metadata (_player->video_container_size(), _film->frame_size())) {
767                 return false;
768         }
769
770         display_player_video ();
771         return true;
772 }
773
774 void
775 FilmViewer::set_position (DCPTime p)
776 {
777         _video_position = p;
778         seek (p, true);
779         update_position_label ();
780         update_position_slider ();
781 }
782
783 void
784 FilmViewer::set_position (shared_ptr<Content> content, ContentTime t)
785 {
786         set_position (_player->content_time_to_dcp (content, t));
787 }
788
789 void
790 FilmViewer::set_coalesce_player_changes (bool c)
791 {
792         _coalesce_player_changes = c;
793
794         if (!c) {
795                 BOOST_FOREACH (int i, _pending_player_changes) {
796                         player_changed (i, false);
797                 }
798                 _pending_player_changes.clear ();
799         }
800 }
801
802 void
803 FilmViewer::timecode_clicked ()
804 {
805         PlayheadToTimecodeDialog* dialog = new PlayheadToTimecodeDialog (this, _film->video_frame_rate ());
806         if (dialog->ShowModal() == wxID_OK) {
807                 go_to (dialog->get ());
808         }
809         dialog->Destroy ();
810 }
811
812 void
813 FilmViewer::frame_number_clicked ()
814 {
815         PlayheadToFrameDialog* dialog = new PlayheadToFrameDialog (this, _film->video_frame_rate ());
816         if (dialog->ShowModal() == wxID_OK) {
817                 go_to (dialog->get ());
818         }
819         dialog->Destroy ();
820 }
821
822 void
823 FilmViewer::jump_to_selected_clicked ()
824 {
825         Config::instance()->set_jump_to_selected (_jump_to_selected->GetValue ());
826 }
827
828 void
829 FilmViewer::seek (DCPTime t, bool accurate)
830 {
831         if (!_butler) {
832                 return;
833         }
834
835         bool const was_running = stop ();
836
837         _butler->seek (t, accurate);
838         get ();
839
840         if (was_running) {
841                 start ();
842         }
843 }
844
845 void
846 FilmViewer::config_changed (Config::Property p)
847 {
848         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
849                 return;
850         }
851
852         if (_audio.isStreamOpen ()) {
853                 _audio.closeStream ();
854         }
855
856         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
857                 unsigned int st = 0;
858                 if (Config::instance()->sound_output()) {
859                         while (st < _audio.getDeviceCount()) {
860                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
861                                         break;
862                                 }
863                                 ++st;
864                         }
865                         if (st == _audio.getDeviceCount()) {
866                                 st = _audio.getDefaultOutputDevice();
867                         }
868                 } else {
869                         st = _audio.getDefaultOutputDevice();
870                 }
871
872                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
873
874                 RtAudio::StreamParameters sp;
875                 sp.deviceId = st;
876                 sp.nChannels = _audio_channels;
877                 sp.firstChannel = 0;
878                 try {
879                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
880 #ifdef DCPOMATIC_USE_RTERROR
881                 } catch (RtError& e) {
882 #else
883                 } catch (RtAudioError& e) {
884 #endif
885                         error_dialog (
886                                 this,
887                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
888                                 );
889                 }
890                 recreate_butler ();
891
892         } else {
893                 _audio_channels = 0;
894                 recreate_butler ();
895         }
896 }
897
898 DCPTime
899 FilmViewer::time () const
900 {
901         if (_audio.isStreamRunning ()) {
902                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
903                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
904         }
905
906         return _video_position;
907 }
908
909 int
910 FilmViewer::audio_callback (void* out_p, unsigned int frames)
911 {
912         _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
913
914         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
915         if (lm) {
916                 _latency_history.push_back (_audio.getStreamLatency ());
917                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
918                         _latency_history.pop_front ();
919                 }
920         }
921
922         return 0;
923 }
924
925 Frame
926 FilmViewer::average_latency () const
927 {
928         boost::mutex::scoped_lock lm (_latency_history_mutex);
929         if (_latency_history.empty()) {
930                 return 0;
931         }
932
933         Frame total = 0;
934         BOOST_FOREACH (Frame i, _latency_history) {
935                 total += i;
936         }
937
938         return total / _latency_history.size();
939 }
940
941 void
942 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
943 {
944         _dcp_decode_reduction = reduction;
945         if (_player) {
946                 _player->set_dcp_decode_reduction (reduction);
947         }
948 }
949
950 optional<int>
951 FilmViewer::dcp_decode_reduction () const
952 {
953         return _dcp_decode_reduction;
954 }
955
956 DCPTime
957 FilmViewer::one_video_frame () const
958 {
959         return DCPTime::from_frames (1, _film->video_frame_rate());
960 }