Skip to content

Commit ff5dc66

Browse files
committed
feat: play RTSP streams, with timeouts and interruptible reads
A source can now be a live stream behind an rtsp:// URL, such as an IP camera's, as well as a local file. The FFmpeg build enables networking, the RTSP demuxer and the RTP, UDP and TCP protocols. FFmpeg asks for RTP over UDP first and falls back to TCP, interleaved on the RTSP connection, when the server refuses UDP or nothing arrives. A network source can stall or vanish, so every call that waits on one now runs under a deadline, enforced through FFmpeg's interrupt callback: opening, probing, each read, seeking and closing. Running out of time reads as a timeout. The timeout is 10 seconds unless another is passed to MediaReader or MediaFileSource. Closing a player interrupts its reader first, so it never waits on a stalled stream, and the error that interruption causes is not reported to the listener. Every source is opened with a protocol whitelist. The RTSP demuxer brings the HTTP protocol along for tunnelling, and a URL passed on from a user must not be able to fetch through it. Testing against a server showed three more things to fix. An error opening a source quoted its URL, password included, and now leaves the credentials out. A looping player ignored a failed rewind, so a live stream that ended while looping reported a connection error; a source that cannot rewind now simply ends. And network errors read as bare numbers on Windows, where the C runtime has no words for them and FFmpeg passes most Winsock codes through; the common ones are now named, in a single helper that replaces three copies. The examples take stream URLs as well: the player shows a stream's URL without its credentials and disables looping for a live source, and both describe how to run them against a camera. The Media Files guide covers live streams, their timeouts and their limits. RtspStreamTest plays against a small RTSP server in the test sources, which refuses UDP and streams PCM audio over TCP.
1 parent 5075f7e commit ff5dc66

17 files changed

Lines changed: 1100 additions & 90 deletions

File tree

