diff --git a/docs/guide/media/media-files.md b/docs/guide/media/media-files.md index 573510842..891ca90c2 100644 --- a/docs/guide/media/media-files.md +++ b/docs/guide/media/media-files.md @@ -144,7 +144,7 @@ source.getState(); // IDLE, PLAYING, PAUSED, ENDED or CLOSED Looping keeps the timing across the seam, so a looping file works as a stand-in for a camera that never stops. A looping source never reports an end of stream. -A seek starts playback at the position asked for. The decoder has to go back to the keyframe at or before it to produce a picture at all, so the frames from there up to the position are decoded and dropped, and the audio is cut at it. How long a seek takes therefore depends on how often the media was encoded with keyframes. +A seek starts playback at the position asked for. The decoder has to go back to the keyframe at or before it to produce a picture at all, so the frames from there up to the position are decoded and dropped, and the audio is cut at it. How long a seek takes therefore depends on how often the media was encoded with keyframes, not on how long the media is: MKV and MP4 have an index that takes the reader straight to that keyframe. MPEG-TS has none, and a search for the position by its timestamps can land past the keyframe before it. The player then searches again further back, a second before the position, then two, four and so on, so that the seek still starts at the position. ## Following Playback diff --git a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h index 3c6d29e14..ea0128b0b 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h @@ -125,10 +125,25 @@ namespace ffmpeg // of a stream and a loop both need. void DrainDecoders(); - int DecodeVideo(); + // Takes the decoded video and hands it to the pacer. At the end + // of the stream a seek that landed too late is not retried: the + // source is about to end or start over, and that would be lost. + int DecodeVideo(bool at_end); int DecodeAudio(); void PerformSeek(int64_t position_us); + + // Moves the reader to the given time and starts decoding from + // there towards the position of the seek being carried out. + // Returns 0 or a negative AVERROR. + int SeekReader(int64_t from_us); + + // Seeks again further back, after the video decoded since a seek + // started past its position: the reader landed past the keyframe + // before it. Returns whether it did; there is nothing further back + // to try once the reader would land where it did already, or the + // distance has grown past kMaxSeekBackUs. + bool SeekFurtherBack(); void SetState(int state); // Records the state, with the lock held. Returns whether it @@ -165,6 +180,19 @@ namespace ffmpeg bool seek_pending_ = false; int64_t seek_position_us_ = 0; + // How far before the position a seek that landed too late looks + // next, doubling each time, and how far at most: past that, a + // stream whose keyframes are this far apart starts at the next + // one, as a reader without an index would leave it. + static constexpr int64_t kFirstSeekBackUs = 1000000; + static constexpr int64_t kMaxSeekBackUs = 64000000; + + // The seek being carried out, on the decode thread: its position, + // how far before it the reader was last sent, and where to. + int64_t seek_target_us_ = 0; + int64_t seek_back_us_ = 0; + int64_t seek_from_us_ = 0; + // Set once the source has run out and everything queued has been // delivered, so that the thread stops pumping until something // asks it to start again. diff --git a/webrtc-media/src/main/cpp/include/media/VideoDecoder.h b/webrtc-media/src/main/cpp/include/media/VideoDecoder.h index 45288f6fa..d6142a003 100644 --- a/webrtc-media/src/main/cpp/include/media/VideoDecoder.h +++ b/webrtc-media/src/main/cpp/include/media/VideoDecoder.h @@ -80,6 +80,14 @@ namespace ffmpeg // the first frame that reaches it. void DiscardBefore(int64_t timestamp_us); + // Whether the first frame since DiscardBefore lay past its + // position with none before it to drop: the seek landed past the + // keyframe before the position, and the decoder had nothing to + // show until the next one. A container without an index, such as + // MPEG-TS, is searched by timestamp and can land that way. + // Reported once, by the call after that frame was taken. + bool LandedPastPosition(); + // Hands a packet to the decoder, or null to start draining at the // end of the stream. Returns 0 or a negative AVERROR. int SendPacket(const AVPacket * packet); @@ -212,6 +220,11 @@ namespace ffmpeg // Where the frames after a seek are to start. int64_t discard_before_us_ = 0; bool discarding_ = false; + + // Whether a frame before that position has been dropped, and + // whether the first frame then came past it without one. + bool dropped_before_ = false; + bool landed_past_ = false; }; } diff --git a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp index b90be950a..1df87f794 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp @@ -18,6 +18,7 @@ #include "media/AllocationFault.h" #include "media/ErrorText.h" +#include #include #include @@ -422,7 +423,7 @@ namespace ffmpeg } if (video) { - return DecodeVideo() >= 0; + return DecodeVideo(false) >= 0; } if (audio) { return DecodeAudio() >= 0; @@ -435,7 +436,7 @@ namespace ffmpeg { if (has_video_) { video_decoder_.SendPacket(nullptr); - DecodeVideo(); + DecodeVideo(true); } if (has_audio_) { audio_decoder_.SendPacket(nullptr); @@ -443,7 +444,7 @@ namespace ffmpeg } } - int MediaPlayer::DecodeVideo() + int MediaPlayer::DecodeVideo(bool at_end) { for (;;) { AVFrame * frame = nullptr; @@ -460,6 +461,14 @@ namespace ffmpeg return result; } + if (!at_end && video_decoder_.LandedPastPosition() && SeekFurtherBack()) { + // From a later keyframe than the one the seek needs; decoding + // starts again from an earlier one. + av_frame_free(&frame); + + return 0; + } + if (timestamp_us > max_source_pts_us_) { max_source_pts_us_ = timestamp_us; } @@ -502,14 +511,46 @@ namespace ffmpeg void MediaPlayer::PerformSeek(int64_t position_us) { - int result = reader_->Seek(position_us); + seek_target_us_ = position_us; + seek_back_us_ = 0; + + int result = SeekReader(position_us); if (result < 0) { ReportError("Seeking failed", result); + } + } - return; + bool MediaPlayer::SeekFurtherBack() + { + const int64_t back = seek_back_us_ == 0 ? kFirstSeekBackUs : seek_back_us_ * 2; + const int64_t from = std::max(seek_target_us_ - back, 0); + + // Before the start the reader lands where it did, at the first + // picture, which is the one to play. + if (back > kMaxSeekBackUs || from >= seek_from_us_) { + return false; } + seek_back_us_ = back; + + // Where it failed, the reader stays where it was, and the frame that + // came too late is played after all. + return SeekReader(from) >= 0; + } + + int MediaPlayer::SeekReader(int64_t from_us) + { + const int64_t position_us = seek_target_us_; + + int result = reader_->Seek(from_us); + + if (result < 0) { + return result; + } + + seek_from_us_ = std::max(from_us, 0); + video_decoder_.Flush(); audio_decoder_.Flush(); @@ -527,6 +568,8 @@ namespace ffmpeg max_source_pts_us_ = position_us; pacer_->Flush(position_us); + + return 0; } void MediaPlayer::SetState(int state) diff --git a/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp b/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp index 858ec156c..e42898745 100644 --- a/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp +++ b/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp @@ -366,6 +366,17 @@ namespace ffmpeg { discard_before_us_ = timestamp_us; discarding_ = true; + dropped_before_ = false; + landed_past_ = false; + } + + bool VideoDecoder::LandedPastPosition() + { + const bool landed_past = landed_past_; + + landed_past_ = false; + + return landed_past; } bool VideoDecoder::IsHardwareFailure(int result) const @@ -465,6 +476,8 @@ namespace ffmpeg } if (*frame == nullptr) { // Dropped before it was read back and converted. + dropped_before_ = true; + continue; } @@ -473,10 +486,15 @@ namespace ffmpeg // probation, which only a picture made in full can end. av_frame_free(frame); + dropped_before_ = true; + continue; } - discarding_ = false; + if (discarding_) { + landed_past_ = !dropped_before_ && *timestamp_us > discard_before_us_; + discarding_ = false; + } return 0; } diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java index 7419abf8b..cddbef903 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java @@ -80,6 +80,16 @@ class MediaPlayerTest { /** 3.008 seconds at 15 frames a second. */ private static final int EXPECTED_FRAMES = 45; + /** + * 320x240 H.264 at 15 fps, ten seconds, in MPEG-TS, with a key frame every + * four seconds, at 0.133, 4.133 and 8.133 s: two B-frames put the first + * picture 0.133 s in. MPEG-TS has no index, so FFmpeg seeks in it by + * searching for a timestamp, which can land past the key frame before the + * position. Made with libx264 (veryfast, CRF 42, keyint 60, no scene cuts, + * two B-frames) from a moving gradient. + */ + private static final String TS_ASSET = "/media-test-h264.ts"; + /** 3.008 seconds in chunks of 10 ms. */ private static final int EXPECTED_CHUNKS = 300; @@ -325,6 +335,47 @@ void seekCutsTheAudioFrameItFallsIn() throws Exception { } } + @Test + void seekWithoutIndexStartsAtThePositionAskedFor() throws Exception { + try (Playback playback = new Playback(new MediaReader( + Paths.get(MediaPlayerTest.class.getResource(TS_ASSET).toURI())))) { + // Just before the key frame at 8.133 s. A search for 7.8 s lands + // past the one at 4.133 s, and the decoder has nothing to show + // until 8.133 s, so the player has to look further back. + playback.player.seek(7_800_000); + playback.player.play(); + + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + + // The picture at 7.8 s is the 116th, 0.133 s + 115 / 15 s in. + long first = playback.firstFramePositionUs.get(); + + assertTrue(first >= 7_800_000 && first < 7_800_000 + 1_000_000 / 15, + "first frame at " + first + " us"); + + // 7.8 s to the end: the last 35 of the 150 pictures. + assertTrue(Math.abs(playback.frames.get() - 35) <= 1, + "video frames: " + playback.frames.get()); + } + } + + @Test + void seekWithoutIndexToItsStartPlaysItAll() throws Exception { + try (Playback playback = new Playback(new MediaReader( + Paths.get(MediaPlayerTest.class.getResource(TS_ASSET).toURI())))) { + // Before the first picture, which is 0.133 s in: there is nothing + // further back to look for, and the player starts at that picture. + playback.player.seek(0); + playback.player.play(); + + assertTrue(playback.ended.await(20, TimeUnit.SECONDS), "no end of stream"); + + assertEquals(133_333, playback.firstFramePositionUs.get(), 1); + assertTrue(Math.abs(playback.frames.get() - 150) <= 1, + "video frames: " + playback.frames.get()); + } + } + @Test void seekNearTheEndIsNotLost() throws Exception { // Two seconds of video only. All of it is decoded and queued within diff --git a/webrtc-media/src/test/resources/media-test-h264.ts b/webrtc-media/src/test/resources/media-test-h264.ts new file mode 100644 index 000000000..d10f5c344 Binary files /dev/null and b/webrtc-media/src/test/resources/media-test-h264.ts differ