From 612f4a82945918cf52a3083ae88c46208de3c55a Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 5 Nov 2026 12:27:10 +0100 Subject: [PATCH] fix: reject custom audio that WebRTC cannot send pushAudio accepted chunks the encoder drops silently and formats that abort the process. It now requires exactly 10 ms, 1, 2, 4, 6 or 8 channels and 8 to 192 kHz; PcmFormat follows. --- docs/guide/audio/custom-audio-source.md | 13 ++- docs/guide/audio/headless-audio.md | 4 +- .../dev/onvoid/webrtc/client/PcmFormat.java | 23 +++-- .../webrtc/media/audio/CustomAudioSource.java | 96 ++++++++++++------- .../onvoid/webrtc/CustomAudioSendTests.java | 68 +++++++++++++ .../java/dev/onvoid/webrtc/TestMediaCall.java | 44 +++++++-- .../dev/onvoid/webrtc/client/MediaTests.java | 20 +++- .../media/audio/AudioDataAccessTests.java | 5 +- .../media/audio/CustomAudioSourceTest.java | 64 +++++++++++-- 9 files changed, 263 insertions(+), 74 deletions(-) create mode 100644 webrtc/src/test/java/dev/onvoid/webrtc/CustomAudioSendTests.java diff --git a/docs/guide/audio/custom-audio-source.md b/docs/guide/audio/custom-audio-source.md index 787542486..322c371a8 100644 --- a/docs/guide/audio/custom-audio-source.md +++ b/docs/guide/audio/custom-audio-source.md @@ -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) @@ -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 @@ -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 diff --git a/docs/guide/audio/headless-audio.md b/docs/guide/audio/headless-audio.md index 2c95351cd..1444988fe 100644 --- a/docs/guide/audio/headless-audio.md +++ b/docs/guide/audio/headless-audio.md @@ -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); @@ -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. diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/PcmFormat.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/PcmFormat.java index 361153a6a..aac06d780 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/PcmFormat.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/PcmFormat.java @@ -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 diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/CustomAudioSource.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/CustomAudioSource.java index 027c515b3..808aed678 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/CustomAudioSource.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/audio/CustomAudioSource.java @@ -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; /** @@ -73,8 +87,9 @@ public CustomAudioSource(SyncClock clock) { * from one thread at a time. *

* 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. *

@@ -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) { @@ -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() */ @@ -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. @@ -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 @@ -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)); } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/CustomAudioSendTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/CustomAudioSendTests.java new file mode 100644 index 000000000..330c95710 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/CustomAudioSendTests.java @@ -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 stats = call.getOutboundAudioStats(); + + if (stats != null && ((Number) stats.get("packetsSent")).longValue() > 0) { + return true; + } + + Thread.sleep(20); + } + + return false; + } + +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/TestMediaCall.java b/webrtc/src/test/java/dev/onvoid/webrtc/TestMediaCall.java index e9c90ab3b..03c33fbd0 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/TestMediaCall.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/TestMediaCall.java @@ -72,6 +72,9 @@ class TestMediaCall implements AutoCloseable { private volatile int width = DEFAULT_WIDTH; private volatile int height = DEFAULT_HEIGHT; + private volatile int audioRate = 48000; + private volatile int audioChannels = 1; + TestMediaCall(PeerConnectionFactory factory, boolean video, boolean audio) { this(factory, video, audio, "VP8"); @@ -145,6 +148,15 @@ void setVideoSize(int width, int height) { this.height = height; } + /** + * Sets the format of the audio the call sends, 48 kHz mono unless changed. + * Call it before {@link #startMedia()}. + */ + void setAudioFormat(int sampleRate, int channels) { + this.audioRate = sampleRate; + this.audioChannels = channels; + } + /** * Waits for both ends to connect. */ @@ -168,10 +180,22 @@ void startMedia() { * if there are none yet. */ Map getOutboundVideoStats() throws InterruptedException { + return getOutboundStats(videoSender); + } + + /** + * Returns the caller's statistics of its outbound audio stream, or null + * if there are none yet. + */ + Map getOutboundAudioStats() throws InterruptedException { + return getOutboundStats(audioSender); + } + + private Map getOutboundStats(RTCRtpSender sender) throws InterruptedException { CountDownLatch done = new CountDownLatch(1); AtomicReference> outbound = new AtomicReference<>(); - caller.getPeerConnection().getStats(videoSender, report -> { + caller.getPeerConnection().getStats(sender, report -> { for (RTCStats stats : report.getStats().values()) { if (stats.getType() == RTCStatsType.OUTBOUND_RTP) { outbound.set(stats.getAttributes()); @@ -336,7 +360,10 @@ private static void preferCodec(PeerConnectionFactory factory, RTCPeerConnection } private void feed() { - byte[] audio = new byte[480 * 2]; + int rate = audioRate; + int channels = audioChannels; + int frames = rate / 100; + byte[] audio = new byte[frames * channels * 2]; long startNs = System.nanoTime(); long audioChunks = 0; long videoFrames = 0; @@ -347,13 +374,16 @@ private void feed() { while (audioSource != null && audioChunks * 10 <= elapsedMs) { // A tone, so that the encoder has something to encode. - for (int i = 0; i < 480; i++) { - short sample = (short) (Math.sin(2 * Math.PI * 440 * (audioChunks * 480 + i) / 48000) * 8000); - audio[2 * i] = (byte) sample; - audio[2 * i + 1] = (byte) (sample >> 8); + for (int i = 0; i < frames; i++) { + short sample = (short) (Math.sin(2 * Math.PI * 440 * (audioChunks * frames + i) / rate) * 8000); + + for (int channel = 0; channel < channels; channel++) { + audio[2 * (i * channels + channel)] = (byte) sample; + audio[2 * (i * channels + channel) + 1] = (byte) (sample >> 8); + } } - audioSource.pushAudio(audio, 16, 48000, 1, 480); + audioSource.pushAudio(audio, 16, rate, channels, frames); audioChunks++; } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java index 7bf302f03..319e39b92 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java @@ -344,12 +344,22 @@ void slowPushLeavesTimerFree() throws Exception { @Test void oversizedFormatRejected() { - // 10 ms of these hold 30720 samples, more than WebRTC takes at once. - assertThrows(IllegalArgumentException.class, () -> PcmFormat.of(384000, 8)); + // 10 ms of these hold 15360 samples, more than WebRTC takes at once. + assertThrows(IllegalArgumentException.class, () -> PcmFormat.of(192000, 8)); - // The largest that fit, 7680 and 3840 samples. - PcmFormat.of(384000, 2); - PcmFormat.of(48000, 8); + // The largest that fit, 7680 samples each. + PcmFormat.of(192000, 4); + PcmFormat.of(96000, 8); + } + + @Test + void unsendableFormatRejected() { + // The encoder drops these, so a track would stay silent without a word. + assertThrows(IllegalArgumentException.class, () -> PcmFormat.of(48000, 3)); + assertThrows(IllegalArgumentException.class, () -> PcmFormat.of(48000, 5)); + assertThrows(IllegalArgumentException.class, () -> PcmFormat.of(48000, 7)); + assertThrows(IllegalArgumentException.class, () -> PcmFormat.of(192100, 2)); + assertThrows(IllegalArgumentException.class, () -> PcmFormat.of(384000, 2)); } @Test 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 index b027202ae..45f31ffd4 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioDataAccessTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/AudioDataAccessTests.java @@ -201,14 +201,15 @@ void addNullAccess() { } /** - * Pushes 16-bit stereo audio at 48 kHz whose every byte is {@code value}. + * Pushes 10 ms of 16-bit stereo audio whose every byte is {@code value}, + * at the sample rate that makes that the given number of frames. */ 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); + source.pushAudio(data, 16, frames * 100, 2, frames); } private static void assertFilled(byte[] data, int value, int frames) { diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java index 585b8e382..b790aedee 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/audio/CustomAudioSourceTest.java @@ -76,9 +76,9 @@ void pushAudioRejectsArrayShorterThanTheFramesItClaims() { byte[] data = new byte[480 * 2 * 2]; IllegalArgumentException e = assertThrows(IllegalArgumentException.class, - () -> customAudioSource.pushAudio(data, 16, 48000, 2, 481)); + () -> customAudioSource.pushAudio(new byte[data.length - 1], 16, 48000, 2, 480)); - assertTrue(e.getMessage().contains("1924"), e.getMessage()); + assertTrue(e.getMessage().contains("1920"), e.getMessage()); // Exactly the required size is fine, and so is a longer array. customAudioSource.pushAudio(data, 16, 48000, 2, 480); @@ -89,19 +89,63 @@ void pushAudioRejectsArrayShorterThanTheFramesItClaims() { void pushAudioRejectsChunkLargerThanWebRtcTakes() { // WebRTC copies a chunk into a fixed-size frame and aborts the process // when it does not fit, so an oversized chunk must not reach it. - int frames = CustomAudioSource.MAX_SAMPLES_PER_PUSH / 2 + 1; - byte[] data = new byte[frames * 2 * 2]; + byte[] data = new byte[1920 * 6 * 2]; IllegalArgumentException e = assertThrows(IllegalArgumentException.class, - () -> customAudioSource.pushAudio(data, 16, 48000, 2, frames)); + () -> customAudioSource.pushAudio(data, 16, 192000, 6, 1920)); assertTrue(e.getMessage().contains(String.valueOf( CustomAudioSource.MAX_SAMPLES_PER_PUSH)), e.getMessage()); - // The largest chunk that still fits is accepted. - int maxFrames = CustomAudioSource.MAX_SAMPLES_PER_PUSH / 2; + // The largest chunks that still fit are accepted. + customAudioSource.pushAudio(data, 16, 192000, 4, 1920); + customAudioSource.pushAudio(data, 16, 96000, 8, 960); + } + + @Test + void pushAudioRejectsChunkOtherThan10Ms() { + // A sender drops such a chunk on another thread, so the push would + // appear to succeed while nothing is sent. + byte[] data = new byte[960 * 2 * 2]; + + for (int frames : new int[] { 240, 479, 481, 960 }) { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> customAudioSource.pushAudio(data, 16, 48000, 2, frames)); + + assertTrue(e.getMessage().contains("480 frames"), e.getMessage()); + } + } + + @Test + void pushAudioRejectsChannelCountWebRtcCannotSend() { + byte[] data = new byte[80 * 24 * 2]; + + // Dropped by the encoder, and from 17 channels on the process aborts. + for (int channels : new int[] { 3, 5, 7, 9, 10, 17, 24 }) { + assertThrows(IllegalArgumentException.class, + () -> customAudioSource.pushAudio(data, 16, 8000, channels, 80)); + } + + for (int channels : new int[] { 1, 2, 4, 6, 8 }) { + customAudioSource.pushAudio(data, 16, 8000, channels, 80); + } + } + + @Test + void pushAudioRejectsSampleRateWebRtcCannotSend() { + byte[] data = new byte[2000 * 2]; + + // Too low a rate aborts the process in the resampler, and the encoder + // drops too high a one. + assertThrows(IllegalArgumentException.class, + () -> customAudioSource.pushAudio(data, 16, 1000, 1, 10)); + assertThrows(IllegalArgumentException.class, + () -> customAudioSource.pushAudio(data, 16, 7900, 1, 79)); + assertThrows(IllegalArgumentException.class, + () -> customAudioSource.pushAudio(data, 16, 192100, 1, 1921)); - customAudioSource.pushAudio(new byte[maxFrames * 2 * 2], 16, 48000, 2, maxFrames); + customAudioSource.pushAudio(data, 16, CustomAudioSource.MIN_SAMPLE_RATE, 1, 80); + customAudioSource.pushAudio(data, 16, CustomAudioSource.MAX_SAMPLE_RATE, 1, 1920); } @Test @@ -196,8 +240,8 @@ void concurrentAddRemoveSinkDoesNotCrash() throws InterruptedException { @Test void pushAudioWithDifferentFormats() { - // Every rate and channel count is passed through unchanged. Only 16-bit - // samples are accepted, since that is what WebRTC reads. + // Every accepted rate and channel count is passed through unchanged. + // Only 16-bit samples are accepted, since that is what WebRTC reads. testAudioFormat(16, 8000, 1, 80); // 8kHz, mono, 10ms testAudioFormat(16, 16000, 1, 160); // 16kHz, mono, 10ms testAudioFormat(16, 44100, 2, 441); // 44.1kHz, stereo, 10ms