Skip to content

Commit dea20c0

Browse files
committed
feat: let MediaReader analyze a source for longer
MediaReaderOptions sets the timeout, the analysis duration and the probe size of a reader, so that a camera whose keyframes come further apart than FFmpeg's 5 seconds reports its video size when it opens. Opening gets the analysis duration on top of the timeout. MediaFileSource takes a reader opened that way. Refs #598
1 parent 0937124 commit dea20c0

10 files changed

Lines changed: 388 additions & 12 deletions

File tree

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

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -347,11 +347,31 @@ If the server cannot be reached, the constructor throws an `IOException` once th
347347
A live stream has no end and no length:
348348

349349
- Its `MediaInfo` reports a duration of 0.
350-
- Its `MediaInfo` can report a video size of 0x0. Many cameras say how large their pictures are only with each keyframe, which may come too late for the reader. The video plays all the same, and its frames have their size.
351350
- Looping does not apply, and seeking is reported as an error.
352351
- Pausing stops reading from the server, but the server keeps sending. Resuming carries on from where playback paused, which leaves it behind real time by as long as it was paused.
353352
- To get back to live, close the source and open it again.
354353

354+
### Video Size of a Camera
355+
356+
Many cameras say how large their pictures are only with each keyframe. FFmpeg reads 5 seconds of a source when it opens it. If the first keyframe comes later, `MediaInfo` reports a video size of 0x0. The video plays all the same, and its frames have their size.
357+
358+
To know the size when the source opens, let FFmpeg read for longer than the camera's keyframe interval:
359+
360+
```java
361+
// Import required classes
362+
import dev.onvoid.webrtc.media.player.MediaReader;
363+
import dev.onvoid.webrtc.media.player.MediaReaderOptions;
364+
365+
MediaReaderOptions options = MediaReaderOptions.builder()
366+
.analyzeDuration(Duration.ofSeconds(15))
367+
.build();
368+
369+
MediaReader reader = new MediaReader("rtsp://camera.local/stream1", options);
370+
MediaFileSource source = new MediaFileSource(reader, false);
371+
```
372+
373+
The source takes over the reader and closes it. Opening takes up to the analysis duration on top of the timeout, as the camera sends in real time. FFmpeg also stops after 5 MB. For a stream of a high bit rate, raise that limit with `probeSize(bytes)` as well.
374+
355375
## Closing
356376

