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
13 changes: 8 additions & 5 deletions docs/guide/audio/custom-audio-source.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ The key feature of `CustomAudioSource` is the ability to push audio data directl
// Parameters for the audio data
int bitsPerSample = 16; // Must be 16; WebRTC reads the samples as 16-bit PCM
int sampleRate = 48000; // Common values: 8000, 16000, 44100, 48000
int channels = 2; // 1 for mono, 2 for stereo
int frameCount = 480; // For 10ms of audio at 48kHz
int channels = 2; // 1, 2, 4, 6 or 8
int frameCount = 480; // Always 10ms of audio: sampleRate / 100

// Create a buffer for the audio data
// Size = frameCount * channels * (bitsPerSample / 8)
Expand All @@ -81,11 +81,13 @@ byte[] audioData = new byte[frameCount * channels * bytesPerSample];
audioSource.pushAudio(audioData, bitsPerSample, sampleRate, channels, frameCount);
```

The call checks its arguments and throws `IllegalArgumentException` rather than letting a bad chunk reach WebRTC, where it would read past your array or abort the process:
The call checks its arguments and throws `IllegalArgumentException` rather than letting a bad chunk reach WebRTC, where it would read past your array, abort the process, or be dropped by the encoder while the push appears to succeed:

- Samples must be **16-bit** signed PCM in the platform byte order, with the channels interleaved.
- The array must hold at least `frameCount * channels * 2` bytes. A longer array is fine; only that many bytes are read.
- One call carries one chunk, and **10 ms** is the size WebRTC works with. A chunk may hold at most `CustomAudioSource.MAX_SAMPLES_PER_PUSH` samples counting every channel, so push in small chunks rather than handing over a whole file or a growing buffer.
- One call carries one chunk of exactly **10 ms**, so `frameCount` must be `sampleRate / 100`. Split audio of any other length, such as 20 ms buffers, into 10 ms chunks first, or let the [client API](/guide/client-api) do it.
- The sample rate must lie between 8000 and 192000 Hz, and the channel count must be 1, 2, 4, 6 or 8.
- A chunk may hold at most `CustomAudioSource.MAX_SAMPLES_PER_PUSH` samples counting every channel, which rules out the highest rates with many channels: 96 kHz with 8 channels or 192 kHz with 4 is the limit.
- `frameCount` counts frames, not samples and not bytes. A frame holds one sample per channel, so 10 ms at 48 kHz is 480 frames whether it is mono or stereo.

::: warning Push from one thread
Expand Down Expand Up @@ -122,9 +124,10 @@ When pushing audio data, you need to consider the following parameters:
### Channels
- **1 (Mono)**: Single channel audio
- **2 (Stereo)**: Dual channel audio
- **4, 6 or 8**: Multichannel audio, mixed down to what the encoder sends. No other counts are accepted.

### Frame Count
The number of frames depends on the desired buffer size and sample rate. For a 10ms buffer:
A chunk is always 10 ms long, so the number of frames follows from the sample rate:
- At 8000 Hz: 80 frames
- At 16000 Hz: 160 frames
- At 44100 Hz: 441 frames
Expand Down
4 changes: 2 additions & 2 deletions docs/guide/audio/headless-audio.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ CustomAudioSource source = new CustomAudioSource();
AudioTrack senderTrack = factory.createAudioTrack("audio0", source);
RTCRtpSender sender = peerConnection.addTrack(senderTrack, Collections.singletonList("stream0"));

// Push PCM frames into the CustomAudioSource (10 ms chunks work well)
// Push PCM frames into the CustomAudioSource, 10 ms per call
byte[] pcm = new byte[480 /* frames */ * 2 /* ch */ * 2 /* bytes */];
source.pushAudio(pcm, 16, 48000, 2, 480);

Expand All @@ -118,7 +118,7 @@ factory.dispose();
```

