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