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
47 changes: 44 additions & 3 deletions docs/guide/media/media-recording.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
This guide explains how to record what a peer connection sends or receives into a media file with `MediaRecorder`, from the `webrtc-java-media` module. It covers:

- Recording senders and receivers
- Replacing a file that exists
- Choosing the container
- Following a recording with a listener
- How tracks are started, timed and left out
- Measuring what a recording lost
- Recording an end-to-end encrypted call

`MediaRecorder` writes the encoded frames of each sender or receiver into the file as they are, without decoding or re-encoding them. A recording therefore costs next to no CPU, keeps exactly the quality that went over the network, and needs no codec at all, only the container. The frames are taken in native code, straight from WebRTC, and written by a thread of the recorder's own, so neither Java nor a slow disk ever holds up the call.
Expand All @@ -30,14 +32,14 @@ try (MediaRecorder recorder = new MediaRecorder(Paths.get("call.mkv"))) {

A sender's frames are recorded as they leave the encoder, a receiver's as they go to the decoder. Senders and receivers of any number of peer connections can go into one file, e.g. both sides of a call.

`stop()` waits until everything received so far is written and the file is finished and closed, and returns whether the file holds a recording. A recorder that never got any media to write deletes its file rather than leave an unplayable one behind. `close()` stops a recording that still runs.
`stop()` waits until everything received so far is written and the file is finished and closed, and returns whether the recording was kept. A recorder that never got any media to write deletes what it wrote rather than leave an unplayable file behind. `close()` stops a recording that still runs.

How the recording ended, `getResult()` tells once the recorder is stopped, and keeps telling after `close()`:

| Result | File | Meaning |
| --- | --- | --- |
| `COMPLETE` | kept | Everything was written, and the file was finished and closed. |
| `PARTIAL` | kept | Media went into the file, but writing, finishing or closing it failed later. What made it into the file is kept, since it may still play. |
| `PARTIAL` | kept | Media went into the file, but writing, finishing or closing it failed later, or it could not [replace an existing file](#replacing-a-file). What made it into the file is kept, since it may still play. |
| `EMPTY` | deleted | No media arrived before the stop. |
| `FAILED` | deleted | Writing failed before any media went into the file. |

Expand All @@ -62,6 +64,20 @@ recorder.addTrack(remoteTrack); // a RemoteTrack from peer.onTrack

The peer keeps its native senders and receivers to itself and asks them for key frames on its own thread, so nothing needs to be kept undisposed: removing a sender or closing the peer ends the track in the recording, and `stop()` still finishes the file.

## Replacing a File

A recorder does not touch a file that exists: its constructor throws a `FileAlreadyExistsException`, so a new recording cannot cost an earlier one by accident. To replace the file, ask for it:

```java
try (MediaRecorder recorder = new MediaRecorder(Paths.get("call.mkv"), true)) {
// ...
}
```

The recording then goes into a temporary file beside it, named `.recording-<id>.mkv`, and the existing file stays untouched until `stop()` has finished the recording. Only then does the recording take its place, in one step, with the permissions of the file it replaces, and a symbolic link stays a link to the new recording. A recording that gets no media, or fails before any went into the file, leaves the existing file as it was.

If the process ends before the stop, the existing file is still there, next to the temporary file with what was recorded so far. If the recording cannot take the place of the existing file when it stops, it stays in the temporary file: `onError` is told, the result is `PARTIAL`, and `getFile()` returns where it is.

## Containers

The container follows the file name:
Expand Down Expand Up @@ -112,7 +128,32 @@ Running out of native memory while writing ends the recording the same way: `onE
- **The file begins once the tracks are known.** The file header describes every stream, and a stream is only known from its first frames. The file begins once every track has sent some, or once the tracks that have waited three seconds for the rest. A track that sends nothing by then is left out, with a warning.
- **Tracks share one timeline.** Each track is placed by when its first frame arrived, and follows its own RTP timestamps from there, so its timing is exact. The tracks of one sender line up within the jitter of the network.
- **One simulcast layer.** A sender with simulcast is recorded at the layer whose frames reach the recorder first.
- **Nothing is lost to a slow disk, up to a point.** Frames queue up in memory for the writer, up to 64 MB. Beyond that, frames are dropped, and video starts over at the next key frame.
- **Nothing is lost to a slow disk, up to a point.** Frames queue up in memory for the writer, up to 64 MB. Beyond that, frames are dropped, and video starts over at the next key frame. `getStats()` [tells how much that cost](#measuring-what-was-lost).

## Measuring What Was Lost

A result of `COMPLETE` means that everything the recorder took went into the file. It says nothing about frames it had to drop before that, and a video gap can come from a single one, since video only goes on from the next key frame. `getStats()` tells what happened, per track and in the order the tracks were added. It can be asked at any time, also after `close()`:

```java
MediaRecorderStats stats = recorder.getStats();

for (MediaRecorderStats.Track track : stats.getTracks()) {
if (track.getDroppedFrames() > 0) {
System.out.println("Lost " + track.getDroppedFrames() + " frames");
}
}

System.out.println("Queue peak: " + stats.getMaxQueuedBytes() + " bytes");
```

| Value | Meaning |
| --- | --- |
| `getDroppedQueueFull()` | Frames dropped because the writer did not keep up and its queue was full. |
| `getDroppedAllocationFailed()` | Frames dropped because there was no memory to copy them. |
| `getDroppedAwaitingKeyFrame()` | Video frames dropped on the way to the next key frame, since nothing could decode them after what was lost before. |
| `getDroppedFrames()` | All of these together. |

`getMaxQueuedBytes()` is the most that ever waited for the writer, of all tracks together, and shows how close a recording came to the limit of 64 MB. Frames a track was never meant to record do not count, such as those before its first key frame or those of another simulcast layer.

## Recording an Encrypted Call

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,8 @@ public static void main(String[] args) throws Exception {
* they decrypted.
*/
private static void record(Path file, RemoteTrack video, RemoteTrack audio) throws Exception {
try (MediaRecorder recorder = new MediaRecorder(file)) {
// Replaces what an earlier run recorded, once this one is finished.
try (MediaRecorder recorder = new MediaRecorder(file, true)) {
recorder.setListener(new MediaRecorderListener() {

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

#include "JavaContext.h"

#include <new>

namespace jni
{
JavaContext::JavaContext(JavaVM * vm) :
Expand All @@ -24,6 +26,12 @@ namespace jni
auto className = JavaClassUtils::toNativeClassName(env, javaRef);
NativeRef entry = { JavaGlobalRef<jobject>(env, javaRef.get()), owner, kind, nativeRef };

// Out of memory, which NewGlobalRef reports by returning null. An
// entry without its Java object could never be found again.
if (entry.javaRef.get() == nullptr) {
throw std::bad_alloc();
}

std::lock_guard<std::mutex> lock(objectMapMutex);

objectMap[className].push_back(std::move(entry));
Expand Down
45 changes: 45 additions & 0 deletions webrtc-jni/src/main/cpp/include/AllocationFault.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* 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.
*/

#ifndef JNI_WEBRTC_ALLOCATION_FAULT_H_
#define JNI_WEBRTC_ALLOCATION_FAULT_H_

namespace jni
{
// Makes an allocation fail on purpose, so that the tests can see what the
// code around it does when memory runs out, which it does not on demand.
//
// Only the tests arm it, through JNI_AllocationFault. A check that is not
// armed pays a single atomic load.
class AllocationFault
{
public:
// Fails the next registration of a track listener, once, after the
// track got its observer and before the observer has an owner.
static void FailNextListener();
// Fails the next encoded_observer_add() of the extension API, once,
// as an allocation for its handle does.
static void FailNextEncodedObserver();
// Forgets a fault that has not fired.
static void Disarm();
// Throws std::bad_alloc if a fault is armed, and disarms it.
static void CheckListener();
// The same for an encoded observer.
static void CheckEncodedObserver();
};
}

#endif
76 changes: 76 additions & 0 deletions webrtc-jni/src/main/cpp/include/JNI_AllocationFault.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* 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_internal_AllocationFault */

#ifndef _Included_dev_onvoid_webrtc_internal_AllocationFault
#define _Included_dev_onvoid_webrtc_internal_AllocationFault
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: dev_onvoid_webrtc_internal_AllocationFault
* Method: failNextListener
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_failNextListener
(JNIEnv *, jclass);

/*
* Class: dev_onvoid_webrtc_internal_AllocationFault
* Method: failNextEncodedObserver
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_failNextEncodedObserver
(JNIEnv *, jclass);

/*
* Class: dev_onvoid_webrtc_internal_AllocationFault
* Method: addEncodedObserver
* Signature: (J)J
*/
JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_addEncodedObserver
(JNIEnv *, jclass, jlong);

/*
* Class: dev_onvoid_webrtc_internal_AllocationFault
* Method: removeEncodedObserver
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_removeEncodedObserver
(JNIEnv *, jclass, jlong);

/*
* Class: dev_onvoid_webrtc_internal_AllocationFault
* Method: encodedObservers
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_encodedObservers
(JNIEnv *, jclass, jlong);

/*
* Class: dev_onvoid_webrtc_internal_AllocationFault
* Method: disarm
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_disarm
(JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif
1 change: 1 addition & 0 deletions webrtc-jni/src/main/cpp/include/api/EncodedFrameRouter.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ namespace jni
// When this returns, the observer is not running and never runs
// again.
void RemoveObserver(Observer * observer);
size_t GetObserverCount() const;

// Shows the frame to every observer.
void Observe(const webrtc::TransformableFrameInterface & frame);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ namespace jni

EncodedFrameRouter::Observer * AddObserver(wj_encoded_frame_fn fn, void * opaque);
void RemoveObserver(EncodedFrameRouter::Observer * observer);
size_t GetObserverCount() const;

// FrameTransformerInterface implementation.
void Transform(std::unique_ptr<webrtc::TransformableFrameInterface> frame) override;
Expand Down
3 changes: 2 additions & 1 deletion webrtc-jni/src/main/cpp/include/webrtc_java_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,8 @@ struct webrtc_java_api {
* @param opaque Passed to "fn" unchanged.
*
* @return The observer, for encoded_observer_remove(), or null if a
* handle or the function was null.
* handle or the function was null, or memory ran out. Nothing is
* attached then, and the handle stays valid.
*/
void * (*encoded_observer_add)(void * frames, wj_encoded_frame_fn fn, void * opaque);

Expand Down
59 changes: 59 additions & 0 deletions webrtc-jni/src/main/cpp/src/AllocationFault.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* 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 "AllocationFault.h"

#include <atomic>
#include <new>

namespace
{
std::atomic<bool> fail_listener{ false };
std::atomic<bool> fail_encoded_observer{ false };
}

namespace jni
{
void AllocationFault::FailNextListener()
{
fail_listener.store(true);
}

void AllocationFault::FailNextEncodedObserver()
{
fail_encoded_observer.store(true);
}

void AllocationFault::Disarm()
{
fail_listener.store(false);
fail_encoded_observer.store(false);
}

void AllocationFault::CheckListener()
{
if (fail_listener.load() && fail_listener.exchange(false)) {
throw std::bad_alloc();
}
}

void AllocationFault::CheckEncodedObserver()
{
if (fail_encoded_observer.load() && fail_encoded_observer.exchange(false)) {
throw std::bad_alloc();
}
}
}
67 changes: 67 additions & 0 deletions webrtc-jni/src/main/cpp/src/JNI_AllocationFault.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* 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_AllocationFault.h"
#include "AllocationFault.h"

#include "api/EncodedFrameTransformer.h"
#include "api/ExtensionApi.h"

namespace
{
void IgnoreFrame(void * opaque, const wj_encoded_frame * frame)
{
}
}

// The Java class this belongs to exists in the tests only, so that nothing but
// them can make an allocation fail.

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_failNextListener
(JNIEnv * env, jclass caller)
{
jni::AllocationFault::FailNextListener();
}

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_failNextEncodedObserver
(JNIEnv * env, jclass caller)
{
jni::AllocationFault::FailNextEncodedObserver();
}

JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_addEncodedObserver
(JNIEnv * env, jclass caller, jlong frames)
{
return reinterpret_cast<jlong>(jni::GetExtensionApi()->encoded_observer_add(reinterpret_cast<void *>(frames), &IgnoreFrame, nullptr));
}

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_removeEncodedObserver
(JNIEnv * env, jclass caller, jlong observer)
{
jni::GetExtensionApi()->encoded_observer_remove(reinterpret_cast<void *>(observer));
}

JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_encodedObservers
(JNIEnv * env, jclass caller, jlong frames)
{
return static_cast<jint>(reinterpret_cast<jni::EncodedFrameTransformer *>(frames)->GetObserverCount());
}

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_disarm
(JNIEnv * env, jclass caller)
{
jni::AllocationFault::Disarm();
}
Loading
Loading