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