Skip to content

Commit 040a77e

Browse files
committed
Merge branch 'main' into feat/fast-seek
Keeps the seek further back of #496 for precise seeks only: a fast seek plays from the keyframe the reader lands on.
2 parents 03c8753 + 2945560 commit 040a77e

10 files changed

Lines changed: 225 additions & 10 deletions

File tree

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

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

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

148-
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.
148+
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.
149149

150150
`fastSeek` moves to that keyframe and plays from there, without decoding up to the position, so it takes no longer however far the keyframes are apart. That suits a slider being dragged, as browsers' `fastSeek()` does: fast seeks while it moves, and a `seek` once it is let go. In a container without an index, such as MPEG-TS, the keyframe can be the one after the position.
151151

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

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,26 @@ namespace ffmpeg
126126
// of a stream and a loop both need.
127127
void DrainDecoders();
128128

129-
int DecodeVideo();
129+
// Takes the decoded video and hands it to the pacer. At the end
130+
// of the stream a seek that landed too late is not retried: the
131+
// source is about to end or start over, and that would be lost.
132+
int DecodeVideo(bool at_end);
130133
int DecodeAudio();
131134

132135
void PerformSeek(int64_t position_us, bool precise);
136+
137+
// Moves the reader to the given time and starts decoding from
138+
// there towards the position of the seek being carried out.
139+
// Returns 0 or a negative AVERROR.
140+
int SeekReader(int64_t from_us);
141+
142+
// Seeks again further back, after the video decoded since a seek
143+
// started past its position: the reader landed past the keyframe
144+
// before it. Only a precise seek does: a fast one plays from the
145+
// keyframe it lands on. Returns whether it did; there is nothing
146+
// further back to try once the reader would land where it did
147+
// already, or the distance has grown past kMaxSeekBackUs.
148+
bool SeekFurtherBack();
133149
void SetState(int state);
134150

135151
// Records the state, with the lock held. Returns whether it
@@ -167,6 +183,21 @@ namespace ffmpeg
167183
int64_t seek_position_us_ = 0;
168184
bool seek_precise_ = true;
169185

186+
// How far before the position a seek that landed too late looks
187+
// next, doubling each time, and how far at most: past that, a
188+
// stream whose keyframes are this far apart starts at the next
189+
// one, as a reader without an index would leave it.
190+
static constexpr int64_t kFirstSeekBackUs = 1000000;
191+
static constexpr int64_t kMaxSeekBackUs = 64000000;
192+
193+
// The seek being carried out, on the decode thread: its position,
194+
// whether it is precise, how far before it the reader was last
195+
// sent, and where to.
196+
int64_t seek_target_us_ = 0;
197+
bool seek_target_precise_ = true;
198+
int64_t seek_back_us_ = 0;
199+
int64_t seek_from_us_ = 0;
200+
170201
// Set once the source has run out and everything queued has been
171202
// delivered, so that the thread stops pumping until something
172203
// asks it to start again.

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,14 @@ namespace ffmpeg
8080
// the first frame that reaches it.
8181
void DiscardBefore(int64_t timestamp_us);
8282

83+
// Whether the first frame since DiscardBefore lay past its
84+
// position with none before it to drop: the seek landed past the
85+
// keyframe before the position, and the decoder had nothing to
86+
// show until the next one. A container without an index, such as
87+
// MPEG-TS, is searched by timestamp and can land that way.
88+
// Reported once, by the call after that frame was taken.
89+
bool LandedPastPosition();
90+
8391
// Hands a packet to the decoder, or null to start draining at the
8492
// end of the stream. Returns 0 or a negative AVERROR.
8593
int SendPacket(const AVPacket * packet);
@@ -212,6 +220,11 @@ namespace ffmpeg
212220
// Where the frames after a seek are to start.
213221
int64_t discard_before_us_ = 0;
214222
bool discarding_ = false;
223+
224+
// Whether a frame before that position has been dropped, and
225+
// whether the first frame then came past it without one.
226+
bool dropped_before_ = false;
227+
bool landed_past_ = false;
215228
};
216229
}
217230

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

Lines changed: 54 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#include "media/AllocationFault.h"
1919
#include "media/ErrorText.h"
2020

21+
#include <algorithm>
2122
#include <chrono>
2223
#include <utility>
2324

@@ -426,7 +427,7 @@ namespace ffmpeg
426427
}
427428

