Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guide/media/media-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
30 changes: 29 additions & 1 deletion webrtc-media/src/main/cpp/include/media/MediaPlayer.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions webrtc-media/src/main/cpp/include/media/VideoDecoder.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
};
}

Expand Down
53 changes: 48 additions & 5 deletions webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include "media/AllocationFault.h"
#include "media/ErrorText.h"

#include <algorithm>
#include <chrono>
#include <utility>

Expand Down Expand Up @@ -422,7 +423,7 @@ namespace ffmpeg
}

if (video) {
return DecodeVideo() >= 0;
return DecodeVideo(false) >= 0;
}
if (audio) {
return DecodeAudio() >= 0;
Expand All @@ -435,15 +436,15 @@ namespace ffmpeg
{
if (has_video_) {
video_decoder_.SendPacket(nullptr);
DecodeVideo();
DecodeVideo(true);
}
if (has_audio_) {
audio_decoder_.SendPacket(nullptr);
DecodeAudio();
}
}

int MediaPlayer::DecodeVideo()
int MediaPlayer::DecodeVideo(bool at_end)
{
for (;;) {
AVFrame * frame = nullptr;
Expand All @@ -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;
}
Expand Down Expand Up @@ -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<int64_t>(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<int64_t>(from_us, 0);

video_decoder_.Flush();
audio_decoder_.Flush();

Expand All @@ -527,6 +568,8 @@ namespace ffmpeg
max_source_pts_us_ = position_us;

pacer_->Flush(position_us);

return 0;
}

void MediaPlayer::SetState(int state)
Expand Down
20 changes: 19 additions & 1 deletion webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -465,6 +476,8 @@ namespace ffmpeg
}
if (*frame == nullptr) {
// Dropped before it was read back and converted.
dropped_before_ = true;

continue;
}

Expand All @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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
Expand Down
Binary file not shown.
Loading