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