428429
if (video) {
429-
return DecodeVideo() >= 0;
430+
return DecodeVideo(false) >= 0;
430431
}
431432
if (audio) {
432433
return DecodeAudio() >= 0;
@@ -439,15 +440,15 @@ namespace ffmpeg
439440
{
440441
if (has_video_) {
441442
video_decoder_.SendPacket(nullptr);
442-
DecodeVideo();
443+
DecodeVideo(true);
443444
}
444445
if (has_audio_) {
445446
audio_decoder_.SendPacket(nullptr);
446447
DecodeAudio();
447448
}
448449
}
449450

450-
int MediaPlayer::DecodeVideo()
451+
int MediaPlayer::DecodeVideo(bool at_end)
451452
{
452453
for (;;) {
453454
AVFrame * frame = nullptr;
@@ -464,6 +465,14 @@ namespace ffmpeg
464465
return result;
465466
}
466467

468+
if (!at_end && video_decoder_.LandedPastPosition() && SeekFurtherBack()) {
469+
// From a later keyframe than the one the seek needs; decoding
470+
// starts again from an earlier one.
471+
av_frame_free(&frame);
472+
473+
return 0;
474+
}
475+
467476
if (timestamp_us > max_source_pts_us_) {
468477
max_source_pts_us_ = timestamp_us;
469478
}
@@ -506,14 +515,51 @@ namespace ffmpeg
506515

507516
void MediaPlayer::PerformSeek(int64_t position_us, bool precise)
508517
{
509-
int result = reader_->Seek(position_us);
518+
seek_target_us_ = position_us;
519+
seek_target_precise_ = precise;
520+
seek_back_us_ = 0;
521+
522+
int result = SeekReader(position_us);
510523

511524
if (result < 0) {
512525
ReportError("Seeking failed", result);
526+
}
527+
}
513528

514-
return;
529+
bool MediaPlayer::SeekFurtherBack()
530+
{
531+
if (!seek_target_precise_) {
532+
return false;
533+
}
534+
535+
const int64_t back = seek_back_us_ == 0 ? kFirstSeekBackUs : seek_back_us_ * 2;
536+
const int64_t from = std::max<int64_t>(seek_target_us_ - back, 0);
537+
538+
// Before the start the reader lands where it did, at the first
539+
// picture, which is the one to play.
540+
if (back > kMaxSeekBackUs || from >= seek_from_us_) {
541+
return false;
515542
}
516543

544+
seek_back_us_ = back;
545+
546+
// Where it failed, the reader stays where it was, and the frame that
547+
// came too late is played after all.
548+
return SeekReader(from) >= 0;
549+
}
550+
551+
int MediaPlayer::SeekReader(int64_t from_us)
552+
{
553+
const int64_t position_us = seek_target_us_;
554+
555+
int result = reader_->Seek(from_us);
556+
557+
if (result < 0) {
558+
return result;
559+
}
560+
561+
seek_from_us_ = std::max<int64_t>(from_us, 0);
562+
517563
video_decoder_.Flush();
518564
audio_decoder_.Flush();
519565

@@ -522,7 +568,7 @@ namespace ffmpeg
522568
// the position itself: what comes before it is decoded and dropped,
523569
// and the audio frame it falls in is cut there. Otherwise it begins
524570
// at that keyframe, video and audio alike.
525-
if (precise) {
571+
if (seek_target_precise_) {
526572
video_decoder_.DiscardBefore(position_us);
527573
audio_decoder_.DiscardBefore(position_us);
528574
}
@@ -534,6 +580,8 @@ namespace ffmpeg
534580
max_source_pts_us_ = position_us;
535581

536582
pacer_->Flush(position_us);
583+
584+
return 0;
537585
}
538586

539587
void MediaPlayer::SetState(int state)

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,13 @@ namespace ffmpeg
354354

355355
if (recorded.packet == nullptr
356356
|| av_new_packet(recorded.packet.get(), static_cast<int>(frame->size)) < 0) {
357+
// Dropped like a frame the queue has no room for: video goes on
358+
// from the next key frame.
359+
if (video) {
360+
input->waiting_for_key_frame = true;
361+
WantKeyFrameLocked(input);
362+
}
363+
357364
return;
358365
}
359366

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

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,17 @@ namespace ffmpeg
366366
{
367367
discard_before_us_ = timestamp_us;
368368
discarding_ = true;
369+
dropped_before_ = false;
370+
landed_past_ = false;
371+
}
372+
373+
bool VideoDecoder::LandedPastPosition()
374+
{
375+
const bool landed_past = landed_past_;
376+
377+
landed_past_ = false;
378+
379+
return landed_past;
369380
}
370381

371382
bool VideoDecoder::IsHardwareFailure(int result) const
@@ -465,6 +476,8 @@ namespace ffmpeg
465476
}
466477
if (*frame == nullptr) {
467478
// Dropped before it was read back and converted.
479+
dropped_before_ = true;
480+
468481
continue;
469482
}
470483

@@ -473,10 +486,15 @@ namespace ffmpeg
473486
// probation, which only a picture made in full can end.
474487
av_frame_free(frame);
475488

489+
dropped_before_ = true;
490+
476491
continue;
477492
}
478493

479-
discarding_ = false;
494+
if (discarding_) {
495+
landed_past_ = !dropped_before_ && *timestamp_us > discard_before_us_;
496+
discarding_ = false;
497+
}
480498

481499
return 0;
482500
}

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,16 @@ class MediaPlayerTest {
8080
/** 3.008 seconds at 15 frames a second. */
8181
private static final int EXPECTED_FRAMES = 45;
8282

83+
/**
84+
* 320x240 H.264 at 15 fps, ten seconds, in MPEG-TS, with a key frame every
85+
* four seconds, at 0.133, 4.133 and 8.133 s: two B-frames put the first
86+
* picture 0.133 s in. MPEG-TS has no index, so FFmpeg seeks in it by
87+
* searching for a timestamp, which can land past the key frame before the
88+
* position. Made with libx264 (veryfast, CRF 42, keyint 60, no scene cuts,
89+
* two B-frames) from a moving gradient.
90+
*/
91+
private static final String TS_ASSET = "/media-test-h264.ts";
92+
8393
/** 3.008 seconds in chunks of 10 ms. */
8494
private static final int EXPECTED_CHUNKS = 300;
8595

@@ -347,6 +357,47 @@ void seekCutsTheAudioFrameItFallsIn() throws Exception {
347357
}
348358
}
349359

