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