Skip to content

Commit 3d8254f

Browse files
authored
fix: start playback after a seek at the position asked for (#493)
* fix: start playback after a seek at the position asked for The reader lands on the keyframe before the position. The player now decodes from there, drops the video before the position and cuts the audio frame it falls in. * perf: drop the frames before a seek's position before converting them The video decoder drops them as they come out of the codec, so a frame decoded in hardware is not read back and none goes through swscale. While the hardware is on probation they are converted all the same, since only a full picture ends it.
1 parent 9810791 commit 3d8254f

9 files changed

Lines changed: 191 additions & 13 deletions

File tree

‎docs/guide/media/media-files.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ source.getState(); // IDLE, PLAYING, PAUSED, ENDED or CLOSED
144144

145145
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.
146146

147-
A seek lands on the keyframe at or before the position asked for, which is how far back the decoder has to go to produce a picture at all. How close that is to the position asked for depends on how often the media was encoded with keyframes.
147+
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.
148148

149149
## Following Playback
150150

‎webrtc-media/src/main/cpp/include/media/AudioDecoder.h‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,17 @@ namespace ffmpeg
7272
void Close();
7373

7474
// Drops the decoder's state and the partial chunk being gathered,
75-
// which is what a seek needs.
75+
// which is what a seek needs. Forgets a position set with
76+
// DiscardBefore.
7677
void Flush();
7778

79+
// Makes the audio after a flush start at the given time on the
80+
// source's timeline. A seek lands on a keyframe before it, and the
81+
// audio decoded from there up to the position asked for is
82+
// dropped: frames that end before it entirely, and the start of
83+
// the frame it falls in, so the first chunk starts at it.
84+
void DiscardBefore(int64_t timestamp_us);
85+
7886
// Hands a packet to the decoder, or null to start draining at the
7987
// end of the stream. Returns 0 or a negative AVERROR.
8088
int SendPacket(const AVPacket * packet);
@@ -142,6 +150,12 @@ namespace ffmpeg
142150
int64_t next_timestamp_us_ = 0;
143151
bool have_timestamp_ = false;
144152

153+
// Where the audio after a seek is to start. Only acted on while
154+
// there is no timestamp yet, which is up to the first frame that
155+
// reaches it.
156+
int64_t discard_before_us_ = 0;
157+
bool discarding_ = false;
158+
145159
// Set once the resampler has been drained at the end of the
146160
// stream, so that it is drained once and not on every call.
147161
bool resampler_drained_ = false;

‎webrtc-media/src/main/cpp/include/media/MediaPlayer.h‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,8 @@ namespace ffmpeg
9090
void Pause();
9191

9292
// Moves playback to the given position, in microseconds from the
93-
// start. What is already queued is dropped.
93+
// start. What is already queued is dropped, and what is decoded
94+
// between the keyframe the seek lands on and the position as well.
9495
void Seek(int64_t position_us);
9596

9697
void SetLooping(bool looping);

‎webrtc-media/src/main/cpp/include/media/VideoDecoder.h‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,16 @@ namespace ffmpeg
7070

7171
// Drops everything the decoder holds, which is what a seek needs:
7272
// the frames in flight belong to the position that was left.
73+
// Forgets a position set with DiscardBefore.
7374
void Flush();
7475

76+
// Makes the frames after a flush start at the given time on the
77+
// source's timeline. A seek lands on a keyframe before it, and
78+
// the frames from there up to it are decoded and dropped, before
79+
// they are read back from the hardware and converted. Ends with
80+
// the first frame that reaches it.
81+
void DiscardBefore(int64_t timestamp_us);
82+
7583
// Hands a packet to the decoder, or null to start draining at the
7684
// end of the stream. Returns 0 or a negative AVERROR.
7785
int SendPacket(const AVPacket * packet);
@@ -114,9 +122,15 @@ namespace ffmpeg
114122
static AVPixelFormat ChooseFormat(AVCodecContext * context, const AVPixelFormat * formats);
115123

116124
// The next picture of the codec, in I420, hardware frames brought
117-
// into system memory first.
125+
// into system memory first, passing over those before the
126+
// position set with DiscardBefore.
118127
int ReceiveFromCodec(AVFrame ** frame, int64_t * timestamp_us);
119128

129+
// One picture of the codec, as ReceiveFromCodec takes them. Leaves
130+
// the frame null, and returns 0, for one it dropped before reading
131+
// it back and converting it.
132+
int ReceivePicture(AVFrame ** frame, int64_t * timestamp_us);
133+
120134
// Whether a result of the hardware decoder means that it failed.
121135
// A stream that cannot be decoded, which is how corrupt data shows,
122136
// fails a software decoder as well and says nothing of the
@@ -194,6 +208,10 @@ namespace ffmpeg
194208
bool awaiting_key_frame_ = false;
195209
size_t skipped_ = 0;
196210
std::deque<Pending> pending_;
211+
212+
// Where the frames after a seek are to start.
213+
int64_t discard_before_us_ = 0;
214+
bool discarding_ = false;
197215
};
198216
}
199217

