From 8b897675e04756c64ec32cc142654d4c0679fcd8 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 00:09:24 +0100 Subject: [PATCH 1/6] fix: count media positions from the start of the source A seek went to the container's clock as it was, while the decoders gave out its times unchanged, so a source that does not start at zero sought to the wrong place and could not be looped or played again. Positions now count from the first frame played, video or audio, and a seek before the video starts keeps the audio that comes first. --- docs/guide/media/media-files.md | 2 + .../src/main/cpp/include/media/AudioDecoder.h | 7 +- .../src/main/cpp/include/media/MediaPlayer.h | 12 +- .../src/main/cpp/include/media/MediaReader.h | 26 +- .../src/main/cpp/include/media/VideoDecoder.h | 7 +- .../src/main/cpp/src/media/AudioDecoder.cpp | 10 +- .../src/main/cpp/src/media/MediaPlayer.cpp | 5 +- .../src/main/cpp/src/media/MediaReader.cpp | 77 ++++- .../src/main/cpp/src/media/VideoDecoder.cpp | 6 +- .../webrtc/media/player/MediaPlayer.java | 7 +- .../webrtc/media/player/MediaPlayerTest.java | 213 ++++++++++++- .../onvoid/webrtc/media/player/TestMedia.java | 290 +++++++++++++++++- 12 files changed, 619 insertions(+), 43 deletions(-) diff --git a/docs/guide/media/media-files.md b/docs/guide/media/media-files.md index 9a2bca5f9..7ffe466b4 100644 --- a/docs/guide/media/media-files.md +++ b/docs/guide/media/media-files.md @@ -145,6 +145,8 @@ 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. +Positions count from the start of the source, which is its first video or audio frame, whichever comes first. The times a container gives its frames do not have to begin at zero: a file cut out of a longer recording or an MPEG-TS capture may start at any time, and `seek(2_000_000)` still means two seconds into it. Video and audio share that start, so a stream that begins after the other one keeps that distance. + 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. `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. diff --git a/webrtc-media/src/main/cpp/include/media/AudioDecoder.h b/webrtc-media/src/main/cpp/include/media/AudioDecoder.h index ddafbf2f5..ccfc92af6 100644 --- a/webrtc-media/src/main/cpp/include/media/AudioDecoder.h +++ b/webrtc-media/src/main/cpp/include/media/AudioDecoder.h @@ -66,8 +66,10 @@ namespace ffmpeg // Opens a decoder for the given stream, which must outlive this // decoder. Source audio of more than two channels is downmixed to - // stereo. Returns 0 or a negative AVERROR. - int Open(const AVStream * stream); + // stereo. Timestamps are given out relative to the start time, + // which is where the source starts on the container's clock. + // Returns 0 or a negative AVERROR. + int Open(const AVStream * stream, int64_t start_time_us = 0); void Close(); @@ -136,6 +138,7 @@ namespace ffmpeg int in_format_ = -1; int in_rate_ = 0; AVRational time_base_ = { 0, 1 }; + int64_t start_time_us_ = 0; int channels_ = 0; // Resampled samples not yet handed out, interleaved. diff --git a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h index 96d82ab84..feb7f1f78 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h @@ -57,6 +57,11 @@ namespace ffmpeg // Once those are full the decode thread blocks, which is what keeps a // whole file from being decoded into memory at once. // + // Everything here counts in positions, in microseconds from where the + // source starts: the reader knows where that is on the container's clock, + // and the decoders give out their timestamps relative to it, for video and + // audio alike. A stream that starts after the other one keeps that distance. + // // What the observer is told goes through a thread of its own. Each report // is queued under the lock, in the same step as the change it reports, // and that thread makes the calls one after the other, in that order. @@ -97,9 +102,10 @@ namespace ffmpeg void Pause(); // Moves playback to the given position, in microseconds from the - // start. What is already queued is dropped. A precise seek drops - // what is decoded between the keyframe it lands on and the - // position as well; one that is not plays from that keyframe. + // start of the source. What is already queued is dropped. A + // precise seek drops what is decoded between the keyframe it + // lands on and the position as well; one that is not plays from + // that keyframe. void Seek(int64_t position_us, bool precise); void SetLooping(bool looping); diff --git a/webrtc-media/src/main/cpp/include/media/MediaReader.h b/webrtc-media/src/main/cpp/include/media/MediaReader.h index f51f2c494..0373f8e81 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaReader.h +++ b/webrtc-media/src/main/cpp/include/media/MediaReader.h @@ -71,6 +71,17 @@ namespace ffmpeg // container does not say, as is the case for a live stream. int64_t GetDurationUs() const; + // Where the source starts on the container's clock, in + // microseconds: the first frame of the video and audio stream + // picked, whichever comes first, which is 0 when the container + // does not say. A file cut out of a longer one, or an MPEG-TS + // capture, can start well past 0. + // + // Every position is counted from here, for both streams, which + // is what keeps a stream that starts after the other one apart + // from the source starting late. + int64_t GetStartTimeUs() const; + bool HasVideo() const; int GetVideoWidth() const; int GetVideoHeight() const; @@ -104,11 +115,21 @@ namespace ffmpeg int ReadPacket(AVPacket * packet); // Moves to the keyframe at or before the given position, in - // microseconds from the start. The decoders have to be flushed - // afterwards, since what they hold belongs to the old position. + // microseconds from GetStartTimeUs. The decoders have to be + // flushed afterwards, since what they hold belongs to the old + // position. int Seek(int64_t position_us); private: + // Works out what GetStartTimeUs reports, once the streams to + // play have been picked. + int64_t FindStartTimeUs() const; + + // Seeks to the given time on the container's clock, by the given + // stream, or by the one libavformat picks if that is null. + // Returns what libavformat does, yet to be translated. + int SeekStream(const AVStream * stream, int64_t time_us, int flags); + // Polled by libavformat while it blocks. Returning non-zero // makes the blocking call fail with AVERROR_EXIT. static int OnInterrupt(void * opaque); @@ -124,6 +145,7 @@ namespace ffmpeg AVFormatContext * format_context_ = nullptr; int video_stream_index_ = -1; int audio_stream_index_ = -1; + int64_t start_time_us_ = 0; const int64_t timeout_us_; diff --git a/webrtc-media/src/main/cpp/include/media/VideoDecoder.h b/webrtc-media/src/main/cpp/include/media/VideoDecoder.h index f2f98b967..667a83dab 100644 --- a/webrtc-media/src/main/cpp/include/media/VideoDecoder.h +++ b/webrtc-media/src/main/cpp/include/media/VideoDecoder.h @@ -63,8 +63,12 @@ namespace ffmpeg // a hardware decoder for the codec, and in software otherwise. // HEVC goes to the hardware in any case, and without a hardware // decoder for it the result is AVERROR_DECODER_NOT_FOUND. + // + // Timestamps are given out relative to the start time, which is + // where the source starts on the container's clock. + // // Returns 0 or a negative AVERROR. - int Open(const AVStream * stream, bool hardware = false); + int Open(const AVStream * stream, bool hardware = false, int64_t start_time_us = 0); void Close(); @@ -195,6 +199,7 @@ namespace ffmpeg int pool_width_ = 0; int pool_height_ = 0; AVRational time_base_ = { 0, 1 }; + int64_t start_time_us_ = 0; AVPixelFormat hardware_format_ = AV_PIX_FMT_NONE; std::atomic hardware_{ false }; diff --git a/webrtc-media/src/main/cpp/src/media/AudioDecoder.cpp b/webrtc-media/src/main/cpp/src/media/AudioDecoder.cpp index 71ee4fab2..da3d3b722 100644 --- a/webrtc-media/src/main/cpp/src/media/AudioDecoder.cpp +++ b/webrtc-media/src/main/cpp/src/media/AudioDecoder.cpp @@ -32,7 +32,7 @@ namespace ffmpeg Close(); } - int AudioDecoder::Open(const AVStream * stream) + int AudioDecoder::Open(const AVStream * stream, int64_t start_time_us) { Close(); @@ -95,6 +95,7 @@ namespace ffmpeg } time_base_ = stream->time_base; + start_time_us_ = start_time_us; return 0; } @@ -118,6 +119,7 @@ namespace ffmpeg pending_.clear(); time_base_ = { 0, 1 }; + start_time_us_ = 0; channels_ = 0; next_timestamp_us_ = 0; have_timestamp_ = false; @@ -241,7 +243,7 @@ namespace ffmpeg if (!have_timestamp_) { int64_t start_us = pts != AV_NOPTS_VALUE - ? av_rescale_q(pts, time_base_, AV_TIME_BASE_Q) : 0; + ? av_rescale_q(pts, time_base_, AV_TIME_BASE_Q) - start_time_us_ : 0; // A frame without a timestamp cannot be placed against the // position, and is taken to start there. @@ -265,8 +267,8 @@ namespace ffmpeg have_timestamp_ = true; } else if (pts != AV_NOPTS_VALUE) { - int result = FollowTimestamp(av_rescale_q(pts, time_base_, AV_TIME_BASE_Q), - &skip); + int result = FollowTimestamp( + av_rescale_q(pts, time_base_, AV_TIME_BASE_Q) - start_time_us_, &skip); if (result < 0) { return result; diff --git a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp index c91fbf9ef..0ecd8db8f 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp @@ -65,7 +65,8 @@ namespace ffmpeg } if (reader_->HasVideo()) { - int result = video_decoder_.Open(reader_->GetVideoStream(), hardware_decoding_); + int result = video_decoder_.Open(reader_->GetVideoStream(), hardware_decoding_, + reader_->GetStartTimeUs()); if (result < 0) { return result; @@ -75,7 +76,7 @@ namespace ffmpeg } if (reader_->HasAudio()) { - int result = audio_decoder_.Open(reader_->GetAudioStream()); + int result = audio_decoder_.Open(reader_->GetAudioStream(), reader_->GetStartTimeUs()); if (result < 0) { return result; diff --git a/webrtc-media/src/main/cpp/src/media/MediaReader.cpp b/webrtc-media/src/main/cpp/src/media/MediaReader.cpp index 8cd9376cc..83f1509ca 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaReader.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaReader.cpp @@ -16,6 +16,7 @@ #include "media/MediaReader.h" +#include #include extern "C" { @@ -32,6 +33,12 @@ namespace // here: nothing this module plays is meant to fetch an arbitrary URL. constexpr const char * kProtocolWhitelist = "file,pipe,rtsp,rtp,udp,tcp"; + // How far before the first frame a seek to the start aims. A search by + // timestamp, which is all a container without an index has, goes by decode + // times, and those of the first keyframe come before its presentation + // time: aiming at that exactly finds the keyframe after it. + constexpr int64_t kStartMarginUs = 1000000; + std::once_flag network_initialized; } @@ -120,9 +127,35 @@ namespace ffmpeg return AVERROR_STREAM_NOT_FOUND; } + start_time_us_ = FindStartTimeUs(); + return 0; } + int64_t MediaReader::FindStartTimeUs() const + { + int64_t start_us = AV_NOPTS_VALUE; + + // The streams that are played, and not the container's own start: that + // also takes in the streams nothing here plays, such as a data track. + for (const AVStream * stream : { GetVideoStream(), GetAudioStream() }) { + if (stream == nullptr || stream->start_time == AV_NOPTS_VALUE) { + continue; + } + + const int64_t stream_us = av_rescale_q(stream->start_time, stream->time_base, + AV_TIME_BASE_Q); + + start_us = start_us == AV_NOPTS_VALUE ? stream_us : std::min(start_us, stream_us); + } + + if (start_us == AV_NOPTS_VALUE) { + start_us = format_context_->start_time; + } + + return start_us != AV_NOPTS_VALUE ? start_us : 0; + } + void MediaReader::Close() { if (format_context_ != nullptr) { @@ -137,6 +170,7 @@ namespace ffmpeg format_context_ = nullptr; video_stream_index_ = -1; audio_stream_index_ = -1; + start_time_us_ = 0; } bool MediaReader::IsOpen() const @@ -155,6 +189,11 @@ namespace ffmpeg return format_context_->duration; } + int64_t MediaReader::GetStartTimeUs() const + { + return start_time_us_; + } + bool MediaReader::HasVideo() const { return GetVideoStream() != nullptr; @@ -253,14 +292,48 @@ namespace ffmpeg position_us = 0; } + // libavformat takes the time on the container's clock, which is not + // where the source starts. + const int64_t target_us = position_us + start_time_us_; + const int64_t search_us = position_us > 0 ? target_us + : std::min(start_time_us_, std::max(start_time_us_ - kStartMarginUs, 0)); + + // libavformat searches the video by default. Before it starts there + // is no keyframe to go to, and a demuxer such as Matroska then goes to + // its first one and skips the audio that comes before that. + const AVStream * video = GetVideoStream(); + const AVStream * audio = GetAudioStream(); + const bool audio_first = video != nullptr && audio != nullptr + && video->start_time != AV_NOPTS_VALUE + && target_us < av_rescale_q(video->start_time, video->time_base, AV_TIME_BASE_Q); + // AVSEEK_FLAG_BACKWARD lands on the keyframe at or before the target, // so that what follows can actually be decoded. Frames between that // keyframe and the target are decoded and dropped by the caller. + int result = SeekStream(audio_first ? audio : nullptr, search_us, AVSEEK_FLAG_BACKWARD); + + if (result >= 0 || interrupted_.load() || timed_out_.load()) { + return TranslateError(result); + } + + // Nothing at or before the target, which some demuxers take for a + // failure. A stream that starts late has that for all that comes + // before it, and the first keyframe after is the nearest there is. + return TranslateError(SeekStream(audio_first ? audio : nullptr, target_us, 0)); + } + + int MediaReader::SeekStream(const AVStream * stream, int64_t time_us, int flags) + { + // Without a stream, libavformat picks one and takes the time as it is. + const int index = stream != nullptr ? stream->index : -1; + const int64_t timestamp = stream != nullptr + ? av_rescale_q(time_us, AV_TIME_BASE_Q, stream->time_base) : time_us; + BeginBlocking(); - int result = av_seek_frame(format_context_, -1, position_us, AVSEEK_FLAG_BACKWARD); + int result = av_seek_frame(format_context_, index, timestamp, flags); EndBlocking(); - return TranslateError(result); + return result; } void MediaReader::Interrupt() diff --git a/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp b/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp index 0508b3e29..6d32c7894 100644 --- a/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp +++ b/webrtc-media/src/main/cpp/src/media/VideoDecoder.cpp @@ -114,7 +114,7 @@ namespace ffmpeg Close(); } - int VideoDecoder::Open(const AVStream * stream, bool hardware) + int VideoDecoder::Open(const AVStream * stream, bool hardware, int64_t start_time_us) { Close(); @@ -168,6 +168,7 @@ namespace ffmpeg } time_base_ = stream->time_base; + start_time_us_ = start_time_us; // A decoder that is set up for hardware is on probation until it has // produced its first frame. @@ -343,6 +344,7 @@ namespace ffmpeg skipped_ = 0; discarding_ = false; time_base_ = { 0, 1 }; + start_time_us_ = 0; } void VideoDecoder::Flush() @@ -539,7 +541,7 @@ namespace ffmpeg ? decoded_->best_effort_timestamp : decoded_->pts; *timestamp_us = pts != AV_NOPTS_VALUE - ? av_rescale_q(pts, time_base_, AV_TIME_BASE_Q) : 0; + ? av_rescale_q(pts, time_base_, AV_TIME_BASE_Q) - start_time_us_ : 0; const bool hardware_frame = hardware_format_ != AV_PIX_FMT_NONE && decoded_->format == hardware_format_; diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java index 6d79167bb..fe853ac1c 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java @@ -194,6 +194,10 @@ public void pause() { * yet delivered is dropped. Video is decoded from the keyframe at or * before the position, and what comes before the position is dropped, so * the further the keyframes are apart, the longer this takes. + *

