Another try at sorting out the thorny question of timing.
[dcpomatic.git] / src / lib / player.cc
index 5d4635e5a865b0a7334e5381f50f59f5aa873ddd..9969fbf9e163ab1d9428ffdace1a0911f435e805 100644 (file)
@@ -1,5 +1,3 @@
-/* -*- c-basic-offset: 8; default-tab-width: 8; -*- */
-
 /*
     Copyright (C) 2013 Carl Hetherington <cth@carlh.net>
 
@@ -19,6 +17,7 @@
 
 */
 
+#include <stdint.h>
 #include "player.h"
 #include "film.h"
 #include "ffmpeg_decoder.h"
 #include "playlist.h"
 #include "job.h"
 #include "image.h"
+#include "ratio.h"
+#include "resampler.h"
 
 using std::list;
 using std::cout;
 using std::min;
+using std::max;
 using std::vector;
+using std::pair;
+using std::map;
 using boost::shared_ptr;
 using boost::weak_ptr;
 using boost::dynamic_pointer_cast;
 
+#define DEBUG_PLAYER 1
+
+class Piece
+{
+public:
+       Piece (shared_ptr<Content> c)
+               : content (c)
+               , video_position (c->start ())
+               , audio_position (c->start ())
+       {}
+       
+       Piece (shared_ptr<Content> c, shared_ptr<Decoder> d)
+               : content (c)
+               , decoder (d)
+               , video_position (c->start ())
+               , audio_position (c->start ())
+       {}
+       
+       shared_ptr<Content> content;
+       shared_ptr<Decoder> decoder;
+       Time video_position;
+       Time audio_position;
+};
+
+#ifdef DEBUG_PLAYER
+std::ostream& operator<<(std::ostream& s, Piece const & p)
+{
+       if (dynamic_pointer_cast<FFmpegContent> (p.content)) {
+               s << "\tffmpeg     ";
+       } else if (dynamic_pointer_cast<ImageMagickContent> (p.content)) {
+               s << "\timagemagick";
+       } else if (dynamic_pointer_cast<SndfileContent> (p.content)) {
+               s << "\tsndfile    ";
+       }
+       
+       s << " at " << p.content->start() << " until " << p.content->end();
+       
+       return s;
+}
+#endif 
+
 Player::Player (shared_ptr<const Film> f, shared_ptr<const Playlist> p)
        : _film (f)
        , _playlist (p)
        , _video (true)
        , _audio (true)
-       , _subtitles (true)
-       , _have_valid_decoders (false)
-       , _position (0)
-       , _audio_buffers (MAX_AUDIO_CHANNELS, 0)
-       , _last_video (0)
-       , _last_was_black (false)
-       , _last_audio (0)
+       , _have_valid_pieces (false)
+       , _video_position (0)
+       , _audio_position (0)
+       , _audio_buffers (f->dcp_audio_channels(), 0)
 {
        _playlist->Changed.connect (bind (&Player::playlist_changed, this));
        _playlist->ContentChanged.connect (bind (&Player::content_changed, this, _1, _2));
+       set_video_container_size (_film->container()->size (_film->full_frame ()));
 }
 
 void
@@ -68,91 +111,194 @@ Player::disable_audio ()
        _audio = false;
 }
 
