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