diff --git a/docs/guide/media/media-recording.md b/docs/guide/media/media-recording.md index 65c5f6a1f..6ce173d9e 100644 --- a/docs/guide/media/media-recording.md +++ b/docs/guide/media/media-recording.md @@ -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. @@ -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. | @@ -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-.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: @@ -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 diff --git a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/EncryptedRecordingExample.java b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/EncryptedRecordingExample.java index 6b7bd950e..1c08cfc43 100644 --- a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/EncryptedRecordingExample.java +++ b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/EncryptedRecordingExample.java @@ -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 diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaContext.cpp b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaContext.cpp index a1dffc586..3e3ee43ea 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaContext.cpp +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaContext.cpp @@ -7,6 +7,8 @@ #include "JavaContext.h" +#include + namespace jni { JavaContext::JavaContext(JavaVM * vm) : @@ -24,6 +26,12 @@ namespace jni auto className = JavaClassUtils::toNativeClassName(env, javaRef); NativeRef entry = { JavaGlobalRef(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 lock(objectMapMutex); objectMap[className].push_back(std::move(entry)); diff --git a/webrtc-jni/src/main/cpp/include/AllocationFault.h b/webrtc-jni/src/main/cpp/include/AllocationFault.h new file mode 100644 index 000000000..0265c14db --- /dev/null +++ b/webrtc-jni/src/main/cpp/include/AllocationFault.h @@ -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 diff --git a/webrtc-jni/src/main/cpp/include/JNI_AllocationFault.h b/webrtc-jni/src/main/cpp/include/JNI_AllocationFault.h new file mode 100644 index 000000000..e42406d3f --- /dev/null +++ b/webrtc-jni/src/main/cpp/include/JNI_AllocationFault.h @@ -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 +/* 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 diff --git a/webrtc-jni/src/main/cpp/include/api/EncodedFrameRouter.h b/webrtc-jni/src/main/cpp/include/api/EncodedFrameRouter.h index f7529dc4c..09b7a60a2 100644 --- a/webrtc-jni/src/main/cpp/include/api/EncodedFrameRouter.h +++ b/webrtc-jni/src/main/cpp/include/api/EncodedFrameRouter.h @@ -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); diff --git a/webrtc-jni/src/main/cpp/include/api/EncodedFrameTransformer.h b/webrtc-jni/src/main/cpp/include/api/EncodedFrameTransformer.h index 43c443710..e8f77836d 100644 --- a/webrtc-jni/src/main/cpp/include/api/EncodedFrameTransformer.h +++ b/webrtc-jni/src/main/cpp/include/api/EncodedFrameTransformer.h @@ -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 frame) override; diff --git a/webrtc-jni/src/main/cpp/include/webrtc_java_api.h b/webrtc-jni/src/main/cpp/include/webrtc_java_api.h index f5df65c5c..7d303fcbc 100644 --- a/webrtc-jni/src/main/cpp/include/webrtc_java_api.h +++ b/webrtc-jni/src/main/cpp/include/webrtc_java_api.h @@ -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); diff --git a/webrtc-jni/src/main/cpp/src/AllocationFault.cpp b/webrtc-jni/src/main/cpp/src/AllocationFault.cpp new file mode 100644 index 000000000..f78b34909 --- /dev/null +++ b/webrtc-jni/src/main/cpp/src/AllocationFault.cpp @@ -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 +#include + +namespace +{ + std::atomic fail_listener{ false }; + std::atomic 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(); + } + } +} diff --git a/webrtc-jni/src/main/cpp/src/JNI_AllocationFault.cpp b/webrtc-jni/src/main/cpp/src/JNI_AllocationFault.cpp new file mode 100644 index 000000000..e2c756479 --- /dev/null +++ b/webrtc-jni/src/main/cpp/src/JNI_AllocationFault.cpp @@ -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(jni::GetExtensionApi()->encoded_observer_add(reinterpret_cast(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(observer)); +} + +JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_encodedObservers +(JNIEnv * env, jclass caller, jlong frames) +{ + return static_cast(reinterpret_cast(frames)->GetObserverCount()); +} + +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_disarm +(JNIEnv * env, jclass caller) +{ + jni::AllocationFault::Disarm(); +} diff --git a/webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp b/webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp index 063763b6a..fd0db4317 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp @@ -15,6 +15,7 @@ */ #include "JNI_MediaStreamTrack.h" +#include "AllocationFault.h" #include "NativeHandle.h" #include "JavaContext.h" #include "JavaEnums.h" @@ -34,6 +35,33 @@ #include #include +namespace +{ + void AddListener(JNIEnv * env, webrtc::MediaStreamTrackInterface * track, jobject jListener, jni::MediaStreamTrackEvent event) + { + auto observer = std::make_shared(env, jni::JavaGlobalRef(env, jListener), track, event); + + track->RegisterObserver(observer.get()); + + try { + jni::AllocationFault::CheckListener(); + + javaContext->addNativeRef(env, jni::JavaLocalRef(env, jListener), observer, track, static_cast(event)); + } + catch (...) { + // The track holds a bare pointer, and the observer goes with this + // scope, so it has to leave the track first. No notification can + // call it after that: unregistering runs on the track's thread, + // behind one under way there, and a listener adding this one from + // within a notification is on a list copied before it got added. + observer->detach(); + track->UnregisterObserver(observer.get()); + + throw; + } + } +} + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_dispose (JNIEnv * env, jobject caller) { @@ -159,12 +187,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_addEndedEve CHECK_HANDLE(track); try { - jni::MediaStreamTrackObserver * observer = new jni::MediaStreamTrackObserver(env, jni::JavaGlobalRef(env, jListener), track, jni::MediaStreamTrackEvent::ended); - auto observerPtr = std::shared_ptr(observer); - - track->RegisterObserver(observer); - - javaContext->addNativeRef(env, jni::JavaLocalRef(env, jListener), observerPtr, track, static_cast(jni::MediaStreamTrackEvent::ended)); + AddListener(env, track, jListener, jni::MediaStreamTrackEvent::ended); } catch (...) { ThrowCxxJavaException(env); @@ -201,12 +224,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_addMuteEven CHECK_HANDLE(track); try { - jni::MediaStreamTrackObserver * observer = new jni::MediaStreamTrackObserver(env, jni::JavaGlobalRef(env, jListener), track, jni::MediaStreamTrackEvent::mute); - auto observerPtr = std::shared_ptr(observer); - - track->RegisterObserver(observer); - - javaContext->addNativeRef(env, jni::JavaLocalRef(env, jListener), observerPtr, track, static_cast(jni::MediaStreamTrackEvent::mute)); + AddListener(env, track, jListener, jni::MediaStreamTrackEvent::mute); } catch (...) { ThrowCxxJavaException(env); diff --git a/webrtc-jni/src/main/cpp/src/api/EncodedFrameRouter.cpp b/webrtc-jni/src/main/cpp/src/api/EncodedFrameRouter.cpp index c97376e32..a5c08adcb 100644 --- a/webrtc-jni/src/main/cpp/src/api/EncodedFrameRouter.cpp +++ b/webrtc-jni/src/main/cpp/src/api/EncodedFrameRouter.cpp @@ -136,6 +136,11 @@ namespace jni observerCount.store(observers.size(), std::memory_order_release); } + size_t EncodedFrameRouter::GetObserverCount() const + { + return observerCount.load(std::memory_order_acquire); + } + void EncodedFrameRouter::Observe(const webrtc::TransformableFrameInterface & frame) { if (observerCount.load(std::memory_order_acquire) == 0) { diff --git a/webrtc-jni/src/main/cpp/src/api/EncodedFrameTransformer.cpp b/webrtc-jni/src/main/cpp/src/api/EncodedFrameTransformer.cpp index bbe2ba958..d71543690 100644 --- a/webrtc-jni/src/main/cpp/src/api/EncodedFrameTransformer.cpp +++ b/webrtc-jni/src/main/cpp/src/api/EncodedFrameTransformer.cpp @@ -176,6 +176,11 @@ namespace jni router->RemoveObserver(observer); } + size_t EncodedFrameTransformer::GetObserverCount() const + { + return router->GetObserverCount(); + } + void EncodedFrameTransformer::Transform(std::unique_ptr frame) { if (!frame) { diff --git a/webrtc-jni/src/main/cpp/src/api/ExtensionApi.cpp b/webrtc-jni/src/main/cpp/src/api/ExtensionApi.cpp index b65e27428..04577ae53 100644 --- a/webrtc-jni/src/main/cpp/src/api/ExtensionApi.cpp +++ b/webrtc-jni/src/main/cpp/src/api/ExtensionApi.cpp @@ -17,6 +17,8 @@ #include "api/ExtensionApi.h" #include "api/EncodedFrameTransformer.h" +#include "AllocationFault.h" + #include "media/audio/CustomAudioSource.h" #include "media/video/CustomVideoSource.h" @@ -26,6 +28,7 @@ #include "rtc_base/time_utils.h" #include +#include namespace jni { @@ -201,12 +204,24 @@ namespace jni return nullptr; } - webrtc::scoped_refptr transformer( - static_cast(frames)); + // Nothing may be thrown through the C interface. + try { + AllocationFault::CheckEncodedObserver(); + + // The handle first: an observer without one could never be + // removed, and would go on being called. + auto handle = std::make_unique(EncodedObserver{ + webrtc::scoped_refptr(static_cast(frames)), + nullptr + }); - EncodedFrameRouter::Observer * observer = transformer->AddObserver(fn, opaque); + handle->observer = handle->transformer->AddObserver(fn, opaque); - return new EncodedObserver{ std::move(transformer), observer }; + return handle.release(); + } + catch (...) { + return nullptr; + } } void ApiEncodedObserverRemove(void * observer) diff --git a/webrtc-media/src/main/cpp/include/JNI_AllocationFault.h b/webrtc-media/src/main/cpp/include/JNI_AllocationFault.h index d10f077b8..ff20d998e 100644 --- a/webrtc-media/src/main/cpp/include/JNI_AllocationFault.h +++ b/webrtc-media/src/main/cpp/include/JNI_AllocationFault.h @@ -54,6 +54,30 @@ extern "C" { JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failWriterAllocation (JNIEnv *, jclass, jint); + /* + * Class: dev_onvoid_webrtc_media_player_AllocationFault + * Method: failNextOption + * Signature: ()V + */ + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failNextOption + (JNIEnv *, jclass); + + /* + * Class: dev_onvoid_webrtc_media_player_AllocationFault + * Method: failObserverAdd + * Signature: (I)V + */ + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failObserverAdd + (JNIEnv *, jclass, jint); + + /* + * Class: dev_onvoid_webrtc_media_player_AllocationFault + * Method: failNextQueueRoom + * Signature: ()V + */ + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failNextQueueRoom + (JNIEnv *, jclass); + /* * Class: dev_onvoid_webrtc_media_player_AllocationFault * Method: isArmed diff --git a/webrtc-media/src/main/cpp/include/JNI_MediaRecorder.h b/webrtc-media/src/main/cpp/include/JNI_MediaRecorder.h index 5fb9a84fe..415310642 100644 --- a/webrtc-media/src/main/cpp/include/JNI_MediaRecorder.h +++ b/webrtc-media/src/main/cpp/include/JNI_MediaRecorder.h @@ -54,6 +54,14 @@ extern "C" { JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_recorder_MediaRecorder_stop (JNIEnv *, jclass, jlong); + /* + * Class: dev_onvoid_webrtc_media_recorder_MediaRecorder + * Method: stats + * Signature: (J)[J + */ + JNIEXPORT jlongArray JNICALL Java_dev_onvoid_webrtc_media_recorder_MediaRecorder_stats + (JNIEnv *, jclass, jlong); + /* * Class: dev_onvoid_webrtc_media_recorder_MediaRecorder * Method: dispose diff --git a/webrtc-media/src/main/cpp/include/JNI_WriteFault.h b/webrtc-media/src/main/cpp/include/JNI_WriteFault.h index 913f5c51a..3249f740a 100644 --- a/webrtc-media/src/main/cpp/include/JNI_WriteFault.h +++ b/webrtc-media/src/main/cpp/include/JNI_WriteFault.h @@ -22,6 +22,14 @@ #ifdef __cplusplus extern "C" { #endif + /* + * Class: dev_onvoid_webrtc_media_recorder_WriteFault + * Method: failOpen + * Signature: ()V + */ + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_recorder_WriteFault_failOpen + (JNIEnv *, jclass); + /* * Class: dev_onvoid_webrtc_media_recorder_WriteFault * Method: failHeader diff --git a/webrtc-media/src/main/cpp/include/media/AllocationFault.h b/webrtc-media/src/main/cpp/include/media/AllocationFault.h index e68d5bde0..5c9c31050 100644 --- a/webrtc-media/src/main/cpp/include/media/AllocationFault.h +++ b/webrtc-media/src/main/cpp/include/media/AllocationFault.h @@ -38,6 +38,13 @@ namespace ffmpeg // Fails an allocation of a recorder's writer thread, once, after // it has handled the given number of frames. static void FailWriterAllocation(int after_frames); + // Fails the next setting of an FFmpeg option that is checked, once. + static void FailNextOption(); + // Fails attaching a recorder to a track, once, after it has + // attached to the given number of tracks. + static void FailObserverAdd(int after_tracks); + // Makes a recorder's queue look full for the next frame, once. + static void FailNextQueueRoom(); // Forgets a fault that has not fired. static void Disarm(); // Whether a fault is armed that has not fired. @@ -51,6 +58,15 @@ namespace ffmpeg // Throws std::bad_alloc if a writer fault is armed and its frames // are counted down, and disarms it. static void CheckWriterAllocation(); + // Returns the result of setting an option, or the error of a heap + // that ran out if a fault is armed, which disarms it. + static int CheckOption(int result); + // Whether a recorder is to fail attaching to its next track, which + // disarms the fault. + static bool CheckObserverAdd(); + // Whether a frame is to find the queue full, which disarms the + // fault. + static bool CheckQueueRoom(); }; } diff --git a/webrtc-media/src/main/cpp/include/media/MediaRecorder.h b/webrtc-media/src/main/cpp/include/media/MediaRecorder.h index 8dc801db8..577219d8e 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaRecorder.h +++ b/webrtc-media/src/main/cpp/include/media/MediaRecorder.h @@ -70,6 +70,26 @@ namespace ffmpeg kFailed }; + // What one track lost, in the order the Java MediaRecorderStats + // reads it. + struct TrackStats + { + // Frames the writer's queue had no room for. + int64_t dropped_queue_full = 0; + // Frames that could not be copied for want of memory. + int64_t dropped_allocation_failed = 0; + // Video frames dropped on the way to the next key frame. + int64_t dropped_awaiting_key_frame = 0; + }; + + struct Stats + { + // The most that ever waited for the writer. + int64_t max_queued_bytes = 0; + // In the order of AddTrack(). + std::vector tracks; + }; + MediaRecorder(const webrtc_java_api * api, std::string path); // Stops the recording if it still runs. @@ -91,8 +111,9 @@ namespace ffmpeg // Start(). int AddTrack(void * frames); - // Attaches to every track and starts writing. A writer thread that - // cannot be started throws, and leaves the recorder unstarted. + // Attaches to every track and starts writing. A track that cannot + // be attached to, or a writer thread that cannot be started, throws + // and leaves the recorder unstarted, as it was before. void Start(); // Detaches from every track, writes out what is queued, finishes @@ -101,6 +122,9 @@ namespace ffmpeg // more, and returns the same. Result Stop(); + // What was lost so far. Stays available once stopped. + Stats GetStats(); + private: // What the observer callback knows about a track. Guarded by // mutex_, since WebRTC calls in on threads of its own. @@ -126,8 +150,13 @@ namespace ffmpeg int64_t last_key_frame_request_us = 0; bool reported_codec_change = false; + + TrackStats stats; }; + // When this returns, no callback runs any more. + void RemoveObservers(); + static void OnEncodedFrame(void * opaque, const wj_encoded_frame * frame); void Enqueue(Input * input, const wj_encoded_frame * frame); @@ -201,6 +230,7 @@ namespace ffmpeg std::vector> inputs_; std::deque queue_; size_t queued_bytes_ = 0; + size_t max_queued_bytes_ = 0; // What the callbacks have to report, which the writer does. std::vector pending_warnings_; // Wakes the writer for something other than frames. diff --git a/webrtc-media/src/main/cpp/include/media/WriteFault.h b/webrtc-media/src/main/cpp/include/media/WriteFault.h index cc7337fd5..a73722f48 100644 --- a/webrtc-media/src/main/cpp/include/media/WriteFault.h +++ b/webrtc-media/src/main/cpp/include/media/WriteFault.h @@ -32,6 +32,7 @@ namespace ffmpeg public: enum class Call { + kOpen, kHeader, kPacket, kTrailer, diff --git a/webrtc-media/src/main/cpp/src/JNI_AllocationFault.cpp b/webrtc-media/src/main/cpp/src/JNI_AllocationFault.cpp index 3d793a06e..993ac1177 100644 --- a/webrtc-media/src/main/cpp/src/JNI_AllocationFault.cpp +++ b/webrtc-media/src/main/cpp/src/JNI_AllocationFault.cpp @@ -48,6 +48,24 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failW ffmpeg::AllocationFault::FailWriterAllocation(afterFrames); } +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failNextOption +(JNIEnv * env, jclass caller) +{ + ffmpeg::AllocationFault::FailNextOption(); +} + +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failObserverAdd +(JNIEnv * env, jclass caller, jint afterTracks) +{ + ffmpeg::AllocationFault::FailObserverAdd(afterTracks); +} + +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failNextQueueRoom +(JNIEnv * env, jclass caller) +{ + ffmpeg::AllocationFault::FailNextQueueRoom(); +} + JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_isArmed (JNIEnv * env, jclass caller) { diff --git a/webrtc-media/src/main/cpp/src/JNI_MediaRecorder.cpp b/webrtc-media/src/main/cpp/src/JNI_MediaRecorder.cpp index 84643547d..ee1331bef 100644 --- a/webrtc-media/src/main/cpp/src/JNI_MediaRecorder.cpp +++ b/webrtc-media/src/main/cpp/src/JNI_MediaRecorder.cpp @@ -24,6 +24,7 @@ #include #include +#include namespace { @@ -113,6 +114,35 @@ JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_recorder_MediaRecorder_stop }); } +JNIEXPORT jlongArray JNICALL Java_dev_onvoid_webrtc_media_recorder_MediaRecorder_stats +(JNIEnv * env, jclass caller, jlong handle) +{ + return ffmpeg::CallFromJava(env, nullptr, [&]() -> jlongArray { + const ffmpeg::MediaRecorder::Stats stats = RecorderOf(handle)->GetStats(); + + // In the order MediaRecorderStats reads them. + std::vector values; + + values.reserve(1 + stats.tracks.size() * 3); + values.push_back(stats.max_queued_bytes); + + for (const auto & track : stats.tracks) { + values.push_back(track.dropped_queue_full); + values.push_back(track.dropped_allocation_failed); + values.push_back(track.dropped_awaiting_key_frame); + } + + const jsize size = static_cast(values.size()); + jlongArray array = env->NewLongArray(size); + + if (array != nullptr) { + env->SetLongArrayRegion(array, 0, size, values.data()); + } + + return array; + }); +} + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_recorder_MediaRecorder_dispose (JNIEnv * env, jclass caller, jlong handle) { diff --git a/webrtc-media/src/main/cpp/src/JNI_WriteFault.cpp b/webrtc-media/src/main/cpp/src/JNI_WriteFault.cpp index b233a5de6..3556bdffe 100644 --- a/webrtc-media/src/main/cpp/src/JNI_WriteFault.cpp +++ b/webrtc-media/src/main/cpp/src/JNI_WriteFault.cpp @@ -29,6 +29,12 @@ extern "C" { using ffmpeg::WriteFault; +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_recorder_WriteFault_failOpen +(JNIEnv * env, jclass caller) +{ + WriteFault::Fail(WriteFault::Call::kOpen, AVERROR(EACCES), 0); +} + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_recorder_WriteFault_failHeader (JNIEnv * env, jclass caller) { diff --git a/webrtc-media/src/main/cpp/src/media/AllocationFault.cpp b/webrtc-media/src/main/cpp/src/media/AllocationFault.cpp index e0fa77b85..48af3562a 100644 --- a/webrtc-media/src/main/cpp/src/media/AllocationFault.cpp +++ b/webrtc-media/src/main/cpp/src/media/AllocationFault.cpp @@ -17,9 +17,14 @@ #include "media/AllocationFault.h" #include +#include #include #include +extern "C" { +#include +} + namespace { std::atomic fail_string_copy{ false }; @@ -27,6 +32,10 @@ namespace std::atomic fail_thread_start{ false }; std::atomic fail_writer_allocation{ false }; std::atomic writer_frames_left{ 0 }; + std::atomic fail_option{ false }; + std::atomic fail_observer_add{ false }; + std::atomic observers_left{ 0 }; + std::atomic fail_queue_room{ false }; } namespace ffmpeg @@ -52,18 +61,38 @@ namespace ffmpeg fail_writer_allocation.store(true); } + void AllocationFault::FailNextOption() + { + fail_option.store(true); + } + + void AllocationFault::FailObserverAdd(int after_tracks) + { + observers_left.store(after_tracks); + fail_observer_add.store(true); + } + + void AllocationFault::FailNextQueueRoom() + { + fail_queue_room.store(true); + } + void AllocationFault::Disarm() { fail_string_copy.store(false); fail_allocation.store(false); fail_thread_start.store(false); fail_writer_allocation.store(false); + fail_option.store(false); + fail_observer_add.store(false); + fail_queue_room.store(false); } bool AllocationFault::IsArmed() { return fail_string_copy.load() || fail_allocation.load() || fail_thread_start.load() - || fail_writer_allocation.load(); + || fail_writer_allocation.load() || fail_option.load() || fail_observer_add.load() + || fail_queue_room.load(); } void AllocationFault::CheckStringCopy() @@ -97,4 +126,27 @@ namespace ffmpeg throw std::bad_alloc(); } } + + int AllocationFault::CheckOption(int result) + { + if (fail_option.load() && fail_option.exchange(false)) { + return AVERROR(ENOMEM); + } + + return result; + } + + bool AllocationFault::CheckObserverAdd() + { + if (!fail_observer_add.load() || observers_left.fetch_sub(1) > 0) { + return false; + } + + return fail_observer_add.exchange(false); + } + + bool AllocationFault::CheckQueueRoom() + { + return fail_queue_room.load() && fail_queue_room.exchange(false); + } } diff --git a/webrtc-media/src/main/cpp/src/media/MediaReader.cpp b/webrtc-media/src/main/cpp/src/media/MediaReader.cpp index 8cd9376cc..8a99f5db6 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaReader.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaReader.cpp @@ -15,6 +15,7 @@ */ #include "media/MediaReader.h" +#include "media/AllocationFault.h" #include @@ -68,10 +69,21 @@ namespace ffmpeg AVDictionary * options = nullptr; - av_dict_set(&options, "protocol_whitelist", kProtocolWhitelist, 0); + int result = AllocationFault::CheckOption( + av_dict_set(&options, "protocol_whitelist", kProtocolWhitelist, 0)); + + if (result < 0) { + // Without the whitelist a source could reach any protocol of the + // build, so nothing is opened. + av_dict_free(&options); + avformat_free_context(format_context_); + format_context_ = nullptr; + + return result; + } BeginBlocking(); - int result = avformat_open_input(&format_context_, url.c_str(), nullptr, &options); + result = avformat_open_input(&format_context_, url.c_str(), nullptr, &options); EndBlocking(); av_dict_free(&options); diff --git a/webrtc-media/src/main/cpp/src/media/MediaRecorder.cpp b/webrtc-media/src/main/cpp/src/media/MediaRecorder.cpp index c1468407d..b0afe75cd 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaRecorder.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaRecorder.cpp @@ -19,6 +19,7 @@ #include "media/ErrorText.h" #include "media/WriteFault.h" +#include #include #include #include @@ -103,7 +104,8 @@ namespace ffmpeg context_->max_interleave_delta = 2000000; if (!(context_->oformat->flags & AVFMT_NOFILE)) { - result = avio_open(&context_->pb, path_.c_str(), AVIO_FLAG_WRITE); + result = WriteFault::Check(WriteFault::Call::kOpen, + avio_open(&context_->pb, path_.c_str(), AVIO_FLAG_WRITE)); if (result < 0) { return result; @@ -163,33 +165,49 @@ namespace ffmpeg } started_ = true; - accepting_ = true; - start_us_ = api_->now_us(); } + // Everything that can fail comes before the first frame is taken and + // before there is a writer, which would finish the file on its way + // out, so that taking the observers off again undoes all of it. try { + // The inputs do not change once started, so the callbacks may hold + // on to them without the lock. + for (const auto & input : inputs_) { + input->observer = AllocationFault::CheckObserverAdd() ? nullptr + : api_->encoded_observer_add(input->frames, &MediaRecorder::OnEncodedFrame, input.get()); + + // Given a track and a callback, only memory can be missing. + if (input->observer == nullptr) { + throw std::bad_alloc(); + } + } + AllocationFault::CheckThreadStart(); thread_ = std::thread(&MediaRecorder::Run, this); } catch (...) { - // Without a writer the recorder stays as it was before the call: - // it may be started again, and stopping only has to release the - // frames and close the file. + // The recorder stays as it was before the call: it may be started + // again, and stopping only has to release the frames and close + // the file. + RemoveObservers(); + std::lock_guard lock(mutex_); started_ = false; - accepting_ = false; throw; } - // The inputs do not change once started, so the callbacks may hold on - // to them without the lock. - for (const auto & input : inputs_) { - input->observer = api_->encoded_observer_add(input->frames, &MediaRecorder::OnEncodedFrame, - input.get()); + { + std::lock_guard lock(mutex_); + + accepting_ = true; + start_us_ = api_->now_us(); + } - // The observer keeps what it observes alive on its own. + // The observers keep what they observe alive on their own. + for (const auto & input : inputs_) { api_->encoded_frames_release(input->frames); input->frames = nullptr; } @@ -209,11 +227,9 @@ namespace ffmpeg // No callback runs once its observer is removed, so after this nothing // comes in any more. + RemoveObservers(); + for (const auto & input : inputs_) { - if (input->observer != nullptr) { - api_->encoded_observer_remove(input->observer); - input->observer = nullptr; - } if (input->frames != nullptr) { api_->encoded_frames_release(input->frames); input->frames = nullptr; @@ -256,6 +272,32 @@ namespace ffmpeg return result_; } + MediaRecorder::Stats MediaRecorder::GetStats() + { + std::lock_guard lock(mutex_); + + Stats stats; + + stats.max_queued_bytes = static_cast(max_queued_bytes_); + stats.tracks.reserve(inputs_.size()); + + for (const auto & input : inputs_) { + stats.tracks.push_back(input->stats); + } + + return stats; + } + + void MediaRecorder::RemoveObservers() + { + for (const auto & input : inputs_) { + if (input->observer != nullptr) { + api_->encoded_observer_remove(input->observer); + input->observer = nullptr; + } + } + } + void MediaRecorder::OnEncodedFrame(void * opaque, const wj_encoded_frame * frame) { Input * input = static_cast(opaque); @@ -308,6 +350,7 @@ namespace ffmpeg return; } if (video && !frame->key_frame) { + input->stats.dropped_awaiting_key_frame++; WantKeyFrameLocked(input); return; } @@ -331,6 +374,7 @@ namespace ffmpeg if (video && input->waiting_for_key_frame) { if (!frame->key_frame) { + input->stats.dropped_awaiting_key_frame++; WantKeyFrameLocked(input); return; } @@ -338,9 +382,11 @@ namespace ffmpeg input->waiting_for_key_frame = false; } - if (queued_bytes_ + frame->size > kMaxQueuedBytes) { + if (queued_bytes_ + frame->size > kMaxQueuedBytes || AllocationFault::CheckQueueRoom()) { // The writer does not keep up. Video goes on from the next key // frame, since everything up to it could not be decoded anyway. + input->stats.dropped_queue_full++; + if (video) { input->waiting_for_key_frame = true; WantKeyFrameLocked(input); @@ -356,6 +402,8 @@ namespace ffmpeg || av_new_packet(recorded.packet.get(), static_cast(frame->size)) < 0) { // Dropped like a frame the queue has no room for: video goes on // from the next key frame. + input->stats.dropped_allocation_failed++; + if (video) { input->waiting_for_key_frame = true; WantKeyFrameLocked(input); @@ -382,20 +430,21 @@ namespace ffmpeg input->last_time_us = frame->time_us; queued_bytes_ += frame->size; + max_queued_bytes_ = std::max(max_queued_bytes_, queued_bytes_); wake_.notify_one(); } void MediaRecorder::Dropped(Input * input, bool video) { - if (!video) { - return; - } - std::lock_guard lock(mutex_); - input->waiting_for_key_frame = true; - WantKeyFrameLocked(input); + input->stats.dropped_allocation_failed++; + + if (video) { + input->waiting_for_key_frame = true; + WantKeyFrameLocked(input); + } } void MediaRecorder::WantKeyFrameLocked(Input * input) diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorder.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorder.java index 24fbd6c60..3bad3b122 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorder.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorder.java @@ -19,8 +19,10 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.util.List; import java.util.Objects; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -65,6 +67,10 @@ * } * } *