::: info
- Push one chunk of 16-bit PCM per call, with 10 ms being the size WebRTC works with. See [Custom Audio Source](/guide/audio/custom-audio-source) for the format rules.
- Push one chunk of 10 ms of 16-bit PCM per call. See [Custom Audio Source](/guide/audio/custom-audio-source) for the format rules.
- Push from a single thread. The audio reaches the sender on the thread that calls `pushAudio`.
- The module exposes one virtual recording device; selection calls succeed with index 0.
- Stereo can be enabled/disabled via the standard ADM methods; by default 1 channel is used.
Expand Down
23 changes: 14 additions & 9 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/PcmFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,26 @@ private PcmFormat(int sampleRate, int channels) {
}

/**
* @param sampleRate the sample rate in Hz, a multiple of 100 so that 10 ms
* hold a whole number of samples.
* @param channels the channel count, 1 to 8. 10 ms of all channels
* together may hold at most {@value
* @param sampleRate the sample rate in Hz, from {@value
* CustomAudioSource#MIN_SAMPLE_RATE} to {@value
* CustomAudioSource#MAX_SAMPLE_RATE}, a multiple of 100
* so that 10 ms hold a whole number of samples.
* @param channels the channel count: 1, 2, 4, 6 or 8. 10 ms of all
* channels together may hold at most {@value
* CustomAudioSource#MAX_SAMPLES_PER_PUSH} samples, as
* 48 kHz with 8 channels or 384 kHz with 2 do.
* 96 kHz with 8 channels or 192 kHz with 4 do.
*
* @return the format.
*/
public static PcmFormat of(int sampleRate, int channels) {
if (sampleRate < 8000 || sampleRate > 384000 || sampleRate % 100 != 0) {
throw new IllegalArgumentException("The sample rate must be a multiple of 100 between 8000 and 384000 Hz, got " + sampleRate);
if (sampleRate < CustomAudioSource.MIN_SAMPLE_RATE || sampleRate > CustomAudioSource.MAX_SAMPLE_RATE
|| sampleRate % 100 != 0) {
throw new IllegalArgumentException("The sample rate must be a multiple of 100 between "
+ CustomAudioSource.MIN_SAMPLE_RATE + " and " + CustomAudioSource.MAX_SAMPLE_RATE + " Hz, got "
+ sampleRate);
}
if (channels < 1 || channels > 8) {
throw new IllegalArgumentException("The channel count must be between 1 and 8, got " + channels);
if (channels != 1 && (channels < 1 || channels > CustomAudioSource.MAX_CHANNELS || channels % 2 != 0)) {
throw new IllegalArgumentException("The channel count must be 1, 2, 4, 6 or 8, got " + channels);
}

// WebRTC takes audio in 10 ms chunks of a bounded size. A larger chunk
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,24 @@ public class CustomAudioSource extends AudioTrackSource {
public static final int MAX_SAMPLES_PER_PUSH = 7680;

/**
* The most channels one pushed chunk may hold. Mirrors
* {@code kMaxNumberOfAudioChannels} in the native library.
* The lowest sample rate a chunk may have. WebRTC resamples what it sends
* to the rate of the encoder, and aborts the process when the rate is too
* far below that.
*/
public static final int MAX_CHANNELS = 24;
public static final int MIN_SAMPLE_RATE = 8000;

/**
* The highest sample rate a chunk may have. Mirrors
* {@code kMaxInputSampleRateHz} of the audio coding module in the native
* library.
*/
public static final int MAX_SAMPLE_RATE = 192000;

/**
* The most channels one pushed chunk may hold. The audio coding module in
* the native library takes 1, 2, 4, 6 or 8 channels.
*/
public static final int MAX_CHANNELS = 8;


/**
Expand Down Expand Up @@ -73,8 +87,9 @@ public CustomAudioSource(SyncClock clock) {
* from one thread at a time.
* <p>
* The samples must be 16-bit signed PCM in the platform byte order, with
* the channels interleaved. A call carries one chunk of audio, for which
* 10 ms is the size WebRTC works with; at most
* the channels interleaved. A call carries one chunk of exactly 10 ms,
* {@code sampleRate / 100} frames, of 1, 2, 4, 6 or 8 channels: a sender
* drops anything else without a trace, so it is rejected here. At most
* {@value #MAX_SAMPLES_PER_PUSH} samples, counting every channel, fit in
* one chunk.
* <p>
Expand All @@ -86,18 +101,21 @@ public CustomAudioSource(SyncClock clock) {
* @param audioData The raw audio data bytes to process. Must hold at
* least {@code frameCount * channels * 2} bytes.
* @param bits_per_sample The number of bits per sample, which must be 16.
* @param sampleRate The sample rate of the audio in Hz (e.g., 44100, 48000).
* @param channels The number of audio channels (1 for mono, 2 for stereo).
* @param frameCount The number of frames in the provided audio data. A
* frame holds one sample for each channel, so 10 ms
* at 48 kHz is 480 frames whatever the channel count.
* @param sampleRate The sample rate of the audio in Hz (e.g., 44100, 48000),
* from {@value #MIN_SAMPLE_RATE} to {@value #MAX_SAMPLE_RATE}.
* @param channels The number of audio channels: 1, 2, 4, 6 or 8.
* @param frameCount The number of frames in the provided audio data,
* which must be {@code sampleRate / 100}. A frame
* holds one sample for each channel, so 10 ms at
* 48 kHz is 480 frames whatever the channel count.
*
* @throws NullPointerException If the audio data is {@code null}.
* @throws IllegalArgumentException If the audio format is not 16-bit PCM,
* if a value is not positive, if the chunk
* is larger than WebRTC can take, or if the
* array is too short for the frames it is
* said to hold.
* if the sample rate or channel count is
* not one WebRTC can send, if the chunk is
* not 10 ms long or larger than WebRTC can
* take, or if the array is too short for
* the frames it is said to hold.
*/
public void pushAudio(byte[] audioData, int bits_per_sample, int sampleRate,
int channels, int frameCount) {
Expand All @@ -119,18 +137,21 @@ public void pushAudio(byte[] audioData, int bits_per_sample, int sampleRate,
* @param audioData The raw audio data bytes to process. Must hold at
* least {@code frameCount * channels * 2} bytes.
* @param bits_per_sample The number of bits per sample, which must be 16.
* @param sampleRate The sample rate of the audio in Hz (e.g., 44100, 48000).
* @param channels The number of audio channels (1 for mono, 2 for stereo).
* @param frameCount The number of frames in the provided audio data.
* @param sampleRate The sample rate of the audio in Hz (e.g., 44100, 48000),
* from {@value #MIN_SAMPLE_RATE} to {@value #MAX_SAMPLE_RATE}.
* @param channels The number of audio channels: 1, 2, 4, 6 or 8.
* @param frameCount The number of frames in the provided audio data,
* which must be {@code sampleRate / 100}.
* @param timestampUs The capture time of the chunk, on the clock of
* {@link dev.onvoid.webrtc.media.SyncClock#currentTimeUs()}.
*
* @throws NullPointerException If the audio data is {@code null}.
* @throws IllegalArgumentException If the audio format is not 16-bit PCM,
* if a value is not positive, if the chunk
* is larger than WebRTC can take, or if the
* array is too short for the frames it is
* said to hold.
* if the sample rate or channel count is
* not one WebRTC can send, if the chunk is
* not 10 ms long or larger than WebRTC can
* take, or if the array is too short for
* the frames it is said to hold.
*
* @see dev.onvoid.webrtc.media.SyncClock#currentTimeUs()
*/
Expand All @@ -143,9 +164,10 @@ public void pushAudio(byte[] audioData, int bits_per_sample, int sampleRate,
}

/**
* Checks that a chunk of audio is something WebRTC can take, so that a bad
* chunk is rejected here instead of reading past the end of the array or
* aborting the process in native code.
* Checks that a chunk of audio is something WebRTC can send, so that a bad
* chunk is rejected here instead of reading past the end of the array,
* aborting the process in native code, or being dropped by the encoder
* while the push appears to succeed.
*
* @param audioData The raw audio data bytes to process.
* @param bits_per_sample The number of bits per sample, which must be 16.
Expand All @@ -165,18 +187,24 @@ private static void validate(byte[] audioData, int bits_per_sample,
"Audio must be %d-bit PCM, got %d bits per sample",
BITS_PER_SAMPLE, bits_per_sample));
}
if (sampleRate <= 0) {
throw new IllegalArgumentException(
"Sample rate must be positive, got " + sampleRate);
}
if (channels <= 0 || channels > MAX_CHANNELS) {
if (sampleRate < MIN_SAMPLE_RATE || sampleRate > MAX_SAMPLE_RATE) {
throw new IllegalArgumentException(String.format(
"Channel count must be between 1 and %d, got %d",
MAX_CHANNELS, channels));
"Sample rate must be between %d and %d Hz, got %d",
MIN_SAMPLE_RATE, MAX_SAMPLE_RATE, sampleRate));
}
if (frameCount <= 0) {
if (channels != 1 && (channels <= 0 || channels > MAX_CHANNELS || channels % 2 != 0)) {
throw new IllegalArgumentException(
"Frame count must be positive, got " + frameCount);
"Channel count must be 1, 2, 4, 6 or 8, got " + channels);
}

// The encoder takes 10 ms at a time and drops any other size, which
// the push cannot tell since encoding happens on another thread.
int framesPer10Ms = sampleRate / 100;

if (frameCount != framesPer10Ms) {
throw new IllegalArgumentException(String.format(
"A chunk holds exactly 10 ms of audio, %d frames at %d Hz, got %d frames",
framesPer10Ms, sampleRate, frameCount));
}

// WebRTC copies the chunk into a fixed-size audio frame and aborts the
Expand All @@ -186,7 +214,7 @@ private static void validate(byte[] audioData, int bits_per_sample,
if (samples > MAX_SAMPLES_PER_PUSH) {
throw new IllegalArgumentException(String.format(
"A chunk holds at most %d samples across all channels, got %d "
+ "(%d frames x %d channels). Push shorter chunks, 10 ms each.",
+ "(%d frames x %d channels). Use fewer channels or a lower sample rate.",
MAX_SAMPLES_PER_PUSH, samples, frameCount, channels));
}

Expand Down
68 changes: 68 additions & 0 deletions webrtc/src/test/java/dev/onvoid/webrtc/CustomAudioSendTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright 2026 Alex Andres
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package dev.onvoid.webrtc;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Map;

import org.junit.jupiter.api.Test;

/**
* The checks of {@code CustomAudioSource.pushAudio} reject what a sender drops.
* These tests hold them to the other half of that: what passes reaches the
* wire, also at the limits of what the checks let through.
*/
class CustomAudioSendTests extends TestBase {

private static final long TIMEOUT_NANOS = 10_000_000_000L;


@Test
void acceptedFormatsAreSent() throws Exception {
int[][] formats = { { 8000, 1 }, { 44100, 2 }, { 48000, 4 }, { 48000, 6 }, { 48000, 8 },
{ 96000, 8 }, { 192000, 4 } };

for (int[] format : formats) {
try (TestMediaCall call = new TestMediaCall(factory, false, true)) {
call.setAudioFormat(format[0], format[1]);
call.negotiate();
call.awaitConnected();
call.startMedia();

assertTrue(awaitPackets(call), format[0] + " Hz with " + format[1] + " channels was not sent");
}
}
}

private static boolean awaitPackets(TestMediaCall call) throws InterruptedException {
long start = System.nanoTime();

while (System.nanoTime() - start < TIMEOUT_NANOS) {
Map<String, Object> stats = call.getOutboundAudioStats();

if (stats != null && ((Number) stats.get("packetsSent")).longValue() > 0) {
return true;
}

Thread.sleep(20);
}

return false;
}

}
Loading
Loading