360+
@Test
361+
void seekWithoutIndexStartsAtThePositionAskedFor() throws Exception {
362+
try (Playback playback = new Playback(new MediaReader(
363+
Paths.get(MediaPlayerTest.class.getResource(TS_ASSET).toURI())))) {
364+
// Just before the key frame at 8.133 s. A search for 7.8 s lands
365+
// past the one at 4.133 s, and the decoder has nothing to show
366+
// until 8.133 s, so the player has to look further back.
367+
playback.player.seek(7_800_000);
368+
playback.player.play();
369+
370+
assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream");
371+
372+
// The picture at 7.8 s is the 116th, 0.133 s + 115 / 15 s in.
373+
long first = playback.firstFramePositionUs.get();
374+
375+
assertTrue(first >= 7_800_000 && first < 7_800_000 + 1_000_000 / 15,
376+
"first frame at " + first + " us");
377+
378+
// 7.8 s to the end: the last 35 of the 150 pictures.
379+
assertTrue(Math.abs(playback.frames.get() - 35) <= 1,
380+
"video frames: " + playback.frames.get());
381+
}
382+
}
383+
384+
@Test
385+
void seekWithoutIndexToItsStartPlaysItAll() throws Exception {
386+
try (Playback playback = new Playback(new MediaReader(
387+
Paths.get(MediaPlayerTest.class.getResource(TS_ASSET).toURI())))) {
388+
// Before the first picture, which is 0.133 s in: there is nothing
389+
// further back to look for, and the player starts at that picture.
390+
playback.player.seek(0);
391+
playback.player.play();
392+
393+
assertTrue(playback.ended.await(20, TimeUnit.SECONDS), "no end of stream");
394+
395+
assertEquals(133_333, playback.firstFramePositionUs.get(), 1);
396+
assertTrue(Math.abs(playback.frames.get() - 150) <= 1,
397+
"video frames: " + playback.frames.get());
398+
}
399+
}
400+
350401
@Test
351402
void seekNearTheEndIsNotLost() throws Exception {
352403
// Two seconds of video only. All of it is decoded and queued within
181 KB
Binary file not shown.

‎webrtc/src/main/java/dev/onvoid/webrtc/client/PeerImpl.java‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1024,7 +1024,8 @@ public String toString() {
10241024
* Starts closing, once.
10251025
*
10261026
* @return a future that completes on the control executor once the
1027-
* connection is closed, before the handlers hear of it.
1027+
* connection is closed and the control tasks queued before that have run,
1028+
* before the handlers hear of it.
10281029
*/
10291030
CompletableFuture<Void> closeInternal() {
10301031
if (closing.compareAndSet(false, true)) {
@@ -1774,6 +1775,19 @@ private void teardown() {
17741775

17751776
state = PeerState.CLOSED;
17761777
rtc.removePeer(this);
1778+
1779+
// Finished only once the tasks queued before the connection closed
1780+
// have run: a callback of WebRTC may have queued one behind this
1781+
// teardown, such as a channel the remote side opened, and that task
1782+
// still calls into its native objects. The runtime frees the factory,
1783+
// and with it WebRTC's threads, as soon as closedInternal completes.
1784+
// Nothing is queued for the connection once it has closed.
1785+
Runnable finish = () -> finishTeardown(ended, error);
1786+
1787+
control.execute(finish, finish);
1788+
}
1789+
1790+
private void finishTeardown(List<RemoteTrackImpl> ended, PeerClosedException error) {
17771791
closedInternal.complete(null);
17781792

17791793
events.execute(() -> {

0 commit comments

Comments
 (0)