diff --git a/docs/guide/audio/custom-audio-source.md b/docs/guide/audio/custom-audio-source.md index 919f23fee..787542486 100644 --- a/docs/guide/audio/custom-audio-source.md +++ b/docs/guide/audio/custom-audio-source.md @@ -206,6 +206,17 @@ audioTrack.removeSink(monitorSink); As with video tracks, sinks may be added and removed from any thread, and also from within `onData`, the sink's own included. Only `dispose()` must not be called from within a callback. +Each call hands a sink a new array, which it may keep, for example in a queue for another thread. A sink that reads the audio only while it is called can take the same array in every call instead, so that no array is allocated for it a hundred times a second: + +```java +import dev.onvoid.webrtc.media.audio.AudioDataAccess; + +// The array holds the audio only until onData returns; copy what you keep. +audioTrack.addSink(monitorSink, AudioDataAccess.REUSED); +``` + +The array is replaced when the size of the chunks changes, so its length is always that of the audio. + ## Cleanup When you're done with the custom audio source, make sure to clean up resources: diff --git a/webrtc-jni/src/main/cpp/include/JNI_AudioTrack.h b/webrtc-jni/src/main/cpp/include/JNI_AudioTrack.h index 616ed1461..f53ab76e1 100644 --- a/webrtc-jni/src/main/cpp/include/JNI_AudioTrack.h +++ b/webrtc-jni/src/main/cpp/include/JNI_AudioTrack.h @@ -26,10 +26,10 @@ extern "C" { /* * Class: dev_onvoid_webrtc_media_audio_AudioTrack * Method: addSinkInternal - * Signature: (Ldev/onvoid/webrtc/media/audio/AudioTrackSink;Z)J + * Signature: (Ldev/onvoid/webrtc/media/audio/AudioTrackSink;ZZ)J */ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_addSinkInternal - (JNIEnv *, jobject, jobject, jboolean); + (JNIEnv *, jobject, jobject, jboolean, jboolean); /* * Class: dev_onvoid_webrtc_media_audio_AudioTrack diff --git a/webrtc-jni/src/main/cpp/include/api/AudioTrackSink.h b/webrtc-jni/src/main/cpp/include/api/AudioTrackSink.h index 1a27aa1e6..471eda50a 100644 --- a/webrtc-jni/src/main/cpp/include/api/AudioTrackSink.h +++ b/webrtc-jni/src/main/cpp/include/api/AudioTrackSink.h @@ -24,6 +24,7 @@ #include "api/rtp_packet_infos.h" #include +#include #include #include @@ -33,8 +34,9 @@ namespace jni { public: // With packetInfos, the Java sink is called with the RTP packets - // the audio was assembled from. - AudioTrackSink(JNIEnv * env, const JavaGlobalRef & sink, bool packetInfos); + // the audio was assembled from. With reuseData, it gets the same + // array in every call instead of a new one. + AudioTrackSink(JNIEnv * env, const JavaGlobalRef & sink, bool packetInfos, bool reuseData); ~AudioTrackSink() = default; // AudioTrackSinkInterface implementation. WebRTC calls the variant @@ -63,6 +65,16 @@ namespace jni const bool packetInfos; + const bool reuseData; + + // The array handed to the Java sink in every call when reuseData + // is set. Only the call that has set reusedInUse touches it. + JavaGlobalRef reusedArray; + + jsize reusedSize; + + std::atomic reusedInUse; + const std::shared_ptr javaClass; }; } diff --git a/webrtc-jni/src/main/cpp/src/JNI_AudioTrack.cpp b/webrtc-jni/src/main/cpp/src/JNI_AudioTrack.cpp index ac18b51b5..23a78b32b 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_AudioTrack.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_AudioTrack.cpp @@ -23,7 +23,7 @@ #include "api/media_stream_interface.h" JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_addSinkInternal -(JNIEnv * env, jobject caller, jobject jsink, jboolean packetInfos) +(JNIEnv * env, jobject caller, jobject jsink, jboolean packetInfos, jboolean reuseData) { try { if (jsink == nullptr) { @@ -34,7 +34,7 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_addSinkInt webrtc::AudioTrackInterface * track = GetHandle(env, caller); CHECK_HANDLEV(track, 0); - auto sink = new jni::AudioTrackSink(env, jni::JavaGlobalRef(env, jsink), packetInfos); + auto sink = new jni::AudioTrackSink(env, jni::JavaGlobalRef(env, jsink), packetInfos, reuseData); track->AddSink(sink); diff --git a/webrtc-jni/src/main/cpp/src/api/AudioTrackSink.cpp b/webrtc-jni/src/main/cpp/src/api/AudioTrackSink.cpp index d8c57c5d4..39bdf691f 100644 --- a/webrtc-jni/src/main/cpp/src/api/AudioTrackSink.cpp +++ b/webrtc-jni/src/main/cpp/src/api/AudioTrackSink.cpp @@ -23,9 +23,14 @@ namespace jni { - AudioTrackSink::AudioTrackSink(JNIEnv * env, const JavaGlobalRef & sink, bool packetInfos) : + AudioTrackSink::AudioTrackSink(JNIEnv * env, const JavaGlobalRef & sink, bool packetInfos, + bool reuseData) : sink(sink), packetInfos(packetInfos), + reuseData(reuseData), + reusedArray(nullptr), + reusedSize(0), + reusedInUse(false), javaClass(JavaClasses::get(env)) { } @@ -59,10 +64,30 @@ namespace jni const jbyte * buffer = static_cast(data); jsize dataSize = static_cast(frames * channels * (bitsPerSample / 8)); - JavaLocalRef dataArray(env, env->NewByteArray(dataSize)); + // The reused array belongs to one call at a time. A call that finds it + // in use, should a source deliver on two threads at once, falls back + // to an array of its own. + const bool reusing = reuseData && !reusedInUse.exchange(true, std::memory_order_acquire); - if (dataArray.get() != nullptr) { - env->SetByteArrayRegion(dataArray.get(), 0, dataSize, buffer); + JavaLocalRef ownArray(env, reusing ? nullptr : env->NewByteArray(dataSize)); + jbyteArray dataArray = ownArray.get(); + + if (reusing) { + if (reusedArray.get() == nullptr || reusedSize != dataSize) { + // Its length is that of the audio, as with a new array per call. + JavaLocalRef array(env, env->NewByteArray(dataSize)); + + reusedArray = (array.get() != nullptr) + ? JavaGlobalRef(env, array.get()) + : JavaGlobalRef(nullptr); + reusedSize = dataSize; + } + + dataArray = reusedArray.get(); + } + + if (dataArray != nullptr) { + env->SetByteArrayRegion(dataArray, 0, dataSize, buffer); if (packetInfos) { try { @@ -70,7 +95,7 @@ namespace jni ? RTCRtpPacketInfo::toJavaArray(env, *infos) : RTCRtpPacketInfo::toJavaArray(env, webrtc::RtpPacketInfos()); - env->CallVoidMethod(sink, javaClass->onDataWithPacketInfos, dataArray.get(), + env->CallVoidMethod(sink, javaClass->onDataWithPacketInfos, dataArray, static_cast(bitsPerSample), static_cast(sampleRate), static_cast(channels), static_cast(frames), infoArray.get()); } @@ -79,11 +104,15 @@ namespace jni } } else { - env->CallVoidMethod(sink, javaClass->onData, dataArray.get(), static_cast(bitsPerSample), + env->CallVoidMethod(sink, javaClass->onData, dataArray, static_cast(bitsPerSample), static_cast(sampleRate), static_cast(channels), static_cast(frames)); } } + if (reusing) { + reusedInUse.store(false, std::memory_order_release); + } + ReportPendingException(env); } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/AudioDispatcher.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/AudioDispatcher.java index 98e27e7c6..1df942d40 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/AudioDispatcher.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/AudioDispatcher.java @@ -43,6 +43,7 @@ public void onData(byte[] data, int bitsPerSample, int sampleRate, int channels, return; } + // The track reuses the array for the next chunk. offer(new AudioChunk(data.clone(), sampleRate, channels, frames)); } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteAudioImpl.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteAudioImpl.java index 28da80c29..0d4f95a80 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteAudioImpl.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/RemoteAudioImpl.java @@ -25,6 +25,7 @@ import dev.onvoid.webrtc.RTCRtpReceiver; import dev.onvoid.webrtc.internal.Timeouts; +import dev.onvoid.webrtc.media.audio.AudioDataAccess; import dev.onvoid.webrtc.media.audio.AudioTrack; /** @@ -68,7 +69,8 @@ public Subscription onAudio(Duration buffer, Consumer handler) { onControl(() -> { dispatchers.add(dispatcher); - track.addSink(dispatcher); + // The dispatcher copies each chunk, so it needs no new array per call. + track.addSink(dispatcher, AudioDataAccess.REUSED); }); return () -> { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioDataAccess.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioDataAccess.java new file mode 100644 index 000000000..68137dab0 --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioDataAccess.java @@ -0,0 +1,44 @@ +/* + * 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; + +/** + * How the audio of a track reaches an {@link AudioTrackSink}, chosen when the + * sink is added with {@link AudioTrack#addSink(AudioTrackSink, + * AudioDataAccess)}. + */ +public enum AudioDataAccess { + + /** + * Each call hands the sink a new array, which the sink may keep, for + * example in a queue for another thread. This costs an array per chunk + * and sink, a hundred a second. + */ + COPY, + + /** + * The sink gets the same array in every call, filled with the new audio + * each time, so that no array is allocated for it per chunk. The array + * holds the audio only until the call returns: a sink that keeps the + * audio beyond that copies it. A new array takes the place of the old one + * when the size of the chunks changes, so its length is always that of + * the audio. Should a source hand the sink audio on two threads at once, + * the call that finds the array in use gets one of its own. + */ + REUSED + +} diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java index bf3a629e0..4ac04eb0a 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java @@ -68,22 +68,43 @@ public void dispose() { } /** - * Adds an AudioSink to the track. A track can have any number of AudioSinks. - * Called from within the callback of a sink, it returns before the sink is - * registered, and the sink gets the audio that follows once it is. + * Adds an AudioSink to the track, which gets a new array in each call, as + * with {@link AudioDataAccess#COPY}. A track can have any number of + * AudioSinks. * * @param sink The audio sink that will receive audio data from the track. * Adding it again does nothing. * * @throws IllegalStateException if the track has been disposed. + * + * @see #addSink(AudioTrackSink, AudioDataAccess) */ public void addSink(AudioTrackSink sink) { - if (isNull(sink)) { + addSink(sink, AudioDataAccess.COPY); + } + + /** + * Adds an AudioSink to the track. A track can have any number of + * AudioSinks. Called from within the callback of a sink, it returns + * before the sink is registered, and the sink gets the audio that follows + * once it is. + * + * @param sink The audio sink that will receive audio data from the + * track. Adding it again does nothing, whatever the access. + * @param access Whether the sink gets a new array in each call, which it + * may keep, or the same one, valid until the call returns. + * + * @throws IllegalStateException if the track has been disposed. + */ + public void addSink(AudioTrackSink sink, AudioDataAccess access) { + if (isNull(sink) || isNull(access)) { throw new NullPointerException(); } + boolean reused = access == AudioDataAccess.REUSED; + sinks.add(sink, (s, registration) -> addSinkInternal(new SinkDelivery(s, registration), - takesPacketInfos(s))); + takesPacketInfos(s), reused)); } /** @@ -183,7 +204,7 @@ public void setVolume(double volume) { private native void setVolumeInternal(double volume); - private native long addSinkInternal(AudioTrackSink sink, boolean packetInfos); + private native long addSinkInternal(AudioTrackSink sink, boolean packetInfos, boolean reuseData); private native void removeSinkInternal(long sinkHandle); diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioDataAccessTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioDataAccessTests.java new file mode 100644 index 000000000..b027202ae --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioDataAccessTests.java @@ -0,0 +1,222 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.media.audio; + +import static org.junit.jupiter.api.Assertions.*; + +import dev.onvoid.webrtc.RTCRtpPacketInfo; +import dev.onvoid.webrtc.TestBase; +import dev.onvoid.webrtc.internal.SinkRegistry; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * A custom source hands its audio to the sinks of its track before {@code + * pushAudio} returns, on the pushing thread, so each test sees every call of + * its sink by the time the push is done. + */ +class AudioDataAccessTests extends TestBase { + + private CustomAudioSource source; + + private AudioTrack track; + + + @BeforeEach + void init() { + source = new CustomAudioSource(); + track = factory.createAudioTrack("audioTrack", source); + } + + @AfterEach + void dispose() { + track.dispose(); + source.dispose(); + } + + @Test + void copiedArraysAreKept() { + List arrays = new ArrayList<>(); + + track.addSink((data, bits, rate, channels, frames) -> arrays.add(data)); + + push(1, 480); + push(2, 480); + + assertEquals(2, arrays.size()); + assertNotSame(arrays.get(0), arrays.get(1)); + assertFilled(arrays.get(0), 1, 480); + assertFilled(arrays.get(1), 2, 480); + } + + @Test + void reusedArrayIsTheSame() { + List arrays = new ArrayList<>(); + List contents = new ArrayList<>(); + + track.addSink((data, bits, rate, channels, frames) -> { + arrays.add(data); + contents.add(data.clone()); + }, AudioDataAccess.REUSED); + + push(1, 480); + push(2, 480); + + assertEquals(2, arrays.size()); + assertSame(arrays.get(0), arrays.get(1)); + assertFilled(contents.get(0), 1, 480); + assertFilled(contents.get(1), 2, 480); + } + + @Test + void reusedArrayFollowsChunkSize() { + List arrays = new ArrayList<>(); + + track.addSink((data, bits, rate, channels, frames) -> arrays.add(data), AudioDataAccess.REUSED); + + push(1, 480); + push(2, 160); + push(3, 160); + + assertEquals(480 * 4, arrays.get(0).length); + assertEquals(160 * 4, arrays.get(1).length); + assertSame(arrays.get(1), arrays.get(2)); + assertFilled(arrays.get(2), 3, 160); + } + + @Test + void sinksReuseArraysOfTheirOwn() { + List first = new ArrayList<>(); + List second = new ArrayList<>(); + + track.addSink((data, bits, rate, channels, frames) -> first.add(data), AudioDataAccess.REUSED); + track.addSink((data, bits, rate, channels, frames) -> second.add(data), AudioDataAccess.REUSED); + + push(1, 480); + + assertNotSame(first.get(0), second.get(0)); + } + + @Test + void reusedSinkGetsPacketInfos() { + List arrays = new ArrayList<>(); + List infos = new ArrayList<>(); + + track.addSink(new AudioTrackSink() { + + @Override + public void onData(byte[] data, int bitsPerSample, int sampleRate, int channels, int frames) { + fail("Called without packets"); + } + + @Override + public void onData(byte[] data, int bitsPerSample, int sampleRate, int channels, int frames, + RTCRtpPacketInfo[] packetInfos) { + arrays.add(data); + infos.add(packetInfos); + } + }, AudioDataAccess.REUSED); + + push(1, 480); + push(2, 480); + + assertSame(arrays.get(0), arrays.get(1)); + // A local track has no packets. + assertEquals(0, infos.get(0).length); + } + + @Test + void reusedSinkSwapsInCallback() throws Exception { + List calls = new ArrayList<>(); + + AudioTrackSink second = (data, bits, rate, channels, frames) -> calls.add("second"); + + track.addSink(new AudioTrackSink() { + + @Override + public void onData(byte[] data, int bitsPerSample, int sampleRate, int channels, int frames) { + calls.add("first"); + + // The source holds the lock that adding and removing take while + // it is here. + track.removeSink(this); + track.addSink(second, AudioDataAccess.REUSED); + } + }, AudioDataAccess.REUSED); + + assertTimeoutPreemptively(Duration.ofSeconds(5), () -> { + push(1, 480); + + // The native calls made from within the callback come after it. + SinkRegistry.awaitDeferred(); + + push(2, 480); + }); + + assertEquals(Arrays.asList("first", "second"), calls); + } + + @Test + void addAgainKeepsAccess() { + List arrays = new ArrayList<>(); + AudioTrackSink sink = (data, bits, rate, channels, frames) -> arrays.add(data); + + track.addSink(sink, AudioDataAccess.REUSED); + track.addSink(sink, AudioDataAccess.COPY); + + push(1, 480); + push(2, 480); + + assertEquals(2, arrays.size()); + assertSame(arrays.get(0), arrays.get(1)); + } + + @Test + void addNullAccess() { + AudioTrackSink sink = (data, bits, rate, channels, frames) -> { }; + + assertThrows(NullPointerException.class, () -> track.addSink(sink, null)); + assertThrows(NullPointerException.class, () -> track.addSink(null, AudioDataAccess.REUSED)); + } + + /** + * Pushes 16-bit stereo audio at 48 kHz whose every byte is {@code value}. + */ + private void push(int value, int frames) { + byte[] data = new byte[frames * 2 * 2]; + + Arrays.fill(data, (byte) value); + + source.pushAudio(data, 16, 48000, 2, frames); + } + + private static void assertFilled(byte[] data, int value, int frames) { + byte[] expected = new byte[frames * 2 * 2]; + + Arrays.fill(expected, (byte) value); + + assertArrayEquals(expected, data); + } + +}