Merge branch 'master' of ssh://git.carlh.net/home/carl/git/dcpomatic
[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 "closed_captions_dialog.h"
30 #include "lib/film.h"
31 #include "lib/ratio.h"
32 #include "lib/util.h"
33 #include "lib/job_manager.h"
34 #include "lib/image.h"
35 #include "lib/exceptions.h"
36 #include "lib/examine_content_job.h"
37 #include "lib/filter.h"
38 #include "lib/player.h"
39 #include "lib/player_video.h"
40 #include "lib/video_content.h"
41 #include "lib/video_decoder.h"
42 #include "lib/timer.h"
43 #include "lib/butler.h"
44 #include "lib/log.h"
45 #include "lib/config.h"
46 extern "C" {
47 #include <libavutil/pixfmt.h>
48 }
49 #include <dcp/exceptions.h>
50 #include <wx/tglbtn.h>
51 #include <iostream>
52 #include <iomanip>
53
54 using std::string;
55 using std::pair;
56 using std::min;
57 using std::max;
58 using std::cout;
59 using std::list;
60 using std::bad_alloc;
61 using std::make_pair;
62 using std::exception;
63 using boost::shared_ptr;
64 using boost::dynamic_pointer_cast;
65 using boost::weak_ptr;
66 using boost::optional;
67 using dcp::Size;
68
69 static
70 int
71 rtaudio_callback (void* out, void *, unsigned int frames, double, RtAudioStreamStatus, void* data)
72 {
73         return reinterpret_cast<FilmViewer*>(data)->audio_callback (out, frames);
74 }
75
76 FilmViewer::FilmViewer (wxWindow* p, bool outline_content, bool jump_to_selected)
77         : wxPanel (p)
78         , _panel (new wxPanel (this))
79         , _outline_content (0)
80         , _eye (0)
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         , _closed_captions_dialog (new ClosedCaptionsDialog(GetParent()))
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 | wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_GAP);
115         }
116
117         _eye = new wxChoice (this, wxID_ANY);
118         _eye->Append (_("Left"));
119         _eye->Append (_("Right"));
120         _eye->SetSelection (0);
121         view_options->Add (_eye, 0, wxLEFT | wxRIGHT | wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_GAP);
122
123         if (jump_to_selected) {
124                 _jump_to_selected = new wxCheckBox (this, wxID_ANY, _("Jump to selected content"));
125                 view_options->Add (_jump_to_selected, 0, wxLEFT | wxRIGHT | wxALIGN_CENTER_VERTICAL, DCPOMATIC_SIZER_GAP);
126         }
127
128         _v_sizer->Add (view_options, 0, wxALL, DCPOMATIC_SIZER_GAP);
129
130         wxBoxSizer* h_sizer = new wxBoxSizer (wxHORIZONTAL);
131
132         wxBoxSizer* time_sizer = new wxBoxSizer (wxVERTICAL);
133         time_sizer->Add (_frame_number, 0, wxEXPAND);
134         time_sizer->Add (_timecode, 0, wxEXPAND);
135
136         h_sizer->Add (_rewind_button, 0, wxALL, 2);
137         h_sizer->Add (_back_button, 0, wxALL, 2);
138         h_sizer->Add (time_sizer, 0, wxEXPAND);
139         h_sizer->Add (_forward_button, 0, wxALL, 2);
140         h_sizer->Add (_play_button, 0, wxEXPAND);
141         h_sizer->Add (_slider, 1, wxEXPAND);
142
143         _v_sizer->Add (h_sizer, 0, wxEXPAND | wxALL, 6);
144
145         _frame_number->SetMinSize (wxSize (84, -1));
146         _rewind_button->SetMinSize (wxSize (32, -1));
147         _back_button->SetMinSize (wxSize (32, -1));
148         _forward_button->SetMinSize (wxSize (32, -1));
149
150         _panel->Bind            (wxEVT_PAINT,               boost::bind (&FilmViewer::paint_panel,     this));
151         _panel->Bind            (wxEVT_SIZE,                boost::bind (&FilmViewer::panel_sized,     this, _1));
152         if (_outline_content) {
153                 _outline_content->Bind  (wxEVT_CHECKBOX,    boost::bind (&FilmViewer::refresh_panel,   this));
154         }
155         _eye->Bind              (wxEVT_CHOICE,              boost::bind (&FilmViewer::slow_refresh,    this));
156         _slider->Bind           (wxEVT_SCROLL_THUMBTRACK,   boost::bind (&FilmViewer::slider_moved,    this, false));
157         _slider->Bind           (wxEVT_SCROLL_PAGEUP,       boost::bind (&FilmViewer::slider_moved,    this, true));
158         _slider->Bind           (wxEVT_SCROLL_PAGEDOWN,     boost::bind (&FilmViewer::slider_moved,    this, true));
159         _slider->Bind           (wxEVT_SCROLL_THUMBRELEASE, boost::bind (&FilmViewer::slider_released, this));
160         _play_button->Bind      (wxEVT_TOGGLEBUTTON,        boost::bind (&FilmViewer::play_clicked,    this));
161         _timer.Bind             (wxEVT_TIMER,               boost::bind (&FilmViewer::timer,           this));
162         _rewind_button->Bind    (wxEVT_LEFT_DOWN,           boost::bind (&FilmViewer::rewind_clicked,  this, _1));
163         _back_button->Bind      (wxEVT_LEFT_DOWN,           boost::bind (&FilmViewer::back_clicked,    this, _1));
164         _forward_button->Bind   (wxEVT_LEFT_DOWN,           boost::bind (&FilmViewer::forward_clicked, this, _1));
165         _frame_number->Bind     (wxEVT_LEFT_DOWN,           boost::bind (&FilmViewer::frame_number_clicked, this));
166         _timecode->Bind         (wxEVT_LEFT_DOWN,           boost::bind (&FilmViewer::timecode_clicked, this));
167         if (_jump_to_selected) {
168                 _jump_to_selected->Bind (wxEVT_CHECKBOX, boost::bind (&FilmViewer::jump_to_selected_clicked, this));
169                 _jump_to_selected->SetValue (Config::instance()->jump_to_selected ());
170         }
171
172         set_film (shared_ptr<Film> ());
173
174         JobManager::instance()->ActiveJobsChanged.connect (
175                 bind (&FilmViewer::active_jobs_changed, this, _2)
176                 );
177
178         setup_sensitivity ();
179
180         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
181         config_changed (Config::SOUND_OUTPUT);
182 }
183
184 FilmViewer::~FilmViewer ()
185 {
186         stop ();
187 }
188
189 void
190 FilmViewer::set_film (shared_ptr<Film> film)
191 {
192         if (_film == film) {
193                 return;
194         }
195
196         _film = film;
197
198         _frame.reset ();
199         _closed_captions_dialog->clear ();
200
201         update_position_slider ();
202         update_position_label ();
203
204         if (!_film) {
205                 _player.reset ();
206                 recreate_butler ();
207                 _frame.reset ();
208                 refresh_panel ();
209                 return;
210         }
211
212         try {
213                 _player.reset (new Player (_film, _film->playlist ()));
214                 _player->set_fast ();
215                 if (_dcp_decode_reduction) {
216                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
217                 }
218         } catch (bad_alloc) {
219                 error_dialog (this, _("There is not enough free memory to do that."));
220                 _film.reset ();
221                 return;
222         }
223
224         _player->set_always_burn_open_subtitles ();
225         _player->set_play_referenced ();
226
227         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
228         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
229
230         /* Keep about 1 second's worth of history samples */
231         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
232
233         recreate_butler ();
234
235         calculate_sizes ();
236         slow_refresh ();
237
238         setup_sensitivity ();
239 }
240
241 void
242 FilmViewer::recreate_butler ()
243 {
244         bool const was_running = stop ();
245         _butler.reset ();
246
247         if (!_film) {
248                 return;
249         }
250
251         AudioMapping map = AudioMapping (_film->audio_channels(), _audio_channels);
252
253         if (_audio_channels != 2 || _film->audio_channels() < 3) {
254                 for (int i = 0; i < min (_film->audio_channels(), _audio_channels); ++i) {
255                         map.set (i, i, 1);
256                 }
257         } else {
258                 /* Special case: stereo output, at least 3 channel input.
259                    Map so that Lt = L(-3dB) + Ls(-3dB) + C(-6dB) + Lfe(-10dB)
260                                Rt = R(-3dB) + Rs(-3dB) + C(-6dB) + Lfe(-10dB)
261                 */
262                 map.set (dcp::LEFT,   0, 1 / sqrt(2)); // L -> Lt
263                 map.set (dcp::RIGHT,  1, 1 / sqrt(2)); // R -> Rt
264                 map.set (dcp::CENTRE, 0, 1 / 2.0); // C -> Lt
265                 map.set (dcp::CENTRE, 1, 1 / 2.0); // C -> Rt
266                 map.set (dcp::LFE,    0, 1 / sqrt(10)); // Lfe -> Lt
267                 map.set (dcp::LFE,    1, 1 / sqrt(10)); // Lfe -> Rt
268                 map.set (dcp::LS,     0, 1 / sqrt(2)); // Ls -> Lt
269                 map.set (dcp::RS,     1, 1 / sqrt(2)); // Rs -> Rt
270         }
271
272         _butler.reset (new Butler (_player, _film->log(), map, _audio_channels));
273         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
274                 _butler->disable_audio ();
275         }
276
277         _closed_captions_dialog->set_butler (_butler);
278
279         if (was_running) {
280                 start ();
281         }
282 }
283
284 void
285 FilmViewer::refresh_panel ()
286 {
287         _panel->Refresh ();
288         _panel->Update ();
289 }
290
291 void
292 FilmViewer::get ()
293 {
294         DCPOMATIC_ASSERT (_butler);
295
296         do {
297                 Butler::Error e;
298                 _player_video = _butler->get_video (&e);
299                 if (!_player_video.first && e == Butler::AGAIN) {
300                         signal_manager->when_idle (boost::bind(&FilmViewer::get, this));
301                         return;
302                 }
303         } while (
304                 _player_video.first &&
305                 _film->three_d() &&
306                 ((_eye->GetSelection() == 0 && _player_video.first->eyes() == EYES_RIGHT) || (_eye->GetSelection() == 1 && _player_video.first->eyes() == EYES_LEFT))
307                 );
308
309         _butler->rethrow ();
310
311         display_player_video ();
312 }
313
314 void
315 FilmViewer::display_player_video ()
316 {
317         if (!_player_video.first) {
318                 _frame.reset ();
319                 refresh_panel ();
320                 return;
321         }
322
323         if (_playing && (time() - _player_video.second) > one_video_frame()) {
324                 /* Too late; just drop this frame before we try to get its image (which will be the time-consuming
325                    part if this frame is J2K).
326                 */
327                 _video_position = _player_video.second;
328                 ++_dropped;
329                 return;
330         }
331
332         /* In an ideal world, what we would do here is:
333          *
334          * 1. convert to XYZ exactly as we do in the DCP creation path.
335          * 2. convert back to RGB for the preview display, compensating
336          *    for the monitor etc. etc.
337          *
338          * but this is inefficient if the source is RGB.  Since we don't
339          * (currently) care too much about the precise accuracy of the preview's
340          * colour mapping (and we care more about its speed) we try to short-
341          * circuit this "ideal" situation in some cases.
342          *
343          * The content's specified colour conversion indicates the colourspace
344          * which the content is in (according to the user).
345          *
346          * PlayerVideo::image (bound to PlayerVideo::always_rgb) will take the source
347          * image and convert it (from whatever the user has said it is) to RGB.
348          */
349
350         _frame = _player_video.first->image (
351                 bind (&Log::dcp_log, _film->log().get(), _1, _2),
352                 bind (&PlayerVideo::always_rgb, _1),
353                 false, true
354                 );
355
356         ImageChanged (_player_video.first);
357
358         _video_position = _player_video.second;
359         _inter_position = _player_video.first->inter_position ();
360         _inter_size = _player_video.first->inter_size ();
361
362         refresh_panel ();
363
364         _closed_captions_dialog->update (time());
365 }
366
367 void
368 FilmViewer::timer ()
369 {
370         if (!_film || !_playing) {
371                 return;
372         }
373
374         get ();
375         update_position_label ();
376         update_position_slider ();
377         DCPTime const next = _video_position + one_video_frame();
378
379         if (next >= _film->length()) {
380                 stop ();
381         }
382
383         _timer.Start (max ((next.seconds() - time().seconds()) * 1000, 1.0), wxTIMER_ONE_SHOT);
384
385         if (_butler) {
386                 _butler->rethrow ();
387         }
388 }
389
390 void
391 FilmViewer::paint_panel ()
392 {
393         wxPaintDC dc (_panel);
394
395         if (!_frame || !_film || !_out_size.width || !_out_size.height || _out_size != _frame->size()) {
396                 dc.Clear ();
397                 return;
398         }
399
400         wxImage frame (_out_size.width, _out_size.height, _frame->data()[0], true);
401         wxBitmap frame_bitmap (frame);
402         dc.DrawBitmap (frame_bitmap, 0, 0);
403
404         if (_out_size.width < _panel_size.width) {
405                 wxPen p (GetBackgroundColour ());
406                 wxBrush b (GetBackgroundColour ());
407                 dc.SetPen (p);
408                 dc.SetBrush (b);
409                 dc.DrawRectangle (_out_size.width, 0, _panel_size.width - _out_size.width, _panel_size.height);
410         }
411
412         if (_out_size.height < _panel_size.height) {
413                 wxPen p (GetBackgroundColour ());
414                 wxBrush b (GetBackgroundColour ());
415                 dc.SetPen (p);
416                 dc.SetBrush (b);
417                 dc.DrawRectangle (0, _out_size.height, _panel_size.width, _panel_size.height - _out_size.height);
418         }
419
420         if (_outline_content && _outline_content->GetValue ()) {
421                 wxPen p (wxColour (255, 0, 0), 2);
422                 dc.SetPen (p);
423                 dc.SetBrush (*wxTRANSPARENT_BRUSH);
424                 dc.DrawRectangle (_inter_position.x, _inter_position.y, _inter_size.width, _inter_size.height);
425         }
426 }
427
428 /** @param page true if this was a PAGEUP/PAGEDOWN event for which we won't receive a THUMBRELEASE */
429 void
430 FilmViewer::slider_moved (bool page)
431 {
432         if (!_film) {
433                 return;
434         }
435
436         if (!page && !_slider_being_moved) {
437                 /* This is the first event of a drag; stop playback for the duration of the drag */
438                 _was_running_before_slider = stop ();
439                 _slider_being_moved = true;
440         }
441
442         DCPTime t (_slider->GetValue() * _film->length().get() / 4096);
443         t = t.round (_film->video_frame_rate());
444         /* Ensure that we hit the end of the film at the end of the slider */
445         if (t >= _film->length ()) {
446                 t = _film->length() - one_video_frame();
447         }
448         seek (t, false);
449         update_position_label ();
450 }
451
452 void
453 FilmViewer::slider_released ()
454 {
455         if (_was_running_before_slider) {
456                 /* Restart after a drag */
457                 start ();
458         }
459         _slider_being_moved = false;
460 }
461
462 void
463 FilmViewer::panel_sized (wxSizeEvent& ev)
464 {
465         _panel_size.width = ev.GetSize().GetWidth();
466         _panel_size.height = ev.GetSize().GetHeight();
467
468         calculate_sizes ();
469         if (!quick_refresh()) {
470                 slow_refresh ();
471         }
472         update_position_label ();
473         update_position_slider ();
474 }
475
476 void
477 FilmViewer::calculate_sizes ()
478 {
479         if (!_film || !_player) {
480                 return;
481         }
482
483         Ratio const * container = _film->container ();
484
485         float const panel_ratio = _panel_size.ratio ();
486         float const film_ratio = container ? container->ratio () : 1.78;
487
488         if (panel_ratio < film_ratio) {
489                 /* panel is less widscreen than the film; clamp width */
490                 _out_size.width = _panel_size.width;
491                 _out_size.height = lrintf (_out_size.width / film_ratio);
492         } else {
493                 /* panel is more widescreen than the film; clamp height */
494                 _out_size.height = _panel_size.height;
495                 _out_size.width = lrintf (_out_size.height * film_ratio);
496         }
497
498         /* Catch silly values */
499         _out_size.width = max (64, _out_size.width);
500         _out_size.height = max (64, _out_size.height);
501
502         _player->set_video_container_size (_out_size);
503 }
504
505 void
506 FilmViewer::play_clicked ()
507 {
508         check_play_state ();
509 }
510
511 void
512 FilmViewer::check_play_state ()
513 {
514         if (!_film || _film->video_frame_rate() == 0) {
515                 return;
516         }
517
518         if (_play_button->GetValue()) {
519                 start ();
520         } else {
521                 stop ();
522         }
523 }
524
525 void
526 FilmViewer::start ()
527 {
528         if (!_film) {
529                 return;
530         }
531
532         if (_audio.isStreamOpen()) {
533                 _audio.setStreamTime (_video_position.seconds());
534                 _audio.startStream ();
535         }
536
537         _playing = true;
538         _dropped = 0;
539         timer ();
540         _play_button->SetValue (true);
541 }
542
543 bool
544 FilmViewer::stop ()
545 {
546         if (_audio.isStreamRunning()) {
547                 /* stop stream and discard any remaining queued samples */
548                 _audio.abortStream ();
549         }
550
551         if (!_playing) {
552                 return false;
553         }
554
555         _playing = false;
556         _play_button->SetValue (false);
557         return true;
558 }
559
560 void
561 FilmViewer::update_position_slider ()
562 {
563         if (!_film) {
564                 _slider->SetValue (0);
565                 return;
566         }
567
568         DCPTime const len = _film->length ();
569
570         if (len.get ()) {
571                 int const new_slider_position = 4096 * _video_position.get() / len.get();
572                 if (new_slider_position != _slider->GetValue()) {
573                         _slider->SetValue (new_slider_position);
574                 }
575         }
576 }
577
578 void
579 FilmViewer::update_position_label ()
580 {
581         if (!_film) {
582                 _frame_number->SetLabel ("0");
583                 _timecode->SetLabel ("0:0:0.0");
584                 return;
585         }
586
587         double const fps = _film->video_frame_rate ();
588         /* Count frame number from 1 ... not sure if this is the best idea */
589         _frame_number->SetLabel (wxString::Format (wxT("%ld"), lrint (_video_position.seconds() * fps) + 1));
590         _timecode->SetLabel (time_to_timecode (_video_position, fps));
591 }
592
593 void
594 FilmViewer::active_jobs_changed (optional<string> j)
595 {
596         /* examine content is the only job which stops the viewer working */
597         bool const a = !j || *j != "examine_content";
598         _slider->Enable (a);
599         _play_button->Enable (a);
600 }
601
602 DCPTime
603 FilmViewer::nudge_amount (wxKeyboardState& ev)
604 {
605         DCPTime amount = one_video_frame ();
606
607         if (ev.ShiftDown() && !ev.ControlDown()) {
608                 amount = DCPTime::from_seconds (1);
609         } else if (!ev.ShiftDown() && ev.ControlDown()) {
610                 amount = DCPTime::from_seconds (10);
611         } else if (ev.ShiftDown() && ev.ControlDown()) {
612                 amount = DCPTime::from_seconds (60);
613         }
614
615         return amount;
616 }
617
618 void
619 FilmViewer::go_to (DCPTime t)
620 {
621         if (t < DCPTime ()) {
622                 t = DCPTime ();
623         }
624
625         if (t >= _film->length ()) {
626                 t = _film->length ();
627         }
628
629         seek (t, true);
630         update_position_label ();
631         update_position_slider ();
632 }
633
634 void
635 FilmViewer::rewind_clicked (wxMouseEvent& ev)
636 {
637         go_to(DCPTime());
638         ev.Skip();
639 }
640
641 void
642 FilmViewer::back_frame ()
643 {
644         if (!_film) {
645                 return;
646         }
647
648         go_to (_video_position - one_video_frame());
649 }
650
651 void
652 FilmViewer::forward_frame ()
653 {
654         if (!_film) {
655                 return;
656         }
657
658         go_to (_video_position + one_video_frame());
659 }
660
661 void
662 FilmViewer::back_clicked (wxKeyboardState& ev)
663 {
664         go_to (_video_position - nudge_amount (ev));
665 }
666
667 void
668 FilmViewer::forward_clicked (wxKeyboardState& ev)
669 {
670         go_to (_video_position + nudge_amount (ev));
671 }
672
673 void
674 FilmViewer::player_change (ChangeType type, int property, bool frequent)
675 {
676         if (type != CHANGE_TYPE_DONE || frequent) {
677                 return;
678         }
679
680         if (_coalesce_player_changes) {
681                 _pending_player_changes.push_back (property);
682                 return;
683         }
684
685         calculate_sizes ();
686         bool refreshed = false;
687         if (
688                 property == VideoContentProperty::CROP ||
689                 property == VideoContentProperty::SCALE ||
690                 property == VideoContentProperty::FADE_IN ||
691                 property == VideoContentProperty::FADE_OUT ||
692                 property == VideoContentProperty::COLOUR_CONVERSION ||
693                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
694                 property == PlayerProperty::FILM_CONTAINER
695                 ) {
696                 refreshed = quick_refresh ();
697         }
698
699         if (!refreshed) {
700                 slow_refresh ();
701         }
702         update_position_label ();
703         update_position_slider ();
704 }
705
706 void
707 FilmViewer::setup_sensitivity ()
708 {
709         bool const c = _film && !_film->content().empty ();
710
711         _slider->Enable (c);
712         _rewind_button->Enable (c);
713         _back_button->Enable (c);
714         _forward_button->Enable (c);
715         _play_button->Enable (c);
716         if (_outline_content) {
717                 _outline_content->Enable (c);
718         }
719         _frame_number->Enable (c);
720         _timecode->Enable (c);
721         if (_jump_to_selected) {
722                 _jump_to_selected->Enable (c);
723         }
724
725         _eye->Enable (c && _film->three_d ());
726 }
727
728 void
729 FilmViewer::film_change (ChangeType type, Film::Property p)
730 {
731         if (type != CHANGE_TYPE_DONE) {
732                 return;
733         }
734
735         if (p == Film::CONTENT || p == Film::THREE_D) {
736                 setup_sensitivity ();
737         } else if (p == Film::AUDIO_CHANNELS) {
738                 recreate_butler ();
739         }
740 }
741
742 /** Re-get the current frame slowly by seeking */
743 void
744 FilmViewer::slow_refresh ()
745 {
746         seek (_video_position, true);
747 }
748
749 /** Try to re-get the current frame quickly by resetting the metadata
750  *  in the PlayerVideo that we used last time.
751  *  @return true if this was possible, false if not.
752  */
753 bool
754 FilmViewer::quick_refresh ()
755 {
756         if (!_player_video.first) {
757                 return false;
758         }
759
760         if (!_player_video.first->reset_metadata (_player->video_container_size(), _film->frame_size())) {
761                 return false;
762         }
763
764         display_player_video ();
765         return true;
766 }
767
768 void
769 FilmViewer::set_position (DCPTime p)
770 {
771         _video_position = p;
772         seek (p, true);
773         update_position_label ();
774         update_position_slider ();
775 }
776
777 void
778 FilmViewer::set_position (shared_ptr<Content> content, ContentTime t)
779 {
780         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
781         if (dt) {
782                 set_position (*dt);
783         }
784 }
785
786 void
787 FilmViewer::set_coalesce_player_changes (bool c)
788 {
789         _coalesce_player_changes = c;
790
791         if (!c) {
792                 BOOST_FOREACH (int i, _pending_player_changes) {
793                         player_change (CHANGE_TYPE_DONE, i, false);
794                 }
795                 _pending_player_changes.clear ();
796         }
797 }
798
799 void
800 FilmViewer::timecode_clicked ()
801 {
802         PlayheadToTimecodeDialog* dialog = new PlayheadToTimecodeDialog (this, _film->video_frame_rate ());
803         if (dialog->ShowModal() == wxID_OK) {
804                 go_to (dialog->get ());
805         }
806         dialog->Destroy ();
807 }
808
809 void
810 FilmViewer::frame_number_clicked ()
811 {
812         PlayheadToFrameDialog* dialog = new PlayheadToFrameDialog (this, _film->video_frame_rate ());
813         if (dialog->ShowModal() == wxID_OK) {
814                 go_to (dialog->get ());
815         }
816         dialog->Destroy ();
817 }
818
819 void
820 FilmViewer::jump_to_selected_clicked ()
821 {
822         Config::instance()->set_jump_to_selected (_jump_to_selected->GetValue ());
823 }
824
825 void
826 FilmViewer::seek (DCPTime t, bool accurate)
827 {
828         if (!_butler) {
829                 return;
830         }
831
832         bool const was_running = stop ();
833
834         _closed_captions_dialog->clear ();
835         _butler->seek (t, accurate);
836         get ();
837
838         if (was_running) {
839                 start ();
840         }
841 }
842
843 void
844 FilmViewer::config_changed (Config::Property p)
845 {
846         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
847                 return;
848         }
849
850         if (_audio.isStreamOpen ()) {
851                 _audio.closeStream ();
852         }
853
854         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
855                 unsigned int st = 0;
856                 if (Config::instance()->sound_output()) {
857                         while (st < _audio.getDeviceCount()) {
858                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
859                                         break;
860                                 }
861                                 ++st;
862                         }
863                         if (st == _audio.getDeviceCount()) {
864                                 st = _audio.getDefaultOutputDevice();
865                         }
866                 } else {
867                         st = _audio.getDefaultOutputDevice();
868                 }
869
870                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
871
872                 RtAudio::StreamParameters sp;
873                 sp.deviceId = st;
874                 sp.nChannels = _audio_channels;
875                 sp.firstChannel = 0;
876                 try {
877                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
878 #ifdef DCPOMATIC_USE_RTERROR
879                 } catch (RtError& e) {
880 #else
881                 } catch (RtAudioError& e) {
882 #endif
883                         error_dialog (
884                                 this,
885                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
886                                 );
887                 }
888                 recreate_butler ();
889
890         } else {
891                 _audio_channels = 0;
892                 recreate_butler ();
893         }
894 }
895
896 DCPTime
897 FilmViewer::uncorrected_time () const
898 {
899         if (_audio.isStreamRunning ()) {
900                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
901         }
902
903         return _video_position;
904 }
905
906 DCPTime
907 FilmViewer::time () const
908 {
909         if (_audio.isStreamRunning ()) {
910                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
911                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
912         }
913
914         return _video_position;
915 }
916
917 int
918 FilmViewer::audio_callback (void* out_p, unsigned int frames)
919 {
920         while (true) {
921                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
922                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
923                         /* There was an underrun or this audio is on time; carry on */
924                         break;
925                 }
926                 /* The audio we just got was (very) late; drop it and get some more. */
927         }
928
929         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
930         if (lm) {
931                 _latency_history.push_back (_audio.getStreamLatency ());
932                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
933                         _latency_history.pop_front ();
934                 }
935         }
936
937         return 0;
938 }
939
940 Frame
941 FilmViewer::average_latency () const
942 {
943         boost::mutex::scoped_lock lm (_latency_history_mutex);
944         if (_latency_history.empty()) {
945                 return 0;
946         }
947
948         Frame total = 0;
949         BOOST_FOREACH (Frame i, _latency_history) {
950                 total += i;
951         }
952
953         return total / _latency_history.size();
954 }
955
956 void
957 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
958 {
959         _dcp_decode_reduction = reduction;
960         if (_player) {
961                 _player->set_dcp_decode_reduction (reduction);
962         }
963 }
964
965 optional<int>
966 FilmViewer::dcp_decode_reduction () const
967 {
968         return _dcp_decode_reduction;
969 }
970
971 DCPTime
972 FilmViewer::one_video_frame () const
973 {
974         return DCPTime::from_frames (1, _film->video_frame_rate());
975 }
976
977 void
978 FilmViewer::show_closed_captions ()
979 {
980         _closed_captions_dialog->Show();
981 }