Skip to content

Commit aa338da

Browse files
authored
fix: bound AudioResampler buffers and keep cropped I420 buffers alive (#413)
AudioResampler passed the output array's capacity instead of the requested samples per channel and ignored the channel count, so stereo wrote past the array. Both arrays are now checked against samplesPerChannel * channels. Cropping a NativeI420Buffer without scaling returned a wrapper with no native handle over the source's memory. The crop is now a native buffer that holds a reference to its source.
1 parent 8956629 commit aa338da

8 files changed

Lines changed: 362 additions & 61 deletions

File tree

‎webrtc-jni/src/main/cpp/include/JNI_NativeI420Buffer.h‎

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webrtc-jni/src/main/cpp/src/JNI_AudioResampler.cpp‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,16 @@ JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_audio_AudioResampler_resampl
6868
webrtc::PushResampler<int16_t> * resampler = GetHandle<webrtc::PushResampler<int16_t>>(env, caller);
6969
CHECK_HANDLEV(resampler, -1);
7070

71+
// Java checks these too, but the views below must never reach past an array.
72+
const jlong srcBytes = static_cast<jlong>(srcSamplesPerChannel) * channels * sizeof(int16_t);
73+
const jlong dstBytes = static_cast<jlong>(dstSamplesPerChannel) * channels * sizeof(int16_t);
74+
75+
if (srcSamplesPerChannel <= 0 || dstSamplesPerChannel <= 0 || channels <= 0 ||
76+
env->GetArrayLength(samplesIn) < srcBytes || env->GetArrayLength(samplesOut) < dstBytes) {
77+
ThrowJavaException(env, "java/lang/IllegalArgumentException", "Sample arrays too short for the requested samples");
78+
return -1;
79+
}
80+
7181
auto releaseSrc = [env, samplesIn](jbyte * bytes) {
7282
env->ReleaseByteArrayElements(samplesIn, bytes, JNI_ABORT);
7383
};

‎webrtc-jni/src/main/cpp/src/JNI_NativeI420Buffer.cpp‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include "JavaUtils.h"
2121

2222
#include "api/video/i420_buffer.h"
23+
#include "common_video/include/video_frame_buffer.h"
2324
#include "libyuv/scale.h"
2425

2526
JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_video_NativeI420Buffer_allocate
@@ -64,6 +65,34 @@ JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_video_NativeI420Buffer_co
6465
}
6566
}
6667

