Skip to content

Commit 8bc6fe8

Browse files
committed
docs: add a media files guide and a runnable example
The guide covers adding the module, sending a file with MediaFileSource, reading a source with MediaReader, controlling playback, following it with a listener, and driving your own media sources with MediaPlayer. It says plainly what can be played, that only local files work so far, and that the module is opt-in and built for windows-x86_64 only, so nobody plans around something that is not there yet. MediaFileExample is the same story as code: it opens a file, reports what it contains, makes tracks, adds them to a peer connection and follows playback to the end. Building it needs care, because the examples are a JPMS module and the media module is opt-in. A "requires" cannot be made conditional, and a descriptor naming a module that is not there fails the whole compile, so the example lives in a source directory of its own and is compiled by its own execution into an output directory of its own. That keeps its module descriptor off the sourcepath, leaves the modular build of the other examples untouched, and means a build without the profile does not see the example at all. exec-maven-plugin is pointed at that directory so the command the docs give works as written. When the media module joins the reactor by default, all of it collapses into one dependency and one "requires".
1 parent ddc4c4a commit 8bc6fe8

5 files changed

Lines changed: 565 additions & 0 deletions

File tree

‎docs/.vitepress/sidebar.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] {
2222
{ text: 'Media Devices', link: '/media/media-devices' },
2323
{ text: 'Media Constraints', link: '/media/constraints' },
2424
{ text: 'Media Directionality', link: '/media/directionality' },
25+
{ text: 'Media Files', link: '/media/media-files' },
2526
],
2627
},
2728
{

‎docs/guide/examples.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,27 @@ The [`DesktopVideoExample`](https://github.com/devopvoid/webrtc-java/blob/master
5252

5353
This example is particularly useful for applications that need to implement screen sharing or remote desktop functionality.
5454

55+
## Media File
56+
57+
The [`MediaFileExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/media/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.
58+
59+
**Key features demonstrated:**
60+
- Opening a media file with a `MediaFileSource`
61+
- Reading what the source contains from its `MediaInfo`
62+
- Creating audio and video tracks from the media sources it feeds
63+
- Adding those tracks to a peer connection
64+
- Following playback through a `MediaPlayerListener`
65+
66+
This example is useful for applications that stream pre-recorded media, or that need a dependable stand-in for a camera in testing.
67+
68+
::: warning
69+
This example needs the `webrtc-java-media` module, which is opt-in while it is being brought up on every platform, so it is built and run with the `with-media-extension` profile:
70+
71+
```bash
72+
mvn -Pwith-media-extension exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.MediaFileExample" -D"exec.args=movie.mp4"
73+
```
74+
:::
75+
5576
## Web Client
5677

5778
The [`WebClientExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/web/WebClientExample.java) demonstrates how to combine WebSocket signaling with WebRTC peer connections for real-time communication between web and Java clients.

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

Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
# Media Files
2+
3+
This guide explains how to send a media file over a peer connection instead of a camera and a microphone, using the `webrtc-java-media` module. It covers:
4+
5+
- Adding the media module to a project
6+
- Sending a file with `MediaFileSource`
7+
- Reading what a source contains with `MediaReader` and `MediaInfo`
8+
- Controlling playback and following it with a listener
9+
- Feeding your own media sources with `MediaPlayer`
10+
11+
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.
12+
13+
Decoding happens entirely in native code. Frames never travel through Java: the module hands decoded pictures straight to the native side of a `CustomVideoSource`, and 10 ms chunks to a `CustomAudioSource`. They are paced in real time and carry the presentation times of the file, so what a receiver gets keeps the timing of the media rather than the timing of a Java thread.
14+
15+
::: warning Opt-in while it is being brought up
16+
The media module is not part of the default build yet, and its native library has so far been built for `windows-x86_64` only. Build it with the `with-media-extension` profile, as described below.
17+
:::
18+
19+
## Adding the Module
20+
21+
The module builds FFmpeg from a submodule pinned to a release tag, so the submodule has to be present:
22+
23+
```shell
24+
git submodule update --init --depth 1 webrtc-java-media/third-party/ffmpeg
25+
mvn install -Pwith-media-extension
26+
```
27+
28+
Building FFmpeg needs `make` and `nasm`. On Windows they come from MSYS2:
29+
30+
```shell
31+
winget install MSYS2.MSYS2
32+
C:\msys64\usr\bin\bash -lc "pacman -S --needed make nasm diffutils pkgconf"
33+
```
34+
35+
Maven still runs from an ordinary shell; the build enters MSYS2 and the Visual Studio environment on its own. The first build compiles FFmpeg, which takes a while; later builds reuse the install directory.
36+
37+
Once installed, depend on it alongside `webrtc-java`:
38+
39+
```xml
40+
<dependency>
41+
<groupId>dev.onvoid.webrtc</groupId>
42+
<artifactId>webrtc-java-media</artifactId>
43+
<version>0.19.0-SNAPSHOT</version>
44+
</dependency>
45+
```
46+
47+
The classifier jar carries the module's native library together with the FFmpeg shared libraries it uses. Applications that do not use this module never download FFmpeg.
48+
49+
## Sending a File
50+
51+
`MediaFileSource` is the short way to do all of it. It opens the source, creates a media source for each kind of media the file actually has, and wires a player to feed them:
52+
53+
```java
54+
// Import required classes
55+
import dev.onvoid.webrtc.media.ffmpeg.MediaFileSource;
56+
import dev.onvoid.webrtc.media.audio.AudioTrack;
57+
import dev.onvoid.webrtc.media.video.VideoTrack;
58+
import java.nio.file.Path;
59+
import java.util.List;
60+
61+
MediaFileSource source = new MediaFileSource(Path.of("movie.mp4"));
62+
63+
// Create tracks from the media sources the file feeds.
64+
VideoTrack videoTrack = factory.createVideoTrack("video", source.getVideoSource());
65+
AudioTrack audioTrack = factory.createAudioTrack("audio", source.getAudioSource());
66+
67+
peerConnection.addTrack(videoTrack, List.of("stream"));
68+
peerConnection.addTrack(audioTrack, List.of("stream"));
69+
70+
// Start sending.
71+
source.play();
72+
```
73+
74+
A file with no audio has no audio source, and likewise for video, so check before making a track:
75+
76+
```java
77+
if (source.getVideoSource() != null) {
78+
VideoTrack videoTrack = factory.createVideoTrack("video", source.getVideoSource());
79+
peerConnection.addTrack(videoTrack, List.of("stream"));
80+
}
81+
```
82+
83+
::: warning A factory sends either pushed audio or captured audio
84+
A `PeerConnectionFactory` fed from this module is sending pushed audio and cannot also send audio captured by its `AudioDeviceModule`. Give such a factory a dummy audio layer, and use a second factory if an application needs both:
85+
86+
```java
87+
AudioDeviceModule audioModule = new AudioDeviceModule(AudioLayer.kDummyAudio);
88+
PeerConnectionFactory factory = new PeerConnectionFactory(audioModule);
89+
```
90+
:::
91+
92+
## Reading What a Source Contains
93+
94+
`MediaReader` opens a source and reports what is in it, without playing anything:
95+
96+
```java
97+
// Import required classes
98+
import dev.onvoid.webrtc.media.ffmpeg.MediaInfo;
99+
import dev.onvoid.webrtc.media.ffmpeg.MediaReader;
100+
101+
try (MediaReader reader = new MediaReader(Path.of("movie.mp4"))) {
102+
MediaInfo info = reader.getInfo();
103+
104+
System.out.println("Runs " + info.getDurationUs() / 1_000_000.0 + " s");
105+
106+
if (info.hasVideo()) {
107+
System.out.println(info.getVideoWidth() + "x" + info.getVideoHeight()
108+
+ " at " + info.getFrameRate() + " fps, " + info.getVideoCodec());
109+
}
110+
if (info.hasAudio()) {
111+
System.out.println(info.getSampleRate() + " Hz, "
112+
+ info.getChannels() + " channels, " + info.getAudioCodec());
113+
}
114+
}
115+
```
116+
117+
A `MediaFileSource` already has this, so there is no need to open the file twice:
118+
119+
```java
120+
MediaInfo info = source.getInfo();
121+
```
122+
123+
::: info
124+
Duration is `0` for a source whose container does not say how long it runs, which is the case for live streams. Opening fails if a source holds nothing that can be played.
125+
:::
126+
127+
## Controlling Playback
128+
129+
```java
130+
source.play(); // start, or resume after a pause
131+
source.pause(); // hold playback where it is
132+
source.seek(30_000_000); // move to 30 seconds
133+
source.setLooping(true); // start over instead of ending
134+
source.getPositionUs(); // where playback has got to
135+
source.getState(); // IDLE, PLAYING, PAUSED, ENDED or CLOSED
136+
```
137+
138+
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.
139+
140+
A seek lands on the keyframe at or before the position asked for, which is how far back the decoder has to go to produce a picture at all. How close that is to the position asked for depends on how often the media was encoded with keyframes.
141+
142+
## Following Playback
143+
144+
```java
145+
// Import required classes
146+
import dev.onvoid.webrtc.media.ffmpeg.MediaPlayerListener;
147+
import dev.onvoid.webrtc.media.ffmpeg.MediaPlayerState;
148+
149+
source.setListener(new MediaPlayerListener() {
150+
151+
@Override
152+
public void onStateChanged(MediaPlayerState state) {
153+
System.out.println("Player state: " + state);
154+
}
155+
156+
@Override
157+
public void onEndOfStream() {
158+
System.out.println("The source ran out.");
159+
}
160+
161+
@Override
162+
public void onError(String message) {
163+
System.out.println("Playback failed: " + message);
164+
}
165+
});
166+
```
167+
168+
::: warning
169+
Every call arrives on the player's own thread, and that thread is the one decoding the media. A listener must return promptly, and must not wait on the player.
170+
:::
171+
172+
## Feeding Your Own Media Sources
173+
174+
`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:
175+
176+
```java
177+
// Import required classes
178+
import dev.onvoid.webrtc.media.ffmpeg.MediaPlayer;
179+
import dev.onvoid.webrtc.media.ffmpeg.MediaReader;
180+
import dev.onvoid.webrtc.media.video.CustomVideoSource;
181+
182+
CustomVideoSource videoSource = new CustomVideoSource();
183+
184+
// Video only: passing null for the audio source decodes and drops the audio.
185+
MediaPlayer player = new MediaPlayer(new MediaReader(path), videoSource, null);
186+
187+
VideoTrack videoTrack = factory.createVideoTrack("video", videoSource);
188+
189+
player.play();
190+
```
191+
192+
::: info
193+
The player takes over the reader it is given. That reader must not be used or closed afterwards; closing the player releases it.
194+
:::
195+
196+
## Closing
197+
198+
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:
199+
200+
```java
201+
videoSender.dispose();
202+
audioSender.dispose();
203+
peerConnection.close();
204+
205+
source.close();
206+
```
207+
208+
## What Can Be Played
209+
210+
The FFmpeg build is deliberately small, and carries only what this module plays:
211+
212+
| | |
213+
| --- | --- |
214+
| **Containers** | MP4 and MOV, Matroska and WebM, AVI, MPEG-TS, FLV, WAV, MP3, Ogg, FLAC, AAC |
215+
| **Video** | H.264, H.265/HEVC, VP8, VP9, MPEG-4, MJPEG |
216+
| **Audio** | AAC, MP3, Opus, Vorbis, FLAC, PCM |
217+
218+
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.
219+
220+
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.
221+
222+
## Licensing
223+
224+
The module uses FFmpeg under the LGPL version 2.1 or later. It is configured without `--enable-gpl` and without `--enable-nonfree`, and FFmpeg is linked dynamically and shipped as separate files inside the platform jar, so its libraries may be replaced with your own build, as the LGPL requires. The wrapper code is licensed under the Apache License 2.0 like the rest of webrtc-java.
225+
226+
## Complete Example
227+
228+
See `MediaFileExample` in the `webrtc-examples` module, which opens a file, reports what it contains, creates tracks, adds them to a peer connection and follows playback to the end.
229+
230+
```shell
231+
mvn -Pwith-media-extension -pl webrtc-examples compile
232+
```

‎webrtc-examples/pom.xml‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,75 @@
9494
<version>2.0.18</version>
9595
</dependency>
9696
</dependencies>
97+
98+
<profiles>
99+
<!--
100+
The media example needs webrtc-java-media, which is itself opt-in
101+
while it is being brought up on every platform, so it is built the
102+
same way and under the same profile name. Its source lives in a
103+
directory of its own, so that a build without the profile does not
104+
see it at all and an IDE does not report it as broken.
105+
106+
It is compiled on its own, out of its own source directory and into
107+
an output directory of its own, rather than being added to the
108+
other examples. Those are a JPMS module, the example reads
109+
webrtc.java.media, and a "requires" cannot be made conditional:
110+
naming a module that is not there fails the whole compile. Keeping
111+
the example out of that source tree keeps its module descriptor off
112+
the sourcepath, so this compiles on the class path, which is how an
113+
example is run anyway. Once the media module builds on every
114+
platform and joins the reactor by default, all of this collapses
115+
into one dependency and one "requires".
116+
-->
117+
<profile>
118+
<id>with-media-extension</id>
119+
120+
<build>
121+
<plugins>
122+
<plugin>
123+
<groupId>org.apache.maven.plugins</groupId>
124+
<artifactId>maven-compiler-plugin</artifactId>
125+
<executions>
126+
<execution>
127+
<id>compile-media-example</id>
128+
<phase>compile</phase>
129+
<goals>
130+
<goal>compile</goal>
131+
</goals>
132+
<configuration>
133+
<release>17</release>
134+
<compileSourceRoots>
135+
<compileSourceRoot>${project.basedir}/src/media/java</compileSourceRoot>
136+
</compileSourceRoots>
137+
<outputDirectory>${project.build.directory}/media-classes</outputDirectory>
138+
</configuration>
139+
</execution>
140+
</executions>
141+
</plugin>
142+
143+
<!-- The example is compiled apart from the others, so the
144+
directory it lands in has to be named for a run to
145+
find it. -->
146+
<plugin>
147+
<groupId>org.codehaus.mojo</groupId>
148+
<artifactId>exec-maven-plugin</artifactId>
149+
<version>3.5.0</version>
150+
<configuration>
151+
<additionalClasspathElements>
152+
<additionalClasspathElement>${project.build.directory}/media-classes</additionalClasspathElement>
153+
</additionalClasspathElements>
154+
</configuration>
155+
</plugin>
156+
</plugins>
157+
</build>
158+
159+
<dependencies>
160+
<dependency>
161+
<groupId>${project.groupId}</groupId>
162+
<artifactId>webrtc-java-media</artifactId>
163+
<version>${project.version}</version>
164+
</dependency>
165+
</dependencies>
166+
</profile>
167+
</profiles>
97168
</project>

0 commit comments

Comments
 (0)