-void
-Player::disable_subtitles ()
-{
-       _subtitles = false;
-}
-
 bool
 Player::pass ()
 {
-       if (!_have_valid_decoders) {
-               setup_decoders ();
-               _have_valid_decoders = true;
+       if (!_have_valid_pieces) {
+               setup_pieces ();
+               _have_valid_pieces = true;
        }
 
-        /* Here we are just finding the active decoder with the earliest last emission time, then
-           calling pass on it.  If there is no decoder, we skip our position on until there is.
-           Hence this method will cause video and audio to be emitted, and it is up to the
-           process_{video,audio} methods to tidy it up.
-        */
+#ifdef DEBUG_PLAYER
+       cout << "= PASS\n";
+#endif 
 
-        Time earliest_pos = TIME_MAX;
-        shared_ptr<DecoderRecord> earliest;
-        Time next_wait = TIME_MAX;
-
-        for (list<shared_ptr<DecoderRecord> >::iterator i = _decoders.begin(); i != _decoders.end(); ++i) {
-                Time const ts = (*i)->content->time();
-                Time const te = (*i)->content->time() + (*i)->content->length (_film);
-                if (ts <= _position && te > _position) {
-                        Time const pos = ts + (*i)->last;
-                        if (pos < earliest_pos) {
-                                earliest_pos = pos;
-                                earliest = *i;
-                        }
-                }
+        Time earliest_t = TIME_MAX;
+        shared_ptr<Piece> earliest;
+       enum {
+               VIDEO,
+               AUDIO
+       } type = VIDEO;
 
-                if (ts > _position) {
-                        next_wait = min (next_wait, ts - _position);
-                }
-        }
+       for (list<shared_ptr<Piece> >::iterator i = _pieces.begin(); i != _pieces.end(); ++i) {
+               if ((*i)->decoder->done ()) {
+                       continue;
+               }
 
-        if (earliest) {
-                earliest->decoder->pass ();
-                _position = earliest->last;
-        } else if (next_wait < TIME_MAX) {
-                _position += next_wait;
-        } else {
-                return true;
-        }
+               if (dynamic_pointer_cast<VideoDecoder> ((*i)->decoder)) {
+                       if ((*i)->video_position < earliest_t) {
+                               earliest_t = (*i)->video_position;
+                               earliest = *i;
+                               type = VIDEO;
+                       }
+               }
+
+               if (dynamic_pointer_cast<AudioDecoder> ((*i)->decoder)) {
+                       if ((*i)->audio_position < earliest_t) {
+                               earliest_t = (*i)->audio_position;
+                               earliest = *i;
+                               type = AUDIO;
+                       }
+               }
+       }
+
+       if (!earliest) {
+#ifdef DEBUG_PLAYER
+               cout << "no earliest piece.\n";
+#endif         
+               
+               flush ();
+               return true;
+       }
+
+       switch (type) {
+       case VIDEO:
+               if (earliest_t > _video_position) {
+#ifdef DEBUG_PLAYER
+                       cout << "no video here; emitting black frame.\n";
+#endif
+                       emit_black ();
+               } else {
+#ifdef DEBUG_PLAYER
+                       cout << "Pass " << *earliest << "\n";
+#endif                 
+                       earliest->decoder->pass ();
+               }
+               break;
+
+       case AUDIO:
+               if (earliest_t > _audio_position) {
+#ifdef DEBUG_PLAYER
+                       cout << "no audio here; emitting silence.\n";
+#endif
+                       emit_silence (_film->time_to_audio_frames (earliest_t - _audio_position));
+               } else {
+#ifdef DEBUG_PLAYER
+                       cout << "Pass " << *earliest << "\n";
+#endif                 
+                       earliest->decoder->pass ();
+               }
+               break;
+       }
+
+#ifdef DEBUG_PLAYER
+       cout << "\tpost pass " << _video_position << " " << _audio_position << "\n";
+#endif 
 
         return false;
 }
 
 void
-Player::process_video (shared_ptr<DecoderRecord> dr, shared_ptr<const Image> image, bool same, shared_ptr<Subtitle> sub, Time time)
+Player::process_video (weak_ptr<Piece> weak_piece, shared_ptr<const Image> image, bool same, VideoContent::Frame frame)
 {
-        shared_ptr<VideoDecoder> vd = dynamic_pointer_cast<VideoDecoder> (dr->decoder);
-        
-        Time const global_time = dr->content->time() + time;
-        while ((global_time - _last_video) > 1) {
-                /* Fill in with black */
-                emit_black_frame ();
-        }
+       shared_ptr<Piece> piece = weak_piece.lock ();
+       if (!piece) {
+               return;
+       }
+
+       shared_ptr<VideoContent> content = dynamic_pointer_cast<VideoContent> (piece->content);
+       assert (content);
+
+       FrameRateConversion frc (content->video_frame_rate(), _film->dcp_video_frame_rate());
+       if (frc.skip && (frame % 2) == 1) {
+               return;
+       }
+
+       image = image->crop (content->crop(), true);
+
+       libdcp::Size const image_size = content->ratio()->size (_video_container_size);
+       
+       image = image->scale_and_convert_to_rgb (image_size, _film->scaler(), true);
+
+#if 0  
+       if (film->with_subtitles ()) {
+               shared_ptr<Subtitle> sub;
+               if (_timed_subtitle && _timed_subtitle->displayed_at (t)) {
+                       sub = _timed_subtitle->subtitle ();
+               }
+               
+               if (sub) {
+                       dcpomatic::Rect const tx = subtitle_transformed_area (
+                               float (image_size.width) / content->video_size().width,
+                               float (image_size.height) / content->video_size().height,
+                               sub->area(), film->subtitle_offset(), film->subtitle_scale()
+                               );
+                       
+                       shared_ptr<Image> im = sub->image()->scale (tx.size(), film->scaler(), true);
+                       image->alpha_blend (im, tx.position());
+               }
+       }
+#endif 
+
+       if (image_size != _video_container_size) {
+               assert (image_size.width <= _video_container_size.width);
+               assert (image_size.height <= _video_container_size.height);
+               shared_ptr<Image> im (new SimpleImage (PIX_FMT_RGB24, _video_container_size, true));
+               im->make_black ();
+               im->copy (image, Position ((_video_container_size.width - image_size.width) / 2, (_video_container_size.height - image_size.height) / 2));
+               image = im;
+       }
+
+       Time time = content->start() + (frame * frc.factor() * TIME_HZ / _film->dcp_video_frame_rate());
+       
+        Video (image, same, time);
+       time += TIME_HZ / _film->dcp_video_frame_rate();
+
+       if (frc.repeat) {
+               Video (image, true, time);
+               time += TIME_HZ / _film->dcp_video_frame_rate();
+       }
 
-        Video (image, same, sub, global_time);
-        dr->last = time;
-       _last_video = global_time;
-       _last_was_black = false;
+       _video_position = piece->video_position = time;
 }
 
 void
-Player::process_audio (shared_ptr<DecoderRecord> dr, shared_ptr<const AudioBuffers> audio, Time time)
+Player::process_audio (weak_ptr<Piece> weak_piece, shared_ptr<const AudioBuffers> audio, AudioContent::Frame frame)
 {
-        /* XXX: mapping */
+       shared_ptr<Piece> piece = weak_piece.lock ();
+       if (!piece) {
+               return;
+       }
+
+       shared_ptr<AudioContent> content = dynamic_pointer_cast<AudioContent> (piece->content);
+       assert (content);
+
+       if (content->content_audio_frame_rate() != content->output_audio_frame_rate()) {
+               audio = resampler(content)->run (audio);
+       }
+
+       /* Remap channels */
+       shared_ptr<AudioBuffers> dcp_mapped (new AudioBuffers (_film->dcp_audio_channels(), audio->frames()));
+       dcp_mapped->make_silent ();
+       list<pair<int, libdcp::Channel> > map = content->audio_mapping().content_to_dcp ();
+       for (list<pair<int, libdcp::Channel> >::iterator i = map.begin(); i != map.end(); ++i) {
+               dcp_mapped->accumulate_channel (audio.get(), i->first, i->second);
+       }
 
         /* The time of this audio may indicate that some of our buffered audio is not going to
            be added to any more, so it can be emitted.
         */
 
-        if (time > _last_audio) {
+       Time const time = content->start() + (frame * TIME_HZ / _film->dcp_audio_frame_rate());
+
+        if (time > _audio_position) {
                 /* We can emit some audio from our buffers */
-                OutputAudioFrame const N = min (_film->time_to_audio_frames (time - _last_audio), static_cast<OutputAudioFrame> (_audio_buffers.frames()));
+                OutputAudioFrame const N = _film->time_to_audio_frames (time - _audio_position);
+               assert (N <= _audio_buffers.frames());
                 shared_ptr<AudioBuffers> emit (new AudioBuffers (_audio_buffers.channels(), N));
                 emit->copy_from (&_audio_buffers, N, 0, 0);
-                Audio (emit, _last_audio);
-                _last_audio += _film->audio_frames_to_time (N);
+                Audio (emit, _audio_position);
+                _audio_position = piece->audio_position = time + _film->audio_frames_to_time (N);
 
                 /* And remove it from our buffers */
                 if (_audio_buffers.frames() > N) {
@@ -162,76 +308,94 @@ Player::process_audio (shared_ptr<DecoderRecord> dr, shared_ptr<const AudioBuffe
         }
 
         /* Now accumulate the new audio into our buffers */
+        _audio_buffers.ensure_size (_audio_buffers.frames() + audio->frames());
+        _audio_buffers.accumulate_frames (audio.get(), 0, 0, audio->frames ());
+       _audio_buffers.set_frames (_audio_buffers.frames() + audio->frames());
+}
 
-        if (_audio_buffers.frames() == 0) {
-                /* We have no remaining data.  Emit silence up to the start of this new data */
-                if ((time - _last_audio) > 0) {
-                        emit_silence (time - _last_audio);
-                }
-        }
+void
+Player::flush ()
+{
+       if (_audio_buffers.frames() > 0) {
+               shared_ptr<AudioBuffers> emit (new AudioBuffers (_audio_buffers.channels(), _audio_buffers.frames()));
+               emit->copy_from (&_audio_buffers, _audio_buffers.frames(), 0, 0);
+               Audio (emit, _audio_position);
+               _audio_position += _film->audio_frames_to_time (_audio_buffers.frames ());
+               _audio_buffers.set_frames (0);
+       }
 
-        _audio_buffers.ensure_size (time - _last_audio + audio->frames());
-        _audio_buffers.accumulate (audio.get(), 0, _film->time_to_audio_frames (time - _last_audio));
-        dr->last = time + _film->audio_frames_to_time (audio->frames ());
+       while (_video_position < _audio_position) {
+               emit_black ();
+       }
+
+       while (_audio_position < _video_position) {
+               emit_silence (_film->time_to_audio_frames (_video_position - _audio_position));
+       }
+       
 }
 
 /** @return true on error */
-bool
+void
 Player::seek (Time t)
 {
-       if (!_have_valid_decoders) {
-               setup_decoders ();
-               _have_valid_decoders = true;
+       if (!_have_valid_pieces) {
+               setup_pieces ();
+               _have_valid_pieces = true;
        }
 
-       if (_decoders.empty ()) {
-               return true;
+       if (_pieces.empty ()) {
+               return;
        }
 
-       /* XXX */
+       for (list<shared_ptr<Piece> >::iterator i = _pieces.begin(); i != _pieces.end(); ++i) {
+               shared_ptr<VideoContent> vc = dynamic_pointer_cast<VideoContent> ((*i)->content);
+               if (!vc) {
+                       continue;
+               }
+               
+               Time s = t - vc->start ();
+               s = max (static_cast<Time> (0), s);
+               s = min (vc->length(), s);
+
+               FrameRateConversion frc (vc->video_frame_rate(), _film->dcp_video_frame_rate());
+               VideoContent::Frame f = s * _film->dcp_video_frame_rate() / (frc.factor() * TIME_HZ);
+               dynamic_pointer_cast<VideoDecoder>((*i)->decoder)->seek (f);
+       }
 
        /* XXX: don't seek audio because we don't need to... */
-
-       return false;
 }
 
 
 void
 Player::seek_back ()
 {
-       /* XXX */
-}
 
-void
-Player::seek_forward ()
-{
-       /* XXX */
 }
 
-
 void
-Player::setup_decoders ()
+Player::setup_pieces ()
 {
-       list<shared_ptr<DecoderRecord> > old_decoders = _decoders;
+       list<shared_ptr<Piece> > old_pieces = _pieces;
 
-       _decoders.clear ();
+       _pieces.clear ();
 
        Playlist::ContentList content = _playlist->content ();
+       sort (content.begin(), content.end(), ContentSorter ());
+       
        for (Playlist::ContentList::iterator i = content.begin(); i != content.end(); ++i) {
 
-               shared_ptr<DecoderRecord> dr (new DecoderRecord);
-               dr->content = *i;
-               
+               shared_ptr<Piece> piece (new Piece (*i));
+
                 /* XXX: into content? */
 
                shared_ptr<const FFmpegContent> fc = dynamic_pointer_cast<const FFmpegContent> (*i);
                if (fc) {
-                       shared_ptr<FFmpegDecoder> fd (new FFmpegDecoder (_film, fc, _video, _audio, _subtitles));
+                       shared_ptr<FFmpegDecoder> fd (new FFmpegDecoder (_film, fc, _video, _audio));
                        
-                       fd->Video.connect (bind (&Player::process_video, this, dr, _1, _2, _3, _4));
-                       fd->Audio.connect (bind (&Player::process_audio, this, dr, _1, _2));
+                       fd->Video.connect (bind (&Player::process_video, this, piece, _1, _2, _3));
+                       fd->Audio.connect (bind (&Player::process_audio, this, piece, _1, _2));
 
-                       dr->decoder = fd;
+                       piece->decoder = fd;
                }
                
                shared_ptr<const ImageMagickContent> ic = dynamic_pointer_cast<const ImageMagickContent> (*i);
@@ -239,8 +403,8 @@ Player::setup_decoders ()
                        shared_ptr<ImageMagickDecoder> id;
                        
                        /* See if we can re-use an old ImageMagickDecoder */
-                       for (list<shared_ptr<DecoderRecord> >::const_iterator i = old_decoders.begin(); i != old_decoders.end(); ++i) {
-                               shared_ptr<ImageMagickDecoder> imd = dynamic_pointer_cast<ImageMagickDecoder> ((*i)->decoder);
+                       for (list<shared_ptr<Piece> >::const_iterator j = old_pieces.begin(); j != old_pieces.end(); ++j) {
+                               shared_ptr<ImageMagickDecoder> imd = dynamic_pointer_cast<ImageMagickDecoder> ((*j)->decoder);
                                if (imd && imd->content() == ic) {
                                        id = imd;
                                }
@@ -248,24 +412,29 @@ Player::setup_decoders ()
 
                        if (!id) {
                                id.reset (new ImageMagickDecoder (_film, ic));
-                               id->Video.connect (bind (&Player::process_video, this, dr, _1, _2, _3, _4));
+                               id->Video.connect (bind (&Player::process_video, this, piece, _1, _2, _3));
                        }
 
-                       dr->decoder = id;
+                       piece->decoder = id;
                }
 
                shared_ptr<const SndfileContent> sc = dynamic_pointer_cast<const SndfileContent> (*i);
                if (sc) {
                        shared_ptr<AudioDecoder> sd (new SndfileDecoder (_film, sc));
-                       sd->Audio.connect (bind (&Player::process_audio, this, dr, _1, _2));
+                       sd->Audio.connect (bind (&Player::process_audio, this, piece, _1, _2));
 
-                       dr->decoder = sd;
+                       piece->decoder = sd;
                }
 
-               _decoders.push_back (dr);
+               _pieces.push_back (piece);
        }
 
-       _position = 0;
+#ifdef DEBUG_PLAYER
+       cout << "=== Player setup:\n";
+       for (list<shared_ptr<Piece> >::iterator i = _pieces.begin(); i != _pieces.end(); ++i) {
+               cout << *(i->get()) << "\n";
+       }
+#endif 
 }
 
 void
@@ -276,36 +445,55 @@ Player::content_changed (weak_ptr<Content> w, int p)
                return;
        }
 
-       if (p == VideoContentProperty::VIDEO_LENGTH) {
-               _have_valid_decoders = false;
+       if (p == ContentProperty::START || p == ContentProperty::LENGTH) {
+               _have_valid_pieces = false;
        }
 }
 
 void
 Player::playlist_changed ()
 {
-       _have_valid_decoders = false;
+       _have_valid_pieces = false;
 }
 
 void
-Player::emit_black_frame ()
+Player::set_video_container_size (libdcp::Size s)
 {
-       shared_ptr<SimpleImage> image (new SimpleImage (AV_PIX_FMT_RGB24, libdcp::Size (128, 128), true));
-       Video (image, _last_was_black, shared_ptr<Subtitle> (), _last_video);
-       _last_video += _film->video_frames_to_time (1);
+       _video_container_size = s;
+       _black_frame.reset (new SimpleImage (PIX_FMT_RGB24, _video_container_size, true));
+       _black_frame->make_black ();
 }
 
-void
-Player::emit_silence (Time t)
+shared_ptr<Resampler>
+Player::resampler (shared_ptr<AudioContent> c)
 {
-       OutputAudioFrame frames = _film->time_to_audio_frames (t);
-       while (frames) {
-               /* Do this in half-second chunks so we don't overwhelm anybody */
-               OutputAudioFrame this_time = min (_film->dcp_audio_frame_rate() / 2, frames);
-               shared_ptr<AudioBuffers> silence (new AudioBuffers (MAX_AUDIO_CHANNELS, this_time));
-               silence->make_silent ();
-               Audio (silence, _last_audio);
-               _last_audio += _film->audio_frames_to_time (this_time);
-               frames -= this_time;
+       map<shared_ptr<AudioContent>, shared_ptr<Resampler> >::iterator i = _resamplers.find (c);
+       if (i != _resamplers.end ()) {
+               return i->second;
        }
+       
+       shared_ptr<Resampler> r (new Resampler (c->content_audio_frame_rate(), c->output_audio_frame_rate(), c->audio_channels()));
+       _resamplers[c] = r;
+       return r;
+}
+
+void
+Player::emit_black ()
+{
+       /* XXX: use same here */
+       Video (_black_frame, false, _video_position);
+       _video_position += _film->video_frames_to_time (1);
 }
+
+void
+Player::emit_silence (OutputAudioFrame most)
+{
+       OutputAudioFrame N = min (most, _film->dcp_audio_frame_rate() / 2);
+       shared_ptr<AudioBuffers> silence (new AudioBuffers (_film->dcp_audio_channels(), N));
+       silence->make_silent ();
+       Audio (silence, _audio_position);
+       _audio_position += _film->audio_frames_to_time (N);
+}
+
+       
+