Skip to content

Commit 45b41bc

Browse files
authored
fix: make media player seeking, position and queue memory reliable (#537)
* 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. * 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. * 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. * 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. * 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. * 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.
1 parent 77ce8e7 commit 45b41bc

23 files changed

Lines changed: 1601 additions & 105 deletions

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,8 @@ source.getState(); // IDLE, PLAYING, PAUSED, ENDED or CLOSED
145145

146146
Looping keeps the timing across the seam, so a looping file works as a stand-in for a camera that never stops. A looping source never reports an end of stream.
147147

148+
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.
149+
148150
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.
149151

150152
`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.
@@ -183,6 +185,17 @@ A listener must still return promptly: the calls behind it wait, and so does a `
183185
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.
184186
:::
185187

188+
## Memory
189+
190+
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.
191+
192+
To see what an application really needs, ask the players that run:
193+
194+
```java
195+
source.getQueuedVideoBytes(); // what the queued pictures take right now
196+
source.getPeakQueuedVideoBytes(); // the most they have taken so far
197+
```
198+
186199
## Feeding Your Own Media Sources
187200

188201
`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:

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,30 @@ extern "C" {
9494
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_dispose
9595
(JNIEnv *, jclass, jlong);
9696

97+
/*
98+
* Class: dev_onvoid_webrtc_media_player_MediaPlayer
99+
* Method: queuedVideoBytes
100+
* Signature: (J)J
101+
*/
102+
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_queuedVideoBytes
103+
(JNIEnv *, jclass, jlong);
104+
105+
/*
106+
* Class: dev_onvoid_webrtc_media_player_MediaPlayer
107+
* Method: peakQueuedVideoBytes
108+
* Signature: (J)J
109+
*/
110+
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_peakQueuedVideoBytes
111+
(JNIEnv *, jclass, jlong);
112+
113+
/*
114+
* Class: dev_onvoid_webrtc_media_player_MediaPlayer
115+
* Method: maxQueuedVideoBytes
116+
* Signature: ()J
117+
*/
118+
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_maxQueuedVideoBytes
119+
(JNIEnv *, jclass);
120+
97121
#ifdef __cplusplus
98122
}
99123
#endif
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
#include <jni.h>
18+
/* Header for class dev_onvoid_webrtc_media_player_PlaybackProbe */
19+
20+
#ifndef _Included_dev_onvoid_webrtc_media_player_PlaybackProbe
21+
#define _Included_dev_onvoid_webrtc_media_player_PlaybackProbe
22+
#ifdef __cplusplus
23+
extern "C" {
24+
#endif
25+
/*
26+
* Class: dev_onvoid_webrtc_media_player_PlaybackProbe
27+
* Method: seeks
28+
* Signature: ()J
29+
*/
30+
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_PlaybackProbe_seeks
31+
(JNIEnv *, jclass);
32+
33+
/*
34+
* Class: dev_onvoid_webrtc_media_player_PlaybackProbe
35+
* Method: waitingPushes
36+
* Signature: ()I
37+
*/
38+
JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_PlaybackProbe_waitingPushes
39+
(JNIEnv *, jclass);
40+
41+
#ifdef __cplusplus
42+
}
43+
#endif
44+
#endif

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,10 @@ namespace ffmpeg
6666

6767
// Opens a decoder for the given stream, which must outlive this
6868
// decoder. Source audio of more than two channels is downmixed to
69-
// stereo. Returns 0 or a negative AVERROR.
70-
int Open(const AVStream * stream);
69+
// stereo. Timestamps are given out relative to the start time,
70+
// which is where the source starts on the container's clock.
71+
// Returns 0 or a negative AVERROR.
72+
int Open(const AVStream * stream, int64_t start_time_us = 0);
7173

7274
void Close();
7375

@@ -136,6 +138,7 @@ namespace ffmpeg
136138
int in_format_ = -1;
137139
int in_rate_ = 0;
138140
AVRational time_base_ = { 0, 1 };
141+
int64_t start_time_us_ = 0;
139142
int channels_ = 0;
140143

141144
// Resampled samples not yet handed out, interleaved.

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

Lines changed: 105 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,9 @@ namespace ffmpeg
4444
// is a time on the WebRTC clock. Every item carries that time with it, so
4545
// the timeline that reaches the receiver is the source's own and not the
4646
// pacing thread's, and audio stays lined up with video however much the
47-
// thread is jostled.
47+
// thread is jostled. The mapping starts at the position playback starts
48+
// from, if audio gets here first, as video that belongs before it may
49+
// still be in the decoder.
4850
//
4951
// Video and audio are paced independently. They go to different sources
5052
// and need no ordering between them, and keeping them independent is also
@@ -58,6 +60,13 @@ namespace ffmpeg
5860
static constexpr size_t kVideoCapacity = 60;
5961
static constexpr size_t kAudioCapacity = 100;
6062

63+
// What the pictures in the video queue may take, on top of their
64+
// number. Sixty pictures in 4K would take over 700 MiB, for each
65+
// player. This leaves 1080p its sixty pictures, of about 3 MiB
66+
// each, and 4K about twenty, which is still most of a second.
67+
// A single picture larger than this goes through on its own.
68+
static constexpr size_t kVideoByteCapacity = 256 * 1024 * 1024;
69+
6170
// How far audio may run past its capacity while video is short.
6271
//
6372
// One thread decodes both, in the order the container stores
@@ -68,10 +77,19 @@ namespace ffmpeg
6877
// then leaves the video queue running dry, and its frames arrive
6978
// late and all at once, which WebRTC's encoder answers by dropping
7079
// all but the last of each burst. Letting audio grow while video
71-
// is below half its capacity is what keeps video fed; this bounds
72-
// how much, at ten seconds, for a source that has no video at all.
80+
// is below half its capacity, in pictures and in bytes, is what
81+
// keeps video fed; this bounds how much, at ten seconds, for a
82+
// source that has no video at all.
7383
static constexpr size_t kAudioOverflowCapacity = 1000;
7484

85+
// How far past the position playback starts from the first audio
86+
// may lie for the mapping to start at that position regardless.
87+
// It covers what a decoder holds back, which is up to one picture
88+
// for each of its threads. Further than that the video would be
89+
// here by now, and a source with timestamps that do not count
90+
// from its start must not be held up for as long as they say.
91+
static constexpr int64_t kMaxStartGapUs = 5000000;
92+
7593
// The sources may be 0, in which case media of that kind is
7694
// dropped rather than delivered.
7795
MediaPacer(const webrtc_java_api * api, void * video_source,
@@ -87,17 +105,24 @@ namespace ffmpeg
87105
// call more than once.
88106
void Stop();
89107

90-
// Hands over a decoded frame and its presentation time. Ownership
91-
// of the frame passes to the pacer whether this succeeds or not.
108+
// Hands over a decoded frame and its presentation time, which is
109+
// its position in the source. A source played again is pushed
110+
// with a loop offset, which goes on top of that to make the times
111+
// of all its passes one timeline that only rises. Ownership of
112+
// the frame passes to the pacer whether this succeeds or not.
92113
//
93114
// Blocks while the queue is full, which is the backpressure that
94115
// keeps decoding from running ahead of playback. Returns false
95-
// once the pacer has been stopped.
96-
bool PushVideo(AVFrame * frame, int64_t timestamp_us);
116+
// once the pacer has been stopped, or once the generation given
117+
// is no longer the current one: what was decoded for it belongs
118+
// to a position that is being left, so it is dropped, and a wait
119+
// for room ends there, as nothing else may ever end it.
120+
bool PushVideo(AVFrame * frame, int64_t timestamp_us, int64_t loop_offset_us,
121+
uint64_t generation);
97122

98123
// Hands over one 10 ms chunk of interleaved 16-bit PCM.
99124
bool PushAudio(std::vector<int16_t> && samples, int channels,
100-
int64_t timestamp_us);
125+
int64_t timestamp_us, int64_t loop_offset_us, uint64_t generation);
101126

102127
void Pause();
103128
void Resume();
@@ -106,17 +131,47 @@ namespace ffmpeg
106131
// the next item delivered starts a new one. This is what a seek
107132
// needs: what is queued belongs to the position being left. The
108133
// position is where playback is taken to be until an item has been
109-
// delivered, in the timestamps the items are pushed with.
110-
void Flush(int64_t position_us);
134+
// delivered, in the source: the first item then sets it, wherever
135+
// that landed, and starts a new timeline with no loop offset.
136+
//
137+
// Exact says that playback really starts at this position, which
138+
// a seek to a keyframe does not: there, what is played comes as
139+
// it lands, so the first item starts the mapping.
140+
void Flush(int64_t position_us, bool exact);
141+
142+
// Flushes, and starts a new generation, which turns away what is
143+
// still being pushed for the one before. This is for a seek that
144+
// has been asked for, by a thread other than the one pushing,
145+
// which may have more on its way than the queue can take. With
146+
// playback paused nothing would ever make room for that, and the
147+
// thread would never get round to the seek.
148+
void StartGeneration(int64_t position_us);
149+
150+
// The generation pushes have to name to be taken. The thread
151+
// pushing reads this when it starts on a seek, so that everything
152+
// it pushes from there on was decoded for that seek.
153+
uint64_t GetGeneration() const;
111154

112155
// True once everything handed over has been delivered: the
113156
// queues are empty and no item is being handed to a source.
114157
bool IsDrained() const;
115158

116-
// The presentation time of the item delivered last, which is where
117-
// playback has got to.
159+
// Where playback has got to in the source, in the pass that is
160+
// being delivered: the furthest item delivered so far. It only
161+
// moves forward, as video and audio are delivered independently
162+
// and a frame that arrives late is behind what has been heard,
163+
// other than when a flush moves it, or a pass of the source ends
164+
// and the next one starts. That happens as the next pass reaches
165+
// delivery, however far ahead the decoder has started it.
118166
int64_t GetPositionUs() const;
119167

168+
// What the pictures in the video queue take right now, in bytes.
169+
size_t GetQueuedVideoBytes() const;
170+
171+
// The most they have taken so far. Nothing delivered counts, nor
172+
// the pictures the decoder holds on to.
173+
size_t GetPeakQueuedVideoBytes() const;
174+
120175
// True on the pacing thread, which is the one that calls the sinks
121176
// of the tracks fed by the sources.
122177
bool IsOwnThread() const;
@@ -126,9 +181,12 @@ namespace ffmpeg
126181
{
127182
AVFrame * frame = nullptr;
128183
int64_t timestamp_us = 0;
184+
int64_t loop_offset_us = 0;
185+
size_t bytes = 0;
129186

130187
VideoItem() = default;
131-
VideoItem(AVFrame * f, int64_t ts) : frame(f), timestamp_us(ts) {}
188+
VideoItem(AVFrame * f, int64_t ts, int64_t offset, size_t size)
189+
: frame(f), timestamp_us(ts), loop_offset_us(offset), bytes(size) {}
132190
~VideoItem();
133191

134192
VideoItem(VideoItem && other) noexcept;
@@ -143,10 +201,25 @@ namespace ffmpeg
143201
std::vector<int16_t> samples;
144202
int channels = 0;
145203
int64_t timestamp_us = 0;
204+
int64_t loop_offset_us = 0;
146205
};
147206

148207
void Run();
149208

209+
void FlushLocked(int64_t position_us, bool exact);
210+
211+
// Takes in the time of an item about to be delivered, on the
212+
// timeline of all passes, and the loop offset of its pass.
213+
void AdvancePosition(int64_t timestamp_us, int64_t loop_offset_us);
214+
215+
// Whether a picture of the given size fits the video queue. An
216+
// empty queue takes anything, as nothing else would ever let a
217+
// picture larger than the queue through.
218+
bool HasVideoRoom(size_t bytes) const;
219+
220+
// Whether video is below half of what its queue takes.
221+
bool IsVideoShort() const;
222+
150223
// Both run without the lock held: the extension API delivers
151224
// synchronously into WebRTC, which must not happen underneath a
152225
// lock of ours. The time on the WebRTC clock is worked out by the
@@ -169,17 +242,35 @@ namespace ffmpeg
169242
std::deque<VideoItem> video_queue_;
170243
std::deque<AudioItem> audio_queue_;
171244

245+
// What the pictures in the video queue take, and the most they
246+
// have taken.
247+
size_t video_bytes_ = 0;
248+
size_t peak_video_bytes_ = 0;
249+
172250
bool running_ = false;
173251
bool paused_ = false;
174252

175253
// Items taken from a queue whose delivery has not returned yet.
176254
int delivering_ = 0;
177255

178-
// Presentation time plus this is a time on the WebRTC clock.
256+
// Counts the seeks asked for.
257+
uint64_t generation_ = 0;
258+
259+
// Presentation time, on the timeline of all passes, plus this is
260+
// a time on the WebRTC clock.
179261
int64_t base_us_ = 0;
180262
bool have_base_ = false;
263+
264+
// Whether the mapping to come starts at the position.
265+
bool exact_start_ = true;
181266
int64_t paused_at_us_ = 0;
267+
268+
// Where playback has got to on the timeline of all passes, the
269+
// loop offset of the pass that is in, and whether an item has set
270+
// them since the last flush.
182271
int64_t position_us_ = 0;
272+
int64_t position_offset_us_ = 0;
273+
bool position_set_ = false;
183274
};
184275
}
185276

0 commit comments

Comments
 (0)