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