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