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