357377
Closing a `MediaFileSource` stops playback, and releases the player along with both media sources. Before that, release the senders a peer connection handed out, and the tracks:

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ extern "C" {
2525
/*
2626
* Class: dev_onvoid_webrtc_media_player_MediaReader
2727
* Method: open
28-
* Signature: (Ljava/lang/String;J)J
28+
* Signature: (Ljava/lang/String;JJJ)J
2929
*/
3030
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaReader_open
31-
(JNIEnv *, jclass, jstring, jlong);
31+
(JNIEnv *, jclass, jstring, jlong, jlong, jlong);
3232

3333
/*
3434
* Class: dev_onvoid_webrtc_media_player_MediaReader

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,13 @@ namespace ffmpeg
5050
MediaReader(const MediaReader &) = delete;
5151
MediaReader & operator=(const MediaReader &) = delete;
5252

53+
// How much of the source libavformat reads when it opens it, to
54+
// find what the streams hold: in microseconds of the source and
55+
// in bytes. 0 leaves its default. Opening may take the analysis
56+
// duration on top of the timeout, which a live stream needs to
57+
// send that much. Call this before Open.
58+
void SetAnalysis(int64_t analyze_duration_us, int64_t probe_size);
59+
5360
// Opens the given source and selects the video and audio stream
5461
// that are meant to be played. Returns 0, or the negative AVERROR
5562
// libavformat reported, in which case the reader stays closed.
@@ -134,8 +141,9 @@ namespace ffmpeg
134141
// makes the blocking call fail with AVERROR_EXIT.
135142
static int OnInterrupt(void * opaque);
136143

137-
// Starts the time the next blocking call has, and ends it.
138-
void BeginBlocking();
144+
// Starts the time the next blocking call has, the timeout and the
145+
// given extra time, and ends it.
146+
void BeginBlocking(int64_t extra_us = 0);
139147
void EndBlocking();
140148

141149
// A blocking call that failed because it ran out of time rather
@@ -149,6 +157,10 @@ namespace ffmpeg
149157

150158
const int64_t timeout_us_;
151159

160+
// 0 for the defaults of libavformat.
161+
int64_t analyze_duration_us_ = 0;
162+
int64_t probe_size_ = 0;
163+
152164
// When the current blocking call runs out of time, on the clock
153165
// of av_gettime_relative(), or 0 while none is running.
154166
std::atomic<int64_t> deadline_us_{ 0 };

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ namespace
6262
}
6363

6464
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaReader_open
65-
(JNIEnv * env, jclass caller, jstring source, jlong timeoutUs)
65+
(JNIEnv * env, jclass caller, jstring source, jlong timeoutUs, jlong analyzeDurationUs,
66+
jlong probeSize)
6667
{
6768
return ffmpeg::CallFromJava<jlong>(env, 0, [&]() -> jlong {
6869
if (source == nullptr) {
@@ -92,6 +93,9 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaReader_open
9293
}
9394

9495
auto reader = std::make_unique<ffmpeg::MediaReader>(static_cast<int64_t>(timeoutUs));
96+
97+
reader->SetAnalysis(static_cast<int64_t>(analyzeDurationUs), static_cast<int64_t>(probeSize));
98+
9599
int result = reader->Open(url);
96100

97101
if (result < 0) {

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

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ namespace ffmpeg
5757
Close();
5858
}
5959

60+
void MediaReader::SetAnalysis(int64_t analyze_duration_us, int64_t probe_size)
61+
{
62+
analyze_duration_us_ = std::max<int64_t>(analyze_duration_us, 0);
63+
probe_size_ = std::max<int64_t>(probe_size, 0);
64+
}
65+
6066
int MediaReader::Open(const std::string & url)
6167
{
6268
Close();
@@ -76,6 +82,15 @@ namespace ffmpeg
7682
format_context_->interrupt_callback.callback = &MediaReader::OnInterrupt;
7783
format_context_->interrupt_callback.opaque = this;
7884

85+
// Set on the context rather than passed as options, which only fail
86+
// where an allocation can. 0 is what libavformat takes for its own
87+
// choice of analysis duration; its probe size has a default instead.
88+
format_context_->max_analyze_duration = analyze_duration_us_;
89+
90+
if (probe_size_ > 0) {
91+
format_context_->probesize = probe_size_;
92+
}
93+
7994
AVDictionary * options = nullptr;
8095

8196
int result = AllocationFault::CheckOption(
@@ -105,7 +120,9 @@ namespace ffmpeg
105120
return TranslateError(result);
106121
}
107122

108-
BeginBlocking();
123+
// A live stream takes as long to send what is analyzed as it lasts,
124+
// which the timeout alone may not cover.
125+
BeginBlocking(analyze_duration_us_);
109126
result = avformat_find_stream_info(format_context_, nullptr);
110127
EndBlocking();
111128

@@ -382,7 +399,7 @@ namespace ffmpeg
382399
return 0;
383400
}
384401

385-
void MediaReader::BeginBlocking()
402+
void MediaReader::BeginBlocking(int64_t extra_us)
386403
{
387404
timed_out_.store(false);
388405

@@ -394,8 +411,9 @@ namespace ffmpeg
394411
// Saturated: a timeout too long to count arrives as INT64_MAX, and the
395412
// sum would wrap around into a deadline that has passed already.
396413
const int64_t now = av_gettime_relative();
414+
const int64_t time_us = extra_us > INT64_MAX - timeout_us_ ? INT64_MAX : timeout_us_ + extra_us;
397415

398-
deadline_us_.store(timeout_us_ > INT64_MAX - now ? INT64_MAX : now + timeout_us_);
416+
deadline_us_.store(time_us > INT64_MAX - now ? INT64_MAX : now + time_us);
399417
}
400418

401419
void MediaReader::EndBlocking()

‎webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaFileSource.java‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.io.IOException;
2020
import java.nio.file.Path;
2121
import java.time.Duration;
22+
import java.util.Objects;
2223
import java.util.concurrent.atomic.AtomicBoolean;
2324
import java.util.function.Supplier;
2425

@@ -162,6 +163,27 @@ public MediaFileSource(String source, Duration timeout, boolean hardwareDecoding
162163
hardwareDecoding);
163164
}
164165

166+
/**
167+
* Plays the source of a reader opened by the caller, such as one given
168+
* {@link MediaReaderOptions}, decoding its video in hardware where the
169+
* platform can if asked to, as {@link MediaPlayer#MediaPlayer(MediaReader,
170+
* CustomVideoSource, CustomAudioSource, boolean)} describes.
171+
* <p>
172+
* The reader is taken over, and closed with this source, or right away
173+
* if this source cannot be made. It must not be used afterwards.
174+
*
175+
* @param reader An open reader of the source to play.
176+
* @param hardwareDecoding Whether to decode video in hardware if possible.
177+
* HEVC is decoded in hardware regardless.
178+
*
179+
* @throws IOException if the source cannot be decoded.
180+
* @throws IllegalStateException if the reader is closed.
181+
*/
182+
public MediaFileSource(MediaReader reader, boolean hardwareDecoding) throws IOException {
183+
this(Objects.requireNonNull(reader, "Reader is null"), CustomVideoSource::new,
184+
CustomAudioSource::new, hardwareDecoding);
185+
}
186+
165187
/**
166188
* Builds on a reader that is open, which this source takes over whether
167189
* or not it is made. The suppliers make the media sources, which tests

‎webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaReader.java‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.io.IOException;
2020
import java.nio.file.Path;
2121
import java.time.Duration;
22+
import java.util.Objects;
2223

2324
import dev.onvoid.webrtc.internal.Timeouts;
2425

@@ -96,11 +97,30 @@ public MediaReader(String source) throws IOException {
9697
* @throws IllegalArgumentException if the timeout is negative.
9798
*/
9899
public MediaReader(String source, Duration timeout) throws IOException {
100+
this(source, MediaReaderOptions.builder().timeout(timeout).build());
101+
}
102+
103+
/**
104+
* Opens the given media source with the given options: the timeout of
105+
* each operation on it, and how much of it FFmpeg reads to find out what
106+
* its streams hold.
107+
*
108+
* @param source The path or {@code rtsp://} URL of the source to open.
109+
* @param options How to open the source.
110+
*
111+
* @throws IOException if the source cannot be opened in time, or holds
112+
* nothing that can be played.
113+
*/
114+
public MediaReader(String source, MediaReaderOptions options) throws IOException {
115+
Objects.requireNonNull(options, "Options are null");
116+
99117
// Zero is the one timeout without limit: a positive one rounds up to a
100118
// microsecond, and one too long to count is as long as can be counted.
101-
Timeouts.requireNonNegative(timeout, "timeout");
119+
Duration analyzeDuration = options.getAnalyzeDuration();
102120

103-
handle = open(source, Timeouts.toMicros(timeout));
121+
handle = open(source, Timeouts.toMicros(options.getTimeout()),
122+
analyzeDuration != null ? Timeouts.toMicros(analyzeDuration) : 0,
123+
options.getProbeSize());
104124
}
105125

106126
/**
@@ -149,7 +169,8 @@ synchronized long detach() {
149169
return detaching;
150170
}
151171

152-
private static native long open(String source, long timeoutUs) throws IOException;
172+
private static native long open(String source, long timeoutUs, long analyzeDurationUs,
173+
long probeSize) throws IOException;
153174

154175
private static native MediaInfo info(long handle);
155176

0 commit comments

Comments
 (0)