‎docs/guide/examples.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,37 +57,38 @@ This example is particularly useful for applications that need to implement scre
5757
The [`MediaFileExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFileExample.java) demonstrates how to send a media file over a peer connection, in place of a camera and a microphone. See the [Media Files](/guide/media/media-files) guide for the API it uses.
5858

5959
**Key features demonstrated:**
60-
- Opening a media file with a `MediaFileSource`
60+
- Opening a media file, or a live RTSP stream, with a `MediaFileSource`
6161
- Reading what the source contains from its `MediaInfo`
6262
- Creating audio and video tracks from the media sources it feeds
6363
- Adding those tracks to a peer connection
6464
- Following playback through a `MediaPlayerListener`
6565

66-
This example is useful for applications that stream pre-recorded media, or that need a dependable stand-in for a camera in testing.
66+
This example is useful for applications that stream pre-recorded media, relay an IP camera into WebRTC, or need a dependable stand-in for a camera in testing.
6767

6868
::: info
6969
This example needs the `webrtc-java-media` module, which builds FFmpeg from the `third-party/ffmpeg` submodule. Make sure the submodule is checked out before building, as the [Media Files](/guide/media/media-files) guide describes.
7070

7171
```bash
7272
mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.MediaFileExample" -D"exec.args=movie.mp4"
73+
mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.MediaFileExample" -D"exec.args=rtsp://camera.local/stream1"
7374
```
7475
:::
7576

7677
## Media File Player
7778

78-
The [`MediaFilePlayerExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFilePlayerExample.java) is a Swing application that sends a media file from one peer connection to another in the same process, then shows the received video and plays the received audio in sync. Start and Stop buttons set up and tear down the whole session.
79+
The [`MediaFilePlayerExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFilePlayerExample.java) is a Swing application that sends a media file, or a live RTSP stream, from one peer connection to another in the same process, then shows the received video and plays the received audio in sync. Start and Stop buttons set up and tear down the whole session.
7980

8081
**Key features demonstrated:**
8182
- Connecting two peer connections in one application, without a signaling server
8283
- Using one factory with a dummy audio layer to send the file, and another with the platform audio layer to play what is received
8384
- Keeping audio and video in sync by sending both tracks in the same media stream
8485
- Raising the video sender's `maxBitrate` above WebRTC's default, so a high-resolution file is not held to a fraction of its size
8586
- Rendering received video frames in a Swing component with `VideoBufferConverter`
86-
- Showing the file's format, the playback position, and live receive metrics (codec, resolution, frame rate, bitrate, packet loss, jitter, audio level) read from `getStats()`
87+
- Showing the source's format, the playback position, and live receive metrics (codec, resolution, frame rate, bitrate, packet loss, jitter, audio level) read from `getStats()`
8788
- Releasing senders, peer connections, tracks and the source in order on Stop
8889

8990
::: info
90-
Like the [Media File](#media-file) example, this one needs the `webrtc-java-media` module. The file argument is optional; a file can also be chosen from the window.
91+
Like the [Media File](#media-file) example, this one needs the `webrtc-java-media` module. The source argument is optional; a file can also be chosen from the window, or a stream URL typed into it. A stream URL's credentials are never shown, and the Loop box is disabled while a live stream plays, since it has no length to start over from.
9192

9293
```bash
9394
mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.MediaFilePlayerExample" -D"exec.args=movie.mp4"

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ This guide explains how to send a media file over a peer connection instead of a
77
- Reading what a source contains with `MediaReader` and `MediaInfo`
88
- Controlling playback and following it with a listener
99
- Feeding your own media sources with `MediaPlayer`
10+
- Playing a live stream from an IP camera or media server over RTSP
1011

1112
Sending a file is a common need: a test pattern instead of a webcam, a pre-recorded briefing, a video that has to reach several participants. Without help, an application has to bring its own decoder and push I420 frames into a `CustomVideoSource` itself. The media module removes that work by decoding with [FFmpeg](https://ffmpeg.org) inside the library.
1213

@@ -203,6 +204,29 @@ The player takes over the reader it is given. That reader must not be used or cl
203204
It also keeps the native side of the media sources it feeds alive until it is closed, so disposing of a source or its track while the player runs is safe.
204205
:::
205206

207+
## Playing a Live Stream
208+
209+
A source can also be a live stream behind an `rtsp://` URL, which is what IP cameras, video recorders and most media servers offer. Everything above works the same way; only the URL differs:
210+
211+
```java
212+
MediaFileSource source = new MediaFileSource("rtsp://camera.local:554/stream1");
213+
```
214+
215+
Credentials go into the URL, as `rtsp://user:password@camera.local/stream1`. FFmpeg first asks the server for RTP over UDP, and falls back to RTP interleaved on the RTSP connection over TCP if the server refuses UDP or no UDP packets arrive, which is what gets a stream through most firewalls.
216+
217+
A network source can stall or disappear, so every operation that waits on a source has a time limit: opening it, and then each read during playback. It is 10 seconds unless you pass another:
218+
219+
```java
220+
// Import required classes
221+
import java.time.Duration;
222+
223+
MediaFileSource source = new MediaFileSource("rtsp://camera.local/stream1", Duration.ofSeconds(5));
224+
```
225+
226+
An unreachable server makes the constructor throw an `IOException` once that time is up. A stream that stops sending during playback is reported to the listener's `onError`, and the player is left `PAUSED`. Closing a player never waits for the time limit: it breaks off whatever the player is waiting for at once.
227+
228+
A live stream has no end and no length: its `MediaInfo` reports a duration of 0, looping does not apply, and seeking is reported as an error. 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. To get back to live, close the source and open it again.
229+
206230
## Closing
207231

208232
Closing a `MediaFileSource` stops playback and releases the player along with both media sources. Release the senders a peer connection handed out, and the tracks, before that:
@@ -227,7 +251,7 @@ The FFmpeg build is deliberately small, and carries only what this module plays:
227251

228252
Audio of any rate or layout is resampled to what WebRTC takes, which is 48 kHz 16-bit PCM in mono or stereo. Video that decodes to I420 — almost all 8-bit H.264, VP8, VP9 and MPEG-4 — reaches the encoder without being copied; anything else is converted first.
229253

230-
Only local files play today. FFmpeg demuxes network sources just as well, so the same code will cover http, rtsp and rtmp once those protocols are turned on in the build.
254+
Sources can be local files, or live streams over RTSP (`rtsp://`), with RTP over UDP or TCP. Protocols that need TLS, such as `rtsps://` and `https://`, are not part of the build, and neither are HLS, DASH and RTMP. A source cannot reach any other protocol either, even one FFmpeg uses internally, so a URL passed on from a user cannot make the module fetch something else.
231255

232256
## Licensing
233257

‎webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFileExample.java‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
* <p>
4747
* This example shows how to:
4848
* <ul>
49-
* <li>Open a media file or network stream with a MediaFileSource</li>
49+
* <li>Open a media file, or a live RTSP stream, with a MediaFileSource</li>
5050
* <li>Read what the source contains from its MediaInfo</li>
5151
* <li>Create audio and video tracks from the sources it feeds</li>
5252
* <li>Add those tracks to a peer connection</li>
@@ -61,23 +61,23 @@
6161
* reach a remote peer through a signaling channel, as
6262
* {@link PeerConnectionExample} shows.
6363
* <p>
64-
* Run it with the media file to send:
64+
* Run it with the media file or stream URL to send:
6565
* <pre>
6666
* java dev.onvoid.webrtc.examples.MediaFileExample movie.mp4
67+
* java dev.onvoid.webrtc.examples.MediaFileExample rtsp://camera.local/stream1
6768
* </pre>
68-
* <p>
69-
* Only local files play today. FFmpeg demuxes network sources just as well,
70-
* so the same code covers http, rtsp and rtmp once those protocols are turned
71-
* on in the build.
69+
* A stream that cannot be reached, or stops sending, is given up on after the
70+
* reader's timeout, 10 seconds unless another is passed to the source.
7271
*
7372
* @author Alex Andres
7473
*/
7574
public class MediaFileExample {
7675

7776
public static void main(String[] args) {
7877
if (args.length < 1) {
79-
System.out.println("Usage: MediaFileExample <media-file>");
78+
System.out.println("Usage: MediaFileExample <media-file | rtsp-url>");
8079
System.out.println(" for example: MediaFileExample movie.mp4");
80+
System.out.println(" or: MediaFileExample rtsp://camera.local/stream1");
8181
return;
8282
}
8383

@@ -144,7 +144,13 @@ public void onError(String message) {
144144
}
145145

146146
private static void printInfo(MediaInfo info) {
147-
System.out.printf("Source runs %.3f s%n", info.getDurationUs() / 1_000_000.0);
147+
if (info.getDurationUs() > 0) {
148+
System.out.printf("Source runs %.3f s%n", info.getDurationUs() / 1_000_000.0);
149+
}
150+
else {
151+
// A live stream, which has no length.
152+
System.out.println("Source is live");
153+
}
148154

149155
if (info.hasVideo()) {
150156
System.out.printf(" video: %dx%d at %.2f fps, %s%n", info.getVideoWidth(),

‎webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFilePlayerExample.java‎

Lines changed: 44 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,10 @@
9393
import dev.onvoid.webrtc.media.video.VideoTrackSink;
9494

9595
/**
96-
* Desktop UI counterpart to {@link MediaFileExample}: plays a media file
97-
* through a pair of peer connections that live in the same application, and
98-
* shows the received video while the received audio plays on the speakers.
96+
* Desktop UI counterpart to {@link MediaFileExample}: plays a media file, or
97+
* a live stream from an {@code rtsp://} URL such as an IP camera's, through a
98+
* pair of peer connections that live in the same application, and shows the
99+
* received video while the received audio plays on the speakers.
99100
* <p>
100101
* This example shows how to:
101102
* <ul>
@@ -119,10 +120,12 @@
119120
* media stream: the receiver lines them up with each other before handing
120121
* them on, so the video sink only has to draw each frame as it arrives.
121122
* <p>
122-
* Run it with an optional media file to preselect:
123+
* Run it with an optional media file or stream URL to preselect:
123124
* <pre>
124125
* java dev.onvoid.webrtc.examples.MediaFilePlayerExample movie.mp4
126+
* java dev.onvoid.webrtc.examples.MediaFilePlayerExample rtsp://camera.local/stream1
125127
* </pre>
128+
* A live stream has no length, so the Loop box is disabled while one plays.
126129
*
127130
* @author Alex Andres
128131
*/
@@ -155,7 +158,7 @@ public class MediaFilePlayerExample {
155158
return thread;
156159
});
157160

158-
private final JFrame frame = new JFrame("Media File Player");
161+
private final JFrame frame = new JFrame("Media Player");
159162
private final JTextField fileField = new JTextField(32);
160163
private final JButton browseButton = new JButton("Browse...");
161164
private final JButton startButton = new JButton("Start");
@@ -182,6 +185,26 @@ public static void main(String[] args) {
182185
});
183186
}
184187

188+
/**
189+
* A short name for a source: a file's name, or a stream URL without the
190+
* credentials it may carry.
191+
*/
192+
private static String sourceName(String source) {
193+
return source.contains("://") ? withoutCredentials(source) : new File(source).getName();
194+
}
195+
196+
/**
197+
* The given source without the user name and password a URL can carry in
198+
* front of its host, so that it can be shown. Anything else, a file path
199+
* included, is returned as it is.
200+
*/
201+
private static String withoutCredentials(String source) {
202+
// Everything between the scheme and the last @ before the path. Not
203+
// parsed as a URI: a password is free to hold characters a URI
204+
// parser rejects, and then it would be shown after all.
205+
return source.replaceFirst("://[^/?#]*@", "://");
206+
}
207+
185208
/**
186209
* Makes the window look like the platform's own applications rather than
187210
* Swing's cross-platform default. It has to happen before the first
@@ -207,6 +230,7 @@ private MediaFilePlayerExample() {
207230

208231
private void show(String file) {
209232
fileField.setText(file);
233+
fileField.setToolTipText("A media file, or an rtsp:// stream URL");
210234

211235
browseButton.addActionListener(e -> chooseFile());
212236
startButton.addActionListener(e -> start());
@@ -270,7 +294,7 @@ private void chooseFile() {
270294
private void start() {
271295
String file = fileField.getText().trim();
272296
if (file.isEmpty()) {
273-
statusLabel.setText("Choose a media file first.");
297+
statusLabel.setText("Choose a media file or enter an rtsp:// URL first.");
274298
return;
275299
}
276300

@@ -285,7 +309,12 @@ private void start() {
285309
Session started = new Session(file, looping);
286310
session = started;
287311

288-
SwingUtilities.invokeLater(() -> metricsPanel.showMedia(file, started.info));
312+
SwingUtilities.invokeLater(() -> {
313+
metricsPanel.showMedia(file, started.info);
314+
315+
// Only a source with a length can start over.
316+
loopBox.setEnabled(started.info.getDurationUs() > 0);
317+
});
289318
}
290319
catch (Exception e) {
291320
LOG.log(Level.SEVERE, "Could not start playback", e);
@@ -354,6 +383,10 @@ private void setRunning(boolean running) {
354383
fileField.setEnabled(!running);
355384
browseButton.setEnabled(!running);
356385

386+
if (!running) {
387+
loopBox.setEnabled(true);
388+
}
389+
357390
if (running) {
358391
statusTimer.start();
359392
statsTimer.start();
@@ -906,7 +939,7 @@ private static class MetricsPanel extends JPanel {
906939
setPreferredSize(new Dimension(320, 0));
907940

908941
addSection("Media");
909-
addRow("media.file", "File");
942+
addRow("media.file", "Source");
910943
addRow("media.duration", "Duration");
911944
addRow("media.video", "Video");
912945
addRow("media.audio", "Audio");
@@ -941,8 +974,9 @@ private static class MetricsPanel extends JPanel {
941974
}
942975

943976
void showMedia(String file, MediaInfo info) {
944-
set("media.file", new File(file).getName());
945-
values.get("media.file").setToolTipText(file);
977+
set("media.file", sourceName(file));
978+
// Never the source as typed: a stream URL may carry a password.
979+
values.get("media.file").setToolTipText(withoutCredentials(file));
946980
set("media.duration", info.getDurationUs() > 0
947981
? formatTime(info.getDurationUs()) : "unknown");
948982
set("media.video", info.hasVideo()

‎webrtc-java-media/src/main/cpp/dependencies/ffmpeg/CMakeLists.txt‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ set(FFMPEG_COMPONENTS
4848
--enable-demuxer=mp3
4949
--enable-demuxer=ogg
5050
--enable-demuxer=flac
51+
# Live streams from IP cameras and media servers. The RTSP demuxer brings
52+
# the RTP depacketizers along, and with them the demuxers of the formats
53+
# RTP can carry (ASF, MOV, MPEG-TS, RealMedia), as well as the HTTP
54+
# protocol for RTSP tunnelled over HTTP.
55+
--enable-demuxer=rtsp
5156
--enable-demuxer=aac
5257
# Video this module decodes.
5358
--enable-decoder=h264
@@ -93,10 +98,13 @@ set(FFMPEG_COMPONENTS
9398
--enable-parser=opus
9499
--enable-parser=vorbis
95100
--enable-parser=flac
96-
# Local files only for now; network protocols follow once the TLS
97-
# backends are wired up per platform.
101+
# Local files, and what RTSP runs over. Protocols that need TLS are left
102+
# out until a TLS backend is chosen per platform.
98103
--enable-protocol=file
99104
--enable-protocol=pipe
105+
--enable-protocol=rtp
106+
--enable-protocol=udp
107+
--enable-protocol=tcp
100108
)
101109

102110
# Written next to an install once it is built, naming the components it was
@@ -273,7 +281,6 @@ else()
273281
--disable-programs
274282
--disable-avdevice
275283
--disable-avfilter
276-
--disable-network
277284
--disable-everything
278285
--disable-autodetect
279286
${FFMPEG_COMPONENTS}

‎webrtc-java-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
28+
* Signature: (Ljava/lang/String;J)J
2929
*/
3030
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_player_MediaReader_open
31-
(JNIEnv *, jclass, jstring);
31+
(JNIEnv *, jclass, jstring, jlong);
3232

3333
/*
3434
* Class: dev_onvoid_webrtc_media_player_MediaReader
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
#ifndef WEBRTC_JAVA_MEDIA_ERROR_TEXT_H_
18+
#define WEBRTC_JAVA_MEDIA_ERROR_TEXT_H_
19+
20+
#include <string>
21+
22+
namespace ffmpeg
23+
{
24+
// What a negative AVERROR code means, in words, for messages that reach
25+
// Java. FFmpeg describes most codes itself, but leaves plain errno codes
26+
// to the C runtime, and on Windows that has no words for some of the
27+
// ones networking produces, such as a timeout.
28+
std::string ErrorText(int error);
29+
}
30+
31+
#endif

0 commit comments

Comments
 (0)