diff --git a/webrtc-jni/src/main/cpp/include/JNI_RTCEncodedAudioFrameInjector.h b/webrtc-jni/src/main/cpp/include/JNI_RTCEncodedAudioFrameInjector.h index 6063ac53..995ef2b4 100644 --- a/webrtc-jni/src/main/cpp/include/JNI_RTCEncodedAudioFrameInjector.h +++ b/webrtc-jni/src/main/cpp/include/JNI_RTCEncodedAudioFrameInjector.h @@ -22,10 +22,10 @@ extern "C" { #endif JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedAudioFrameInjector_injectDirectBuffer - (JNIEnv *, jobject, jobject, jint, jint, jint, jlong, jint, jboolean, jlong, jboolean); + (JNIEnv *, jobject, jobject, jint, jint, jint, jlong, jint, jboolean, jlong, jboolean, jintArray); JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedAudioFrameInjector_injectByteArray - (JNIEnv *, jobject, jbyteArray, jint, jlong, jint, jboolean, jlong, jboolean); + (JNIEnv *, jobject, jbyteArray, jint, jlong, jint, jboolean, jlong, jboolean, jintArray); JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedAudioFrameInjector_dispose (JNIEnv *, jobject); diff --git a/webrtc-jni/src/main/cpp/include/api/RTCRtpContributingSource.h b/webrtc-jni/src/main/cpp/include/api/RTCRtpContributingSource.h index 07cccd88..66e7578f 100644 --- a/webrtc-jni/src/main/cpp/include/api/RTCRtpContributingSource.h +++ b/webrtc-jni/src/main/cpp/include/api/RTCRtpContributingSource.h @@ -24,6 +24,9 @@ #include +#include +#include + namespace jni { namespace RTCRtpContributingSource @@ -35,15 +38,13 @@ namespace jni jclass cls; jmethodID ctor; - jfieldID timestamp; - jfieldID sourceId; - jfieldID sourceType; - jfieldID audioLevel; - jfieldID rtpTimestamp; }; + // Converts an RTP audio level in -dBov to the linear value between 0 and + // 1 of the Java classes. A source without a level reads as silence. + jdouble toLinearAudioLevel(const std::optional & audioLevel); + JavaLocalRef toJava(JNIEnv * env, const webrtc::RtpSource & source); - webrtc::RtpSource toNative(JNIEnv * env, const JavaRef & source); } } diff --git a/webrtc-jni/src/main/cpp/include/api/RTCRtpSynchronizationSource.h b/webrtc-jni/src/main/cpp/include/api/RTCRtpSynchronizationSource.h index 760d4b47..a7a8fbaa 100644 --- a/webrtc-jni/src/main/cpp/include/api/RTCRtpSynchronizationSource.h +++ b/webrtc-jni/src/main/cpp/include/api/RTCRtpSynchronizationSource.h @@ -35,11 +35,9 @@ namespace jni jclass cls; jmethodID ctor; - jfieldID voiceActivityFlag; }; JavaLocalRef toJava(JNIEnv * env, const webrtc::RtpSource & source); - webrtc::RtpSource toNative(JNIEnv * env, const JavaRef & source); } } diff --git a/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedAudioFrameInjector.cpp b/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedAudioFrameInjector.cpp index 281c4597..c0d3087e 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedAudioFrameInjector.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_RTCEncodedAudioFrameInjector.cpp @@ -27,10 +27,21 @@ #include #include #include +#include + +static std::vector toCsrcs(JNIEnv * env, jintArray jSources) +{ + std::vector sources(static_cast(env->GetArrayLength(jSources))); + + env->GetIntArrayRegion(jSources, 0, static_cast(sources.size()), sources.data()); + + return std::vector(sources.begin(), sources.end()); +} static void injectFrame(webrtc::EncodedAudioFrameInjectorInterface * injector, std::span data, jint payloadType, jlong rtpTimestamp, - jint audioLevel, jboolean hasAudioLevel, jlong captureTimeMs, jboolean hasCaptureTime) + jint audioLevel, jboolean hasAudioLevel, jlong captureTimeMs, jboolean hasCaptureTime, + const std::vector & csrcs) { std::optional level; std::optional captureTime; @@ -47,14 +58,15 @@ static void injectFrame(webrtc::EncodedAudioFrameInjectorInterface * injector, auto frame = webrtc::CreateOutgoingAudioFrame( webrtc::TransformableAudioFrameInterface::FrameType::kAudioFrameSpeech, webrtc::PayloadType(payloadType), static_cast(rtpTimestamp), data.data(), data.size(), - captureTime, 0, {}, "", std::nullopt, level); + captureTime, 0, csrcs, "", std::nullopt, level); injector->InjectFrame(std::move(frame)); } JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedAudioFrameInjector_injectDirectBuffer (JNIEnv * env, jobject caller, jobject jBuffer, jint position, jint length, jint payloadType, - jlong rtpTimestamp, jint audioLevel, jboolean hasAudioLevel, jlong captureTimeMs, jboolean hasCaptureTime) + jlong rtpTimestamp, jint audioLevel, jboolean hasAudioLevel, jlong captureTimeMs, jboolean hasCaptureTime, + jintArray jContributingSources) { jni::CallFromJava(env, [&]() { jni::NativeLease injector(env, caller); @@ -75,9 +87,15 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedAudioFrameInjector_injec return; } + const std::vector csrcs = toCsrcs(env, jContributingSources); + + if (env->ExceptionCheck()) { + 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); + payloadType, rtpTimestamp, audioLevel, hasAudioLevel, captureTimeMs, hasCaptureTime, csrcs); } catch (...) { ThrowCxxJavaException(env); @@ -87,13 +105,20 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedAudioFrameInjector_injec 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) + jint audioLevel, jboolean hasAudioLevel, jlong captureTimeMs, jboolean hasCaptureTime, + jintArray jContributingSources) { jni::CallFromJava(env, [&]() { jni::NativeLease injector(env, caller); CHECK_HANDLE(injector); try { + const std::vector csrcs = toCsrcs(env, jContributingSources); + + if (env->ExceptionCheck()) { + return; + } + auto releaseArray = [env, jData](jbyte * bytes) { env->ReleaseByteArrayElements(jData, bytes, JNI_ABORT); }; @@ -106,7 +131,8 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_RTCEncodedAudioFrameInjector_injec auto data = std::span(reinterpret_cast(bytes.get()), static_cast(env->GetArrayLength(jData))); - injectFrame(injector, data, payloadType, rtpTimestamp, audioLevel, hasAudioLevel, captureTimeMs, hasCaptureTime); + injectFrame(injector, data, payloadType, rtpTimestamp, audioLevel, hasAudioLevel, captureTimeMs, + hasCaptureTime, csrcs); } catch (...) { ThrowCxxJavaException(env); diff --git a/webrtc-jni/src/main/cpp/src/api/RTCRtpContributingSource.cpp b/webrtc-jni/src/main/cpp/src/api/RTCRtpContributingSource.cpp index 47316216..7de312fd 100644 --- a/webrtc-jni/src/main/cpp/src/api/RTCRtpContributingSource.cpp +++ b/webrtc-jni/src/main/cpp/src/api/RTCRtpContributingSource.cpp @@ -15,22 +15,34 @@ */ #include "api/RTCRtpContributingSource.h" -#include "JavaObject.h" #include "JavaRef.h" #include "JavaUtils.h" #include "JNI_WebRTC.h" +#include + namespace jni { namespace RTCRtpContributingSource { + jdouble toLinearAudioLevel(const std::optional & audioLevel) + { + // RFC 6464 reserves 127 for silence, which the formula of the WebRTC + // specification would not reach. + if (!audioLevel.has_value() || *audioLevel >= 127) { + return 0; + } + + return std::pow(10.0, -static_cast(*audioLevel) / 20.0); + } + JavaLocalRef toJava(JNIEnv * env, const webrtc::RtpSource & source) { const auto javaClass = JavaClasses::get(env); jlong timestamp = static_cast(source.timestamp().us()); jlong sourceId = static_cast(source.source_id()); - jdouble audioLevel = static_cast(source.audio_level().value_or(0)); + jdouble audioLevel = toLinearAudioLevel(source.audio_level()); jlong rtpTimestamp = static_cast(source.rtp_timestamp()); jobject object = env->NewObject(javaClass->cls, javaClass->ctor, @@ -39,35 +51,11 @@ namespace jni return JavaLocalRef(env, object); } - webrtc::RtpSource toNative(JNIEnv * env, const JavaRef & source) - { - const auto javaClass = JavaClasses::get(env); - - JavaObject obj(env, source); - - webrtc::RtpSource::Extensions extensions; - extensions.audio_level = static_cast(obj.getDouble(javaClass->audioLevel)); - - return webrtc::RtpSource( - webrtc::Timestamp::Micros(static_cast(obj.getLong(javaClass->timestamp))), - static_cast(obj.getLong(javaClass->sourceId)), - webrtc::RtpSourceType::CSRC, - static_cast(obj.getLong(javaClass->rtpTimestamp)), - extensions - ); - } - JavaRTCRtpContributingSourceClass::JavaRTCRtpContributingSourceClass(JNIEnv * env) { cls = FindClass(env, PKG"RTCRtpContributingSource"); ctor = GetMethod(env, cls, "", "(JJDJ)V"); - - timestamp = GetFieldID(env, cls, "timestamp", "J"); - sourceId = GetFieldID(env, cls, "sourceId", "J"); - sourceType = GetFieldID(env, cls, "sourceType", "J"); - audioLevel = GetFieldID(env, cls, "audioLevel", "D"); - rtpTimestamp = GetFieldID(env, cls, "rtpTimestamp", "J"); } } } diff --git a/webrtc-jni/src/main/cpp/src/api/RTCRtpSynchronizationSource.cpp b/webrtc-jni/src/main/cpp/src/api/RTCRtpSynchronizationSource.cpp index fc9621b7..c483da62 100644 --- a/webrtc-jni/src/main/cpp/src/api/RTCRtpSynchronizationSource.cpp +++ b/webrtc-jni/src/main/cpp/src/api/RTCRtpSynchronizationSource.cpp @@ -16,7 +16,6 @@ #include "api/RTCRtpSynchronizationSource.h" #include "api/RTCRtpContributingSource.h" -#include "JavaObject.h" #include "JavaRef.h" #include "JavaUtils.h" #include "JNI_WebRTC.h" @@ -31,7 +30,7 @@ namespace jni jlong timestamp = static_cast(source.timestamp().us()); jlong sourceId = static_cast(source.source_id()); - jdouble audioLevel = static_cast(source.audio_level().value_or(0)); + jdouble audioLevel = RTCRtpContributingSource::toLinearAudioLevel(source.audio_level()); jlong rtpTimestamp = static_cast(source.rtp_timestamp()); jboolean voiceActivityFlag = false; @@ -41,32 +40,11 @@ namespace jni return JavaLocalRef(env, object); } - webrtc::RtpSource toNative(JNIEnv * env, const JavaRef & source) - { - const auto javaClass = JavaClasses::get(env); - const auto parentClass = JavaClasses::get(env); - - JavaObject obj(env, source); - - webrtc::RtpSource::Extensions extensions; - extensions.audio_level = static_cast(obj.getDouble(parentClass->audioLevel)); - - return webrtc::RtpSource( - webrtc::Timestamp::Micros(static_cast(obj.getLong(parentClass->timestamp))), - static_cast(obj.getLong(parentClass->sourceId)), - webrtc::RtpSourceType::SSRC, - static_cast(obj.getLong(parentClass->rtpTimestamp)), - extensions - ); - } - JavaRTCRtpSynchronizationSourceClass::JavaRTCRtpSynchronizationSourceClass(JNIEnv * env) { cls = FindClass(env, PKG"RTCRtpSynchronizationSource"); ctor = GetMethod(env, cls, "", "(JJDJZ)V"); - - voiceActivityFlag = GetFieldID(env, cls, "voiceActivityFlag", "Z"); } } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCEncodedAudioFrameInjector.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCEncodedAudioFrameInjector.java index 27f4906f..719c17a8 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCEncodedAudioFrameInjector.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCEncodedAudioFrameInjector.java @@ -41,6 +41,8 @@ */ public class RTCEncodedAudioFrameInjector extends DisposableNativeObject { + private static final int[] NO_SOURCES = new int[0]; + /* * The native observer set through this object, owned by it and freed when * disposed. @@ -87,6 +89,19 @@ public void injectFrame(ByteBuffer data, int payloadType, long rtpTimestamp) { */ public void injectFrame(ByteBuffer data, int payloadType, long rtpTimestamp, Integer audioLevel, Long captureTimeMs) { + injectFrame(data, payloadType, rtpTimestamp, audioLevel, captureTimeMs, NO_SOURCES); + } + + /** + * Sends an encoded frame like {@link #injectFrame(ByteBuffer, int, long, + * Integer, Long)}, naming the sources mixed into it. Nothing but a test can + * produce a received CSRC without this. + * + * @param contributingSources The CSRCs of the frame, at most 15, as + * unsigned 32-bit values. + */ + void injectFrame(ByteBuffer data, int payloadType, long rtpTimestamp, Integer audioLevel, + Long captureTimeMs, int[] contributingSources) { Objects.requireNonNull(data, "data"); if (payloadType < 0 || payloadType > 127) { @@ -104,11 +119,11 @@ public void injectFrame(ByteBuffer data, int payloadType, long rtpTimestamp, Int if (data.isDirect()) { injectDirectBuffer(data, data.position(), data.remaining(), payloadType, rtpTimestamp, - level, audioLevel != null, captureTime, captureTimeMs != null); + level, audioLevel != null, captureTime, captureTimeMs != null, contributingSources); } else { injectByteArray(RTCDataChannel.copyWindow(data), payloadType, rtpTimestamp, - level, audioLevel != null, captureTime, captureTimeMs != null); + level, audioLevel != null, captureTime, captureTimeMs != null, contributingSources); } } @@ -121,9 +136,11 @@ public void injectFrame(ByteBuffer data, int payloadType, long rtpTimestamp, Int public native void dispose(); private native void injectDirectBuffer(ByteBuffer data, int position, int length, int payloadType, - long rtpTimestamp, int audioLevel, boolean hasAudioLevel, long captureTimeMs, boolean hasCaptureTime); + long rtpTimestamp, int audioLevel, boolean hasAudioLevel, long captureTimeMs, boolean hasCaptureTime, + int[] contributingSources); private native void injectByteArray(byte[] data, int payloadType, long rtpTimestamp, - int audioLevel, boolean hasAudioLevel, long captureTimeMs, boolean hasCaptureTime); + int audioLevel, boolean hasAudioLevel, long captureTimeMs, boolean hasCaptureTime, + int[] contributingSources); } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/RTCEncodedFrameInjectorTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/RTCEncodedFrameInjectorTests.java index 6a48790f..24030734 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/RTCEncodedFrameInjectorTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/RTCEncodedFrameInjectorTests.java @@ -33,6 +33,7 @@ import java.util.concurrent.atomic.AtomicReference; import dev.onvoid.webrtc.media.MediaType; +import dev.onvoid.webrtc.media.audio.HeadlessAudioDeviceModule; import dev.onvoid.webrtc.media.video.VideoTrack; import dev.onvoid.webrtc.media.video.VideoTrackSink; @@ -49,6 +50,9 @@ class RTCEncodedFrameInjectorTests extends TestBase { private static final long TIMEOUT_SECONDS = 10; + // Above the signed range, as CSRCs are unsigned. + private static final int CSRC = 0xCAFE0001; + @Test void injectedVideoIsDecoded() throws Exception { @@ -132,15 +136,7 @@ void injectedAudioIsReceived() throws Exception { negotiate(caller, callee); - int payloadType = -1; - - for (RTCRtpCodecParameters codec : sender.getParameters().codecs) { - if ("opus".equalsIgnoreCase(codec.codecName)) { - payloadType = codec.payloadType; - } - } - - assertTrue(payloadType >= 0, "opus was not negotiated"); + int payloadType = getOpusPayloadType(sender); RTCRtpReceiver receiver = getReceiver(callee); receiver.setTransform(frame -> { @@ -183,6 +179,55 @@ void injectedAudioIsReceived() throws Exception { } } + @Test + void injectedAudioReportsSources() throws Exception { + List frames = captureAudioFrames(50); + + // A receiver learns its audio sources as playout pulls the audio, which + // the dummy module of the other tests does not do. + HeadlessAudioDeviceModule audioModule = new HeadlessAudioDeviceModule(); + PeerConnectionFactory headlessFactory = new PeerConnectionFactory(audioModule); + + audioModule.initPlayout(); + audioModule.startPlayout(); + + try { + TestPeerConnection caller = new TestPeerConnection(factory); + TestPeerConnection callee = new TestPeerConnection(headlessFactory); + + try { + RTCRtpTransceiver transceiver = addSendOnlyTransceiver(caller, MediaType.AUDIO, "opus"); + RTCRtpSender sender = transceiver.getSender(); + RTCEncodedAudioFrameInjector injector = sender.createEncodedAudioFrameInjector(null); + + negotiate(caller, callee); + + int payloadType = getOpusPayloadType(sender); + RTCRtpReceiver receiver = getReceiver(callee); + + // The levels the WebRTC specification converts to 10^(-level / 20), + // with 127 standing for silence. + long rtpTimestamp = injectUntilLevel(injector, payloadType, receiver, frames, 0, 0, 1.0); + rtpTimestamp = injectUntilLevel(injector, payloadType, receiver, frames, rtpTimestamp, 20, 0.1); + injectUntilLevel(injector, payloadType, receiver, frames, rtpTimestamp, 127, 0.0); + + receiver.dispose(); + injector.dispose(); + sender.dispose(); + transceiver.dispose(); + } + finally { + caller.close(); + callee.close(); + } + } + finally { + audioModule.stopPlayout(); + headlessFactory.dispose(); + audioModule.dispose(); + } + } + @Test void injectorNeedsTracklessSender() throws Exception { try (TestMediaCall call = new TestMediaCall(factory, true, false)) { @@ -293,6 +338,67 @@ private RTCRtpTransceiver addSendOnlyTransceiver(TestPeerConnection peer, MediaT return transceiver; } + private static int getOpusPayloadType(RTCRtpSender sender) { + for (RTCRtpCodecParameters codec : sender.getParameters().codecs) { + if ("opus".equalsIgnoreCase(codec.codecName)) { + return codec.payloadType; + } + } + + throw new AssertionError("opus was not negotiated"); + } + + /** + * Injects frames of the given RTP audio level and a contributing source, + * until the receiver reports the expected linear level for both the + * contributing and the synchronization source. + * + * @return The RTP timestamp to go on with. + */ + private static long injectUntilLevel(RTCEncodedAudioFrameInjector injector, int payloadType, + RTCRtpReceiver receiver, List frames, long rtpTimestamp, int rtpLevel, + double expected) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS); + List contributing = List.of(); + List synchronization = List.of(); + + while (System.nanoTime() < deadline) { + for (CapturedFrame frame : frames) { + injector.injectFrame(ByteBuffer.wrap(frame.data), payloadType, rtpTimestamp, rtpLevel, null, + new int[] { CSRC }); + // Opus frames of 20 ms on its 48 kHz clock. + rtpTimestamp += 960; + Thread.sleep(20); + + contributing = receiver.getContributingSources(); + synchronization = receiver.getSynchronizationSources(); + + if (hasLevel(contributing, expected) && hasLevel(synchronization, expected)) { + assertEquals(1, contributing.size()); + assertEquals(Integer.toUnsignedLong(CSRC), contributing.get(0).sourceId); + return rtpTimestamp; + } + } + } + + throw new AssertionError("RTP level " + rtpLevel + " was not reported as " + expected + + ": CSRC " + levels(contributing) + ", SSRC " + levels(synchronization)); + } + + private static boolean hasLevel(List sources, double expected) { + return !sources.isEmpty() && Math.abs(sources.get(0).audioLevel - expected) < 1e-9; + } + + private static List levels(List sources) { + List levels = new ArrayList<>(); + + for (RTCRtpContributingSource source : sources) { + levels.add(source.audioLevel); + } + + return levels; + } + private static void negotiate(TestPeerConnection caller, TestPeerConnection callee) throws Exception { caller.setRemotePeerConnection(callee); callee.setRemotePeerConnection(caller); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/RTCRtpReceiverSourceTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/RTCRtpReceiverSourceTests.java index 1d215aff..159719f8 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/RTCRtpReceiverSourceTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/RTCRtpReceiverSourceTests.java @@ -77,6 +77,9 @@ public void onSourceChanged(boolean ssrc, boolean csrc) { assertTrue(changed.await(TIMEOUT_SECONDS, TimeUnit.SECONDS), "no source change reported"); assertTrue(ssrcChanged.get(), "the first packet did not change the SSRC"); + // Video has no audio level, which must not read as full volume. + assertEquals(0.0, receiver.getSynchronizationSources().get(0).audioLevel); + receiver.setObserver(null); receiver.dispose(); }