68+
JNIEXPORT jobject JNICALL Java_dev_onvoid_webrtc_media_video_NativeI420Buffer_crop
69+
(JNIEnv * env, jobject caller, jint cropX, jint cropY, jint cropW, jint cropH)
70+
{
71+
webrtc::I420BufferInterface * buffer = GetHandle<webrtc::I420BufferInterface>(env, caller);
72+
CHECK_HANDLEV(buffer, nullptr);
73+
74+
try {
75+
webrtc::scoped_refptr<webrtc::I420BufferInterface> source(buffer);
76+
77+
// The cropped buffer points into the source, which it keeps alive until it is gone itself.
78+
webrtc::scoped_refptr<webrtc::I420BufferInterface> cropped = webrtc::WrapI420Buffer(cropW, cropH,
79+
source->DataY() + cropX + cropY * source->StrideY(), source->StrideY(),
80+
source->DataU() + cropX / 2 + cropY / 2 * source->StrideU(), source->StrideU(),
81+
source->DataV() + cropX / 2 + cropY / 2 * source->StrideV(), source->StrideV(),
82+
[source]() {});
83+
84+
jni::JavaLocalRef<jobject> jBuffer = jni::I420Buffer::toJava(env, cropped);
85+
86+
cropped->AddRef();
87+
88+
return jBuffer.release();
89+
}
90+
catch (...) {
91+
ThrowCxxJavaException(env);
92+
return nullptr;
93+
}
94+
}
95+
6796
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_NativeI420Buffer_cropAndScale
6897
(JNIEnv * env, jclass caller, jobject jSrcY, jint srcStrideY, jobject jSrcU, jint srcStrideU,
6998
jobject jSrcV, jint srcStrideV, jint cropX, jint cropY, jint cropW, jint cropH,

‎webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
#include "api/VideoFrame.h"
1818
#include "JavaObject.h"
1919
#include "JavaUtils.h"
20+
#include "JavaRuntimeException.h"
21+
#include "JavaWrappedException.h"
2022
#include "JNI_WebRTC.h"
2123

2224
#include "api/video/i420_buffer.h"
@@ -62,6 +64,13 @@ namespace jni
6264
*/
6365

6466
webrtc::I420BufferInterface * i420Buffer = GetHandle<webrtc::I420BufferInterface>(env, jBuffer);
67+
68+
// A buffer that has been released for good has no pixels left.
69+
if (i420Buffer == nullptr) {
70+
throw JavaWrappedException(JavaLocalRef<jthrowable>(env,
71+
JavaRuntimeException(env, "The buffer of the VideoFrame has been released")));
72+
}
73+
6574
webrtc::scoped_refptr<webrtc::I420BufferInterface> buffer(i420Buffer);
6675

6776
return webrtc::VideoFrame::Builder()
@@ -107,6 +116,11 @@ namespace jni
107116
if (env->IsInstanceOf(javaBuffer, nativeClass->cls)) {
108117
webrtc::I420BufferInterface * buffer = GetHandle<webrtc::I420BufferInterface>(env, javaBuffer);
109118

119+
// Released for good, so there is nothing to read.
120+
if (buffer == nullptr) {
121+
return nullptr;
122+
}
123+
110124
return webrtc::scoped_refptr<webrtc::VideoFrameBuffer>(buffer);
111125
}
112126

@@ -154,9 +168,14 @@ namespace jni
154168
{
155169
const auto javaClass = JavaClasses::get<JavaNativeI420BufferClass>(env);
156170

157-
jobject yBuffer = env->NewDirectByteBuffer(const_cast<uint8_t *>(buffer->DataY()), static_cast<jlong>(buffer->StrideY()) * buffer->height());
158-
jobject uBuffer = env->NewDirectByteBuffer(const_cast<uint8_t *>(buffer->DataU()), static_cast<jlong>(buffer->StrideU()) * buffer->ChromaHeight());
159-
jobject vBuffer = env->NewDirectByteBuffer(const_cast<uint8_t *>(buffer->DataV()), static_cast<jlong>(buffer->StrideV()) * buffer->ChromaHeight());
171+
// The last row ends at the width: a cropped buffer has no padding behind it that belongs to it.
172+
auto planeSize = [](int stride, int width, int height) {
173+
return static_cast<jlong>(stride) * (height - 1) + width;
174+
};
175+
176+
jobject yBuffer = env->NewDirectByteBuffer(const_cast<uint8_t *>(buffer->DataY()), planeSize(buffer->StrideY(), buffer->width(), buffer->height()));
177+
jobject uBuffer = env->NewDirectByteBuffer(const_cast<uint8_t *>(buffer->DataU()), planeSize(buffer->StrideU(), buffer->ChromaWidth(), buffer->ChromaHeight()));
178+
jobject vBuffer = env->NewDirectByteBuffer(const_cast<uint8_t *>(buffer->DataV()), planeSize(buffer->StrideV(), buffer->ChromaWidth(), buffer->ChromaHeight()));
160179

161180
jobject jBuffer = env->NewObject(javaClass->cls, javaClass->ctor, buffer->width(), buffer->height(),
162181
yBuffer, buffer->StrideY(), uBuffer, buffer->StrideU(), vBuffer, buffer->StrideV());

‎webrtc/src/main/java/dev/onvoid/webrtc/media/audio/AudioResampler.java‎

Lines changed: 62 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import static java.util.Objects.requireNonNull;
2020

2121
import dev.onvoid.webrtc.internal.DisposableNativeObject;
22+
import dev.onvoid.webrtc.internal.NativeLoader;
2223

2324
/**
2425
* Audio sampling rate converter. This resampler operates on audio frames of 10
@@ -28,6 +29,24 @@
2829
*/
2930
public class AudioResampler extends DisposableNativeObject {
3031

32+
/** The most samples of one channel in 10 ms that WebRTC resamples, at 384 kHz. */
33+
private static final int MAX_SAMPLES_PER_CHANNEL = 3840;
34+
35+
/** The most channels that WebRTC resamples at once. */
36+
private static final int MAX_CHANNELS = 8;
37+
38+
/** Bytes of a 16-bit PCM sample. */
39+
private static final int BYTES_PER_SAMPLE = 2;
40+
41+
static {
42+
try {
43+
NativeLoader.loadLibrary("webrtc-java");
44+
}
45+
catch (Exception e) {
46+
throw new RuntimeException("Load library 'webrtc-java' failed", e);
47+
}
48+
}
49+
3150
/**
3251
* Creates a new {@code AudioResampler} without sampling parameters.
3352
*/
@@ -44,7 +63,14 @@ public AudioResampler() {
4463
* @param channels The number of audio channels to resample.
4564
*/
4665
public AudioResampler(int sourceSampleRate, int targetSampleRate, int channels) {
47-
initialize(getSamplesPerChannel(sourceSampleRate), getSamplesPerChannel(targetSampleRate), channels);
66+
int srcSamplesPerChannel = getSamplesPerChannel(sourceSampleRate);
67+
int dstSamplesPerChannel = getSamplesPerChannel(targetSampleRate);
68+
69+
checkSamplesPerChannel(srcSamplesPerChannel, "source");
70+
checkSamplesPerChannel(dstSamplesPerChannel, "destination");
71+
checkChannels(channels);
72+
73+
initialize(srcSamplesPerChannel, dstSamplesPerChannel, channels);
4874
}
4975

5076
/**
@@ -59,20 +85,24 @@ public AudioResampler(int sourceSampleRate, int targetSampleRate, int channels)
5985
* @param dstSamplesPerChannel The number of samples per destination channel.
6086
* @param channels The number of audio channels to resample.
6187
*
62-
* @return The number of converted audio samples.
88+
* @return The number of converted audio samples per channel.
89+
*
90+
* @throws IllegalArgumentException if a sample count or the channel count is out of range, or if
91+
* an array holds fewer than {@code samplesPerChannel * channels}
92+
* samples.
6393
*/
6494
public int resample(byte[] samplesIn, int srcSamplesPerChannel, byte[] samplesOut, int dstSamplesPerChannel,
6595
int channels) {
6696
requireNonNull(samplesIn);
6797
requireNonNull(samplesOut);
6898

69-
final int maxSamplesOut = samplesOut.length / 2; // 16-bit PCM sample
70-
71-
if (dstSamplesPerChannel > maxSamplesOut) {
72-
throw new IllegalArgumentException("Insufficient samples output length");
73-
}
99+
checkSamplesPerChannel(srcSamplesPerChannel, "source");
100+
checkSamplesPerChannel(dstSamplesPerChannel, "destination");
101+
checkChannels(channels);
102+
checkLength(samplesIn, srcSamplesPerChannel, channels, "input");
103+
checkLength(samplesOut, dstSamplesPerChannel, channels, "output");
74104

75-
return resampleInternal(samplesIn, srcSamplesPerChannel, samplesOut, maxSamplesOut, channels);
105+
return resampleInternal(samplesIn, srcSamplesPerChannel, samplesOut, dstSamplesPerChannel, channels);
76106
}
77107

78108
@Override
@@ -95,4 +125,28 @@ private native int resampleInternal(byte[] samplesIn, int srcSamplesPerChannel,
95125
public static int getSamplesPerChannel(int sampleRate) {
96126
return sampleRate / 100;
97127
}
128+
129+
private static void checkSamplesPerChannel(int samplesPerChannel, String name) {
130+
if (samplesPerChannel <= 0 || samplesPerChannel > MAX_SAMPLES_PER_CHANNEL) {
131+
throw new IllegalArgumentException("Invalid number of " + name + " samples per channel: "
132+
+ samplesPerChannel + ", must be between 1 and " + MAX_SAMPLES_PER_CHANNEL);
133+
}
134+
}
135+
136+
private static void checkChannels(int channels) {
137+
if (channels <= 0 || channels > MAX_CHANNELS) {
138+
throw new IllegalArgumentException("Invalid number of channels: " + channels
139+
+ ", must be between 1 and " + MAX_CHANNELS);
140+
}
141+
}
142+
143+
private static void checkLength(byte[] samples, int samplesPerChannel, int channels, String name) {
144+
// Both counts are bounded, so this cannot overflow.
145+
final int required = samplesPerChannel * channels * BYTES_PER_SAMPLE;
146+
147+
if (samples.length < required) {
148+
throw new IllegalArgumentException("Insufficient samples " + name + " length: need "
149+
+ required + " bytes, but was " + samples.length);
150+
}
151+
}
98152
}

‎webrtc/src/main/java/dev/onvoid/webrtc/media/video/NativeI420Buffer.java‎

Lines changed: 14 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -131,49 +131,26 @@ private static native NativeI420Buffer copy(int width, int height, ByteBuffer da
131131
int strideU, ByteBuffer dataV, int strideV);
132132

133133
/**
134-
* Wraps existing ByteBuffers into NativeI420Buffer object without copying the
135-
* contents.
134+
* Crops this buffer without copying. The cropped buffer shares the pixels of this one and holds a
135+
* reference to it, so it stays valid when this buffer is released.
136136
*/
137-
private static I420Buffer wrap(int width, int height, ByteBuffer dataY, int strideY, ByteBuffer dataU,
138-
int strideU, ByteBuffer dataV, int strideV) {
139-
if (dataY == null || dataU == null || dataV == null) {
140-
throw new IllegalArgumentException("Data buffers cannot be null");
137+
private native NativeI420Buffer crop(int cropX, int cropY, int cropWidth, int cropHeight);
138+
139+
private static VideoFrameBuffer cropAndScale(final NativeI420Buffer buffer, int cropX, int cropY,
140+
int cropWidth, int cropHeight, int scaleWidth, int scaleHeight) {
141+
if (cropX < 0 || cropY < 0 || cropWidth <= 0 || cropHeight <= 0
142+
|| cropWidth > buffer.getWidth() - cropX || cropHeight > buffer.getHeight() - cropY) {
143+
throw new IllegalArgumentException("Crop rectangle " + cropWidth + "x" + cropHeight + " at ("
144+
+ cropX + ", " + cropY + ") does not fit the " + buffer.getWidth() + "x"
145+
+ buffer.getHeight() + " buffer");
141146
}
142-
if (!dataY.isDirect() || !dataU.isDirect() || !dataV.isDirect()) {
143-
throw new IllegalArgumentException("Data buffers must be direct byte buffers");
147+
if (scaleWidth <= 0 || scaleHeight <= 0) {
148+
throw new IllegalArgumentException("Invalid scale size " + scaleWidth + "x" + scaleHeight);
144149
}
145150

146-
// Slice the buffers to prevent external modifications to the position / limit
147-
// of the buffer.
148-
// Note that this doesn't protect the contents of the buffers from modifications.
149-
dataY = dataY.slice();
150-
dataU = dataU.slice();
151-
dataV = dataV.slice();
152-
153-
final int chromaWidth = (width + 1) / 2;
154-
final int chromaHeight = (height + 1) / 2;
155-
156-
checkCapacity(dataY, width, height, strideY);
157-
checkCapacity(dataU, chromaWidth, chromaHeight, strideU);
158-
checkCapacity(dataV, chromaWidth, chromaHeight, strideV);
159-
160-
return new NativeI420Buffer(width, height, dataY, strideY, dataU, strideU, dataV, strideV);
161-
}
162-
163-
private static VideoFrameBuffer cropAndScale(final I420Buffer buffer, int cropX, int cropY,
164-
int cropWidth, int cropHeight, int scaleWidth, int scaleHeight) {
165151
if (cropWidth == scaleWidth && cropHeight == scaleHeight) {
166152
// No scaling.
167-
ByteBuffer dataY = buffer.getDataY();
168-
ByteBuffer dataU = buffer.getDataU();
169-
ByteBuffer dataV = buffer.getDataV();
170-
171-
dataY.position(cropX + cropY * buffer.getStrideY());
172-
dataU.position(cropX / 2 + cropY / 2 * buffer.getStrideU());
173-
dataV.position(cropX / 2 + cropY / 2 * buffer.getStrideV());
174-
175-
return wrap(scaleWidth, scaleHeight, dataY.slice(), buffer.getStrideY(), dataU.slice(),
176-
buffer.getStrideU(), dataV.slice(), buffer.getStrideV());
153+
return buffer.crop(cropX, cropY, cropWidth, cropHeight);
177154
}
178155

179156
I420Buffer newBuffer = allocate(scaleWidth, scaleHeight);
@@ -186,16 +163,6 @@ private static VideoFrameBuffer cropAndScale(final I420Buffer buffer, int cropX,
186163
return newBuffer;
187164
}
188165

189-
private static void checkCapacity(ByteBuffer data, int width, int height, int stride) {
190-
// The last row does not necessarily need padding.
191-
final int minCapacity = stride * (height - 1) + width;
192-
193-
if (data.capacity() < minCapacity) {
194-
throw new IllegalArgumentException("Buffer must be at least " + minCapacity +
195-
" bytes, but was " + data.capacity());
196-
}
197-
}
198-
199166
private static native void cropAndScale(ByteBuffer srcY, int srcStrideY,
200167
ByteBuffer srcU, int srcStrideU, ByteBuffer srcV, int srcStrideV, int cropX, int cropY,
201168
int cropWidth, int cropHeight, ByteBuffer dstY, int dstStrideY, ByteBuffer dstU,

0 commit comments

Comments
 (0)