‎webrtc-media/src/main/cpp/src/media/AudioDecoder.cpp‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ namespace ffmpeg
121121
channels_ = 0;
122122
next_timestamp_us_ = 0;
123123
have_timestamp_ = false;
124+
discarding_ = false;
124125
resampler_drained_ = false;
125126
}
126127

@@ -141,6 +142,13 @@ namespace ffmpeg
141142

142143
// The next frame decoded tells where the audio now starts.
143144
have_timestamp_ = false;
145+
discarding_ = false;
146+
}
147+
148+
void AudioDecoder::DiscardBefore(int64_t timestamp_us)
149+
{
150+
discard_before_us_ = timestamp_us;
151+
discarding_ = true;
144152
}
145153

146154
int AudioDecoder::SendPacket(const AVPacket * packet)
@@ -232,8 +240,28 @@ namespace ffmpeg
232240
int skip = 0;
233241

234242
if (!have_timestamp_) {
235-
next_timestamp_us_ = pts != AV_NOPTS_VALUE
243+
int64_t start_us = pts != AV_NOPTS_VALUE
236244
? av_rescale_q(pts, time_base_, AV_TIME_BASE_Q) : 0;
245+
246+
// A frame without a timestamp cannot be placed against the
247+
// position, and is taken to start there.
248+
if (discarding_ && pts != AV_NOPTS_VALUE) {
249+
const int64_t cut = av_rescale(discard_before_us_ - start_us,
250+
in_rate_, AV_TIME_BASE);
251+
252+
if (cut >= frame->nb_samples) {
253+
// Before the position as a whole. The audio still has no
254+
// timestamp, so the next frame is measured the same way.
255+
return 0;
256+
}
257+
if (cut > 0) {
258+
skip = static_cast<int>(cut);
259+
start_us += av_rescale(cut, AV_TIME_BASE, in_rate_);
260+
}
261+
}
262+
263+
discarding_ = false;
264+
next_timestamp_us_ = start_us;
237265
have_timestamp_ = true;
238266
}
239267
else if (pts != AV_NOPTS_VALUE) {

‎webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,13 @@ namespace ffmpeg
513513
video_decoder_.Flush();
514514
audio_decoder_.Flush();
515515

516+
// The reader lands on the keyframe at or before the position, which
517+
// is where decoding has to begin. Playback begins at the position
518+
// itself: what comes before it is decoded and dropped, and the audio
519+
// frame it falls in is cut there.
520+
video_decoder_.DiscardBefore(position_us);
521+
audio_decoder_.DiscardBefore(position_us);
522+
516523
// A seek starts a timeline of its own: the pacer maps the first item
517524
// that arrives onto the clock afresh, so the offset that kept looping
518525
// monotonic is no longer needed and would only skew the position.

‎webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp‎

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,7 @@ namespace ffmpeg
336336
draining_ = false;
337337
awaiting_key_frame_ = false;
338338
skipped_ = 0;
339+
discarding_ = false;
339340
time_base_ = { 0, 1 };
340341
}
341342

