Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ The library provides a comprehensive set of Java classes that map to the WebRTC
**Optional modules**

- **[Media playback](https://jrtc.dev/guide/media/media-files)** (`webrtc-java-media`) - Stream video and audio files or RTSP sources into a call, decoded with FFmpeg
- **[Call recording](https://jrtc.dev/guide/media/media-recording)** (`webrtc-java-media`) - Save what a call sends or receives into MKV, WebM or MP4 files, without re-encoding
- **[Call recording](https://jrtc.dev/guide/media/media-recording)** (`webrtc-java-media`) - Save what a call sends or receives into MKV, WebM or MP4 files, without re-encoding, as one file, rotating segments, or a replay buffer of the last seconds

**Platforms**

Expand Down
2 changes: 1 addition & 1 deletion docs/guide/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ This section provides detailed guides for various features of the webrtc-java li
- [Bitrate and Framerate Constraints](/guide/media/constraints) - Controlling media quality
- [Send-only and Receive-only](/guide/media/directionality) - Configure transceiver directions (send-only, receive-only or inactive)
- [Media Files](/guide/media/media-files) - Sending video and audio files instead of a camera and microphone
- [Media Recording](/guide/media/media-recording) - Recording what a call sends or receives into a media file, without re-encoding
- [Media Recording](/guide/media/media-recording) - Recording what a call sends or receives into a media file, into rotating segments, or into a replay buffer, without re-encoding

## Audio

Expand Down
62 changes: 62 additions & 0 deletions docs/guide/media/media-recording.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ This guide explains how to record what a peer connection sends or receives into
- Recording senders and receivers
- Replacing a file that exists
- Choosing the container
- Splitting a recording into segments, and how many to keep
- Keeping the last seconds in memory and saving them on demand
- Following a recording with a listener
- How tracks are started, timed and left out
- Measuring what a recording lost
Expand Down Expand Up @@ -92,6 +94,66 @@ A name FFmpeg does not know gets Matroska. A track whose codec the file cannot h

Matroska has no codec ID of its own for G.711, so it is stored as Windows audio (`A_MS/ACM`), the way FFmpeg itself stores it. Players built on FFmpeg, such as VLC and mpv, play it; some others do not.

## Recording in Segments

For recordings that run for hours, such as surveillance or support sessions, a recorder can split the recording into segments: files that each play on their own, ended by duration or size, of which it keeps as many as asked.

```java
SegmentOptions segments = SegmentOptions.builder(Paths.get("recordings", "camera-%05d.mkv"))
.maxDuration(Duration.ofMinutes(10)) // end a segment after 10 minutes,
.maxSize(512L * 1024 * 1024) // or once it holds 512 MB
.maxTotalSize(20L * 1024 * 1024 * 1024) // keep the newest 20 GB
.build();

try (MediaRecorder recorder = new MediaRecorder(segments)) {
recorder.setListener(new MediaRecorderListener() {

@Override
public void onSegmentFinished(MediaRecorderSegment segment) {
upload(segment.getFile());
}
});
recorder.addTrack(videoReceiver);
recorder.addTrack(audioReceiver);
recorder.start();

// ...
}
```

The file name of the pattern holds the segment's number as `%d`, or zero-padded as `%05d`; a literal percent sign is `%%`. The extension picks the container of all segments, as for a single file. Numbering goes on from the highest number already in the directory, so a recorder started again continues after the last segment, and a segment never empties a file that exists: its number is skipped instead.

- **Every segment begins at a key frame.** Once a segment has reached its duration or size, the recorder asks the video tracks for key frames, and the next segment begins with the first that arrives, usually a fraction of a second later. A segment is therefore somewhat longer or larger than the limit. Without video, a segment ends right at the limit.
- **Several video tracks lose nothing.** A video track whose key frame comes after the one that began the next segment goes on in the segment before until then, so neither file has a gap. One that sends no key frame within three seconds starts the new segment at its next.
- **Each segment starts at zero.** Its tracks are shifted by the same amount, so they stay in sync, and one segment follows the other without a gap. `MediaRecorderSegment.getStart()` tells where a segment lies in the recording.
- **A codec change starts a segment.** A file cannot change the codec of a stream, so a track that changes its codec, e.g. after a renegotiation, goes on in the next segment, which begins as soon as the new codec is known. A single file leaves such a track out from then on instead.
- **A slow disk holds nothing up.** Segments are finished and opened by the recorder's writer thread, with the frames queuing up meanwhile as always, and old segments are deleted on the listener's thread.

`onSegmentFinished` hears of every segment once it is finished and closed, the last one when the recorder stops. Right after it returns, the oldest segments beyond `maxSegments` or `maxTotalSize` are deleted, so a segment to be kept for longer has to be moved or copied by then. The newest segment is always kept, and the one being written does not count toward `maxTotalSize`, so the recording takes up to that much and one segment more. `getSegments()` lists the segments that are kept, and `getFile()` returns the last one finished.

A write that fails, e.g. because the disk is full, ends the recording as it does for a single file. The segment it happened in is kept as `PARTIAL` if it holds media; one that failed before any went into it is deleted.

## Replay Buffer

A `ReplayBuffer` keeps the last seconds of a call in memory and writes them into a file only when asked, for "save the last 30 seconds":

```java
try (ReplayBuffer buffer = new ReplayBuffer(Duration.ofSeconds(30))) {
buffer.addTrack(videoReceiver);
buffer.addTrack(audioReceiver);
buffer.start();

// ... something happens worth keeping ...

buffer.save(Paths.get("incident.mkv"))
.thenAccept(replay -> System.out.println("Saved " + replay.getDuration()));
}
```

`save` creates the file at once, refusing one that exists, and the buffer's own thread writes the replay, while the buffer goes on taking frames. The future completes on the listener's thread with a `MediaRecorderSegment`, or exceptionally if nothing could be saved, and the file is then deleted. A buffer can save any number of replays, in any container; a track whose codec the container cannot hold is left out of that replay with a warning.

A replay begins with a key frame of every video track: the last one before the window, so a replay holds at least the window, and a few seconds more. Since WebRTC rarely sends key frames of its own accord, the buffer asks its video tracks for one every third of the window, at least every two seconds and at most every ten. Besides the window, the buffer holds at most 256 MB, or what its constructor is given; beyond that, the oldest frames go first, and a replay is shorter. A track that changes its codec is kept with the new codec from then on.

## Following a Recording

A `MediaRecorderListener` hears when the file begins, what was left out, and whether writing failed:
Expand Down
24 changes: 24 additions & 0 deletions webrtc-media/src/main/cpp/include/JNI_MediaRecorder.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,22 @@ extern "C" {
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_recorder_MediaRecorder_create
(JNIEnv *, jobject, jstring, jlong);

/*
* Class: dev_onvoid_webrtc_media_recorder_MediaRecorder
* Method: createSegments
* Signature: (Ljava/lang/String;Ljava/lang/String;IJJJJ)J
*/
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_recorder_MediaRecorder_createSegments
(JNIEnv *, jobject, jstring, jstring, jint, jlong, jlong, jlong, jlong);

/*
* Class: dev_onvoid_webrtc_media_recorder_MediaRecorder
* Method: createReplay
* Signature: (JJJ)J
*/
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_recorder_MediaRecorder_createReplay
(JNIEnv *, jobject, jlong, jlong, jlong);

/*
* Class: dev_onvoid_webrtc_media_recorder_MediaRecorder
* Method: addTrack
Expand Down Expand Up @@ -62,6 +78,14 @@ extern "C" {
JNIEXPORT jlongArray JNICALL Java_dev_onvoid_webrtc_media_recorder_MediaRecorder_stats
(JNIEnv *, jclass, jlong);

/*
* Class: dev_onvoid_webrtc_media_recorder_MediaRecorder
* Method: saveReplay
* Signature: (JILjava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_media_recorder_MediaRecorder_saveReplay
(JNIEnv *, jclass, jlong, jint, jstring);

/*
* Class: dev_onvoid_webrtc_media_recorder_MediaRecorder
* Method: dispose
Expand Down
36 changes: 36 additions & 0 deletions webrtc-media/src/main/cpp/include/JNI_RecordingProbe.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* 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.h>
/* Header for class dev_onvoid_webrtc_media_recorder_RecordingProbe */

#ifndef _Included_dev_onvoid_webrtc_media_recorder_RecordingProbe
#define _Included_dev_onvoid_webrtc_media_recorder_RecordingProbe
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: dev_onvoid_webrtc_media_recorder_RecordingProbe
* Method: streams
* Signature: (Ljava/lang/String;)[J
*/
JNIEXPORT jlongArray JNICALL Java_dev_onvoid_webrtc_media_recorder_RecordingProbe_streams
(JNIEnv *, jclass, jstring);

#ifdef __cplusplus
}
#endif
#endif
4 changes: 2 additions & 2 deletions webrtc-media/src/main/cpp/include/JNI_WriteFault.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ extern "C" {
/*
* Class: dev_onvoid_webrtc_media_recorder_WriteFault
* Method: failHeader
* Signature: ()V
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_recorder_WriteFault_failHeader
(JNIEnv *, jclass);
(JNIEnv *, jclass, jint);

/*
* Class: dev_onvoid_webrtc_media_recorder_WriteFault
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ namespace ffmpeg
void OnWarning(const std::string & message) override;
void OnError(const std::string & message) override;
void OnKeyFrameNeeded(int track) override;
void OnSegmentFinished(int64_t index, const std::string & path,
int64_t start_us, int64_t duration_us, int result) override;
void OnReplaySaved(int id, int result, int64_t start_us,
int64_t duration_us, const std::string & error) override;

private:
// Calls a void Java method taking one String.
Expand All @@ -69,6 +73,8 @@ namespace ffmpeg
jmethodID on_warning_ = nullptr;
jmethodID on_error_ = nullptr;
jmethodID on_key_frame_needed_ = nullptr;
jmethodID on_segment_finished_ = nullptr;
jmethodID on_replay_saved_ = nullptr;
};
}

Expand Down
Loading
Loading