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