Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/guide/audio/custom-audio-source.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions webrtc-jni/src/main/cpp/include/JNI_AudioTrack.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 14 additions & 2 deletions webrtc-jni/src/main/cpp/include/api/AudioTrackSink.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include "api/rtp_packet_infos.h"

#include <jni.h>
#include <atomic>
#include <memory>
#include <optional>

Expand All @@ -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<jobject> & 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<jobject> & sink, bool packetInfos, bool reuseData);
~AudioTrackSink() = default;

// AudioTrackSinkInterface implementation. WebRTC calls the variant
Expand Down Expand Up @@ -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<jbyteArray> reusedArray;

jsize reusedSize;

std::atomic<bool> reusedInUse;

const std::shared_ptr<JavaAudioTrackSinkClass> javaClass;
};
}
Expand Down
4 changes: 2 additions & 2 deletions webrtc-jni/src/main/cpp/src/JNI_AudioTrack.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -34,7 +34,7 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_media_audio_AudioTrack_addSinkInt
webrtc::AudioTrackInterface * track = GetHandle<webrtc::AudioTrackInterface>(env, caller);
CHECK_HANDLEV(track, 0);

auto sink = new jni::AudioTrackSink(env, jni::JavaGlobalRef<jobject>(env, jsink), packetInfos);
auto sink = new jni::AudioTrackSink(env, jni::JavaGlobalRef<jobject>(env, jsink), packetInfos, reuseData);

track->AddSink(sink);

Expand Down
41 changes: 35 additions & 6 deletions webrtc-jni/src/main/cpp/src/api/AudioTrackSink.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,14 @@

namespace jni
{
AudioTrackSink::AudioTrackSink(JNIEnv * env, const JavaGlobalRef<jobject> & sink, bool packetInfos) :
AudioTrackSink::AudioTrackSink(JNIEnv * env, const JavaGlobalRef<jobject> & sink, bool packetInfos,
bool reuseData) :
sink(sink),
packetInfos(packetInfos),
reuseData(reuseData),
reusedArray(nullptr),
reusedSize(0),
reusedInUse(false),
javaClass(JavaClasses::get<JavaAudioTrackSinkClass>(env))
{
}
Expand Down Expand Up @@ -59,18 +64,38 @@ namespace jni
const jbyte * buffer = static_cast<const jbyte *>(data);
jsize dataSize = static_cast<jsize>(frames * channels * (bitsPerSample / 8));

JavaLocalRef<jbyteArray> 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<jbyteArray> 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<jbyteArray> array(env, env->NewByteArray(dataSize));

reusedArray = (array.get() != nullptr)
? JavaGlobalRef<jbyteArray>(env, array.get())
: JavaGlobalRef<jbyteArray>(nullptr);
reusedSize = dataSize;
}

dataArray = reusedArray.get();
}

if (dataArray != nullptr) {
env->SetByteArrayRegion(dataArray, 0, dataSize, buffer);

if (packetInfos) {
try {
JavaLocalRef<jobjectArray> infoArray = (infos != nullptr)
? RTCRtpPacketInfo::toJavaArray(env, *infos)
: RTCRtpPacketInfo::toJavaArray(env, webrtc::RtpPacketInfos());

env->CallVoidMethod(sink, javaClass->onDataWithPacketInfos, dataArray.get(),
env->CallVoidMethod(sink, javaClass->onDataWithPacketInfos, dataArray,
static_cast<jint>(bitsPerSample), static_cast<jint>(sampleRate),
static_cast<jint>(channels), static_cast<jint>(frames), infoArray.get());
}
Expand All @@ -79,11 +104,15 @@ namespace jni
}
}
else {
env->CallVoidMethod(sink, javaClass->onData, dataArray.get(), static_cast<jint>(bitsPerSample),
env->CallVoidMethod(sink, javaClass->onData, dataArray, static_cast<jint>(bitsPerSample),
static_cast<jint>(sampleRate), static_cast<jint>(channels), static_cast<jint>(frames));
}
}

if (reusing) {
reusedInUse.store(false, std::memory_order_release);
}

ReportPendingException(env);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -68,7 +69,8 @@ public Subscription onAudio(Duration buffer, Consumer<AudioChunk> 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 () -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -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

}
33 changes: 27 additions & 6 deletions webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioTrack.java
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

/**
Expand Down Expand Up @@ -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);

Expand Down
Loading
Loading