+ * Positions count from the start of the source, which is its first video + * or audio frame, whichever comes first, whatever time the container gives + * that frame. A stream that starts after the other one keeps that distance. * * @param positionUs The position in microseconds from the start. * @@ -236,7 +240,8 @@ public void setLooping(boolean looping) { /** * Returns where playback has got to within the current pass, in - * microseconds. A looping source starts again from zero. + * microseconds from the start of the source, as {@link #seek(long)} counts + * them. A looping source starts again from zero. * * @return The position in microseconds. */ 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 c06afc9f4..8ba5a7967 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 @@ -39,6 +39,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; @@ -87,8 +88,9 @@ class MediaPlayerTest { /** * 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 + * four seconds, at 0, 4 and 8 s. On the container's clock those are 0.133, + * 4.133 and 8.133 s: two B-frames put the first picture 0.133 s in, while + * its decode time is 0. 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. @@ -366,22 +368,22 @@ void seekCutsTheAudioFrameItFallsIn() throws Exception { 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. + // Just before the key frame at 8 s. A search for 7.8 s lands past + // the one at 4 s, and the decoder has nothing to show until 8 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. + // The picture at 7.8 s is the 118th, 117 / 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, + // 7.8 s to the end: the last 33 of the 150 pictures. + assertTrue(Math.abs(playback.frames.get() - 33) <= 1, "video frames: " + playback.frames.get()); } } @@ -390,14 +392,15 @@ void seekWithoutIndexStartsAtThePositionAskedFor() throws Exception { 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. + // A search for exactly where the first picture is would find the + // next key frame: it goes by decode times, and that of the first + // picture comes 0.133 s before it. 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); + assertEquals(0, playback.firstFramePositionUs.get(), 1); assertTrue(Math.abs(playback.frames.get() - 150) <= 1, "video frames: " + playback.frames.get()); } @@ -405,8 +408,8 @@ void seekWithoutIndexToItsStartPlaysItAll() throws Exception { @Test void loopAfterASeekWithoutIndexThatLandedLateStartsOver() throws Exception { - // The asset cut off after its last keyframe, at 8.133 s. A search for - // 7.8 s lands past the one at 4.133 s, and the decoder, holding + // The asset cut off after its last keyframe, at 8 s. A search for + // 7.8 s lands past the one at 4 s, and the decoder, holding // pictures back for its B-frames, gives the one at 8.133 s only once // it is drained at the end, where a seek that landed late is not // retried. @@ -427,7 +430,7 @@ void loopAfterASeekWithoutIndexThatLandedLateStartsOver() throws Exception { assertTrue(positions.size() > 10, "frames: " + positions); - // The picture at 8.133 s, and then the next pass from the start. + // The picture at 8 s, and then the next pass from the start. // The late landing, left over from the seek once the source had // started over, used to send the reader back before 7.8 s, so that // the last pictures played again before the next pass. What the @@ -504,6 +507,173 @@ void positionFollowsABackwardSeekOfAudio() throws Exception { } } + @Test + void seekCountsFromTheFirstFrame() throws Exception { + // Video at 5 s on the container's clock, audio a second after it. The + // source starts where its first frame does, so 2 s in is 7 s there. + try (Playback playback = new Playback(new MediaReader( + TestMedia.shiftedMatroska(tempDir, asset(), 5000, 6000)))) { + playback.player.seek(2_000_000); + playback.player.play(); + + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + + long first = playback.firstFramePositionUs.get(); + + assertTrue(first >= 2_000_000 && first < 2_000_000 + 1_000_000 / 15, + "first frame at " + first + " us"); + + // Video runs up to 3 s, audio from 1 s to 4 s. + assertTrue(Math.abs(playback.frames.get() - 15) <= 1, + "video frames: " + playback.frames.get()); + assertTrue(Math.abs(playback.chunks.get() - 200) <= 3, + "audio chunks: " + playback.chunks.get()); + } + } + + @Test + void seekCountsFromAudioThatStartsFirst() throws Exception { + // The other way around: audio at 5 s, video a second after it. + try (Playback playback = new Playback(new MediaReader( + TestMedia.shiftedMatroska(tempDir, asset(), 6000, 5000)))) { + playback.player.seek(2_000_000); + playback.player.play(); + + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + + long first = playback.firstFramePositionUs.get(); + + assertTrue(first >= 2_000_000 && first < 2_000_000 + 1_000_000 / 15, + "first frame at " + first + " us"); + + // Video runs from 1 s to 4 s, audio up to 3 s. + assertTrue(Math.abs(playback.frames.get() - 30) <= 1, + "video frames: " + playback.frames.get()); + assertTrue(Math.abs(playback.chunks.get() - 100) <= 3, + "audio chunks: " + playback.chunks.get()); + } + } + + @Test + void seekBeforeVideoStartsKeepsTheAudio() throws Exception { + try (Playback playback = new Playback(new MediaReader( + TestMedia.shiftedMatroska(tempDir, asset(), 6000, 5000)))) { + playback.player.seek(500_000); + playback.player.play(); + + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + + // All of the video, which starts at 1 s, and audio from 0.5 s. + assertTrue(Math.abs(playback.frames.get() - EXPECTED_FRAMES) <= 1, + "video frames: " + playback.frames.get()); + assertTrue(Math.abs(playback.chunks.get() - 250) <= 3, + "audio chunks: " + playback.chunks.get()); + } + } + + @Test + void positionCountsFromTheFirstFrame() throws Exception { + try (Playback playback = new Playback(new MediaReader( + TestMedia.shiftedMatroska(tempDir, asset(), 6000, 5000)))) { + playback.player.play(); + + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + + // Video starts a second after the source does. + long first = playback.firstFramePositionUs.get(); + + assertTrue(Math.abs(first - 1_000_000) < 20_000, "first frame at " + first + " us"); + + long end = playback.player.getPositionUs(); + + assertTrue(end > 3_900_000 && end < 4_100_000, "ended at " + end + " us"); + } + } + + @Test + void playsAgainFromTheFirstFrame() throws Exception { + try (Playback playback = new Playback(new MediaReader( + TestMedia.shiftedMatroska(tempDir, asset(), 5000, 6000)))) { + playback.player.play(); + + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + + int frames = playback.frames.get(); + int chunks = playback.chunks.get(); + + assertTrue(frames >= EXPECTED_FRAMES - 1, "video frames: " + frames); + + playback.framePositionsUs.clear(); + playback.player.play(); + + assertTrue(waitFor(() -> playback.frames.get() >= 2 * frames, 10_000), + "second pass played " + (playback.frames.get() - frames) + " of " + frames); + assertTrue(playback.framePositionsUs.get(0) < 1_000_000 / 15, + "second pass started at " + playback.framePositionsUs.get(0) + " us"); + assertTrue(waitFor(() -> playback.chunks.get() >= 2 * chunks - 3, 10_000), + "second pass of audio: " + (playback.chunks.get() - chunks)); + } + } + + @Test + void playsAgainFromAudioThatStartsFirst() throws Exception { + try (Playback playback = new Playback(new MediaReader( + TestMedia.shiftedMatroska(tempDir, asset(), 6000, 5000)))) { + playback.player.play(); + + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + + int frames = playback.frames.get(); + int chunks = playback.chunks.get(); + + playback.player.play(); + + assertTrue(waitFor(() -> playback.frames.get() >= 2 * frames, 10_000), + "second pass played " + (playback.frames.get() - frames) + " of " + frames); + assertTrue(waitFor(() -> playback.chunks.get() >= 2 * chunks - 3, 10_000), + "second pass of audio: " + (playback.chunks.get() - chunks) + " of " + chunks); + } + } + + @Test + void playsAgainWithoutAnEntryBeforeTheStart() throws Exception { + // Aiming before the start finds nothing in an FLV file, and that is + // not the end of the seek. + Path flv = TestMedia.pcmFlv(tempDir, (short) 1000, 5000, 10); + + try (Playback playback = new Playback(new MediaReader(flv))) { + playback.player.play(); + + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + assertEquals(null, playback.error.get()); + + int chunks = playback.chunks.get(); + + assertTrue(chunks > 0, "played nothing"); + + playback.player.play(); + + assertTrue(waitFor(() -> playback.chunks.get() >= 2 * chunks - 3, 10_000), + "second pass of audio: " + (playback.chunks.get() - chunks) + " of " + chunks + + ", error: " + playback.error.get()); + } + } + + @Test + void loopsWithoutAGapAtTheSeam() throws Exception { + // The file does not say how long it runs, so the next pass is placed + // after the last frame seen. That is 4 s from the start of the source, + // not from the start of the container's clock. + try (Playback playback = new Playback(new MediaReader( + TestMedia.shiftedMatroska(tempDir, asset(), 5000, 6000)))) { + playback.player.setLooping(true); + playback.player.play(); + + assertTrue(waitFor(() -> playback.frames.get() > EXPECTED_FRAMES + 15, 7_000), + "video frames after a pass and a half: " + playback.frames.get()); + } + } + @Test void needsAtLeastOneSource() throws Exception { MediaReader reader = new MediaReader(asset()); @@ -1027,6 +1197,21 @@ private static Path cutAfterLastKeyFrame(Path source, Path target) throws IOExce return Files.write(target, Arrays.copyOf(data, end)); } + private static boolean waitFor(BooleanSupplier condition, long timeoutMs) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs); + + while (!condition.getAsBoolean()) { + if (System.nanoTime() > deadline) { + return false; + } + + Thread.sleep(5); + } + + return true; + } + private static Path asset() throws Exception { URL url = MediaPlayerTest.class.getResource(ASSET); diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java index 807b80e3a..fee3e10f3 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java @@ -23,7 +23,10 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Comparator; +import java.util.List; import java.util.function.IntFunction; /** @@ -184,6 +187,86 @@ static Path pcmMatroska(Path directory, short value, long... blockTimes) matroska(track, blockTimes, n -> block)); } + /** + * Copies a Matroska file holding a video and an audio track, moving each + * track to start at the given time, which is what a recording cut out of + * a longer one or a stream captured part way through looks like. The + * frames stay interleaved by time, and every video keyframe gets a cue. + * The copy does not say how long it runs. + * + * @param directory Where to write the file. + * @param source The file to copy. + * @param videoStartMs When the first video frame is to start. + * @param audioStartMs When the first audio frame is to start. + * + * @return The file written. + */ + static Path shiftedMatroska(Path directory, Path source, long videoStartMs, + long audioStartMs) throws IOException { + MatroskaContent content = new MatroskaContent(Files.readAllBytes(source)); + List frames = new ArrayList<>(); + + for (Frame frame : content.frames) { + long start = frame.track == content.videoTrack ? videoStartMs : audioStartMs; + + frames.add(new Frame(frame.track, start + frame.timeMs, frame.key, frame.data)); + } + + frames.sort(Comparator.comparingLong(frame -> frame.timeMs)); + + return Files.write(directory.resolve("shifted.mkv"), + matroska(content.tracks, frames, content.videoTrack)); + } + + /** + * Writes 44.1 kHz, mono, 16-bit PCM in an FLV file, in tags of 100 ms of a + * constant, non-zero value. FLV has no index, and FFmpeg finds its way + * through one by the entries it has made while reading, so a time before + * the first of them cannot be found. + * + * @param directory Where to write the file. + * @param value The value of every sample. + * @param startMs When the first tag starts. + * @param tags How many tags to write. + * + * @return The file written. + */ + static Path pcmFlv(Path directory, short value, long startMs, int tags) throws IOException { + byte[] audio = new byte[1 + 4410 * 2]; + + // Little-endian PCM at 44.1 kHz, in 16 bits, mono. + audio[0] = 0x3E; + + for (int i = 1; i < audio.length; i += 2) { + audio[i] = (byte) value; + audio[i + 1] = (byte) (value >> 8); + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + // The signature, version 1, audio only, the size of this header. + writeBytes(out, ascii("FLV")); + out.write(1); + out.write(0x04); + writeInt(out, 9, 4); + // The size of the tag before the first one. + writeInt(out, 0, 4); + + for (int i = 0; i < tags; i++) { + long time = startMs + i * 100L; + + out.write(8); // An audio tag + writeInt(out, audio.length, 3); + writeInt(out, time & 0xFFFFFF, 3); + out.write((int) (time >>> 24)); + writeInt(out, 0, 3); // The stream ID + writeBytes(out, audio); + writeInt(out, 11 + audio.length, 4); + } + + return Files.write(directory.resolve("pcm.flv"), out.toByteArray()); + } + /** * Writes Opus in a Matroska file, with more channels than the eight a * decoded frame has room for in its data pointers, in 20 ms packets of @@ -238,28 +321,64 @@ static Path wideOpusMatroska(Path directory, int channels, int packets) */ private static byte[] matroska(byte[] track, long[] blockTimes, IntFunction block) { - ByteArrayOutputStream segment = new ByteArrayOutputStream(); + List frames = new ArrayList<>(); + + for (int i = 0; i < blockTimes.length; i++) { + frames.add(new Frame(1, blockTimes[i], true, block.apply(i))); + } + + return matroska(track, frames, -1); + } + + /** + * A Matroska file of the given tracks and one frame in each cluster, with + * a cue for every keyframe of the given track, if any. The cues come + * before the clusters, where the demuxer finds them without a seek head. + */ + private static byte[] matroska(byte[] tracks, List frames, int cueTrack) { + ByteArrayOutputStream head = new ByteArrayOutputStream(); // Info, with timestamps in milliseconds. - writeBytes(segment, ebml(0x1549A966, ebmlUInt(0x2AD7B1, 1000000))); + writeBytes(head, ebml(0x1549A966, ebmlUInt(0x2AD7B1, 1000000))); // Tracks. - writeBytes(segment, ebml(0x1654AE6B, track)); + writeBytes(head, ebml(0x1654AE6B, tracks)); + + ByteArrayOutputStream clusters = new ByteArrayOutputStream(); + List keyFrames = new ArrayList<>(); + + for (Frame frame : frames) { + if (frame.track == cueTrack && frame.key) { + keyFrames.add(new long[] { frame.timeMs, clusters.size() }); + } - for (int i = 0; i < blockTimes.length; i++) { ByteArrayOutputStream simpleBlock = new ByteArrayOutputStream(); - // Track 1, no offset from the cluster's time, a keyframe. - simpleBlock.write(0x81); + // The track, no offset from the cluster's time, the keyframe flag. + simpleBlock.write(0x80 | frame.track); writeInt(simpleBlock, 0, 2); - simpleBlock.write(0x80); - writeBytes(simpleBlock, block.apply(i)); + simpleBlock.write(frame.key ? 0x80 : 0); + writeBytes(simpleBlock, frame.data); // A cluster: its time, then the SimpleBlock. - writeBytes(segment, ebml(0x1F43B675, - ebmlUInt(0xE7, blockTimes[i]), + writeBytes(clusters, ebml(0x1F43B675, + ebmlUInt(0xE7, frame.timeMs), ebml(0xA3, simpleBlock.toByteArray()))); } + ByteArrayOutputStream segment = new ByteArrayOutputStream(); + + writeBytes(segment, head.toByteArray()); + + if (!keyFrames.isEmpty()) { + // Every number takes eight bytes, so the size of the cues does not + // depend on the positions they hold, which depend on that size. + int cuesSize = cues(keyFrames, cueTrack, 0).length; + + writeBytes(segment, cues(keyFrames, cueTrack, head.size() + cuesSize)); + } + + writeBytes(segment, clusters.toByteArray()); + ByteArrayOutputStream out = new ByteArrayOutputStream(); writeBytes(out, ebml(0x1A45DFA3, @@ -275,6 +394,24 @@ private static byte[] matroska(byte[] track, long[] blockTimes, return out.toByteArray(); } + /** + * The Cues element for the given pairs of time and position, positions + * being relative to where the clusters start. + */ + private static byte[] cues(List keyFrames, int track, long clustersStart) { + ByteArrayOutputStream points = new ByteArrayOutputStream(); + + for (long[] keyFrame : keyFrames) { + writeBytes(points, ebml(0xBB, + ebmlUInt(0xB3, keyFrame[0]), + ebml(0xB7, + ebmlUInt(0xF7, track), + ebmlUInt(0xF1, clustersStart + keyFrame[1])))); + } + + return ebml(0x1C53BB6B, points.toByteArray()); + } + /** * The TrackEntry of track 1, an audio track at 48 kHz, with any further * audio settings given. @@ -483,4 +620,137 @@ private static byte[] ascii(String text) { return text.getBytes(StandardCharsets.US_ASCII); } + /** One frame of a Matroska file, with its time in milliseconds. */ + private static final class Frame { + + final int track; + final long timeMs; + final boolean key; + final byte[] data; + + + Frame(int track, long timeMs, boolean key, byte[] data) { + this.track = track; + this.timeMs = timeMs; + this.key = key; + this.data = data; + } + } + + /** + * What a Matroska file with timestamps in milliseconds holds, as far as + * the committed assets use the format: no lacing, and track numbers of + * one byte. + */ + private static final class MatroskaContent { + + final List frames = new ArrayList<>(); + byte[] tracks; + int videoTrack; + + private final ByteBuffer data; + private long clusterTime; + private long trackNumber; + + + MatroskaContent(byte[] file) { + data = ByteBuffer.wrap(file); + + read(file.length); + } + + private void read(int end) { + while (data.position() < end) { + int id = readId(); + long size = readSize(); + int start = data.position(); + int stop = size < 0 ? end : (int) Math.min(start + size, end); + + switch (id) { + case 0x18538067: // Segment + case 0x1F43B675: // Cluster + case 0xA0: // BlockGroup + case 0xAE: // TrackEntry + read(stop); + break; + case 0x1654AE6B: // Tracks + tracks = Arrays.copyOfRange(data.array(), start, stop); + read(stop); + break; + case 0xD7: // TrackNumber + trackNumber = readUInt(stop); + break; + case 0x83: // TrackType, which follows the number + if (readUInt(stop) == 1) { + videoTrack = (int) trackNumber; + } + break; + case 0xE7: // Timestamp + clusterTime = readUInt(stop); + break; + case 0xA3: // SimpleBlock + case 0xA1: // Block + readBlock(stop, id == 0xA3); + break; + default: + break; + } + + data.position(stop); + } + } + + private void readBlock(int end, boolean simple) { + int track = data.get() & 0x7F; + long time = clusterTime + data.getShort(); + int flags = data.get() & 0xFF; + + if ((flags & 0x06) != 0) { + throw new IllegalArgumentException("Laced block"); + } + + frames.add(new Frame(track, time, !simple || (flags & 0x80) != 0, + Arrays.copyOfRange(data.array(), data.position(), end))); + } + + private long readUInt(int end) { + long value = 0; + + while (data.position() < end) { + value = (value << 8) | (data.get() & 0xFF); + } + + return value; + } + + private int readId() { + int first = data.get() & 0xFF; + int value = first; + + for (int i = Integer.numberOfLeadingZeros(first) - 24; i > 0; i--) { + value = (value << 8) | (data.get() & 0xFF); + } + + return value; + } + + /** Returns the size, or -1 for an element of unknown size. */ + private long readSize() { + int first = data.get() & 0xFF; + int length = Integer.numberOfLeadingZeros(first) - 24; + int mask = 0xFF >> (length + 1); + long value = first & mask; + boolean unknown = value == mask; + + for (int i = 0; i < length; i++) { + int next = data.get() & 0xFF; + + unknown &= next == 0xFF; + value = (value << 8) | next; + } + + return unknown ? -1 : value; + } + } + } From 6dcc75e2e81c26f362a79589fcd16bd92c1fa72e Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 00:12:54 +0100 Subject: [PATCH 2/6] fix: let a seek through a queue the old position keeps full The seek emptied the queues to free the decode thread, but a decoder with more on its way than a queue takes filled them again, and with playback paused nothing made room, so the thread never got to the seek. Each seek now starts a generation of the pacer, which turns away what is pushed for the one before. --- .../src/main/cpp/include/JNI_PlaybackProbe.h | 44 ++++++++++++++ .../src/main/cpp/include/media/MediaPacer.h | 27 ++++++++- .../src/main/cpp/include/media/MediaPlayer.h | 4 ++ .../main/cpp/include/media/PlaybackProbe.h | 58 +++++++++++++++++++ .../src/main/cpp/src/JNI_PlaybackProbe.cpp | 33 +++++++++++ .../src/main/cpp/src/media/MediaPacer.cpp | 56 ++++++++++++++---- .../src/main/cpp/src/media/MediaPlayer.cpp | 20 +++++-- .../src/main/cpp/src/media/PlaybackProbe.cpp | 53 +++++++++++++++++ .../webrtc/media/player/MediaPlayerTest.java | 25 ++++++++ .../webrtc/media/player/PlaybackProbe.java | 50 ++++++++++++++++ .../onvoid/webrtc/media/player/TestMedia.java | 38 ++++++++++-- 11 files changed, 384 insertions(+), 24 deletions(-) create mode 100644 webrtc-media/src/main/cpp/include/JNI_PlaybackProbe.h create mode 100644 webrtc-media/src/main/cpp/include/media/PlaybackProbe.h create mode 100644 webrtc-media/src/main/cpp/src/JNI_PlaybackProbe.cpp create mode 100644 webrtc-media/src/main/cpp/src/media/PlaybackProbe.cpp create mode 100644 webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlaybackProbe.java diff --git a/webrtc-media/src/main/cpp/include/JNI_PlaybackProbe.h b/webrtc-media/src/main/cpp/include/JNI_PlaybackProbe.h new file mode 100644 index 000000000..f3e2bf786 --- /dev/null +++ b/webrtc-media/src/main/cpp/include/JNI_PlaybackProbe.h @@ -0,0 +1,44 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +/* Header for class dev_onvoid_webrtc_media_player_PlaybackProbe */ + +#ifndef _Included_dev_onvoid_webrtc_media_player_PlaybackProbe +#define _Included_dev_onvoid_webrtc_media_player_PlaybackProbe +#ifdef __cplusplus +extern "C" { +#endif + /* + * Class: dev_onvoid_webrtc_media_player_PlaybackProbe + * Method: seeks + * Signature: ()J + */ + JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_PlaybackProbe_seeks + (JNIEnv *, jclass); + + /* + * Class: dev_onvoid_webrtc_media_player_PlaybackProbe + * Method: waitingPushes + * Signature: ()I + */ + JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_PlaybackProbe_waitingPushes + (JNIEnv *, jclass); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/webrtc-media/src/main/cpp/include/media/MediaPacer.h b/webrtc-media/src/main/cpp/include/media/MediaPacer.h index 54732bab2..df3e45372 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPacer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPacer.h @@ -92,12 +92,15 @@ namespace ffmpeg // // Blocks while the queue is full, which is the backpressure that // keeps decoding from running ahead of playback. Returns false - // once the pacer has been stopped. - bool PushVideo(AVFrame * frame, int64_t timestamp_us); + // once the pacer has been stopped, or once the generation given + // is no longer the current one: what was decoded for it belongs + // to a position that is being left, so it is dropped, and a wait + // for room ends there, as nothing else may ever end it. + bool PushVideo(AVFrame * frame, int64_t timestamp_us, uint64_t generation); // Hands over one 10 ms chunk of interleaved 16-bit PCM. bool PushAudio(std::vector && samples, int channels, - int64_t timestamp_us); + int64_t timestamp_us, uint64_t generation); void Pause(); void Resume(); @@ -109,6 +112,19 @@ namespace ffmpeg // delivered, in the timestamps the items are pushed with. void Flush(int64_t position_us); + // Flushes, and starts a new generation, which turns away what is + // still being pushed for the one before. This is for a seek that + // has been asked for, by a thread other than the one pushing, + // which may have more on its way than the queue can take. With + // playback paused nothing would ever make room for that, and the + // thread would never get round to the seek. + void StartGeneration(int64_t position_us); + + // The generation pushes have to name to be taken. The thread + // pushing reads this when it starts on a seek, so that everything + // it pushes from there on was decoded for that seek. + uint64_t GetGeneration() const; + // True once everything handed over has been delivered: the // queues are empty and no item is being handed to a source. bool IsDrained() const; @@ -147,6 +163,8 @@ namespace ffmpeg void Run(); + void FlushLocked(int64_t position_us); + // Both run without the lock held: the extension API delivers // synchronously into WebRTC, which must not happen underneath a // lock of ours. The time on the WebRTC clock is worked out by the @@ -175,6 +193,9 @@ namespace ffmpeg // Items taken from a queue whose delivery has not returned yet. int delivering_ = 0; + // Counts the seeks asked for. + uint64_t generation_ = 0; + // Presentation time plus this is a time on the WebRTC clock. int64_t base_us_ = 0; bool have_base_ = false; diff --git a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h index feb7f1f78..cf173ef81 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h @@ -234,6 +234,10 @@ namespace ffmpeg static constexpr int64_t kFirstSeekBackUs = 1000000; static constexpr int64_t kMaxSeekBackUs = 64000000; + // The generation of the pacer that the decode thread pushes for, + // the one of the seek it took last. On the decode thread. + uint64_t generation_ = 0; + // The seek being carried out, on the decode thread: its position, // whether it is precise, how far before it the reader was last // sent, and where to. diff --git a/webrtc-media/src/main/cpp/include/media/PlaybackProbe.h b/webrtc-media/src/main/cpp/include/media/PlaybackProbe.h new file mode 100644 index 000000000..13fd5eb19 --- /dev/null +++ b/webrtc-media/src/main/cpp/include/media/PlaybackProbe.h @@ -0,0 +1,58 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef WEBRTC_JAVA_MEDIA_PLAYBACK_PROBE_H_ +#define WEBRTC_JAVA_MEDIA_PLAYBACK_PROBE_H_ + +#include + +namespace ffmpeg +{ + // Shows the tests what a player's decode thread is up to, which nothing + // in the player's interface does: a seek takes effect on the position at + // once, and a thread held up by a full queue looks like one that is done. + // + // Only the tests read it, through JNI_PlaybackProbe, and it costs a player + // a single atomic update per seek and per wait for room in a queue. The + // counts are those of all players, which tests one at a time can tell + // apart. + class PlaybackProbe + { + public: + // Notes a seek that the decode thread has carried out. + static void NoteSeek(); + + // How many seeks have been carried out so far. + static int64_t Seeks(); + + // Counts a push as waiting for room in a queue for as long as + // this lives. + class WaitingPush + { + public: + WaitingPush(); + ~WaitingPush(); + + WaitingPush(const WaitingPush &) = delete; + WaitingPush & operator=(const WaitingPush &) = delete; + }; + + // How many pushes are waiting for room in a queue right now. + static int WaitingPushes(); + }; +} + +#endif diff --git a/webrtc-media/src/main/cpp/src/JNI_PlaybackProbe.cpp b/webrtc-media/src/main/cpp/src/JNI_PlaybackProbe.cpp new file mode 100644 index 000000000..c38dce4f3 --- /dev/null +++ b/webrtc-media/src/main/cpp/src/JNI_PlaybackProbe.cpp @@ -0,0 +1,33 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "JNI_PlaybackProbe.h" +#include "media/PlaybackProbe.h" + +// The Java class this belongs to exists in the tests only, so that nothing but +// them can reach it. + +JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_PlaybackProbe_seeks +(JNIEnv * env, jclass caller) +{ + return static_cast(ffmpeg::PlaybackProbe::Seeks()); +} + +JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_PlaybackProbe_waitingPushes +(JNIEnv * env, jclass caller) +{ + return static_cast(ffmpeg::PlaybackProbe::WaitingPushes()); +} diff --git a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp index d8d6ef99a..8c66222f2 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp @@ -16,6 +16,7 @@ #include "media/MediaPacer.h" #include "media/AudioDecoder.h" +#include "media/PlaybackProbe.h" #include #include @@ -134,15 +135,22 @@ namespace ffmpeg audio_queue_.clear(); } - bool MediaPacer::PushVideo(AVFrame * frame, int64_t timestamp_us) + bool MediaPacer::PushVideo(AVFrame * frame, int64_t timestamp_us, uint64_t generation) { std::unique_lock lock(mutex_); - video_space_.wait(lock, [this] { - return !running_ || video_queue_.size() < kVideoCapacity; - }); + const auto room = [this, generation] { + return !running_ || generation != generation_ + || video_queue_.size() < kVideoCapacity; + }; - if (!running_) { + if (!room()) { + PlaybackProbe::WaitingPush waiting; + + video_space_.wait(lock, room); + } + + if (!running_ || generation != generation_) { // The frame became ours on the way in, so it is ours to drop. av_frame_free(&frame); @@ -157,12 +165,13 @@ namespace ffmpeg } bool MediaPacer::PushAudio(std::vector && samples, int channels, - int64_t timestamp_us) + int64_t timestamp_us, uint64_t generation) { std::unique_lock lock(mutex_); - audio_space_.wait(lock, [this] { - if (!running_ || audio_queue_.size() < kAudioCapacity) { + const auto room = [this, generation] { + if (!running_ || generation != generation_ + || audio_queue_.size() < kAudioCapacity) { return true; } @@ -170,9 +179,15 @@ namespace ffmpeg // while it is running short. return audio_queue_.size() < kAudioOverflowCapacity && video_queue_.size() < kVideoCapacity / 2; - }); + }; + + if (!room()) { + PlaybackProbe::WaitingPush waiting; + + audio_space_.wait(lock, room); + } - if (!running_) { + if (!running_ || generation != generation_) { return false; } @@ -223,6 +238,27 @@ namespace ffmpeg { std::lock_guard lock(mutex_); + FlushLocked(position_us); + } + + void MediaPacer::StartGeneration(int64_t position_us) + { + std::lock_guard lock(mutex_); + + ++generation_; + + FlushLocked(position_us); + } + + uint64_t MediaPacer::GetGeneration() const + { + std::lock_guard lock(mutex_); + + return generation_; + } + + void MediaPacer::FlushLocked(int64_t position_us) + { video_queue_.clear(); audio_queue_.clear(); diff --git a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp index 0ecd8db8f..3c3e6c8d2 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp @@ -17,6 +17,7 @@ #include "media/MediaPlayer.h" #include "media/AllocationFault.h" #include "media/ErrorText.h" +#include "media/PlaybackProbe.h" #include #include @@ -167,15 +168,16 @@ namespace ffmpeg ended_ = false; // The decode thread may be held up by a full queue, and it cannot act - // on the request until it gets out of that. Dropping what is queued - // both frees it and throws away what belongs to the old position; the - // thread flushes again once the seek has actually happened. + // on the request until it gets out of that. A new generation frees it + // and throws away what belongs to the old position, what is queued as + // well as what it still has to push; it flushes again once the seek + // has actually happened. // // Under the lock, as the thread takes the request only under it: a // flush after that would throw away what it has decoded at the new // position, and an audio source, decoded seconds ahead, would skip // ahead or end at once. - pacer_->Flush(position_us + loop_offset_us_.load()); + pacer_->StartGeneration(position_us + loop_offset_us_.load()); command_.notify_all(); } @@ -308,6 +310,10 @@ namespace ffmpeg seek_to = seek_position_us_; seek_precise = seek_precise_; do_seek = true; + + // Under the lock, so that a seek coming in after this one + // turns away what is decoded for it. + generation_ = pacer_->GetGeneration(); } } @@ -485,7 +491,7 @@ namespace ffmpeg // The frame belongs to the pacer from here on, whether or not it // makes it into the queue. - if (!pacer_->PushVideo(frame, timestamp_us + loop_offset_us_.load())) { + if (!pacer_->PushVideo(frame, timestamp_us + loop_offset_us_.load(), generation_)) { return 0; } } @@ -513,7 +519,7 @@ namespace ffmpeg } if (!pacer_->PushAudio(std::move(chunk), audio_decoder_.GetChannels(), - timestamp_us + loop_offset_us_.load())) { + timestamp_us + loop_offset_us_.load(), generation_)) { return 0; } } @@ -530,6 +536,8 @@ namespace ffmpeg if (result < 0) { ReportError("Seeking failed", result); } + + PlaybackProbe::NoteSeek(); } bool MediaPlayer::SeekFurtherBack() diff --git a/webrtc-media/src/main/cpp/src/media/PlaybackProbe.cpp b/webrtc-media/src/main/cpp/src/media/PlaybackProbe.cpp new file mode 100644 index 000000000..5510f4054 --- /dev/null +++ b/webrtc-media/src/main/cpp/src/media/PlaybackProbe.cpp @@ -0,0 +1,53 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "media/PlaybackProbe.h" + +#include + +namespace +{ + std::atomic seeks{ 0 }; + std::atomic waiting_pushes{ 0 }; +} + +namespace ffmpeg +{ + void PlaybackProbe::NoteSeek() + { + seeks.fetch_add(1); + } + + int64_t PlaybackProbe::Seeks() + { + return seeks.load(); + } + + PlaybackProbe::WaitingPush::WaitingPush() + { + waiting_pushes.fetch_add(1); + } + + PlaybackProbe::WaitingPush::~WaitingPush() + { + waiting_pushes.fetch_sub(1); + } + + int PlaybackProbe::WaitingPushes() + { + return waiting_pushes.load(); + } +} 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 8ba5a7967..a746a1f77 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 @@ -674,6 +674,31 @@ void loopsWithoutAGapAtTheSeam() throws Exception { } } + @Test + void pausedSeekFinishesWithoutPlaying() throws Exception { + // A block of 25 s comes out of the decoder in one go, which is more + // than the audio queue takes even when a seek has just emptied it. + // While paused, nothing makes room in it again. + Path mkv = TestMedia.longPcmBlockMatroska(tempDir, (short) 1000, 25); + + try (Playback playback = new Playback(new MediaReader(mkv))) { + playback.player.play(); + + assertTrue(waitFor(() -> PlaybackProbe.waitingPushes() > 0, 10_000), + "the audio queue did not fill up"); + + playback.player.pause(); + + long seeks = PlaybackProbe.seeks(); + + playback.player.seek(0); + + assertTrue(waitFor(() -> PlaybackProbe.seeks() > seeks, 3_000), + "the seek was not carried out, with " + + PlaybackProbe.waitingPushes() + " push waiting"); + } + } + @Test void needsAtLeastOneSource() throws Exception { MediaReader reader = new MediaReader(asset()); diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlaybackProbe.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlaybackProbe.java new file mode 100644 index 000000000..c9e224d88 --- /dev/null +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlaybackProbe.java @@ -0,0 +1,50 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.media.player; + +/** + * Shows what the decode thread of a player is up to, which the interface of a + * player does not: a seek moves the position at once, and a thread held up by + * a full queue looks like one that has nothing to do. It lives in the tests so + * that nothing else can reach it. + *

+ * The counts are those of all players in the process. + * + * @author Alex Andres + */ +final class PlaybackProbe { + + static { + FFmpeg.load(); + } + + + private PlaybackProbe() { + // Static access only. + } + + /** + * Returns how many seeks decode threads have carried out so far. + */ + static native long seeks(); + + /** + * Returns how many decode threads are waiting for room in a queue. + */ + static native int waitingPushes(); + +} diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java index fee3e10f3..8333f8b9e 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java @@ -173,18 +173,46 @@ static Path corruptFlac(Path directory, int frames, int corruptFrame) */ static Path pcmMatroska(Path directory, short value, long... blockTimes) throws IOException { - byte[] block = new byte[FLAC_BLOCK_SIZE * 2]; + byte[] block = pcmBlock(value, FLAC_BLOCK_SIZE); + + return Files.write(directory.resolve("pcm.mkv"), + matroska(pcmTrack(), blockTimes, n -> block)); + } + + /** + * Writes 48 kHz, mono, 16-bit PCM in a Matroska file, all of it in a + * single block of a constant, non-zero value. A decoder gives all of a + * block out in one go, so a long one is more audio at once than a queue + * of a player can take. + * + * @param directory Where to write the file. + * @param value The value of every sample. + * @param seconds How long the block is. + * + * @return The file written. + */ + static Path longPcmBlockMatroska(Path directory, short value, int seconds) + throws IOException { + byte[] block = pcmBlock(value, seconds * FLAC_SAMPLE_RATE); + + return Files.write(directory.resolve("long-block.mkv"), + matroska(pcmTrack(), new long[] { 0 }, n -> block)); + } + + private static byte[] pcmBlock(short value, int samples) { + byte[] block = new byte[samples * 2]; for (int i = 0; i < block.length; i += 2) { block[i] = (byte) value; block[i + 1] = (byte) (value >> 8); } - byte[] track = trackEntry("A_PCM/INT/LIT", null, 1, - ebmlUInt(0x6264, 16)); // BitDepth + return block; + } - return Files.write(directory.resolve("pcm.mkv"), - matroska(track, blockTimes, n -> block)); + private static byte[] pcmTrack() { + return trackEntry("A_PCM/INT/LIT", null, 1, + ebmlUInt(0x6264, 16)); // BitDepth } /** From 67f27e05335316f20c647fa10ddea86a6dbe2be6 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 00:15:32 +0100 Subject: [PATCH 3/6] fix: limit the memory a player's video queue takes Sixty pictures take over 700 MiB in 4K. The queue is now held to 256 MiB as well, which leaves 1080p its sixty pictures, and a player reports what its queue takes and has taken, so that this can be measured across players running side by side. --- docs/guide/media/media-files.md | 11 +++ .../src/main/cpp/include/JNI_MediaPlayer.h | 24 ++++++ .../src/main/cpp/include/media/MediaPacer.h | 36 ++++++++- .../src/main/cpp/include/media/MediaPlayer.h | 5 ++ .../src/main/cpp/src/JNI_MediaPlayer.cpp | 22 ++++++ .../src/main/cpp/src/media/MediaPacer.cpp | 65 +++++++++++++-- .../src/main/cpp/src/media/MediaPlayer.cpp | 10 +++ .../webrtc/media/player/MediaFileSource.java | 24 ++++++ .../webrtc/media/player/MediaPlayer.java | 47 +++++++++++ .../webrtc/media/player/MediaPlayerTest.java | 79 +++++++++++++++++++ 10 files changed, 313 insertions(+), 10 deletions(-) diff --git a/docs/guide/media/media-files.md b/docs/guide/media/media-files.md index 7ffe466b4..0fc534d01 100644 --- a/docs/guide/media/media-files.md +++ b/docs/guide/media/media-files.md @@ -185,6 +185,17 @@ A listener must still return promptly: the calls behind it wait, and so does a ` Closing the player, or the `MediaFileSource`, from a listener is fine: it takes effect at once, and the native player is released on another thread once the listener has returned. The same holds for a sink of a track made from the player's sources, which the player calls on threads of its own as well. ::: +## Memory + +Decoding runs ahead of playback by up to sixty pictures, and at most by what `MediaPlayer.getMaxQueuedVideoBytes()` reports, which is 256 MiB. That keeps sixty pictures of 1080p, about twenty of 4K, and whatever the resolution, a player does not take more than that for pictures waiting to be delivered. Several players take that much each, on top of what the decoders use themselves. + +To see what an application really needs, ask the players that run: + +```java +source.getQueuedVideoBytes(); // what the queued pictures take right now +source.getPeakQueuedVideoBytes(); // the most they have taken so far +``` + ## Feeding Your Own Media Sources `MediaFileSource` creates the media sources for you. An application that needs its own — to feed a source it already created, or to send only the video of a file — uses `MediaPlayer` directly: diff --git a/webrtc-media/src/main/cpp/include/JNI_MediaPlayer.h b/webrtc-media/src/main/cpp/include/JNI_MediaPlayer.h index 54f5d3271..d44222617 100644 --- a/webrtc-media/src/main/cpp/include/JNI_MediaPlayer.h +++ b/webrtc-media/src/main/cpp/include/JNI_MediaPlayer.h @@ -94,6 +94,30 @@ extern "C" { JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_dispose (JNIEnv *, jclass, jlong); + /* + * Class: dev_onvoid_webrtc_media_player_MediaPlayer + * Method: queuedVideoBytes + * Signature: (J)J + */ + JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_queuedVideoBytes + (JNIEnv *, jclass, jlong); + + /* + * Class: dev_onvoid_webrtc_media_player_MediaPlayer + * Method: peakQueuedVideoBytes + * Signature: (J)J + */ + JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_peakQueuedVideoBytes + (JNIEnv *, jclass, jlong); + + /* + * Class: dev_onvoid_webrtc_media_player_MediaPlayer + * Method: maxQueuedVideoBytes + * Signature: ()J + */ + JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_maxQueuedVideoBytes + (JNIEnv *, jclass); + #ifdef __cplusplus } #endif diff --git a/webrtc-media/src/main/cpp/include/media/MediaPacer.h b/webrtc-media/src/main/cpp/include/media/MediaPacer.h index df3e45372..78fd7c1cf 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPacer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPacer.h @@ -58,6 +58,13 @@ namespace ffmpeg static constexpr size_t kVideoCapacity = 60; static constexpr size_t kAudioCapacity = 100; + // What the pictures in the video queue may take, on top of their + // number. Sixty pictures in 4K would take over 700 MiB, for each + // player. This leaves 1080p its sixty pictures, of about 3 MiB + // each, and 4K about twenty, which is still most of a second. + // A single picture larger than this goes through on its own. + static constexpr size_t kVideoByteCapacity = 256 * 1024 * 1024; + // How far audio may run past its capacity while video is short. // // One thread decodes both, in the order the container stores @@ -68,8 +75,9 @@ namespace ffmpeg // then leaves the video queue running dry, and its frames arrive // late and all at once, which WebRTC's encoder answers by dropping // all but the last of each burst. Letting audio grow while video - // is below half its capacity is what keeps video fed; this bounds - // how much, at ten seconds, for a source that has no video at all. + // is below half its capacity, in pictures and in bytes, is what + // keeps video fed; this bounds how much, at ten seconds, for a + // source that has no video at all. static constexpr size_t kAudioOverflowCapacity = 1000; // The sources may be 0, in which case media of that kind is @@ -133,6 +141,13 @@ namespace ffmpeg // playback has got to. int64_t GetPositionUs() const; + // What the pictures in the video queue take right now, in bytes. + size_t GetQueuedVideoBytes() const; + + // The most they have taken so far. Nothing delivered counts, nor + // the pictures the decoder holds on to. + size_t GetPeakQueuedVideoBytes() const; + // True on the pacing thread, which is the one that calls the sinks // of the tracks fed by the sources. bool IsOwnThread() const; @@ -142,9 +157,11 @@ namespace ffmpeg { AVFrame * frame = nullptr; int64_t timestamp_us = 0; + size_t bytes = 0; VideoItem() = default; - VideoItem(AVFrame * f, int64_t ts) : frame(f), timestamp_us(ts) {} + VideoItem(AVFrame * f, int64_t ts, size_t size) + : frame(f), timestamp_us(ts), bytes(size) {} ~VideoItem(); VideoItem(VideoItem && other) noexcept; @@ -165,6 +182,14 @@ namespace ffmpeg void FlushLocked(int64_t position_us); + // Whether a picture of the given size fits the video queue. An + // empty queue takes anything, as nothing else would ever let a + // picture larger than the queue through. + bool HasVideoRoom(size_t bytes) const; + + // Whether video is below half of what its queue takes. + bool IsVideoShort() const; + // Both run without the lock held: the extension API delivers // synchronously into WebRTC, which must not happen underneath a // lock of ours. The time on the WebRTC clock is worked out by the @@ -187,6 +212,11 @@ namespace ffmpeg std::deque video_queue_; std::deque audio_queue_; + // What the pictures in the video queue take, and the most they + // have taken. + size_t video_bytes_ = 0; + size_t peak_video_bytes_ = 0; + bool running_ = false; bool paused_ = false; diff --git a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h index cf173ef81..49c2b12fa 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h @@ -122,6 +122,11 @@ namespace ffmpeg int GetState() const; + // What the decoded pictures waiting to be delivered take right + // now, in bytes, and the most they have taken so far. + size_t GetQueuedVideoBytes() const; + size_t GetPeakQueuedVideoBytes() const; + // True on any thread of the player, which are the ones its // observer and the sinks of the tracks it feeds are called on. // Such a thread cannot destroy the player: that waits for the diff --git a/webrtc-media/src/main/cpp/src/JNI_MediaPlayer.cpp b/webrtc-media/src/main/cpp/src/JNI_MediaPlayer.cpp index f3ff87d1c..9f5744239 100644 --- a/webrtc-media/src/main/cpp/src/JNI_MediaPlayer.cpp +++ b/webrtc-media/src/main/cpp/src/JNI_MediaPlayer.cpp @@ -152,6 +152,28 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_position }); } +JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_queuedVideoBytes +(JNIEnv * env, jclass caller, jlong handle) +{ + return ffmpeg::CallFromJava(env, 0, [&]() -> jlong { + return handle != 0 ? static_cast(PlayerOf(handle)->GetQueuedVideoBytes()) : 0; + }); +} + +JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_peakQueuedVideoBytes +(JNIEnv * env, jclass caller, jlong handle) +{ + return ffmpeg::CallFromJava(env, 0, [&]() -> jlong { + return handle != 0 ? static_cast(PlayerOf(handle)->GetPeakQueuedVideoBytes()) : 0; + }); +} + +JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_maxQueuedVideoBytes +(JNIEnv * env, jclass caller) +{ + return static_cast(ffmpeg::MediaPacer::kVideoByteCapacity); +} + JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_hardwareDecoding (JNIEnv * env, jclass caller, jlong handle) { diff --git a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp index 8c66222f2..76553907f 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp @@ -32,6 +32,25 @@ namespace av_frame_free(&frame); } + + // What a frame keeps in memory, padding and alignment included, which is + // what its buffers hold rather than what its size works out at. + size_t FrameBytes(const AVFrame * frame) + { + size_t bytes = 0; + + for (const AVBufferRef * buffer : frame->buf) { + if (buffer != nullptr) { + bytes += buffer->size; + } + } + + for (int i = 0; i < frame->nb_extended_buf; ++i) { + bytes += frame->extended_buf[i]->size; + } + + return bytes; + } } namespace ffmpeg @@ -44,7 +63,7 @@ namespace ffmpeg } MediaPacer::VideoItem::VideoItem(VideoItem && other) noexcept - : frame(other.frame), timestamp_us(other.timestamp_us) + : frame(other.frame), timestamp_us(other.timestamp_us), bytes(other.bytes) { other.frame = nullptr; } @@ -58,6 +77,7 @@ namespace ffmpeg frame = other.frame; timestamp_us = other.timestamp_us; + bytes = other.bytes; other.frame = nullptr; } @@ -133,15 +153,17 @@ namespace ffmpeg video_queue_.clear(); audio_queue_.clear(); + video_bytes_ = 0; } bool MediaPacer::PushVideo(AVFrame * frame, int64_t timestamp_us, uint64_t generation) { + const size_t bytes = FrameBytes(frame); + std::unique_lock lock(mutex_); - const auto room = [this, generation] { - return !running_ || generation != generation_ - || video_queue_.size() < kVideoCapacity; + const auto room = [this, generation, bytes] { + return !running_ || generation != generation_ || HasVideoRoom(bytes); }; if (!room()) { @@ -157,7 +179,9 @@ namespace ffmpeg return false; } - video_queue_.emplace_back(frame, timestamp_us); + video_queue_.emplace_back(frame, timestamp_us, bytes); + video_bytes_ += bytes; + peak_video_bytes_ = std::max(peak_video_bytes_, video_bytes_); work_.notify_one(); @@ -177,8 +201,7 @@ namespace ffmpeg // Full, but blocking now would keep video from being decoded // while it is running short. - return audio_queue_.size() < kAudioOverflowCapacity - && video_queue_.size() < kVideoCapacity / 2; + return audio_queue_.size() < kAudioOverflowCapacity && IsVideoShort(); }; if (!room()) { @@ -261,6 +284,7 @@ namespace ffmpeg { video_queue_.clear(); audio_queue_.clear(); + video_bytes_ = 0; // Audio only ever moves the position forward, so a position left from // before a seek backwards would hold it there until audio caught up. @@ -291,6 +315,32 @@ namespace ffmpeg return position_us_; } + size_t MediaPacer::GetQueuedVideoBytes() const + { + std::lock_guard lock(mutex_); + + return video_bytes_; + } + + size_t MediaPacer::GetPeakQueuedVideoBytes() const + { + std::lock_guard lock(mutex_); + + return peak_video_bytes_; + } + + bool MediaPacer::HasVideoRoom(size_t bytes) const + { + return video_queue_.empty() || (video_queue_.size() < kVideoCapacity + && video_bytes_ + bytes <= kVideoByteCapacity); + } + + bool MediaPacer::IsVideoShort() const + { + return video_queue_.size() < kVideoCapacity / 2 + && video_bytes_ < kVideoByteCapacity / 2; + } + bool MediaPacer::IsOwnThread() const { std::lock_guard lock(mutex_); @@ -335,6 +385,7 @@ namespace ffmpeg VideoItem item = std::move(video_queue_.front()); video_queue_.pop_front(); + video_bytes_ -= item.bytes; position_us_ = item.timestamp_us; video_space_.notify_one(); diff --git a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp index 3c3e6c8d2..033088359 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp @@ -264,6 +264,16 @@ namespace ffmpeg return state_; } + size_t MediaPlayer::GetQueuedVideoBytes() const + { + return pacer_->GetQueuedVideoBytes(); + } + + size_t MediaPlayer::GetPeakQueuedVideoBytes() const + { + return pacer_->GetPeakQueuedVideoBytes(); + } + bool MediaPlayer::IsOwnThread() const { { diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaFileSource.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaFileSource.java index 3fd968200..42305cc8a 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaFileSource.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaFileSource.java @@ -302,6 +302,30 @@ public long getPositionUs() { return player.getPositionUs(); } + /** + * Returns how much memory the decoded pictures waiting to be delivered + * take right now. + * + * @return The size in bytes. + * + * @see MediaPlayer#getQueuedVideoBytes() + */ + public long getQueuedVideoBytes() { + return player.getQueuedVideoBytes(); + } + + /** + * Returns the most memory the decoded pictures waiting to be delivered + * have taken so far. + * + * @return The size in bytes. + * + * @see MediaPlayer#getPeakQueuedVideoBytes() + */ + public long getPeakQueuedVideoBytes() { + return player.getPeakQueuedVideoBytes(); + } + /** * Returns what the player is currently doing. * diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java index fe853ac1c..d5f20c0d8 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java @@ -251,6 +251,47 @@ public long getPositionUs() { } } + /** + * Returns the most memory that the decoded pictures waiting to be + * delivered may take in one player, in bytes. That holds whatever the + * resolution, so {@code n} players stay within {@code n} times this, on + * top of what the decoders themselves use. A single picture larger than + * this still goes through, on its own. + * + * @return The limit in bytes. + * + * @see #getPeakQueuedVideoBytes() + */ + public static long getMaxQueuedVideoBytes() { + return maxQueuedVideoBytes(); + } + + /** + * Returns how much memory the decoded pictures waiting to be delivered + * take right now, padding included. + * + * @return The size in bytes, which is 0 once the player is closed. + */ + public long getQueuedVideoBytes() { + synchronized (lock) { + return queuedVideoBytes(handle); + } + } + + /** + * Returns the most memory the decoded pictures waiting to be delivered + * have taken so far. Added up over the players of an application, this is + * what they actually needed, as opposed to what + * {@link #getMaxQueuedVideoBytes()} allows them. + * + * @return The size in bytes, which is 0 once the player is closed. + */ + public long getPeakQueuedVideoBytes() { + synchronized (lock) { + return peakQueuedVideoBytes(handle); + } + } + /** * Returns whether the video is being decoded in hardware. That can be * less than was asked for: the platform may have no hardware decoder for @@ -389,6 +430,12 @@ private native long create(long readerHandle, long tableAddress, private static native long position(long handle); + private static native long queuedVideoBytes(long handle); + + private static native long peakQueuedVideoBytes(long handle); + + private static native long maxQueuedVideoBytes(); + private static native int state(long handle); private static native boolean hardwareDecoding(long handle); 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 a746a1f77..b871d7887 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 @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.IOException; import java.net.URL; @@ -97,6 +98,12 @@ class MediaPlayerTest { */ private static final String TS_ASSET = "/media-test-h264.ts"; + /** 3840x2160 H.264, fifteen pictures. */ + private static final String H264_4K = "/media-test-h264-4k.mkv"; + + /** 1920x1080 H.264, fifteen pictures. */ + private static final String H264_1080P = "/media-test-h264-1080p.mkv"; + /** 3.008 seconds in chunks of 10 ms. */ private static final int EXPECTED_CHUNKS = 300; @@ -699,6 +706,74 @@ void pausedSeekFinishesWithoutPlaying() throws Exception { } } + @Test + void videoQueueKeepsToItsByteLimit() throws Exception { + // Two players, as what counts is what they take side by side. A loop + // gives the decoder more to do than the 15 pictures of the asset. + long limit = MediaPlayer.getMaxQueuedVideoBytes(); + + try (Playback first = new Playback(new MediaReader(resource(H264_4K))); + Playback second = new Playback(new MediaReader(resource(H264_4K)))) { + first.player.setLooping(true); + second.player.setLooping(true); + + first.player.play(); + second.player.play(); + + // A machine that decodes this slower than it plays has nothing + // to show here. + assumeTrue(waitFor(() -> PlaybackProbe.waitingPushes() == 2, 30_000), + "the video queues did not fill up"); + + long firstPeak = first.player.getPeakQueuedVideoBytes(); + long secondPeak = second.player.getPeakQueuedVideoBytes(); + + // Sixty pictures would come to over 700 MiB. + assertTrue(firstPeak <= limit, "first player took " + firstPeak + " bytes"); + assertTrue(secondPeak <= limit, "second player took " + secondPeak + " bytes"); + + // Full up to within a picture, and what is measured is what is + // queued now. + long picture = 3840L * 2160 * 3 / 2; + + assertTrue(firstPeak > limit - 2 * picture, "first player took " + firstPeak + " bytes"); + assertTrue(first.player.getQueuedVideoBytes() <= firstPeak, + "queued " + first.player.getQueuedVideoBytes() + " of " + firstPeak); + } + } + + @Test + void videoQueueHoldsSixtyPicturesOf1080p() throws Exception { + try (Playback playback = new Playback(new MediaReader(resource(H264_1080P)))) { + playback.player.setLooping(true); + playback.player.play(); + + assumeTrue(waitFor(() -> PlaybackProbe.waitingPushes() > 0, 30_000), + "the video queue did not fill up"); + + // Not cut short by the limit on bytes. + long peak = playback.player.getPeakQueuedVideoBytes(); + long picture = 1920L * 1080 * 3 / 2; + + assertTrue(peak >= 59 * picture, "took " + peak + " bytes"); + assertTrue(peak < MediaPlayer.getMaxQueuedVideoBytes(), "took " + peak + " bytes"); + } + } + + @Test + void closedPlayerHoldsNoVideo() throws Exception { + Playback playback = new Playback(); + + playback.player.play(); + + assertTrue(waitFor(() -> playback.frames.get() > 0, 10_000), "played nothing"); + + playback.close(); + + assertEquals(0, playback.player.getQueuedVideoBytes()); + assertEquals(0, playback.player.getPeakQueuedVideoBytes()); + } + @Test void needsAtLeastOneSource() throws Exception { MediaReader reader = new MediaReader(asset()); @@ -1237,6 +1312,10 @@ private static boolean waitFor(BooleanSupplier condition, long timeoutMs) return true; } + private static Path resource(String name) throws Exception { + return Paths.get(MediaPlayerTest.class.getResource(name).toURI()); + } + private static Path asset() throws Exception { URL url = MediaPlayerTest.class.getResource(ASSET); From b5b53313a3fc31774560f08c4d3f2df860ed9ca7 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 00:22:52 +0100 Subject: [PATCH 4/6] fix: keep the position from running backwards Video set the position outright, so a frame delivered late took it back behind audio already played. Delivery now only moves it forward. Items also carry the loop offset of their pass, as the player's own is ahead of playback by the whole queue: looping held the position at zero for most of a short source, and now restarts it as the next pass reaches delivery. --- .../src/main/cpp/include/media/MediaPacer.h | 43 +++++++--- .../src/main/cpp/include/media/MediaPlayer.h | 14 ++-- .../src/main/cpp/src/media/MediaPacer.cpp | 39 +++++++--- .../src/main/cpp/src/media/MediaPlayer.cpp | 14 ++-- .../webrtc/media/player/MediaPlayer.java | 4 +- .../webrtc/media/player/MediaPlayerTest.java | 78 +++++++++++++++++-- .../onvoid/webrtc/media/player/TestMedia.java | 39 ++++++++++ 7 files changed, 191 insertions(+), 40 deletions(-) diff --git a/webrtc-media/src/main/cpp/include/media/MediaPacer.h b/webrtc-media/src/main/cpp/include/media/MediaPacer.h index 78fd7c1cf..f9885eb8f 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPacer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPacer.h @@ -95,8 +95,11 @@ namespace ffmpeg // call more than once. void Stop(); - // Hands over a decoded frame and its presentation time. Ownership - // of the frame passes to the pacer whether this succeeds or not. + // Hands over a decoded frame and its presentation time, which is + // its position in the source. A source played again is pushed + // with a loop offset, which goes on top of that to make the times + // of all its passes one timeline that only rises. Ownership of + // the frame passes to the pacer whether this succeeds or not. // // Blocks while the queue is full, which is the backpressure that // keeps decoding from running ahead of playback. Returns false @@ -104,11 +107,12 @@ namespace ffmpeg // is no longer the current one: what was decoded for it belongs // to a position that is being left, so it is dropped, and a wait // for room ends there, as nothing else may ever end it. - bool PushVideo(AVFrame * frame, int64_t timestamp_us, uint64_t generation); + bool PushVideo(AVFrame * frame, int64_t timestamp_us, int64_t loop_offset_us, + uint64_t generation); // Hands over one 10 ms chunk of interleaved 16-bit PCM. bool PushAudio(std::vector && samples, int channels, - int64_t timestamp_us, uint64_t generation); + int64_t timestamp_us, int64_t loop_offset_us, uint64_t generation); void Pause(); void Resume(); @@ -117,7 +121,8 @@ namespace ffmpeg // the next item delivered starts a new one. This is what a seek // needs: what is queued belongs to the position being left. The // position is where playback is taken to be until an item has been - // delivered, in the timestamps the items are pushed with. + // delivered, in the source: the first item then sets it, wherever + // that landed, and starts a new timeline with no loop offset. void Flush(int64_t position_us); // Flushes, and starts a new generation, which turns away what is @@ -137,8 +142,13 @@ namespace ffmpeg // queues are empty and no item is being handed to a source. bool IsDrained() const; - // The presentation time of the item delivered last, which is where - // playback has got to. + // Where playback has got to in the source, in the pass that is + // being delivered: the furthest item delivered so far. It only + // moves forward, as video and audio are delivered independently + // and a frame that arrives late is behind what has been heard, + // other than when a flush moves it, or a pass of the source ends + // and the next one starts. That happens as the next pass reaches + // delivery, however far ahead the decoder has started it. int64_t GetPositionUs() const; // What the pictures in the video queue take right now, in bytes. @@ -157,11 +167,12 @@ namespace ffmpeg { AVFrame * frame = nullptr; int64_t timestamp_us = 0; + int64_t loop_offset_us = 0; size_t bytes = 0; VideoItem() = default; - VideoItem(AVFrame * f, int64_t ts, size_t size) - : frame(f), timestamp_us(ts), bytes(size) {} + VideoItem(AVFrame * f, int64_t ts, int64_t offset, size_t size) + : frame(f), timestamp_us(ts), loop_offset_us(offset), bytes(size) {} ~VideoItem(); VideoItem(VideoItem && other) noexcept; @@ -176,12 +187,17 @@ namespace ffmpeg std::vector samples; int channels = 0; int64_t timestamp_us = 0; + int64_t loop_offset_us = 0; }; void Run(); void FlushLocked(int64_t position_us); + // Takes in the time of an item about to be delivered, on the + // timeline of all passes, and the loop offset of its pass. + void AdvancePosition(int64_t timestamp_us, int64_t loop_offset_us); + // Whether a picture of the given size fits the video queue. An // empty queue takes anything, as nothing else would ever let a // picture larger than the queue through. @@ -226,11 +242,18 @@ namespace ffmpeg // Counts the seeks asked for. uint64_t generation_ = 0; - // Presentation time plus this is a time on the WebRTC clock. + // Presentation time, on the timeline of all passes, plus this is + // a time on the WebRTC clock. int64_t base_us_ = 0; bool have_base_ = false; int64_t paused_at_us_ = 0; + + // Where playback has got to on the timeline of all passes, the + // loop offset of the pass that is in, and whether an item has set + // them since the last flush. int64_t position_us_ = 0; + int64_t position_offset_us_ = 0; + bool position_set_ = false; }; } diff --git a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h index 49c2b12fa..50aac1741 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h @@ -117,7 +117,9 @@ namespace ffmpeg void Close(); // Where playback has got to within the current pass, in - // microseconds. A looping player starts again from zero. + // microseconds. It moves forward only, other than by a seek, and + // a looping player starts again from zero once the next pass + // reaches delivery. int64_t GetPositionUs() const; int GetState() const; @@ -262,11 +264,13 @@ namespace ffmpeg std::atomic looping_{ false }; - // Added to every presentation time handed to the pacer, so that a - // source played again keeps producing times that increase. The + // Goes with every presentation time handed to the pacer, so that + // a source played again keeps producing times that increase. The // pacer needs that: WebRTC drops a frame whose capture time does - // not advance. - std::atomic loop_offset_us_{ 0 }; + // not advance. Runs ahead of what is delivered, by as much as the + // decoder does, so only the pacer can tell where playback is. + // On the decode thread. + int64_t loop_offset_us_ = 0; }; } diff --git a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp index 76553907f..647441b4a 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp @@ -63,7 +63,8 @@ namespace ffmpeg } MediaPacer::VideoItem::VideoItem(VideoItem && other) noexcept - : frame(other.frame), timestamp_us(other.timestamp_us), bytes(other.bytes) + : frame(other.frame), timestamp_us(other.timestamp_us), + loop_offset_us(other.loop_offset_us), bytes(other.bytes) { other.frame = nullptr; } @@ -77,6 +78,7 @@ namespace ffmpeg frame = other.frame; timestamp_us = other.timestamp_us; + loop_offset_us = other.loop_offset_us; bytes = other.bytes; other.frame = nullptr; } @@ -156,7 +158,8 @@ namespace ffmpeg video_bytes_ = 0; } - bool MediaPacer::PushVideo(AVFrame * frame, int64_t timestamp_us, uint64_t generation) + bool MediaPacer::PushVideo(AVFrame * frame, int64_t timestamp_us, int64_t loop_offset_us, + uint64_t generation) { const size_t bytes = FrameBytes(frame); @@ -179,7 +182,7 @@ namespace ffmpeg return false; } - video_queue_.emplace_back(frame, timestamp_us, bytes); + video_queue_.emplace_back(frame, timestamp_us + loop_offset_us, loop_offset_us, bytes); video_bytes_ += bytes; peak_video_bytes_ = std::max(peak_video_bytes_, video_bytes_); @@ -189,7 +192,7 @@ namespace ffmpeg } bool MediaPacer::PushAudio(std::vector && samples, int channels, - int64_t timestamp_us, uint64_t generation) + int64_t timestamp_us, int64_t loop_offset_us, uint64_t generation) { std::unique_lock lock(mutex_); @@ -218,7 +221,8 @@ namespace ffmpeg item.samples = std::move(samples); item.channels = channels; - item.timestamp_us = timestamp_us; + item.timestamp_us = timestamp_us + loop_offset_us; + item.loop_offset_us = loop_offset_us; audio_queue_.push_back(std::move(item)); @@ -286,9 +290,13 @@ namespace ffmpeg audio_queue_.clear(); video_bytes_ = 0; - // Audio only ever moves the position forward, so a position left from - // before a seek backwards would hold it there until audio caught up. + // Items only ever move the position forward, so a position left from + // before a seek backwards would hold it there until they caught up. + // Nor can what comes next be held to this one: a seek that is not + // precise plays from a keyframe before it. position_us_ = position_us; + position_offset_us_ = 0; + position_set_ = false; // The next item delivered starts a new mapping, wherever it comes from. have_base_ = false; @@ -312,7 +320,18 @@ namespace ffmpeg { std::lock_guard lock(mutex_); - return position_us_; + return position_us_ - position_offset_us_; + } + + void MediaPacer::AdvancePosition(int64_t timestamp_us, int64_t loop_offset_us) + { + if (position_set_ && timestamp_us <= position_us_) { + return; + } + + position_us_ = timestamp_us; + position_offset_us_ = loop_offset_us; + position_set_ = true; } size_t MediaPacer::GetQueuedVideoBytes() const @@ -386,7 +405,7 @@ namespace ffmpeg video_queue_.pop_front(); video_bytes_ -= item.bytes; - position_us_ = item.timestamp_us; + AdvancePosition(item.timestamp_us, item.loop_offset_us); video_space_.notify_one(); // A shorter video queue may be what lets audio past its @@ -413,7 +432,7 @@ namespace ffmpeg AudioItem item = std::move(audio_queue_.front()); audio_queue_.pop_front(); - position_us_ = std::max(position_us_, item.timestamp_us); + AdvancePosition(item.timestamp_us, item.loop_offset_us); audio_space_.notify_one(); diff --git a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp index 033088359..a88c8d04d 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp @@ -177,7 +177,7 @@ namespace ffmpeg // flush after that would throw away what it has decoded at the new // position, and an audio source, decoded seconds ahead, would skip // ahead or end at once. - pacer_->StartGeneration(position_us + loop_offset_us_.load()); + pacer_->StartGeneration(position_us); command_.notify_all(); } @@ -252,9 +252,7 @@ namespace ffmpeg int64_t MediaPlayer::GetPositionUs() const { - const int64_t position = pacer_->GetPositionUs() - loop_offset_us_.load(); - - return position > 0 ? position : 0; + return std::max(pacer_->GetPositionUs(), 0); } int MediaPlayer::GetState() const @@ -361,7 +359,7 @@ namespace ffmpeg advance = max_source_pts_us_ + 10000; } - loop_offset_us_.fetch_add(advance); + loop_offset_us_ += advance; video_decoder_.Flush(); audio_decoder_.Flush(); @@ -501,7 +499,7 @@ namespace ffmpeg // The frame belongs to the pacer from here on, whether or not it // makes it into the queue. - if (!pacer_->PushVideo(frame, timestamp_us + loop_offset_us_.load(), generation_)) { + if (!pacer_->PushVideo(frame, timestamp_us, loop_offset_us_, generation_)) { return 0; } } @@ -529,7 +527,7 @@ namespace ffmpeg } if (!pacer_->PushAudio(std::move(chunk), audio_decoder_.GetChannels(), - timestamp_us + loop_offset_us_.load(), generation_)) { + timestamp_us, loop_offset_us_, generation_)) { return 0; } } @@ -600,7 +598,7 @@ namespace ffmpeg // A seek starts a timeline of its own: the pacer maps the first item // that arrives onto the clock afresh, so the offset that kept looping // monotonic is no longer needed and would only skew the position. - loop_offset_us_.store(0); + loop_offset_us_ = 0; max_source_pts_us_ = position_us; pacer_->Flush(position_us); diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java index d5f20c0d8..5790e0e86 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java @@ -241,7 +241,9 @@ public void setLooping(boolean looping) { /** * Returns where playback has got to within the current pass, in * microseconds from the start of the source, as {@link #seek(long)} counts - * them. A looping source starts again from zero. + * them. It moves forward only, whichever of video and audio is ahead, + * other than by a seek. A looping source starts again from zero as the + * next pass begins to play. * * @return The position in microseconds. */ 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 b871d7887..6d9a1f70b 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 @@ -340,7 +340,10 @@ void fastSeekPlaysFromTheKeyframeBefore() throws Exception { assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); - assertEquals(1_000_000, playback.firstFramePositionUs.get()); + // Audio going out alongside it can be a little ahead of the frame. + long first = playback.firstFramePositionUs.get(); + + assertTrue(first >= 1_000_000 && first < 1_040_000, "first frame at " + first + " us"); // 1 s to 2.933 s, and the audio from the first packet the reader // lands on, a few milliseconds after 1 s, uncut: about half a @@ -440,10 +443,8 @@ void loopAfterASeekWithoutIndexThatLandedLateStartsOver() throws Exception { // The picture at 8 s, and then the next pass from the start. // The late landing, left over from the seek once the source had // started over, used to send the reader back before 7.8 s, so that - // the last pictures played again before the next pass. What the - // first frame reports depends on whether the decoding thread has - // already started over, which it does long before the frame is - // due; the frames after it are all from the next pass. + // the last pictures played again before the next pass. + assertTrue(positions.get(0) > 7_800_000, "not from the position: " + positions); assertTrue(positions.get(1) < 1_000_000, "next pass not from the start: " + positions); for (int i = 2; i < positions.size(); i++) { @@ -615,7 +616,7 @@ void playsAgainFromTheFirstFrame() throws Exception { assertTrue(waitFor(() -> playback.frames.get() >= 2 * frames, 10_000), "second pass played " + (playback.frames.get() - frames) + " of " + frames); - assertTrue(playback.framePositionsUs.get(0) < 1_000_000 / 15, + assertTrue(playback.framePositionsUs.get(0) < 1_100_000, "second pass started at " + playback.framePositionsUs.get(0) + " us"); assertTrue(waitFor(() -> playback.chunks.get() >= 2 * chunks - 3, 10_000), "second pass of audio: " + (playback.chunks.get() - chunks)); @@ -774,6 +775,71 @@ void closedPlayerHoldsNoVideo() throws Exception { assertEquals(0, playback.player.getPeakQueuedVideoBytes()); } + @Test + void lateVideoLeavesThePositionAlone() throws Exception { + // Twelve seconds of audio ahead of the video in the file. Only ten go + // into the queue, so the video gets its turn once two have played, + // and frames that were due at the start are delivered at 2 s. + Path mkv = TestMedia.lateVideoMatroska(tempDir, asset(), 12_000); + + try (Playback playback = new Playback(new MediaReader(mkv))) { + playback.player.play(); + + assertTrue(waitFor(() -> playback.frames.get() > 0, 10_000), "no video"); + + long first = playback.firstFramePositionUs.get(); + + assertTrue(first > 1_500_000, "position fell back to " + first + " us"); + } + } + + @Test + void positionRestartsWithTheNextPass() throws Exception { + try (Playback playback = new Playback()) { + playback.player.setLooping(true); + playback.player.play(); + + assertTrue(waitFor(() -> playback.frames.get() >= EXPECTED_FRAMES + 30, 10_000), + "frames: " + playback.frames.get()); + + // The decoder starts over about a second ahead of what is played, + // which must not show: the position keeps rising up to the end of + // the pass, falls back once, and then rises again. + List positions = new ArrayList<>(playback.framePositionsUs); + int seam = -1; + + for (int i = 1; i < positions.size(); i++) { + if (positions.get(i) < positions.get(i - 1)) { + assertEquals(-1, seam, "went back more than once: " + positions); + + seam = i; + } + } + + assertTrue(seam > 0, "never went back: " + positions); + assertTrue(positions.get(seam - 1) > 2_800_000, + "pass cut short at frame " + seam + ": " + positions); + assertTrue(positions.get(seam) < 200_000, + "next pass late at frame " + seam + ": " + positions); + } + } + + @Test + void positionFollowsAFastSeekToItsKeyframe() throws Exception { + try (Playback playback = new Playback()) { + // The keyframe is at 1 s. The position must not wait at 1.5 s for + // playback to catch up with it. + playback.player.fastSeek(1_500_000); + playback.player.play(); + + assertTrue(waitFor(() -> playback.frames.get() > 0, 10_000), "no video"); + + long first = playback.firstFramePositionUs.get(); + + assertTrue(first < 1_100_000, "first frame at " + first + " us"); + } + } + @Test void needsAtLeastOneSource() throws Exception { MediaReader reader = new MediaReader(asset()); diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java index 8333f8b9e..c18226b2e 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java @@ -246,6 +246,45 @@ static Path shiftedMatroska(Path directory, Path source, long videoStartMs, matroska(content.tracks, frames, content.videoTrack)); } + /** + * Copies a Matroska file holding a video and an audio track so that its + * video comes late. The audio is repeated until it runs for the given + * time, and all of it is stored ahead of the video, which keeps its times. + * A player reading this has to play audio to make room for the rest of it + * before it gets to the video, whose first frames are overdue by then. + * + * @param directory Where to write the file. + * @param source The file to copy. + * @param audioMs How long the audio is to run. + * + * @return The file written. + */ + static Path lateVideoMatroska(Path directory, Path source, long audioMs) + throws IOException { + MatroskaContent content = new MatroskaContent(Files.readAllBytes(source)); + List video = new ArrayList<>(); + List audio = new ArrayList<>(); + + for (Frame frame : content.frames) { + (frame.track == content.videoTrack ? video : audio).add(frame); + } + + // Opus frames of 20 ms, the last of which ends a pass. + long pass = audio.get(audio.size() - 1).timeMs + 20; + List frames = new ArrayList<>(); + + for (long start = 0; start < audioMs; start += pass) { + for (Frame frame : audio) { + frames.add(new Frame(frame.track, start + frame.timeMs, frame.key, frame.data)); + } + } + + frames.addAll(video); + + return Files.write(directory.resolve("late-video.mkv"), + matroska(content.tracks, frames, -1)); + } + /** * Writes 44.1 kHz, mono, 16-bit PCM in an FLV file, in tags of 100 ms of a * constant, non-zero value. FLV has no index, and FFmpeg finds its way From 0e1158f4b4fbe6ff724fd227a0639479c0c5ec45 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 00:25:33 +0100 Subject: [PATCH 5/6] fix: keep video ahead of audio from going out all at once The clock mapping came from whatever reached the pacer first, which on a decoder with many threads was audio starting after the video: the first pictures were overdue by then, and WebRTC dropped all but the last. The mapping now starts at the position when audio gets there first. --- .../src/main/cpp/include/media/MediaPacer.h | 23 ++++++++++++++++--- .../src/main/cpp/src/media/MediaPacer.cpp | 19 +++++++++++---- .../src/main/cpp/src/media/MediaPlayer.cpp | 2 +- .../webrtc/media/player/MediaPlayerTest.java | 22 +++++++++++++++++- 4 files changed, 57 insertions(+), 9 deletions(-) diff --git a/webrtc-media/src/main/cpp/include/media/MediaPacer.h b/webrtc-media/src/main/cpp/include/media/MediaPacer.h index f9885eb8f..a30230894 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPacer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPacer.h @@ -44,7 +44,9 @@ namespace ffmpeg // is a time on the WebRTC clock. Every item carries that time with it, so // the timeline that reaches the receiver is the source's own and not the // pacing thread's, and audio stays lined up with video however much the - // thread is jostled. + // thread is jostled. The mapping starts at the position playback starts + // from, if audio gets here first, as video that belongs before it may + // still be in the decoder. // // Video and audio are paced independently. They go to different sources // and need no ordering between them, and keeping them independent is also @@ -80,6 +82,14 @@ namespace ffmpeg // source that has no video at all. static constexpr size_t kAudioOverflowCapacity = 1000; + // How far past the position playback starts from the first audio + // may lie for the mapping to start at that position regardless. + // It covers what a decoder holds back, which is up to one picture + // for each of its threads. Further than that the video would be + // here by now, and a source with timestamps that do not count + // from its start must not be held up for as long as they say. + static constexpr int64_t kMaxStartGapUs = 5000000; + // The sources may be 0, in which case media of that kind is // dropped rather than delivered. MediaPacer(const webrtc_java_api * api, void * video_source, @@ -123,7 +133,11 @@ namespace ffmpeg // position is where playback is taken to be until an item has been // delivered, in the source: the first item then sets it, wherever // that landed, and starts a new timeline with no loop offset. - void Flush(int64_t position_us); + // + // Exact says that playback really starts at this position, which + // a seek to a keyframe does not: there, what is played comes as + // it lands, so the first item starts the mapping. + void Flush(int64_t position_us, bool exact); // Flushes, and starts a new generation, which turns away what is // still being pushed for the one before. This is for a seek that @@ -192,7 +206,7 @@ namespace ffmpeg void Run(); - void FlushLocked(int64_t position_us); + void FlushLocked(int64_t position_us, bool exact); // Takes in the time of an item about to be delivered, on the // timeline of all passes, and the loop offset of its pass. @@ -246,6 +260,9 @@ namespace ffmpeg // a time on the WebRTC clock. int64_t base_us_ = 0; bool have_base_ = false; + + // Whether the mapping to come starts at the position. + bool exact_start_ = true; int64_t paused_at_us_ = 0; // Where playback has got to on the timeline of all passes, the diff --git a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp index 647441b4a..ad879afef 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp @@ -261,11 +261,11 @@ namespace ffmpeg work_.notify_all(); } - void MediaPacer::Flush(int64_t position_us) + void MediaPacer::Flush(int64_t position_us, bool exact) { std::lock_guard lock(mutex_); - FlushLocked(position_us); + FlushLocked(position_us, exact); } void MediaPacer::StartGeneration(int64_t position_us) @@ -274,7 +274,8 @@ namespace ffmpeg ++generation_; - FlushLocked(position_us); + // Should the seek fail, playback carries on from where it was. + FlushLocked(position_us, false); } uint64_t MediaPacer::GetGeneration() const @@ -284,7 +285,7 @@ namespace ffmpeg return generation_; } - void MediaPacer::FlushLocked(int64_t position_us) + void MediaPacer::FlushLocked(int64_t position_us, bool exact) { video_queue_.clear(); audio_queue_.clear(); @@ -300,6 +301,7 @@ namespace ffmpeg // The next item delivered starts a new mapping, wherever it comes from. have_base_ = false; + exact_start_ = exact; video_space_.notify_all(); audio_space_.notify_all(); @@ -393,6 +395,15 @@ namespace ffmpeg first = std::min(first, audio_queue_.front().timestamp_us); } + // Audio can get here ahead of video that comes before it, as + // a decoder on many threads holds on to its first pictures. + // Mapped from that audio, those pictures would be overdue, + // and go out all at once. + if (video_queue_.empty() && exact_start_ && first > position_us_ + && first - position_us_ <= kMaxStartGapUs) { + first = position_us_; + } + base_us_ = now - first; have_base_ = true; } diff --git a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp index a88c8d04d..d930a4df0 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp @@ -601,7 +601,7 @@ namespace ffmpeg loop_offset_us_ = 0; max_source_pts_us_ = position_us; - pacer_->Flush(position_us); + pacer_->Flush(position_us, seek_target_precise_); 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 6d9a1f70b..18b528a79 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 @@ -539,6 +539,26 @@ void seekCountsFromTheFirstFrame() throws Exception { } } + @Test + void videoAheadOfAudioKeepsItsPace() throws Exception { + // A decoder running on many threads gives out its first picture once + // it has been fed as many packets, by which time the audio a second + // in has long reached the pacer. That must not make the first second + // of video overdue, or it goes out all at once. + try (Playback playback = new Playback(new MediaReader( + TestMedia.shiftedMatroska(tempDir, asset(), 5000, 6000)))) { + playback.player.play(); + + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + + // Fourteen frames apart at 15 fps, with room for a slow machine. + long spanMs = TimeUnit.NANOSECONDS.toMillis( + playback.frameTimes.get(14) - playback.frameTimes.get(0)); + + assertTrue(spanMs > 700, "the first 15 frames took " + spanMs + " ms"); + } + } + @Test void seekCountsFromAudioThatStartsFirst() throws Exception { // The other way around: audio at 5 s, video a second after it. @@ -616,7 +636,7 @@ void playsAgainFromTheFirstFrame() throws Exception { assertTrue(waitFor(() -> playback.frames.get() >= 2 * frames, 10_000), "second pass played " + (playback.frames.get() - frames) + " of " + frames); - assertTrue(playback.framePositionsUs.get(0) < 1_100_000, + assertTrue(playback.framePositionsUs.get(0) < 1_000_000 / 15, "second pass started at " + playback.framePositionsUs.get(0) + " us"); assertTrue(waitFor(() -> playback.chunks.get() >= 2 * chunks - 3, 10_000), "second pass of audio: " + (playback.chunks.get() - chunks)); From db22f639ee4b3fe19ed5a7ff578381b55b3252a0 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 00:36:57 +0100 Subject: [PATCH 6/6] fix: report how long a Matroska file that starts late runs Matroska gives where a file ends on its clock, which libavformat passes on as the duration. With positions counting from the first frame, that was too long for a slider and left a gap of the start time at each seam of a loop. --- .../src/main/cpp/src/media/MediaReader.cpp | 11 +++++- .../webrtc/media/player/MediaPlayerTest.java | 15 ++++++++ .../webrtc/media/player/MediaReaderTest.java | 10 +++++ .../onvoid/webrtc/media/player/TestMedia.java | 38 +++++++++++++++---- 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/webrtc-media/src/main/cpp/src/media/MediaReader.cpp b/webrtc-media/src/main/cpp/src/media/MediaReader.cpp index 83f1509ca..6154c0692 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaReader.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaReader.cpp @@ -17,6 +17,7 @@ #include "media/MediaReader.h" #include +#include #include extern "C" { @@ -186,7 +187,15 @@ namespace ffmpeg // AVFormatContext::duration is already in AV_TIME_BASE units, which // are microseconds. - return format_context_->duration; + const int64_t duration_us = format_context_->duration; + + // Matroska gives where the file ends on its clock, which libavformat + // passes on, and that is only how long it runs if it starts at zero. + if (start_time_us_ > 0 && std::strstr(format_context_->iformat->name, "matroska") != nullptr) { + return std::max(duration_us - start_time_us_, 0); + } + + return duration_us; } int64_t MediaReader::GetStartTimeUs() const 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 18b528a79..8c36cf790 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 @@ -702,6 +702,21 @@ void loopsWithoutAGapAtTheSeam() throws Exception { } } + @Test + void loopsWithoutAGapWhenTheFileGivesItsEnd() throws Exception { + // A Matroska file gives where it ends, 9 s on its clock, which is not + // how long it runs, and is not where the next pass goes. + Path mkv = TestMedia.shiftedMatroska(tempDir, asset(), 5000, 6000, 9008); + + try (Playback playback = new Playback(new MediaReader(mkv))) { + playback.player.setLooping(true); + playback.player.play(); + + assertTrue(waitFor(() -> playback.frames.get() > EXPECTED_FRAMES + 15, 7_000), + "video frames after a pass and a half: " + playback.frames.get()); + } + } + @Test void pausedSeekFinishesWithoutPlaying() throws Exception { // A block of 25 s comes out of the decoder in one go, which is more diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaReaderTest.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaReaderTest.java index 2410a3327..8c680147c 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaReaderTest.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaReaderTest.java @@ -84,6 +84,16 @@ void readsAudioInfo() throws Exception { } } + @Test + void durationCountsFromTheFirstFrame(@TempDir Path dir) throws Exception { + Path mkv = TestMedia.shiftedMatroska(dir, asset(), 5000, 6000, 9008); + + try (MediaReader reader = new MediaReader(mkv)) { + // Video from 5 s and audio up to 9 s on the file's clock. + assertEquals(4_008_000, reader.getInfo().getDurationUs(), 50_000); + } + } + @Test void readsDuration() throws Exception { try (MediaReader reader = new MediaReader(asset())) { diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java index c18226b2e..bd6de7b35 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/TestMedia.java @@ -231,6 +231,24 @@ private static byte[] pcmTrack() { */ static Path shiftedMatroska(Path directory, Path source, long videoStartMs, long audioStartMs) throws IOException { + return shiftedMatroska(directory, source, videoStartMs, audioStartMs, -1); + } + + /** + * Copies a Matroska file as {@link #shiftedMatroska(Path, Path, long, long)} + * does, and has the copy give a duration, which in Matroska is where the + * file ends, counted from time zero and not from its first frame. + * + * @param directory Where to write the file. + * @param source The file to copy. + * @param videoStartMs When the first video frame is to start. + * @param audioStartMs When the first audio frame is to start. + * @param endMs The duration to give. + * + * @return The file written. + */ + static Path shiftedMatroska(Path directory, Path source, long videoStartMs, + long audioStartMs, long endMs) throws IOException { MatroskaContent content = new MatroskaContent(Files.readAllBytes(source)); List frames = new ArrayList<>(); @@ -243,7 +261,7 @@ static Path shiftedMatroska(Path directory, Path source, long videoStartMs, frames.sort(Comparator.comparingLong(frame -> frame.timeMs)); return Files.write(directory.resolve("shifted.mkv"), - matroska(content.tracks, frames, content.videoTrack)); + matroska(content.tracks, frames, content.videoTrack, endMs)); } /** @@ -282,7 +300,7 @@ static Path lateVideoMatroska(Path directory, Path source, long audioMs) frames.addAll(video); return Files.write(directory.resolve("late-video.mkv"), - matroska(content.tracks, frames, -1)); + matroska(content.tracks, frames, -1, -1)); } /** @@ -394,19 +412,25 @@ private static byte[] matroska(byte[] track, long[] blockTimes, frames.add(new Frame(1, blockTimes[i], true, block.apply(i))); } - return matroska(track, frames, -1); + return matroska(track, frames, -1, -1); } /** * A Matroska file of the given tracks and one frame in each cluster, with - * a cue for every keyframe of the given track, if any. The cues come - * before the clusters, where the demuxer finds them without a seek head. + * a cue for every keyframe of the given track, if any, and a duration, if + * it is not negative. The cues come before the clusters, where the demuxer + * finds them without a seek head. */ - private static byte[] matroska(byte[] tracks, List frames, int cueTrack) { + private static byte[] matroska(byte[] tracks, List frames, int cueTrack, + long durationMs) { ByteArrayOutputStream head = new ByteArrayOutputStream(); // Info, with timestamps in milliseconds. - writeBytes(head, ebml(0x1549A966, ebmlUInt(0x2AD7B1, 1000000))); + byte[] scale = ebmlUInt(0x2AD7B1, 1000000); + byte[] duration = durationMs < 0 ? new byte[0] + : ebml(0x4489, ByteBuffer.allocate(8).putDouble(durationMs).array()); + + writeBytes(head, ebml(0x1549A966, scale, duration)); // Tracks. writeBytes(head, ebml(0x1654AE6B, tracks));