Separate Controls into standard/swaroop.
[dcpomatic.git] / src / wx / film_viewer.cc
1 /*
2     Copyright (C) 2012-2018 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 #include "lib/compose.hpp"
47 extern "C" {
48 #include <libavutil/pixfmt.h>
49 }
50 #include <dcp/exceptions.h>
51 #include <wx/tglbtn.h>
52 #include <iostream>
53 #include <iomanip>
54
55 using std::string;
56 using std::pair;
57 using std::min;
58 using std::max;
59 using std::cout;
60 using std::list;
61 using std::bad_alloc;
62 using std::make_pair;
63 using std::exception;
64 using boost::shared_ptr;
65 using boost::dynamic_pointer_cast;
66 using boost::weak_ptr;
67 using boost::optional;
68 using dcp::Size;
69
70 static
71 int
72 rtaudio_callback (void* out, void *, unsigned int frames, double, RtAudioStreamStatus, void* data)
73 {
74         return reinterpret_cast<FilmViewer*>(data)->audio_callback (out, frames);
75 }
76
77 FilmViewer::FilmViewer (wxWindow* p)
78         : _panel (new wxPanel (p))
79         , _coalesce_player_changes (false)
80         , _audio (DCPOMATIC_RTAUDIO_API)
81         , _audio_channels (0)
82         , _audio_block_size (1024)
83         , _playing (false)
84         , _latency_history_count (0)
85         , _dropped (0)
86         , _closed_captions_dialog (new ClosedCaptionsDialog(p))
87         , _outline_content (false)
88         , _eyes (EYES_LEFT)
89         , _pad_black (false)
90 #ifdef DCPOMATIC_VARIANT_SWAROOP
91         , _in_watermark (false)
92 #endif
93 {
94 #ifndef __WXOSX__
95         _panel->SetDoubleBuffered (true);
96 #endif
97
98         _panel->SetBackgroundStyle (wxBG_STYLE_PAINT);
99         _panel->SetBackgroundColour (*wxBLACK);
100
101         _panel->Bind (wxEVT_PAINT, boost::bind (&FilmViewer::paint_panel, this));
102         _panel->Bind (wxEVT_SIZE,  boost::bind (&FilmViewer::panel_sized, this, _1));
103         _timer.Bind  (wxEVT_TIMER, boost::bind (&FilmViewer::timer, this));
104
105         set_film (shared_ptr<Film> ());
106
107         _config_changed_connection = Config::instance()->Changed.connect (bind (&FilmViewer::config_changed, this, _1));
108         config_changed (Config::SOUND_OUTPUT);
109 }
110
111 FilmViewer::~FilmViewer ()
112 {
113         stop ();
114 }
115
116 void
117 FilmViewer::set_film (shared_ptr<Film> film)
118 {
119         if (_film == film) {
120                 return;
121         }
122
123         _film = film;
124
125         _frame.reset ();
126         _closed_captions_dialog->clear ();
127
128         if (!_film) {
129                 _player.reset ();
130                 recreate_butler ();
131                 _frame.reset ();
132                 refresh_panel ();
133                 return;
134         }
135
136         try {
137                 _player.reset (new Player (_film, _film->playlist ()));
138                 _player->set_fast ();
139                 if (_dcp_decode_reduction) {
140                         _player->set_dcp_decode_reduction (_dcp_decode_reduction);
141                 }
142         } catch (bad_alloc) {
143                 error_dialog (_panel, _("There is not enough free memory to do that."));
144                 _film.reset ();
145                 return;
146         }
147
148         _player->set_always_burn_open_subtitles ();
149         _player->set_play_referenced ();
150
151         _film->Change.connect (boost::bind (&FilmViewer::film_change, this, _1, _2));
152         _player->Change.connect (boost::bind (&FilmViewer::player_change, this, _1, _2, _3));
153
154         /* Keep about 1 second's worth of history samples */
155         _latency_history_count = _film->audio_frame_rate() / _audio_block_size;
156
157         recreate_butler ();
158
159         calculate_sizes ();
160         slow_refresh ();
161 }
162
163 void
164 FilmViewer::recreate_butler ()
165 {
166         bool const was_running = stop ();
167         _butler.reset ();
168
169         if (!_film) {
170                 return;
171         }
172
173         AudioMapping map = AudioMapping (_film->audio_channels(), _audio_channels);
174
175         if (_audio_channels != 2 || _film->audio_channels() < 3) {
176                 for (int i = 0; i < min (_film->audio_channels(), _audio_channels); ++i) {
177                         map.set (i, i, 1);
178                 }
179         } else {
180                 /* Special case: stereo output, at least 3 channel input.
181                    Map so that Lt = L(-3dB) + Ls(-3dB) + C(-6dB) + Lfe(-10dB)
182                                Rt = R(-3dB) + Rs(-3dB) + C(-6dB) + Lfe(-10dB)
183                 */
184                 map.set (dcp::LEFT,   0, 1 / sqrt(2)); // L -> Lt
185                 map.set (dcp::RIGHT,  1, 1 / sqrt(2)); // R -> Rt
186                 map.set (dcp::CENTRE, 0, 1 / 2.0); // C -> Lt
187                 map.set (dcp::CENTRE, 1, 1 / 2.0); // C -> Rt
188                 map.set (dcp::LFE,    0, 1 / sqrt(10)); // Lfe -> Lt
189                 map.set (dcp::LFE,    1, 1 / sqrt(10)); // Lfe -> Rt
190                 map.set (dcp::LS,     0, 1 / sqrt(2)); // Ls -> Lt
191                 map.set (dcp::RS,     1, 1 / sqrt(2)); // Rs -> Rt
192         }
193
194         _butler.reset (new Butler(_player, map, _audio_channels, bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), false, true));
195         if (!Config::instance()->sound() && !_audio.isStreamOpen()) {
196                 _butler->disable_audio ();
197         }
198
199         _closed_captions_dialog->set_butler (_butler);
200
201         if (was_running) {
202                 start ();
203         }
204 }
205
206 void
207 FilmViewer::refresh_panel ()
208 {
209         _panel->Refresh ();
210         _panel->Update ();
211 }
212
213 void
214 FilmViewer::get ()
215 {
216         DCPOMATIC_ASSERT (_butler);
217
218         do {
219                 Butler::Error e;
220                 _player_video = _butler->get_video (&e);
221                 if (!_player_video.first && e == Butler::AGAIN) {
222                         signal_manager->when_idle (boost::bind(&FilmViewer::get, this));
223                         return;
224                 }
225         } while (
226                 _player_video.first &&
227                 _film->three_d() &&
228                 (_eyes != _player_video.first->eyes())
229                 );
230
231         _butler->rethrow ();
232
233         display_player_video ();
234 }
235
236 void
237 FilmViewer::display_player_video ()
238 {
239         if (!_player_video.first) {
240                 _frame.reset ();
241                 refresh_panel ();
242                 return;
243         }
244
245         if (_playing && (time() - _player_video.second) > one_video_frame()) {
246                 /* Too late; just drop this frame before we try to get its image (which will be the time-consuming
247                    part if this frame is J2K).
248                 */
249                 _video_position = _player_video.second;
250                 ++_dropped;
251                 return;
252         }
253
254         /* In an ideal world, what we would do here is:
255          *
256          * 1. convert to XYZ exactly as we do in the DCP creation path.
257          * 2. convert back to RGB for the preview display, compensating
258          *    for the monitor etc. etc.
259          *
260          * but this is inefficient if the source is RGB.  Since we don't
261          * (currently) care too much about the precise accuracy of the preview's
262          * colour mapping (and we care more about its speed) we try to short-
263          * circuit this "ideal" situation in some cases.
264          *
265          * The content's specified colour conversion indicates the colourspace
266          * which the content is in (according to the user).
267          *
268          * PlayerVideo::image (bound to PlayerVideo::force) will take the source
269          * image and convert it (from whatever the user has said it is) to RGB.
270          */
271
272         _frame = _player_video.first->image (bind(&PlayerVideo::force, _1, AV_PIX_FMT_RGB24), false, true);
273
274         ImageChanged (_player_video.first);
275
276         _video_position = _player_video.second;
277         _inter_position = _player_video.first->inter_position ();
278         _inter_size = _player_video.first->inter_size ();
279
280         refresh_panel ();
281
282         _closed_captions_dialog->update (time());
283 }
284
285 void
286 FilmViewer::timer ()
287 {
288         if (!_film || !_playing) {
289                 return;
290         }
291
292         get ();
293         PositionChanged ();
294         DCPTime const next = _video_position + one_video_frame();
295
296         if (next >= _film->length()) {
297                 stop ();
298         }
299
300         _timer.Start (max ((next.seconds() - time().seconds()) * 1000, 1.0), wxTIMER_ONE_SHOT);
301
302         if (_butler) {
303                 _butler->rethrow ();
304         }
305 }
306
307 bool
308 FilmViewer::maybe_draw_background_image (wxPaintDC& dc)
309 {
310 #ifdef DCPOMATIC_VARIANT_SWAROOP
311         optional<boost::filesystem::path> bg = Config::instance()->player_background_image();
312         if (bg) {
313                 wxImage image (std_to_wx(bg->string()));
314                 wxBitmap bitmap (image);
315                 dc.DrawBitmap (bitmap, max(0, (_panel_size.width - image.GetSize().GetWidth()) / 2), max(0, (_panel_size.height - image.GetSize().GetHeight()) / 2));
316                 return true;
317         }
318 #endif
319
320         return false;
321 }
322
323 void
324 FilmViewer::paint_panel ()
325 {
326         wxPaintDC dc (_panel);
327
328         if (!_frame || !_film || !_out_size.width || !_out_size.height || _out_size != _frame->size()) {
329                 dc.Clear ();
330                 maybe_draw_background_image (dc);
331                 return;
332         }
333
334         if (_video_position == DCPTime() && maybe_draw_background_image (dc)) {
335                 return;
336         }
337
338         wxImage frame (_out_size.width, _out_size.height, _frame->data()[0], true);
339         wxBitmap frame_bitmap (frame);
340         dc.DrawBitmap (frame_bitmap, 0, max(0, (_panel_size.height - _out_size.height) / 2));
341
342 #ifdef DCPOMATIC_VARIANT_SWAROOP
343         DCPTime const period = DCPTime::from_seconds(Config::instance()->player_watermark_period() * 60);
344         int64_t n = _video_position.get() / period.get();
345         DCPTime from(n * period.get());
346         DCPTime to = from + DCPTime::from_seconds(Config::instance()->player_watermark_duration() / 1000.0);
347         if (from <= _video_position && _video_position <= to) {
348                 if (!_in_watermark) {
349                         _in_watermark = true;
350                         _watermark_x = rand() % _panel_size.width;
351                         _watermark_y = rand() % _panel_size.height;
352                 }
353                 dc.SetTextForeground(*wxWHITE);
354                 string wm = Config::instance()->player_watermark_theatre();
355                 boost::posix_time::ptime t = boost::posix_time::second_clock::local_time();
356                 wm += "\n" + boost::posix_time::to_iso_extended_string(t);
357                 dc.DrawText(std_to_wx(wm), _watermark_x, _watermark_y);
358         } else {
359                 _in_watermark = false;
360         }
361 #endif
362
363         if (_out_size.width < _panel_size.width) {
364                 /* XXX: these colours are right for GNOME; may need adjusting for other OS */
365                 wxPen   p (_pad_black ? wxColour(0, 0, 0) : wxColour(240, 240, 240));
366                 wxBrush b (_pad_black ? wxColour(0, 0, 0) : wxColour(240, 240, 240));
367                 dc.SetPen (p);
368                 dc.SetBrush (b);
369                 dc.DrawRectangle (_out_size.width, 0, _panel_size.width - _out_size.width, _panel_size.height);
370         }
371
372         if (_out_size.height < _panel_size.height) {
373                 wxPen   p (_pad_black ? wxColour(0, 0, 0) : wxColour(240, 240, 240));
374                 wxBrush b (_pad_black ? wxColour(0, 0, 0) : wxColour(240, 240, 240));
375                 dc.SetPen (p);
376                 dc.SetBrush (b);
377                 int const gap = (_panel_size.height - _out_size.height) / 2;
378                 dc.DrawRectangle (0, 0, _panel_size.width, gap);
379                 dc.DrawRectangle (0, gap + _out_size.height + 1, _panel_size.width, gap);
380         }
381
382         if (_outline_content) {
383                 wxPen p (wxColour (255, 0, 0), 2);
384                 dc.SetPen (p);
385                 dc.SetBrush (*wxTRANSPARENT_BRUSH);
386                 dc.DrawRectangle (_inter_position.x, _inter_position.y + (_panel_size.height - _out_size.height) / 2, _inter_size.width, _inter_size.height);
387         }
388 }
389
390 void
391 FilmViewer::set_outline_content (bool o)
392 {
393         _outline_content = o;
394         refresh_panel ();
395 }
396
397 void
398 FilmViewer::set_eyes (Eyes e)
399 {
400         _eyes = e;
401         slow_refresh ();
402 }
403
404 void
405 FilmViewer::panel_sized (wxSizeEvent& ev)
406 {
407         _panel_size.width = ev.GetSize().GetWidth();
408         _panel_size.height = ev.GetSize().GetHeight();
409
410         calculate_sizes ();
411         if (!quick_refresh()) {
412                 slow_refresh ();
413         }
414         PositionChanged ();
415 }
416
417 void
418 FilmViewer::calculate_sizes ()
419 {
420         if (!_film || !_player) {
421                 return;
422         }
423
424         Ratio const * container = _film->container ();
425
426         float const panel_ratio = _panel_size.ratio ();
427         float const film_ratio = container ? container->ratio () : 1.78;
428
429         if (panel_ratio < film_ratio) {
430                 /* panel is less widscreen than the film; clamp width */
431                 _out_size.width = _panel_size.width;
432                 _out_size.height = lrintf (_out_size.width / film_ratio);
433         } else {
434                 /* panel is more widescreen than the film; clamp height */
435                 _out_size.height = _panel_size.height;
436                 _out_size.width = lrintf (_out_size.height * film_ratio);
437         }
438
439         /* Catch silly values */
440         _out_size.width = max (64, _out_size.width);
441         _out_size.height = max (64, _out_size.height);
442
443         _player->set_video_container_size (_out_size);
444 }
445
446 void
447 FilmViewer::start ()
448 {
449         if (!_film) {
450                 return;
451         }
452
453         optional<bool> v = PlaybackPermitted ();
454         if (v && !*v) {
455                 /* Computer says no */
456                 return;
457         }
458
459         if (_audio.isStreamOpen()) {
460                 _audio.setStreamTime (_video_position.seconds());
461                 _audio.startStream ();
462         }
463
464         _playing = true;
465         _dropped = 0;
466         timer ();
467         Started (position());
468 }
469
470 bool
471 FilmViewer::stop ()
472 {
473         if (_audio.isStreamRunning()) {
474                 /* stop stream and discard any remaining queued samples */
475                 _audio.abortStream ();
476         }
477
478         if (!_playing) {
479                 return false;
480         }
481
482         _playing = false;
483         Stopped (position());
484         return true;
485 }
486
487 void
488 FilmViewer::player_change (ChangeType type, int property, bool frequent)
489 {
490         if (type != CHANGE_TYPE_DONE || frequent) {
491                 return;
492         }
493
494         if (_coalesce_player_changes) {
495                 _pending_player_changes.push_back (property);
496                 return;
497         }
498
499         calculate_sizes ();
500         bool refreshed = false;
501         if (
502                 property == VideoContentProperty::CROP ||
503                 property == VideoContentProperty::SCALE ||
504                 property == VideoContentProperty::FADE_IN ||
505                 property == VideoContentProperty::FADE_OUT ||
506                 property == VideoContentProperty::COLOUR_CONVERSION ||
507                 property == PlayerProperty::VIDEO_CONTAINER_SIZE ||
508                 property == PlayerProperty::FILM_CONTAINER
509                 ) {
510                 refreshed = quick_refresh ();
511         }
512
513         if (!refreshed) {
514                 slow_refresh ();
515         }
516         PositionChanged ();
517 }
518
519 void
520 FilmViewer::film_change (ChangeType type, Film::Property p)
521 {
522         if (type == CHANGE_TYPE_DONE && p == Film::AUDIO_CHANNELS) {
523                 recreate_butler ();
524         }
525 }
526
527 /** Re-get the current frame slowly by seeking */
528 void
529 FilmViewer::slow_refresh ()
530 {
531         seek (_video_position, true);
532 }
533
534 /** Try to re-get the current frame quickly by resetting the metadata
535  *  in the PlayerVideo that we used last time.
536  *  @return true if this was possible, false if not.
537  */
538 bool
539 FilmViewer::quick_refresh ()
540 {
541         if (!_player_video.first) {
542                 return false;
543         }
544
545         if (!_player_video.first->reset_metadata (_film, _player->video_container_size(), _film->frame_size())) {
546                 return false;
547         }
548
549         display_player_video ();
550         return true;
551 }
552
553 void
554 FilmViewer::seek (shared_ptr<Content> content, ContentTime t, bool accurate)
555 {
556         optional<DCPTime> dt = _player->content_time_to_dcp (content, t);
557         if (dt) {
558                 seek (*dt, accurate);
559         }
560 }
561
562 void
563 FilmViewer::set_coalesce_player_changes (bool c)
564 {
565         _coalesce_player_changes = c;
566
567         if (!c) {
568                 BOOST_FOREACH (int i, _pending_player_changes) {
569                         player_change (CHANGE_TYPE_DONE, i, false);
570                 }
571                 _pending_player_changes.clear ();
572         }
573 }
574
575 void
576 FilmViewer::seek (DCPTime t, bool accurate)
577 {
578         if (!_butler) {
579                 return;
580         }
581
582         if (t < DCPTime ()) {
583                 t = DCPTime ();
584         }
585
586         if (t >= _film->length ()) {
587                 t = _film->length ();
588         }
589
590         bool const was_running = stop ();
591
592         _closed_captions_dialog->clear ();
593         _butler->seek (t, accurate);
594         get ();
595
596         if (was_running) {
597                 start ();
598         }
599
600         PositionChanged ();
601         Seeked (position());
602 }
603
604 void
605 FilmViewer::config_changed (Config::Property p)
606 {
607 #ifdef DCPOMATIC_VARIANT_SWAROOP
608         if (p == Config::PLAYER_BACKGROUND_IMAGE) {
609                 refresh_panel ();
610                 return;
611         }
612 #endif
613
614         if (p != Config::SOUND && p != Config::SOUND_OUTPUT) {
615                 return;
616         }
617
618         if (_audio.isStreamOpen ()) {
619                 _audio.closeStream ();
620         }
621
622         if (Config::instance()->sound() && _audio.getDeviceCount() > 0) {
623                 unsigned int st = 0;
624                 if (Config::instance()->sound_output()) {
625                         while (st < _audio.getDeviceCount()) {
626                                 if (_audio.getDeviceInfo(st).name == Config::instance()->sound_output().get()) {
627                                         break;
628                                 }
629                                 ++st;
630                         }
631                         if (st == _audio.getDeviceCount()) {
632                                 st = _audio.getDefaultOutputDevice();
633                         }
634                 } else {
635                         st = _audio.getDefaultOutputDevice();
636                 }
637
638                 _audio_channels = _audio.getDeviceInfo(st).outputChannels;
639                 cout << "RtAudio reports " << _audio_channels << " channels.\n";
640
641                 RtAudio::StreamParameters sp;
642                 sp.deviceId = st;
643                 sp.nChannels = _audio_channels;
644                 sp.firstChannel = 0;
645                 try {
646                         _audio.openStream (&sp, 0, RTAUDIO_FLOAT32, 48000, &_audio_block_size, &rtaudio_callback, this);
647 #ifdef DCPOMATIC_USE_RTERROR
648                 } catch (RtError& e) {
649 #else
650                 } catch (RtAudioError& e) {
651 #endif
652                         error_dialog (
653                                 _panel,
654                                 _("Could not set up audio output.  There will be no audio during the preview."), std_to_wx(e.what())
655                                 );
656                 }
657                 recreate_butler ();
658
659         } else {
660                 _audio_channels = 0;
661                 recreate_butler ();
662         }
663 }
664
665 DCPTime
666 FilmViewer::uncorrected_time () const
667 {
668         if (_audio.isStreamRunning ()) {
669                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime());
670         }
671
672         return _video_position;
673 }
674
675 DCPTime
676 FilmViewer::time () const
677 {
678         if (_audio.isStreamRunning ()) {
679                 return DCPTime::from_seconds (const_cast<RtAudio*>(&_audio)->getStreamTime ()) -
680                         DCPTime::from_frames (average_latency(), _film->audio_frame_rate());
681         }
682
683         return _video_position;
684 }
685
686 int
687 FilmViewer::audio_callback (void* out_p, unsigned int frames)
688 {
689         while (true) {
690                 optional<DCPTime> t = _butler->get_audio (reinterpret_cast<float*> (out_p), frames);
691                 if (!t || DCPTime(uncorrected_time() - *t) < one_video_frame()) {
692                         /* There was an underrun or this audio is on time; carry on */
693                         break;
694                 }
695                 /* The audio we just got was (very) late; drop it and get some more. */
696         }
697
698         boost::mutex::scoped_lock lm (_latency_history_mutex, boost::try_to_lock);
699         if (lm) {
700                 _latency_history.push_back (_audio.getStreamLatency ());
701                 if (_latency_history.size() > static_cast<size_t> (_latency_history_count)) {
702                         _latency_history.pop_front ();
703                 }
704         }
705
706         return 0;
707 }
708
709 Frame
710 FilmViewer::average_latency () const
711 {
712         boost::mutex::scoped_lock lm (_latency_history_mutex);
713         if (_latency_history.empty()) {
714                 return 0;
715         }
716
717         Frame total = 0;
718         BOOST_FOREACH (Frame i, _latency_history) {
719                 total += i;
720         }
721
722         return total / _latency_history.size();
723 }
724
725 void
726 FilmViewer::set_dcp_decode_reduction (optional<int> reduction)
727 {
728         _dcp_decode_reduction = reduction;
729         if (_player) {
730                 _player->set_dcp_decode_reduction (reduction);
731         }
732 }
733
734 optional<int>
735 FilmViewer::dcp_decode_reduction () const
736 {
737         return _dcp_decode_reduction;
738 }
739
740 DCPTime
741 FilmViewer::one_video_frame () const
742 {
743         return DCPTime::from_frames (1, _film->video_frame_rate());
744 }
745
746 /** Open a dialog box showing our film's closed captions */
747 void
748 FilmViewer::show_closed_captions ()
749 {
750         _closed_captions_dialog->Show();
751 }
752
753 void
754 FilmViewer::seek_by (DCPTime by, bool accurate)
755 {
756         seek (_video_position + by, accurate);
757 }
758
759 void
760 FilmViewer::set_pad_black (bool p)
761 {
762         _pad_black = p;
763 }