+ * A file that exists is refused unless {@link #MediaRecorder(Path, boolean)} + * is asked to replace it, which happens only once the new recording is + * finished: a recording that fails or gets no media costs nothing. + *

* How it behaves: *

    *
  • A video track is recorded from its first key frame, and the recorder @@ -91,7 +97,11 @@ public class MediaRecorder implements AutoCloseable { private final Object lock = new Object(); - private final Path file; + /** The file being written: the file itself, or one beside it to replace it. */ + private final Path output; + + /** Where the recording is meant to end up, or stays if it cannot. */ + private volatile Path file; /** * How to ask each track for a key frame, by track index. Filled before @@ -113,20 +123,70 @@ public class MediaRecorder implements AutoCloseable { /** How the recording ended, or null until it was stopped. */ private MediaRecorderResult result; + /** What the native recorder reported last, for the time after it is gone. */ + private MediaRecorderStats stats = new MediaRecorderStats(new long[1]); + /** - * Creates a recorder writing to the given file, which is created, or - * emptied if it exists. + * Creates a recorder writing to the given file, which must not exist yet. * * @param file Where to record to; its extension picks the container. * + * @throws java.nio.file.FileAlreadyExistsException If the file exists. * @throws IOException If the file cannot be written. */ public MediaRecorder(Path file) throws IOException { + this(file, false); + } + + /** + * Creates a recorder writing to the given file, which may be asked to + * replace a file that exists. + *

    + * A recorder that replaces a file writes to a temporary file in the same + * directory, with the same extension, and leaves the existing file alone + * until {@link #stop()} has finished the recording: only then does the + * recording take its place, in one step and with its permissions. A + * recording without media leaves the existing file as it was, and so + * does a process that ends before the stop, which leaves the temporary + * file behind as well. + * + * @param file Where to record to; its extension picks the container. + * @param overwrite Whether to replace the file if it exists. + * + * @throws java.nio.file.FileAlreadyExistsException If the file exists, and + * is not to be replaced. + * @throws IOException If the file cannot be written, or is a directory. + */ + public MediaRecorder(Path file, boolean overwrite) throws IOException { Objects.requireNonNull(file, "File is null"); - this.file = file.toAbsolutePath(); - this.handle = create(this.file.toString(), NativeApi.tableAddress()); + Path target = file.toAbsolutePath(); + + if (overwrite && Files.exists(target)) { + if (!Files.isRegularFile(target)) { + throw new IOException(target + " is not a file"); + } + + // A link stays in place, and what it points to is replaced. + if (Files.isSymbolicLink(target)) { + target = target.toRealPath(); + } + } + + this.file = target; + // Created here rather than by the native recorder, which would empty + // a file that came into being since the check. + this.output = overwrite ? createTemporaryFile(target) : Files.createFile(target); + + try { + this.handle = create(output.toString(), NativeApi.tableAddress()); + } + catch (IOException | RuntimeException | Error e) { + deleteOutput(); + + throw e; + } } /** @@ -216,7 +276,8 @@ public void addTrack(RemoteTrack track) { } /** - * Starts recording the tracks added so far. + * Starts recording the tracks added so far. If that fails, the recorder + * is as it was before and may be started again. * * @throws IllegalStateException If the recorder has no tracks, or was * started or closed before. @@ -239,8 +300,9 @@ public void start() { start(handle); } catch (RuntimeException | Error e) { - // The native recorder could not start its writer, and is as - // it was: still idle, and closing it deletes its file. + // The native recorder could not attach to every track or start + // its writer, and undid what it had done: it is still idle, + // may be started again, and closing it deletes its file. events.shutdown(); events = null; @@ -254,21 +316,22 @@ public void start() { /** * Stops recording and finishes the file, waiting for everything received * so far to be written. A recorder that never got any media to write - * deletes its file rather than leave an unplayable one behind. + * deletes what it wrote rather than leave an unplayable file behind, and + * a file it was to replace stays as it was. *

    * A file that holds media is kept even when writing, finishing or closing - * it failed, since what made it into the file may still play. Whether it - * is complete, {@link #getResult()} tells. + * it failed, since what made it into the file may still play, and takes + * the place of a file it was to replace. Whether it is complete, {@link + * #getResult()} tells. *

    * Stopping a recorder that is stopped does nothing, and returns the same. - * Stopping one that was never started deletes its file. + * Stopping one that was never started is the same as stopping one that + * got no media. * - * @return True if the file holds a recording, complete or not, false if it + * @return True if the recording was kept, complete or not, false if it * was deleted. */ public boolean stop() { - boolean recorded; - synchronized (lock) { if (result != null) { return result.keepsFile(); @@ -280,24 +343,16 @@ public boolean stop() { // In the order of the native MediaRecorder::Result. result = MediaRecorderResult.values()[stop(handle)]; state = MediaRecorderState.STOPPED; - recorded = result.keepsFile(); + + finishOutput(); if (events != null) { // Lets the reports already queued run, then ends the thread. events.shutdown(); } - } - if (!recorded) { - try { - Files.deleteIfExists(file); - } - catch (IOException e) { - // The file stays behind, empty; there is nothing else to do. - } + return result.keepsFile(); } - - return recorded; } /** @@ -326,7 +381,29 @@ public MediaRecorderResult getResult() { } /** - * @return The file this recorder writes to. + * Returns what the recording lost so far, and how full the queue for the + * writer got. It can be asked at any time, and stays the same once the + * recorder is stopped, after {@link #close()} as well. + * + * @return The numbers as of now. + */ + public MediaRecorderStats getStats() { + synchronized (lock) { + if (handle != 0) { + stats = new MediaRecorderStats(stats(handle)); + } + + return stats; + } + } + + /** + * Returns where the recording goes, and once it is stopped, where it is: + * the file given to the constructor, or the temporary file beside it + * if the recording could not take the place of that file, as {@link + * MediaRecorderListener#onError(String)} was told. + * + * @return The file of the recording. */ public Path getFile() { return file; @@ -342,12 +419,72 @@ public void close() { synchronized (lock) { if (handle != 0) { - dispose(handle); - handle = 0; + try { + stats = new MediaRecorderStats(stats(handle)); + } + finally { + dispose(handle); + handle = 0; + } } } } + /** + * Creates the file a recording goes into until it replaces the target. It + * has the target's extension, which picks the container. + */ + private static Path createTemporaryFile(Path target) throws IOException { + String name = target.getFileName().toString(); + int dot = name.lastIndexOf('.'); + String extension = dot < 0 ? "" : name.substring(dot); + + return Files.createFile(target.resolveSibling(".recording-" + UUID.randomUUID() + extension)); + } + + /** Called with the lock held, once the native recorder closed the output. */ + private void finishOutput() { + if (!result.keepsFile()) { + deleteOutput(); + } + else if (!output.equals(file)) { + try { + replaceFile(); + } + catch (IOException e) { + // The recording is safe where it is, so it stays there. + String error = "Replacing " + file + " failed, the recording stays in " + output + ": " + e; + + file = output; + result = MediaRecorderResult.PARTIAL; + + onNativeError(error); + } + } + } + + private void replaceFile() throws IOException { + if (Files.isRegularFile(file)) { + try { + Files.setPosixFilePermissions(output, Files.getPosixFilePermissions(file)); + } + catch (UnsupportedOperationException e) { + // Not a POSIX file system. + } + } + + Files.move(output, file, StandardCopyOption.ATOMIC_MOVE); + } + + private void deleteOutput() { + try { + Files.deleteIfExists(output); + } + catch (IOException e) { + // The file stays behind, empty; there is nothing else to do. + } + } + /** Called with the lock held, in the idle state. */ private void addTrack(EncodedFrames.Source source) { addTrack(source.take(), source::requestKeyFrame); @@ -492,6 +629,8 @@ private void onNativeKeyFrameNeeded(int track) { private static native int stop(long handle); + private static native long[] stats(long handle); + private static native void dispose(long handle); } diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorderResult.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorderResult.java index e7eaf6ff8..724a05f4f 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorderResult.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorderResult.java @@ -28,7 +28,9 @@ public enum MediaRecorderResult { /** * Everything the recorder took went into the file, and the file was - * finished and closed without an error. + * finished and closed without an error. Frames it had to drop before + * taking them, e.g. because the writer fell behind, are no error: {@link + * MediaRecorder#getStats()} tells how many there were. */ COMPLETE, @@ -38,19 +40,24 @@ public enum MediaRecorderResult { * file is kept: it may end before the recording was stopped, lack its * index, or miss what the system had not yet written when closing it * failed. + *

    + * The same goes for a recording that could not take the place of the file + * it was to replace. It stays in the temporary file that {@link + * MediaRecorder#getFile()} then returns. */ PARTIAL, /** * Nothing went wrong, but no media arrived to be written, e.g. because * the recorder was stopped right after it was started, or never started. - * The file is deleted. + * What it wrote is deleted, and a file it was to replace stays as it was. */ EMPTY, /** * Writing failed before any media went into the file, e.g. writing its - * header. The file is deleted. + * header. What it wrote is deleted, and a file it was to replace stays as + * it was. */ FAILED; diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorderStats.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorderStats.java new file mode 100644 index 000000000..b2ec11196 --- /dev/null +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/recorder/MediaRecorderStats.java @@ -0,0 +1,132 @@ +/* + * 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. + */ + +package dev.onvoid.webrtc.media.recorder; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * What a {@link MediaRecorder} lost so far, and how close it came to that, as + * {@link MediaRecorder#getStats()} tells. A recording can end as {@link + * MediaRecorderResult#COMPLETE} with frames missing: the result speaks of + * what the recorder took, and this of what it had to leave out before. + *

    + * Frames that a track was never meant to record do not count, such as those + * before its first key frame, those of another simulcast layer, or those that + * arrive once the recording has failed. + * + * @author Alex Andres + */ +public final class MediaRecorderStats { + + /** How many values the native recorder reports per track. */ + private static final int TRACK_VALUES = 3; + + private final long maxQueuedBytes; + + private final List tracks; + + + /** + * @param values The peak of the queue, then the counters of each track in + * the order of the native MediaRecorder::TrackStats. + */ + MediaRecorderStats(long[] values) { + List list = new ArrayList<>(); + + for (int i = 1; i + TRACK_VALUES <= values.length; i += TRACK_VALUES) { + list.add(new Track(values[i], values[i + 1], values[i + 2])); + } + + this.maxQueuedBytes = values[0]; + this.tracks = Collections.unmodifiableList(list); + } + + /** + * Returns the most that ever waited for the writer, of all tracks together, + * which share one queue of 64 MB. Near that limit, frames are dropped. + * + * @return The peak of the queue, in bytes. + */ + public long getMaxQueuedBytes() { + return maxQueuedBytes; + } + + /** + * @return What each track lost, in the order the tracks were added. + */ + public List getTracks() { + return tracks; + } + + + /** + * What one track of a recording lost. + */ + public static final class Track { + + private final long droppedQueueFull; + + private final long droppedAllocationFailed; + + private final long droppedAwaitingKeyFrame; + + + private Track(long droppedQueueFull, long droppedAllocationFailed, long droppedAwaitingKeyFrame) { + this.droppedQueueFull = droppedQueueFull; + this.droppedAllocationFailed = droppedAllocationFailed; + this.droppedAwaitingKeyFrame = droppedAwaitingKeyFrame; + } + + /** + * @return How many frames were dropped because the writer did not keep + * up and its queue was full. + */ + public long getDroppedQueueFull() { + return droppedQueueFull; + } + + /** + * @return How many frames were dropped because there was no memory to + * copy them. + */ + public long getDroppedAllocationFailed() { + return droppedAllocationFailed; + } + + /** + * Returns how many video frames were dropped on the way to the next + * key frame, since a decoder could do nothing with them after what + * was lost before. These frames make the visible gap in the video. + * + * @return The number of frames. + */ + public long getDroppedAwaitingKeyFrame() { + return droppedAwaitingKeyFrame; + } + + /** + * @return How many frames were dropped for any of these reasons. + */ + public long getDroppedFrames() { + return droppedQueueFull + droppedAllocationFailed + droppedAwaitingKeyFrame; + } + + } + +} diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/AllocationFault.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/AllocationFault.java index 5c4acab4a..22e9629e4 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/AllocationFault.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/AllocationFault.java @@ -66,6 +66,27 @@ private AllocationFault() { */ public static native void failWriterAllocation(int afterFrames); + /** + * Fails the next setting of an FFmpeg option that is checked, such as the + * protocols a reader may reach. + */ + public static native void failNextOption(); + + /** + * Makes a recorder fail to attach to a track, as it does when {@code + * encoded_observer_add()} returns null. + * + * @param afterTracks How many tracks it attaches to before the one that + * fails. + */ + public static native void failObserverAdd(int afterTracks); + + /** + * Makes a recorder's queue look full for the next frame, which no test can + * fill for real without holding up the writer. + */ + public static native void failNextQueueRoom(); + /** * @return True if a fault is armed that has not fired yet. */ diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaReaderTest.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaReaderTest.java index 2410a3327..f972de1ec 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaReaderTest.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaReaderTest.java @@ -17,6 +17,7 @@ package dev.onvoid.webrtc.media.player; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -186,6 +187,24 @@ void sourceCopyFails() throws Exception { } } + @Test + void failedWhitelistRefusesSource() throws Exception { + // A source must not open without the limit on what it may reach. + AllocationFault.failNextOption(); + + try { + assertThrows(IOException.class, () -> new MediaReader(asset())); + assertFalse(AllocationFault.isArmed()); + } + finally { + AllocationFault.disarm(); + } + + try (MediaReader reader = new MediaReader(asset())) { + assertTrue(reader.getInfo().hasVideo()); + } + } + @Test void closesTwice() throws Exception { MediaReader reader = new MediaReader(asset()); diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/recorder/MediaRecorderTest.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/recorder/MediaRecorderTest.java index 883654572..51e898241 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/recorder/MediaRecorderTest.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/recorder/MediaRecorderTest.java @@ -16,6 +16,7 @@ package dev.onvoid.webrtc.media.recorder; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; @@ -23,8 +24,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; @@ -43,6 +49,7 @@ import dev.onvoid.webrtc.media.player.UnicodeFileName; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @@ -60,6 +67,9 @@ class MediaRecorderTest { private static final long RECORD_MS = 3000; + /** What a file holds that a recording must not cost. */ + private static final byte[] EARLIER_RECORDING = "earlier recording".getBytes(StandardCharsets.UTF_8); + private AudioDeviceModule audioModule; private PeerConnectionFactory factory; @@ -201,10 +211,269 @@ void failedOpenBeyondBasicPlaneNamesPath() { IOException e = assertThrows(IOException.class, () -> new MediaRecorder(file)); - // The path comes back to Java as it went in. assertTrue(e.getMessage().contains(UnicodeFileName.NAME), e.getMessage()); } + @Test + void failedNativeOpenNamesPath(@TempDir Path dir) { + Path file = UnicodeFileName.resolve(dir, "mkv"); + + WriteFault.failOpen(); + + try { + IOException e = assertThrows(IOException.class, () -> new MediaRecorder(file)); + + // The path comes back to Java as it went in. + assertTrue(e.getMessage().contains(UnicodeFileName.NAME), e.getMessage()); + } + finally { + WriteFault.disarm(); + } + + assertEquals(Collections.emptyList(), filesIn(dir)); + } + + @Test + void refusesFileThatExists() throws Exception { + Path file = tempDir.resolve("refused.mkv"); + + Files.write(file, EARLIER_RECORDING); + + assertThrows(FileAlreadyExistsException.class, () -> new MediaRecorder(file)); + assertArrayEquals(EARLIER_RECORDING, Files.readAllBytes(file)); + } + + @Test + void replacesFileOnceFinished(@TempDir Path dir) throws Exception { + Path file = dir.resolve("replaced.mkv"); + Listener listener = new Listener(); + + Files.write(file, EARLIER_RECORDING); + + try (TestCall call = new TestCall(factory); + MediaRecorder recorder = new MediaRecorder(file, true)) { + recorder.setListener(listener); + recorder.addTrack(call.getVideoSender()); + recorder.start(); + + assertTrue(listener.started.await(10, TimeUnit.SECONDS), "not started"); + + Thread.sleep(1000); + + assertArrayEquals(EARLIER_RECORDING, Files.readAllBytes(file)); + assertEquals(2, filesIn(dir).size()); + + assertTrue(recorder.stop()); + assertEquals(MediaRecorderResult.COMPLETE, recorder.getResult()); + assertEquals(file, recorder.getFile()); + } + + assertNull(listener.error.get()); + assertEquals(Collections.singletonList(file), filesIn(dir)); + assertEquals("vp8", readInfo(file).getVideoCodec()); + } + + @Test + void replacingCreatesMissingFile(@TempDir Path dir) throws Exception { + Path file = dir.resolve("created.mp4"); + Listener listener = new Listener(); + + try (TestCall call = new TestCall(factory); + MediaRecorder recorder = new MediaRecorder(file, true)) { + recorder.setListener(listener); + recorder.addTrack(call.getAudioSender()); + recorder.start(); + + assertTrue(listener.started.await(10, TimeUnit.SECONDS), "not started"); + + Thread.sleep(1000); + + assertTrue(recorder.stop()); + } + + assertEquals(Collections.singletonList(file), filesIn(dir)); + + // The temporary file kept the extension, which picks the container. + byte[] start = Arrays.copyOf(Files.readAllBytes(file), 8); + + assertEquals("ftyp", new String(start, 4, 4, StandardCharsets.US_ASCII)); + } + + @Test + void recordingWithoutMediaKeepsReplacedFile(@TempDir Path dir) throws Exception { + Path file = dir.resolve("kept.mkv"); + + Files.write(file, EARLIER_RECORDING); + + try (TestCall call = new TestCall(factory); + MediaRecorder recorder = new MediaRecorder(file, true)) { + recorder.addTrack(call.getVideoSender()); + recorder.start(); + + // Too soon for any frame to have made it into the file. + assertFalse(recorder.stop()); + assertEquals(MediaRecorderResult.EMPTY, recorder.getResult()); + } + + assertArrayEquals(EARLIER_RECORDING, Files.readAllBytes(file)); + assertEquals(Collections.singletonList(file), filesIn(dir)); + } + + @Test + void unstartedRecorderKeepsReplacedFile(@TempDir Path dir) throws Exception { + Path file = dir.resolve("kept.mkv"); + + Files.write(file, EARLIER_RECORDING); + + new MediaRecorder(file, true).close(); + + assertArrayEquals(EARLIER_RECORDING, Files.readAllBytes(file)); + assertEquals(Collections.singletonList(file), filesIn(dir)); + } + + @Test + void failedRecordingKeepsReplacedFile(@TempDir Path dir) throws Exception { + Path file = dir.resolve("kept.mkv"); + Listener listener = new Listener(); + + Files.write(file, EARLIER_RECORDING); + + WriteFault.failHeader(); + + try (TestCall call = new TestCall(factory); + MediaRecorder recorder = new MediaRecorder(file, true)) { + recorder.setListener(listener); + recorder.addTrack(call.getVideoSender()); + recorder.start(); + + assertTrue(listener.failed.await(10, TimeUnit.SECONDS), "not failed"); + assertFalse(recorder.stop()); + assertEquals(MediaRecorderResult.FAILED, recorder.getResult()); + } + finally { + WriteFault.disarm(); + } + + assertArrayEquals(EARLIER_RECORDING, Files.readAllBytes(file)); + assertEquals(Collections.singletonList(file), filesIn(dir)); + } + + @Test + void failedReplaceKeepsRecording(@TempDir Path dir) throws Exception { + Path file = dir.resolve("blocked.mkv"); + Listener listener = new Listener(); + + try (TestCall call = new TestCall(factory); + MediaRecorder recorder = new MediaRecorder(file, true)) { + recorder.setListener(listener); + recorder.addTrack(call.getVideoSender()); + recorder.start(); + + assertTrue(listener.started.await(10, TimeUnit.SECONDS), "not started"); + + Thread.sleep(1000); + + // No file can take the place of a directory that holds something. + Files.createFile(Files.createDirectory(file).resolve("child")); + + assertTrue(recorder.stop()); + assertEquals(MediaRecorderResult.PARTIAL, recorder.getResult()); + assertTrue(listener.failed.await(10, TimeUnit.SECONDS), "not reported"); + assertFalse(file.equals(recorder.getFile())); + assertEquals("vp8", readInfo(recorder.getFile()).getVideoCodec()); + } + + assertErrorStartsWith(listener, "Replacing " + file + " failed"); + } + + @Test + void replacingKeepsPermissions(@TempDir Path dir) throws Exception { + Assumptions.assumeTrue(dir.getFileSystem().supportedFileAttributeViews().contains("posix")); + + Path file = dir.resolve("private.mkv"); + Listener listener = new Listener(); + + Files.write(file, EARLIER_RECORDING); + Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rw-r-----")); + + try (TestCall call = new TestCall(factory); + MediaRecorder recorder = new MediaRecorder(file, true)) { + recorder.setListener(listener); + recorder.addTrack(call.getVideoSender()); + recorder.start(); + + assertTrue(listener.started.await(10, TimeUnit.SECONDS), "not started"); + + Thread.sleep(1000); + + assertTrue(recorder.stop()); + } + + assertEquals(PosixFilePermissions.fromString("rw-r-----"), Files.getPosixFilePermissions(file)); + } + + @Test + void replacingKeepsLink(@TempDir Path dir) throws Exception { + Path file = dir.resolve("real.mkv"); + Path link = dir.resolve("link.mkv"); + Listener listener = new Listener(); + + Files.write(file, EARLIER_RECORDING); + + try { + Files.createSymbolicLink(link, file); + } + catch (UnsupportedOperationException | IOException e) { + Assumptions.abort("No symbolic links here: " + e); + } + + try (TestCall call = new TestCall(factory); + MediaRecorder recorder = new MediaRecorder(link, true)) { + recorder.setListener(listener); + recorder.addTrack(call.getVideoSender()); + recorder.start(); + + assertTrue(listener.started.await(10, TimeUnit.SECONDS), "not started"); + + Thread.sleep(1000); + + assertTrue(recorder.stop()); + } + + assertTrue(Files.isSymbolicLink(link)); + assertEquals("vp8", readInfo(file).getVideoCodec()); + } + + @Test + void replacingKeepsGivenPath(@TempDir Path dir) throws Exception { + // As on macOS, whose temporary directories lie behind a link. + Path real = Files.createDirectory(dir.resolve("real")); + Path linked = dir.resolve("linked"); + + try { + Files.createSymbolicLink(linked, real); + } + catch (UnsupportedOperationException | IOException e) { + Assumptions.abort("No symbolic links here: " + e); + } + + Path file = linked.resolve("given.mkv"); + + Files.write(file, EARLIER_RECORDING); + + try (MediaRecorder recorder = new MediaRecorder(file, true)) { + assertEquals(file, recorder.getFile()); + } + } + + @Test + void replacingRefusesDirectory(@TempDir Path dir) throws Exception { + Path file = Files.createDirectory(dir.resolve("directory.mkv")); + + assertThrows(IOException.class, () -> new MediaRecorder(file, true)); + assertEquals(Collections.singletonList(file), filesIn(dir)); + } + @Test void recordsMuLawIntoMatroska() throws Exception { assertRecordsG711("PCMU", "pcm_mulaw"); @@ -407,6 +676,77 @@ void failedStartLeavesRecorderIdle() throws Exception { assertTrue(readInfo(file).hasVideo()); } + @Test + void failedAttachLeavesRecorderIdle() throws Exception { + Path file = tempDir.resolve("failed-attach.mkv"); + Listener listener = new Listener(); + + try (TestCall call = new TestCall(factory); + MediaRecorder recorder = new MediaRecorder(file)) { + recorder.setListener(listener); + recorder.addTrack(call.getVideoSender()); + recorder.addTrack(call.getAudioSender()); + + // The second track fails, with the first one attached. + AllocationFault.failObserverAdd(1); + + assertThrows(OutOfMemoryError.class, recorder::start); + assertFalse(AllocationFault.isArmed()); + assertEquals(MediaRecorderState.IDLE, recorder.getState()); + assertNull(recorder.getResult()); + + // Nothing was left half started, so it starts on a second try, + // with both tracks. + recorder.start(); + + assertTrue(listener.started.await(10, TimeUnit.SECONDS), "not started"); + + Thread.sleep(1000); + + assertTrue(recorder.stop()); + assertEquals(MediaRecorderResult.COMPLETE, recorder.getResult()); + } + finally { + AllocationFault.disarm(); + } + + assertNull(listener.error.get()); + assertTrue(listener.warnings.isEmpty(), listener.warnings.toString()); + + MediaInfo info = readInfo(file); + + assertTrue(info.hasVideo()); + assertTrue(info.hasAudio()); + } + + @Test + void closeAfterFailedAttach() throws Exception { + Path file = tempDir.resolve("closed-after-failed-attach.mkv"); + + try (TestCall call = new TestCall(factory)) { + MediaRecorder recorder = new MediaRecorder(file); + + recorder.addTrack(call.getVideoSender()); + recorder.addTrack(call.getAudioSender()); + + AllocationFault.failObserverAdd(1); + + assertThrows(OutOfMemoryError.class, recorder::start); + + recorder.close(); + + assertEquals(MediaRecorderResult.EMPTY, recorder.getResult()); + assertFalse(Files.exists(file)); + + // The call goes on: an observer left on the first track would + // call into the recorder freed by now. + Thread.sleep(500); + } + finally { + AllocationFault.disarm(); + } + } + @Test void dropsFrameThatCannotBeQueued() throws Exception { Path file = tempDir.resolve("dropped-frame.mkv"); @@ -423,18 +763,17 @@ void dropsFrameThatCannotBeQueued() throws Exception { // The next frame cannot be copied, on a WebRTC thread, where // nothing may be thrown. AllocationFault.failNextAllocation(); - - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); - - while (AllocationFault.isArmed() && System.nanoTime() < deadline) { - Thread.sleep(10); - } - - assertFalse(AllocationFault.isArmed(), "no frame arrived"); + awaitFault(); Thread.sleep(1000); assertTrue(recorder.stop()); + assertEquals(MediaRecorderResult.COMPLETE, recorder.getResult()); + + MediaRecorderStats.Track track = recorder.getStats().getTracks().get(0); + + assertEquals(1, track.getDroppedAllocationFailed()); + assertEquals(0, track.getDroppedQueueFull()); } finally { AllocationFault.disarm(); @@ -444,6 +783,101 @@ void dropsFrameThatCannotBeQueued() throws Exception { assertTrue(readInfo(file).hasVideo()); } + @Test + void countsVideoLostToFullQueue() throws Exception { + Path file = tempDir.resolve("full-queue.mkv"); + Listener listener = new Listener(); + MediaRecorderStats stats; + + try (TestCall call = new TestCall(factory)) { + MediaRecorder recorder = new MediaRecorder(file); + + recorder.setListener(listener); + recorder.addTrack(call.getVideoSender()); + recorder.start(); + + assertTrue(listener.started.await(10, TimeUnit.SECONDS), "not started"); + + // Twice, since the recorder asks for a key frame once a second: + // the first time it gets one right away, the second time the video + // goes on without one until the second is over. + AllocationFault.failNextQueueRoom(); + awaitFault(); + AllocationFault.failNextQueueRoom(); + awaitFault(); + + Thread.sleep(1500); + + assertTrue(recorder.stop()); + assertEquals(MediaRecorderResult.COMPLETE, recorder.getResult()); + + stats = recorder.getStats(); + + recorder.close(); + + // Kept beyond the close. + assertEquals(stats.getMaxQueuedBytes(), recorder.getStats().getMaxQueuedBytes()); + assertEquals(1, recorder.getStats().getTracks().size()); + } + finally { + AllocationFault.disarm(); + } + + MediaRecorderStats.Track track = stats.getTracks().get(0); + + assertEquals(2, track.getDroppedQueueFull()); + assertEquals(0, track.getDroppedAllocationFailed()); + assertTrue(track.getDroppedAwaitingKeyFrame() > 0, "nothing skipped"); + assertEquals(2 + track.getDroppedAwaitingKeyFrame(), track.getDroppedFrames()); + assertTrue(stats.getMaxQueuedBytes() > 0); + } + + @Test + void countsAudioLostToAllocation() throws Exception { + Path file = tempDir.resolve("lost-audio.mkv"); + Listener listener = new Listener(); + + try (TestCall call = new TestCall(factory); + MediaRecorder recorder = new MediaRecorder(file)) { + recorder.setListener(listener); + recorder.addTrack(call.getAudioSender()); + recorder.start(); + + assertTrue(listener.started.await(10, TimeUnit.SECONDS), "not started"); + + AllocationFault.failNextAllocation(); + awaitFault(); + + assertTrue(recorder.stop()); + + MediaRecorderStats.Track track = recorder.getStats().getTracks().get(0); + + assertEquals(1, track.getDroppedAllocationFailed()); + assertEquals(1, track.getDroppedFrames()); + } + finally { + AllocationFault.disarm(); + } + } + + @Test + void statsPerTrack() throws Exception { + try (TestCall call = new TestCall(factory); + MediaRecorder recorder = new MediaRecorder(tempDir.resolve("stats.mkv"))) { + assertTrue(recorder.getStats().getTracks().isEmpty()); + + recorder.addTrack(call.getVideoSender()); + recorder.addTrack(call.getAudioSender()); + + MediaRecorderStats stats = recorder.getStats(); + + assertEquals(2, stats.getTracks().size()); + assertEquals(0, stats.getMaxQueuedBytes()); + assertEquals(0, stats.getTracks().get(0).getDroppedFrames()); + assertEquals(0, stats.getTracks().get(1).getDroppedFrames()); + } + } + @Test void failedHeaderFailsRecording() throws Exception { Path file = tempDir.resolve("failed-header.mkv"); @@ -603,6 +1037,26 @@ private void assertFailedFinishKeepsFile(String name, Runnable fault, String err assertTrue(Files.exists(file)); } + /** Waits for a frame to run into the fault that is armed. */ + private static void awaitFault() throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + + while (AllocationFault.isArmed() && System.nanoTime() < deadline) { + Thread.sleep(10); + } + + assertFalse(AllocationFault.isArmed(), "no frame arrived"); + } + + private static List filesIn(Path dir) { + try (Stream files = Files.list(dir)) { + return files.collect(Collectors.toList()); + } + catch (IOException e) { + throw new AssertionError(e); + } + } + private static void assertErrorStartsWith(Listener listener, String prefix) { String error = listener.error.get(); diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/recorder/WriteFault.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/recorder/WriteFault.java index f112da1bf..5bf223b53 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/recorder/WriteFault.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/recorder/WriteFault.java @@ -42,6 +42,11 @@ private WriteFault() { // Static access only. } + /** + * Fails the opening of the file, as a file system does that refuses it. + */ + static native void failOpen(); + /** * Fails the writing of the file header, before any media is in the file. */ diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/MediaStreamTrackListenerTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/MediaStreamTrackListenerTests.java new file mode 100644 index 000000000..1cec0f0b5 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/MediaStreamTrackListenerTests.java @@ -0,0 +1,106 @@ +/* + * 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. + */ + +package dev.onvoid.webrtc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import dev.onvoid.webrtc.internal.AllocationFault; +import dev.onvoid.webrtc.media.MediaStreamTrackEndedListener; +import dev.onvoid.webrtc.media.MediaStreamTrackMuteListener; +import dev.onvoid.webrtc.media.audio.AudioOptions; +import dev.onvoid.webrtc.media.audio.AudioTrack; +import dev.onvoid.webrtc.media.audio.AudioTrackSource; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +/** + * A track keeps a bare pointer to the observer of each listener, so a listener + * that fails to be registered must leave the track before its observer goes. + * With an observer left behind, the first change of the track calls into freed + * memory, which ends the test run. + */ +@Execution(ExecutionMode.SAME_THREAD) +class MediaStreamTrackListenerTests extends TestBase { + + private AudioTrackSource audioSource; + + private AudioTrack audioTrack; + + + @BeforeEach + void init() { + audioSource = factory.createAudioSource(new AudioOptions()); + audioTrack = factory.createAudioTrack("audioTrack", audioSource); + } + + @AfterEach + void dispose() { + AllocationFault.disarm(); + + audioTrack.dispose(); + audioSource.dispose(); + } + + @Test + void failedMuteListenerLeavesTrack() { + AtomicInteger calls = new AtomicInteger(); + MediaStreamTrackMuteListener listener = (track, muted) -> calls.incrementAndGet(); + + AllocationFault.failNextListener(); + + assertThrows(Error.class, () -> audioTrack.addTrackMuteListener(listener)); + + audioTrack.setEnabled(false); + + assertEquals(0, calls.get()); + + // Nothing of the failed registration is in the way of a new one. + audioTrack.addTrackMuteListener(listener); + audioTrack.setEnabled(true); + + assertEquals(1, calls.get()); + + audioTrack.removeTrackMuteListener(listener); + audioTrack.setEnabled(false); + + assertEquals(1, calls.get()); + } + + @Test + void failedEndedListenerLeavesTrack() { + MediaStreamTrackEndedListener listener = track -> { }; + + AllocationFault.failNextListener(); + + assertThrows(Error.class, () -> audioTrack.addTrackEndedListener(listener)); + + // Any change of the track reaches all of its observers. + audioTrack.setEnabled(false); + + audioTrack.addTrackEndedListener(listener); + audioTrack.setEnabled(true); + audioTrack.removeTrackEndedListener(listener); + } + +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/AllocationFault.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/AllocationFault.java new file mode 100644 index 000000000..f0b39c494 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/AllocationFault.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package dev.onvoid.webrtc.internal; + +/** + * Makes an allocation of the native library 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. It lives in the tests so that nothing else can reach it. + *

    + * The library has to be loaded, as it is by any test that created a factory. + * + * @author Alex Andres + */ +public final class AllocationFault { + + private AllocationFault() { + // Static access only. + } + + /** + * Fails the next registration of a track listener, right after the track + * got its observer and before anything owns that observer. + */ + public static native void failNextListener(); + + /** + * Fails the next {@code encoded_observer_add()} of the extension API, as + * an allocation for the handle it returns does. + */ + public static native void failNextEncodedObserver(); + + /** + * Calls {@code encoded_observer_add()} of the extension API, with an + * observer that ignores its frames. + * + * @param frames A handle from {@link NativeApi#encodedFramesOf}. + * + * @return The observer, or {@code 0} if it could not be attached. + */ + static native long addEncodedObserver(long frames); + + /** + * Calls {@code encoded_observer_remove()} of the extension API. + * + * @param observer The observer from {@link #addEncodedObserver(long)}. + */ + static native void removeEncodedObserver(long observer); + + /** + * @param frames A handle from {@link NativeApi#encodedFramesOf}. + * + * @return How many observers are attached to what the handle stands for. + */ + static native int encodedObservers(long frames); + + /** + * Forgets a fault that has not fired. + */ + public static native void disarm(); + +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/NativeApiTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/NativeApiTests.java index e6a81d0e0..dfec20d41 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/internal/NativeApiTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/NativeApiTests.java @@ -21,11 +21,19 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import dev.onvoid.webrtc.RTCConfiguration; +import dev.onvoid.webrtc.RTCPeerConnection; +import dev.onvoid.webrtc.RTCRtpSender; import dev.onvoid.webrtc.TestBase; import dev.onvoid.webrtc.media.SyncClock; +import dev.onvoid.webrtc.media.audio.AudioOptions; +import dev.onvoid.webrtc.media.audio.AudioTrack; +import dev.onvoid.webrtc.media.audio.AudioTrackSource; import dev.onvoid.webrtc.media.audio.CustomAudioSource; import dev.onvoid.webrtc.media.video.CustomVideoSource; +import java.util.Collections; + import org.junit.jupiter.api.Test; /** @@ -82,6 +90,46 @@ void handleOfNull() { assertThrows(NullPointerException.class, () -> NativeApi.handleOf(null)); } + @Test + void failedObserverAddAttachesNothing() { + AudioTrackSource source = factory.createAudioSource(new AudioOptions()); + AudioTrack track = factory.createAudioTrack("audioTrack", source); + RTCPeerConnection connection = factory.createPeerConnection(new RTCConfiguration(), candidate -> { }); + + try { + RTCRtpSender sender = connection.addTrack(track, Collections.singletonList("stream")); + long frames = NativeApi.encodedFramesOf(sender); + + try { + AllocationFault.failNextEncodedObserver(); + + // An observer attached now could never be removed. + assertEquals(0L, AllocationFault.addEncodedObserver(frames)); + assertEquals(0, AllocationFault.encodedObservers(frames)); + + // The handle is still good for another try. + long observer = AllocationFault.addEncodedObserver(frames); + + assertNotEquals(0L, observer); + assertEquals(1, AllocationFault.encodedObservers(frames)); + + AllocationFault.removeEncodedObserver(observer); + + assertEquals(0, AllocationFault.encodedObservers(frames)); + } + finally { + NativeApi.releaseEncodedFrames(frames); + sender.dispose(); + } + } + finally { + AllocationFault.disarm(); + connection.close(); + track.dispose(); + source.dispose(); + } + } + @Test void mediaClockAdvances() throws Exception { // The clock the table's now_us() reports and in which the push