From 77bdcb6b60ad089db6ac4445b8dd47ad89a28c45 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Tue, 3 Nov 2026 14:29:06 +0100 Subject: [PATCH 1/3] fix: free the local class references of the JNI helpers GetFieldID on an object and the class name lookup of JavaContext left the class of GetObjectClass behind. On a native thread attached for a callback, nothing frees local references until the thread detaches. The class loader no longer creates a global reference while an exception is pending. --- .../cpp/dependencies/jni-voithos/src/JavaClassLoader.cpp | 4 +++- .../cpp/dependencies/jni-voithos/src/JavaClassUtils.cpp | 8 ++++---- .../main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp | 8 +++++--- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassLoader.cpp b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassLoader.cpp index 3e15e8b34..c67dcb27e 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassLoader.cpp +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassLoader.cpp @@ -19,12 +19,14 @@ namespace jni explicit JavaClassLoader(JNIEnv * env, const JavaGlobalRef & classLoader) : classLoader(classLoader) { - classLoaderClass_ = reinterpret_cast(env->NewGlobalRef(env->FindClass("java/lang/ClassLoader"))); + JavaLocalRef cls(env, env->FindClass("java/lang/ClassLoader")); if (ExceptionCheck(env)) { return; } + classLoaderClass_ = reinterpret_cast(env->NewGlobalRef(cls.get())); + loadClass = env->GetMethodID(classLoaderClass_, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;"); ExceptionCheck(env); diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassUtils.cpp b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassUtils.cpp index 53d07765a..8bd4f5d1a 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassUtils.cpp +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaClassUtils.cpp @@ -13,17 +13,17 @@ namespace jni { JavaClassUtils::JavaClassUtils(JNIEnv * env) { - jclass cls = env->FindClass("java/lang/Class"); + JavaLocalRef cls(env, env->FindClass("java/lang/Class")); - getClassName = GetMethod(env, cls, "getName", "()Ljava/lang/String;"); + getClassName = GetMethod(env, cls.get(), "getName", "()Ljava/lang/String;"); } std::string JavaClassUtils::toNativeClassName(JNIEnv * env, const JavaLocalRef & javaRef) { const auto classUtils = JavaClasses::get(env); - jclass cls = env->GetObjectClass(javaRef.get()); - jstring clsName = static_cast(env->CallObjectMethod(cls, classUtils->getClassName)); + JavaLocalRef cls(env, env->GetObjectClass(javaRef.get())); + jstring clsName = static_cast(env->CallObjectMethod(cls.get(), classUtils->getClassName)); ExceptionCheck(env); return JavaString::toNative(env, JavaLocalRef(env, clsName)); diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp index 7f089a2af..3ed90da05 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaUtils.cpp @@ -173,14 +173,16 @@ jfieldID GetHandleField(JNIEnv * env, jobject obj, const std::string & fieldName jfieldID GetFieldID(JNIEnv * env, jobject obj, const std::string & fieldName, const char * type) { - jclass cls = env->GetObjectClass(obj); + // Deleted on return: on a native thread attached for a callback, nothing + // else frees local references until the thread detaches. + jni::JavaLocalRef cls(env, env->GetObjectClass(obj)); - if (cls == nullptr) { + if (cls.get() == nullptr) { ExceptionCheck(env); return nullptr; } - return GetFieldID(env, cls, fieldName, type); + return GetFieldID(env, cls.get(), fieldName, type); } jfieldID GetFieldID(JNIEnv * env, jclass cls, const std::string & fieldName, const char * type) From eb68727d935dbcd6a1bbd5d3e141710947dda6ca Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Tue, 3 Nov 2026 14:29:16 +0100 Subject: [PATCH 2/3] fix: test under -Xcheck:jni on macOS and Windows as well The jni-check job also runs on macOS arm64 and Windows x86_64, whose device modules, capturers and codecs reach Java on code paths of their own. Ahead of that, the paths only real devices take check their JNI calls: an AudioSource that throws on the playout thread is reported instead of leaving the exception pending, and a device whose Java constructor threw is not filled in. --- .../actions/test-natives/jni-check-report.sh | 2 + .github/workflows/platforms.yml | 31 +++++-- webrtc-jni/src/main/cpp/src/media/Device.cpp | 7 ++ .../main/cpp/src/media/audio/AudioDevice.cpp | 7 ++ .../src/media/audio/AudioTransportSource.cpp | 25 +++++- .../webrtc/media/audio/AudioSourceTests.java | 81 +++++++++++++++++++ 6 files changed, 142 insertions(+), 11 deletions(-) create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioSourceTests.java diff --git a/.github/actions/test-natives/jni-check-report.sh b/.github/actions/test-natives/jni-check-report.sh index b253d3f76..140fab40c 100644 --- a/.github/actions/test-natives/jni-check-report.sh +++ b/.github/actions/test-natives/jni-check-report.sh @@ -22,6 +22,8 @@ fatal=$(grep -c 'FATAL ERROR in native method' "$log" || true) warnings=$(grep -cE 'WARNING in native method|WARNING: JNI local refs' "$log" || true) summary=$(awk ' + # The JVM on Windows ends some lines with CRLF. + { sub(/\r$/, "") } function flush() { if (kind != "") { key = kind " | " (frame != "" ? frame : (native ? "" : "")) diff --git a/.github/workflows/platforms.yml b/.github/workflows/platforms.yml index 2e18a9a75..714939378 100644 --- a/.github/workflows/platforms.yml +++ b/.github/workflows/platforms.yml @@ -158,14 +158,29 @@ jobs: java-architecture: ${{ matrix.platform.java-architecture }} version: ${{ inputs.version }} - # The tests once more under -Xcheck:jni, on one platform only: the JNI code - # is the same on all of them, and its exception checks are what this is - # about. It fails on any JNI error or warning, see the test-natives action. + # The tests once more under -Xcheck:jni, once per OS: the JNI glue is shared, + # but the device modules, capturers and hardware codecs that call back into + # Java are not, so each OS has JNI code of its own. One architecture each is + # enough, since that code is the same across them. It fails on any JNI error + # or warning, see the test-natives action. jni-check: - name: jni-check (linux_x86-64) + name: jni-check (${{ matrix.platform.name }}) needs: build timeout-minutes: 30 - runs-on: ubuntu-22.04 + strategy: + fail-fast: false + matrix: + platform: + - name: linux_x86-64 + runs-on: ubuntu-22.04 + classifier: linux-x86_64 + - name: macos_arm64 + runs-on: macos-15 + classifier: macos-aarch64 + - name: windows_x86_64 + runs-on: windows-2022 + classifier: windows-x86_64 + runs-on: ${{ matrix.platform.runs-on }} steps: - name: Checkout code uses: actions/checkout@v7 @@ -175,9 +190,9 @@ jobs: - name: Test natives under -Xcheck:jni uses: ./.github/actions/test-natives with: - platform-name: linux_x86-64 - classifier: linux-x86_64 - profile: linux-x86_64 + platform-name: ${{ matrix.platform.name }} + classifier: ${{ matrix.platform.classifier }} + profile: ${{ matrix.platform.classifier }} java-distribution: temurin version: ${{ inputs.version }} jni-check: 'true' diff --git a/webrtc-jni/src/main/cpp/src/media/Device.cpp b/webrtc-jni/src/main/cpp/src/media/Device.cpp index 5156bf3db..9cf66de3a 100644 --- a/webrtc-jni/src/main/cpp/src/media/Device.cpp +++ b/webrtc-jni/src/main/cpp/src/media/Device.cpp @@ -17,6 +17,7 @@ #include "media/Device.h" #include "JavaClasses.h" #include "JavaString.h" +#include "JavaUtils.h" #include "JNI_WebRTC.h" #include "JavaEnums.h" @@ -88,6 +89,12 @@ namespace jni JavaString::toJava(env, device->getName()).get(), JavaString::toJava(env, device->getDescriptor()).get()); + // A constructor that threw leaves no object to fill in. + if (obj == nullptr) { + ExceptionCheck(env); + return nullptr; + } + auto deviceTransport = JavaEnums::toJava(env, device->getDeviceTransport()); env->SetObjectField(obj, javaClass->deviceTransport, deviceTransport.get()); diff --git a/webrtc-jni/src/main/cpp/src/media/audio/AudioDevice.cpp b/webrtc-jni/src/main/cpp/src/media/audio/AudioDevice.cpp index 0737d8b89..e21a27e68 100644 --- a/webrtc-jni/src/main/cpp/src/media/audio/AudioDevice.cpp +++ b/webrtc-jni/src/main/cpp/src/media/audio/AudioDevice.cpp @@ -18,6 +18,7 @@ #include "JavaClasses.h" #include "JavaString.h" +#include "JavaUtils.h" #include "JNI_WebRTC.h" #include "JavaEnums.h" @@ -42,6 +43,12 @@ namespace jni JavaString::toJava(env, device->getName()).get(), JavaString::toJava(env, device->getDescriptor()).get()); + // A constructor that threw leaves no object to fill in. + if (obj == nullptr) { + ExceptionCheck(env); + return nullptr; + } + auto deviceTransport = JavaEnums::toJava(env, device->getDeviceTransport()); env->SetObjectField(obj, javaClass->deviceTransport, deviceTransport.get()); diff --git a/webrtc-jni/src/main/cpp/src/media/audio/AudioTransportSource.cpp b/webrtc-jni/src/main/cpp/src/media/audio/AudioTransportSource.cpp index dca821b8c..15e026cca 100644 --- a/webrtc-jni/src/main/cpp/src/media/audio/AudioTransportSource.cpp +++ b/webrtc-jni/src/main/cpp/src/media/audio/AudioTransportSource.cpp @@ -15,6 +15,7 @@ */ #include "media/audio/AudioTransportSource.h" +#include "api/WebRTCUtils.h" #include "JavaClasses.h" #include "JNI_WebRTC.h" @@ -51,19 +52,37 @@ namespace jni jsize bufferSize = static_cast(nSamples * nBytesPerSample); if (buffer.get() == nullptr) { - jbyteArray dataArray = env->NewByteArray(bufferSize); + JavaLocalRef dataArray(env, env->NewByteArray(bufferSize)); - buffer = JavaGlobalRef(env, dataArray); + // The audio device's thread must not see a C++ exception, nor keep + // an OutOfMemoryError pending for its next JNI call. + if (dataArray.get() == nullptr) { + nSamplesOut = 0; + ReportPendingException(env); + return 0; + } + + buffer = JavaGlobalRef(env, dataArray.get()); jsize bufferLength = env->GetArrayLength(buffer); if (bufferLength < bufferSize) { buffer = JavaGlobalRef(env, nullptr); + nSamplesOut = 0; return 0; } } - nSamplesOut = env->CallIntMethod(source, javaClass->onPlaybackData, buffer.get(), nSamples, nBytesPerSample, nChannels, samplesPerSec); + jint samples = env->CallIntMethod(source, javaClass->onPlaybackData, buffer.get(), nSamples, nBytesPerSample, nChannels, samplesPerSec); + + // What the Java source threw is reported, and nothing is played. + if (env->ExceptionCheck()) { + nSamplesOut = 0; + ReportPendingException(env); + return 0; + } + + nSamplesOut = samples > 0 ? static_cast(samples) : 0; if (nSamplesOut > 0) { env->GetByteArrayRegion(buffer, 0, bufferSize, reinterpret_cast(audioSamples)); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioSourceTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioSourceTests.java new file mode 100644 index 000000000..baaabbb14 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioSourceTests.java @@ -0,0 +1,81 @@ +/* + * 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.assertTrue; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +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 AudioSourceTests { + + /** + * What an AudioSource throws on the module's playout thread goes to the + * uncaught exception handler, and the thread goes on pulling: the + * exception used to stay pending on that thread, for the JNI calls of all + * the pulls after it. + */ + @Test + void throwingSourceIsReported() throws Exception { + RuntimeException failure = new RuntimeException("source failed"); + CountDownLatch reported = new CountDownLatch(1); + CountDownLatch pulledAgain = new CountDownLatch(1); + AtomicInteger pulls = new AtomicInteger(); + + Thread.UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler(); + Thread.setDefaultUncaughtExceptionHandler((thread, e) -> { + if (e == failure) { + reported.countDown(); + } + else if (previous != null) { + previous.uncaughtException(thread, e); + } + }); + + HeadlessAudioDeviceModule module = new HeadlessAudioDeviceModule(); + + try { + module.setAudioSource((samples, nSamples, nBytesPerSample, nChannels, samplesPerSec) -> { + if (pulls.getAndIncrement() == 0) { + throw failure; + } + + pulledAgain.countDown(); + + return nSamples; + }); + + module.initPlayout(); + module.startPlayout(); + + assertTrue(reported.await(10, TimeUnit.SECONDS), "exception not reported"); + assertTrue(pulledAgain.await(10, TimeUnit.SECONDS), "source not pulled again"); + } + finally { + module.stopPlayout(); + module.dispose(); + + Thread.setDefaultUncaughtExceptionHandler(previous); + } + } +} From 368d97b7a851e8e060ddf244a287eb0c782f0f2a Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Tue, 3 Nov 2026 14:29:21 +0100 Subject: [PATCH 3/3] fix: turn every C++ exception of a JNI entry point into a Java one A C++ exception that reaches the VM ends the process. jni::CallFromJava runs the body of an entry point and turns any into a Java exception, the way the entry points with a try block of their own do. It now guards those that had none, or that called a throwing helper before their try block. --- .../dependencies/jni-voithos/CMakeLists.txt | 1 + .../jni-voithos/include/JavaBoundary.h | 71 ++++ .../src/main/cpp/src/JNI_AudioConverter.cpp | 89 ++--- .../cpp/src/JNI_AudioDeviceModuleBase.cpp | 311 ++++++++++-------- .../src/main/cpp/src/JNI_AudioProcessing.cpp | 85 +++-- .../src/main/cpp/src/JNI_AudioResampler.cpp | 15 +- .../src/main/cpp/src/JNI_AudioTrack.cpp | 65 ++-- .../src/main/cpp/src/JNI_AudioTrackSource.cpp | 21 +- .../main/cpp/src/JNI_CustomAudioSource.cpp | 35 +- .../main/cpp/src/JNI_CustomVideoSource.cpp | 97 +++--- .../src/main/cpp/src/JNI_DesktopCapturer.cpp | 89 ++--- .../cpp/src/JNI_HeadlessAudioDeviceModule.cpp | 23 +- webrtc-jni/src/main/cpp/src/JNI_Logging.cpp | 5 +- .../src/main/cpp/src/JNI_MediaStream.cpp | 113 ++++--- webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp | 25 +- .../src/main/cpp/src/JNI_NativeI420Buffer.cpp | 81 ++--- .../src/JNI_RTCEncodedAudioFrameInjector.cpp | 99 +++--- .../src/main/cpp/src/JNI_RTCEncodedFrame.cpp | 63 ++-- .../src/JNI_RTCEncodedVideoFrameInjector.cpp | 99 +++--- .../main/cpp/src/JNI_RTCRtpTransceiver.cpp | 87 ++--- .../src/main/cpp/src/JNI_RefCountedObject.cpp | 23 +- webrtc-jni/src/main/cpp/src/JNI_SyncClock.cpp | 55 ++-- .../main/cpp/src/JNI_VideoBufferConverter.cpp | 87 ++--- .../src/main/cpp/src/JNI_VideoCapture.cpp | 119 ++++--- .../main/cpp/src/JNI_VideoDesktopSource.cpp | 101 +++--- .../main/cpp/src/JNI_VideoDeviceSource.cpp | 117 ++++--- .../src/main/cpp/src/JNI_VideoTrack.cpp | 17 +- .../src/main/cpp/src/JNI_VideoTrackSource.cpp | 113 ++++--- 28 files changed, 1206 insertions(+), 900 deletions(-) create mode 100644 webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaBoundary.h diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/CMakeLists.txt b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/CMakeLists.txt index 76e25bcfa..b62525237 100644 --- a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/CMakeLists.txt +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/CMakeLists.txt @@ -10,6 +10,7 @@ target_sources(${PROJECT_NAME} include/JavaArray.h include/JavaArrayList.h include/JavaBigInteger.h + include/JavaBoundary.h include/JavaClasses.h include/JavaClass.h include/JavaClassLoader.h diff --git a/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaBoundary.h b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaBoundary.h new file mode 100644 index 000000000..146c455e8 --- /dev/null +++ b/webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaBoundary.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2026, Alex Andres. All rights reserved. + * + * Use of this source code is governed by the 3-Clause BSD license that can be + * found in the LICENSE file in the root of the source tree. + */ + +#ifndef JNI_JAVA_BOUNDARY_H_ +#define JNI_JAVA_BOUNDARY_H_ + +#include "JavaUtils.h" + +#include + +namespace jni +{ + namespace detail + { + // What a native method returns when its body failed: null, zero or + // false, which Java never sees, since an exception is pending then. + template + struct FailedReturn + { + static R value() + { + return R(); + } + }; + + template <> + struct FailedReturn + { + static void value() + { + } + }; + } + + // Runs the body of a JNI entry point. A C++ exception that reaches the VM + // ends the process, and the helpers of this library throw them: a Java + // exception they ran into as JavaWrappedException, a failed allocation as + // std::bad_alloc. Here every C++ exception becomes a Java one, with + // ThrowCxxJavaException(), and the entry point returns null, zero or + // false. What the body holds is released before that, so a destructor may + // still call into Java. The body's own returns, also those of + // CHECK_HANDLE, return from the entry point as before: + // + // JNIEXPORT jobject JNICALL Java_..._getFoo(JNIEnv * env, jobject caller) + // { + // return jni::CallFromJava(env, [&]() -> jobject { + // ... + // }); + // } + // + // A body that catches its own exceptions, such as one with a try block of + // its own around everything that may throw, needs none of this. + template + auto CallFromJava(JNIEnv * env, Body && body) noexcept -> decltype(body()) + { + try { + return body(); + } + catch (...) { + ThrowCxxJavaException(env); + } + + return detail::FailedReturn::value(); + } +} + +#endif diff --git a/webrtc-jni/src/main/cpp/src/JNI_AudioConverter.cpp b/webrtc-jni/src/main/cpp/src/JNI_AudioConverter.cpp index 25f4bf14f..a5d003d6b 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_AudioConverter.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_AudioConverter.cpp @@ -15,6 +15,7 @@ */ #include "JNI_AudioConverter.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/audio/audio_processing.h" #include "media/audio/AudioConverter.h" @@ -26,62 +27,66 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioConverter_convertInternal (JNIEnv * env, jobject caller, jbyteArray src, jint nSrcSamples, jbyteArray dst, jint nDstSamples) { - jni::NativeLease converter(env, caller); - CHECK_HANDLE(converter); + jni::CallFromJava(env, [&]() { + jni::NativeLease converter(env, caller); + CHECK_HANDLE(converter); - if (src == nullptr || dst == nullptr) { - ThrowJavaException(env, "java/lang/NullPointerException", "Sample arrays must not be null"); - return; - } - - // The counts are samples over all channels. The converter checks them against its format, this the arrays. - const jlong bytesPerSample = sizeof(int16_t); - - if (nSrcSamples < 0 || nDstSamples < 0 || - env->GetArrayLength(src) < nSrcSamples * bytesPerSample || env->GetArrayLength(dst) < nDstSamples * bytesPerSample) { - ThrowJavaException(env, "java/lang/IllegalArgumentException", "Sample arrays too short for the requested samples"); - return; - } - - try { - auto releaseSrc = [env, src](jbyte * bytes) { - env->ReleaseByteArrayElements(src, bytes, JNI_ABORT); - }; - std::unique_ptr srcPtr(env->GetByteArrayElements(src, nullptr), releaseSrc); - if (!srcPtr) { + if (src == nullptr || dst == nullptr) { + ThrowJavaException(env, "java/lang/NullPointerException", "Sample arrays must not be null"); return; } - // Mode 0 writes the samples back when the VM handed out a copy. - auto releaseDst = [env, dst](jbyte * bytes) { - env->ReleaseByteArrayElements(dst, bytes, 0); - }; - std::unique_ptr dstPtr(env->GetByteArrayElements(dst, nullptr), releaseDst); - if (!dstPtr) { + // The counts are samples over all channels. The converter checks them against its format, this the arrays. + const jlong bytesPerSample = sizeof(int16_t); + + if (nSrcSamples < 0 || nDstSamples < 0 || + env->GetArrayLength(src) < nSrcSamples * bytesPerSample || env->GetArrayLength(dst) < nDstSamples * bytesPerSample) { + ThrowJavaException(env, "java/lang/IllegalArgumentException", "Sample arrays too short for the requested samples"); return; } - converter->convert(reinterpret_cast(srcPtr.get()), nSrcSamples, reinterpret_cast(dstPtr.get()), nDstSamples); - } - catch (const std::invalid_argument & e) { - ThrowJavaException(env, "java/lang/IllegalArgumentException", e.what()); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + auto releaseSrc = [env, src](jbyte * bytes) { + env->ReleaseByteArrayElements(src, bytes, JNI_ABORT); + }; + std::unique_ptr srcPtr(env->GetByteArrayElements(src, nullptr), releaseSrc); + if (!srcPtr) { + return; + } + + // Mode 0 writes the samples back when the VM handed out a copy. + auto releaseDst = [env, dst](jbyte * bytes) { + env->ReleaseByteArrayElements(dst, bytes, 0); + }; + std::unique_ptr dstPtr(env->GetByteArrayElements(dst, nullptr), releaseDst); + if (!dstPtr) { + return; + } + + converter->convert(reinterpret_cast(srcPtr.get()), nSrcSamples, reinterpret_cast(dstPtr.get()), nDstSamples); + } + catch (const std::invalid_argument & e) { + ThrowJavaException(env, "java/lang/IllegalArgumentException", e.what()); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioConverter_dispose (JNIEnv * env, jobject caller) { - jni::AudioConverter * converter = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + jni::AudioConverter * converter = jni::TakeHandle(env, caller); - if (converter == nullptr) { - return; - } + if (converter == nullptr) { + return; + } - jni::ReleaseHandle(env, converter, [converter](bool) { - delete converter; + jni::ReleaseHandle(env, converter, [converter](bool) { + delete converter; + }); }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_AudioDeviceModuleBase.cpp b/webrtc-jni/src/main/cpp/src/JNI_AudioDeviceModuleBase.cpp index e573e05f9..98dbf0dac 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_AudioDeviceModuleBase.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_AudioDeviceModuleBase.cpp @@ -15,6 +15,7 @@ */ #include "JNI_AudioDeviceModuleBase.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "Exception.h" #include "JavaArrayList.h" @@ -71,73 +72,85 @@ namespace JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_initPlayout (JNIEnv * env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - if (audioModule->InitPlayout() != 0) { - env->Throw(jni::JavaError(env, "Init playout failed")); - return; - } + if (audioModule->InitPlayout() != 0) { + env->Throw(jni::JavaError(env, "Init playout failed")); + return; + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_stopPlayout (JNIEnv* env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - if (audioModule->StopPlayout() != 0) { - env->Throw(jni::JavaError(env, "Stop playout failed")); - return; - } + if (audioModule->StopPlayout() != 0) { + env->Throw(jni::JavaError(env, "Stop playout failed")); + return; + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_startPlayout (JNIEnv* env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - if (audioModule->StartPlayout() != 0) { - env->Throw(jni::JavaError(env, "Start playout failed")); - return; - } + if (audioModule->StartPlayout() != 0) { + env->Throw(jni::JavaError(env, "Start playout failed")); + return; + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_initRecording (JNIEnv * env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - if (audioModule->InitRecording() != 0) { - env->Throw(jni::JavaError(env, "Init recording failed")); - return; - } + if (audioModule->InitRecording() != 0) { + env->Throw(jni::JavaError(env, "Init recording failed")); + return; + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_stopRecording (JNIEnv* env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - if (audioModule->StopRecording() != 0) { - env->Throw(jni::JavaError(env, "Stop recording failed")); - return; - } + if (audioModule->StopRecording() != 0) { + env->Throw(jni::JavaError(env, "Stop recording failed")); + return; + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_startRecording (JNIEnv* env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - if (audioModule->StartRecording() != 0) { - env->Throw(jni::JavaError(env, "Start recording failed")); - return; - } + if (audioModule->StartRecording() != 0) { + env->Throw(jni::JavaError(env, "Start recording failed")); + return; + } + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_getPlayoutDevices @@ -279,161 +292,185 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_ JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_isSpeakerMuted (JNIEnv * env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLEV(audioModule, true); + return jni::CallFromJava(env, [&]() -> jboolean { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLEV(audioModule, true); - bool mute = true; + bool mute = true; - audioModule->SpeakerMute(&mute); + audioModule->SpeakerMute(&mute); - return mute; + return mute; + }); } JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_isMicrophoneMuted (JNIEnv * env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLEV(audioModule, true); + return jni::CallFromJava(env, [&]() -> jboolean { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLEV(audioModule, true); - bool mute = true; + bool mute = true; - audioModule->MicrophoneMute(&mute); + audioModule->MicrophoneMute(&mute); - return mute; + return mute; + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_getSpeakerVolume (JNIEnv * env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLEV(audioModule, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLEV(audioModule, 0); - uint32_t volume = 0; + uint32_t volume = 0; - if (audioModule->SpeakerVolume(&volume) != 0) { - env->Throw(jni::JavaError(env, "Get speaker volume failed")); - } + if (audioModule->SpeakerVolume(&volume) != 0) { + env->Throw(jni::JavaError(env, "Get speaker volume failed")); + } - return volume; + return volume; + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_getMaxSpeakerVolume (JNIEnv * env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLEV(audioModule, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLEV(audioModule, 0); - uint32_t volume = 0; + uint32_t volume = 0; - if (audioModule->MaxSpeakerVolume(&volume) != 0) { - env->Throw(jni::JavaError(env, "Get max speaker volume failed")); - } + if (audioModule->MaxSpeakerVolume(&volume) != 0) { + env->Throw(jni::JavaError(env, "Get max speaker volume failed")); + } - return volume; + return volume; + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_getMinSpeakerVolume (JNIEnv * env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLEV(audioModule, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLEV(audioModule, 0); - uint32_t volume = 0; + uint32_t volume = 0; - if (audioModule->MinSpeakerVolume(&volume) != 0) { - env->Throw(jni::JavaError(env, "Get min speaker volume failed")); - } + if (audioModule->MinSpeakerVolume(&volume) != 0) { + env->Throw(jni::JavaError(env, "Get min speaker volume failed")); + } - return volume; + return volume; + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_getMicrophoneVolume (JNIEnv * env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLEV(audioModule, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLEV(audioModule, 0); - uint32_t volume = 0; + uint32_t volume = 0; - if (audioModule->MicrophoneVolume(&volume) != 0) { - env->Throw(jni::JavaError(env, "Get microphone volume failed")); - } + if (audioModule->MicrophoneVolume(&volume) != 0) { + env->Throw(jni::JavaError(env, "Get microphone volume failed")); + } - return volume; + return volume; + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_getMaxMicrophoneVolume (JNIEnv * env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLEV(audioModule, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLEV(audioModule, 0); - uint32_t volume = 0; + uint32_t volume = 0; - if (audioModule->MaxMicrophoneVolume(&volume) != 0) { - env->Throw(jni::JavaError(env, "Get max microphone volume failed")); - } + if (audioModule->MaxMicrophoneVolume(&volume) != 0) { + env->Throw(jni::JavaError(env, "Get max microphone volume failed")); + } - return volume; + return volume; + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_getMinMicrophoneVolume (JNIEnv * env, jobject caller) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLEV(audioModule, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLEV(audioModule, 0); - uint32_t volume = 0; + uint32_t volume = 0; - if (audioModule->MinMicrophoneVolume(&volume) != 0) { - env->Throw(jni::JavaError(env, "Get min microphone volume failed")); - } + if (audioModule->MinMicrophoneVolume(&volume) != 0) { + env->Throw(jni::JavaError(env, "Get min microphone volume failed")); + } - return volume; + return volume; + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_setSpeakerVolume (JNIEnv * env, jobject caller, jint volume) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - if (audioModule->SetSpeakerVolume(static_cast(volume)) != 0) { - env->Throw(jni::JavaError(env, "Set speaker volume failed")); - } + if (audioModule->SetSpeakerVolume(static_cast(volume)) != 0) { + env->Throw(jni::JavaError(env, "Set speaker volume failed")); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_setSpeakerMute (JNIEnv * env, jobject caller, jboolean mute) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - if (audioModule->SetSpeakerMute(mute) != 0) { - env->Throw(jni::JavaError(env, "Set speaker mute failed")); - } + if (audioModule->SetSpeakerMute(mute) != 0) { + env->Throw(jni::JavaError(env, "Set speaker mute failed")); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_setMicrophoneVolume (JNIEnv * env, jobject caller, jint volume) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - if (audioModule->SetMicrophoneVolume(static_cast(volume)) != 0) { - env->Throw(jni::JavaError(env, "Set microphone volume failed")); - } + if (audioModule->SetMicrophoneVolume(static_cast(volume)) != 0) { + env->Throw(jni::JavaError(env, "Set microphone volume failed")); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_setMicrophoneMute (JNIEnv * env, jobject caller, jboolean mute) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - if (audioModule->SetMicrophoneMute(mute) != 0) { - env->Throw(jni::JavaError(env, "Set microphone mute failed")); - } + if (audioModule->SetMicrophoneMute(mute) != 0) { + env->Throw(jni::JavaError(env, "Set microphone mute failed")); + } + }); } JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_addSinkInternal @@ -463,16 +500,18 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_removeSinkInternal (JNIEnv * env, jobject caller, jlong sinkHandle) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - auto sink = reinterpret_cast(sinkHandle); + auto sink = reinterpret_cast(sinkHandle); - if (sink != nullptr) { - audioModule->RegisterAudioCallback(nullptr); + if (sink != nullptr) { + audioModule->RegisterAudioCallback(nullptr); - delete sink; - } + delete sink; + } + }); } JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_addSourceInternal @@ -502,36 +541,40 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_removeSourceInternal (JNIEnv * env, jobject caller, jlong sourceHandle) { - jni::NativeLease audioModule(env, caller); - CHECK_HANDLE(audioModule); + jni::CallFromJava(env, [&]() { + jni::NativeLease audioModule(env, caller); + CHECK_HANDLE(audioModule); - auto source = reinterpret_cast(sourceHandle); + auto source = reinterpret_cast(sourceHandle); - if (source != nullptr) { - audioModule->RegisterAudioCallback(nullptr); + if (source != nullptr) { + audioModule->RegisterAudioCallback(nullptr); - delete source; - } + delete source; + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioDeviceModuleBase_disposeInternal (JNIEnv * env, jobject caller) { - webrtc::AudioDeviceModule * audioModule = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::AudioDeviceModule * audioModule = jni::TakeHandle(env, caller); - if (audioModule == nullptr) { - return; - } - - jni::ReleaseHandle(env, audioModule, [audioModule](bool) { - if (audioModule->Initialized()) { - audioModule->Terminate(); + if (audioModule == nullptr) { + return; } - webrtc::RefCountReleaseStatus status = audioModule->Release(); + jni::ReleaseHandle(env, audioModule, [audioModule](bool) { + if (audioModule->Initialized()) { + audioModule->Terminate(); + } + + webrtc::RefCountReleaseStatus status = audioModule->Release(); - if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; - } + if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + } + }); }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_AudioProcessing.cpp b/webrtc-jni/src/main/cpp/src/JNI_AudioProcessing.cpp index c771b716f..a0564a29e 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_AudioProcessing.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_AudioProcessing.cpp @@ -15,6 +15,7 @@ */ #include "JNI_AudioProcessing.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "Exception.h" #include "JavaArrayList.h" @@ -57,19 +58,23 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioProcessing_applyC JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioProcessing_setStreamDelayMs (JNIEnv * env, jobject caller, jint delayMs) { - jni::NativeLease apm(env, caller); - CHECK_HANDLE(apm); + jni::CallFromJava(env, [&]() { + jni::NativeLease apm(env, caller); + CHECK_HANDLE(apm); - apm->set_stream_delay_ms(delayMs); + apm->set_stream_delay_ms(delayMs); + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioProcessing_getStreamDelayMs (JNIEnv * env, jobject caller) { - jni::NativeLease apm(env, caller); - CHECK_HANDLEV(apm, 0); + return jni::CallFromJava(env, [&]() -> jint { + jni::NativeLease apm(env, caller); + CHECK_HANDLEV(apm, 0); - return apm->stream_delay_ms(); + return apm->stream_delay_ms(); + }); } // Shared by processStream and processReverseStream, which differ only in the @@ -146,65 +151,75 @@ static jint processFrame(JNIEnv * env, jobject caller, jbyteArray src, jobject i JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioProcessing_processStream (JNIEnv * env, jobject caller, jbyteArray src, jobject inputConfig, jobject outputConfig, jbyteArray dest) { - return processFrame(env, caller, src, inputConfig, outputConfig, dest, false); + return jni::CallFromJava(env, [&]() -> jint { + return processFrame(env, caller, src, inputConfig, outputConfig, dest, false); + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioProcessing_processReverseStream (JNIEnv * env, jobject caller, jbyteArray src, jobject inputConfig, jobject outputConfig, jbyteArray dest) { - return processFrame(env, caller, src, inputConfig, outputConfig, dest, true); + return jni::CallFromJava(env, [&]() -> jint { + return processFrame(env, caller, src, inputConfig, outputConfig, dest, true); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioProcessing_dispose (JNIEnv * env, jobject caller) { - webrtc::AudioProcessing * apm = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::AudioProcessing * apm = jni::TakeHandle(env, caller); - if (apm == nullptr) { - return; - } + if (apm == nullptr) { + return; + } - auto tap = GetHandle>(env, caller, "captureTapHandle"); + auto tap = GetHandle>(env, caller, "captureTapHandle"); - SetHandle(env, caller, "captureTapHandle", nullptr); + SetHandle(env, caller, "captureTapHandle", nullptr); - jni::ReleaseHandle(env, apm, [apm, tap](bool) { - webrtc::RefCountReleaseStatus status = apm->Release(); + jni::ReleaseHandle(env, apm, [apm, tap](bool) { + webrtc::RefCountReleaseStatus status = apm->Release(); - if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; - } + if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + } - // The module, if a factory still uses it, keeps a share of the tap. - delete tap; + // The module, if a factory still uses it, keeps a share of the tap. + delete tap; + }); }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioProcessing_initialize (JNIEnv * env, jobject caller) { - jni::WebRTCContext * context = static_cast(javaContext); + jni::CallFromJava(env, [&]() { + jni::WebRTCContext * context = static_cast(javaContext); - auto tap = std::make_shared(); + auto tap = std::make_shared(); - webrtc::scoped_refptr apm = webrtc::BuiltinAudioProcessingBuilder() - .SetCapturePostProcessing(jni::AudioCaptureTap::CreateProcessing(tap)) - .Build(context->webrtcEnv); + webrtc::scoped_refptr apm = webrtc::BuiltinAudioProcessingBuilder() + .SetCapturePostProcessing(jni::AudioCaptureTap::CreateProcessing(tap)) + .Build(context->webrtcEnv); - if (!apm) { - env->Throw(jni::JavaError(env, "Create AudioProcessing failed")); - return; - } + if (!apm) { + env->Throw(jni::JavaError(env, "Create AudioProcessing failed")); + return; + } - SetHandle(env, caller, apm.release()); - SetHandle(env, caller, "captureTapHandle", new std::shared_ptr(std::move(tap))); + SetHandle(env, caller, apm.release()); + SetHandle(env, caller, "captureTapHandle", new std::shared_ptr(std::move(tap))); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioProcessing_updateStats (JNIEnv* env, jobject caller) { - jni::NativeLease apm(env, caller); - CHECK_HANDLE(apm); + jni::CallFromJava(env, [&]() { + jni::NativeLease apm(env, caller); + CHECK_HANDLE(apm); - jni::AudioProcessing::updateStats(apm->GetStatistics(), env, jni::JavaLocalRef(env, caller)); + jni::AudioProcessing::updateStats(apm->GetStatistics(), env, jni::JavaLocalRef(env, caller)); + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_AudioResampler.cpp b/webrtc-jni/src/main/cpp/src/JNI_AudioResampler.cpp index 8bf8b20fb..c55708888 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_AudioResampler.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_AudioResampler.cpp @@ -15,6 +15,7 @@ */ #include "JNI_AudioResampler.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "Exception.h" #include "JavaObject.h" @@ -28,14 +29,16 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioResampler_dispose (JNIEnv * env, jobject caller) { - webrtc::PushResampler * resampler = jni::TakeHandle>(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::PushResampler * resampler = jni::TakeHandle>(env, caller); - if (resampler == nullptr) { - return; - } + if (resampler == nullptr) { + return; + } - jni::ReleaseHandle(env, resampler, [resampler](bool) { - delete resampler; + jni::ReleaseHandle(env, resampler, [resampler](bool) { + delete resampler; + }); }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_AudioTrack.cpp b/webrtc-jni/src/main/cpp/src/JNI_AudioTrack.cpp index 95878d704..cb75be77e 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_AudioTrack.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_AudioTrack.cpp @@ -15,6 +15,7 @@ */ #include "JNI_AudioTrack.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/AudioTrackSink.h" #include "JavaNullPointerException.h" @@ -50,16 +51,18 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_addSinkInt JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_removeSinkInternal (JNIEnv * env, jobject caller, jlong sinkHandle) { - jni::NativeLease track(env, caller); - CHECK_HANDLE(track); + jni::CallFromJava(env, [&]() { + jni::NativeLease track(env, caller); + CHECK_HANDLE(track); - auto sink = reinterpret_cast(sinkHandle); + auto sink = reinterpret_cast(sinkHandle); - if (sink != nullptr) { - track->RemoveSink(sink); + if (sink != nullptr) { + track->RemoveSink(sink); - delete sink; - } + delete sink; + } + }); } JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_addVoiceActivityListenerInternal @@ -85,43 +88,49 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_addVoiceAc JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_removeVoiceActivityListenerInternal (JNIEnv * env, jobject caller, jlong sinkHandle) { - jni::NativeLease track(env, caller); - CHECK_HANDLE(track); + jni::CallFromJava(env, [&]() { + jni::NativeLease track(env, caller); + CHECK_HANDLE(track); - auto sink = reinterpret_cast(sinkHandle); + auto sink = reinterpret_cast(sinkHandle); - if (sink != nullptr) { - // Once removed, the source no longer calls it. - track->RemoveSink(sink); + if (sink != nullptr) { + // Once removed, the source no longer calls it. + track->RemoveSink(sink); - delete sink; - } + delete sink; + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_setVolumeInternal (JNIEnv * env, jobject caller, jdouble volume) { - jni::NativeLease track(env, caller); - CHECK_HANDLE(track); + jni::CallFromJava(env, [&]() { + jni::NativeLease track(env, caller); + CHECK_HANDLE(track); - // Only the source of a remote track, a RemoteAudioSource, applies the - // volume; the source of a local track ignores it. - webrtc::AudioSourceInterface * source = track->GetSource(); + // Only the source of a remote track, a RemoteAudioSource, applies the + // volume; the source of a local track ignores it. + webrtc::AudioSourceInterface * source = track->GetSource(); - if (source != nullptr) { - source->SetVolume(static_cast(volume)); - } + if (source != nullptr) { + source->SetVolume(static_cast(volume)); + } + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_getSignalLevel (JNIEnv * env, jobject caller) { - int level = 0; + return jni::CallFromJava(env, [&]() -> jint { + int level = 0; - jni::NativeLease track(env, caller); - CHECK_HANDLEV(track, level); + jni::NativeLease track(env, caller); + CHECK_HANDLEV(track, level); - track->GetSignalLevel(&level); + track->GetSignalLevel(&level); - return static_cast(level); + return static_cast(level); + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_AudioTrackSource.cpp b/webrtc-jni/src/main/cpp/src/JNI_AudioTrackSource.cpp index b74c1b33a..4a173631b 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_AudioTrackSource.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_AudioTrackSource.cpp @@ -15,6 +15,7 @@ */ #include "JNI_AudioTrackSource.h" +#include "JavaBoundary.h" #include "JavaUtils.h" #include "NativeHandle.h" @@ -25,17 +26,19 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrackSource_dispose (JNIEnv * env, jobject caller) { - webrtc::AudioSourceInterface * source = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::AudioSourceInterface * source = jni::TakeHandle(env, caller); - if (source == nullptr) { - return; - } + if (source == nullptr) { + return; + } - jni::ReleaseHandle(env, source, [source](bool) { - webrtc::RefCountReleaseStatus status = source->Release(); + jni::ReleaseHandle(env, source, [source](bool) { + webrtc::RefCountReleaseStatus status = source->Release(); - if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; - } + if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + } + }); }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_CustomAudioSource.cpp b/webrtc-jni/src/main/cpp/src/JNI_CustomAudioSource.cpp index fb6691322..0c852f47c 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_CustomAudioSource.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_CustomAudioSource.cpp @@ -15,6 +15,7 @@ */ #include "JNI_CustomAudioSource.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "JavaUtils.h" @@ -39,31 +40,35 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_CustomAudioSource_init JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_CustomAudioSource_initializeWithClock (JNIEnv * env, jobject caller, jobject javaClock) { - jni::NativeLease> clock(env, javaClock); - CHECK_HANDLE(clock); + jni::CallFromJava(env, [&]() { + jni::NativeLease> clock(env, javaClock); + CHECK_HANDLE(clock); - // The source shares the clock, so disposing the Java clock while the - // source is still pushed to does not free it. - webrtc::scoped_refptr source = webrtc::make_ref_counted(*clock); + // The source shares the clock, so disposing the Java clock while the + // source is still pushed to does not free it. + webrtc::scoped_refptr source = webrtc::make_ref_counted(*clock); - SetHandle(env, caller, source.release()); + SetHandle(env, caller, source.release()); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_CustomAudioSource_dispose (JNIEnv * env, jobject caller) { - jni::CustomAudioSource * source = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + jni::CustomAudioSource * source = jni::TakeHandle(env, caller); - if (source == nullptr) { - return; - } + if (source == nullptr) { + return; + } - jni::ReleaseHandle(env, source, [source](bool) { - webrtc::RefCountReleaseStatus status = source->Release(); + jni::ReleaseHandle(env, source, [source](bool) { + webrtc::RefCountReleaseStatus status = source->Release(); - if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; - } + if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + } + }); }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_CustomVideoSource.cpp b/webrtc-jni/src/main/cpp/src/JNI_CustomVideoSource.cpp index 74d4bd63a..16fc1d786 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_CustomVideoSource.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_CustomVideoSource.cpp @@ -15,6 +15,7 @@ */ #include "JNI_CustomVideoSource.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "JavaUtils.h" #include "api/VideoFrame.h" @@ -40,68 +41,76 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_CustomVideoSource_init JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_CustomVideoSource_initializeWithClock (JNIEnv * env, jobject caller, jobject javaClock) { - jni::NativeLease> clock(env, javaClock); - CHECK_HANDLE(clock); + jni::CallFromJava(env, [&]() { + jni::NativeLease> clock(env, javaClock); + CHECK_HANDLE(clock); - // The source shares the clock, so disposing the Java clock while the - // source is still pushed to does not free it. - webrtc::scoped_refptr source = webrtc::make_ref_counted(*clock); + // The source shares the clock, so disposing the Java clock while the + // source is still pushed to does not free it. + webrtc::scoped_refptr source = webrtc::make_ref_counted(*clock); - SetHandle(env, caller, source.release()); + SetHandle(env, caller, source.release()); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_CustomVideoSource_dispose (JNIEnv * env, jobject caller) { - jni::CustomVideoSource * source = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + jni::CustomVideoSource * source = jni::TakeHandle(env, caller); - if (source == nullptr) { - return; - } + if (source == nullptr) { + return; + } - jni::ReleaseHandle(env, source, [source](bool) { - webrtc::RefCountReleaseStatus status = source->Release(); + jni::ReleaseHandle(env, source, [source](bool) { + webrtc::RefCountReleaseStatus status = source->Release(); - if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; - } - }); + if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + } + }); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_CustomVideoSource_pushFrame (JNIEnv * env, jobject caller, jobject javaFrame) { - jni::NativeLease source(env, caller); - CHECK_HANDLE(source); - - if (javaFrame != nullptr) { - try { - auto frame = jni::JavaLocalRef(env, javaFrame); - webrtc::VideoFrame nativeFrame = jni::VideoFrame::toNative(env, frame); - - source->PushFrame(nativeFrame); - } - catch (...) { - ThrowCxxJavaException(env); - } - } + jni::CallFromJava(env, [&]() { + jni::NativeLease source(env, caller); + CHECK_HANDLE(source); + + if (javaFrame != nullptr) { + try { + auto frame = jni::JavaLocalRef(env, javaFrame); + webrtc::VideoFrame nativeFrame = jni::VideoFrame::toNative(env, frame); + + source->PushFrame(nativeFrame); + } + catch (...) { + ThrowCxxJavaException(env); + } + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_CustomVideoSource_pushFrameTimestamped (JNIEnv * env, jobject caller, jobject javaFrame, jlong timestampUs) { - jni::NativeLease source(env, caller); - CHECK_HANDLE(source); - - if (javaFrame != nullptr) { - try { - auto frame = jni::JavaLocalRef(env, javaFrame); - webrtc::VideoFrame nativeFrame = jni::VideoFrame::toNative(env, frame); - - source->PushFrame(nativeFrame, timestampUs); - } - catch (...) { - ThrowCxxJavaException(env); - } - } + jni::CallFromJava(env, [&]() { + jni::NativeLease source(env, caller); + CHECK_HANDLE(source); + + if (javaFrame != nullptr) { + try { + auto frame = jni::JavaLocalRef(env, javaFrame); + webrtc::VideoFrame nativeFrame = jni::VideoFrame::toNative(env, frame); + + source->PushFrame(nativeFrame, timestampUs); + } + catch (...) { + ThrowCxxJavaException(env); + } + } + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_DesktopCapturer.cpp b/webrtc-jni/src/main/cpp/src/JNI_DesktopCapturer.cpp index 76badc757..b250e74e0 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_DesktopCapturer.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_DesktopCapturer.cpp @@ -15,6 +15,7 @@ */ #include "JNI_DesktopCapturer.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "JavaArrayList.h" #include "JavaError.h" @@ -28,21 +29,23 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_DesktopCapturer_dispose (JNIEnv * env, jobject caller) { - jni::DesktopCapturer * capturer = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + jni::DesktopCapturer * capturer = jni::TakeHandle(env, caller); - if (capturer == nullptr) { - return; - } + if (capturer == nullptr) { + return; + } - auto callback = GetHandle(env, caller, "callbackHandle"); + auto callback = GetHandle(env, caller, "callbackHandle"); - SetHandle(env, caller, "callbackHandle", nullptr); + SetHandle(env, caller, "callbackHandle", nullptr); - // A captureFrame() running on another thread, or the one whose callback - // disposes the capturer, still uses both. - jni::ReleaseHandle(env, capturer, [capturer, callback](bool) { - delete capturer; - delete callback; + // A captureFrame() running on another thread, or the one whose callback + // disposes the capturer, still uses both. + jni::ReleaseHandle(env, capturer, [capturer, callback](bool) { + delete capturer; + delete callback; + }); }); } @@ -95,54 +98,62 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_DesktopCapture JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_DesktopCapturer_setFocusSelectedSource (JNIEnv * env, jobject caller, jboolean focus) { - jni::NativeLease capturer(env, caller); - CHECK_HANDLE(capturer); + jni::CallFromJava(env, [&]() { + jni::NativeLease capturer(env, caller); + CHECK_HANDLE(capturer); - capturer->setFocusSelectedSource(focus); + capturer->setFocusSelectedSource(focus); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_DesktopCapturer_setMaxFrameRate (JNIEnv * env, jobject caller, jint maxFrameRate) { - jni::NativeLease capturer(env, caller); - CHECK_HANDLE(capturer); + jni::CallFromJava(env, [&]() { + jni::NativeLease capturer(env, caller); + CHECK_HANDLE(capturer); - capturer->SetMaxFrameRate(maxFrameRate); + capturer->SetMaxFrameRate(maxFrameRate); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_DesktopCapturer_start (JNIEnv * env, jobject caller, jobject jcallback) { - if (jcallback == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "DesktopCaptureCallback is null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jcallback == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "DesktopCaptureCallback is null")); + return; + } - jni::NativeLease capturer(env, caller); - CHECK_HANDLE(capturer); + jni::NativeLease capturer(env, caller); + CHECK_HANDLE(capturer); - auto callback = new jni::DesktopCaptureCallback(env, jni::JavaGlobalRef(env, jcallback)); + auto callback = new jni::DesktopCaptureCallback(env, jni::JavaGlobalRef(env, jcallback)); - try { - SetHandle(env, caller, "callbackHandle", callback); + try { + SetHandle(env, caller, "callbackHandle", callback); - capturer->Start(callback); - } - catch (...) { - ThrowCxxJavaException(env); - } + capturer->Start(callback); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_desktop_DesktopCapturer_captureFrame (JNIEnv * env, jobject caller) { - jni::NativeLease capturer(env, caller); - CHECK_HANDLE(capturer); + jni::CallFromJava(env, [&]() { + jni::NativeLease capturer(env, caller); + CHECK_HANDLE(capturer); - try { - capturer->CaptureFrame(); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + capturer->CaptureFrame(); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_HeadlessAudioDeviceModule.cpp b/webrtc-jni/src/main/cpp/src/JNI_HeadlessAudioDeviceModule.cpp index 529842853..5969069ba 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_HeadlessAudioDeviceModule.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_HeadlessAudioDeviceModule.cpp @@ -15,6 +15,7 @@ */ #include "JNI_HeadlessAudioDeviceModule.h" +#include "JavaBoundary.h" #include "Exception.h" #include "JavaError.h" #include "JavaUtils.h" @@ -26,17 +27,19 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_audio_HeadlessAudioDeviceModule_initialize (JNIEnv* env, jobject caller) { - webrtc::scoped_refptr audioModule = jni::HeadlessAudioDeviceModule::Create(); + jni::CallFromJava(env, [&]() { + webrtc::scoped_refptr audioModule = jni::HeadlessAudioDeviceModule::Create(); - if (!audioModule) { - env->Throw(jni::JavaError(env, "Create HeadlessAudioDeviceModule failed")); - return; - } + if (!audioModule) { + env->Throw(jni::JavaError(env, "Create HeadlessAudioDeviceModule failed")); + return; + } - if (audioModule->Init() != 0) { - env->Throw(jni::JavaError(env, "Initialize HeadlessAudioDeviceModule failed")); - return; - } + if (audioModule->Init() != 0) { + env->Throw(jni::JavaError(env, "Initialize HeadlessAudioDeviceModule failed")); + return; + } - SetHandle(env, caller, audioModule.release()); + SetHandle(env, caller, audioModule.release()); + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_Logging.cpp b/webrtc-jni/src/main/cpp/src/JNI_Logging.cpp index a7951c847..cc14c0549 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_Logging.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_Logging.cpp @@ -15,6 +15,7 @@ */ #include "JNI_Logging.h" +#include "JavaBoundary.h" #include "rtc/LogSink.h" #include "JavaEnums.h" #include "JavaRef.h" @@ -116,5 +117,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_logging_Logging_logToDebug JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_logging_Logging_logTimestamps (JNIEnv * env, jclass caller, jboolean enable) { - webrtc::LogMessage::LogTimestamps(static_cast(enable)); + jni::CallFromJava(env, [&]() { + webrtc::LogMessage::LogTimestamps(static_cast(enable)); + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_MediaStream.cpp b/webrtc-jni/src/main/cpp/src/JNI_MediaStream.cpp index 3549486ef..f20d704ed 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_MediaStream.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_MediaStream.cpp @@ -15,6 +15,7 @@ */ #include "JNI_MediaStream.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/WebRTCUtils.h" #include "JavaError.h" @@ -44,81 +45,91 @@ JNIEXPORT jstring JNICALL Java_dev_onvoid_webrtc_media_MediaStream_id JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_media_MediaStream_getAudioTracks (JNIEnv * env, jobject caller) { - jni::NativeLease stream(env, caller); - CHECK_HANDLEV(stream, nullptr); + return jni::CallFromJava(env, [&]() -> jobjectArray { + jni::NativeLease stream(env, caller); + CHECK_HANDLEV(stream, nullptr); - jni::JavaLocalRef objectArray; + jni::JavaLocalRef objectArray; - try { - objectArray = jni::MediaStreamTrackView::createArray(env, stream->GetAudioTracks()); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + objectArray = jni::MediaStreamTrackView::createArray(env, stream->GetAudioTracks()); + } + catch (...) { + ThrowCxxJavaException(env); + } - return objectArray.release(); + return objectArray.release(); + }); } JNIEXPORT jobjectArray JNICALL Java_dev_onvoid_webrtc_media_MediaStream_getVideoTracks (JNIEnv * env, jobject caller) { - jni::NativeLease stream(env, caller); - CHECK_HANDLEV(stream, nullptr); + return jni::CallFromJava(env, [&]() -> jobjectArray { + jni::NativeLease stream(env, caller); + CHECK_HANDLEV(stream, nullptr); - jni::JavaLocalRef objectArray; + jni::JavaLocalRef objectArray; - try { - objectArray = jni::MediaStreamTrackView::createArray(env, stream->GetVideoTracks()); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + objectArray = jni::MediaStreamTrackView::createArray(env, stream->GetVideoTracks()); + } + catch (...) { + ThrowCxxJavaException(env); + } - return objectArray.release(); + return objectArray.release(); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStream_addTrack (JNIEnv * env, jobject caller, jobject jTrack) { - jni::NativeLease stream(env, caller); - CHECK_HANDLE(stream); - - jni::NativeLease track(env, jTrack); - CHECK_HANDLE(track); - - if (webrtc::AudioTrackInterface * t = dynamic_cast(track.get())) { - stream->AddTrack(webrtc::scoped_refptr(t)); - } - else if (webrtc::VideoTrackInterface * t = dynamic_cast(track.get())) { - stream->AddTrack(webrtc::scoped_refptr(t)); - } + jni::CallFromJava(env, [&]() { + jni::NativeLease stream(env, caller); + CHECK_HANDLE(stream); + + jni::NativeLease track(env, jTrack); + CHECK_HANDLE(track); + + if (webrtc::AudioTrackInterface * t = dynamic_cast(track.get())) { + stream->AddTrack(webrtc::scoped_refptr(t)); + } + else if (webrtc::VideoTrackInterface * t = dynamic_cast(track.get())) { + stream->AddTrack(webrtc::scoped_refptr(t)); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStream_removeTrack (JNIEnv * env, jobject caller, jobject jTrack) { - jni::NativeLease stream(env, caller); - CHECK_HANDLE(stream); - - jni::NativeLease track(env, jTrack); - CHECK_HANDLE(track); - - if (webrtc::AudioTrackInterface * t = dynamic_cast(track.get())) { - stream->RemoveTrack(webrtc::scoped_refptr(t)); - } - else if (webrtc::VideoTrackInterface * t = dynamic_cast(track.get())) { - stream->RemoveTrack(webrtc::scoped_refptr(t)); - } + jni::CallFromJava(env, [&]() { + jni::NativeLease stream(env, caller); + CHECK_HANDLE(stream); + + jni::NativeLease track(env, jTrack); + CHECK_HANDLE(track); + + if (webrtc::AudioTrackInterface * t = dynamic_cast(track.get())) { + stream->RemoveTrack(webrtc::scoped_refptr(t)); + } + else if (webrtc::VideoTrackInterface * t = dynamic_cast(track.get())) { + stream->RemoveTrack(webrtc::scoped_refptr(t)); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_MediaStream_dispose (JNIEnv * env, jobject caller) { - // Java MediaStreams are only made by PeerConnectionObserver::OnAddTrack, - // as views of the peer connection's remote streams that hold no reference. - // Releasing one here dropped the peer connection's reference instead, and - // could free the stream while WebRTC still used it. Only the Java object - // is detached. A Java MediaStream made with a reference of its own would - // have to be told apart here, as MediaStreamTrack tells its views apart. - jni::NativeHandle::Take(env, caller); + jni::CallFromJava(env, [&]() { + // Java MediaStreams are only made by PeerConnectionObserver::OnAddTrack, + // as views of the peer connection's remote streams that hold no reference. + // Releasing one here dropped the peer connection's reference instead, and + // could free the stream while WebRTC still used it. Only the Java object + // is detached. A Java MediaStream made with a reference of its own would + // have to be told apart here, as MediaStreamTrack tells its views apart. + jni::NativeHandle::Take(env, caller); + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp b/webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp index 0cc208a86..1b11e467e 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp @@ -15,6 +15,7 @@ */ #include "JNI_NativeApi.h" +#include "JavaBoundary.h" #include "api/ExtensionApi.h" #include "api/EncodedFrameTransformer.h" @@ -32,33 +33,43 @@ namespace JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_tableAddress (JNIEnv * env, jclass caller) { - return reinterpret_cast(jni::GetExtensionApi()); + return jni::CallFromJava(env, [&]() -> jlong { + return reinterpret_cast(jni::GetExtensionApi()); + }); } JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_version (JNIEnv * env, jclass caller) { - return static_cast(jni::GetExtensionApi()->version); + return jni::CallFromJava(env, [&]() -> jint { + return static_cast(jni::GetExtensionApi()->version); + }); } JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_senderFrames (JNIEnv * env, jclass caller, jlong handle) { - auto sender = reinterpret_cast(handle); + return jni::CallFromJava(env, [&]() -> jlong { + auto sender = reinterpret_cast(handle); - return sender != nullptr ? Retained(jni::EncodedFrameTransformer::Of(sender)) : 0; + return sender != nullptr ? Retained(jni::EncodedFrameTransformer::Of(sender)) : 0; + }); } JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_receiverFrames (JNIEnv * env, jclass caller, jlong handle) { - auto receiver = reinterpret_cast(handle); + return jni::CallFromJava(env, [&]() -> jlong { + auto receiver = reinterpret_cast(handle); - return receiver != nullptr ? Retained(jni::EncodedFrameTransformer::Of(receiver)) : 0; + return receiver != nullptr ? Retained(jni::EncodedFrameTransformer::Of(receiver)) : 0; + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_releaseFrames (JNIEnv * env, jclass caller, jlong frames) { - jni::GetExtensionApi()->encoded_frames_release(reinterpret_cast(frames)); + jni::CallFromJava(env, [&]() { + jni::GetExtensionApi()->encoded_frames_release(reinterpret_cast(frames)); + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_NativeI420Buffer.cpp b/webrtc-jni/src/main/cpp/src/JNI_NativeI420Buffer.cpp index a69301a6d..4f884eb59 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_NativeI420Buffer.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_NativeI420Buffer.cpp @@ -15,6 +15,7 @@ */ #include "JNI_NativeI420Buffer.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/VideoFrame.h" #include "JavaRuntimeException.h" @@ -72,29 +73,31 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_video_NativeI420Buffer_co JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_video_NativeI420Buffer_crop (JNIEnv * env, jobject caller, jint cropX, jint cropY, jint cropW, jint cropH) { - jni::NativeLease buffer(env, caller); - CHECK_HANDLEV(buffer, nullptr); + return jni::CallFromJava(env, [&]() -> jobject { + jni::NativeLease buffer(env, caller); + CHECK_HANDLEV(buffer, nullptr); - try { - webrtc::scoped_refptr source(buffer); + try { + webrtc::scoped_refptr source(buffer); - // The cropped buffer points into the source, which it keeps alive until it is gone itself. - webrtc::scoped_refptr cropped = webrtc::WrapI420Buffer(cropW, cropH, - source->DataY() + cropX + cropY * source->StrideY(), source->StrideY(), - source->DataU() + cropX / 2 + cropY / 2 * source->StrideU(), source->StrideU(), - source->DataV() + cropX / 2 + cropY / 2 * source->StrideV(), source->StrideV(), - [source]() {}); + // The cropped buffer points into the source, which it keeps alive until it is gone itself. + webrtc::scoped_refptr cropped = webrtc::WrapI420Buffer(cropW, cropH, + source->DataY() + cropX + cropY * source->StrideY(), source->StrideY(), + source->DataU() + cropX / 2 + cropY / 2 * source->StrideU(), source->StrideU(), + source->DataV() + cropX / 2 + cropY / 2 * source->StrideV(), source->StrideV(), + [source]() {}); - jni::JavaLocalRef jBuffer = jni::I420Buffer::toJava(env, cropped); + jni::JavaLocalRef jBuffer = jni::I420Buffer::toJava(env, cropped); - cropped->AddRef(); + cropped->AddRef(); - return jBuffer.release(); - } - catch (...) { - ThrowCxxJavaException(env); - return nullptr; - } + return jBuffer.release(); + } + catch (...) { + ThrowCxxJavaException(env); + return nullptr; + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_NativeI420Buffer_cropAndScale @@ -103,24 +106,26 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_NativeI420Buffer_cropA jobject jDstY, jint dstStrideY, jobject jDstU, jint dstStrideU, jobject jDstV, jint dstStrideV, jint scaleW, jint scaleH) { - const uint8_t * src_y = static_cast(env->GetDirectBufferAddress(jSrcY)); - const uint8_t * src_u = static_cast(env->GetDirectBufferAddress(jSrcU)); - const uint8_t * src_v = static_cast(env->GetDirectBufferAddress(jSrcV)); - uint8_t * dst_y = static_cast(env->GetDirectBufferAddress(jDstY)); - uint8_t * dst_u = static_cast(env->GetDirectBufferAddress(jDstU)); - uint8_t * dst_v = static_cast(env->GetDirectBufferAddress(jDstV)); - - // Perform cropping using pointer arithmetic. - src_y += cropX + cropY * srcStrideY; - src_u += cropX / 2 + cropY / 2 * srcStrideU; - src_v += cropX / 2 + cropY / 2 * srcStrideV; - - bool ret = libyuv::I420Scale( - src_y, srcStrideY, src_u, srcStrideU, src_v, srcStrideV, cropW, - cropH, dst_y, dstStrideY, dst_u, dstStrideU, dst_v, - dstStrideV, scaleW, scaleH, libyuv::kFilterBox); - - if (ret != 0) { - env->Throw(jni::JavaRuntimeException(env, "I420Buffer crop and scale failed")); - } + jni::CallFromJava(env, [&]() { + const uint8_t * src_y = static_cast(env->GetDirectBufferAddress(jSrcY)); + const uint8_t * src_u = static_cast(env->GetDirectBufferAddress(jSrcU)); + const uint8_t * src_v = static_cast(env->GetDirectBufferAddress(jSrcV)); + uint8_t * dst_y = static_cast(env->GetDirectBufferAddress(jDstY)); + uint8_t * dst_u = static_cast(env->GetDirectBufferAddress(jDstU)); + uint8_t * dst_v = static_cast(env->GetDirectBufferAddress(jDstV)); + + // Perform cropping using pointer arithmetic. + src_y += cropX + cropY * srcStrideY; + src_u += cropX / 2 + cropY / 2 * srcStrideU; + src_v += cropX / 2 + cropY / 2 * srcStrideV; + + bool ret = libyuv::I420Scale( + src_y, srcStrideY, src_u, srcStrideU, src_v, srcStrideV, cropW, + cropH, dst_y, dstStrideY, dst_u, dstStrideU, dst_v, + dstStrideV, scaleW, scaleH, libyuv::kFilterBox); + + if (ret != 0) { + env->Throw(jni::JavaRuntimeException(env, "I420Buffer crop and scale failed")); + } + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedAudioFrameInjector.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedAudioFrameInjector.cpp index 9deadd94c..281c45976 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedAudioFrameInjector.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedAudioFrameInjector.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RTCEncodedAudioFrameInjector.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/EncodedFrameInjectorObserver.h" #include "JavaError.h" @@ -55,74 +56,80 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedAudioFrameInjector_injec (JNIEnv * env, jobject caller, jobject jBuffer, jint position, jint length, jint payloadType, jlong rtpTimestamp, jint audioLevel, jboolean hasAudioLevel, jlong captureTimeMs, jboolean hasCaptureTime) { - jni::NativeLease injector(env, caller); - CHECK_HANDLE(injector); + jni::CallFromJava(env, [&]() { + jni::NativeLease injector(env, caller); + CHECK_HANDLE(injector); - try { - const uint8_t * address = static_cast(env->GetDirectBufferAddress(jBuffer)); + try { + const uint8_t * address = static_cast(env->GetDirectBufferAddress(jBuffer)); - if (address == nullptr) { - env->Throw(jni::JavaError(env, "Non-direct buffer provided")); - return; - } + if (address == nullptr) { + env->Throw(jni::JavaError(env, "Non-direct buffer provided")); + return; + } - jlong capacity = env->GetDirectBufferCapacity(jBuffer); + jlong capacity = env->GetDirectBufferCapacity(jBuffer); - if (position < 0 || length < 0 || static_cast(position) + length > capacity) { - env->Throw(jni::JavaError(env, "Buffer position/length out of bounds")); - return; - } + if (position < 0 || length < 0 || static_cast(position) + length > capacity) { + env->Throw(jni::JavaError(env, "Buffer position/length out of bounds")); + return; + } - // The frame copies the data, so the caller may reuse the buffer. - injectFrame(injector, std::span(address + position, static_cast(length)), - payloadType, rtpTimestamp, audioLevel, hasAudioLevel, captureTimeMs, hasCaptureTime); - } - catch (...) { - ThrowCxxJavaException(env); - } + // The frame copies the data, so the caller may reuse the buffer. + injectFrame(injector, std::span(address + position, static_cast(length)), + payloadType, rtpTimestamp, audioLevel, hasAudioLevel, captureTimeMs, hasCaptureTime); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedAudioFrameInjector_injectByteArray (JNIEnv * env, jobject caller, jbyteArray jData, jint payloadType, jlong rtpTimestamp, jint audioLevel, jboolean hasAudioLevel, jlong captureTimeMs, jboolean hasCaptureTime) { - jni::NativeLease injector(env, caller); - CHECK_HANDLE(injector); + jni::CallFromJava(env, [&]() { + jni::NativeLease injector(env, caller); + CHECK_HANDLE(injector); - try { - auto releaseArray = [env, jData](jbyte * bytes) { - env->ReleaseByteArrayElements(jData, bytes, JNI_ABORT); - }; - std::unique_ptr bytes(env->GetByteArrayElements(jData, nullptr), releaseArray); + try { + auto releaseArray = [env, jData](jbyte * bytes) { + env->ReleaseByteArrayElements(jData, bytes, JNI_ABORT); + }; + std::unique_ptr bytes(env->GetByteArrayElements(jData, nullptr), releaseArray); - if (!bytes) { - return; - } + if (!bytes) { + return; + } - auto data = std::span(reinterpret_cast(bytes.get()), - static_cast(env->GetArrayLength(jData))); + auto data = std::span(reinterpret_cast(bytes.get()), + static_cast(env->GetArrayLength(jData))); - injectFrame(injector, data, payloadType, rtpTimestamp, audioLevel, hasAudioLevel, captureTimeMs, hasCaptureTime); - } - catch (...) { - ThrowCxxJavaException(env); - } + injectFrame(injector, data, payloadType, rtpTimestamp, audioLevel, hasAudioLevel, captureTimeMs, hasCaptureTime); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedAudioFrameInjector_dispose (JNIEnv * env, jobject caller) { - webrtc::EncodedAudioFrameInjectorInterface * injector = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::EncodedAudioFrameInjectorInterface * injector = jni::TakeHandle(env, caller); - if (injector == nullptr) { - return; - } + if (injector == nullptr) { + return; + } - // The sender keeps the injector and its callbacks; only the Java observer - // stops hearing from them here. - ClearNativeObserver(env, caller, "observerHandle"); + // The sender keeps the injector and its callbacks; only the Java observer + // stops hearing from them here. + ClearNativeObserver(env, caller, "observerHandle"); - jni::ReleaseHandle(env, injector, [injector](bool) { - injector->Release(); + jni::ReleaseHandle(env, injector, [injector](bool) { + injector->Release(); + }); }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedFrame.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedFrame.cpp index 1df047948..7c01999cf 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedFrame.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedFrame.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RTCEncodedFrame.h" +#include "JavaBoundary.h" #include "api/frame_transformer_interface.h" @@ -37,53 +38,59 @@ namespace JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedFrame_copyData (JNIEnv * env, jclass caller, jlong handle, jobject target) { - webrtc::TransformableFrameInterface * frame = FrameOf(handle); + jni::CallFromJava(env, [&]() { + webrtc::TransformableFrameInterface * frame = FrameOf(handle); - if (frame == nullptr) { - return; - } + if (frame == nullptr) { + return; + } - uint8_t * address = static_cast(env->GetDirectBufferAddress(target)); - jlong capacity = env->GetDirectBufferCapacity(target); - std::span data = frame->GetData(); + uint8_t * address = static_cast(env->GetDirectBufferAddress(target)); + jlong capacity = env->GetDirectBufferCapacity(target); + std::span data = frame->GetData(); - if (address != nullptr && !data.empty() && capacity >= static_cast(data.size())) { - std::memcpy(address, data.data(), data.size()); - } + if (address != nullptr && !data.empty() && capacity >= static_cast(data.size())) { + std::memcpy(address, data.data(), data.size()); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedFrame_setDataBuffer (JNIEnv * env, jclass caller, jlong handle, jobject source, jint offset, jint length) { - webrtc::TransformableFrameInterface * frame = FrameOf(handle); - const uint8_t * address = static_cast(env->GetDirectBufferAddress(source)); + jni::CallFromJava(env, [&]() { + webrtc::TransformableFrameInterface * frame = FrameOf(handle); + const uint8_t * address = static_cast(env->GetDirectBufferAddress(source)); - if (frame == nullptr || address == nullptr) { - return; - } + if (frame == nullptr || address == nullptr) { + return; + } - frame->SetData(std::span(address + offset, static_cast(length))); + frame->SetData(std::span(address + offset, static_cast(length))); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedFrame_setDataArray (JNIEnv * env, jclass caller, jlong handle, jbyteArray source, jint offset, jint length) { - webrtc::TransformableFrameInterface * frame = FrameOf(handle); + jni::CallFromJava(env, [&]() { + webrtc::TransformableFrameInterface * frame = FrameOf(handle); - if (frame == nullptr) { - return; - } + if (frame == nullptr) { + return; + } - // SetData() copies, so the array stays pinned for no longer than that. - void * elements = env->GetPrimitiveArrayCritical(source, nullptr); + // SetData() copies, so the array stays pinned for no longer than that. + void * elements = env->GetPrimitiveArrayCritical(source, nullptr); - if (elements == nullptr) { - return; - } + if (elements == nullptr) { + return; + } - const uint8_t * address = static_cast(elements) + offset; + const uint8_t * address = static_cast(elements) + offset; - frame->SetData(std::span(address, static_cast(length))); + frame->SetData(std::span(address, static_cast(length))); - env->ReleasePrimitiveArrayCritical(source, elements, JNI_ABORT); + env->ReleasePrimitiveArrayCritical(source, elements, JNI_ABORT); + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedVideoFrameInjector.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedVideoFrameInjector.cpp index 4229dbfac..c7e93ace3 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedVideoFrameInjector.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedVideoFrameInjector.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RTCEncodedVideoFrameInjector.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/EncodedFrameInjectorObserver.h" #include "JavaError.h" @@ -51,74 +52,80 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedVideoFrameInjector_injec (JNIEnv * env, jobject caller, jobject jBuffer, jint position, jint length, jlong rtpTimestamp, jboolean keyFrame, jint width, jint height, jlong captureTimeMs, jboolean hasCaptureTime) { - jni::NativeLease injector(env, caller); - CHECK_HANDLE(injector); + jni::CallFromJava(env, [&]() { + jni::NativeLease injector(env, caller); + CHECK_HANDLE(injector); - try { - const uint8_t * address = static_cast(env->GetDirectBufferAddress(jBuffer)); + try { + const uint8_t * address = static_cast(env->GetDirectBufferAddress(jBuffer)); - if (address == nullptr) { - env->Throw(jni::JavaError(env, "Non-direct buffer provided")); - return; - } + if (address == nullptr) { + env->Throw(jni::JavaError(env, "Non-direct buffer provided")); + return; + } - jlong capacity = env->GetDirectBufferCapacity(jBuffer); + jlong capacity = env->GetDirectBufferCapacity(jBuffer); - if (position < 0 || length < 0 || static_cast(position) + length > capacity) { - env->Throw(jni::JavaError(env, "Buffer position/length out of bounds")); - return; - } + if (position < 0 || length < 0 || static_cast(position) + length > capacity) { + env->Throw(jni::JavaError(env, "Buffer position/length out of bounds")); + return; + } - // The frame copies the data, so the caller may reuse the buffer. - injectFrame(injector, std::span(address + position, static_cast(length)), - rtpTimestamp, keyFrame, width, height, captureTimeMs, hasCaptureTime); - } - catch (...) { - ThrowCxxJavaException(env); - } + // The frame copies the data, so the caller may reuse the buffer. + injectFrame(injector, std::span(address + position, static_cast(length)), + rtpTimestamp, keyFrame, width, height, captureTimeMs, hasCaptureTime); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedVideoFrameInjector_injectByteArray (JNIEnv * env, jobject caller, jbyteArray jData, jlong rtpTimestamp, jboolean keyFrame, jint width, jint height, jlong captureTimeMs, jboolean hasCaptureTime) { - jni::NativeLease injector(env, caller); - CHECK_HANDLE(injector); + jni::CallFromJava(env, [&]() { + jni::NativeLease injector(env, caller); + CHECK_HANDLE(injector); - try { - auto releaseArray = [env, jData](jbyte * bytes) { - env->ReleaseByteArrayElements(jData, bytes, JNI_ABORT); - }; - std::unique_ptr bytes(env->GetByteArrayElements(jData, nullptr), releaseArray); + try { + auto releaseArray = [env, jData](jbyte * bytes) { + env->ReleaseByteArrayElements(jData, bytes, JNI_ABORT); + }; + std::unique_ptr bytes(env->GetByteArrayElements(jData, nullptr), releaseArray); - if (!bytes) { - return; - } + if (!bytes) { + return; + } - auto data = std::span(reinterpret_cast(bytes.get()), - static_cast(env->GetArrayLength(jData))); + auto data = std::span(reinterpret_cast(bytes.get()), + static_cast(env->GetArrayLength(jData))); - injectFrame(injector, data, rtpTimestamp, keyFrame, width, height, captureTimeMs, hasCaptureTime); - } - catch (...) { - ThrowCxxJavaException(env); - } + injectFrame(injector, data, rtpTimestamp, keyFrame, width, height, captureTimeMs, hasCaptureTime); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedVideoFrameInjector_dispose (JNIEnv * env, jobject caller) { - webrtc::EncodedVideoFrameInjectorInterface * injector = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::EncodedVideoFrameInjectorInterface * injector = jni::TakeHandle(env, caller); - if (injector == nullptr) { - return; - } + if (injector == nullptr) { + return; + } - // The sender keeps the injector and its callbacks; only the Java observer - // stops hearing from them here. - ClearNativeObserver(env, caller, "observerHandle"); + // The sender keeps the injector and its callbacks; only the Java observer + // stops hearing from them here. + ClearNativeObserver(env, caller, "observerHandle"); - jni::ReleaseHandle(env, injector, [injector](bool) { - injector->Release(); + jni::ReleaseHandle(env, injector, [injector](bool) { + injector->Release(); + }); }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCRtpTransceiver.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCRtpTransceiver.cpp index c34e30521..3951c7a4f 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCRtpTransceiver.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCRtpTransceiver.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RTCRtpTransceiver.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/RTCRtpCodecCapability.h" #include "JavaEnums.h" @@ -145,35 +146,41 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_getCurrentDir JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_stop (JNIEnv * env, jobject caller) { - jni::NativeLease transceiver(env, caller); - CHECK_HANDLE(transceiver); + jni::CallFromJava(env, [&]() { + jni::NativeLease transceiver(env, caller); + CHECK_HANDLE(transceiver); - webrtc::RTCError result = transceiver->StopStandard(); + webrtc::RTCError result = transceiver->StopStandard(); - if (!result.ok()) { - env->Throw(jni::JavaRuntimeException(env, "Stop transceiver failed: %s %s", - ToString(result.type()), result.message())); - } + if (!result.ok()) { + env->Throw(jni::JavaRuntimeException(env, "Stop transceiver failed: %s %s", + ToString(result.type()), result.message())); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_stopImmediately (JNIEnv * env, jobject caller) { - jni::NativeLease transceiver(env, caller); - CHECK_HANDLE(transceiver); + jni::CallFromJava(env, [&]() { + jni::NativeLease transceiver(env, caller); + CHECK_HANDLE(transceiver); - // Unlike StopStandard, stopped() is true at once, so that an answer - // created next rejects the m-line rather than making it inactive. - transceiver->StopInternal(); + // Unlike StopStandard, stopped() is true at once, so that an answer + // created next rejects the m-line rather than making it inactive. + transceiver->StopInternal(); + }); } JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_stopped (JNIEnv * env, jobject caller) { - jni::NativeLease transceiver(env, caller); - CHECK_HANDLEV(transceiver, true); + return jni::CallFromJava(env, [&]() -> jboolean { + jni::NativeLease transceiver(env, caller); + CHECK_HANDLEV(transceiver, true); - return static_cast(transceiver->stopped()); + return static_cast(transceiver->stopped()); + }); } JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_getCodecPreferences @@ -196,39 +203,43 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_getCodecPrefe JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_setCodecPreferences (JNIEnv * env, jobject caller, jobject jPreferences) { - jni::NativeLease transceiver(env, caller); - CHECK_HANDLE(transceiver); + jni::CallFromJava(env, [&]() { + jni::NativeLease transceiver(env, caller); + CHECK_HANDLE(transceiver); - try { - auto ref = jni::JavaLocalRef(env, jPreferences); - auto preferences = jni::JavaList::toVector(env, ref, &jni::RTCRtpCodecCapability::toNative); + try { + auto ref = jni::JavaLocalRef(env, jPreferences); + auto preferences = jni::JavaList::toVector(env, ref, &jni::RTCRtpCodecCapability::toNative); - webrtc::RTCError result = transceiver->SetCodecPreferences(preferences); + webrtc::RTCError result = transceiver->SetCodecPreferences(preferences); - if (!result.ok()) { - env->Throw(jni::JavaError(env, "Set codec preferences failed: %s", jni::RTCErrorToString(result).c_str())); + if (!result.ok()) { + env->Throw(jni::JavaError(env, "Set codec preferences failed: %s", jni::RTCErrorToString(result).c_str())); + } } - } - catch (...) { - ThrowCxxJavaException(env); - } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCRtpTransceiver_dispose (JNIEnv * env, jobject caller) { - webrtc::RtpTransceiverInterface * transceiver = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + webrtc::RtpTransceiverInterface * transceiver = jni::TakeHandle(env, caller); - if (transceiver == nullptr) { - return; - } + if (transceiver == nullptr) { + return; + } - // Unlike e.g. MediaStreamTrack, an RTCRtpTransceiver is not exclusively - // owned by one Java wrapper: the owning PeerConnection keeps its own - // reference, and other Java wrappers may have been obtained via separate - // getTransceivers() calls. Dropping our reference here is expected to - // leave others around, so it is not reported as an error. - jni::ReleaseHandle(env, transceiver, [transceiver](bool) { - transceiver->Release(); + // Unlike e.g. MediaStreamTrack, an RTCRtpTransceiver is not exclusively + // owned by one Java wrapper: the owning PeerConnection keeps its own + // reference, and other Java wrappers may have been obtained via separate + // getTransceivers() calls. Dropping our reference here is expected to + // leave others around, so it is not reported as an error. + jni::ReleaseHandle(env, transceiver, [transceiver](bool) { + transceiver->Release(); + }); }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_RefCountedObject.cpp b/webrtc-jni/src/main/cpp/src/JNI_RefCountedObject.cpp index 040e1eb45..15333fa12 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RefCountedObject.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RefCountedObject.cpp @@ -15,6 +15,7 @@ */ #include "JNI_RefCountedObject.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "JavaUtils.h" @@ -23,21 +24,25 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_RefCountedObject_retain (JNIEnv * env, jobject caller) { - jni::NativeLease ref(env, caller); - CHECK_HANDLE(ref); + jni::CallFromJava(env, [&]() { + jni::NativeLease ref(env, caller); + CHECK_HANDLE(ref); - ref->AddRef(); + ref->AddRef(); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_RefCountedObject_release (JNIEnv * env, jobject caller) { - jni::NativeLease ref(env, caller); - CHECK_HANDLE(ref); + jni::CallFromJava(env, [&]() { + jni::NativeLease ref(env, caller); + CHECK_HANDLE(ref); - const auto status = ref->Release(); + const auto status = ref->Release(); - if (status == webrtc::RefCountReleaseStatus::kDroppedLastRef) { - SetHandle(env, caller, nullptr); - } + if (status == webrtc::RefCountReleaseStatus::kDroppedLastRef) { + SetHandle(env, caller, nullptr); + } + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_SyncClock.cpp b/webrtc-jni/src/main/cpp/src/JNI_SyncClock.cpp index 70719c552..993f60f95 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_SyncClock.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_SyncClock.cpp @@ -15,6 +15,7 @@ */ #include "JNI_SyncClock.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "JavaUtils.h" #include "media/SyncClock.h" @@ -42,51 +43,61 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_SyncClock_initialize JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_SyncClock_getTimestampUs (JNIEnv * env, jobject caller) { - jni::NativeLease> clock(env, caller); - CHECK_HANDLEV(clock, 0); + return jni::CallFromJava(env, [&]() -> jlong { + jni::NativeLease> clock(env, caller); + CHECK_HANDLEV(clock, 0); - return (*clock)->GetTimestampUs(); + return (*clock)->GetTimestampUs(); + }); } JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_SyncClock_getTimestampMs (JNIEnv * env, jobject caller) { - jni::NativeLease> clock(env, caller); - CHECK_HANDLEV(clock, 0); + return jni::CallFromJava(env, [&]() -> jlong { + jni::NativeLease> clock(env, caller); + CHECK_HANDLEV(clock, 0); - return (*clock)->GetTimestampMs(); + return (*clock)->GetTimestampMs(); + }); } JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_SyncClock_getNtpTime (JNIEnv * env, jobject caller) { - jni::NativeLease> clock(env, caller); - CHECK_HANDLEV(clock, 0); + return jni::CallFromJava(env, [&]() -> jlong { + jni::NativeLease> clock(env, caller); + CHECK_HANDLEV(clock, 0); - webrtc::NtpTime ntpTime = (*clock)->GetNtpTime(); - return ntpTime.ToMs(); + webrtc::NtpTime ntpTime = (*clock)->GetNtpTime(); + return ntpTime.ToMs(); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_SyncClock_dispose (JNIEnv * env, jobject caller) { - auto clock = jni::TakeHandle>(env, caller); + jni::CallFromJava(env, [&]() { + auto clock = jni::TakeHandle>(env, caller); - if (clock == nullptr) { - return; - } + if (clock == nullptr) { + return; + } - // Drops this wrapper's reference only; sources still using the clock - // keep theirs. - jni::ReleaseHandle(env, clock, [clock](bool) { - delete clock; - }); + // Drops this wrapper's reference only; sources still using the clock + // keep theirs. + jni::ReleaseHandle(env, clock, [clock](bool) { + delete clock; + }); + }); } JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_SyncClock_currentTimeUs (JNIEnv * env, jclass caller) { - // The clock capture timestamps handed to the custom media sources are - // interpreted in, which is the one WebRTC itself runs on. - return webrtc::TimeMicros(); + return jni::CallFromJava(env, [&]() -> jlong { + // The clock capture timestamps handed to the custom media sources are + // interpreted in, which is the one WebRTC itself runs on. + return webrtc::TimeMicros(); + }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoBufferConverter.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoBufferConverter.cpp index 3eb280643..ade51c65c 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoBufferConverter.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoBufferConverter.cpp @@ -15,6 +15,7 @@ */ #include "JNI_VideoBufferConverter.h" +#include "JavaBoundary.h" #include "JavaRuntimeException.h" #include "JavaUtils.h" @@ -189,30 +190,32 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoBufferConverter_I (JNIEnv * env, jclass, jobject jSrcY, jint srcStrideY, jobject jSrcU, jint srcStrideU, jobject jSrcV, jint srcStrideV, jobject dst, jint width, jint height, jint fourCC) { - const uint8_t * srcY = static_cast(env->GetDirectBufferAddress(jSrcY)); - const uint8_t * srcU = static_cast(env->GetDirectBufferAddress(jSrcU)); - const uint8_t * srcV = static_cast(env->GetDirectBufferAddress(jSrcV)); + jni::CallFromJava(env, [&]() { + const uint8_t * srcY = static_cast(env->GetDirectBufferAddress(jSrcY)); + const uint8_t * srcU = static_cast(env->GetDirectBufferAddress(jSrcU)); + const uint8_t * srcV = static_cast(env->GetDirectBufferAddress(jSrcV)); - uint8_t * address = static_cast(env->GetDirectBufferAddress(dst)); + uint8_t * address = static_cast(env->GetDirectBufferAddress(dst)); - if (address != NULL) { - jlong bufferLength = env->GetDirectBufferCapacity(dst); + if (address != NULL) { + jlong bufferLength = env->GetDirectBufferCapacity(dst); - if (!CheckBufferSize(env, width, height, fourCC, static_cast(bufferLength))) { - return; - } + if (!CheckBufferSize(env, width, height, fourCC, static_cast(bufferLength))) { + return; + } - const int conversionResult = ConvertFromI420(srcY, srcStrideY, srcU, srcStrideU, - srcV, srcStrideV, address, width, height, static_cast(fourCC)); + const int conversionResult = ConvertFromI420(srcY, srcStrideY, srcU, srcStrideU, + srcV, srcStrideV, address, width, height, static_cast(fourCC)); - if (conversionResult < 0) { - env->Throw(jni::JavaRuntimeException(env, "Failed to convert buffer to I420: %d", - conversionResult)); + if (conversionResult < 0) { + env->Throw(jni::JavaRuntimeException(env, "Failed to convert buffer to I420: %d", + conversionResult)); + } } - } - else { - env->Throw(jni::JavaRuntimeException(env, "Non-direct buffer provided")); - } + else { + env->Throw(jni::JavaRuntimeException(env, "Non-direct buffer provided")); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoBufferConverter_byteArrayToI420 @@ -264,33 +267,35 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoBufferConverter_d (JNIEnv * env, jclass, jobject src, jint width, jint height, jobject jDstY, jint dstStrideY, jobject jDstU, jint dstStrideU, jobject jDstV, jint dstStrideV, jint fourCC) { - uint8_t * dstY = static_cast(env->GetDirectBufferAddress(jDstY)); - uint8_t * dstU = static_cast(env->GetDirectBufferAddress(jDstU)); - uint8_t * dstV = static_cast(env->GetDirectBufferAddress(jDstV)); + jni::CallFromJava(env, [&]() { + uint8_t * dstY = static_cast(env->GetDirectBufferAddress(jDstY)); + uint8_t * dstU = static_cast(env->GetDirectBufferAddress(jDstU)); + uint8_t * dstV = static_cast(env->GetDirectBufferAddress(jDstV)); - const uint8_t * address = static_cast(env->GetDirectBufferAddress(src)); + const uint8_t * address = static_cast(env->GetDirectBufferAddress(src)); - if (address != NULL) { - jlong bufferLength = env->GetDirectBufferCapacity(src); + if (address != NULL) { + jlong bufferLength = env->GetDirectBufferCapacity(src); - if (!CheckBufferSize(env, width, height, fourCC, static_cast(bufferLength))) { - return; - } + if (!CheckBufferSize(env, width, height, fourCC, static_cast(bufferLength))) { + return; + } - const int conversionResult = libyuv::ConvertToI420( - address, bufferLength, - dstY, dstStrideY, - dstU, dstStrideU, - dstV, dstStrideV, - 0, 0, width, height, width, height, - libyuv::kRotate0, static_cast(fourCC)); + const int conversionResult = libyuv::ConvertToI420( + address, bufferLength, + dstY, dstStrideY, + dstU, dstStrideU, + dstV, dstStrideV, + 0, 0, width, height, width, height, + libyuv::kRotate0, static_cast(fourCC)); - if (conversionResult < 0) { - env->Throw(jni::JavaRuntimeException(env, "Failed to convert buffer to I420: %d", - conversionResult)); + if (conversionResult < 0) { + env->Throw(jni::JavaRuntimeException(env, "Failed to convert buffer to I420: %d", + conversionResult)); + } } - } - else { - env->Throw(jni::JavaRuntimeException(env, "Non-direct buffer provided")); - } + else { + env->Throw(jni::JavaRuntimeException(env, "Non-direct buffer provided")); + } + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp index 11e3ff0d9..63b7a84bd 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoCapture.cpp @@ -15,6 +15,7 @@ */ #include "JNI_VideoCapture.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/VideoTrackSink.h" #include "media/video/VideoCapture.h" @@ -52,91 +53,101 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_setVideoC JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_setVideoCaptureCapability (JNIEnv * env, jobject caller, jobject jcapability) { - jni::NativeLease videoSource(env, caller); - CHECK_HANDLE(videoSource); + jni::CallFromJava(env, [&]() { + jni::NativeLease videoSource(env, caller); + CHECK_HANDLE(videoSource); - if (!jcapability) { - env->Throw(jni::JavaNullPointerException(env, "VideoCaptureCapability is null")); - return; - } + if (!jcapability) { + env->Throw(jni::JavaNullPointerException(env, "VideoCaptureCapability is null")); + return; + } - jint width = env->GetIntField(jcapability, GetFieldID(env, jcapability, "width", "I")); - jint height = env->GetIntField(jcapability, GetFieldID(env, jcapability, "height", "I")); - jint frameRate = env->GetIntField(jcapability, GetFieldID(env, jcapability, "frameRate", "I")); + jint width = env->GetIntField(jcapability, GetFieldID(env, jcapability, "width", "I")); + jint height = env->GetIntField(jcapability, GetFieldID(env, jcapability, "height", "I")); + jint frameRate = env->GetIntField(jcapability, GetFieldID(env, jcapability, "frameRate", "I")); - webrtc::VideoCaptureCapability capability; - capability.width = static_cast(width); - capability.height = static_cast(height); - capability.maxFPS = static_cast(frameRate); + webrtc::VideoCaptureCapability capability; + capability.width = static_cast(width); + capability.height = static_cast(height); + capability.maxFPS = static_cast(frameRate); - videoSource->setVideoCaptureCapability(capability); + videoSource->setVideoCaptureCapability(capability); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_setVideoSink (JNIEnv * env, jobject caller, jobject jsink) { - if (jsink == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "VideoTrackSink must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jsink == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "VideoTrackSink must not be null")); + return; + } - jni::NativeLease videoSource(env, caller); - CHECK_HANDLE(videoSource); + jni::NativeLease videoSource(env, caller); + CHECK_HANDLE(videoSource); - try { - videoSource->setVideoSink(std::make_unique(env, jni::JavaGlobalRef(env, jsink), false)); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + videoSource->setVideoSink(std::make_unique(env, jni::JavaGlobalRef(env, jsink), false)); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_start (JNIEnv * env, jobject caller) { - jni::NativeLease videoSource(env, caller); - CHECK_HANDLE(videoSource); + jni::CallFromJava(env, [&]() { + jni::NativeLease videoSource(env, caller); + CHECK_HANDLE(videoSource); - if (!videoSource->hasDevice()) { - ThrowJavaException(env, "java/lang/IllegalStateException", "No video capture device set"); - return; - } + if (!videoSource->hasDevice()) { + ThrowJavaException(env, "java/lang/IllegalStateException", "No video capture device set"); + return; + } - try { - videoSource->start(); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + videoSource->start(); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_stop (JNIEnv * env, jobject caller) { - jni::NativeLease videoSource(env, caller); - CHECK_HANDLE(videoSource); + jni::CallFromJava(env, [&]() { + jni::NativeLease videoSource(env, caller); + CHECK_HANDLE(videoSource); - try { - videoSource->stop(); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + videoSource->stop(); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoCapture_dispose (JNIEnv * env, jobject caller) { - jni::VideoCaptureBase * videoSource = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + jni::VideoCaptureBase * videoSource = jni::TakeHandle(env, caller); - if (videoSource == nullptr) { - return; - } + if (videoSource == nullptr) { + return; + } - // The destructor stops a running capture and detaches the sink before - // both are destroyed. - jni::ReleaseHandle(env, videoSource, [videoSource](bool) { - delete videoSource; + // The destructor stops a running capture and detaches the sink before + // both are destroyed. + jni::ReleaseHandle(env, videoSource, [videoSource](bool) { + delete videoSource; + }); }); } diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp index be2e8161a..85e765acc 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp @@ -15,6 +15,7 @@ */ #include "JNI_VideoDesktopSource.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/VideoTrackSink.h" #include "media/video/VideoTrackDesktopSource.h" @@ -28,86 +29,100 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setSourceId (JNIEnv * env, jobject caller, jlong sourceId, jboolean isWindow) { - jni::NativeLease videoSource(env, caller); - CHECK_HANDLE(videoSource); + jni::CallFromJava(env, [&]() { + jni::NativeLease videoSource(env, caller); + CHECK_HANDLE(videoSource); - videoSource->setSourceId(static_cast(sourceId), static_cast(isWindow)); + videoSource->setSourceId(static_cast(sourceId), static_cast(isWindow)); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setFrameRate (JNIEnv * env, jobject caller, jint frameRate) { - jni::NativeLease videoSource(env, caller); - CHECK_HANDLE(videoSource); + jni::CallFromJava(env, [&]() { + jni::NativeLease videoSource(env, caller); + CHECK_HANDLE(videoSource); - videoSource->setFrameRate(static_cast(frameRate)); + videoSource->setFrameRate(static_cast(frameRate)); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setMaxFrameSize (JNIEnv* env, jobject caller, jint width, jint height) { - jni::NativeLease videoSource(env, caller); - CHECK_HANDLE(videoSource); + jni::CallFromJava(env, [&]() { + jni::NativeLease videoSource(env, caller); + CHECK_HANDLE(videoSource); - videoSource->setMaxFrameSize(webrtc::DesktopSize(width, height)); + videoSource->setMaxFrameSize(webrtc::DesktopSize(width, height)); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_start (JNIEnv * env, jobject caller) { - jni::NativeLease videoSource(env, caller); - CHECK_HANDLE(videoSource); - - try { - videoSource->start(); - } - catch (...) { - ThrowCxxJavaException(env); - } + jni::CallFromJava(env, [&]() { + jni::NativeLease videoSource(env, caller); + CHECK_HANDLE(videoSource); + + try { + videoSource->start(); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_stop (JNIEnv * env, jobject caller) { - jni::NativeLease videoSource(env, caller); - CHECK_HANDLE(videoSource); - - try { - videoSource->stop(); - } - catch (...) { - ThrowCxxJavaException(env); - } + jni::CallFromJava(env, [&]() { + jni::NativeLease videoSource(env, caller); + CHECK_HANDLE(videoSource); + + try { + videoSource->stop(); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_disposeInternal (JNIEnv * env, jobject caller) { - jni::VideoTrackDesktopSource * videoSource = jni::TakeHandle(env, caller); + jni::CallFromJava(env, [&]() { + jni::VideoTrackDesktopSource * videoSource = jni::TakeHandle(env, caller); - if (videoSource == nullptr) { - return; - } + if (videoSource == nullptr) { + return; + } - // A track may keep the source alive; it must not reach the processor - // any more. - videoSource->SetVideoProcessor(env, nullptr); - SetHandle(env, caller, "processorHostHandle", nullptr); + // A track may keep the source alive; it must not reach the processor + // any more. + videoSource->SetVideoProcessor(env, nullptr); + SetHandle(env, caller, "processorHostHandle", nullptr); - jni::ReleaseHandle(env, videoSource, [videoSource](bool) { - webrtc::RefCountReleaseStatus status = videoSource->Release(); + jni::ReleaseHandle(env, videoSource, [videoSource](bool) { + webrtc::RefCountReleaseStatus status = videoSource->Release(); - if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; - } + if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + } + }); }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_initialize (JNIEnv * env, jobject caller) { - webrtc::scoped_refptr videoSource = webrtc::make_ref_counted(); + jni::CallFromJava(env, [&]() { + webrtc::scoped_refptr videoSource = webrtc::make_ref_counted(); - SetHandle(env, caller, "processorHostHandle", static_cast(videoSource.get())); - SetHandle(env, caller, videoSource.release()); + SetHandle(env, caller, "processorHostHandle", static_cast(videoSource.get())); + SetHandle(env, caller, videoSource.release()); + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoDeviceSource.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoDeviceSource.cpp index 33db91389..5e9074f94 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoDeviceSource.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoDeviceSource.cpp @@ -15,6 +15,7 @@ */ #include "JNI_VideoDeviceSource.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/VideoTrackSink.h" #include "media/video/VideoDevice.h" @@ -59,106 +60,116 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDeviceSource_setV JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDeviceSource_setVideoCaptureCapability (JNIEnv * env, jobject caller, jobject jcapability) { + jni::CallFromJava(env, [&]() { #ifdef __APPLE__ - jni::NativeLease videoSource(env, caller); + jni::NativeLease videoSource(env, caller); #else - jni::NativeLease videoSource(env, caller); + jni::NativeLease videoSource(env, caller); #endif - CHECK_HANDLE(videoSource); + CHECK_HANDLE(videoSource); - if (!jcapability) { - env->Throw(jni::JavaNullPointerException(env, "VideoCaptureCapability is null")); - return; - } + if (!jcapability) { + env->Throw(jni::JavaNullPointerException(env, "VideoCaptureCapability is null")); + return; + } - jint width = env->GetIntField(jcapability, GetFieldID(env, jcapability, "width", "I")); - jint height = env->GetIntField(jcapability, GetFieldID(env, jcapability, "height", "I")); - jint frameRate = env->GetIntField(jcapability, GetFieldID(env, jcapability, "frameRate", "I")); + jint width = env->GetIntField(jcapability, GetFieldID(env, jcapability, "width", "I")); + jint height = env->GetIntField(jcapability, GetFieldID(env, jcapability, "height", "I")); + jint frameRate = env->GetIntField(jcapability, GetFieldID(env, jcapability, "frameRate", "I")); - webrtc::VideoCaptureCapability capability; - capability.width = static_cast(width); - capability.height = static_cast(height); - capability.maxFPS = static_cast(frameRate); + webrtc::VideoCaptureCapability capability; + capability.width = static_cast(width); + capability.height = static_cast(height); + capability.maxFPS = static_cast(frameRate); - videoSource->setVideoCaptureCapability(capability); + videoSource->setVideoCaptureCapability(capability); + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDeviceSource_start (JNIEnv * env, jobject caller) { + jni::CallFromJava(env, [&]() { #ifdef __APPLE__ - jni::NativeLease videoSource(env, caller); + jni::NativeLease videoSource(env, caller); #else - jni::NativeLease videoSource(env, caller); + jni::NativeLease videoSource(env, caller); #endif - CHECK_HANDLE(videoSource); + CHECK_HANDLE(videoSource); - try { - videoSource->start(); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + videoSource->start(); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDeviceSource_stop (JNIEnv * env, jobject caller) { + jni::CallFromJava(env, [&]() { #ifdef __APPLE__ - jni::NativeLease videoSource(env, caller); + jni::NativeLease videoSource(env, caller); #else - jni::NativeLease videoSource(env, caller); + jni::NativeLease videoSource(env, caller); #endif - CHECK_HANDLE(videoSource); + CHECK_HANDLE(videoSource); - try { - videoSource->stop(); - } - catch (...) { - ThrowCxxJavaException(env); - } + try { + videoSource->stop(); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDeviceSource_disposeInternal (JNIEnv * env, jobject caller) { + jni::CallFromJava(env, [&]() { #ifdef __APPLE__ - jni::VideoTrackDeviceSourceMac * videoSource = jni::TakeHandle(env, caller); + jni::VideoTrackDeviceSourceMac * videoSource = jni::TakeHandle(env, caller); #else - jni::VideoTrackDeviceSource * videoSource = jni::TakeHandle(env, caller); + jni::VideoTrackDeviceSource * videoSource = jni::TakeHandle(env, caller); #endif - if (videoSource == nullptr) { - return; - } + if (videoSource == nullptr) { + return; + } - // A track may keep the source alive; it must not reach the processor - // any more. - videoSource->SetVideoProcessor(env, nullptr); - SetHandle(env, caller, "processorHostHandle", nullptr); + // A track may keep the source alive; it must not reach the processor + // any more. + videoSource->SetVideoProcessor(env, nullptr); + SetHandle(env, caller, "processorHostHandle", nullptr); - jni::ReleaseHandle(env, videoSource, [videoSource](bool) { - webrtc::RefCountReleaseStatus status = videoSource->Release(); + jni::ReleaseHandle(env, videoSource, [videoSource](bool) { + webrtc::RefCountReleaseStatus status = videoSource->Release(); - if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { - RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; - } + if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) { + RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere."; + } + }); }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDeviceSource_initialize (JNIEnv * env, jobject caller) { + jni::CallFromJava(env, [&]() { #ifdef __APPLE__ - webrtc::scoped_refptr videoSource_ = webrtc::make_ref_counted(); - SetHandle(env, caller, "processorHostHandle", static_cast(videoSource_.get())); - SetHandle(env, caller, videoSource_.release()); + webrtc::scoped_refptr videoSource_ = webrtc::make_ref_counted(); + SetHandle(env, caller, "processorHostHandle", static_cast(videoSource_.get())); + SetHandle(env, caller, videoSource_.release()); #else - webrtc::scoped_refptr videoSource = webrtc::make_ref_counted(); - SetHandle(env, caller, "processorHostHandle", static_cast(videoSource.get())); - SetHandle(env, caller, videoSource.release()); + webrtc::scoped_refptr videoSource = webrtc::make_ref_counted(); + SetHandle(env, caller, "processorHostHandle", static_cast(videoSource.get())); + SetHandle(env, caller, videoSource.release()); #endif + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoTrack.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoTrack.cpp index 98c14b856..839309fca 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoTrack.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoTrack.cpp @@ -15,6 +15,7 @@ */ #include "JNI_VideoTrack.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/VideoTrackSink.h" #include "JavaNullPointerException.h" @@ -49,14 +50,16 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrack_addSinkInt JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrack_removeSinkInternal (JNIEnv * env, jobject caller, jlong sinkHandle) { - jni::NativeLease track(env, caller); - CHECK_HANDLE(track); + jni::CallFromJava(env, [&]() { + jni::NativeLease track(env, caller); + CHECK_HANDLE(track); - auto sink = reinterpret_cast *>(sinkHandle); + auto sink = reinterpret_cast *>(sinkHandle); - if (sink != nullptr) { - track->RemoveSink(sink); + if (sink != nullptr) { + track->RemoveSink(sink); - delete sink; - } + delete sink; + } + }); } \ No newline at end of file diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoTrackSource.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoTrackSource.cpp index 408eb276c..303096c02 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoTrackSource.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoTrackSource.cpp @@ -15,6 +15,7 @@ */ #include "JNI_VideoTrackSource.h" +#include "JavaBoundary.h" #include "NativeHandle.h" #include "api/VideoFrame.h" #include "media/video/VideoProcessorHost.h" @@ -31,72 +32,76 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrackSource_setVideoProcessorNative (JNIEnv * env, jobject caller, jobject jProcessor) { - // Keeps the source, which the host is part of, from being freed meanwhile. - jni::NativeLease source(env, caller); - CHECK_HANDLE(source); - - jni::VideoProcessorHost * host = GetHandle(env, caller, "processorHostHandle"); - - if (host == nullptr) { - env->Throw(jni::JavaRuntimeException(env, "The video source does not support a VideoProcessor")); - return; - } - - try { - host->SetVideoProcessor(env, jProcessor); - } - catch (...) { - ThrowCxxJavaException(env); - } + jni::CallFromJava(env, [&]() { + // Keeps the source, which the host is part of, from being freed meanwhile. + jni::NativeLease source(env, caller); + CHECK_HANDLE(source); + + jni::VideoProcessorHost * host = GetHandle(env, caller, "processorHostHandle"); + + if (host == nullptr) { + env->Throw(jni::JavaRuntimeException(env, "The video source does not support a VideoProcessor")); + return; + } + + try { + host->SetVideoProcessor(env, jProcessor); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoTrackSource_deliverProcessedFrame (JNIEnv * env, jobject caller, jobject jFrame) { - if (jFrame == nullptr) { - env->Throw(jni::JavaNullPointerException(env, "VideoFrame must not be null")); - return; - } + jni::CallFromJava(env, [&]() { + if (jFrame == nullptr) { + env->Throw(jni::JavaNullPointerException(env, "VideoFrame must not be null")); + return; + } - // Keeps the source, which the host is part of, from being freed meanwhile. - jni::NativeLease source(env, caller); + // Keeps the source, which the host is part of, from being freed meanwhile. + jni::NativeLease source(env, caller); - jni::VideoProcessorHost * host = source - ? GetHandle(env, caller, "processorHostHandle") - : nullptr; + jni::VideoProcessorHost * host = source + ? GetHandle(env, caller, "processorHostHandle") + : nullptr; - // The source has been disposed. - if (host == nullptr) { - return; - } + // The source has been disposed. + if (host == nullptr) { + return; + } - try { - const auto frameClass = jni::JavaClasses::get(env); + try { + const auto frameClass = jni::JavaClasses::get(env); - const jni::JavaLocalRef frameRef(env, jFrame); - jni::JavaObject frame(env, frameRef); + const jni::JavaLocalRef frameRef(env, jFrame); + jni::JavaObject frame(env, frameRef); - const jint rotation = frame.getInt(frameClass->rotation); - const jlong timestampNs = frame.getLong(frameClass->timestampNs); + const jint rotation = frame.getInt(frameClass->rotation); + const jlong timestampNs = frame.getLong(frameClass->timestampNs); - webrtc::scoped_refptr buffer = - jni::VideoFrame::toNativeBuffer(env, frame.getObject(frameClass->buffer)); + webrtc::scoped_refptr buffer = + jni::VideoFrame::toNativeBuffer(env, frame.getObject(frameClass->buffer)); - if (buffer == nullptr) { - env->Throw(jni::JavaRuntimeException(env, "The buffer of the VideoFrame cannot be read")); - return; - } + if (buffer == nullptr) { + env->Throw(jni::JavaRuntimeException(env, "The buffer of the VideoFrame cannot be read")); + return; + } + + // Java only allows multiples of 90. + const int degrees = ((rotation % 360) + 360) % 360; - // Java only allows multiples of 90. - const int degrees = ((rotation % 360) + 360) % 360; - - host->DeliverProcessedFrame(webrtc::VideoFrame::Builder() - .set_video_frame_buffer(buffer) - .set_rotation(static_cast(degrees)) - .set_timestamp_us(timestampNs / 1000) - .build()); - } - catch (...) { - ThrowCxxJavaException(env); - } + host->DeliverProcessedFrame(webrtc::VideoFrame::Builder() + .set_video_frame_buffer(buffer) + .set_rotation(static_cast(degrees)) + .set_timestamp_us(timestampNs / 1000) + .build()); + } + catch (...) { + ThrowCxxJavaException(env); + } + }); }