diff --git a/docs/tools/video/video-buffer-converter.md b/docs/tools/video/video-buffer-converter.md index def1dcbc..1e3b243d 100644 --- a/docs/tools/video/video-buffer-converter.md +++ b/docs/tools/video/video-buffer-converter.md @@ -137,7 +137,9 @@ public void onImage(BufferedImage image) { ## Error handling and edge cases - All methods throw `NullPointerException` if src/dst is null; ensure proper checks. - `ByteBuffer` destinations must be writable (not read-only) for `convertFromI420`. -- A `ByteBuffer` is read or written between its position and its limit only, also when it is a slice or a view of a larger buffer. The window must hold the whole frame; the position and limit stay as they are. +- A packed `ByteBuffer` is read or written between its position and its limit only, also when it is a slice or a view of a larger buffer. The window must hold the whole frame; the position and limit stay as they are. +- I420 frames need positive dimensions. Every Y/U/V plane must be a non-null direct buffer with stride at least its plane width and capacity of at least `stride * (rows - 1L) + columns` bytes. Chroma dimensions round up to half the frame dimensions. The last row needs no trailing padding. +- I420 plane positions and limits are ignored; return a slice with the appropriate capacity to restrict a plane's memory. Read-only planes are accepted as sources, but all three destination planes must be writable. Invalid planes cause a `RuntimeException` before conversion writes any pixels. - Ensure the correct FourCC is used for the actual memory layout you pass/expect. - Beware of frame rotation metadata; conversions do not rotate pixels. Handle `VideoFrame.rotation` separately if your renderer requires upright images. diff --git a/webrtc-jni/src/main/cpp/include/api/VideoFrame.h b/webrtc-jni/src/main/cpp/include/api/VideoFrame.h index b1ff1d56..a1397912 100644 --- a/webrtc-jni/src/main/cpp/include/api/VideoFrame.h +++ b/webrtc-jni/src/main/cpp/include/api/VideoFrame.h @@ -48,6 +48,13 @@ namespace jni namespace I420Buffer { + // Checks a plane's dimensions, stride and direct-buffer capacity before + // native code reads or writes it. The last row needs only width bytes. + // Position and limit are ignored, as in I420Buffer's Java contract. + // Writable destinations must not be read-only. Throws on invalid input. + void CheckPlane(JNIEnv * env, const char * name, jobject data, jint stride, + jint width, jint height, bool writable = false); + // Wraps the pixels of the buffer in a NativeI420Buffer without // copying them. With readOnly its planes are read-only byte buffers, // for pixels that others share. diff --git a/webrtc-jni/src/main/cpp/src/JNI_VideoBufferConverter.cpp b/webrtc-jni/src/main/cpp/src/JNI_VideoBufferConverter.cpp index ade51c65..d2dad1a7 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_VideoBufferConverter.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_VideoBufferConverter.cpp @@ -19,7 +19,7 @@ #include "JavaRuntimeException.h" #include "JavaUtils.h" -#include "api/video/i420_buffer.h" +#include "api/VideoFrame.h" #include "libyuv/convert.h" #include "libyuv/video_common.h" @@ -159,6 +159,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoBufferConverter_I return; } + const jint chromaWidth = static_cast((width + 1LL) / 2); + const jint chromaHeight = static_cast((height + 1LL) / 2); + jni::I420Buffer::CheckPlane(env, "Y", jSrcY, srcStrideY, width, height); + jni::I420Buffer::CheckPlane(env, "U", jSrcU, srcStrideU, chromaWidth, chromaHeight); + jni::I420Buffer::CheckPlane(env, "V", jSrcV, srcStrideV, chromaWidth, chromaHeight); + const uint8_t * srcY = static_cast(env->GetDirectBufferAddress(jSrcY)); const uint8_t * srcU = static_cast(env->GetDirectBufferAddress(jSrcU)); const uint8_t * srcV = static_cast(env->GetDirectBufferAddress(jSrcV)); @@ -191,6 +197,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoBufferConverter_I jobject jSrcV, jint srcStrideV, jobject dst, jint width, jint height, jint fourCC) { jni::CallFromJava(env, [&]() { + const jint chromaWidth = static_cast((width + 1LL) / 2); + const jint chromaHeight = static_cast((height + 1LL) / 2); + jni::I420Buffer::CheckPlane(env, "Y", jSrcY, srcStrideY, width, height); + jni::I420Buffer::CheckPlane(env, "U", jSrcU, srcStrideU, chromaWidth, chromaHeight); + jni::I420Buffer::CheckPlane(env, "V", jSrcV, srcStrideV, chromaWidth, chromaHeight); + const uint8_t * srcY = static_cast(env->GetDirectBufferAddress(jSrcY)); const uint8_t * srcU = static_cast(env->GetDirectBufferAddress(jSrcU)); const uint8_t * srcV = static_cast(env->GetDirectBufferAddress(jSrcV)); @@ -232,6 +244,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoBufferConverter_b return; } + const jint chromaWidth = static_cast((width + 1LL) / 2); + const jint chromaHeight = static_cast((height + 1LL) / 2); + jni::I420Buffer::CheckPlane(env, "Y", jDstY, dstStrideY, width, height, true); + jni::I420Buffer::CheckPlane(env, "U", jDstU, dstStrideU, chromaWidth, chromaHeight, true); + jni::I420Buffer::CheckPlane(env, "V", jDstV, dstStrideV, chromaWidth, chromaHeight, true); + uint8_t * dstY = static_cast(env->GetDirectBufferAddress(jDstY)); uint8_t * dstU = static_cast(env->GetDirectBufferAddress(jDstU)); uint8_t * dstV = static_cast(env->GetDirectBufferAddress(jDstV)); @@ -268,6 +286,12 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoBufferConverter_d jobject jDstU, jint dstStrideU, jobject jDstV, jint dstStrideV, jint fourCC) { jni::CallFromJava(env, [&]() { + const jint chromaWidth = static_cast((width + 1LL) / 2); + const jint chromaHeight = static_cast((height + 1LL) / 2); + jni::I420Buffer::CheckPlane(env, "Y", jDstY, dstStrideY, width, height, true); + jni::I420Buffer::CheckPlane(env, "U", jDstU, dstStrideU, chromaWidth, chromaHeight, true); + jni::I420Buffer::CheckPlane(env, "V", jDstV, dstStrideV, chromaWidth, chromaHeight, true); + uint8_t * dstY = static_cast(env->GetDirectBufferAddress(jDstY)); uint8_t * dstU = static_cast(env->GetDirectBufferAddress(jDstU)); uint8_t * dstV = static_cast(env->GetDirectBufferAddress(jDstV)); diff --git a/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp b/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp index b183a14a..d01cdc84 100644 --- a/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp +++ b/webrtc-jni/src/main/cpp/src/api/VideoFrame.cpp @@ -31,6 +31,19 @@ namespace jni { namespace { + class JavaByteBufferClass : public JavaClass + { + public: + explicit JavaByteBufferClass(JNIEnv * env) + { + cls = FindClass(env, "java/nio/ByteBuffer"); + isReadOnly = GetMethod(env, cls, "isReadOnly", "()Z"); + } + + jclass cls; + jmethodID isReadOnly; + }; + // A direct buffer over a plane, or throws: the allocation may fail, with or without an exception pending. JavaLocalRef NewPlane(JNIEnv * env, const char * name, const uint8_t * data, jlong size) { @@ -55,24 +68,6 @@ namespace jni return view; } - // Throws unless the plane holds every byte a copy reads: the last row ends at the width. - void CheckPlane(JNIEnv * env, const char * name, const JavaRef & data, jint stride, jint width, jint height) - { - if (stride < width) { - throw JavaWrappedException(JavaLocalRef(env, - JavaRuntimeException(env, "Stride %d of the %s plane is less than its width %d", stride, name, width))); - } - - // Neither factor exceeds an int, so the product cannot overflow. - const int64_t required = static_cast(stride) * (height - 1) + width; - const jlong capacity = env->GetDirectBufferCapacity(data); - - if (capacity < required) { - throw JavaWrappedException(JavaLocalRef(env, - JavaRuntimeException(env, "The %s plane holds %lld bytes, but a %dx%d plane with stride %d needs %lld", - name, static_cast(capacity), width, height, stride, static_cast(required)))); - } - } } namespace VideoFrame @@ -203,9 +198,9 @@ namespace jni JavaRuntimeException(env, "Buffer size %dx%d is too large", width, height))); } - CheckPlane(env, "Y", dataY, strideY, width, height); - CheckPlane(env, "U", dataU, strideU, chromaWidth, chromaHeight); - CheckPlane(env, "V", dataV, strideV, chromaWidth, chromaHeight); + I420Buffer::CheckPlane(env, "Y", dataY, strideY, width, height); + I420Buffer::CheckPlane(env, "U", dataU, strideU, chromaWidth, chromaHeight); + I420Buffer::CheckPlane(env, "V", dataV, strideV, chromaWidth, chromaHeight); return webrtc::I420Buffer::Copy(width, height, y, strideY, u, strideU, v, strideV); } @@ -213,6 +208,43 @@ namespace jni namespace I420Buffer { + void CheckPlane(JNIEnv * env, const char * name, jobject data, jint stride, + jint width, jint height, bool writable) + { + if (width <= 0 || height <= 0 || stride < width) { + throw JavaWrappedException(JavaLocalRef(env, + JavaRuntimeException(env, "Invalid %s plane dimensions %dx%d or stride %d", name, width, height, stride))); + } + if (data == nullptr) { + throw JavaWrappedException(JavaLocalRef(env, + JavaRuntimeException(env, "The %s plane is null", name))); + } + + const jlong capacity = env->GetDirectBufferCapacity(data); + if (capacity < 0 || env->GetDirectBufferAddress(data) == nullptr) { + throw JavaWrappedException(JavaLocalRef(env, + JavaRuntimeException(env, "The %s plane must be a direct buffer", name))); + } + + // Each factor is an int; the product and sum fit in 64 bits. + const int64_t required = static_cast(stride) * (height - 1) + width; + if (capacity < required) { + throw JavaWrappedException(JavaLocalRef(env, + JavaRuntimeException(env, "The %s plane holds %lld bytes, but a %dx%d plane with stride %d needs %lld", + name, static_cast(capacity), width, height, stride, static_cast(required)))); + } + + if (writable) { + const auto javaClass = JavaClasses::get(env); + const jboolean readOnly = env->CallBooleanMethod(data, javaClass->isReadOnly); + ExceptionCheck(env); + if (readOnly) { + throw JavaWrappedException(JavaLocalRef(env, + JavaRuntimeException(env, "The %s destination plane is read-only", name))); + } + } + } + JavaLocalRef toJava(JNIEnv * env, const webrtc::scoped_refptr & buffer, bool readOnly) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/I420Buffer.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/I420Buffer.java index 79ae7ada..2853db3e 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/I420Buffer.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/I420Buffer.java @@ -18,12 +18,24 @@ import java.nio.ByteBuffer; +/** + * Planar I420 pixels with positive dimensions and direct Y, U and V buffers. + * Each stride must be at least its plane's width. A plane must hold + * {@code stride * (rows - 1L) + columns} bytes: padding after the last row is + * not required. Chroma columns and rows are the frame dimensions rounded up + * to half size. Plane position and limit are ignored; use a slice to expose + * only the memory belonging to the plane. + *

+ * Read-only planes can be used as sources. Operations that write pixels, + * such as {@link VideoBufferConverter#convertToI420(byte[], I420Buffer, + * dev.onvoid.webrtc.media.FourCC)}, require writable destination planes. + */ public interface I420Buffer extends VideoFrameBuffer { /** * Returns a direct ByteBuffer containing Y-plane data. The buffer capacity is - * at least getStrideY() * getHeight() bytes. The position of the returned - * buffer is ignored and must be 0. Callers may mutate the ByteBuffer (eg. + * at least {@code getStrideY() * (getHeight() - 1L) + getWidth()} bytes. + * The position of the returned buffer is ignored and must be 0. Callers may mutate the ByteBuffer (eg. * through relative-read operations), so implementations must return a new * ByteBuffer or slice for each call. */ @@ -31,8 +43,8 @@ public interface I420Buffer extends VideoFrameBuffer { /** * Returns a direct ByteBuffer containing U-plane data. The buffer capacity is - * at least getStrideU() * ((getHeight() + 1) / 2) bytes. The position of the - * returned buffer is ignored and must be 0. Callers may mutate the ByteBuffer + * large enough for every chroma row, without requiring trailing padding. + * The position of the returned buffer is ignored and must be 0. Callers may mutate the ByteBuffer * (eg. through relative-read operations), so implementations must return a new * ByteBuffer or slice for each call. */ @@ -40,8 +52,8 @@ public interface I420Buffer extends VideoFrameBuffer { /** * Returns a direct ByteBuffer containing V-plane data. The buffer capacity is - * at least getStrideV() * ((getHeight() + 1) / 2) bytes. The position of the - * returned buffer is ignored and must be 0. Callers may mutate the ByteBuffer + * large enough for every chroma row, without requiring trailing padding. + * The position of the returned buffer is ignored and must be 0. Callers may mutate the ByteBuffer * (eg. through relative-read operations), so implementations must return a new * ByteBuffer or slice for each call. */ diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoBufferConverter.java b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoBufferConverter.java index 05c1a939..262b077e 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoBufferConverter.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/media/video/VideoBufferConverter.java @@ -34,6 +34,13 @@ * {@code 2 * ((width + 1) / 2)}. Conversions in both directions use this * layout, and fail when the buffer is smaller than the frame. * + * I420 planes must be non-null direct buffers, with positive dimensions, + * strides at least as large as their plane widths, and capacity for every + * pixel through the last row. The last row needs no trailing padding. + * Destination planes must also be writable. Invalid planes cause a + * {@link RuntimeException} before any destination pixels are written. + * Plane positions and limits are ignored, as specified by {@link I420Buffer}. + * * @author Alex Andres */ public final class VideoBufferConverter { diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/media/video/I420PlaneValidationTest.java b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/I420PlaneValidationTest.java new file mode 100644 index 00000000..96f22b09 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/media/video/I420PlaneValidationTest.java @@ -0,0 +1,229 @@ +/* + * 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.video; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import dev.onvoid.webrtc.TestBase; +import dev.onvoid.webrtc.media.FourCC; + +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; + +class I420PlaneValidationTest extends TestBase { + + @TestFactory + List rejectsInvalidPlanes() { + List tests = new ArrayList<>(); + for (int plane = 0; plane < 3; plane++) { + for (String invalid : new String[] { "short", "heap", "null", "stride", "zero", "negative", "overflow" }) { + for (int storage = 0; storage < 3; storage++) { + for (boolean destination : new boolean[] { false, true }) { + final int selected = plane; + final int path = storage; + String name = "YUV".charAt(plane) + " " + invalid + " path=" + path + " destination=" + destination; + tests.add(DynamicTest.dynamicTest(name, () -> { + Planes frame = new Planes(3, 3); + frame.invalidate(selected, invalid); + Packed packed = new Packed(path, 3 * 3 * 4); + RuntimeException failure = assertThrows(RuntimeException.class, + () -> convert(frame, packed, destination)); + assertTrue(failure.getMessage().contains("" + "YUV".charAt(selected)), failure::getMessage); + frame.assertUntouched(); + packed.assertUntouched(); + })); + } + } + } + } + return tests; + } + + @Test + void rejectsReadOnlyDestinations() { + for (int selected = 0; selected < 3; selected++) { + for (int path = 0; path < 3; path++) { + Planes frame = new Planes(3, 3); + frame.planes[selected] = frame.planes[selected].asReadOnlyBuffer(); + Packed packed = new Packed(path, 3 * 3 * 4); + RuntimeException failure = assertThrows(RuntimeException.class, () -> convert(frame, packed, true)); + assertTrue(failure.getMessage().contains("read-only")); + frame.assertUntouched(); + } + } + } + + @Test + void readsReadOnlyPlanes() throws Exception { + for (int path = 0; path < 3; path++) { + Planes frame = new Planes(3, 3); + Packed expected = new Packed(path, 3 * 3 * 4); + convert(frame, expected, false); + for (int plane = 0; plane < 3; plane++) { + frame.planes[plane] = frame.planes[plane].asReadOnlyBuffer(); + } + Packed actual = new Packed(path, 3 * 3 * 4); + convert(frame, actual, false); + assertArrayEquals(expected.bytes(), actual.bytes()); + frame.assertUntouched(); + } + } + + @Test + void acceptsExactPaddedPlanes() throws Exception { + for (int[] size : new int[][] { { 1, 1 }, { 3, 1 }, { 1, 3 }, { 3, 3 }, { 4, 4 } }) { + for (int path = 0; path < 3; path++) { + Planes frame = new Planes(size[0], size[1]); + Packed packed = new Packed(path, size[0] * size[1] * 4); + convert(frame, packed, true); + frame.assertPaddingUntouched(); + Packed actual = new Packed(path, packed.bytes().length); + convert(frame, actual, false); + frame.assertPaddingUntouched(); + // All input RGB channels have the same constant value. + for (int pixel = 0; pixel < size[0] * size[1]; pixel++) { + byte[] bytes = actual.bytes(); + for (int channel = 0; channel < 3; channel++) { + assertTrue(Math.abs((bytes[pixel * 4 + channel] & 0xff) - Packed.VALUE) <= 2); + } + } + } + } + } + + private static void convert(Planes planes, Packed packed, boolean destination) throws Exception { + if (destination) { + if (packed.buffer == null) VideoBufferConverter.convertToI420(packed.array, planes, FourCC.ARGB); + else VideoBufferConverter.convertToI420(packed.buffer, planes, FourCC.ARGB); + } + else { + if (packed.buffer == null) VideoBufferConverter.convertFromI420(planes, packed.array, FourCC.ARGB); + else VideoBufferConverter.convertFromI420(planes, packed.buffer, FourCC.ARGB); + } + } + + private static class Packed { + static final int VALUE = 90; + final byte[] array; + final ByteBuffer buffer; + + Packed(int storage, int size) { + array = new byte[size]; + Arrays.fill(array, (byte) VALUE); + buffer = storage == 0 ? null : storage == 1 ? ByteBuffer.allocate(size) : ByteBuffer.allocateDirect(size); + if (buffer != null) buffer.put(array).rewind(); + } + + byte[] bytes() { + if (buffer == null) return array; + byte[] result = new byte[array.length]; + buffer.duplicate().get(result); + return result; + } + + void assertUntouched() { + for (byte value : bytes()) assertEquals((byte) VALUE, value); + } + } + + /** Views have exact capacities; larger guarded allocations keep a regression probe safe. */ + private static class Planes implements I420Buffer { + static final byte GUARD = 0x5a; + static final int OFFSET = 16; + final int width; + final int height; + final int[] strides; + final ByteBuffer[] whole = new ByteBuffer[3]; + final ByteBuffer[] planes = new ByteBuffer[3]; + + Planes(int width, int height) { + this.width = width; + this.height = height; + strides = new int[] { width + 2, (width + 1) / 2 + 1, (width + 1) / 2 + 1 }; + for (int plane = 0; plane < 3; plane++) { + int columns = plane == 0 ? width : (width + 1) / 2; + int rows = plane == 0 ? height : (height + 1) / 2; + int required = strides[plane] * (rows - 1) + columns; + whole[plane] = ByteBuffer.allocateDirect(128); + for (int i = 0; i < whole[plane].capacity(); i++) whole[plane].put(i, GUARD); + ByteBuffer window = whole[plane].duplicate(); + window.position(OFFSET); + window.limit(OFFSET + required); + planes[plane] = window.slice(); + } + } + + void invalidate(int selected, String kind) { + switch (kind) { + case "short": + planes[selected].limit(planes[selected].capacity() - 1); + planes[selected] = planes[selected].slice(); + break; + case "heap": planes[selected] = ByteBuffer.allocate(planes[selected].capacity()); break; + case "null": planes[selected] = null; break; + case "stride": strides[selected] = (selected == 0 ? width : (width + 1) / 2) - 1; break; + case "zero": strides[selected] = 0; break; + case "negative": strides[selected] = -1; break; + case "overflow": strides[selected] = Integer.MAX_VALUE; break; + default: throw new AssertionError(kind); + } + } + + void assertUntouched() { + for (ByteBuffer buffer : whole) { + for (int i = 0; i < buffer.capacity(); i++) assertEquals(GUARD, buffer.get(i)); + } + } + + void assertPaddingUntouched() { + for (int plane = 0; plane < 3; plane++) { + int columns = plane == 0 ? width : (width + 1) / 2; + int rows = plane == 0 ? height : (height + 1) / 2; + for (int i = 0; i < whole[plane].capacity(); i++) { + int index = i - OFFSET; + if (index < 0 || index / strides[plane] >= rows || index % strides[plane] >= columns) { + assertEquals(GUARD, whole[plane].get(i), "Plane " + plane + " byte " + i); + } + } + } + } + + @Override public int getWidth() { return width; } + @Override public int getHeight() { return height; } + @Override public int getStrideY() { return strides[0]; } + @Override public int getStrideU() { return strides[1]; } + @Override public int getStrideV() { return strides[2]; } + @Override public ByteBuffer getDataY() { return planes[0]; } + @Override public ByteBuffer getDataU() { return planes[1]; } + @Override public ByteBuffer getDataV() { return planes[2]; } + @Override public I420Buffer toI420() { return this; } + @Override public void retain() { } + @Override public void release() { } + @Override public VideoFrameBuffer cropAndScale(int x, int y, int w, int h, int sw, int sh) { + throw new UnsupportedOperationException(); + } + } +}