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