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