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