Basic jump to selected subtitle (#1200).
[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         , _slider_being_moved (false)
91         , _was_running_before_slider (false)
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::slow_refresh,    this));
149         _right_eye->Bind        (wxEVT_RADIOBUTTON,       boost::bind (&FilmViewer::slow_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, true));
152         _slider->Bind           (wxEVT_SCROLL_PAGEDOWN,   boost::bind (&FilmViewer::slider_moved,    this, true));
153         _slider->Bind           (wxEVT_SCROLL_THUMBRELEASE, boost::bind (&FilmViewer::slider_released, this));
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, _2));
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         slow_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.
255                    Map so that Lt = L(-3dB) + Ls(-3dB) + C(-6dB) + Lfe(-10dB)
256                                Rt = R(-3dB) + Rs(-3dB) + C(-6dB) + Lfe(-10dB)
257                 */
258                 map.set (dcp::LEFT,   0, 1 / sqrt(2)); // L -> Lt
259                 map.set (dcp::RIGHT,  1, 1 / sqrt(2)); // R -> Rt
260                 map.set (dcp::CENTRE, 0, 1 / 2.0); // C -> Lt
261                 map.set (dcp::CENTRE, 1, 1 / 2.0); // C -> Rt
262                 map.set (dcp::LFE,    0, 1 / sqrt(10)); // Lfe -> Lt
263                 map.set (dcp::LFE,    1, 1 / sqrt(10)); // Lfe -> Rt
264                 map.set (dcp::LS,     0, 1 / sqrt(2)); // Ls -> Lt
265                 map.set (dcp::RS,     1, 1 / sqrt(2)); // Rs -> Rt
266         }
267
268         _butler.reset (new Butler (_player, _film->log(), map, _audio_channels));
269         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
270                 _butler->disable_audio ();
271         }
272
273         if (was_running) {
274                 start ();
275         }
276 }
277
278 void
279 FilmViewer::refresh_panel ()
280 {
281         _panel->Refresh ();
282         _panel->Update ();
283 }
284
285 void
286 FilmViewer::get ()
287 {
288         DCPOMATIC_ASSERT (_butler);
289
290         do {
291                 _player_video = _butler->get_video ();
292         } while (
293                 _film->three_d() &&
294                 ((_left_eye->GetValue() && _player_video.first->eyes() == EYES_RIGHT) || (_right_eye->GetValue() && _player_video.first->eyes() == EYES_LEFT))
295                 );
296
297         _butler->rethrow ();
298
299         display_player_video ();
300 }
301
302 void
303 FilmViewer::display_player_video ()
304 {
305         if (!_player_video.first) {
306                 _frame.reset ();
307                 refresh_panel ();
308                 return;
309         }
310
311         if (_playing && (time() - _player_video.second) > one_video_frame()) {
312                 /* Too late; just drop this frame before we try to get its image (which will be the time-consuming
313                    part if this frame is J2K).
314                 */
315                 _video_position = _player_video.second;
316                 ++_dropped;
317                 return;
318         }
319
320         /* In an ideal world, what we would do here is:
321          *
322          * 1. convert to XYZ exactly as we do in the DCP creation path.
323          * 2. convert back to RGB for the preview display, compensating
324          *    for the monitor etc. etc.
325          *
326          * but this is inefficient if the source is RGB.  Since we don't
327          * (currently) care too much about the precise accuracy of the preview's
328          * colour mapping (and we care more about its speed) we try to short-
329          * circuit this "ideal" situation in some cases.
330          *
331          * The content's specified colour conversion indicates the colourspace
332          * which the content is in (according to the user).
333          *
334          * PlayerVideo::image (bound to PlayerVideo::always_rgb) will take the source
335          * image and convert it (from whatever the user has said it is) to RGB.
336          */
337
338         _frame = _player_video.first->image (
339                 bind (&Log::dcp_log, _film->log().get(), _1, _2),
340                 bind (&PlayerVideo::always_rgb, _1),
341                 false, true
342                 );
343
344         ImageChanged (_player_video.first);
345
346         _video_position = _player_video.second;
347         _inter_position = _player_video.first->inter_position ();
348         _inter_size = _player_video.first->inter_size ();
349
350         refresh_panel ();
351 }
352
353 void
354 FilmViewer::timer ()
355 {
356         if (!_film || !_playing) {
357                 return;
358         }
359
360         get ();
361         update_position_label ();
362         update_position_slider ();
363         DCPTime const next = _video_position + one_video_frame();
364
365         if (next >= _film->length()) {
366                 stop ();
367         }
368
369         _timer.Start (max ((next.seconds() - time().seconds()) * 1000, 1.0), wxTIMER_ONE_SHOT);
370
371         if (_butler) {
372                 _butler->rethrow ();
373         }
374 }
375
376 void
377 FilmViewer::paint_panel ()
378 {
379         wxPaintDC dc (_panel);
380
381         if (!_frame || !_film || !_out_size.width || !_out_size.height || _out_size != _frame->size()) {
382                 dc.Clear ();
383                 return;
384         }
385
386         wxImage frame (_out_size.width, _out_size.height, _frame->data()[0], true);
387         wxBitmap frame_bitmap (frame);
388         dc.DrawBitmap (frame_bitmap, 0, 0);
389
390         if (_out_size.width < _panel_size.width) {
391                 wxPen p (GetBackgroundColour ());
392                 wxBrush b (GetBackgroundColour ());
393                 dc.SetPen (p);
394                 dc.SetBrush (b);
395                 dc.DrawRectangle (_out_size.width, 0, _panel_size.width - _out_size.width, _panel_size.height);
396         }
397
398         if (_out_size.height < _panel_size.height) {
399                 wxPen p (GetBackgroundColour ());
400                 wxBrush b (GetBackgroundColour ());
401                 dc.SetPen (p);
402                 dc.SetBrush (b);
403                 dc.DrawRectangle (0, _out_size.height, _panel_size.width, _panel_size.height - _out_size.height);
404         }
405
406         if (_outline_content && _outline_content->GetValue ()) {
407                 wxPen p (wxColour (255, 0, 0), 2);
408                 dc.SetPen (p);
409                 dc.SetBrush (*wxTRANSPARENT_BRUSH);
410                 dc.DrawRectangle (_inter_position.x, _inter_position.y, _inter_size.width, _inter_size.height);
411         }
412 }
413
414 /** @param page true if this was a PAGEUP/PAGEDOWN event for which we won't receive a THUMBRELEASE */
415 void
416 FilmViewer::slider_moved (bool page)
417 {
418         if (!_film) {
419                 return;
420         }
421
422         if (!page && !_slider_being_moved) {
423                 /* This is the first event of a drag; stop playback for the duration of the drag */
424                 _was_running_before_slider = stop ();
425                 _slider_being_moved = true;
426         }
427
428         DCPTime t (_slider->GetValue() * _film->length().get() / 4096);
429         t = t.round (_film->video_frame_rate());
430         /* Ensure that we hit the end of the film at the end of the slider */
431         if (t >= _film->length ()) {
432                 t = _film->length() - one_video_frame();
433         }
434         seek (t, false);
435         update_position_label ();
436 }
437
438 void
439 FilmViewer::slider_released ()
440 {
441         if (_was_running_before_slider) {
442                 /* Restart after a drag */
443                 start ();
444         }
445         _slider_being_moved = false;
446 }
447
448 void
449 FilmViewer::panel_sized (wxSizeEvent& ev)
450 {
451         _panel_size.width = ev.GetSize().GetWidth();
452         _panel_size.height = ev.GetSize().GetHeight();
453
454         calculate_sizes ();
455         if (!quick_refresh()) {
456                 slow_refresh ();
457         }
458         update_position_label ();
459         update_position_slider ();
460 }
461
462 void
463 FilmViewer::calculate_sizes ()
464 {
465         if (!_film) {
466                 return;
467         }
468
469         Ratio const * container = _film->container ();
470
471         float const panel_ratio = _panel_size.ratio ();
472         float const film_ratio = container ? container->ratio () : 1.78;
473
474         if (panel_ratio < film_ratio) {
475                 /* panel is less widscreen than the film; clamp width */
476                 _out_size.width = _panel_size.width;
477                 _out_size.height = lrintf (_out_size.width / film_ratio);
478         } else {
479                 /* panel is more widescreen than the film; clamp height */
480                 _out_size.height = _panel_size.height;
481                 _out_size.width = lrintf (_out_size.height * film_ratio);
482         }
483
484         /* Catch silly values */
485         _out_size.width = max (64, _out_size.width);
486         _out_size.height = max (64, _out_size.height);
487
488         _player->set_video_container_size (_out_size);
489 }
490
491 void
492 FilmViewer::play_clicked ()
493 {
494         check_play_state ();
495 }
496
497 void
498 FilmViewer::check_play_state ()
499 {
500         if (!_film || _film->video_frame_rate() == 0) {
501                 return;
502         }
503
504         if (_play_button->GetValue()) {
505                 start ();
506         } else {
507                 stop ();
508         }
509 }
510
511 void
512 FilmViewer::start ()
513 {
514         if (!_film) {
515                 return;
516         }
517
518         if (_audio.isStreamOpen()) {
519                 _audio.setStreamTime (_video_position.seconds());
520                 _audio.startStream ();
521         }
522
523         _playing = true;
524         _dropped = 0;
525         timer ();
526         _play_button->SetValue (true);
527 }
528
529 bool
530 FilmViewer::stop ()
531 {
532         if (_audio.isStreamRunning()) {
533                 /* stop stream and discard any remaining queued samples */
534                 _audio.abortStream ();
535         }
536
537         if (!_playing) {
538                 return false;
539         }
540
541         _playing = false;
542         _play_button->SetValue (false);
543         return true;
544 }
545
546 void
547 FilmViewer::update_position_slider ()
548 {
549         if (!_film) {
550                 _slider->SetValue (0);
551                 return;
552         }
553
554         DCPTime const len = _film->length ();
555
556         if (len.get ()) {
557                 int const new_slider_position = 4096 * _video_position.get() / len.get();
558                 if (new_slider_position != _slider->GetValue()) {
559                         _slider->SetValue (new_slider_position);
560                 }
561         }
562 }
563
564 void
565 FilmViewer::update_position_label ()
566 {
567         if (!_film) {
568                 _frame_number->SetLabel ("0");
569                 _timecode->SetLabel ("0:0:0.0");
570                 return;
571         }
572
573         double const fps = _film->video_frame_rate ();
574         /* Count frame number from 1 ... not sure if this is the best idea */
575         _frame_number->SetLabel (wxString::Format (wxT("%ld"), lrint (_video_position.seconds() * fps) + 1));
576         _timecode->SetLabel (time_to_timecode (_video_position, fps));
577 }
578
579 void
580 FilmViewer::active_jobs_changed (optional<string> j)
581 {
582         /* examine content is the only job which stops the viewer working */
583         bool const a = !j || *j != "examine_content";
584         _slider->Enable (a);
585         _play_button->Enable (a);
586 }
587
588 DCPTime
589 FilmViewer::nudge_amount (wxKeyboardState& ev)
590 {
591         DCPTime amount = one_video_frame ();
592
593         if (ev.ShiftDown() && !ev.ControlDown()) {
594                 amount = DCPTime::from_seconds (1);
595         } else if (!ev.ShiftDown() && ev.ControlDown()) {
596                 amount = DCPTime::from_seconds (10);
597         } else if (ev.ShiftDown() && ev.ControlDown()) {
598                 amount = DCPTime::from_seconds (60);
599         }
600
601         return amount;
602 }
603
604 void
605 FilmViewer::go_to (DCPTime t)
606 {
607         if (t < DCPTime ()) {
608                 t = DCPTime ();
609         }
610
611         if (t >= _film->length ()) {
612                 t = _film->length ();
613         }
614
615         seek (t, true);
616         update_position_label ();
617         update_position_slider ();
618 }
619
620 void
621 FilmViewer::rewind_clicked (wxMouseEvent& ev)
622 {
623         go_to(DCPTime());
624         ev.Skip();
625 }
626
627 void
628 FilmViewer::back_frame ()
629 {
630         if (!_film) {
631                 return;
632         }
633
634         go_to (_video_position - one_video_frame());
635 }
636
637 void
638 FilmViewer::forward_frame ()
639 {
640         if (!_film) {
641                 return;
642         }
643
644         go_to (_video_position + one_video_frame());
645 }
646
647 void
648 FilmViewer::back_clicked (wxKeyboardState& ev)
649 {
650         go_to (_video_position - nudge_amount (ev));
651 }
652
653 void
654 FilmViewer::forward_clicked (wxKeyboardState& ev)
655 {
656         go_to (_video_position + nudge_amount (ev));
657 }
658
659 void
660 FilmViewer::player_changed (int property, bool frequent)
661 {
662         if (frequent) {
663                 return;
664         }
665
666         if (_coalesce_player_changes) {
667                 _pending_player_changes.push_back (property);
668                 return;
669         }
670
671         calculate_sizes ();
672         bool refreshed = false;
673         if (
674                 property == VideoContentProperty::CROP ||
675                 property == VideoContentProperty::SCALE ||
676                 property == VideoContentProperty::FADE_IN ||
677                 property == VideoContentProperty::FADE_OUT ||
678                 property == VideoContentProperty::COLOUR_CONVERSION ||
679                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
680                 property == PlayerProperty::FILM_CONTAINER
681                 ) {
682                 refreshed = quick_refresh ();
683         }
684
685         if (!refreshed) {
686                 slow_refresh ();
687         }
688         update_position_label ();
689         update_position_slider ();
690 }
691
692 void
693 FilmViewer::setup_sensitivity ()
694 {
695         bool const c = _film && !_film->content().empty ();
696
697         _slider->Enable (c);
698         _rewind_button->Enable (c);
699         _back_button->Enable (c);
700         _forward_button->Enable (c);
701         _play_button->Enable (c);
702         if (_outline_content) {
703                 _outline_content->Enable (c);
704         }
705         _frame_number->Enable (c);
706         _timecode->Enable (c);
707         if (_jump_to_selected) {
708                 _jump_to_selected->Enable (c);
709         }
710
711         _left_eye->Enable (c && _film->three_d ());
712         _right_eye->Enable (c && _film->three_d ());
713 }
714
715 void
716 FilmViewer::film_changed (Film::Property p)
717 {
718         if (p == Film::CONTENT || p == Film::THREE_D) {
719                 setup_sensitivity ();
720         } else if (p == Film::AUDIO_CHANNELS) {
721                 recreate_butler ();
722         }
723 }
724
725 /** Re-get the current frame slowly by seeking */
726 void
727 FilmViewer::slow_refresh ()
728 {
729         seek (_video_position, true);
730 }
731
732 /** Try to re-get the current frame quickly by resetting the metadata
733  *  in the PlayerVideo that we used last time.
734  *  @return true if this was possible, false if not.
735  */
736 bool
737 FilmViewer::quick_refresh ()
738 {
739         if (!_player_video.first) {
740                 return false;
741         }
742
743         if (!_player_video.first->reset_metadata (_player->video_container_size(), _film->frame_size())) {
744                 return false;
745         }
746
747         display_player_video ();
748         return true;
749 }
750
751 void
752 FilmViewer::set_position (DCPTime p)
753 {
754         _video_position = p;
755         seek (p, true);
756         update_position_label ();
757         update_position_slider ();
758 }
759
760 void
761 FilmViewer::set_position (shared_ptr<Content> content, ContentTime t)
762 {
763         set_position (_player->content_time_to_dcp (content, t));
764 }
765
766 void
767 FilmViewer::set_coalesce_player_changes (bool c)
768 {
769         _coalesce_player_changes = c;
770
771         if (!c) {
772                 BOOST_FOREACH (int i, _pending_player_changes) {
773                         player_changed (i, false);
774                 }
775                 _pending_player_changes.clear ();
776         }
777 }
778
779 void
780 FilmViewer::timecode_clicked ()
781 {
782         PlayheadToTimecodeDialog* dialog = new PlayheadToTimecodeDialog (this, _film->video_frame_rate ());
783         if (dialog->ShowModal() == wxID_OK) {
784                 go_to (dialog->get ());
785         }
786         dialog->Destroy ();
787 }
788
789 void
790 FilmViewer::frame_number_clicked ()
791 {
792         PlayheadToFrameDialog* dialog = new PlayheadToFrameDialog (this, _film->video_frame_rate ());
793         if (dialog->ShowModal() == wxID_OK) {
794                 go_to (dialog->get ());
795         }
796         dialog->Destroy ();
797 }
798
799 void
800 FilmViewer::jump_to_selected_clicked ()
801 {
802         Config::instance()->set_jump_to_selected (_jump_to_selected->GetValue ());
803 }
804
805 void
806 FilmViewer::seek (DCPTime t, bool accurate)
807 {
808         if (!_butler) {
809                 return;
810         }
811
812         bool const was_running = stop ();
813
814         _butler->seek (t, accurate);
815         get ();
816
817         if (was_running) {
818                 start ();
819         }
820 }
821
822 void
823 FilmViewer::config_changed (Config::Property p)
824 {
825         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
826                 return;
827         }
828
829         if (_audio.isStreamOpen ()) {
830                 _audio.closeStream ();
831         }
832
833         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
834                 unsigned int st = 0;
835                 if (Config::instance()->sound_output()) {
836                         while (st < _audio.getDeviceCount()) {
837                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
838                                         break;
839                                 }
840                                 ++st;
841                         }
842                         if (st == _audio.getDeviceCount()) {
843                                 st = _audio.getDefaultOutputDevice();
844                         }
845                 } else {
846                         st = _audio.getDefaultOutputDevice();
847                 }
848
849                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
850
851                 RtAudio::StreamParameters sp;
852                 sp.deviceId = st;
853                 sp.nChannels = _audio_channels;
854                 sp.firstChannel = 0;
855                 try {
856                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
857 #ifdef DCPOMATIC_USE_RTERROR
858                 } catch (RtError& e) {
859 #else
860                 } catch (RtAudioError& e) {
861 #endif
862                         error_dialog (
863                                 this,
864                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
865                                 );
866                 }
867                 recreate_butler ();
868
869         } else {
870                 _audio_channels = 0;
871                 recreate_butler ();
872         }
873 }
874
875 DCPTime
876 FilmViewer::time () const
877 {
878         if (_audio.isStreamRunning ()) {
879                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
880                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
881         }
882
883         return _video_position;
884 }
885
886 int
887 FilmViewer::audio_callback (void* out_p, unsigned int frames)
888 {
889         _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
890
891         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
892         if (lm) {
893                 _latency_history.push_back (_audio.getStreamLatency ());
894                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
895                         _latency_history.pop_front ();
896                 }
897         }
898
899         return 0;
900 }
901
902 Frame
903 FilmViewer::average_latency () const
904 {
905         boost::mutex::scoped_lock lm (_latency_history_mutex);
906         if (_latency_history.empty()) {
907                 return 0;
908         }
909
910         Frame total = 0;
911         BOOST_FOREACH (Frame i, _latency_history) {
912                 total += i;
913         }
914
915         return total / _latency_history.size();
916 }
917
918 void
919 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
920 {
921         _dcp_decode_reduction = reduction;
922         if (_player) {
923                 _player->set_dcp_decode_reduction (reduction);
924         }
925 }
926
927 optional<int>
928 FilmViewer::dcp_decode_reduction () const
929 {
930         return _dcp_decode_reduction;
931 }
932
933 DCPTime
934 FilmViewer::one_video_frame () const
935 {
936         return DCPTime::from_frames (1, _film->video_frame_rate());
937 }