diff --git a/docs/guide/advanced/encoded-transforms.md b/docs/guide/advanced/encoded-transforms.md index 7386dab3f..fbcf48eaa 100644 --- a/docs/guide/advanced/encoded-transforms.md +++ b/docs/guide/advanced/encoded-transforms.md @@ -71,7 +71,7 @@ receiver.setTransform(frame -> { }); ``` -`setData` takes a `ByteBuffer` (its remaining bytes) or a `byte[]`, and the new payload may be larger or smaller than the old one. The payload is only copied into Java when `getData()` is called, so a transform that looks at the metadata alone costs no copy at all. +`setData` takes a `ByteBuffer` (its remaining bytes) or a `byte[]`, and the new payload may be larger or smaller than the old one. The payload is only copied into Java when `getData()` is called, so a transform that looks at the metadata alone costs no copy at all. Each transform thread reuses at most 256 KiB of direct scratch memory. Larger payloads use a temporary buffer sized to the frame, released for garbage collection when the transform returns. Workloads with frequent larger frames therefore allocate a buffer for each of them. A frame, and the buffer `getData()` returned, is valid only while `transform` runs and only on its thread. The buffer's memory is reused for the next frame, so copy what you need to keep. Reading or changing a frame after the transform returned throws an `IllegalStateException`; its metadata stays readable. diff --git a/docs/guide/audio/audio-processing.md b/docs/guide/audio/audio-processing.md index 6afd7db3b..2fb204890 100644 --- a/docs/guide/audio/audio-processing.md +++ b/docs/guide/audio/audio-processing.md @@ -61,6 +61,8 @@ With this approach, the WebRTC framework automatically applies the audio process For more control, you can manually process audio streams: +Sample rates in `AudioProcessingStreamConfig` must be positive and divisible by 100 so each 10 ms frame contains a whole number of samples. `AudioConverter` and `AudioResampler` require rates from 100 to 384000 Hz, also divisible by 100; for example, 44100 Hz is accepted and 48099 Hz is rejected. + ```java import dev.onvoid.webrtc.media.audio.AudioProcessing; import dev.onvoid.webrtc.media.audio.AudioProcessingConfig; @@ -354,4 +356,4 @@ These statistics are particularly useful for monitoring the performance of echo The `AudioProcessing` class provides powerful audio processing capabilities for real-time communications. By properly configuring and using these features, you can significantly improve the audio quality in your applications. -Remember that audio processing is CPU-intensive, so consider the performance implications when enabling multiple features, especially on resource-constrained devices. \ No newline at end of file +Remember that audio processing is CPU-intensive, so consider the performance implications when enabling multiple features, especially on resource-constrained devices. diff --git a/docs/guide/audio/custom-audio-source.md b/docs/guide/audio/custom-audio-source.md index 322c371a8..333e4e42b 100644 --- a/docs/guide/audio/custom-audio-source.md +++ b/docs/guide/audio/custom-audio-source.md @@ -86,7 +86,7 @@ The call checks its arguments and throws `IllegalArgumentException` rather than - Samples must be **16-bit** signed PCM in the platform byte order, with the channels interleaved. - The array must hold at least `frameCount * channels * 2` bytes. A longer array is fine; only that many bytes are read. - One call carries one chunk of exactly **10 ms**, so `frameCount` must be `sampleRate / 100`. Split audio of any other length, such as 20 ms buffers, into 10 ms chunks first, or let the [client API](/guide/client-api) do it. -- The sample rate must lie between 8000 and 192000 Hz, and the channel count must be 1, 2, 4, 6 or 8. +- The sample rate must lie between 8000 and 192000 Hz and be divisible by 100, and the channel count must be 1, 2, 4, 6 or 8. - A chunk may hold at most `CustomAudioSource.MAX_SAMPLES_PER_PUSH` samples counting every channel, which rules out the highest rates with many channels: 96 kHz with 8 channels or 192 kHz with 4 is the limit. - `frameCount` counts frames, not samples and not bytes. A frame holds one sample per channel, so 10 ms at 48 kHz is 480 frames whether it is mono or stereo. diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 3eddf1359..040c3964e 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -684,6 +684,8 @@ DataChannel positions = peer.createChannel("positions", ChannelOptions.builder() .build()); ``` +`maxRetransmits(int)` accepts 0 to 65535 retransmissions. `maxPacketLifeTime(Duration)` accepts nonnegative durations up to 65535 milliseconds; positive fractions of a millisecond are rounded down, so a duration below one millisecond becomes zero. The two limits exclude each other. Values outside these ranges are rejected before native processing. + `negotiatedId(int)` creates a channel both peers set up themselves with the same id, without announcing it; such a channel never shows up in `onChannel`. The [Data Channels](/guide/data/data-channels) guide explains the options in detail. ## WHIP and WHEP diff --git a/webrtc-jni/src/main/cpp/include/AllocationFault.h b/webrtc-jni/src/main/cpp/include/AllocationFault.h index 0265c14db..b2c9a4c37 100644 --- a/webrtc-jni/src/main/cpp/include/AllocationFault.h +++ b/webrtc-jni/src/main/cpp/include/AllocationFault.h @@ -23,7 +23,7 @@ namespace jni // 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. + // armed pays a single flag load. class AllocationFault { public: @@ -33,6 +33,9 @@ namespace jni // Fails the next encoded_observer_add() of the extension API, once, // as an allocation for its handle does. static void FailNextEncodedObserver(); + // Fails the next handle lease, as inserting its map entry can. + static void FailNextNativeLease(); + static void CheckNativeLease(); // Forgets a fault that has not fired. static void Disarm(); // Throws std::bad_alloc if a fault is armed, and disarms it. diff --git a/webrtc-jni/src/main/cpp/include/JNI_AllocationFault.h b/webrtc-jni/src/main/cpp/include/JNI_AllocationFault.h index e42406d3f..c1b1b9cc4 100644 --- a/webrtc-jni/src/main/cpp/include/JNI_AllocationFault.h +++ b/webrtc-jni/src/main/cpp/include/JNI_AllocationFault.h @@ -27,6 +27,9 @@ extern "C" { * Method: failNextListener * Signature: ()V */ + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_failNextNativeLease + (JNIEnv *, jclass); + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_failNextListener (JNIEnv *, jclass); diff --git a/webrtc-jni/src/main/cpp/src/AllocationFault.cpp b/webrtc-jni/src/main/cpp/src/AllocationFault.cpp index f78b34909..c28c97da7 100644 --- a/webrtc-jni/src/main/cpp/src/AllocationFault.cpp +++ b/webrtc-jni/src/main/cpp/src/AllocationFault.cpp @@ -21,6 +21,8 @@ namespace { + // A lease failure belongs to the Java thread that armed it. + thread_local bool fail_native_lease = false; std::atomic fail_listener{ false }; std::atomic fail_encoded_observer{ false }; } @@ -37,8 +39,22 @@ namespace jni fail_encoded_observer.store(true); } + void AllocationFault::FailNextNativeLease() + { + fail_native_lease = true; + } + + void AllocationFault::CheckNativeLease() + { + if (fail_native_lease) { + fail_native_lease = false; + throw std::bad_alloc(); + } + } + void AllocationFault::Disarm() { + fail_native_lease = false; fail_listener.store(false); fail_encoded_observer.store(false); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_AllocationFault.cpp b/webrtc-jni/src/main/cpp/src/JNI_AllocationFault.cpp index e2c756479..fdfa5076f 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_AllocationFault.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_AllocationFault.cpp @@ -15,6 +15,7 @@ */ #include "JNI_AllocationFault.h" +#include "JavaBoundary.h" #include "AllocationFault.h" #include "api/EncodedFrameTransformer.h" @@ -30,38 +31,58 @@ namespace // 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_failNextNativeLease +(JNIEnv * env, jclass caller) +{ + jni::CallFromJava(env, [&]() { + jni::AllocationFault::FailNextNativeLease(); + }); +} + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_failNextListener (JNIEnv * env, jclass caller) { - jni::AllocationFault::FailNextListener(); + jni::CallFromJava(env, [&]() { + jni::AllocationFault::FailNextListener(); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_failNextEncodedObserver (JNIEnv * env, jclass caller) { - jni::AllocationFault::FailNextEncodedObserver(); + jni::CallFromJava(env, [&]() { + 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)); + return jni::CallFromJava(env, [&]() -> jlong { + 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)); + jni::CallFromJava(env, [&]() { + 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()); + return jni::CallFromJava(env, [&]() -> jint { + return static_cast(reinterpret_cast(frames)->GetObserverCount()); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_AllocationFault_disarm (JNIEnv * env, jclass caller) { - jni::AllocationFault::Disarm(); + jni::CallFromJava(env, [&]() { + jni::AllocationFault::Disarm(); + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_AudioConverter.cpp b/webrtc-jni/src/main/cpp/src/JNI_AudioConverter.cpp index a5d003d6b..47c1e6c4b 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_AudioConverter.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_AudioConverter.cpp @@ -93,19 +93,21 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioConverter_dispose JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioConverter_initialize (JNIEnv * env, jobject caller, jint srcSampleRate, jint srcChannels, jint dstSampleRate, jint dstChannels) { - // 10 ms frames - size_t srcFrames = webrtc::AudioProcessing::GetFrameSize(srcSampleRate); - size_t dstFrames = webrtc::AudioProcessing::GetFrameSize(dstSampleRate); + jni::CallFromJava(env, [&]() { + // 10 ms frames + size_t srcFrames = webrtc::AudioProcessing::GetFrameSize(srcSampleRate); + size_t dstFrames = webrtc::AudioProcessing::GetFrameSize(dstSampleRate); - try { - jni::AudioConverter * converter = jni::AudioConverter::create(srcFrames, srcChannels, dstFrames, dstChannels).release(); + try { + jni::AudioConverter * converter = jni::AudioConverter::create(srcFrames, srcChannels, dstFrames, dstChannels).release(); - SetHandle(env, caller, converter); - } - catch (const std::invalid_argument & e) { - ThrowJavaException(env, "java/lang/IllegalArgumentException", e.what()); - } - catch (...) { - ThrowCxxJavaException(env); - } + SetHandle(env, caller, converter); + } + catch (const std::invalid_argument & e) { + ThrowJavaException(env, "java/lang/IllegalArgumentException", e.what()); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_BuiltinAudioDecoderFactory.cpp b/webrtc-jni/src/main/cpp/src/JNI_BuiltinAudioDecoderFactory.cpp index 7fe925634..4f19cbcb8 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_BuiltinAudioDecoderFactory.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_BuiltinAudioDecoderFactory.cpp @@ -15,6 +15,7 @@ */ #include "JNI_BuiltinAudioDecoderFactory.h" +#include "JavaBoundary.h" #include "media/audio/codec/AudioCodecInfo.h" #include "JavaUtils.h" @@ -23,14 +24,16 @@ JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_media_audio_codec_BuiltinAudioDecoderFactory_getBuiltinCodecs (JNIEnv * env, jclass caller) { - try { - auto factory = webrtc::CreateBuiltinAudioDecoderFactory(); + return jni::CallFromJava(env, [&]() -> jobjectArray { + try { + auto factory = webrtc::CreateBuiltinAudioDecoderFactory(); - return jni::AudioCodecInfo::toJavaArray(env, factory->GetSupportedDecoders()).release(); - } - catch (...) { - ThrowCxxJavaException(env); - } + return jni::AudioCodecInfo::toJavaArray(env, factory->GetSupportedDecoders()).release(); + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_BuiltinAudioEncoderFactory.cpp b/webrtc-jni/src/main/cpp/src/JNI_BuiltinAudioEncoderFactory.cpp index 1a36d8235..c8236e893 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_BuiltinAudioEncoderFactory.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_BuiltinAudioEncoderFactory.cpp @@ -15,6 +15,7 @@ */ #include "JNI_BuiltinAudioEncoderFactory.h" +#include "JavaBoundary.h" #include "media/audio/codec/AudioCodecInfo.h" #include "JavaUtils.h" @@ -23,14 +24,16 @@ JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_media_audio_codec_BuiltinAudioEncoderFactory_getBuiltinCodecs (JNIEnv * env, jclass caller) { - try { - auto factory = webrtc::CreateBuiltinAudioEncoderFactory(); + return jni::CallFromJava(env, [&]() -> jobjectArray { + try { + auto factory = webrtc::CreateBuiltinAudioEncoderFactory(); - return jni::AudioCodecInfo::toJavaArray(env, factory->GetSupportedEncoders()).release(); - } - catch (...) { - ThrowCxxJavaException(env); - } + return jni::AudioCodecInfo::toJavaArray(env, factory->GetSupportedEncoders()).release(); + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_DefaultVideoDecoderFactory.cpp b/webrtc-jni/src/main/cpp/src/JNI_DefaultVideoDecoderFactory.cpp index 3a0f113e4..af728d72f 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_DefaultVideoDecoderFactory.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_DefaultVideoDecoderFactory.cpp @@ -15,6 +15,7 @@ */ #include "JNI_DefaultVideoDecoderFactory.h" +#include "JavaBoundary.h" #include "media/video/codec/DefaultVideoCodecFactories.h" #include "media/video/codec/VideoCodecInfo.h" #include "JavaUtils.h" @@ -22,14 +23,16 @@ JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_media_video_codec_DefaultVideoDecoderFactory_getSupportedCodecsInternal (JNIEnv * env, jclass caller) { - try { - auto factory = jni::CreateDefaultVideoDecoderFactory(); + return jni::CallFromJava(env, [&]() -> jobjectArray { + try { + auto factory = jni::CreateDefaultVideoDecoderFactory(); - return jni::VideoCodecInfo::toJavaArray(env, factory->GetSupportedFormats()).release(); - } - catch (...) { - ThrowCxxJavaException(env); - } + return jni::VideoCodecInfo::toJavaArray(env, factory->GetSupportedFormats()).release(); + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_DefaultVideoEncoderFactory.cpp b/webrtc-jni/src/main/cpp/src/JNI_DefaultVideoEncoderFactory.cpp index cf0159610..db16f1d5d 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_DefaultVideoEncoderFactory.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_DefaultVideoEncoderFactory.cpp @@ -15,6 +15,7 @@ */ #include "JNI_DefaultVideoEncoderFactory.h" +#include "JavaBoundary.h" #include "media/video/codec/DefaultVideoCodecFactories.h" #include "media/video/codec/VideoCodecInfo.h" #include "JavaUtils.h" @@ -22,14 +23,16 @@ JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_media_video_codec_DefaultVideoEncoderFactory_getSupportedCodecsInternal (JNIEnv * env, jclass caller) { - try { - auto factory = jni::CreateDefaultVideoEncoderFactory(); + return jni::CallFromJava(env, [&]() -> jobjectArray { + try { + auto factory = jni::CreateDefaultVideoEncoderFactory(); - return jni::VideoCodecInfo::toJavaArray(env, factory->GetSupportedFormats()).release(); - } - catch (...) { - ThrowCxxJavaException(env); - } + return jni::VideoCodecInfo::toJavaArray(env, factory->GetSupportedFormats()).release(); + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_HardwareVideoDecoderFactory.cpp b/webrtc-jni/src/main/cpp/src/JNI_HardwareVideoDecoderFactory.cpp index 7342219ab..1cbb29751 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_HardwareVideoDecoderFactory.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_HardwareVideoDecoderFactory.cpp @@ -15,6 +15,7 @@ */ #include "JNI_HardwareVideoDecoderFactory.h" +#include "JavaBoundary.h" #include "media/video/codec/DefaultVideoCodecFactories.h" #include "media/video/codec/VideoCodecInfo.h" #include "JavaUtils.h" @@ -22,26 +23,28 @@ JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_media_video_codec_HardwareVideoDecoderFactory_getCodecsInternal (JNIEnv * env, jclass caller) { - try { - // One factory for both lists, as making one probes the hardware. - auto factory = jni::CreateHardwareVideoDecoderFactory(); + return jni::CallFromJava(env, [&]() -> jobjectArray { + try { + // One factory for both lists, as making one probes the hardware. + auto factory = jni::CreateHardwareVideoDecoderFactory(); - auto supported = jni::VideoCodecInfo::toJavaArray(env, factory->GetSupportedFormats()); - auto hardware = jni::VideoCodecInfo::toJavaArray(env, jni::GetHardwareVideoDecoderFormats(*factory)); - auto arrayClass = jni::JavaLocalRef(env, env->GetObjectClass(supported.get())); + auto supported = jni::VideoCodecInfo::toJavaArray(env, factory->GetSupportedFormats()); + auto hardware = jni::VideoCodecInfo::toJavaArray(env, jni::GetHardwareVideoDecoderFormats(*factory)); + auto arrayClass = jni::JavaLocalRef(env, env->GetObjectClass(supported.get())); - jobjectArray codecs = env->NewObjectArray(2, arrayClass.get(), nullptr); + jobjectArray codecs = env->NewObjectArray(2, arrayClass.get(), nullptr); - ExceptionCheck(env); + ExceptionCheck(env); - env->SetObjectArrayElement(codecs, 0, supported.get()); - env->SetObjectArrayElement(codecs, 1, hardware.get()); + env->SetObjectArrayElement(codecs, 0, supported.get()); + env->SetObjectArrayElement(codecs, 1, hardware.get()); - return codecs; - } - catch (...) { - ThrowCxxJavaException(env); - } + return codecs; + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_HardwareVideoEncoderFactory.cpp b/webrtc-jni/src/main/cpp/src/JNI_HardwareVideoEncoderFactory.cpp index 93ff50cc6..71592dd5e 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_HardwareVideoEncoderFactory.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_HardwareVideoEncoderFactory.cpp @@ -15,6 +15,7 @@ */ #include "JNI_HardwareVideoEncoderFactory.h" +#include "JavaBoundary.h" #include "media/video/codec/DefaultVideoCodecFactories.h" #include "media/video/codec/VideoCodecInfo.h" #include "JavaUtils.h" @@ -22,26 +23,28 @@ JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_media_video_codec_HardwareVideoEncoderFactory_getCodecsInternal (JNIEnv * env, jclass caller) { - try { - // One factory for both lists, as making one probes the hardware. - auto factory = jni::CreateHardwareVideoEncoderFactory(); + return jni::CallFromJava(env, [&]() -> jobjectArray { + try { + // One factory for both lists, as making one probes the hardware. + auto factory = jni::CreateHardwareVideoEncoderFactory(); - auto supported = jni::VideoCodecInfo::toJavaArray(env, factory->GetSupportedFormats()); - auto hardware = jni::VideoCodecInfo::toJavaArray(env, jni::GetHardwareVideoEncoderFormats(*factory)); - auto arrayClass = jni::JavaLocalRef(env, env->GetObjectClass(supported.get())); + auto supported = jni::VideoCodecInfo::toJavaArray(env, factory->GetSupportedFormats()); + auto hardware = jni::VideoCodecInfo::toJavaArray(env, jni::GetHardwareVideoEncoderFormats(*factory)); + auto arrayClass = jni::JavaLocalRef(env, env->GetObjectClass(supported.get())); - jobjectArray codecs = env->NewObjectArray(2, arrayClass.get(), nullptr); + jobjectArray codecs = env->NewObjectArray(2, arrayClass.get(), nullptr); - ExceptionCheck(env); + ExceptionCheck(env); - env->SetObjectArrayElement(codecs, 0, supported.get()); - env->SetObjectArrayElement(codecs, 1, hardware.get()); + env->SetObjectArrayElement(codecs, 0, supported.get()); + env->SetObjectArrayElement(codecs, 1, hardware.get()); - return codecs; - } - catch (...) { - ThrowCxxJavaException(env); - } + return codecs; + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_LeakDetector.cpp b/webrtc-jni/src/main/cpp/src/JNI_LeakDetector.cpp index 7c6254ecb..bb46a7926 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_LeakDetector.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_LeakDetector.cpp @@ -15,6 +15,7 @@ */ #include "JNI_LeakDetector.h" +#include "JavaBoundary.h" #include "JNI_WebRTC.h" #include "LeakDetection.h" #include "JavaUtils.h" @@ -81,41 +82,43 @@ namespace jni JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_LeakDetector_enableNative (JNIEnv * env, jclass) { - if (enabled.load()) { - return; - } + jni::CallFromJava(env, [&]() { + if (enabled.load()) { + return; + } - jclass cls = env->FindClass(PKG_INTERNAL "NativeObject"); + jclass cls = env->FindClass(PKG_INTERNAL "NativeObject"); - if (cls == nullptr) { - return; - } + if (cls == nullptr) { + return; + } - jmethodID bound = env->GetMethodID(cls, "nativeHandleBound", "()V"); + jmethodID bound = env->GetMethodID(cls, "nativeHandleBound", "()V"); - if (bound == nullptr) { - env->DeleteLocalRef(cls); - return; - } + if (bound == nullptr) { + env->DeleteLocalRef(cls); + return; + } - jmethodID released = env->GetMethodID(cls, "nativeHandleReleased", "()V"); + jmethodID released = env->GetMethodID(cls, "nativeHandleReleased", "()V"); - if (released == nullptr) { - env->DeleteLocalRef(cls); - return; - } + if (released == nullptr) { + env->DeleteLocalRef(cls); + return; + } - nativeObjectClass = static_cast(env->NewGlobalRef(cls)); - env->DeleteLocalRef(cls); + nativeObjectClass = static_cast(env->NewGlobalRef(cls)); + env->DeleteLocalRef(cls); - if (nativeObjectClass == nullptr) { - return; - } + if (nativeObjectClass == nullptr) { + return; + } - boundMethod = bound; - releasedMethod = released; + boundMethod = bound; + releasedMethod = released; - enabled.store(true, std::memory_order_release); + enabled.store(true, std::memory_order_release); - SetNativeHandleHook(&OnNativeHandleSet); + SetNativeHandleHook(&OnNativeHandleSet); + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp b/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp index 5557cafae..140073cc5 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_MediaDevices.cpp @@ -15,6 +15,7 @@ */ #include "JNI_MediaDevices.h" +#include "JavaBoundary.h" #include "JavaArrayList.h" #include "JavaContext.h" #include "JavaError.h" @@ -33,245 +34,261 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_addDeviceChangeListener (JNIEnv * env, jclass caller, jobject jListener) { - jni::WebRTCContext * context = static_cast(javaContext); - - try { - auto listener = new jni::DeviceChangeListener(env, jni::JavaGlobalRef(env, jListener)); - auto listenerPtr = std::shared_ptr(listener); - - context->getAudioDeviceManager()->attachHotplugListener(listenerPtr); - context->getVideoDeviceManager()->attachHotplugListener(listenerPtr); - - javaContext->addNativeRef(env, jni::JavaLocalRef(env, jListener), listenerPtr); - } - catch (const jni::AudioBackendUnavailableException & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); - } - catch (const std::bad_alloc &) { - ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); - } - catch (const jni::Exception & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); - } - catch (...) { - ThrowCxxJavaException(env); - } + jni::CallFromJava(env, [&]() { + jni::WebRTCContext * context = static_cast(javaContext); + + try { + auto listener = new jni::DeviceChangeListener(env, jni::JavaGlobalRef(env, jListener)); + auto listenerPtr = std::shared_ptr(listener); + + context->getAudioDeviceManager()->attachHotplugListener(listenerPtr); + context->getVideoDeviceManager()->attachHotplugListener(listenerPtr); + + javaContext->addNativeRef(env, jni::JavaLocalRef(env, jListener), listenerPtr); + } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_removeDeviceChangeListener (JNIEnv * env, jclass caller, jobject jListener) { - jni::WebRTCContext * context = static_cast(javaContext); - auto listener = javaContext->removeNativeRef(env, jni::JavaLocalRef(env, jListener)); - - try { - context->getAudioDeviceManager()->detachHotplugListener(listener); - context->getVideoDeviceManager()->detachHotplugListener(listener); - } - catch (const jni::AudioBackendUnavailableException & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); - } - catch (const std::bad_alloc &) { - ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); - } - catch (const jni::Exception & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); - } - catch (...) { - ThrowCxxJavaException(env); - } + jni::CallFromJava(env, [&]() { + jni::WebRTCContext * context = static_cast(javaContext); + auto listener = javaContext->removeNativeRef(env, jni::JavaLocalRef(env, jListener)); + + try { + context->getAudioDeviceManager()->detachHotplugListener(listener); + context->getVideoDeviceManager()->detachHotplugListener(listener); + } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getDefaultAudioRenderDevice (JNIEnv * env, jclass caller) { - jni::WebRTCContext * context = static_cast(javaContext); + return jni::CallFromJava(env, [&]() -> jobject { + jni::WebRTCContext * context = static_cast(javaContext); - try { - auto device = context->getAudioDeviceManager()->getDefaultAudioPlaybackDevice(); + try { + auto device = context->getAudioDeviceManager()->getDefaultAudioPlaybackDevice(); - if (device == nullptr) { - return nullptr; + if (device == nullptr) { + return nullptr; + } + + return jni::AudioDevice::toJavaAudioDevice(env, device).release(); + } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } + catch (...) { + ThrowCxxJavaException(env); } - return jni::AudioDevice::toJavaAudioDevice(env, device).release(); - } - catch (const jni::AudioBackendUnavailableException & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); - } - catch (const std::bad_alloc &) { - ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); - } - catch (const jni::Exception & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); - } - catch (...) { - ThrowCxxJavaException(env); - } - - return nullptr; + return nullptr; + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getDefaultAudioCaptureDevice (JNIEnv * env, jclass caller) { - jni::WebRTCContext * context = static_cast(javaContext); + return jni::CallFromJava(env, [&]() -> jobject { + jni::WebRTCContext * context = static_cast(javaContext); - try { - auto device = context->getAudioDeviceManager()->getDefaultAudioCaptureDevice(); + try { + auto device = context->getAudioDeviceManager()->getDefaultAudioCaptureDevice(); - if (device == nullptr) { - return nullptr; + if (device == nullptr) { + return nullptr; + } + + return jni::AudioDevice::toJavaAudioDevice(env, device).release(); + } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } + catch (...) { + ThrowCxxJavaException(env); } - return jni::AudioDevice::toJavaAudioDevice(env, device).release(); - } - catch (const jni::AudioBackendUnavailableException & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); - } - catch (const std::bad_alloc &) { - ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); - } - catch (const jni::Exception & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); - } - catch (...) { - ThrowCxxJavaException(env); - } - - return nullptr; + return nullptr; + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getAudioRenderDevices (JNIEnv * env, jclass caller) { - try { - jni::WebRTCContext * context = static_cast(javaContext); + return jni::CallFromJava(env, [&]() -> jobject { + try { + jni::WebRTCContext * context = static_cast(javaContext); - auto devices = context->getAudioDeviceManager()->getAudioPlaybackDevices(); + auto devices = context->getAudioDeviceManager()->getAudioPlaybackDevices(); - jni::JavaArrayList deviceList(env, devices.size()); + jni::JavaArrayList deviceList(env, devices.size()); - for (const auto & device : devices) { - deviceList.add(jni::AudioDevice::toJavaAudioDevice(env, device)); - } + for (const auto & device : devices) { + deviceList.add(jni::AudioDevice::toJavaAudioDevice(env, device)); + } - return deviceList.listObject().release(); - } - catch (const jni::AudioBackendUnavailableException & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); - } - catch (const std::bad_alloc &) { - ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); - } - catch (const jni::Exception & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); - } - catch (...) { - ThrowCxxJavaException(env); - } + return deviceList.listObject().release(); + } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getAudioCaptureDevices (JNIEnv * env, jclass caller) { - try { - jni::WebRTCContext * context = static_cast(javaContext); + return jni::CallFromJava(env, [&]() -> jobject { + try { + jni::WebRTCContext * context = static_cast(javaContext); - auto devices = context->getAudioDeviceManager()->getAudioCaptureDevices(); + auto devices = context->getAudioDeviceManager()->getAudioCaptureDevices(); - jni::JavaArrayList deviceList(env, devices.size()); + jni::JavaArrayList deviceList(env, devices.size()); - for (const auto & device : devices) { - deviceList.add(jni::AudioDevice::toJavaAudioDevice(env, device)); - } + for (const auto & device : devices) { + deviceList.add(jni::AudioDevice::toJavaAudioDevice(env, device)); + } - return deviceList.listObject().release(); - } - catch (const jni::AudioBackendUnavailableException & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); - } - catch (const std::bad_alloc &) { - ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); - } - catch (const jni::Exception & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); - } - catch (...) { - ThrowCxxJavaException(env); - } + return deviceList.listObject().release(); + } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getVideoCaptureDevices (JNIEnv * env, jclass caller) { - try { - jni::WebRTCContext * context = static_cast(javaContext); + return jni::CallFromJava(env, [&]() -> jobject { + try { + jni::WebRTCContext * context = static_cast(javaContext); - auto devices = context->getVideoDeviceManager()->getVideoCaptureDevices(); + auto devices = context->getVideoDeviceManager()->getVideoCaptureDevices(); - jni::JavaArrayList deviceList(env, devices.size()); + jni::JavaArrayList deviceList(env, devices.size()); - for (const auto & device : devices) { - deviceList.add(jni::VideoDevice::toJavaVideoDevice(env, *device.get())); - } + for (const auto & device : devices) { + deviceList.add(jni::VideoDevice::toJavaVideoDevice(env, *device.get())); + } - return deviceList.listObject().release(); - } - catch (const jni::AudioBackendUnavailableException & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); - } - catch (const std::bad_alloc &) { - ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); - } - catch (const jni::Exception & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); - } - catch (...) { - ThrowCxxJavaException(env); - } + return deviceList.listObject().release(); + } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaDevices_getVideoCaptureCapabilities (JNIEnv * env, jclass caller, jobject device) { - if (!device) { - env->Throw(jni::JavaNullPointerException(env, "VideoDevice is null")); - return nullptr; - } + return jni::CallFromJava(env, [&]() -> jobject { + if (!device) { + env->Throw(jni::JavaNullPointerException(env, "VideoDevice is null")); + return nullptr; + } - try { - jni::WebRTCContext * context = static_cast(javaContext); + try { + jni::WebRTCContext * context = static_cast(javaContext); - auto dev = jni::VideoDevice::toNativeVideoDevice(env, jni::JavaLocalRef(env, device)); - auto capabilities = context->getVideoDeviceManager()->getVideoCaptureCapabilities(dev); + auto dev = jni::VideoDevice::toNativeVideoDevice(env, jni::JavaLocalRef(env, device)); + auto capabilities = context->getVideoDeviceManager()->getVideoCaptureCapabilities(dev); - jni::JavaArrayList capabilityList(env, capabilities.size()); + jni::JavaArrayList capabilityList(env, capabilities.size()); - for (const auto & capability : capabilities) { - capabilityList.add(jni::VideoCaptureCapability::toJava(env, capability)); - } + for (const auto & capability : capabilities) { + capabilityList.add(jni::VideoCaptureCapability::toJava(env, capability)); + } - return capabilityList.listObject().release(); - } - catch (const jni::AudioBackendUnavailableException & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); - } - catch (const std::bad_alloc &) { - ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); - } - catch (const jni::Exception & e) { - ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); - } - catch (...) { - ThrowCxxJavaException(env); - } + return capabilityList.listObject().release(); + } + catch (const jni::AudioBackendUnavailableException & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/AudioBackendUnavailableException", e.what()); + } + catch (const std::bad_alloc &) { + ThrowJavaException(env, "java/lang/OutOfMemoryError", "Allocating native device resources failed"); + } + catch (const jni::Exception & e) { + ThrowJavaException(env, "dev/onvoid/webrtc/media/DeviceException", e.what()); + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp b/webrtc-jni/src/main/cpp/src/JNI_MediaStreamTrack.cpp index fd0db4317..deebeb268 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 "JavaBoundary.h" #include "AllocationFault.h" #include "NativeHandle.h" #include "JavaContext.h" @@ -65,55 +66,57 @@ namespace JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_dispose (JNIEnv * env, jobject caller) { - webrtc::MediaStreamTrackInterface * track = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::MediaStreamTrackInterface * track = jni::TakeHandle(env, caller); - if (track == nullptr) { - return; - } + if (track == nullptr) { + return; + } - // A view holds no reference to the track and does not own its listeners: - // the track lives on with whatever owns it, so only this object detaches. - if (jni::MediaStreamTrackView::isView(env, caller)) { - return; - } + // A view holds no reference to the track and does not own its listeners: + // the track lives on with whatever owns it, so only this object detaches. + if (jni::MediaStreamTrackView::isView(env, caller)) { + return; + } - // Disposed from a listener of this track, or of another track the same - // notification reaches: WebRTC goes on calling the observers of the track - // from a copy of their list, and they use the track. Both are freed once - // the notification is over. - bool inCallback = jni::MediaStreamTrackObserver::InCallback(); - webrtc::Thread * callbackThread = inCallback ? webrtc::Thread::Current() : nullptr; - - // Listeners still registered are taken off the track before it goes. Their - // entries are keyed by this track's address, which a later track can be - // given, and an observer left registered would be freed with its entry - // while the track (if something else still holds it) can still call it. - auto observers = javaContext->removeNativeRefs(track); - - for (const auto & observer : observers) { - observer->detach(); - track->UnregisterObserver(observer.get()); - } + // Disposed from a listener of this track, or of another track the same + // notification reaches: WebRTC goes on calling the observers of the track + // from a copy of their list, and they use the track. Both are freed once + // the notification is over. + bool inCallback = jni::MediaStreamTrackObserver::InCallback(); + webrtc::Thread * callbackThread = inCallback ? webrtc::Thread::Current() : nullptr; - jni::ReleaseHandle(env, track, [track, observers, inCallback, callbackThread](bool deferred) { - // The observers go with the last copy of this. - auto release = [track, observers, report = deferred || inCallback]() { - if (track->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - jni::NativeHandle::ReportNotDeleted(report); - } - }; + // Listeners still registered are taken off the track before it goes. Their + // entries are keyed by this track's address, which a later track can be + // given, and an observer left registered would be freed with its entry + // while the track (if something else still holds it) can still call it. + auto observers = javaContext->removeNativeRefs(track); - if (callbackThread != nullptr) { - // Also when a method of another thread held the track until now: - // the notification may still be under way on the callback's thread. - callbackThread->PostTask(std::move(release)); - } - else if (inCallback && !deferred) { - jni::MediaStreamTrackObserver::AfterNotification(std::move(release)); - } - else { - release(); + for (const auto & observer : observers) { + observer->detach(); + track->UnregisterObserver(observer.get()); } + + jni::ReleaseHandle(env, track, [track, observers, inCallback, callbackThread](bool deferred) { + // The observers go with the last copy of this. + auto release = [track, observers, report = deferred || inCallback]() { + if (track->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + jni::NativeHandle::ReportNotDeleted(report); + } + }; + + if (callbackThread != nullptr) { + // Also when a method of another thread held the track until now: + // the notification may still be under way on the callback's thread. + callbackThread->PostTask(std::move(release)); + } + else if (inCallback && !deferred) { + jni::MediaStreamTrackObserver::AfterNotification(std::move(release)); + } + else { + release(); + } + }); }); } @@ -150,19 +153,23 @@ JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_getId JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_isEnabled (JNIEnv * env, jobject caller) { - jni::NativeLease track(env, caller); - CHECK_HANDLEV(track, false); + return jni::CallFromJava(env, [&]() -> jboolean { + jni::NativeLease track(env, caller); + CHECK_HANDLEV(track, false); - return static_cast(track->enabled()); + return static_cast(track->enabled()); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_setEnabled (JNIEnv * env, jobject caller, jboolean enabled) { - jni::NativeLease track(env, caller); - CHECK_HANDLE(track); + jni::CallFromJava(env, [&]() { + jni::NativeLease track(env, caller); + CHECK_HANDLE(track); - track->set_enabled(static_cast(enabled)); + track->set_enabled(static_cast(enabled)); + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_getState @@ -183,73 +190,81 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_getState JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_addEndedEventListener (JNIEnv * env, jobject caller, jobject jListener) { - jni::NativeLease track(env, caller); - CHECK_HANDLE(track); + jni::CallFromJava(env, [&]() { + jni::NativeLease track(env, caller); + CHECK_HANDLE(track); - try { - AddListener(env, track, jListener, jni::MediaStreamTrackEvent::ended); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + AddListener(env, track, jListener, jni::MediaStreamTrackEvent::ended); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_removeEndedEventListener (JNIEnv * env, jobject caller, jobject jListener) { - jni::NativeLease track(env, caller); - CHECK_HANDLE(track); + jni::CallFromJava(env, [&]() { + jni::NativeLease track(env, caller); + CHECK_HANDLE(track); - try { - auto observerPtr = javaContext->removeNativeRef(env, jni::JavaLocalRef(env, jListener), track, static_cast(jni::MediaStreamTrackEvent::ended)); + try { + auto observerPtr = javaContext->removeNativeRef(env, jni::JavaLocalRef(env, jListener), track, static_cast(jni::MediaStreamTrackEvent::ended)); - if (observerPtr) { - observerPtr->detach(); - track->UnregisterObserver(observerPtr.get()); + if (observerPtr) { + observerPtr->detach(); + track->UnregisterObserver(observerPtr.get()); - // Removed in a callback, maybe its own: freed once the notification - // is over. - jni::MediaStreamTrackObserver::AfterNotification([observerPtr]() {}); + // Removed in a callback, maybe its own: freed once the notification + // is over. + jni::MediaStreamTrackObserver::AfterNotification([observerPtr]() {}); + } } - } - catch (...) { - ThrowCxxJavaException(env); - } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_addMuteEventListener (JNIEnv * env, jobject caller, jobject jListener) { - jni::NativeLease track(env, caller); - CHECK_HANDLE(track); + jni::CallFromJava(env, [&]() { + jni::NativeLease track(env, caller); + CHECK_HANDLE(track); - try { - AddListener(env, track, jListener, jni::MediaStreamTrackEvent::mute); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + AddListener(env, track, jListener, jni::MediaStreamTrackEvent::mute); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStreamTrack_removeMuteEventListener (JNIEnv * env, jobject caller, jobject jListener) { - jni::NativeLease track(env, caller); - CHECK_HANDLE(track); + jni::CallFromJava(env, [&]() { + jni::NativeLease track(env, caller); + CHECK_HANDLE(track); - try { - auto observerPtr = javaContext->removeNativeRef(env, jni::JavaLocalRef(env, jListener), track, static_cast(jni::MediaStreamTrackEvent::mute)); + try { + auto observerPtr = javaContext->removeNativeRef(env, jni::JavaLocalRef(env, jListener), track, static_cast(jni::MediaStreamTrackEvent::mute)); - if (observerPtr) { - observerPtr->detach(); - track->UnregisterObserver(observerPtr.get()); + if (observerPtr) { + observerPtr->detach(); + track->UnregisterObserver(observerPtr.get()); - // Removed in a callback, maybe its own: freed once the notification - // is over. - jni::MediaStreamTrackObserver::AfterNotification([observerPtr]() {}); + // Removed in a callback, maybe its own: freed once the notification + // is over. + jni::MediaStreamTrackObserver::AfterNotification([observerPtr]() {}); + } } - } - catch (...) { - ThrowCxxJavaException(env); - } + catch (...) { + ThrowCxxJavaException(env); + } + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_NativeVideoDecoderCallback.cpp b/webrtc-jni/src/main/cpp/src/JNI_NativeVideoDecoderCallback.cpp index 0a0728cd2..8dd1a1549 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_NativeVideoDecoderCallback.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_NativeVideoDecoderCallback.cpp @@ -15,6 +15,7 @@ */ #include "JNI_NativeVideoDecoderCallback.h" +#include "JavaBoundary.h" #include "media/video/codec/VideoDecoderWrapper.h" #include "JavaUtils.h" @@ -23,24 +24,26 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_codec_NativeVideoDecoderCallback_onDecodedFrame (JNIEnv * env, jclass caller, jlong handle, jobject frame, jint decodeTimeMs, jint qp) { - // The Java callback holds its lock and has checked the handle, so the - // wrapper cannot be released meanwhile. - auto decoder = reinterpret_cast(handle); + jni::CallFromJava(env, [&]() { + // The Java callback holds its lock and has checked the handle, so the + // wrapper cannot be released meanwhile. + auto decoder = reinterpret_cast(handle); - std::optional decodeTime; - std::optional frameQp; + std::optional decodeTime; + std::optional frameQp; - if (decodeTimeMs >= 0) { - decodeTime = static_cast(decodeTimeMs); - } - if (qp >= 0 && qp <= 255) { - frameQp = static_cast(qp); - } + if (decodeTimeMs >= 0) { + decodeTime = static_cast(decodeTimeMs); + } + if (qp >= 0 && qp <= 255) { + frameQp = static_cast(qp); + } - try { - decoder->OnDecodedFrame(env, frame, decodeTime, frameQp); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + decoder->OnDecodedFrame(env, frame, decodeTime, frameQp); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_NativeVideoEncoderCallback.cpp b/webrtc-jni/src/main/cpp/src/JNI_NativeVideoEncoderCallback.cpp index b611e0ee6..0a8bf244f 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_NativeVideoEncoderCallback.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_NativeVideoEncoderCallback.cpp @@ -15,20 +15,23 @@ */ #include "JNI_NativeVideoEncoderCallback.h" +#include "JavaBoundary.h" #include "media/video/codec/VideoEncoderWrapper.h" #include "JavaUtils.h" JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_codec_NativeVideoEncoderCallback_onEncodedFrame (JNIEnv * env, jclass caller, jlong handle, jobject image) { - // The Java callback holds its lock and has checked the handle, so the - // wrapper cannot be released meanwhile. - auto encoder = reinterpret_cast(handle); + jni::CallFromJava(env, [&]() { + // The Java callback holds its lock and has checked the handle, so the + // wrapper cannot be released meanwhile. + auto encoder = reinterpret_cast(handle); - try { - encoder->OnEncodedFrame(env, image); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + encoder->OnEncodedFrame(env, image); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_PeerConnectionFactory.cpp b/webrtc-jni/src/main/cpp/src/JNI_PeerConnectionFactory.cpp index cafa97641..0c7a9b65b 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_PeerConnectionFactory.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_PeerConnectionFactory.cpp @@ -15,6 +15,7 @@ */ #include "JNI_PeerConnectionFactory.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/AudioOptions.h" #include "api/CreateSessionDescriptionObserver.h" @@ -63,216 +64,220 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_initialize jobject jVideoEncoderFactory, jobject jVideoDecoderFactory, jobject jAudioEncoderFactory, jobject jAudioDecoderFactory, jboolean hardwareEncoders, jboolean hardwareDecoders) { - webrtc::AudioDeviceModule * audioDevModule = (audioModule != nullptr) - ? GetHandle(env, audioModule) - : nullptr; + jni::CallFromJava(env, [&]() { + webrtc::AudioDeviceModule * audioDevModule = (audioModule != nullptr) + ? GetHandle(env, audioModule) + : nullptr; - try { - std::map fieldTrialsMap; + try { + std::map fieldTrialsMap; - if (jFieldTrials != nullptr) { - for (const auto & entry : jni::JavaHashMap(env, jni::JavaLocalRef(env, jFieldTrials))) { - std::string key = jni::JavaString::toNative(env, jni::static_java_ref_cast(env, entry.first)); - std::string value = jni::JavaString::toNative(env, jni::static_java_ref_cast(env, entry.second)); + if (jFieldTrials != nullptr) { + for (const auto & entry : jni::JavaHashMap(env, jni::JavaLocalRef(env, jFieldTrials))) { + std::string key = jni::JavaString::toNative(env, jni::static_java_ref_cast(env, entry.first)); + std::string value = jni::JavaString::toNative(env, jni::static_java_ref_cast(env, entry.second)); - if (key.empty() || value.empty()) { - throw jni::Exception("Invalid field trial entry: key and value must not be empty"); - } + if (key.empty() || value.empty()) { + throw jni::Exception("Invalid field trial entry: key and value must not be empty"); + } - fieldTrialsMap.emplace(std::move(key), std::move(value)); + fieldTrialsMap.emplace(std::move(key), std::move(value)); + } } - } - - std::unique_ptr fieldTrials = fieldTrialsMap.empty() - ? nullptr - : std::make_unique(std::move(fieldTrialsMap)); - - // Asks the Java factories for their codecs, which is where a broken - // factory surfaces, before anything else is set up. Without a Java - // factory, the built-in codecs are used directly. - std::unique_ptr videoEncoderFactory = (jVideoEncoderFactory != nullptr) - ? std::make_unique(env, jVideoEncoderFactory) - : hardwareEncoders - ? jni::CreateHardwareVideoEncoderFactory() - : jni::CreateDefaultVideoEncoderFactory(); - std::unique_ptr videoDecoderFactory = (jVideoDecoderFactory != nullptr) - ? std::make_unique(env, jVideoDecoderFactory) - : hardwareDecoders - ? jni::CreateHardwareVideoDecoderFactory() - : jni::CreateDefaultVideoDecoderFactory(); - - webrtc::scoped_refptr audioEncoderFactory = - jni::CreateAudioEncoderFactory(env, jni::JavaLocalRef(env, jAudioEncoderFactory)); - webrtc::scoped_refptr audioDecoderFactory = - jni::CreateAudioDecoderFactory(env, jni::JavaLocalRef(env, jAudioDecoderFactory)); - - auto networkThread = webrtc::Thread::CreateWithSocketServer(); - networkThread->SetName("webrtc_jni_network_thread", nullptr); - - auto signalingThread = webrtc::Thread::Create(); - signalingThread->SetName("webrtc_jni_signaling_thread", nullptr); - - if (!networkThread->Start()) { - throw jni::Exception("Start network thread failed"); - } - if (!signalingThread->Start()) { - throw jni::Exception("Start signaling thread failed"); - } - - webrtc::AudioProcessing * processing = (audioProcessing != nullptr) - ? GetHandle(env, audioProcessing) - : nullptr; - webrtc::scoped_refptr adm(audioDevModule); - if (!adm) { - // Without a module, the factory would create the platform default itself - // and abort the process when it fails to initialize, which happens on - // hosts without an audio system. Create it here instead, the same way - // AudioDeviceModule does, so a failure becomes an exception that the - // application can handle, for example by passing a module created - // with AudioLayer.kDummyAudio. - jni::WebRTCContext * context = static_cast(javaContext); + std::unique_ptr fieldTrials = fieldTrialsMap.empty() + ? nullptr + : std::make_unique(std::move(fieldTrialsMap)); + + // Asks the Java factories for their codecs, which is where a broken + // factory surfaces, before anything else is set up. Without a Java + // factory, the built-in codecs are used directly. + std::unique_ptr videoEncoderFactory = (jVideoEncoderFactory != nullptr) + ? std::make_unique(env, jVideoEncoderFactory) + : hardwareEncoders + ? jni::CreateHardwareVideoEncoderFactory() + : jni::CreateDefaultVideoEncoderFactory(); + std::unique_ptr videoDecoderFactory = (jVideoDecoderFactory != nullptr) + ? std::make_unique(env, jVideoDecoderFactory) + : hardwareDecoders + ? jni::CreateHardwareVideoDecoderFactory() + : jni::CreateDefaultVideoDecoderFactory(); + + webrtc::scoped_refptr audioEncoderFactory = + jni::CreateAudioEncoderFactory(env, jni::JavaLocalRef(env, jAudioEncoderFactory)); + webrtc::scoped_refptr audioDecoderFactory = + jni::CreateAudioDecoderFactory(env, jni::JavaLocalRef(env, jAudioDecoderFactory)); + + auto networkThread = webrtc::Thread::CreateWithSocketServer(); + networkThread->SetName("webrtc_jni_network_thread", nullptr); + + auto signalingThread = webrtc::Thread::Create(); + signalingThread->SetName("webrtc_jni_signaling_thread", nullptr); + + if (!networkThread->Start()) { + throw jni::Exception("Start network thread failed"); + } + if (!signalingThread->Start()) { + throw jni::Exception("Start signaling thread failed"); + } - adm = webrtc::CreateAudioDeviceModule(context->webrtcEnv, webrtc::AudioDeviceModule::kPlatformDefaultAudio); + webrtc::AudioProcessing * processing = (audioProcessing != nullptr) + ? GetHandle(env, audioProcessing) + : nullptr; + webrtc::scoped_refptr adm(audioDevModule); if (!adm) { - throw jni::Exception("Create the default AudioDeviceModule failed"); - } - if (adm->Init() != 0) { - throw jni::Exception("Initialize the default AudioDeviceModule failed. On a host without an audio system, pass an AudioDeviceModule created with AudioLayer.kDummyAudio."); + // Without a module, the factory would create the platform default itself + // and abort the process when it fails to initialize, which happens on + // hosts without an audio system. Create it here instead, the same way + // AudioDeviceModule does, so a failure becomes an exception that the + // application can handle, for example by passing a module created + // with AudioLayer.kDummyAudio. + jni::WebRTCContext * context = static_cast(javaContext); + + adm = webrtc::CreateAudioDeviceModule(context->webrtcEnv, webrtc::AudioDeviceModule::kPlatformDefaultAudio); + + if (!adm) { + throw jni::Exception("Create the default AudioDeviceModule failed"); + } + if (adm->Init() != 0) { + throw jni::Exception("Initialize the default AudioDeviceModule failed. On a host without an audio system, pass an AudioDeviceModule created with AudioLayer.kDummyAudio."); + } } - } - // Hand WebRTC a proxy of the module so the device capture path can be - // switched off once this factory sends audio from sink-fed sources. See - // ProxyAudioDeviceModule for why both paths must never feed the same - // send stream. - auto proxy = jni::ProxyAudioDeviceModule::Create(adm); - - // No worker thread is supplied: WebRTC is removing support for one that - // is distinct from the network thread, and without one the factory - // uses the network thread as its worker thread. - webrtc::PeerConnectionFactoryDependencies dependencies; - dependencies.network_thread = networkThread.get(); - dependencies.signaling_thread = signalingThread.get(); - dependencies.socket_factory = networkThread->socketserver(); - dependencies.event_log_factory = std::make_unique(); - dependencies.env = webrtc::CreateEnvironment(std::move(fieldTrials)); - dependencies.adm = proxy; - dependencies.audio_encoder_factory = audioEncoderFactory; - dependencies.audio_decoder_factory = audioDecoderFactory; - // The tap of the module that processes the captured audio: that of the - // application's module, or of the one built here. - std::shared_ptr tap; - - if (processing != nullptr) { - auto moduleTap = GetHandle>(env, audioProcessing, "captureTapHandle"); - - if (moduleTap == nullptr) { - throw jni::Exception("The AudioProcessing was disposed"); - } + // Hand WebRTC a proxy of the module so the device capture path can be + // switched off once this factory sends audio from sink-fed sources. See + // ProxyAudioDeviceModule for why both paths must never feed the same + // send stream. + auto proxy = jni::ProxyAudioDeviceModule::Create(adm); + + // No worker thread is supplied: WebRTC is removing support for one that + // is distinct from the network thread, and without one the factory + // uses the network thread as its worker thread. + webrtc::PeerConnectionFactoryDependencies dependencies; + dependencies.network_thread = networkThread.get(); + dependencies.signaling_thread = signalingThread.get(); + dependencies.socket_factory = networkThread->socketserver(); + dependencies.event_log_factory = std::make_unique(); + dependencies.env = webrtc::CreateEnvironment(std::move(fieldTrials)); + dependencies.adm = proxy; + dependencies.audio_encoder_factory = audioEncoderFactory; + dependencies.audio_decoder_factory = audioDecoderFactory; + // The tap of the module that processes the captured audio: that of the + // application's module, or of the one built here. + std::shared_ptr tap; + + if (processing != nullptr) { + auto moduleTap = GetHandle>(env, audioProcessing, "captureTapHandle"); + + if (moduleTap == nullptr) { + throw jni::Exception("The AudioProcessing was disposed"); + } - tap = *moduleTap; - dependencies.audio_processing_builder = webrtc::CustomAudioProcessing( - webrtc::scoped_refptr(processing)); - } - else { - tap = std::make_shared(); + tap = *moduleTap; + dependencies.audio_processing_builder = webrtc::CustomAudioProcessing( + webrtc::scoped_refptr(processing)); + } + else { + tap = std::make_shared(); - auto builder = std::make_unique(); - builder->SetCapturePostProcessing(jni::AudioCaptureTap::CreateProcessing(tap)); + auto builder = std::make_unique(); + builder->SetCapturePostProcessing(jni::AudioCaptureTap::CreateProcessing(tap)); - dependencies.audio_processing_builder = std::move(builder); - } - dependencies.video_encoder_factory = std::move(videoEncoderFactory); - dependencies.video_decoder_factory = std::move(videoDecoderFactory); + dependencies.audio_processing_builder = std::move(builder); + } + dependencies.video_encoder_factory = std::move(videoEncoderFactory); + dependencies.video_decoder_factory = std::move(videoDecoderFactory); - webrtc::EnableMedia(dependencies); + webrtc::EnableMedia(dependencies); - auto factory = webrtc::CreateModularPeerConnectionFactory(std::move(dependencies)); + auto factory = webrtc::CreateModularPeerConnectionFactory(std::move(dependencies)); - if (factory != nullptr) { - SetHandle(env, caller, factory.release()); - SetHandle(env, caller, "networkThreadHandle", networkThread.release()); - SetHandle(env, caller, "signalingThreadHandle", signalingThread.release()); - SetHandle(env, caller, "audioModuleHandle", proxy.release()); - SetHandle(env, caller, "captureTapHandle", new std::shared_ptr(std::move(tap))); + if (factory != nullptr) { + SetHandle(env, caller, factory.release()); + SetHandle(env, caller, "networkThreadHandle", networkThread.release()); + SetHandle(env, caller, "signalingThreadHandle", signalingThread.release()); + SetHandle(env, caller, "audioModuleHandle", proxy.release()); + SetHandle(env, caller, "captureTapHandle", new std::shared_ptr(std::move(tap))); + } + else { + throw jni::Exception("Create PeerConnectionFactory failed"); + } } - else { - throw jni::Exception("Create PeerConnectionFactory failed"); + catch (...) { + ThrowCxxJavaException(env); } - } - catch (...) { - ThrowCxxJavaException(env); - } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_disposeInternal (JNIEnv * env, jobject caller) { - webrtc::PeerConnectionFactoryInterface * factory = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::PeerConnectionFactoryInterface * factory = jni::TakeHandle(env, caller); - if (factory == nullptr) { - return; - } - - webrtc::Thread * networkThread = GetHandle(env, caller, "networkThreadHandle"); - webrtc::Thread * signalingThread = GetHandle(env, caller, "signalingThreadHandle"); - jni::ProxyAudioDeviceModule * audioModule = GetHandle(env, caller, "audioModuleHandle"); - auto tap = GetHandle>(env, caller, "captureTapHandle"); - - // The calls that use them hold the factory's handle, so they are freed - // with it. - SetHandle(env, caller, "networkThreadHandle", nullptr); - SetHandle(env, caller, "signalingThreadHandle", nullptr); - SetHandle(env, caller, "audioModuleHandle", nullptr); - SetHandle(env, caller, "captureTapHandle", nullptr); - - auto release = [factory, networkThread, signalingThread, audioModule, tap](bool deferred) { - if (factory->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - jni::NativeHandle::ReportNotDeleted(deferred); + if (factory == nullptr) { + return; } - if (networkThread) { - networkThread->Stop(); - delete networkThread; - } - if (signalingThread) { - signalingThread->Stop(); - delete signalingThread; - } - if (audioModule) { - // The factory dropped its reference above; this releases the last one - // and, with it, the proxy's reference on the wrapped module. - webrtc::RefCountReleaseStatus admStatus = audioModule->Release(); + webrtc::Thread * networkThread = GetHandle(env, caller, "networkThreadHandle"); + webrtc::Thread * signalingThread = GetHandle(env, caller, "signalingThreadHandle"); + jni::ProxyAudioDeviceModule * audioModule = GetHandle(env, caller, "audioModuleHandle"); + auto tap = GetHandle>(env, caller, "captureTapHandle"); - if (admStatus != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - RTC_LOG(LS_WARNING) << "ProxyAudioDeviceModule was not deleted. A reference is still around somewhere."; - } - } + // The calls that use them hold the factory's handle, so they are freed + // with it. + SetHandle(env, caller, "networkThreadHandle", nullptr); + SetHandle(env, caller, "signalingThreadHandle", nullptr); + SetHandle(env, caller, "audioModuleHandle", nullptr); + SetHandle(env, caller, "captureTapHandle", nullptr); - // The module, if anything still holds it, keeps a share of the tap. - delete tap; - }; + auto release = [factory, networkThread, signalingThread, audioModule, tap](bool deferred) { + if (factory->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + jni::NativeHandle::ReportNotDeleted(deferred); + } - try { - jni::ReleaseHandle(env, factory, [release, networkThread, signalingThread](bool deferred) { - // A call that held the factory may have run on one of its threads, - // which cannot stop itself. - bool onOwnThread = (networkThread && networkThread->IsCurrent()) || - (signalingThread && signalingThread->IsCurrent()); - - if (onOwnThread) { - std::thread([release]() { release(true); }).detach(); + if (networkThread) { + networkThread->Stop(); + delete networkThread; } - else { - release(deferred); + if (signalingThread) { + signalingThread->Stop(); + delete signalingThread; } - }); - } - catch (...) { - ThrowCxxJavaException(env); - } + if (audioModule) { + // The factory dropped its reference above; this releases the last one + // and, with it, the proxy's reference on the wrapped module. + webrtc::RefCountReleaseStatus admStatus = audioModule->Release(); + + if (admStatus != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + RTC_LOG(LS_WARNING) << "ProxyAudioDeviceModule was not deleted. A reference is still around somewhere."; + } + } + + // The module, if anything still holds it, keeps a share of the tap. + delete tap; + }; + + try { + jni::ReleaseHandle(env, factory, [release, networkThread, signalingThread](bool deferred) { + // A call that held the factory may have run on one of its threads, + // which cannot stop itself. + bool onOwnThread = (networkThread && networkThread->IsCurrent()) || + (signalingThread && signalingThread->IsCurrent()); + + if (onOwnThread) { + std::thread([release]() { release(true); }).detach(); + } + else { + release(deferred); + } + }); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_addVoiceActivityListenerInternal @@ -318,19 +323,21 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_removeVoiceA JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_setDeviceCaptureEnabled (JNIEnv * env, jobject caller, jboolean enabled) { - // Keeps the module, which a dispose releases with the factory. - jni::NativeLease factory(env, caller); - CHECK_HANDLE(factory); + jni::CallFromJava(env, [&]() { + // Keeps the module, which a dispose releases with the factory. + jni::NativeLease factory(env, caller); + CHECK_HANDLE(factory); - jni::ProxyAudioDeviceModule * audioModule = GetHandle(env, caller, "audioModuleHandle"); - CHECK_HANDLE(audioModule); + jni::ProxyAudioDeviceModule * audioModule = GetHandle(env, caller, "audioModuleHandle"); + CHECK_HANDLE(audioModule); - try { - audioModule->SetCaptureEnabled(enabled == JNI_TRUE); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + audioModule->SetCaptureEnabled(enabled == JNI_TRUE); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_createAudioSourceInternal @@ -396,29 +403,31 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_createAud JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_isSinkFedAudioTrack (JNIEnv * env, jobject caller, jobject jTrack) { - if (jTrack == nullptr) { - return JNI_FALSE; - } + return jni::CallFromJava(env, [&]() -> jboolean { + if (jTrack == nullptr) { + return JNI_FALSE; + } - jni::NativeLease track(env, jTrack); + jni::NativeLease track(env, jTrack); - if (track == nullptr || track->kind() != webrtc::MediaStreamTrackInterface::kAudioKind) { - return JNI_FALSE; - } + if (track == nullptr || track->kind() != webrtc::MediaStreamTrackInterface::kAudioKind) { + return JNI_FALSE; + } - webrtc::AudioSourceInterface * source = static_cast(track.get())->GetSource(); + webrtc::AudioSourceInterface * source = static_cast(track.get())->GetSource(); - if (source == nullptr) { - return JNI_FALSE; - } + if (source == nullptr) { + return JNI_FALSE; + } - // A remote source hands the track's sinks the audio it decodes, and a - // CustomAudioSource hands them the audio the application pushes. Either way - // a sender of that track is fed through the track rather than by the audio - // device module. - bool sinkFed = source->remote() || dynamic_cast(source) != nullptr; + // A remote source hands the track's sinks the audio it decodes, and a + // CustomAudioSource hands them the audio the application pushes. Either way + // a sender of that track is fed through the track rather than by the audio + // device module. + bool sinkFed = source->remote() || dynamic_cast(source) != nullptr; - return sinkFed ? JNI_TRUE : JNI_FALSE; + return sinkFed ? JNI_TRUE : JNI_FALSE; + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_createVideoTrack @@ -456,72 +465,74 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_createVid JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_createPeerConnectionInternal (JNIEnv * env, jobject caller, jobject jConfig, jobject jobserver) { - if (jConfig == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCConfiguration is null")); - return nullptr; - } - if (jobserver == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "PeerConnectionObserver is null")); - return nullptr; - } + return jni::CallFromJava(env, [&]() -> jobject { + if (jConfig == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCConfiguration is null")); + return nullptr; + } + if (jobserver == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "PeerConnectionObserver is null")); + return nullptr; + } - jni::NativeLease factory(env, caller); - CHECK_HANDLEV(factory, nullptr); + jni::NativeLease factory(env, caller); + CHECK_HANDLEV(factory, nullptr); - webrtc::PeerConnectionInterface::RTCConfiguration configuration; + webrtc::PeerConnectionInterface::RTCConfiguration configuration; - try { - configuration = jni::RTCConfiguration::toNative(env, jni::JavaLocalRef(env, jConfig)); - } - catch (...) { - ThrowCxxJavaException(env); - return nullptr; - } + try { + configuration = jni::RTCConfiguration::toNative(env, jni::JavaLocalRef(env, jConfig)); + } + catch (...) { + ThrowCxxJavaException(env); + return nullptr; + } - webrtc::PeerConnectionObserver * observer = new jni::PeerConnectionObserver(env, jni::JavaGlobalRef(env, jobserver)); - webrtc::PeerConnectionDependencies dependencies(observer); + webrtc::PeerConnectionObserver * observer = new jni::PeerConnectionObserver(env, jni::JavaGlobalRef(env, jobserver)); + webrtc::PeerConnectionDependencies dependencies(observer); - auto result = factory->CreatePeerConnectionOrError(configuration, std::move(dependencies)); + auto result = factory->CreatePeerConnectionOrError(configuration, std::move(dependencies)); - if (!result.ok()) { - // No peer connection took the observer. - delete observer; + if (!result.ok()) { + // No peer connection took the observer. + delete observer; - // The type is a string_view, which is not terminated and cannot be - // passed through varargs as it is. - const std::string type(ToString(result.error().type())); + // The type is a string_view, which is not terminated and cannot be + // passed through varargs as it is. + const std::string type(ToString(result.error().type())); - env->Throw(jni::JavaRuntimeException(env, "Create PeerConnection failed: %s %s", - type.c_str(), result.error().message())); + env->Throw(jni::JavaRuntimeException(env, "Create PeerConnection failed: %s %s", + type.c_str(), result.error().message())); - return nullptr; - } + return nullptr; + } - auto pc = result.MoveValue(); + auto pc = result.MoveValue(); - if (pc == nullptr) { - delete observer; - return nullptr; - } + if (pc == nullptr) { + delete observer; + return nullptr; + } - try { - // The observer is bound before the Java object takes the connection, so - // that it ends up with both of them or with neither. - auto javaPeerConnection = jni::JavaFactories::createOwning(env, std::move(pc), [&](jobject object) { - SetHandle(env, object, "observerHandle", observer); - }); + try { + // The observer is bound before the Java object takes the connection, so + // that it ends up with both of them or with neither. + auto javaPeerConnection = jni::JavaFactories::createOwning(env, std::move(pc), [&](jobject object) { + SetHandle(env, object, "observerHandle", observer); + }); - return javaPeerConnection.release(); - } - catch (...) { - // The connection is still ours. It calls the observer while it closes, - // so it goes first. - pc = nullptr; - delete observer; + return javaPeerConnection.release(); + } + catch (...) { + // The connection is still ours. It calls the observer while it closes, + // so it goes first. + pc = nullptr; + delete observer; - ThrowCxxJavaException(env); - return nullptr; - } + ThrowCxxJavaException(env); + return nullptr; + } + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_PeerConnectionFactory_getRtpReceiverCapabilities diff --git a/webrtc-jni/src/main/cpp/src/JNI_PowerManagement.cpp b/webrtc-jni/src/main/cpp/src/JNI_PowerManagement.cpp index 38fd5220d..46ddbeac4 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_PowerManagement.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_PowerManagement.cpp @@ -15,34 +15,39 @@ */ #include "JNI_PowerManagement.h" +#include "JavaBoundary.h" #include "WebRTCContext.h" JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagement_enableUserActivityInternal (JNIEnv * env, jobject caller) { - jni::WebRTCContext * context = static_cast(javaContext); + jni::CallFromJava(env, [&]() { + jni::WebRTCContext * context = static_cast(javaContext); - try { - context->getPowerManagement()->enableUserActivity(); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + context->getPowerManagement()->enableUserActivity(); + } + catch (...) { + ThrowCxxJavaException(env); + } - fflush(NULL); + fflush(NULL); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_PowerManagement_disableUserActivityInternal (JNIEnv * env, jobject caller) { - jni::WebRTCContext * context = static_cast(javaContext); + jni::CallFromJava(env, [&]() { + jni::WebRTCContext * context = static_cast(javaContext); - try { - context->getPowerManagement()->disableUserActivity(); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + context->getPowerManagement()->disableUserActivity(); + } + catch (...) { + ThrowCxxJavaException(env); + } - fflush(NULL); + fflush(NULL); + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp index 7aa3e7513..57f71ba6e 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCDataChannel.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RTCDataChannel.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/RTCDataChannelObserver.h" #include "api/RTCDataChannelSendObserver.h" @@ -98,37 +99,45 @@ JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getLabel JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_isReliable (JNIEnv * env, jobject caller) { - jni::NativeLease channel(env, caller); - CHECK_HANDLEV(channel, false); + return jni::CallFromJava(env, [&]() -> jboolean { + jni::NativeLease channel(env, caller); + CHECK_HANDLEV(channel, false); - return static_cast(channel->reliable()); + return static_cast(channel->reliable()); + }); } JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_isOrdered (JNIEnv * env, jobject caller) { - jni::NativeLease channel(env, caller); - CHECK_HANDLEV(channel, false); + return jni::CallFromJava(env, [&]() -> jboolean { + jni::NativeLease channel(env, caller); + CHECK_HANDLEV(channel, false); - return static_cast(channel->ordered()); + return static_cast(channel->ordered()); + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getMaxPacketLifeTime (JNIEnv * env, jobject caller) { - jni::NativeLease channel(env, caller); - CHECK_HANDLEV(channel, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease channel(env, caller); + CHECK_HANDLEV(channel, 0); - return static_cast(channel->maxPacketLifeTime().value_or(0)); + return static_cast(channel->maxPacketLifeTime().value_or(0)); + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getMaxRetransmits (JNIEnv * env, jobject caller) { - jni::NativeLease channel(env, caller); - CHECK_HANDLEV(channel, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease channel(env, caller); + CHECK_HANDLEV(channel, 0); - return static_cast(channel->maxRetransmitsOpt().value_or(0)); + return static_cast(channel->maxRetransmitsOpt().value_or(0)); + }); } JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getProtocol @@ -149,10 +158,12 @@ JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getProtocol JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_isNegotiated (JNIEnv * env, jobject caller) { - jni::NativeLease channel(env, caller); - CHECK_HANDLEV(channel, false); + return jni::CallFromJava(env, [&]() -> jboolean { + jni::NativeLease channel(env, caller); + CHECK_HANDLEV(channel, false); - return static_cast(channel->negotiated()); + return static_cast(channel->negotiated()); + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getPriority @@ -185,10 +196,12 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getPriority JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getId (JNIEnv * env, jobject caller) { - jni::NativeLease channel(env, caller); - CHECK_HANDLEV(channel, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease channel(env, caller); + CHECK_HANDLEV(channel, 0); - return static_cast(channel->id()); + return static_cast(channel->id()); + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getState @@ -209,42 +222,48 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getState JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_getBufferedAmount (JNIEnv * env, jobject caller) { - jni::NativeLease channel(env, caller); - CHECK_HANDLEV(channel, 0); + return jni::CallFromJava(env, [&]() -> jlong { + jni::NativeLease channel(env, caller); + CHECK_HANDLEV(channel, 0); - return static_cast(channel->buffered_amount()); + return static_cast(channel->buffered_amount()); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_close (JNIEnv * env, jobject caller) { - jni::NativeLease channel(env, caller); - CHECK_HANDLE(channel); + jni::CallFromJava(env, [&]() { + jni::NativeLease channel(env, caller); + CHECK_HANDLE(channel); - channel->Close(); + channel->Close(); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_dispose (JNIEnv * env, jobject caller) { - webrtc::DataChannelInterface * channel = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::DataChannelInterface * channel = jni::TakeHandle(env, caller); - if (channel == nullptr) { - return; - } + if (channel == nullptr) { + return; + } - auto slot = DataChannelObserverSlot::Take(env, caller, "observerHandle"); + auto slot = DataChannelObserverSlot::Take(env, caller, "observerHandle"); - // Runs once no other thread registers through this object any more, so - // the observer it frees is the one the channel has, if any. - jni::ReleaseHandle(env, channel, [channel, slot](bool deferred) { - if (slot) { - channel->UnregisterObserver(); - } + // Runs once no other thread registers through this object any more, so + // the observer it frees is the one the channel has, if any. + jni::ReleaseHandle(env, channel, [channel, slot](bool deferred) { + if (slot) { + channel->UnregisterObserver(); + } - if (channel->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - jni::NativeHandle::ReportNotDeleted(deferred); - } + if (channel->Release() != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + jni::NativeHandle::ReportNotDeleted(deferred); + } + }); }); } @@ -395,23 +414,31 @@ static void sendByteArrayBufferAsync(JNIEnv * env, jobject caller, jbyteArray jB JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_sendDirectBufferAsync (JNIEnv * env, jobject caller, jobject jBuffer, jint position, jint length, jboolean isBinary) { - sendDirectBufferAsync(env, caller, jBuffer, position, length, isBinary, nullptr); + jni::CallFromJava(env, [&]() { + sendDirectBufferAsync(env, caller, jBuffer, position, length, isBinary, nullptr); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_sendByteArrayBufferAsync (JNIEnv * env, jobject caller, jbyteArray jBufferArray, jboolean isBinary) { - sendByteArrayBufferAsync(env, caller, jBufferArray, isBinary, nullptr); + jni::CallFromJava(env, [&]() { + sendByteArrayBufferAsync(env, caller, jBufferArray, isBinary, nullptr); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_sendDirectBufferAsyncWithObserver (JNIEnv * env, jobject caller, jobject jBuffer, jint position, jint length, jboolean isBinary, jobject jObserver) { - sendDirectBufferAsync(env, caller, jBuffer, position, length, isBinary, jObserver); + jni::CallFromJava(env, [&]() { + sendDirectBufferAsync(env, caller, jBuffer, position, length, isBinary, jObserver); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDataChannel_sendByteArrayBufferAsyncWithObserver (JNIEnv * env, jobject caller, jbyteArray jBufferArray, jboolean isBinary, jobject jObserver) { - sendByteArrayBufferAsync(env, caller, jBufferArray, isBinary, jObserver); + jni::CallFromJava(env, [&]() { + sendByteArrayBufferAsync(env, caller, jBufferArray, isBinary, jObserver); + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCDtlsTransport.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCDtlsTransport.cpp index 43bad0914..f727c252a 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCDtlsTransport.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCDtlsTransport.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RTCDtlsTransport.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/ObserverSlot.h" #include "api/RegisteredObservers.h" @@ -139,24 +140,26 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtlsTransport_unregisterObserve JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtlsTransport_dispose (JNIEnv * env, jobject caller) { - webrtc::DtlsTransportInterface * transport = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::DtlsTransportInterface * transport = jni::TakeHandle(env, caller); - if (transport == nullptr) { - return; - } + if (transport == nullptr) { + return; + } - auto slot = DtlsTransportObserverSlot::Take(env, caller, "observerHandle"); + auto slot = DtlsTransportObserverSlot::Take(env, caller, "observerHandle"); - // Runs once no other thread registers through this object any more. WebRTC - // must let go of an observer registered through this object before it is - // deleted with the slot. The connection, its senders and receivers, and - // other Java objects keep their own references, so this one need not be - // the last. - jni::ReleaseHandle(env, transport, [transport, slot](bool) { - if (slot && jni::RegisteredObservers::Remove(transport, slot->applied())) { - transport->UnregisterObserver(); - } + // Runs once no other thread registers through this object any more. WebRTC + // must let go of an observer registered through this object before it is + // deleted with the slot. The connection, its senders and receivers, and + // other Java objects keep their own references, so this one need not be + // the last. + jni::ReleaseHandle(env, transport, [transport, slot](bool) { + if (slot && jni::RegisteredObservers::Remove(transport, slot->applied())) { + transport->UnregisterObserver(); + } - transport->Release(); + transport->Release(); + }); }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCDtmfSender.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCDtmfSender.cpp index 3707522b0..1e3ff453d 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCDtmfSender.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCDtmfSender.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RTCDtmfSender.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/ObserverSlot.h" #include "api/RegisteredObservers.h" @@ -45,10 +46,12 @@ namespace JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_canInsertDtmf (JNIEnv * env, jobject caller) { - jni::NativeLease sender(env, caller); - CHECK_HANDLEV(sender, false); + return jni::CallFromJava(env, [&]() -> jboolean { + jni::NativeLease sender(env, caller); + CHECK_HANDLEV(sender, false); - return static_cast(sender->CanInsertDtmf()); + return static_cast(sender->CanInsertDtmf()); + }); } JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_insertDtmf @@ -86,19 +89,23 @@ JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_tones JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_duration (JNIEnv * env, jobject caller) { - jni::NativeLease sender(env, caller); - CHECK_HANDLEV(sender, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease sender(env, caller); + CHECK_HANDLEV(sender, 0); - return static_cast(sender->duration()); + return static_cast(sender->duration()); + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_interToneGap (JNIEnv * env, jobject caller) { - jni::NativeLease sender(env, caller); - CHECK_HANDLEV(sender, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease sender(env, caller); + CHECK_HANDLEV(sender, 0); - return static_cast(sender->inter_tone_gap()); + return static_cast(sender->inter_tone_gap()); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_registerObserver @@ -134,23 +141,25 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_unregisterObserver JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCDtmfSender_dispose (JNIEnv * env, jobject caller) { - webrtc::DtmfSenderInterface * sender = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::DtmfSenderInterface * sender = jni::TakeHandle(env, caller); - if (sender == nullptr) { - return; - } + if (sender == nullptr) { + return; + } - auto slot = DtmfSenderObserverSlot::Take(env, caller, "observerHandle"); + auto slot = DtmfSenderObserverSlot::Take(env, caller, "observerHandle"); - // Runs once no other thread registers through this object any more. WebRTC - // must let go of an observer registered through this object before it is - // deleted with the slot. The RTCRtpSender and other Java objects keep their - // own references, so this one need not be the last. - jni::ReleaseHandle(env, sender, [sender, slot](bool) { - if (slot && jni::RegisteredObservers::Remove(sender, slot->applied())) { - sender->UnregisterObserver(); - } + // Runs once no other thread registers through this object any more. WebRTC + // must let go of an observer registered through this object before it is + // deleted with the slot. The RTCRtpSender and other Java objects keep their + // own references, so this one need not be the last. + jni::ReleaseHandle(env, sender, [sender, slot](bool) { + if (slot && jni::RegisteredObservers::Remove(sender, slot->applied())) { + sender->UnregisterObserver(); + } - sender->Release(); + sender->Release(); + }); }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp index ab6016f51..becbe0ffb 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCPeerConnection.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RTCPeerConnection.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/AddIceCandidateObserver.h" #include "api/CreateSessionDescriptionObserver.h" @@ -58,55 +59,61 @@ JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_getSenders (JNIEnv * env, jobject caller) { - jni::NativeLease pc(env, caller); - CHECK_HANDLEV(pc, nullptr); + return jni::CallFromJava(env, [&]() -> jobjectArray { + jni::NativeLease pc(env, caller); + CHECK_HANDLEV(pc, nullptr); - jni::JavaLocalRef objectArray; + jni::JavaLocalRef objectArray; - try { - objectArray = jni::createOwningObjectArray(env, pc->GetSenders()); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + objectArray = jni::createOwningObjectArray(env, pc->GetSenders()); + } + catch (...) { + ThrowCxxJavaException(env); + } - return objectArray.release(); + return objectArray.release(); + }); } JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_getReceivers (JNIEnv * env, jobject caller) { - jni::NativeLease pc(env, caller); - CHECK_HANDLEV(pc, nullptr); + return jni::CallFromJava(env, [&]() -> jobjectArray { + jni::NativeLease pc(env, caller); + CHECK_HANDLEV(pc, nullptr); - jni::JavaLocalRef objectArray; + jni::JavaLocalRef objectArray; - try { - objectArray = jni::createOwningObjectArray(env, pc->GetReceivers()); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + objectArray = jni::createOwningObjectArray(env, pc->GetReceivers()); + } + catch (...) { + ThrowCxxJavaException(env); + } - return objectArray.release(); + return objectArray.release(); + }); } JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_getTransceivers (JNIEnv * env, jobject caller) { - jni::NativeLease pc(env, caller); - CHECK_HANDLEV(pc, nullptr); + return jni::CallFromJava(env, [&]() -> jobjectArray { + jni::NativeLease pc(env, caller); + CHECK_HANDLEV(pc, nullptr); - jni::JavaLocalRef objectArray; + jni::JavaLocalRef objectArray; - try { - objectArray = jni::createOwningObjectArray(env, pc->GetTransceivers()); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + objectArray = jni::createOwningObjectArray(env, pc->GetTransceivers()); + } + catch (...) { + ThrowCxxJavaException(env); + } - return objectArray.release(); + return objectArray.release(); + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_addTrackInternal @@ -151,23 +158,25 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_addTrackInter JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_removeTrack (JNIEnv * env, jobject caller, jobject jSender) { - if (jSender == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCRtpSender must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jSender == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCRtpSender must not be null")); + return; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - jni::NativeLease sender(env, jSender); - CHECK_HANDLE(sender); + jni::NativeLease sender(env, jSender); + CHECK_HANDLE(sender); - auto result = pc->RemoveTrackOrError(webrtc::scoped_refptr(sender)); + auto result = pc->RemoveTrackOrError(webrtc::scoped_refptr(sender)); - if (!result.ok()) { - env->Throw(jni::JavaRuntimeException(env, "Remove track (RTCRtpSender) failed: %s %s", - ToString(result.type()), result.message())); - } + if (!result.ok()) { + env->Throw(jni::JavaRuntimeException(env, "Remove track (RTCRtpSender) failed: %s %s", + ToString(result.type()), result.message())); + } + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_addTransceiverInternal @@ -215,131 +224,139 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_addTransceive JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_addTransceiverOfType (JNIEnv * env, jobject caller, jobject jMediaType, jobject jTransceiverInit) { - if (jMediaType == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "MediaType must not be null")); - return nullptr; - } + return jni::CallFromJava(env, [&]() -> jobject { + if (jMediaType == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "MediaType must not be null")); + return nullptr; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLEV(pc, nullptr); + jni::NativeLease pc(env, caller); + CHECK_HANDLEV(pc, nullptr); - try { - auto mediaType = jni::JavaEnums::toNative(env, jMediaType); + try { + auto mediaType = jni::JavaEnums::toNative(env, jMediaType); - webrtc::RTCErrorOr> result; + webrtc::RTCErrorOr> result; - if (jTransceiverInit != nullptr) { - auto init = jni::RTCRtpTransceiverInit::toNative(env, jni::JavaLocalRef(env, jTransceiverInit)); + if (jTransceiverInit != nullptr) { + auto init = jni::RTCRtpTransceiverInit::toNative(env, jni::JavaLocalRef(env, jTransceiverInit)); - result = pc->AddTransceiver(mediaType, init); - } - else { - result = pc->AddTransceiver(mediaType); - } + result = pc->AddTransceiver(mediaType, init); + } + else { + result = pc->AddTransceiver(mediaType); + } - if (result.ok()) { - auto transceiver = result.MoveValue(); + if (result.ok()) { + auto transceiver = result.MoveValue(); - return jni::JavaFactories::createOwning(env, std::move(transceiver)).release(); - } + return jni::JavaFactories::createOwning(env, std::move(transceiver)).release(); + } - env->Throw(jni::JavaRuntimeException(env, "%s", jni::RTCErrorToString(result.error()).c_str())); - } - catch (...) { - ThrowCxxJavaException(env); - } + env->Throw(jni::JavaRuntimeException(env, "%s", jni::RTCErrorToString(result.error()).c_str())); + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_createDataChannel (JNIEnv * env, jobject caller, jstring jLabel, jobject jDict) { - if (jLabel == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "Label must not be null")); - return nullptr; - } - if (jDict == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCDataChannelInit must not be null")); - return nullptr; - } + return jni::CallFromJava(env, [&]() -> jobject { + if (jLabel == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "Label must not be null")); + return nullptr; + } + if (jDict == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCDataChannelInit must not be null")); + return nullptr; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLEV(pc, nullptr); + jni::NativeLease pc(env, caller); + CHECK_HANDLEV(pc, nullptr); - std::string label = jni::JavaString::toNative(env, jni::JavaLocalRef(env, jLabel)); - webrtc::DataChannelInit dict = jni::RTCDataChannelInit::toNative(env, jni::JavaLocalRef(env, jDict)); + std::string label = jni::JavaString::toNative(env, jni::JavaLocalRef(env, jLabel)); + webrtc::DataChannelInit dict = jni::RTCDataChannelInit::toNative(env, jni::JavaLocalRef(env, jDict)); - try { - auto result = pc->CreateDataChannelOrError(label, &dict); + try { + auto result = pc->CreateDataChannelOrError(label, &dict); - if (!result.ok()) { - env->Throw(jni::JavaRuntimeException(env, "Create DataChannel failed: %s %s", - ToString(result.error().type()), result.error().message())); + if (!result.ok()) { + env->Throw(jni::JavaRuntimeException(env, "Create DataChannel failed: %s %s", + ToString(result.error().type()), result.error().message())); - return nullptr; - } + return nullptr; + } - auto dataChannel = result.MoveValue(); + auto dataChannel = result.MoveValue(); - return jni::JavaFactories::createOwning(env, std::move(dataChannel)).release(); - } - catch (...) { - ThrowCxxJavaException(env); - return nullptr; - } + return jni::JavaFactories::createOwning(env, std::move(dataChannel)).release(); + } + catch (...) { + ThrowCxxJavaException(env); + return nullptr; + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_createOffer (JNIEnv * env, jobject caller, jobject jOptions, jobject jObserver) { - if (jOptions == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCOfferOptions must not be null")); - return; - } - if (jObserver == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "CreateSessionDescriptionObserver must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jOptions == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCOfferOptions must not be null")); + return; + } + if (jObserver == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "CreateSessionDescriptionObserver must not be null")); + return; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - try { - auto options = jni::RTCOfferOptions::toNative(env, jni::JavaLocalRef(env, jOptions)); - auto observer = new webrtc::RefCountedObject(env, jni::JavaGlobalRef(env, jObserver)); + try { + auto options = jni::RTCOfferOptions::toNative(env, jni::JavaLocalRef(env, jOptions)); + auto observer = new webrtc::RefCountedObject(env, jni::JavaGlobalRef(env, jObserver)); - pc->CreateOffer(observer, options); - } - catch (...) { - ThrowCxxJavaException(env); - } + pc->CreateOffer(observer, options); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_createAnswer (JNIEnv * env, jobject caller, jobject jOptions, jobject jObserver) { - if (jOptions == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCAnswerOptions must not be null")); - return; - } - if (jObserver == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "CreateSessionDescriptionObserver must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jOptions == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCAnswerOptions must not be null")); + return; + } + if (jObserver == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "CreateSessionDescriptionObserver must not be null")); + return; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - try { - auto options = jni::RTCAnswerOptions::toNative(env, jni::JavaLocalRef(env, jOptions)); - auto observer = new webrtc::RefCountedObject(env, jni::JavaGlobalRef(env, jObserver)); + try { + auto options = jni::RTCAnswerOptions::toNative(env, jni::JavaLocalRef(env, jOptions)); + auto observer = new webrtc::RefCountedObject(env, jni::JavaGlobalRef(env, jObserver)); - pc->CreateAnswer(observer, options); - } - catch (...) { - ThrowCxxJavaException(env); - } + pc->CreateAnswer(observer, options); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_getCurrentLocalDescription @@ -459,195 +476,213 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_getPendingRem JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_setLocalDescription (JNIEnv * env, jobject caller, jobject jSessionDesc, jobject jobserver) { - if (jSessionDesc == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCSessionDescription must not be null")); - return; - } - if (jobserver == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "SetSessionDescriptionObserver must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jSessionDesc == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCSessionDescription must not be null")); + return; + } + if (jobserver == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "SetSessionDescriptionObserver must not be null")); + return; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - try { - auto desc = jni::RTCSessionDescription::toNative(env, jni::JavaLocalRef(env, jSessionDesc)); - auto observer = new webrtc::RefCountedObject(env, jni::JavaGlobalRef(env, jobserver)); + try { + auto desc = jni::RTCSessionDescription::toNative(env, jni::JavaLocalRef(env, jSessionDesc)); + auto observer = new webrtc::RefCountedObject(env, jni::JavaGlobalRef(env, jobserver)); - pc->SetLocalDescription(observer, desc.release()); - } - catch (...) { - ThrowCxxJavaException(env); - } + pc->SetLocalDescription(observer, desc.release()); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_setLocalDescriptionImplicit (JNIEnv * env, jobject caller, jobject jobserver) { - if (jobserver == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "SetSessionDescriptionObserver must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jobserver == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "SetSessionDescriptionObserver must not be null")); + return; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - try { - auto observer = new webrtc::RefCountedObject(env, jni::JavaGlobalRef(env, jobserver)); + try { + auto observer = new webrtc::RefCountedObject(env, jni::JavaGlobalRef(env, jobserver)); - pc->SetLocalDescription(observer); - } - catch (...) { - ThrowCxxJavaException(env); - } + pc->SetLocalDescription(observer); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_setRemoteDescription (JNIEnv * env, jobject caller, jobject jSessionDesc, jobject jobserver) { - if (jSessionDesc == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCSessionDescription must not be null")); - return; - } - if (jobserver == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "SetSessionDescriptionObserver must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jSessionDesc == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCSessionDescription must not be null")); + return; + } + if (jobserver == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "SetSessionDescriptionObserver must not be null")); + return; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - try { - auto desc = jni::RTCSessionDescription::toNative(env, jni::JavaLocalRef(env, jSessionDesc)); - auto observer = new webrtc::RefCountedObject(env, jni::JavaGlobalRef(env, jobserver)); + try { + auto desc = jni::RTCSessionDescription::toNative(env, jni::JavaLocalRef(env, jSessionDesc)); + auto observer = new webrtc::RefCountedObject(env, jni::JavaGlobalRef(env, jobserver)); - pc->SetRemoteDescription(observer, desc.release()); - } - catch (...) { - ThrowCxxJavaException(env); - } + pc->SetRemoteDescription(observer, desc.release()); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_addIceCandidate (JNIEnv * env, jobject caller, jobject jCandidate) { - if (jCandidate == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCIceCandidate must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jCandidate == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCIceCandidate must not be null")); + return; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - try { - auto candidate = jni::RTCIceCandidate::toNative(env, jni::JavaLocalRef(env, jCandidate)); + try { + auto candidate = jni::RTCIceCandidate::toNative(env, jni::JavaLocalRef(env, jCandidate)); - pc->AddIceCandidate(candidate.get()); - } - catch (...) { - ThrowCxxJavaException(env); - } + pc->AddIceCandidate(candidate.get()); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_addIceCandidateWithObserver (JNIEnv * env, jobject caller, jobject jCandidate, jobject jObserver) { - if (jCandidate == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCIceCandidate must not be null")); - return; - } - if (jObserver == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "AddIceCandidateObserver must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jCandidate == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCIceCandidate must not be null")); + return; + } + if (jObserver == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "AddIceCandidateObserver must not be null")); + return; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - try { - auto candidate = jni::RTCIceCandidate::toNative(env, jni::JavaLocalRef(env, jCandidate)); + try { + auto candidate = jni::RTCIceCandidate::toNative(env, jni::JavaLocalRef(env, jCandidate)); - // std::function has to be copyable, the observer reports only once. - auto observer = std::make_shared(env, jni::JavaGlobalRef(env, jObserver)); + // std::function has to be copyable, the observer reports only once. + auto observer = std::make_shared(env, jni::JavaGlobalRef(env, jObserver)); - pc->AddIceCandidate(std::move(candidate), [observer](webrtc::RTCError error) { - observer->OnComplete(std::move(error)); - }); - } - catch (...) { - ThrowCxxJavaException(env); - } + pc->AddIceCandidate(std::move(candidate), [observer](webrtc::RTCError error) { + observer->OnComplete(std::move(error)); + }); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_removeIceCandidate (JNIEnv * env, jobject caller, jobject jCandidate) { - if (jCandidate == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCIceCandidate must not be null")); - return false; - } + return jni::CallFromJava(env, [&]() -> jboolean { + if (jCandidate == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCIceCandidate must not be null")); + return false; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLEV(pc, false); + jni::NativeLease pc(env, caller); + CHECK_HANDLEV(pc, false); - try { - auto candidate = jni::RTCIceCandidate::toNative(env, jni::JavaLocalRef(env, jCandidate)); + try { + auto candidate = jni::RTCIceCandidate::toNative(env, jni::JavaLocalRef(env, jCandidate)); - return static_cast(pc->RemoveIceCandidate(candidate.get())); - } - catch (...) { - ThrowCxxJavaException(env); - return false; - } + return static_cast(pc->RemoveIceCandidate(candidate.get())); + } + catch (...) { + ThrowCxxJavaException(env); + return false; + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_setBitrate (JNIEnv * env, jobject caller, jobject jMinBitrate, jobject jCurrentBitrate, jobject jMaxBitrate) { - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::CallFromJava(env, [&]() { + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - auto toOptional = [env](jobject value) -> std::optional { - if (value == nullptr) { - return std::nullopt; - } - return jni::Integer::getValue(env, value); - }; + auto toOptional = [env](jobject value) -> std::optional { + if (value == nullptr) { + return std::nullopt; + } + return jni::Integer::getValue(env, value); + }; - try { - webrtc::BitrateSettings settings; - settings.min_bitrate_bps = toOptional(jMinBitrate); - settings.start_bitrate_bps = toOptional(jCurrentBitrate); - settings.max_bitrate_bps = toOptional(jMaxBitrate); + try { + webrtc::BitrateSettings settings; + settings.min_bitrate_bps = toOptional(jMinBitrate); + settings.start_bitrate_bps = toOptional(jCurrentBitrate); + settings.max_bitrate_bps = toOptional(jMaxBitrate); - webrtc::RTCError error = pc->SetBitrate(settings); + webrtc::RTCError error = pc->SetBitrate(settings); - if (!error.ok()) { - env->Throw(jni::JavaRuntimeException(env, "%s", jni::RTCErrorToString(error).c_str())); + if (!error.ok()) { + env->Throw(jni::JavaRuntimeException(env, "%s", jni::RTCErrorToString(error).c_str())); + } } - } - catch (...) { - ThrowCxxJavaException(env); - } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_setAudioPlayout (JNIEnv * env, jobject caller, jboolean playout) { - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::CallFromJava(env, [&]() { + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - pc->SetAudioPlayout(static_cast(playout)); + pc->SetAudioPlayout(static_cast(playout)); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_setAudioRecording (JNIEnv * env, jobject caller, jboolean recording) { - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::CallFromJava(env, [&]() { + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - pc->SetAudioRecording(static_cast(recording)); + pc->SetAudioRecording(static_cast(recording)); + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_getSignalingState @@ -728,26 +763,28 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_getConfigurat JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_setConfiguration (JNIEnv * env, jobject caller, jobject jConfig) { - if (jConfig == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "RTCConfiguration must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jConfig == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "RTCConfiguration must not be null")); + return; + } - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - try { - auto config = jni::RTCConfiguration::toNative(env, jni::JavaLocalRef(env, jConfig)); + try { + auto config = jni::RTCConfiguration::toNative(env, jni::JavaLocalRef(env, jConfig)); - webrtc::RTCError error = pc->SetConfiguration(config); + webrtc::RTCError error = pc->SetConfiguration(config); - if (!error.ok()) { - env->Throw(jni::JavaRuntimeException(env, "%s", jni::RTCErrorToString(error).c_str())); + if (!error.ok()) { + env->Throw(jni::JavaRuntimeException(env, "%s", jni::RTCErrorToString(error).c_str())); + } } - } - catch (...) { - ThrowCxxJavaException(env); - } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_getStats__Ldev_onvoid_webrtc_RTCStatsCollectorCallback_2 @@ -830,110 +867,114 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_getStats__Ldev_o JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_restartIce (JNIEnv * env, jobject caller) { - jni::NativeLease pc(env, caller); - CHECK_HANDLE(pc); + jni::CallFromJava(env, [&]() { + jni::NativeLease pc(env, caller); + CHECK_HANDLE(pc); - pc->RestartIce(); + pc->RestartIce(); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCPeerConnection_close (JNIEnv * env, jobject caller) { - // Only the first of several closes gets the connection; the others, and - // later ones, find nothing to close. - webrtc::PeerConnectionInterface * pc = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + // Only the first of several closes gets the connection; the others, and + // later ones, find nothing to close. + webrtc::PeerConnectionInterface * pc = jni::TakeHandle(env, caller); - if (pc == nullptr) { - return; - } + if (pc == nullptr) { + return; + } - try { - jni::JavaLocalRef factory(env, env->GetObjectField(caller, - GetFieldID(env, caller, "factory", "L" PKG "PeerConnectionFactory;"))); - - // Keeps the factory's threads while the close is handed on. - jni::NativeLease factoryLease(env, factory.get()); - - webrtc::Thread * signalingThread = factoryLease - ? GetHandle(env, factory.get(), "signalingThreadHandle") - : nullptr; - - webrtc::PeerConnectionObserver * observer = GetHandle(env, caller, "observerHandle"); - - SetHandle(env, caller, "observerHandle", nullptr); - - // Closing takes effect at once, also while another thread is still in - // a method of the connection: that method finds it closed. Only freeing - // the observer and the connection waits, both for the close and for the - // last such method, whichever comes later. - struct Closing - { - webrtc::PeerConnectionInterface * pc; - webrtc::PeerConnectionObserver * observer; - jlong factoryHandle = 0; - std::atomic pending { 2 }; - }; + try { + jni::JavaLocalRef factory(env, env->GetObjectField(caller, + GetFieldID(env, caller, "factory", "L" PKG "PeerConnectionFactory;"))); - auto closing = std::make_shared(); - closing->pc = pc; - closing->observer = observer; + // Keeps the factory's threads while the close is handed on. + jni::NativeLease factoryLease(env, factory.get()); - // Until the connection is freed, a dispose of the factory waits for it: - // the close and the freeing run on the factory's signaling thread, and - // freeing the connection needs that thread. - if (factoryLease) { - closing->factoryHandle = reinterpret_cast(factoryLease.get()); + webrtc::Thread * signalingThread = factoryLease + ? GetHandle(env, factory.get(), "signalingThreadHandle") + : nullptr; - jni::NativeHandle::Pin(closing->factoryHandle); - } + webrtc::PeerConnectionObserver * observer = GetHandle(env, caller, "observerHandle"); - auto free = [closing]() { - if (--closing->pending == 0) { - // The connection lets go of its observer once closed. - delete closing->observer; + SetHandle(env, caller, "observerHandle", nullptr); - // Drop the owning reference taken when the PeerConnection was - // handed to Java in PeerConnectionFactory::createPeerConnection. - closing->pc->Release(); + // Closing takes effect at once, also while another thread is still in + // a method of the connection: that method finds it closed. Only freeing + // the observer and the connection waits, both for the close and for the + // last such method, whichever comes later. + struct Closing + { + webrtc::PeerConnectionInterface * pc; + webrtc::PeerConnectionObserver * observer; + jlong factoryHandle = 0; + std::atomic pending { 2 }; + }; - // May release a factory disposed meanwhile, which then stops its - // threads on a thread of its own when this is one of them. - if (closing->factoryHandle != 0) { - jni::NativeHandle::Unuse(AttachCurrentThread(), closing->factoryHandle); - } + auto closing = std::make_shared(); + closing->pc = pc; + closing->observer = observer; + + // Until the connection is freed, a dispose of the factory waits for it: + // the close and the freeing run on the factory's signaling thread, and + // freeing the connection needs that thread. + if (factoryLease) { + closing->factoryHandle = reinterpret_cast(factoryLease.get()); + + jni::NativeHandle::Pin(closing->factoryHandle); } - }; - auto close = [closing, free]() { - closing->pc->Close(); - free(); - }; + auto free = [closing]() { + if (--closing->pending == 0) { + // The connection lets go of its observer once closed. + delete closing->observer; - // Called from a callback of this or another connection of the same - // factory. WebRTC goes on with the connection once the callback has - // returned, so it must not be closed and freed under its feet. - bool inCallback = signalingThread != nullptr && signalingThread->IsCurrent(); + // Drop the owning reference taken when the PeerConnection was + // handed to Java in PeerConnectionFactory::createPeerConnection. + closing->pc->Release(); - if (inCallback) { - // Runs right after the callback, before what WebRTC posts in turn. - signalingThread->PostTask(close); - } - else { - close(); - } + // May release a factory disposed meanwhile, which then stops its + // threads on a thread of its own when this is one of them. + if (closing->factoryHandle != 0) { + jni::NativeHandle::Unuse(AttachCurrentThread(), closing->factoryHandle); + } + } + }; + + auto close = [closing, free]() { + closing->pc->Close(); + free(); + }; - // Runs once no other thread is in a method of this connection any - // more, which may be later, on the thread of the last such method. - jni::ReleaseHandle(env, pc, [free, signalingThread](bool) { - if (signalingThread != nullptr && signalingThread->IsCurrent()) { - signalingThread->PostTask(free); + // Called from a callback of this or another connection of the same + // factory. WebRTC goes on with the connection once the callback has + // returned, so it must not be closed and freed under its feet. + bool inCallback = signalingThread != nullptr && signalingThread->IsCurrent(); + + if (inCallback) { + // Runs right after the callback, before what WebRTC posts in turn. + signalingThread->PostTask(close); } else { - free(); + close(); } - }); - } - catch (...) { - ThrowCxxJavaException(env); - } + + // Runs once no other thread is in a method of this connection any + // more, which may be later, on the thread of the last such method. + jni::ReleaseHandle(env, pc, [free, signalingThread](bool) { + if (signalingThread != nullptr && signalingThread->IsCurrent()) { + signalingThread->PostTask(free); + } + else { + free(); + } + }); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCRtpReceiver.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCRtpReceiver.cpp index 151db902d..9b18e541b 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCRtpReceiver.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCRtpReceiver.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RTCRtpReceiver.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/ObserverSlot.h" #include "api/RegisteredObservers.h" @@ -38,13 +39,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_getTrack (JNIEnv * env, jobject caller) { - jni::NativeLease receiver(env, caller); - CHECK_HANDLEV(receiver, nullptr); + return jni::CallFromJava(env, [&]() -> jobject { + jni::NativeLease receiver(env, caller); + CHECK_HANDLEV(receiver, nullptr); - webrtc::scoped_refptr track = receiver->track(); + webrtc::scoped_refptr track = receiver->track(); - // The receiver keeps the track; the Java object is only a view of it. - return jni::MediaStreamTrackView::create(env, track.get()).release(); + // The receiver keeps the track; the Java object is only a view of it. + return jni::MediaStreamTrackView::create(env, track.get()).release(); + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_getTransport @@ -134,49 +137,53 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_getSynchronizati JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_setTransform (JNIEnv * env, jobject caller, jobject jTransformer) { - jni::NativeLease receiver(env, caller); - CHECK_HANDLE(receiver); + jni::CallFromJava(env, [&]() { + jni::NativeLease receiver(env, caller); + CHECK_HANDLE(receiver); - try { - // Clearing a transform that was never set installs nothing. - auto transformer = jTransformer != nullptr - ? jni::EncodedFrameTransformer::Of(receiver) - : jni::EncodedFrameTransformer::Find(receiver); + try { + // Clearing a transform that was never set installs nothing. + auto transformer = jTransformer != nullptr + ? jni::EncodedFrameTransformer::Of(receiver) + : jni::EncodedFrameTransformer::Find(receiver); - if (transformer) { - transformer->SetTransformer(env, jTransformer); + if (transformer) { + transformer->SetTransformer(env, jTransformer); + } } - } - catch (...) { - ThrowCxxJavaException(env); - } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_requestKeyFrame (JNIEnv * env, jobject caller) { - jni::NativeLease receiver(env, caller); - CHECK_HANDLE(receiver); + jni::CallFromJava(env, [&]() { + jni::NativeLease receiver(env, caller); + CHECK_HANDLE(receiver); - if (receiver->media_type() != webrtc::MediaType::VIDEO) { - return; - } + if (receiver->media_type() != webrtc::MediaType::VIDEO) { + return; + } - // A receiver has no way of its own to ask for a key frame, but the - // source of its track does: it is what the decoder feeds, and the one - // thing WebRTC lets ask the remote sender for a key frame on demand. - webrtc::scoped_refptr track = receiver->track(); + // A receiver has no way of its own to ask for a key frame, but the + // source of its track does: it is what the decoder feeds, and the one + // thing WebRTC lets ask the remote sender for a key frame on demand. + webrtc::scoped_refptr track = receiver->track(); - if (track == nullptr) { - return; - } + if (track == nullptr) { + return; + } - auto videoTrack = static_cast(track.get()); - webrtc::VideoTrackSourceInterface * source = videoTrack->GetSource(); + auto videoTrack = static_cast(track.get()); + webrtc::VideoTrackSourceInterface * source = videoTrack->GetSource(); - if (source != nullptr) { - source->GenerateKeyFrame(); - } + if (source != nullptr) { + source->GenerateKeyFrame(); + } + }); } JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_getId @@ -214,48 +221,52 @@ namespace JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_setObserver (JNIEnv * env, jobject caller, jobject jObserver) { - jni::NativeLease receiver(env, caller); - CHECK_HANDLE(receiver); + jni::CallFromJava(env, [&]() { + jni::NativeLease receiver(env, caller); + CHECK_HANDLE(receiver); - try { - jni::RTCRtpReceiverObserver * observer = nullptr; + try { + jni::RTCRtpReceiverObserver * observer = nullptr; - if (jObserver != nullptr) { - observer = new jni::RTCRtpReceiverObserver(env, jni::JavaGlobalRef(env, jObserver)); - } + if (jObserver != nullptr) { + observer = new jni::RTCRtpReceiverObserver(env, jni::JavaGlobalRef(env, jObserver)); + } - RTCRtpReceiverObserverSlot::Set(env, caller, "observerHandle", observer, ApplyTo(receiver)); - } - catch (...) { - ThrowCxxJavaException(env); - } + RTCRtpReceiverObserverSlot::Set(env, caller, "observerHandle", observer, ApplyTo(receiver)); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpReceiver_dispose (JNIEnv * env, jobject caller) { - webrtc::RtpReceiverInterface * receiver = jni::TakeHandle(env, caller); - - if (receiver == nullptr) { - return; - } + jni::CallFromJava(env, [&]() { + webrtc::RtpReceiverInterface * receiver = jni::TakeHandle(env, caller); - auto slot = RTCRtpReceiverObserverSlot::Take(env, caller, "observerHandle"); - - // Unlike e.g. MediaStreamTrack, an RTCRtpReceiver is not exclusively - // owned by one Java wrapper: the owning RtpTransceiver keeps its own - // reference, and other Java wrappers may have been obtained via separate - // getReceivers()/getReceiver() calls. Dropping our reference here is - // expected to leave others around, so it is not reported as an error. - // - // Runs once no other thread sets an observer through this object any more. - // WebRTC must let go of an observer set through this object before it is - // deleted with the slot. One that another Java object has set since stays. - jni::ReleaseHandle(env, receiver, [receiver, slot](bool) { - if (slot && jni::RegisteredObservers::Remove(receiver, slot->applied())) { - receiver->SetObserver(nullptr); + if (receiver == nullptr) { + return; } - receiver->Release(); + auto slot = RTCRtpReceiverObserverSlot::Take(env, caller, "observerHandle"); + + // Unlike e.g. MediaStreamTrack, an RTCRtpReceiver is not exclusively + // owned by one Java wrapper: the owning RtpTransceiver keeps its own + // reference, and other Java wrappers may have been obtained via separate + // getReceivers()/getReceiver() calls. Dropping our reference here is + // expected to leave others around, so it is not reported as an error. + // + // Runs once no other thread sets an observer through this object any more. + // WebRTC must let go of an observer set through this object before it is + // deleted with the slot. One that another Java object has set since stays. + jni::ReleaseHandle(env, receiver, [receiver, slot](bool) { + if (slot && jni::RegisteredObservers::Remove(receiver, slot->applied())) { + receiver->SetObserver(nullptr); + } + + receiver->Release(); + }); }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCRtpSender.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCRtpSender.cpp index 9e54e6207..24616c479 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCRtpSender.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCRtpSender.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RTCRtpSender.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/EncodedFrameInjectorObserver.h" #include "api/ObserverSlot.h" @@ -38,13 +39,15 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_getTrack (JNIEnv * env, jobject caller) { - jni::NativeLease sender(env, caller); - CHECK_HANDLEV(sender, nullptr); + return jni::CallFromJava(env, [&]() -> jobject { + jni::NativeLease sender(env, caller); + CHECK_HANDLEV(sender, nullptr); - webrtc::scoped_refptr track = sender->track(); + webrtc::scoped_refptr track = sender->track(); - // The sender keeps the track; the Java object is only a view of it. - return jni::MediaStreamTrackView::create(env, track.get()).release(); + // The sender keeps the track; the Java object is only a view of it. + return jni::MediaStreamTrackView::create(env, track.get()).release(); + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_getTransport @@ -73,19 +76,21 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_getTransport JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_replaceTrack (JNIEnv * env, jobject caller, jobject jTrack) { - jni::NativeLease sender(env, caller); - CHECK_HANDLE(sender); + jni::CallFromJava(env, [&]() { + jni::NativeLease sender(env, caller); + CHECK_HANDLE(sender); - // Null without a track, which detaches the sender's. - jni::NativeLease track(env, jTrack); + // Null without a track, which detaches the sender's. + jni::NativeLease track(env, jTrack); - if (jTrack != nullptr) { - CHECK_HANDLE(track); - } + if (jTrack != nullptr) { + CHECK_HANDLE(track); + } - if (!sender->SetTrack(track)) { - env->Throw(jni::JavaRuntimeException(env, "Set track failed")); - } + if (!sender->SetTrack(track)) { + env->Throw(jni::JavaRuntimeException(env, "Set track failed")); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_setParameters @@ -168,124 +173,132 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_getDtmfSender JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_setTransform (JNIEnv * env, jobject caller, jobject jTransformer) { - jni::NativeLease sender(env, caller); - CHECK_HANDLE(sender); + jni::CallFromJava(env, [&]() { + jni::NativeLease sender(env, caller); + CHECK_HANDLE(sender); - try { - // Clearing a transform that was never set installs nothing. - auto transformer = jTransformer != nullptr - ? jni::EncodedFrameTransformer::Of(sender) - : jni::EncodedFrameTransformer::Find(sender); + try { + // Clearing a transform that was never set installs nothing. + auto transformer = jTransformer != nullptr + ? jni::EncodedFrameTransformer::Of(sender) + : jni::EncodedFrameTransformer::Find(sender); - if (transformer) { - transformer->SetTransformer(env, jTransformer); + if (transformer) { + transformer->SetTransformer(env, jTransformer); + } } - } - catch (...) { - ThrowCxxJavaException(env); - } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_generateKeyFrame (JNIEnv * env, jobject caller) { - jni::NativeLease sender(env, caller); - CHECK_HANDLE(sender); + jni::CallFromJava(env, [&]() { + jni::NativeLease sender(env, caller); + CHECK_HANDLE(sender); - // Audio has no key frames, so there is nothing to ask for. - if (sender->media_type() != webrtc::MediaType::VIDEO) { - return; - } + // Audio has no key frames, so there is nothing to ask for. + if (sender->media_type() != webrtc::MediaType::VIDEO) { + return; + } - webrtc::RTCError result = sender->GenerateKeyFrame({}); + webrtc::RTCError result = sender->GenerateKeyFrame({}); - if (!result.ok()) { - env->Throw(jni::JavaRuntimeException(env, "%s", jni::RTCErrorToString(result).c_str())); - } + if (!result.ok()) { + env->Throw(jni::JavaRuntimeException(env, "%s", jni::RTCErrorToString(result).c_str())); + } + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_createVideoFrameInjector (JNIEnv * env, jobject caller, jobject jObserver) { - jni::NativeLease sender(env, caller); - CHECK_HANDLEV(sender, nullptr); + return jni::CallFromJava(env, [&]() -> jobject { + jni::NativeLease sender(env, caller); + CHECK_HANDLEV(sender, nullptr); - try { - std::unique_ptr observer; - webrtc::KeyFrameCallback keyFrameCallback; - webrtc::BitrateInfoCallback bitrateCallback; - - if (jObserver != nullptr) { - observer = jni::EncodedFrameInjectorObserver::ForVideo(env, jni::JavaLocalRef(env, jObserver)); - keyFrameCallback = observer->CreateKeyFrameCallback(); - bitrateCallback = observer->CreateBitrateInfoCallback(); - } + try { + std::unique_ptr observer; + webrtc::KeyFrameCallback keyFrameCallback; + webrtc::BitrateInfoCallback bitrateCallback; - auto injector = sender->CreateEncodedVideoFrameInjector(std::move(keyFrameCallback), std::move(bitrateCallback)); + if (jObserver != nullptr) { + observer = jni::EncodedFrameInjectorObserver::ForVideo(env, jni::JavaLocalRef(env, jObserver)); + keyFrameCallback = observer->CreateKeyFrameCallback(); + bitrateCallback = observer->CreateBitrateInfoCallback(); + } - // WebRTC refuses the injector for a stopped sender, a sender with a - // track, an audio sender, and a sender that has one already. - if (!injector) { - return nullptr; - } + auto injector = sender->CreateEncodedVideoFrameInjector(std::move(keyFrameCallback), std::move(bitrateCallback)); - // The observer is bound before the Java object takes the injector, so - // that it ends up with both of them or with neither. - auto jInjector = jni::JavaFactories::createOwning(env, std::move(injector), [&](jobject object) { - SetHandle(env, object, "observerHandle", observer.get()); - }); + // WebRTC refuses the injector for a stopped sender, a sender with a + // track, an audio sender, and a sender that has one already. + if (!injector) { + return nullptr; + } - // The Java object owns the observer now. - static_cast(observer.release()); + // The observer is bound before the Java object takes the injector, so + // that it ends up with both of them or with neither. + auto jInjector = jni::JavaFactories::createOwning(env, std::move(injector), [&](jobject object) { + SetHandle(env, object, "observerHandle", observer.get()); + }); - return jInjector.release(); - } - catch (...) { - ThrowCxxJavaException(env); - } + // The Java object owns the observer now. + static_cast(observer.release()); - return nullptr; + return jInjector.release(); + } + catch (...) { + ThrowCxxJavaException(env); + } + + return nullptr; + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_createAudioFrameInjector (JNIEnv * env, jobject caller, jobject jObserver) { - jni::NativeLease sender(env, caller); - CHECK_HANDLEV(sender, nullptr); + return jni::CallFromJava(env, [&]() -> jobject { + jni::NativeLease sender(env, caller); + CHECK_HANDLEV(sender, nullptr); - try { - std::unique_ptr observer; - webrtc::TargetBitrateCallback bitrateCallback; + try { + std::unique_ptr observer; + webrtc::TargetBitrateCallback bitrateCallback; - if (jObserver != nullptr) { - observer = jni::EncodedFrameInjectorObserver::ForAudio(env, jni::JavaLocalRef(env, jObserver)); - bitrateCallback = observer->CreateTargetBitrateCallback(); - } + if (jObserver != nullptr) { + observer = jni::EncodedFrameInjectorObserver::ForAudio(env, jni::JavaLocalRef(env, jObserver)); + bitrateCallback = observer->CreateTargetBitrateCallback(); + } - auto injector = sender->CreateEncodedAudioFrameInjector(std::move(bitrateCallback)); + auto injector = sender->CreateEncodedAudioFrameInjector(std::move(bitrateCallback)); - // WebRTC refuses the injector for a stopped sender, a sender with a - // track, a video sender, and a sender that has one already. - if (!injector) { - return nullptr; - } + // WebRTC refuses the injector for a stopped sender, a sender with a + // track, a video sender, and a sender that has one already. + if (!injector) { + return nullptr; + } - // The observer is bound before the Java object takes the injector, so - // that it ends up with both of them or with neither. - auto jInjector = jni::JavaFactories::createOwning(env, std::move(injector), [&](jobject object) { - SetHandle(env, object, "observerHandle", observer.get()); - }); + // The observer is bound before the Java object takes the injector, so + // that it ends up with both of them or with neither. + auto jInjector = jni::JavaFactories::createOwning(env, std::move(injector), [&](jobject object) { + SetHandle(env, object, "observerHandle", observer.get()); + }); - // The Java object owns the observer now. - static_cast(observer.release()); + // The Java object owns the observer now. + static_cast(observer.release()); - return jInjector.release(); - } - catch (...) { - ThrowCxxJavaException(env); - } + return jInjector.release(); + } + catch (...) { + ThrowCxxJavaException(env); + } - return nullptr; + return nullptr; + }); } JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_getId @@ -306,24 +319,26 @@ JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_getId JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_getStreams (JNIEnv * env, jobject caller) { - jni::NativeLease sender(env, caller); - CHECK_HANDLEV(sender, nullptr); + return jni::CallFromJava(env, [&]() -> jobject { + jni::NativeLease sender(env, caller); + CHECK_HANDLEV(sender, nullptr); - try { - const std::vector streamIds = sender->stream_ids(); + try { + const std::vector streamIds = sender->stream_ids(); - jni::JavaArrayList list(env, streamIds.size()); + jni::JavaArrayList list(env, streamIds.size()); - for (const auto & id : streamIds) { - list.add(jni::JavaString::toJava(env, id)); - } + for (const auto & id : streamIds) { + list.add(jni::JavaString::toJava(env, id)); + } - return list.listObject().release(); - } - catch (...) { - ThrowCxxJavaException(env); - return nullptr; - } + return list.listObject().release(); + } + catch (...) { + ThrowCxxJavaException(env); + return nullptr; + } + }); } namespace @@ -346,48 +361,52 @@ namespace JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_setObserver (JNIEnv * env, jobject caller, jobject jObserver) { - jni::NativeLease sender(env, caller); - CHECK_HANDLE(sender); + jni::CallFromJava(env, [&]() { + jni::NativeLease sender(env, caller); + CHECK_HANDLE(sender); - try { - jni::RTCRtpSenderObserver * observer = nullptr; + try { + jni::RTCRtpSenderObserver * observer = nullptr; - if (jObserver != nullptr) { - observer = new jni::RTCRtpSenderObserver(env, jni::JavaGlobalRef(env, jObserver)); - } + if (jObserver != nullptr) { + observer = new jni::RTCRtpSenderObserver(env, jni::JavaGlobalRef(env, jObserver)); + } - RTCRtpSenderObserverSlot::Set(env, caller, "observerHandle", observer, ApplyTo(sender)); - } - catch (...) { - ThrowCxxJavaException(env); - } + RTCRtpSenderObserverSlot::Set(env, caller, "observerHandle", observer, ApplyTo(sender)); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpSender_dispose (JNIEnv * env, jobject caller) { - webrtc::RtpSenderInterface * sender = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::RtpSenderInterface * sender = jni::TakeHandle(env, caller); - if (sender == nullptr) { - return; - } - - auto slot = RTCRtpSenderObserverSlot::Take(env, caller, "observerHandle"); - - // Unlike e.g. MediaStreamTrack, an RTCRtpSender is not exclusively owned - // by one Java wrapper: the owning RtpTransceiver keeps its own reference, - // and other Java wrappers may have been obtained via separate - // getSenders()/getSender() calls. Dropping our reference here is - // expected to leave others around, so it is not reported as an error. - // - // Runs once no other thread sets an observer through this object any more. - // WebRTC must let go of an observer set through this object before it is - // deleted with the slot. One that another Java object has set since stays. - jni::ReleaseHandle(env, sender, [sender, slot](bool) { - if (slot && jni::RegisteredObservers::Remove(sender, slot->applied())) { - sender->SetObserver(nullptr); + if (sender == nullptr) { + return; } - sender->Release(); + auto slot = RTCRtpSenderObserverSlot::Take(env, caller, "observerHandle"); + + // Unlike e.g. MediaStreamTrack, an RTCRtpSender is not exclusively owned + // by one Java wrapper: the owning RtpTransceiver keeps its own reference, + // and other Java wrappers may have been obtained via separate + // getSenders()/getSender() calls. Dropping our reference here is + // expected to leave others around, so it is not reported as an error. + // + // Runs once no other thread sets an observer through this object any more. + // WebRTC must let go of an observer set through this object before it is + // deleted with the slot. One that another Java object has set since stays. + jni::ReleaseHandle(env, sender, [sender, slot](bool) { + if (slot && jni::RegisteredObservers::Remove(sender, slot->applied())) { + sender->SetObserver(nullptr); + } + + sender->Release(); + }); }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/NativeHandle.cpp b/webrtc-jni/src/main/cpp/src/NativeHandle.cpp index d62647747..6d8a23e9c 100644 --- a/webrtc-jni/src/main/cpp/src/NativeHandle.cpp +++ b/webrtc-jni/src/main/cpp/src/NativeHandle.cpp @@ -15,6 +15,7 @@ */ #include "NativeHandle.h" +#include "AllocationFault.h" #include "JavaClassLoader.h" #include "JavaRef.h" #include "JavaUtils.h" @@ -140,6 +141,7 @@ namespace jni return 0; } + AllocationFault::CheckNativeLease(); stripe.entries[handle].uses++; return handle; @@ -205,6 +207,7 @@ namespace jni std::lock_guard lock(stripe.mutex); // The caller's own use keeps the entry. + AllocationFault::CheckNativeLease(); stripe.entries[handle].uses++; } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCEncodedFrame.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCEncodedFrame.java index 1b98ac8ed..8c67d1c80 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCEncodedFrame.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCEncodedFrame.java @@ -40,15 +40,17 @@ public abstract class RTCEncodedFrame { /** - * Where the payload is copied to. There is one per transform thread, which - * grows to the largest frame seen and is reused for every frame after, so - * reading the payload allocates nothing. + * Where the payload is copied to. Each transform thread reuses a bounded + * buffer. Larger frames get a temporary buffer, retained only by that frame. */ private static final ThreadLocal SCRATCH = new ThreadLocal<>(); /** The smallest scratch buffer, enough for any audio frame. */ private static final int MIN_SCRATCH_CAPACITY = 4096; + /** Maximum direct memory retained per transform thread (256 KiB). */ + private static final int MAX_SCRATCH_CAPACITY = 256 * 1024; + private final Thread owner; private final long timestamp; @@ -310,6 +312,10 @@ private void checkAccess() { } private static ByteBuffer scratch(int size) { + if (size > MAX_SCRATCH_CAPACITY) { + return ByteBuffer.allocateDirect(size); + } + ByteBuffer scratch = SCRATCH.get(); if (scratch == null || scratch.capacity() < size) { @@ -319,7 +325,7 @@ private static ByteBuffer scratch(int size) { capacity = Math.max(capacity, scratch.capacity()); } while (capacity < size) { - capacity = capacity > Integer.MAX_VALUE / 2 ? Integer.MAX_VALUE : capacity * 2; + capacity *= 2; } scratch = ByteBuffer.allocateDirect(capacity); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/ChannelOptions.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/ChannelOptions.java index 1daae6e1c..b16b8a28d 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/ChannelOptions.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/ChannelOptions.java @@ -102,13 +102,13 @@ public Builder ordered(boolean ordered) { * Makes the channel unreliable: a message is sent at most this many * more times. Excludes {@link #maxPacketLifeTime(Duration)}. * - * @param retransmits 0 or more. + * @param retransmits 0 to 65535. * * @return this builder. */ public Builder maxRetransmits(int retransmits) { - if (retransmits < 0) { - throw new IllegalArgumentException("Retransmits must be 0 or more, got " + retransmits); + if (retransmits < 0 || retransmits > 65535) { + throw new IllegalArgumentException("Retransmits must be between 0 and 65535, got " + retransmits); } this.maxRetransmits = retransmits; @@ -119,18 +119,18 @@ public Builder maxRetransmits(int retransmits) { * Makes the channel unreliable: a message is retransmitted only for * this long. Excludes {@link #maxRetransmits(int)}. * - * @param lifeTime how long a message may be retransmitted. + * @param lifeTime how long a message may be retransmitted, from zero to + * 65535 milliseconds. Positive fractions of a millisecond + * are rounded down (so a sub-millisecond duration is zero). * * @return this builder. */ public Builder maxPacketLifeTime(Duration lifeTime) { - long millis = lifeTime.toMillis(); - - if (millis < 0 || millis > Integer.MAX_VALUE) { + if (lifeTime.isNegative() || lifeTime.compareTo(Duration.ofMillis(65535)) > 0) { throw new IllegalArgumentException("Invalid packet life time " + lifeTime); } - this.maxPacketLifeTime = (int) millis; + this.maxPacketLifeTime = (int) lifeTime.toMillis(); return this; } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioConverter.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioConverter.java index d3bde6f33..243c2464d 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioConverter.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioConverter.java @@ -52,7 +52,7 @@ public class AudioConverter extends DisposableNativeObject { * @param dstChannels The number of audio channels of the output signal. * * @throws IllegalArgumentException if a sampling frequency is not between - * 100 Hz and 384 kHz, or a channel count + * 100 Hz and 384 kHz or not divisible by 100, or a channel count * not between 1 and 8. */ public AudioConverter(int srcSampleRate, int srcChannels, int dstSampleRate, @@ -120,9 +120,9 @@ public int convert(byte[] src, byte[] dst) { private native void convertInternal(byte[] src, int nSrcSamples, byte[] dst, int nDstSamples); private static void checkSampleRate(int sampleRate, String name) { - if (sampleRate < 100 || sampleRate > MAX_SAMPLE_RATE) { + if (sampleRate < 100 || sampleRate > MAX_SAMPLE_RATE || sampleRate % 100 != 0) { throw new IllegalArgumentException("Invalid " + name + " sampling frequency: " - + sampleRate + ", must be between 100 and " + MAX_SAMPLE_RATE); + + sampleRate + ", must be between 100 and " + MAX_SAMPLE_RATE + " and divisible by 100"); } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioProcessingStreamConfig.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioProcessingStreamConfig.java index 5ff2e5d0d..97bfe5fc4 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioProcessingStreamConfig.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioProcessingStreamConfig.java @@ -23,7 +23,16 @@ public class AudioProcessingStreamConfig { public final int channels; + /** + * @param sampleRate the sample rate in Hz, positive and divisible by 100 + * so a 10 ms frame has an integral sample count. + * @param channels the number of channels. + * @throws IllegalArgumentException if the sample rate cannot represent 10 ms. + */ public AudioProcessingStreamConfig(int sampleRate, int channels) { + if (sampleRate <= 0 || sampleRate % 100 != 0) { + throw new IllegalArgumentException("Sample rate must be positive and divisible by 100, got " + sampleRate); + } this.sampleRate = sampleRate; this.channels = channels; } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioResampler.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioResampler.java index c658530f0..97bca07d6 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioResampler.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioResampler.java @@ -58,8 +58,8 @@ public AudioResampler() { * Creates a new {@code AudioResampler} with specified sampling frequency * parameters. * - * @param sourceSampleRate The sampling frequency of the input signal. - * @param targetSampleRate The sampling frequency of the output signal. + * @param sourceSampleRate The sampling frequency of the input signal, divisible by 100. + * @param targetSampleRate The sampling frequency of the output signal, divisible by 100. * @param channels The number of audio channels to resample. */ public AudioResampler(int sourceSampleRate, int targetSampleRate, int channels) { @@ -116,13 +116,18 @@ private native int resampleInternal(byte[] samplesIn, int srcSamplesPerChannel, byte[] samplesOut, int dstSamplesPerChannel, int channels); /** - * Returns the number of samples a buffer needs to hold for ~10ms of a single audio channel at a given sample rate. + * Returns the number of samples a buffer needs to hold for exactly 10 ms of a single audio channel at a given sample rate. * - * @param sampleRate The sample rate. + * @param sampleRate The sample rate, 100 to 384000 Hz and divisible by 100. + * + * @throws IllegalArgumentException if the rate is outside this range or not divisible by 100. * * @return The number of samples per channel. */ public static int getSamplesPerChannel(int sampleRate) { + if (sampleRate < 100 || sampleRate > MAX_SAMPLES_PER_CHANNEL * 100 || sampleRate % 100 != 0) { + throw new IllegalArgumentException("Sample rate must be between 100 and 384000 Hz and divisible by 100, got " + sampleRate); + } return sampleRate / 100; } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/CustomAudioSource.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/CustomAudioSource.java index 808aed678..64157452b 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/CustomAudioSource.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/CustomAudioSource.java @@ -105,7 +105,7 @@ public CustomAudioSource(SyncClock clock) { * from {@value #MIN_SAMPLE_RATE} to {@value #MAX_SAMPLE_RATE}. * @param channels The number of audio channels: 1, 2, 4, 6 or 8. * @param frameCount The number of frames in the provided audio data, - * which must be {@code sampleRate / 100}. A frame + * which must be {@code sampleRate / 100} with a rate divisible by 100. A frame * holds one sample for each channel, so 10 ms at * 48 kHz is 480 frames whatever the channel count. * @@ -141,7 +141,7 @@ public void pushAudio(byte[] audioData, int bits_per_sample, int sampleRate, * from {@value #MIN_SAMPLE_RATE} to {@value #MAX_SAMPLE_RATE}. * @param channels The number of audio channels: 1, 2, 4, 6 or 8. * @param frameCount The number of frames in the provided audio data, - * which must be {@code sampleRate / 100}. + * which must be {@code sampleRate / 100} with a rate divisible by 100. * @param timestampUs The capture time of the chunk, on the clock of * {@link dev.onvoid.webrtc.media.SyncClock#currentTimeUs()}. * @@ -187,9 +187,9 @@ private static void validate(byte[] audioData, int bits_per_sample, "Audio must be %d-bit PCM, got %d bits per sample", BITS_PER_SAMPLE, bits_per_sample)); } - if (sampleRate < MIN_SAMPLE_RATE || sampleRate > MAX_SAMPLE_RATE) { + if (sampleRate < MIN_SAMPLE_RATE || sampleRate > MAX_SAMPLE_RATE || sampleRate % 100 != 0) { throw new IllegalArgumentException(String.format( - "Sample rate must be between %d and %d Hz, got %d", + "Sample rate must be between %d and %d Hz and divisible by 100, got %d", MIN_SAMPLE_RATE, MAX_SAMPLE_RATE, sampleRate)); } if (channels != 1 && (channels <= 0 || channels > MAX_CHANNELS || channels % 2 != 0)) { diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/JniBoundaryTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/JniBoundaryTests.java new file mode 100644 index 000000000..ce86bbd26 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/JniBoundaryTests.java @@ -0,0 +1,53 @@ +/* + * 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.*; + +import dev.onvoid.webrtc.internal.AllocationFault; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +@Execution(ExecutionMode.SAME_THREAD) +class JniBoundaryTests extends TestBase { + + @Test + void getterTranslatesAllocationFailure() { + RTCPeerConnection connection = factory.createPeerConnection(new RTCConfiguration(), candidate -> { }); + RTCDataChannel channel = connection.createDataChannel("boundary", new RTCDataChannelInit()); + RTCRtpTransceiver transceiver = connection.addTransceiver( + dev.onvoid.webrtc.media.MediaType.AUDIO, new RTCRtpTransceiverInit()); + RTCRtpSender sender = transceiver.getSender(); + try { + // Both getters used to acquire their leases outside any exception boundary. + AllocationFault.failNextNativeLease(); + assertEquals(Error.class, assertThrows(Error.class, channel::isReliable).getClass()); + assertTrue(channel.isReliable()); + AllocationFault.failNextNativeLease(); + assertEquals(Error.class, assertThrows(Error.class, sender::getTrack).getClass()); + assertNull(sender.getTrack()); + } + finally { + AllocationFault.disarm(); + sender.dispose(); + transceiver.dispose(); + channel.dispose(); + connection.close(); + } + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/RTCEncodedFrameScratchTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/RTCEncodedFrameScratchTests.java new file mode 100644 index 000000000..30f30e8ab --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/RTCEncodedFrameScratchTests.java @@ -0,0 +1,56 @@ +/* + * 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.*; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.ByteBuffer; +import org.junit.jupiter.api.Test; + +class RTCEncodedFrameScratchTests { + + @Test + void oversizedFramesStayTemporary() throws Exception { + Field field = RTCEncodedFrame.class.getDeclaredField("SCRATCH"); + field.setAccessible(true); + ThreadLocal cache = (ThreadLocal) field.get(null); + Method method = RTCEncodedFrame.class.getDeclaredMethod("scratch", int.class); + method.setAccessible(true); + cache.remove(); + try { + int limit = 256 * 1024; + ByteBuffer large = (ByteBuffer) method.invoke(null, limit + 1); + assertTrue(large.isDirect()); + assertEquals(limit + 1, large.capacity()); + assertNull(cache.get()); + + ByteBuffer small = (ByteBuffer) method.invoke(null, 4096); + assertSame(small, cache.get()); + ByteBuffer boundary = (ByteBuffer) method.invoke(null, limit); + assertEquals(limit, boundary.capacity()); + assertSame(boundary, cache.get()); + assertNotSame(large, method.invoke(null, limit + 1)); + assertSame(boundary, cache.get()); + assertSame(boundary, method.invoke(null, 4096)); + } + finally { + cache.remove(); + } + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/ChannelOptionsTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/ChannelOptionsTests.java new file mode 100644 index 000000000..0784185c9 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/ChannelOptionsTests.java @@ -0,0 +1,60 @@ +/* + * 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.client; + +import static org.junit.jupiter.api.Assertions.*; + +import java.time.Duration; +import org.junit.jupiter.api.Test; + +class ChannelOptionsTests { + + @Test + void lifetimeBounds() { + for (Duration invalid : new Duration[] { Duration.ofNanos(-1), Duration.ofMillis(-1), + Duration.ofMillis(65535).plusNanos(1), Duration.ofMillis(120000), + Duration.ofSeconds(Long.MAX_VALUE) }) { + assertThrows(IllegalArgumentException.class, + () -> ChannelOptions.builder().maxPacketLifeTime(invalid)); + } + assertThrows(NullPointerException.class, () -> ChannelOptions.builder().maxPacketLifeTime(null)); + for (int millis : new int[] { 0, 1, 65535 }) { + assertEquals(millis, ChannelOptions.builder().maxPacketLifeTime(Duration.ofMillis(millis)) + .build().toInit().maxPacketLifeTime); + } + } + + @Test + void lifetimeRoundsDown() { + assertEquals(0, ChannelOptions.builder().maxPacketLifeTime(Duration.ofNanos(1)) + .build().toInit().maxPacketLifeTime); + assertEquals(1, ChannelOptions.builder().maxPacketLifeTime(Duration.ofNanos(1999999)) + .build().toInit().maxPacketLifeTime); + } + + @Test + void retransmitBounds() { + for (int invalid : new int[] { -1, 65536, 120000, Integer.MAX_VALUE }) { + assertThrows(IllegalArgumentException.class, () -> ChannelOptions.builder().maxRetransmits(invalid)); + } + for (int count : new int[] { 0, 1, 65535 }) { + assertEquals(count, ChannelOptions.builder().maxRetransmits(count).build().toInit().maxRetransmits); + } + assertThrows(IllegalStateException.class, () -> ChannelOptions.builder() + .maxRetransmits(0).maxPacketLifeTime(Duration.ZERO).build()); + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/AllocationFault.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/AllocationFault.java index f0b39c494..3664f9388 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/internal/AllocationFault.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/AllocationFault.java @@ -37,6 +37,9 @@ private AllocationFault() { */ public static native void failNextListener(); + /** Fails the next acquisition of a native handle lease. */ + public static native void failNextNativeLease(); + /** * Fails the next {@code encoded_observer_add()} of the extension API, as * an allocation for the handle it returns does. diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioSampleRateTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioSampleRateTests.java new file mode 100644 index 000000000..43ce75d56 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioSampleRateTests.java @@ -0,0 +1,51 @@ +/* + * 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.audio; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class AudioSampleRateTests { + + @Test + void rejectsFractionalFrames() { + for (int rate : new int[] { 101, 44101, 48001, 48099, 383999 }) { + assertThrows(IllegalArgumentException.class, () -> new AudioConverter(rate, 1, 48000, 1)); + assertThrows(IllegalArgumentException.class, () -> new AudioConverter(48000, 1, rate, 1)); + assertThrows(IllegalArgumentException.class, () -> new AudioResampler(rate, 48000, 1)); + assertThrows(IllegalArgumentException.class, () -> new AudioResampler(48000, rate, 1)); + assertThrows(IllegalArgumentException.class, () -> AudioResampler.getSamplesPerChannel(rate)); + assertThrows(IllegalArgumentException.class, () -> new AudioProcessingStreamConfig(rate, 1)); + } + } + + @Test + void acceptsIntegralFrames() { + for (int rate : new int[] { 100, 8000, 44100, 48000, 384000 }) { + assertEquals(rate / 100, AudioResampler.getSamplesPerChannel(rate)); + assertEquals(rate, new AudioProcessingStreamConfig(rate, 1).sampleRate); + AudioConverter converter = new AudioConverter(rate, 1, rate, 1); + try { + assertEquals(rate / 100 * 2, converter.getTargetBufferSize()); + } + finally { + converter.dispose(); + } + } + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java index b790aedee..f42caf23b 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java @@ -45,6 +45,15 @@ void dispose() { } + @Test + void rejectsFractionalFrames() { + byte[] data = new byte[480 * 2]; + assertThrows(IllegalArgumentException.class, + () -> customAudioSource.pushAudio(data, 16, 48099, 1, 480)); + assertThrows(IllegalArgumentException.class, + () -> customAudioSource.pushAudio(data, 16, 48099, 1, 480, 1000L)); + } + @Test void pushAudioRejectsBadArguments() { byte[] data = new byte[480 * 2 * 2];