@@ -353,6 +354,13 @@ namespace ffmpeg
353354
draining_ = false;
354355
awaiting_key_frame_ = false;
355356
skipped_ = 0;
357+
discarding_ = false;
358+
}
359+
360+
void VideoDecoder::DiscardBefore(int64_t timestamp_us)
361+
{
362+
discard_before_us_ = timestamp_us;
363+
discarding_ = true;
356364
}
357365

358366
bool VideoDecoder::IsHardwareFailure(int result) const
@@ -441,6 +449,35 @@ namespace ffmpeg
441449
}
442450

443451
int VideoDecoder::ReceiveFromCodec(AVFrame ** frame, int64_t * timestamp_us)
452+
{
453+
for (;;) {
454+
*frame = nullptr;
455+
456+
int result = ReceivePicture(frame, timestamp_us);
457+
458+
if (result < 0) {
459+
return result;
460+
}
461+
if (*frame == nullptr) {
462+
// Dropped before it was read back and converted.
463+
continue;
464+
}
465+
466+
if (discarding_ && *timestamp_us < discard_before_us_) {
467+
// Converted all the same, as the hardware was still on
468+
// probation, which only a picture made in full can end.
469+
av_frame_free(frame);
470+
471+
continue;
472+
}
473+
474+
discarding_ = false;
475+
476+
return 0;
477+
}
478+
}
479+
480+
int VideoDecoder::ReceivePicture(AVFrame ** frame, int64_t * timestamp_us)
444481
{
445482
if (hardware_ && HardwareFault::HoldsPictures()) {
446483
while (avcodec_receive_frame(codec_context_, decoded_) >= 0) {
@@ -477,6 +514,19 @@ namespace ffmpeg
477514

478515
const bool hardware_frame = hardware_format_ != AV_PIX_FMT_NONE && decoded_->format == hardware_format_;
479516

517+
if (discarding_ && !probation_ && *timestamp_us < discard_before_us_) {
518+
// Before the position a seek asked for, and decoded only because
519+
// the pictures after it depend on it. Reading it back from the
520+
// hardware and converting it would be most of what it costs.
521+
if (!hardware_frame) {
522+
hardware_ = false;
523+
}
524+
525+
av_frame_unref(decoded_);
526+
527+
return 0;
528+
}
529+
480530
if (hardware_frame) {
481531
// The picture is in the memory of the hardware decoder. Bring it
482532
// into system memory, as NV12, and convert it like any other
@@ -638,13 +688,22 @@ namespace ffmpeg
638688
AVFrame * frame = nullptr;
639689
int64_t timestamp_us = 0;
640690

641-
if (ReceiveFromCodec(&frame, &timestamp_us) < 0) {
691+
// Out of pictures when all it held lay before the position of a
692+
// seek, and then it takes the packet.
693+
int received = ReceiveFromCodec(&frame, &timestamp_us);
694+
695+
if (received < 0 && received != AVERROR(EAGAIN)) {
642696
break;
643697
}
644-
645-
pending_.push_back({ frame, timestamp_us });
698+
if (received == 0) {
699+
pending_.push_back({ frame, timestamp_us });
700+
}
646701

647702
sent = avcodec_send_packet(codec_context_, packet);
703+
704+
if (received == AVERROR(EAGAIN)) {
705+
break;
706+
}
648707
}
649708
}
650709

‎webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/HardwareDecodingTest.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -502,8 +502,9 @@ void loopsInHardware() throws Exception {
502502

503503
@Test
504504
void seekBetweenKeyFrames() throws Exception {
505-
// Half a second in is not a key frame; the player has to start from
506-
// the key frame before it, however the reader gets there.
505+
// Half a second in is not a key frame; the player has to decode from
506+
// the key frame before it, however the reader gets there, and start
507+
// playing at half a second.
507508
Result software = play(H264, false, 500_000);
508509
Result hardware = play(H264, true, 500_000);
509510

‎webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java‎

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -267,9 +267,7 @@ void pauseHoldsPlayback() throws Exception {
267267
@Test
268268
void seekMovesPlayback() throws Exception {
269269
try (Playback playback = new Playback()) {
270-
// A seek lands on the keyframe at or before the target, so asking
271-
// for 2.5 s starts playback at the 2 s keyframe, leaving about a
272-
// second to play out.
270+
// Half a second is left to play out from 2.5 s.
273271
playback.player.seek(2_500_000);
274272
playback.player.play();
275273

@@ -282,6 +280,51 @@ void seekMovesPlayback() throws Exception {
282280
}
283281
}
284282

283+
@Test
284+
void seekStartsAtThePositionAskedFor() throws Exception {
285+
try (Playback playback = new Playback()) {
286+
// Between the keyframes at 1 s and 2 s. The reader lands on the
287+
// one at 1 s, and what lies between it and 1.5 s is decoded only
288+
// to get there.
289+
playback.player.seek(1_500_000);
290+
playback.player.play();
291+
292+
assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream");
293+
294+
// The first frame at or after 1.5 s is the one at 23 / 15 s.
295+
long first = playback.firstFramePositionUs.get();
296+
297+
assertTrue(first >= 1_500_000 && first < 1_500_000 + 1_000_000 / 15,
298+
"first frame at " + first + " us");
299+
300+
// 1.533 s to 2.933 s, and 1.5 s to 3.008 s of audio. Starting at
301+
// the keyframe would have played 15 frames and 50 chunks more.
302+
assertTrue(Math.abs(playback.frames.get() - 22) <= 1,
303+
"video frames: " + playback.frames.get());
304+
assertTrue(Math.abs(playback.chunks.get() - 151) <= 2,
305+
"audio chunks: " + playback.chunks.get());
306+
}
307+
}
308+
309+
@Test
310+
void seekCutsTheAudioFrameItFallsIn() throws Exception {
311+
// Two seconds in frames of 100 ms, at the rate WebRTC takes, so that
312+
// nothing is resampled and every sample played is one of the file's.
313+
Path flac = TestMedia.constantFlac(tempDir, 48000, 20, (short) 1000);
314+
315+
try (Playback playback = new Playback(new MediaReader(flac))) {
316+
// Half way into the frame at 1 s, which the reader lands on.
317+
playback.player.seek(1_050_000);
318+
playback.player.play();
319+
320+
assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream");
321+
322+
// 0.95 s is exactly 95 chunks, none of them padded.
323+
assertEquals(95, playback.chunks.get());
324+
assertEquals(95 * 480, playback.nonZeroSamples.get());
325+
}
326+
}
327+
285328
@Test
286329
void seekNearTheEndIsNotLost() throws Exception {
287330
// Two seconds of video only. All of it is decoded and queued within
@@ -781,12 +824,19 @@ private final class Playback implements AutoCloseable {
781824
final AtomicInteger framesPerChunk = new AtomicInteger();
782825
final AtomicReference<String> error = new AtomicReference<>();
783826
final List<Long> frameTimes = Collections.synchronizedList(new ArrayList<>());
827+
final AtomicLong firstFramePositionUs = new AtomicLong(-1);
784828
final AtomicLong firstChunkNs = new AtomicLong();
785829
final AtomicInteger unevenChunks = new AtomicInteger();
786830
final AtomicLong nonZeroSamples = new AtomicLong();
787831
final List<Integer> silentChunks = Collections.synchronizedList(new ArrayList<>());
788832

789833
private final VideoTrackSink videoSink = frame -> {
834+
// The pacer delivers on its own thread, having just moved the
835+
// position to the frame's presentation time.
836+
if (firstFramePositionUs.get() < 0) {
837+
firstFramePositionUs.set(Playback.this.player.getPositionUs());
838+
}
839+
790840
frameTimes.add(System.nanoTime());
791841
frames.incrementAndGet();
792842
width.set(frame.buffer.getWidth());

0 commit comments

Comments
 (0)