From eaf67275bf707fe6d5bdc186cac125a35f58ba53 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Mon, 23 Nov 2026 22:24:54 +0200 Subject: [PATCH 1/9] =?UTF-8?q?feat(=F0=9F=8E=9E=EF=B8=8F):=20createNative?= =?UTF-8?q?BufferFromPointer=20takes=20a=20colorSpace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `RNWebGPU.createNativeBufferFromPointer(pointer, { colorSpace })`: a WebCodecs `VideoColorSpaceInit` (a `VideoFrame`'s `colorSpace` fits) that says how to read a YUV buffer carrying no color information of its own, such as an `AHardwareBuffer` from a MediaCodec `ImageReader`. Without it, BT.709 video was read with the BT.601 matrix on Android ((226, 0, 31) for red). The fields it sets replace what the buffer says; a `CVPixelBuffer` keeps its own attachments otherwise. --- packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h | 73 ++++++++++++++++++++++- packages/webgpu/src/index.tsx | 6 +- packages/webgpu/src/types.ts | 18 ++++++ packages/webgpu/src/video.ts | 7 ++- 4 files changed, 100 insertions(+), 4 deletions(-) diff --git a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h index 10f9dfe04d..b406afe309 100644 --- a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h +++ b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h @@ -320,9 +320,78 @@ class RNWebGPU : public NativeObject { // Wrap a CVPixelBufferRef / AHardwareBuffer* pointer (typed as void* via // BigInt on the JS side) into one of our VideoFrames. The native side // CFRetains / acquires so the caller can release immediately. - std::shared_ptr createNativeBufferFromPointer(void *pointer) { + // + // createNativeBufferFromPointer(pointer, { colorSpace? }): `colorSpace` (a + // WebCodecs VideoColorSpaceInit, e.g. a VideoFrame's colorSpace) says how to + // read a YUV buffer that carries no color information of its own, as an + // AHardwareBuffer from a MediaCodec ImageReader. The fields it sets replace + // what the buffer says. + jsi::Value createNativeBufferFromPointer(jsi::Runtime &runtime, + const jsi::Value & /*thisVal*/, + const jsi::Value *args, + size_t count) { + if (count < 1 || !args[0].isBigInt()) { + throw jsi::JSError(runtime, "createNativeBufferFromPointer: expected a " + "pointer (BigInt)"); + } + void *pointer = JSIConverter::fromJSI(runtime, args[0], false); auto handle = _platformContext->wrapNativeBuffer(pointer); - return std::make_shared(std::move(handle)); + if (count > 1 && args[1].isObject()) { + auto colorSpace = + args[1].getObject(runtime).getProperty(runtime, "colorSpace"); + if (colorSpace.isObject()) { + applyVideoColorSpace(runtime, colorSpace.getObject(runtime), + handle.colorSpace); + } + } + return JSIConverter>::toJSI( + runtime, std::make_shared(std::move(handle))); + } + + // A WebCodecs VideoColorSpaceInit onto the color space of a native frame. + static void applyVideoColorSpace(jsi::Runtime &runtime, + const jsi::Object &init, + VideoFrameColorSpace &colorSpace) { + auto field = [&](const char *name) -> std::string { + auto value = init.getProperty(runtime, name); + return value.isString() ? value.getString(runtime).utf8(runtime) : ""; + }; + const auto primaries = field("primaries"); + if (primaries == "bt709") { + colorSpace.primaries = wgpu::ColorSpacePrimariesDawn::SRGB; + } else if (primaries == "bt470bg" || primaries == "smpte170m") { + colorSpace.primaries = wgpu::ColorSpacePrimariesDawn::Rec601; + } else if (primaries == "bt2020") { + colorSpace.primaries = wgpu::ColorSpacePrimariesDawn::Rec2020; + } else if (primaries == "smpte432") { + colorSpace.primaries = wgpu::ColorSpacePrimariesDawn::DisplayP3; + } + const auto transfer = field("transfer"); + if (transfer == "bt709" || transfer == "smpte170m") { + colorSpace.transfer = wgpu::ColorSpaceTransferDawn::SMPTE_170M; + } else if (transfer == "iec61966-2-1") { + colorSpace.transfer = wgpu::ColorSpaceTransferDawn::SRGB; + } else if (transfer == "linear") { + colorSpace.transfer = wgpu::ColorSpaceTransferDawn::Identity; + } else if (transfer == "pq") { + colorSpace.transfer = wgpu::ColorSpaceTransferDawn::PQ; + } else if (transfer == "hlg") { + colorSpace.transfer = wgpu::ColorSpaceTransferDawn::HLG; + } + const auto matrix = field("matrix"); + if (matrix == "bt709") { + colorSpace.matrix = wgpu::ColorSpaceYCbCrMatrixDawn::Rec709; + } else if (matrix == "bt470bg" || matrix == "smpte170m") { + colorSpace.matrix = wgpu::ColorSpaceYCbCrMatrixDawn::Rec601; + } else if (matrix == "bt2020-ncl") { + colorSpace.matrix = wgpu::ColorSpaceYCbCrMatrixDawn::Rec2020; + } + auto fullRange = init.getProperty(runtime, "fullRange"); + if (fullRange.isBool()) { + colorSpace.range = fullRange.getBool() + ? wgpu::ColorSpaceYCbCrRangeDawn::Full + : wgpu::ColorSpaceYCbCrRangeDawn::Narrow; + } } // createNativeBuffer(width, height, { format?, colorSpace? }): an empty diff --git a/packages/webgpu/src/index.tsx b/packages/webgpu/src/index.tsx index 3bc1671f40..1729b018af 100644 --- a/packages/webgpu/src/index.tsx +++ b/packages/webgpu/src/index.tsx @@ -15,6 +15,7 @@ import type { GPUSharedFenceDescriptor, GPUSharedFenceState, CreateNativeBufferOptions, + CreateNativeBufferFromPointerOptions, GPUDawnTogglesDescriptor, GPUNativeExternalTextureDescriptor, GPUSharedTextureMemory, @@ -108,7 +109,10 @@ declare global { // Wrap a NativeBuffer.pointer (CVPixelBufferRef on iOS / AHardwareBuffer* // on Android) into a NativeBuffer. Matches the shape used by libraries // that emit NativeBuffer (e.g. react-native-vision-camera). - createNativeBufferFromPointer: (pointer: bigint) => NativeBuffer; + createNativeBufferFromPointer: ( + pointer: bigint, + options?: CreateNativeBufferFromPointerOptions, + ) => NativeBuffer; // Wrap an externally created WGPUDevice pointer (e.g. Skia's Graphite // device from Skia.getNativeDevice()) into a GPUDevice. Requires the // exporter to link this process's single Dawn copy. diff --git a/packages/webgpu/src/types.ts b/packages/webgpu/src/types.ts index b0bb67435e..540d382adb 100644 --- a/packages/webgpu/src/types.ts +++ b/packages/webgpu/src/types.ts @@ -328,6 +328,24 @@ export interface GPUSharedTextureMemory { destroy(): void; } +/** + * The options of `createNativeBufferFromPointer()`. + */ +export interface CreateNativeBufferFromPointerOptions { + /** + * How to read a YUV buffer that carries no color information of its own + * (an AHardwareBuffer from a MediaCodec ImageReader, for instance): a + * WebCodecs `VideoColorSpaceInit`, such as a `VideoFrame`'s `colorSpace`. + * The fields it sets replace what the buffer says. + */ + colorSpace?: { + primaries?: string | null; + transfer?: string | null; + matrix?: string | null; + fullRange?: boolean | null; + }; +} + /** * The options of `createNativeBuffer()`. The buffer holds premultiplied * pixels. diff --git a/packages/webgpu/src/video.ts b/packages/webgpu/src/video.ts index 131473fda3..9f70fca631 100644 --- a/packages/webgpu/src/video.ts +++ b/packages/webgpu/src/video.ts @@ -1,4 +1,5 @@ import type { + CreateNativeBufferFromPointerOptions, CreateNativeBufferOptions, CreateVideoPlayerOptions, NativeBuffer, @@ -51,9 +52,13 @@ export const createVideoPlayer = ( * VisionCamera's `frame.getNativeBuffer().pointer`) into a `NativeBuffer` * that keeps it alive until released. */ -export const createNativeBufferFromPointer = (pointer: bigint): NativeBuffer => +export const createNativeBufferFromPointer = ( + pointer: bigint, + options?: CreateNativeBufferFromPointerOptions, +): NativeBuffer => native("createNativeBufferFromPointer").createNativeBufferFromPointer( pointer, + options, ); /** From c201a06b76784510c5490bcd8b38b30e83c04065 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Tue, 24 Nov 2026 00:24:50 +0200 Subject: [PATCH 2/9] =?UTF-8?q?test(=F0=9F=8E=9E=EF=B8=8F):=20e2e=20spec?= =?UTF-8?q?=20for=20the=20colorSpace=20option=20of=20createNativeBufferFro?= =?UTF-8?q?mPointer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wraps the NV12 test frame's CVPixelBufferRef (BT.709 limited range attachments) with createNativeBufferFromPointer and samples it through importExternalTexture: without options and with an empty colorSpace the attachments apply; matrix "bt709" / "smpte170m", fullRange true / false and matrix + fullRange each give the colors a reference YCbCr -> sRGB conversion predicts, and the overrides visibly move the result. Skipped where the device has no IOSurface import (Android reads AHardwareBuffers through Vulkan's YCbCr sampler, which the expectations do not model). JS has no CVPixelBufferRef to hand over (NativeBuffer.handle is the IOSurface), so a test-only RNWebGPU.createTestPixelBuffer, left out of the TypeScript declarations, returns the test frame with that pointer as its handle. --- packages/webgpu/apple/ApplePlatformContext.h | 3 + packages/webgpu/apple/ApplePlatformContext.mm | 22 +- packages/webgpu/cpp/rnwgpu/PlatformContext.h | 10 + packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h | 13 + .../__tests__/NativeBufferColorSpace.spec.ts | 320 ++++++++++++++++++ 5 files changed, 366 insertions(+), 2 deletions(-) create mode 100644 packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts diff --git a/packages/webgpu/apple/ApplePlatformContext.h b/packages/webgpu/apple/ApplePlatformContext.h index 0f9f767c7d..db74ba3795 100644 --- a/packages/webgpu/apple/ApplePlatformContext.h +++ b/packages/webgpu/apple/ApplePlatformContext.h @@ -45,6 +45,9 @@ class ApplePlatformContext : public PlatformContext { VideoFrameHandle createTestVideoFrame(uint32_t width, uint32_t height, VideoPixelFormat format) override; + VideoFrameHandle createTestPixelBuffer(uint32_t width, + uint32_t height) override; + VideoFrameHandle createNativeBuffer(uint32_t width, uint32_t height, wgpu::TextureFormat format, bool displayP3) override; diff --git a/packages/webgpu/apple/ApplePlatformContext.mm b/packages/webgpu/apple/ApplePlatformContext.mm index f7803951cc..82b5fb7019 100644 --- a/packages/webgpu/apple/ApplePlatformContext.mm +++ b/packages/webgpu/apple/ApplePlatformContext.mm @@ -578,8 +578,10 @@ ImageData renderViewIntoPixels(const ResolvedSnapshot &snapshot, // The NV12 variant of createTestVideoFrame: a biplanar BT.709 limited-range // frame, red on the left half and green on the right, whose attachments // declare its color space the way the decoder's frames do, so that the -// conversion of importExternalTexture is fully determined. -static VideoFrameHandle createTestYuvFrame(uint32_t width, uint32_t height) { +// conversion of importExternalTexture is fully determined. The caller owns +// the returned reference. +static CVPixelBufferRef createTestYuvPixelBuffer(uint32_t width, + uint32_t height) { NSDictionary *attrs = @{ (NSString *)kCVPixelBufferIOSurfacePropertiesKey : @{}, (NSString *)kCVPixelBufferMetalCompatibilityKey : @YES, @@ -629,7 +631,11 @@ static VideoFrameHandle createTestYuvFrame(uint32_t width, uint32_t height) { } } CVPixelBufferUnlockBaseAddress(pixelBuffer, 0); + return pixelBuffer; +} +static VideoFrameHandle createTestYuvFrame(uint32_t width, uint32_t height) { + CVPixelBufferRef pixelBuffer = createTestYuvPixelBuffer(width, height); try { auto handle = wrapCVPixelBuffer(pixelBuffer); CFRelease(pixelBuffer); // wrapCVPixelBuffer retained its own reference @@ -693,6 +699,18 @@ static VideoFrameHandle createTestYuvFrame(uint32_t width, uint32_t height) { return handle; } +VideoFrameHandle ApplePlatformContext::createTestPixelBuffer(uint32_t width, + uint32_t height) { + CVPixelBufferRef pixelBuffer = createTestYuvPixelBuffer(width, height); + VideoFrameHandle handle; + handle.handle = pixelBuffer; + handle.width = width; + handle.height = height; + handle.pixelFormat = VideoPixelFormat::NV12; + handle.deleter = [pixelBuffer]() { CFRelease(pixelBuffer); }; + return handle; +} + // An IOSurface-backed pixel buffer that Dawn imports as a render target and // Core Animation displays as layer contents (NativeBufferView). The surface is // tagged with its color space (kIOSurfaceColorSpace), which Core Animation diff --git a/packages/webgpu/cpp/rnwgpu/PlatformContext.h b/packages/webgpu/cpp/rnwgpu/PlatformContext.h index f9f96d652a..fa9ec19be1 100644 --- a/packages/webgpu/cpp/rnwgpu/PlatformContext.h +++ b/packages/webgpu/cpp/rnwgpu/PlatformContext.h @@ -228,6 +228,16 @@ class PlatformContext { virtual VideoFrameHandle createTestVideoFrame(uint32_t width, uint32_t height, VideoPixelFormat format) = 0; + // Test only (the e2e specs of createNativeBufferFromPointer): the NV12 test + // frame as the pointer createNativeBufferFromPointer takes, in `handle`. A + // CVPixelBufferRef carrying the frame's color attachments on Apple + // platforms, which is not importable as is; the frame's own AHardwareBuffer* + // elsewhere. + virtual VideoFrameHandle createTestPixelBuffer(uint32_t width, + uint32_t height) { + return createTestVideoFrame(width, height, VideoPixelFormat::NV12); + } + // Allocate an empty, GPU-renderable buffer that a NativeBufferView can // display: an AHardwareBuffer (Android) or an IOSurface (Apple platforms), // with premultiplied pixels in `format`, tagged with `displayP3` or sRGB diff --git a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h index b406afe309..a4b10a920d 100644 --- a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h +++ b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h @@ -317,6 +317,17 @@ class RNWebGPU : public NativeObject { return std::make_shared(std::move(frame)); } + // Test only, left out of the TypeScript declarations: the NV12 test frame as + // a buffer whose `handle` is the pointer createNativeBufferFromPointer takes + // (PlatformContext::createTestPixelBuffer). Pass the handle there; do not + // import the buffer itself. + std::shared_ptr createTestPixelBuffer(double width, + double height) { + auto frame = _platformContext->createTestPixelBuffer( + static_cast(width), static_cast(height)); + return std::make_shared(std::move(frame)); + } + // Wrap a CVPixelBufferRef / AHardwareBuffer* pointer (typed as void* via // BigInt on the JS side) into one of our VideoFrames. The native side // CFRetains / acquires so the caller can release immediately. @@ -645,6 +656,8 @@ class RNWebGPU : public NativeObject { &RNWebGPU::loadVideoFrame); installMethod(runtime, prototype, "createTestVideoFrame", &RNWebGPU::createTestVideoFrame); + installMethod(runtime, prototype, "createTestPixelBuffer", + &RNWebGPU::createTestPixelBuffer); installMethod(runtime, prototype, "createNativeBufferFromPointer", &RNWebGPU::createNativeBufferFromPointer); installMethodWithRuntime(runtime, prototype, "importDevice", diff --git a/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts new file mode 100644 index 0000000000..0538121913 --- /dev/null +++ b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts @@ -0,0 +1,320 @@ +import { client } from "./setup"; + +// A pixel as [r, g, b], 0..255. +type Rgb = number[]; + +type EvalResult = + | { kind: "skip"; reason: string } + | { kind: "fail"; reason: string } + | { kind: "ok"; left: Rgb; right: Rgb }; + +// The colorSpace option of createNativeBufferFromPointer, as a WebCodecs +// VideoColorSpaceInit. `undefined` passes no options at all. +type ColorSpaceInit = { + primaries?: string; + transfer?: string; + matrix?: string; + fullRange?: boolean; +}; + +// The samples of the NV12 test frame (test_yuv_frame in PlatformContext.h): +// red on the left half, green on the right, encoded as BT.709 limited range. +const RED = [63, 102, 240]; +const GREEN = [173, 42, 26]; + +// The luma weights (Kr, Kb) of the YCbCr matrices. +const MATRICES = { + bt709: [0.2126, 0.0722], + smpte170m: [0.299, 0.114], +} as const; + +// What the external texture gives for a [Y, Cb, Cr] sample read with `matrix` +// and `fullRange`, with the BT.709 primaries and transfer function the buffer +// declares, on an sRGB canvas: YCbCr to R'G'B', the BT.709 OETF undone, the +// sRGB one applied. The primaries are the same, so no gamut conversion. +const expectedRgb = ( + [y8, cb8, cr8]: number[], + matrix: keyof typeof MATRICES, + fullRange: boolean, +): Rgb => { + const [kr, kb] = MATRICES[matrix]; + const kg = 1 - kr - kb; + const y = fullRange ? y8 / 255 : (y8 - 16) / 219; + const cb = fullRange ? (cb8 - 128) / 255 : (cb8 - 128) / 224; + const cr = fullRange ? (cr8 - 128) / 255 : (cr8 - 128) / 224; + const r = y + 2 * (1 - kr) * cr; + const b = y + 2 * (1 - kb) * cb; + const g = (y - kr * r - kb * b) / kg; + return [r, g, b].map((v) => { + const c = Math.min(Math.max(v, 0), 1); + const linear = + c < 0.081 ? c / 4.5 : Math.pow((c + 0.099) / 1.099, 1 / 0.45); + const srgb = + linear <= 0.0031308 + ? 12.92 * linear + : 1.055 * Math.pow(linear, 1 / 2.4) - 0.055; + return Math.round(srgb * 255); + }); +}; + +// Wraps the test frame's own pointer (a CVPixelBufferRef carrying BT.709 +// limited range attachments on Apple platforms) with +// createNativeBufferFromPointer, passing `colorSpace` when it is set, and +// samples the result through importExternalTexture onto the canvas. +const render = (colorSpace: ColorSpaceInit | undefined) => + client.eval<{ colorSpace: ColorSpaceInit | null }, EvalResult>( + ({ device, gpu, ctx, canvas, colorSpace: init }) => { + if ( + !device.features.has( + "shared-texture-memory-iosurface" as GPUFeatureName, + ) + ) { + // Android reads a YUV AHardwareBuffer through Vulkan's YCbCr + // sampler, whose results these expectations do not model. + return { + kind: "skip", + reason: "the expectations are for CVPixelBuffer (Apple platforms)", + }; + } + const rnwgpu = RNWebGPU as unknown as { + createTestPixelBuffer?: ( + width: number, + height: number, + ) => { handle: bigint; release(): void }; + }; + if (typeof rnwgpu.createTestPixelBuffer !== "function") { + return { + kind: "skip", + reason: "RNWebGPU.createTestPixelBuffer is unavailable", + }; + } + + let pixelBuffer: { handle: bigint; release(): void }; + let frame: ReturnType; + try { + pixelBuffer = rnwgpu.createTestPixelBuffer(64, 64); + frame = + init === null + ? RNWebGPU.createNativeBufferFromPointer(pixelBuffer.handle) + : RNWebGPU.createNativeBufferFromPointer(pixelBuffer.handle, { + colorSpace: init, + }); + // The frame holds its own reference. + pixelBuffer.release(); + } catch (e) { + return { kind: "fail", reason: `${(e as Error).message ?? e}` }; + } + + try { + const externalTexture = device.importExternalTexture({ + source: frame, + label: "yuv-pointer-frame", + }); + const module = device.createShaderModule({ + code: /* wgsl */ ` + struct VsOut { + @builtin(position) position: vec4f, + @location(0) uv: vec2f, + }; + + @vertex fn vs(@builtin(vertex_index) vid: u32) -> VsOut { + var positions = array( + vec2f(-1.0, -3.0), + vec2f(-1.0, 1.0), + vec2f( 3.0, 1.0), + ); + var uvs = array( + vec2f(0.0, 2.0), + vec2f(0.0, 0.0), + vec2f(2.0, 0.0), + ); + var out: VsOut; + out.position = vec4f(positions[vid], 0.0, 1.0); + out.uv = uvs[vid]; + return out; + } + + @group(0) @binding(0) var srcTex: texture_external; + @group(0) @binding(1) var srcSampler: sampler; + + @fragment fn fs(in: VsOut) -> @location(0) vec4f { + return textureSampleBaseClampToEdge(srcTex, srcSampler, in.uv); + } + `, + }); + const pipeline = device.createRenderPipeline({ + layout: "auto", + vertex: { module, entryPoint: "vs" }, + fragment: { + module, + entryPoint: "fs", + targets: [{ format: gpu.getPreferredCanvasFormat() }], + }, + primitive: { topology: "triangle-list" }, + }); + const sampler = device.createSampler({ + magFilter: "linear", + minFilter: "linear", + }); + const bindGroup = device.createBindGroup({ + layout: pipeline.getBindGroupLayout(0), + entries: [ + { binding: 0, resource: externalTexture }, + { binding: 1, resource: sampler }, + ], + }); + + const encoder = device.createCommandEncoder(); + const pass = encoder.beginRenderPass({ + colorAttachments: [ + { + view: ctx.getCurrentTexture().createView(), + clearValue: { r: 0, g: 0, b: 0, a: 1 }, + loadOp: "clear", + storeOp: "store", + }, + ], + }); + pass.setPipeline(pipeline); + pass.setBindGroup(0, bindGroup); + pass.draw(3); + pass.end(); + device.queue.submit([encoder.finish()]); + externalTexture.destroy(); + + return canvas + .getImageData() + .then( + (image: { + data: number[]; + width: number; + height: number; + format: string; + }) => { + frame.release(); + const bgra = image.format === "bgra8unorm"; + const pixel = (x: number, y: number): Rgb => { + const i = (y * image.width + x) * 4; + return bgra + ? [image.data[i + 2], image.data[i + 1], image.data[i]] + : [image.data[i], image.data[i + 1], image.data[i + 2]]; + }; + const midY = Math.floor(image.height / 2); + return { + kind: "ok" as const, + left: pixel(Math.floor(image.width / 4), midY), + right: pixel(Math.floor((image.width * 3) / 4), midY), + }; + }, + ); + } catch (e) { + frame.release(); + return { kind: "fail", reason: `${(e as Error).message ?? e}` }; + } + }, + { colorSpace: colorSpace ?? null }, + ); + +// 8-bit YCbCr quantization, the bilinear sample and the transfer function +// round trip leave a few levels of slack. +const TOLERANCE = 6; + +const expectColor = (actual: Rgb, expected: Rgb) => { + expected.forEach((channel, i) => { + expect(Math.abs(actual[i] - channel)).toBeLessThanOrEqual(TOLERANCE); + }); +}; + +// The largest per-channel difference between two colors. +const distance = (a: Rgb, b: Rgb) => + Math.max(...a.map((channel, i) => Math.abs(channel - b[i]))); + +const run = async (colorSpace: ColorSpaceInit | undefined) => { + const result = await render(colorSpace); + if (result.kind === "skip") { + console.log(`NativeBufferColorSpace: skipping (${result.reason})`); + return null; + } + if (result.kind === "fail") { + throw new Error(`NativeBufferColorSpace: ${result.reason}`); + } + return result; +}; + +describe("createNativeBufferFromPointer colorSpace", () => { + it("reads the buffer's own attachments without options", async () => { + const result = await run(undefined); + if (!result) { + return; + } + expectColor(result.left, expectedRgb(RED, "bt709", false)); + expectColor(result.right, expectedRgb(GREEN, "bt709", false)); + expectColor(result.left, [255, 0, 0]); + expectColor(result.right, [0, 255, 0]); + }); + + it("keeps the attachments for the fields an empty colorSpace leaves out", async () => { + const result = await run({}); + if (!result) { + return; + } + expectColor(result.left, [255, 0, 0]); + expectColor(result.right, [0, 255, 0]); + }); + + it('reads the samples with the BT.709 matrix for matrix: "bt709"', async () => { + const result = await run({ matrix: "bt709" }); + if (!result) { + return; + } + expectColor(result.left, expectedRgb(RED, "bt709", false)); + expectColor(result.right, expectedRgb(GREEN, "bt709", false)); + }); + + it('reads the samples with the BT.601 matrix for matrix: "smpte170m"', async () => { + const result = await run({ matrix: "smpte170m" }); + if (!result) { + return; + } + const red = expectedRgb(RED, "smpte170m", false); + const green = expectedRgb(GREEN, "smpte170m", false); + expectColor(result.left, red); + expectColor(result.right, green); + // The option really changes the result: far from the BT.709 colors. + expect(distance(red, [255, 0, 0])).toBeGreaterThan(3 * TOLERANCE); + expect(distance(result.left, [255, 0, 0])).toBeGreaterThan(2 * TOLERANCE); + }); + + it("reads the samples as full range for fullRange: true", async () => { + const result = await run({ fullRange: true }); + if (!result) { + return; + } + const red = expectedRgb(RED, "bt709", true); + const green = expectedRgb(GREEN, "bt709", true); + expectColor(result.left, red); + expectColor(result.right, green); + expect(distance(red, [255, 0, 0])).toBeGreaterThan(3 * TOLERANCE); + expect(distance(result.left, [255, 0, 0])).toBeGreaterThan(2 * TOLERANCE); + }); + + it("reads the samples as limited range for fullRange: false", async () => { + // The buffer is limited range already, so the colors stay put; the case + // checks that false is read as limited and not as "unset" or full. + const result = await run({ fullRange: false }); + if (!result) { + return; + } + expectColor(result.left, [255, 0, 0]); + expectColor(result.right, [0, 255, 0]); + }); + + it("combines matrix and fullRange", async () => { + const result = await run({ matrix: "smpte170m", fullRange: true }); + if (!result) { + return; + } + expectColor(result.left, expectedRgb(RED, "smpte170m", true)); + expectColor(result.right, expectedRgb(GREEN, "smpte170m", true)); + }); +}); From 07f9669a63282d7df15c0d48cf4f11f01e44c1eb Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 11:33:45 +0200 Subject: [PATCH 3/9] =?UTF-8?q?refactor(=F0=9F=8E=9E=EF=B8=8F):=20take=20a?= =?UTF-8?q?=20NativeBufferColorSpace=20in=20createNativeBufferFromPointer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The colorSpace option is now the NativeBufferColorSpace that importExternalTexture's sourceColorSpace takes, read by the same parser, instead of a new WebCodecs-shaped type. createTestPixelBuffer and the e2e spec that needed it are gone. --- packages/webgpu/apple/ApplePlatformContext.h | 3 - packages/webgpu/apple/ApplePlatformContext.mm | 22 +- packages/webgpu/cpp/rnwgpu/PlatformContext.h | 10 - packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h | 85 ++--- .../__tests__/NativeBufferColorSpace.spec.ts | 320 ------------------ packages/webgpu/src/types.ts | 13 +- 6 files changed, 26 insertions(+), 427 deletions(-) delete mode 100644 packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts diff --git a/packages/webgpu/apple/ApplePlatformContext.h b/packages/webgpu/apple/ApplePlatformContext.h index db74ba3795..0f9f767c7d 100644 --- a/packages/webgpu/apple/ApplePlatformContext.h +++ b/packages/webgpu/apple/ApplePlatformContext.h @@ -45,9 +45,6 @@ class ApplePlatformContext : public PlatformContext { VideoFrameHandle createTestVideoFrame(uint32_t width, uint32_t height, VideoPixelFormat format) override; - VideoFrameHandle createTestPixelBuffer(uint32_t width, - uint32_t height) override; - VideoFrameHandle createNativeBuffer(uint32_t width, uint32_t height, wgpu::TextureFormat format, bool displayP3) override; diff --git a/packages/webgpu/apple/ApplePlatformContext.mm b/packages/webgpu/apple/ApplePlatformContext.mm index 82b5fb7019..f7803951cc 100644 --- a/packages/webgpu/apple/ApplePlatformContext.mm +++ b/packages/webgpu/apple/ApplePlatformContext.mm @@ -578,10 +578,8 @@ ImageData renderViewIntoPixels(const ResolvedSnapshot &snapshot, // The NV12 variant of createTestVideoFrame: a biplanar BT.709 limited-range // frame, red on the left half and green on the right, whose attachments // declare its color space the way the decoder's frames do, so that the -// conversion of importExternalTexture is fully determined. The caller owns -// the returned reference. -static CVPixelBufferRef createTestYuvPixelBuffer(uint32_t width, - uint32_t height) { +// conversion of importExternalTexture is fully determined. +static VideoFrameHandle createTestYuvFrame(uint32_t width, uint32_t height) { NSDictionary *attrs = @{ (NSString *)kCVPixelBufferIOSurfacePropertiesKey : @{}, (NSString *)kCVPixelBufferMetalCompatibilityKey : @YES, @@ -631,11 +629,7 @@ static CVPixelBufferRef createTestYuvPixelBuffer(uint32_t width, } } CVPixelBufferUnlockBaseAddress(pixelBuffer, 0); - return pixelBuffer; -} -static VideoFrameHandle createTestYuvFrame(uint32_t width, uint32_t height) { - CVPixelBufferRef pixelBuffer = createTestYuvPixelBuffer(width, height); try { auto handle = wrapCVPixelBuffer(pixelBuffer); CFRelease(pixelBuffer); // wrapCVPixelBuffer retained its own reference @@ -699,18 +693,6 @@ static VideoFrameHandle createTestYuvFrame(uint32_t width, uint32_t height) { return handle; } -VideoFrameHandle ApplePlatformContext::createTestPixelBuffer(uint32_t width, - uint32_t height) { - CVPixelBufferRef pixelBuffer = createTestYuvPixelBuffer(width, height); - VideoFrameHandle handle; - handle.handle = pixelBuffer; - handle.width = width; - handle.height = height; - handle.pixelFormat = VideoPixelFormat::NV12; - handle.deleter = [pixelBuffer]() { CFRelease(pixelBuffer); }; - return handle; -} - // An IOSurface-backed pixel buffer that Dawn imports as a render target and // Core Animation displays as layer contents (NativeBufferView). The surface is // tagged with its color space (kIOSurfaceColorSpace), which Core Animation diff --git a/packages/webgpu/cpp/rnwgpu/PlatformContext.h b/packages/webgpu/cpp/rnwgpu/PlatformContext.h index fa9ec19be1..f9f96d652a 100644 --- a/packages/webgpu/cpp/rnwgpu/PlatformContext.h +++ b/packages/webgpu/cpp/rnwgpu/PlatformContext.h @@ -228,16 +228,6 @@ class PlatformContext { virtual VideoFrameHandle createTestVideoFrame(uint32_t width, uint32_t height, VideoPixelFormat format) = 0; - // Test only (the e2e specs of createNativeBufferFromPointer): the NV12 test - // frame as the pointer createNativeBufferFromPointer takes, in `handle`. A - // CVPixelBufferRef carrying the frame's color attachments on Apple - // platforms, which is not importable as is; the frame's own AHardwareBuffer* - // elsewhere. - virtual VideoFrameHandle createTestPixelBuffer(uint32_t width, - uint32_t height) { - return createTestVideoFrame(width, height, VideoPixelFormat::NV12); - } - // Allocate an empty, GPU-renderable buffer that a NativeBufferView can // display: an AHardwareBuffer (Android) or an IOSurface (Apple platforms), // with premultiplied pixels in `format`, tagged with `displayP3` or sRGB diff --git a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h index a4b10a920d..3c067b23f9 100644 --- a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h +++ b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h @@ -17,6 +17,7 @@ #include "GPU.h" #include "GPUCanvasContext.h" #include "GPUDevice.h" +#include "GPUExternalTextureDescriptor.h" #include "GPUSharedFenceState.h" #include "GPUTexture.h" #include "ImageBitmap.h" @@ -317,26 +318,15 @@ class RNWebGPU : public NativeObject { return std::make_shared(std::move(frame)); } - // Test only, left out of the TypeScript declarations: the NV12 test frame as - // a buffer whose `handle` is the pointer createNativeBufferFromPointer takes - // (PlatformContext::createTestPixelBuffer). Pass the handle there; do not - // import the buffer itself. - std::shared_ptr createTestPixelBuffer(double width, - double height) { - auto frame = _platformContext->createTestPixelBuffer( - static_cast(width), static_cast(height)); - return std::make_shared(std::move(frame)); - } - // Wrap a CVPixelBufferRef / AHardwareBuffer* pointer (typed as void* via // BigInt on the JS side) into one of our VideoFrames. The native side // CFRetains / acquires so the caller can release immediately. // // createNativeBufferFromPointer(pointer, { colorSpace? }): `colorSpace` (a - // WebCodecs VideoColorSpaceInit, e.g. a VideoFrame's colorSpace) says how to - // read a YUV buffer that carries no color information of its own, as an - // AHardwareBuffer from a MediaCodec ImageReader. The fields it sets replace - // what the buffer says. + // NativeBufferColorSpace, as importExternalTexture's sourceColorSpace) says + // how to read a YUV buffer that carries no color information of its own, as + // an AHardwareBuffer from a MediaCodec ImageReader. The members it sets + // replace what the buffer says. jsi::Value createNativeBufferFromPointer(jsi::Runtime &runtime, const jsi::Value & /*thisVal*/, const jsi::Value *args, @@ -351,60 +341,27 @@ class RNWebGPU : public NativeObject { auto colorSpace = args[1].getObject(runtime).getProperty(runtime, "colorSpace"); if (colorSpace.isObject()) { - applyVideoColorSpace(runtime, colorSpace.getObject(runtime), - handle.colorSpace); + auto override = external_texture_color_space::parse( + runtime, colorSpace.getObject(runtime)); + auto &reported = handle.colorSpace; + if (override.matrix) { + reported.matrix = override.matrix; + } + if (override.range) { + reported.range = override.range; + } + if (override.primaries) { + reported.primaries = override.primaries; + } + if (override.transfer) { + reported.transfer = override.transfer; + } } } return JSIConverter>::toJSI( runtime, std::make_shared(std::move(handle))); } - // A WebCodecs VideoColorSpaceInit onto the color space of a native frame. - static void applyVideoColorSpace(jsi::Runtime &runtime, - const jsi::Object &init, - VideoFrameColorSpace &colorSpace) { - auto field = [&](const char *name) -> std::string { - auto value = init.getProperty(runtime, name); - return value.isString() ? value.getString(runtime).utf8(runtime) : ""; - }; - const auto primaries = field("primaries"); - if (primaries == "bt709") { - colorSpace.primaries = wgpu::ColorSpacePrimariesDawn::SRGB; - } else if (primaries == "bt470bg" || primaries == "smpte170m") { - colorSpace.primaries = wgpu::ColorSpacePrimariesDawn::Rec601; - } else if (primaries == "bt2020") { - colorSpace.primaries = wgpu::ColorSpacePrimariesDawn::Rec2020; - } else if (primaries == "smpte432") { - colorSpace.primaries = wgpu::ColorSpacePrimariesDawn::DisplayP3; - } - const auto transfer = field("transfer"); - if (transfer == "bt709" || transfer == "smpte170m") { - colorSpace.transfer = wgpu::ColorSpaceTransferDawn::SMPTE_170M; - } else if (transfer == "iec61966-2-1") { - colorSpace.transfer = wgpu::ColorSpaceTransferDawn::SRGB; - } else if (transfer == "linear") { - colorSpace.transfer = wgpu::ColorSpaceTransferDawn::Identity; - } else if (transfer == "pq") { - colorSpace.transfer = wgpu::ColorSpaceTransferDawn::PQ; - } else if (transfer == "hlg") { - colorSpace.transfer = wgpu::ColorSpaceTransferDawn::HLG; - } - const auto matrix = field("matrix"); - if (matrix == "bt709") { - colorSpace.matrix = wgpu::ColorSpaceYCbCrMatrixDawn::Rec709; - } else if (matrix == "bt470bg" || matrix == "smpte170m") { - colorSpace.matrix = wgpu::ColorSpaceYCbCrMatrixDawn::Rec601; - } else if (matrix == "bt2020-ncl") { - colorSpace.matrix = wgpu::ColorSpaceYCbCrMatrixDawn::Rec2020; - } - auto fullRange = init.getProperty(runtime, "fullRange"); - if (fullRange.isBool()) { - colorSpace.range = fullRange.getBool() - ? wgpu::ColorSpaceYCbCrRangeDawn::Full - : wgpu::ColorSpaceYCbCrRangeDawn::Narrow; - } - } - // createNativeBuffer(width, height, { format?, colorSpace? }): an empty // native buffer (AHardwareBuffer / IOSurface) to render into through // importSharedTextureMemory() and display with presentNativeBuffer(). @@ -656,8 +613,6 @@ class RNWebGPU : public NativeObject { &RNWebGPU::loadVideoFrame); installMethod(runtime, prototype, "createTestVideoFrame", &RNWebGPU::createTestVideoFrame); - installMethod(runtime, prototype, "createTestPixelBuffer", - &RNWebGPU::createTestPixelBuffer); installMethod(runtime, prototype, "createNativeBufferFromPointer", &RNWebGPU::createNativeBufferFromPointer); installMethodWithRuntime(runtime, prototype, "importDevice", diff --git a/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts deleted file mode 100644 index 0538121913..0000000000 --- a/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts +++ /dev/null @@ -1,320 +0,0 @@ -import { client } from "./setup"; - -// A pixel as [r, g, b], 0..255. -type Rgb = number[]; - -type EvalResult = - | { kind: "skip"; reason: string } - | { kind: "fail"; reason: string } - | { kind: "ok"; left: Rgb; right: Rgb }; - -// The colorSpace option of createNativeBufferFromPointer, as a WebCodecs -// VideoColorSpaceInit. `undefined` passes no options at all. -type ColorSpaceInit = { - primaries?: string; - transfer?: string; - matrix?: string; - fullRange?: boolean; -}; - -// The samples of the NV12 test frame (test_yuv_frame in PlatformContext.h): -// red on the left half, green on the right, encoded as BT.709 limited range. -const RED = [63, 102, 240]; -const GREEN = [173, 42, 26]; - -// The luma weights (Kr, Kb) of the YCbCr matrices. -const MATRICES = { - bt709: [0.2126, 0.0722], - smpte170m: [0.299, 0.114], -} as const; - -// What the external texture gives for a [Y, Cb, Cr] sample read with `matrix` -// and `fullRange`, with the BT.709 primaries and transfer function the buffer -// declares, on an sRGB canvas: YCbCr to R'G'B', the BT.709 OETF undone, the -// sRGB one applied. The primaries are the same, so no gamut conversion. -const expectedRgb = ( - [y8, cb8, cr8]: number[], - matrix: keyof typeof MATRICES, - fullRange: boolean, -): Rgb => { - const [kr, kb] = MATRICES[matrix]; - const kg = 1 - kr - kb; - const y = fullRange ? y8 / 255 : (y8 - 16) / 219; - const cb = fullRange ? (cb8 - 128) / 255 : (cb8 - 128) / 224; - const cr = fullRange ? (cr8 - 128) / 255 : (cr8 - 128) / 224; - const r = y + 2 * (1 - kr) * cr; - const b = y + 2 * (1 - kb) * cb; - const g = (y - kr * r - kb * b) / kg; - return [r, g, b].map((v) => { - const c = Math.min(Math.max(v, 0), 1); - const linear = - c < 0.081 ? c / 4.5 : Math.pow((c + 0.099) / 1.099, 1 / 0.45); - const srgb = - linear <= 0.0031308 - ? 12.92 * linear - : 1.055 * Math.pow(linear, 1 / 2.4) - 0.055; - return Math.round(srgb * 255); - }); -}; - -// Wraps the test frame's own pointer (a CVPixelBufferRef carrying BT.709 -// limited range attachments on Apple platforms) with -// createNativeBufferFromPointer, passing `colorSpace` when it is set, and -// samples the result through importExternalTexture onto the canvas. -const render = (colorSpace: ColorSpaceInit | undefined) => - client.eval<{ colorSpace: ColorSpaceInit | null }, EvalResult>( - ({ device, gpu, ctx, canvas, colorSpace: init }) => { - if ( - !device.features.has( - "shared-texture-memory-iosurface" as GPUFeatureName, - ) - ) { - // Android reads a YUV AHardwareBuffer through Vulkan's YCbCr - // sampler, whose results these expectations do not model. - return { - kind: "skip", - reason: "the expectations are for CVPixelBuffer (Apple platforms)", - }; - } - const rnwgpu = RNWebGPU as unknown as { - createTestPixelBuffer?: ( - width: number, - height: number, - ) => { handle: bigint; release(): void }; - }; - if (typeof rnwgpu.createTestPixelBuffer !== "function") { - return { - kind: "skip", - reason: "RNWebGPU.createTestPixelBuffer is unavailable", - }; - } - - let pixelBuffer: { handle: bigint; release(): void }; - let frame: ReturnType; - try { - pixelBuffer = rnwgpu.createTestPixelBuffer(64, 64); - frame = - init === null - ? RNWebGPU.createNativeBufferFromPointer(pixelBuffer.handle) - : RNWebGPU.createNativeBufferFromPointer(pixelBuffer.handle, { - colorSpace: init, - }); - // The frame holds its own reference. - pixelBuffer.release(); - } catch (e) { - return { kind: "fail", reason: `${(e as Error).message ?? e}` }; - } - - try { - const externalTexture = device.importExternalTexture({ - source: frame, - label: "yuv-pointer-frame", - }); - const module = device.createShaderModule({ - code: /* wgsl */ ` - struct VsOut { - @builtin(position) position: vec4f, - @location(0) uv: vec2f, - }; - - @vertex fn vs(@builtin(vertex_index) vid: u32) -> VsOut { - var positions = array( - vec2f(-1.0, -3.0), - vec2f(-1.0, 1.0), - vec2f( 3.0, 1.0), - ); - var uvs = array( - vec2f(0.0, 2.0), - vec2f(0.0, 0.0), - vec2f(2.0, 0.0), - ); - var out: VsOut; - out.position = vec4f(positions[vid], 0.0, 1.0); - out.uv = uvs[vid]; - return out; - } - - @group(0) @binding(0) var srcTex: texture_external; - @group(0) @binding(1) var srcSampler: sampler; - - @fragment fn fs(in: VsOut) -> @location(0) vec4f { - return textureSampleBaseClampToEdge(srcTex, srcSampler, in.uv); - } - `, - }); - const pipeline = device.createRenderPipeline({ - layout: "auto", - vertex: { module, entryPoint: "vs" }, - fragment: { - module, - entryPoint: "fs", - targets: [{ format: gpu.getPreferredCanvasFormat() }], - }, - primitive: { topology: "triangle-list" }, - }); - const sampler = device.createSampler({ - magFilter: "linear", - minFilter: "linear", - }); - const bindGroup = device.createBindGroup({ - layout: pipeline.getBindGroupLayout(0), - entries: [ - { binding: 0, resource: externalTexture }, - { binding: 1, resource: sampler }, - ], - }); - - const encoder = device.createCommandEncoder(); - const pass = encoder.beginRenderPass({ - colorAttachments: [ - { - view: ctx.getCurrentTexture().createView(), - clearValue: { r: 0, g: 0, b: 0, a: 1 }, - loadOp: "clear", - storeOp: "store", - }, - ], - }); - pass.setPipeline(pipeline); - pass.setBindGroup(0, bindGroup); - pass.draw(3); - pass.end(); - device.queue.submit([encoder.finish()]); - externalTexture.destroy(); - - return canvas - .getImageData() - .then( - (image: { - data: number[]; - width: number; - height: number; - format: string; - }) => { - frame.release(); - const bgra = image.format === "bgra8unorm"; - const pixel = (x: number, y: number): Rgb => { - const i = (y * image.width + x) * 4; - return bgra - ? [image.data[i + 2], image.data[i + 1], image.data[i]] - : [image.data[i], image.data[i + 1], image.data[i + 2]]; - }; - const midY = Math.floor(image.height / 2); - return { - kind: "ok" as const, - left: pixel(Math.floor(image.width / 4), midY), - right: pixel(Math.floor((image.width * 3) / 4), midY), - }; - }, - ); - } catch (e) { - frame.release(); - return { kind: "fail", reason: `${(e as Error).message ?? e}` }; - } - }, - { colorSpace: colorSpace ?? null }, - ); - -// 8-bit YCbCr quantization, the bilinear sample and the transfer function -// round trip leave a few levels of slack. -const TOLERANCE = 6; - -const expectColor = (actual: Rgb, expected: Rgb) => { - expected.forEach((channel, i) => { - expect(Math.abs(actual[i] - channel)).toBeLessThanOrEqual(TOLERANCE); - }); -}; - -// The largest per-channel difference between two colors. -const distance = (a: Rgb, b: Rgb) => - Math.max(...a.map((channel, i) => Math.abs(channel - b[i]))); - -const run = async (colorSpace: ColorSpaceInit | undefined) => { - const result = await render(colorSpace); - if (result.kind === "skip") { - console.log(`NativeBufferColorSpace: skipping (${result.reason})`); - return null; - } - if (result.kind === "fail") { - throw new Error(`NativeBufferColorSpace: ${result.reason}`); - } - return result; -}; - -describe("createNativeBufferFromPointer colorSpace", () => { - it("reads the buffer's own attachments without options", async () => { - const result = await run(undefined); - if (!result) { - return; - } - expectColor(result.left, expectedRgb(RED, "bt709", false)); - expectColor(result.right, expectedRgb(GREEN, "bt709", false)); - expectColor(result.left, [255, 0, 0]); - expectColor(result.right, [0, 255, 0]); - }); - - it("keeps the attachments for the fields an empty colorSpace leaves out", async () => { - const result = await run({}); - if (!result) { - return; - } - expectColor(result.left, [255, 0, 0]); - expectColor(result.right, [0, 255, 0]); - }); - - it('reads the samples with the BT.709 matrix for matrix: "bt709"', async () => { - const result = await run({ matrix: "bt709" }); - if (!result) { - return; - } - expectColor(result.left, expectedRgb(RED, "bt709", false)); - expectColor(result.right, expectedRgb(GREEN, "bt709", false)); - }); - - it('reads the samples with the BT.601 matrix for matrix: "smpte170m"', async () => { - const result = await run({ matrix: "smpte170m" }); - if (!result) { - return; - } - const red = expectedRgb(RED, "smpte170m", false); - const green = expectedRgb(GREEN, "smpte170m", false); - expectColor(result.left, red); - expectColor(result.right, green); - // The option really changes the result: far from the BT.709 colors. - expect(distance(red, [255, 0, 0])).toBeGreaterThan(3 * TOLERANCE); - expect(distance(result.left, [255, 0, 0])).toBeGreaterThan(2 * TOLERANCE); - }); - - it("reads the samples as full range for fullRange: true", async () => { - const result = await run({ fullRange: true }); - if (!result) { - return; - } - const red = expectedRgb(RED, "bt709", true); - const green = expectedRgb(GREEN, "bt709", true); - expectColor(result.left, red); - expectColor(result.right, green); - expect(distance(red, [255, 0, 0])).toBeGreaterThan(3 * TOLERANCE); - expect(distance(result.left, [255, 0, 0])).toBeGreaterThan(2 * TOLERANCE); - }); - - it("reads the samples as limited range for fullRange: false", async () => { - // The buffer is limited range already, so the colors stay put; the case - // checks that false is read as limited and not as "unset" or full. - const result = await run({ fullRange: false }); - if (!result) { - return; - } - expectColor(result.left, [255, 0, 0]); - expectColor(result.right, [0, 255, 0]); - }); - - it("combines matrix and fullRange", async () => { - const result = await run({ matrix: "smpte170m", fullRange: true }); - if (!result) { - return; - } - expectColor(result.left, expectedRgb(RED, "smpte170m", true)); - expectColor(result.right, expectedRgb(GREEN, "smpte170m", true)); - }); -}); diff --git a/packages/webgpu/src/types.ts b/packages/webgpu/src/types.ts index 540d382adb..aaaf7dd108 100644 --- a/packages/webgpu/src/types.ts +++ b/packages/webgpu/src/types.ts @@ -334,16 +334,11 @@ export interface GPUSharedTextureMemory { export interface CreateNativeBufferFromPointerOptions { /** * How to read a YUV buffer that carries no color information of its own - * (an AHardwareBuffer from a MediaCodec ImageReader, for instance): a - * WebCodecs `VideoColorSpaceInit`, such as a `VideoFrame`'s `colorSpace`. - * The fields it sets replace what the buffer says. + * (an AHardwareBuffer from a MediaCodec ImageReader, for instance), as + * `sourceColorSpace` in `importExternalTexture()`. The members it sets + * replace what the buffer says. */ - colorSpace?: { - primaries?: string | null; - transfer?: string | null; - matrix?: string | null; - fullRange?: boolean | null; - }; + colorSpace?: NativeBufferColorSpace; } /** From 8d20ff1d5a9ea3f21c3e15cce5eeaaa074dc4ec0 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 12:00:39 +0200 Subject: [PATCH 4/9] =?UTF-8?q?test(=F0=9F=8E=9E=EF=B8=8F):=20the=20colorS?= =?UTF-8?q?pace=20of=20createNativeBufferFromPointer=20reads=20like=20sour?= =?UTF-8?q?ceColorSpace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wraps the AHardwareBuffer of the NV12 test frame with and without the option and checks the result against importExternalTexture's sourceColorSpace for the same members. Android only: on Apple platforms no JS API gives a CVPixelBufferRef to wrap. --- .../__tests__/NativeBufferColorSpace.spec.ts | 277 ++++++++++++++++++ 1 file changed, 277 insertions(+) create mode 100644 packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts diff --git a/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts new file mode 100644 index 0000000000..5746f0a333 --- /dev/null +++ b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts @@ -0,0 +1,277 @@ +import { client } from "./setup"; + +// A pixel as [r, g, b, a], 0..255. +type Rgba = number[]; + +type Samples = { left: Rgba; right: Rgba }; + +type EvalResult = + | { kind: "skip"; reason: string } + | { kind: "fail"; reason: string } + | { + kind: "ok"; + // The pointer wrapped without options, imported as is. + plain: Samples; + // The pointer wrapped with the colorSpace option, imported as is. + wrapped: Samples; + // The pointer wrapped without options, imported with the same color + // space as sourceColorSpace. + imported: Samples; + }; + +// The override: neither what the test frame reports (BT.709 limited range) +// nor the fallback for a buffer that reports nothing (BT.601 limited range), +// so that it changes the result whatever the buffer says. +const OVERRIDE = { matrix: "rec2020", range: "full" }; + +describe("createNativeBufferFromPointer colorSpace", () => { + // The option sets the color space of the wrapped buffer: importing it must + // give what importExternalTexture's sourceColorSpace gives for the same + // members, and not what the buffer says on its own. It is compared with + // sourceColorSpace rather than with computed colors, so that it holds + // whatever conversion the platform does. + // + // Android only: the pointer comes from the handle of the NV12 test frame, + // an AHardwareBuffer*, which createNativeBufferFromPointer takes. On Apple + // platforms the handle is an IOSurfaceRef, while createNativeBufferFromPointer + // takes a CVPixelBufferRef, which nothing in JS gives. + it("reads the buffer with the color space it is given", async () => { + const result = await client.eval<{ override: typeof OVERRIDE }, EvalResult>( + ({ device, override }) => { + if ( + !device.features.has( + "shared-texture-memory-ahardware-buffer" as GPUFeatureName, + ) + ) { + return { + kind: "skip", + reason: "the pointer of a test frame is an AHardwareBuffer only", + }; + } + // Android samples YUV buffers through Dawn's opaque YCbCr path, which + // the device only has when the adapter supports Vulkan YCbCr sampling. + if ( + !device.features.has( + "opaque-ycbcr-android-for-external-texture" as GPUFeatureName, + ) + ) { + return { + kind: "skip", + reason: "the device cannot sample YUV hardware buffers", + }; + } + + type Frame = ReturnType; + // Typed loosely so that the spec also builds against a version + // without the option, where it fails rather than not compiling. + const native = RNWebGPU as unknown as { + createNativeBufferFromPointer( + pointer: bigint, + options?: unknown, + ): Frame; + }; + const wrap = (pointer: bigint, options?: unknown) => + native.createNativeBufferFromPointer(pointer, options); + + let source: Frame; + try { + source = RNWebGPU.createTestVideoFrame(64, 64, "nv12"); + } catch (e) { + const message = `${(e as Error).message ?? e}`; + // The platform cannot allocate or fill the YUV layout (Android + // before API 29). + if (message.indexOf("unsupported") !== -1) { + return { kind: "skip", reason: message }; + } + return { kind: "fail", reason: message }; + } + + const frames: Frame[] = [source]; + const release = () => frames.forEach((frame) => frame.release()); + + try { + const plainFrame = wrap(source.handle); + frames.push(plainFrame); + const wrappedFrame = wrap(source.handle, { colorSpace: override }); + frames.push(wrappedFrame); + + const module = device.createShaderModule({ + code: /* wgsl */ ` + struct VsOut { + @builtin(position) position: vec4f, + @location(0) uv: vec2f, + }; + + @vertex fn vs(@builtin(vertex_index) vid: u32) -> VsOut { + var positions = array( + vec2f(-1.0, -3.0), + vec2f(-1.0, 1.0), + vec2f( 3.0, 1.0), + ); + var uvs = array( + vec2f(0.0, 2.0), + vec2f(0.0, 0.0), + vec2f(2.0, 0.0), + ); + var out: VsOut; + out.position = vec4f(positions[vid], 0.0, 1.0); + out.uv = uvs[vid]; + return out; + } + + @group(0) @binding(0) var srcTex: texture_external; + @group(0) @binding(1) var srcSampler: sampler; + + @fragment fn fs(in: VsOut) -> @location(0) vec4f { + return textureSampleBaseClampToEdge(srcTex, srcSampler, in.uv); + } + `, + }); + const pipeline = device.createRenderPipeline({ + layout: "auto", + vertex: { module, entryPoint: "vs" }, + fragment: { + module, + entryPoint: "fs", + targets: [{ format: "rgba8unorm" }], + }, + primitive: { topology: "triangle-list" }, + }); + const sampler = device.createSampler({ + magFilter: "linear", + minFilter: "linear", + }); + + const SIZE = 64; + const BYTES_PER_ROW = SIZE * 4; + + // Samples `frame` onto a 64x64 RGBA texture and reads it back. + const draw = ( + frame: Frame, + sourceColorSpace?: typeof override, + ): Promise => { + const externalTexture = device.importExternalTexture({ + source: frame, + ...(sourceColorSpace ? { sourceColorSpace } : {}), + } as unknown as GPUExternalTextureDescriptor); + const target = device.createTexture({ + size: [SIZE, SIZE], + format: "rgba8unorm", + usage: + GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, + }); + const readback = device.createBuffer({ + size: BYTES_PER_ROW * SIZE, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + }); + const bindGroup = device.createBindGroup({ + layout: pipeline.getBindGroupLayout(0), + entries: [ + { binding: 0, resource: externalTexture }, + { binding: 1, resource: sampler }, + ], + }); + const encoder = device.createCommandEncoder(); + const pass = encoder.beginRenderPass({ + colorAttachments: [ + { + view: target.createView(), + clearValue: { r: 0, g: 0, b: 0, a: 1 }, + loadOp: "clear", + storeOp: "store", + }, + ], + }); + pass.setPipeline(pipeline); + pass.setBindGroup(0, bindGroup); + pass.draw(3); + pass.end(); + encoder.copyTextureToBuffer( + { texture: target }, + { buffer: readback, bytesPerRow: BYTES_PER_ROW }, + [SIZE, SIZE], + ); + device.queue.submit([encoder.finish()]); + externalTexture.destroy(); + + return readback.mapAsync(GPUMapMode.READ).then(() => { + const data = new Uint8Array(readback.getMappedRange()); + const pixel = (x: number, y: number): Rgba => { + const i = y * BYTES_PER_ROW + x * 4; + return [data[i], data[i + 1], data[i + 2], data[i + 3]]; + }; + const midY = SIZE / 2; + const samples = { + left: pixel(SIZE / 4, midY), + right: pixel((SIZE * 3) / 4, midY), + }; + readback.unmap(); + readback.destroy(); + target.destroy(); + return samples; + }); + }; + + return draw(plainFrame) + .then((plain) => + draw(wrappedFrame).then((wrapped) => + draw(plainFrame, override).then((imported) => ({ + kind: "ok" as const, + plain, + wrapped, + imported, + })), + ), + ) + .then( + (samples) => { + release(); + return samples; + }, + (e: unknown) => { + release(); + return { + kind: "fail" as const, + reason: `${(e as Error).message ?? e}`, + }; + }, + ); + } catch (e) { + release(); + return { kind: "fail", reason: `${(e as Error).message ?? e}` }; + } + }, + { override: OVERRIDE }, + ); + + if (result.kind === "skip") { + console.log(`NativeBufferColorSpace: skipping (${result.reason})`); + return; + } + if (result.kind === "fail") { + throw new Error(`NativeBufferColorSpace: ${result.reason}`); + } + console.log( + `NativeBufferColorSpace: ${JSON.stringify({ + plain: result.plain, + wrapped: result.wrapped, + imported: result.imported, + })}`, + ); + + // The same conversion as sourceColorSpace, to the level: both resolve + // the same color space for the same buffer. + expect(result.wrapped).toEqual(result.imported); + // And not the buffer's own: the override really took effect. Full range + // BT.2020 is far from limited range BT.709 / BT.601 for saturated red and + // green, so the largest channel difference is well above rounding. + const distance = (a: Rgba, b: Rgba) => + Math.max(...a.map((channel, i) => Math.abs(channel - b[i]))); + expect(distance(result.wrapped.left, result.plain.left)).toBeGreaterThan( + 10, + ); + expect(distance(result.wrapped.right, result.plain.right)).toBeGreaterThan( + 10, + ); + }); +}); From 679a67f88bb662cbb5ac4cb28d95af94967bb079 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 12:11:11 +0200 Subject: [PATCH 5/9] =?UTF-8?q?test(=F0=9F=8E=9E=EF=B8=8F):=20check=20the?= =?UTF-8?q?=20colors=20a=20buffer=20without=20metadata=20gets=20with=20col?= =?UTF-8?q?orSpace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wraps the test frame's AHardwareBuffer with its real color space (BT.709 narrow) and expects pure red and green, the same as sourceColorSpace gives. One submit and one readback for the three draws, and no loose typing. --- .../__tests__/NativeBufferColorSpace.spec.ts | 221 +++++++----------- 1 file changed, 82 insertions(+), 139 deletions(-) diff --git a/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts index 5746f0a333..e37bd0a759 100644 --- a/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts +++ b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts @@ -8,34 +8,26 @@ type Samples = { left: Rgba; right: Rgba }; type EvalResult = | { kind: "skip"; reason: string } | { kind: "fail"; reason: string } - | { - kind: "ok"; - // The pointer wrapped without options, imported as is. - plain: Samples; - // The pointer wrapped with the colorSpace option, imported as is. - wrapped: Samples; - // The pointer wrapped without options, imported with the same color - // space as sourceColorSpace. - imported: Samples; - }; + | { kind: "ok"; plain: Samples; wrapped: Samples; imported: Samples }; -// The override: neither what the test frame reports (BT.709 limited range) -// nor the fallback for a buffer that reports nothing (BT.601 limited range), -// so that it changes the result whatever the buffer says. -const OVERRIDE = { matrix: "rec2020", range: "full" }; +// How the test frame is encoded: red on the left half, green on the right, in +// BT.709 narrow range. Its AHardwareBuffer carries no color metadata, so +// wrapped without options it is read with the platform's guess (BT.601 +// narrow when the driver has none), as a buffer from another library is. +const OVERRIDE = { matrix: "rec709", range: "narrow" } as const; + +const expectColor = (actual: Rgba, expected: Rgba) => { + expected.forEach((channel, i) => { + expect(Math.abs(actual[i] - channel)).toBeLessThanOrEqual(8); + }); +}; describe("createNativeBufferFromPointer colorSpace", () => { - // The option sets the color space of the wrapped buffer: importing it must - // give what importExternalTexture's sourceColorSpace gives for the same - // members, and not what the buffer says on its own. It is compared with - // sourceColorSpace rather than with computed colors, so that it holds - // whatever conversion the platform does. - // - // Android only: the pointer comes from the handle of the NV12 test frame, - // an AHardwareBuffer*, which createNativeBufferFromPointer takes. On Apple - // platforms the handle is an IOSurfaceRef, while createNativeBufferFromPointer - // takes a CVPixelBufferRef, which nothing in JS gives. - it("reads the buffer with the color space it is given", async () => { + // Wrapping with the option must read the buffer with the color space it is + // given, as importExternalTexture's sourceColorSpace does. Android only: the + // pointer is the test frame's AHardwareBuffer*, and on Apple platforms + // nothing in JS gives a CVPixelBufferRef to wrap. + it("reads a buffer without color metadata with the color space it is given", async () => { const result = await client.eval<{ override: typeof OVERRIDE }, EvalResult>( ({ device, override }) => { if ( @@ -48,8 +40,6 @@ describe("createNativeBufferFromPointer colorSpace", () => { reason: "the pointer of a test frame is an AHardwareBuffer only", }; } - // Android samples YUV buffers through Dawn's opaque YCbCr path, which - // the device only has when the adapter supports Vulkan YCbCr sampling. if ( !device.features.has( "opaque-ycbcr-android-for-external-texture" as GPUFeatureName, @@ -61,19 +51,7 @@ describe("createNativeBufferFromPointer colorSpace", () => { }; } - type Frame = ReturnType; - // Typed loosely so that the spec also builds against a version - // without the option, where it fails rather than not compiling. - const native = RNWebGPU as unknown as { - createNativeBufferFromPointer( - pointer: bigint, - options?: unknown, - ): Frame; - }; - const wrap = (pointer: bigint, options?: unknown) => - native.createNativeBufferFromPointer(pointer, options); - - let source: Frame; + let source: ReturnType; try { source = RNWebGPU.createTestVideoFrame(64, 64, "nv12"); } catch (e) { @@ -85,16 +63,17 @@ describe("createNativeBufferFromPointer colorSpace", () => { } return { kind: "fail", reason: message }; } - - const frames: Frame[] = [source]; - const release = () => frames.forEach((frame) => frame.release()); + const plain = RNWebGPU.createNativeBufferFromPointer(source.handle); + const wrapped = RNWebGPU.createNativeBufferFromPointer(source.handle, { + colorSpace: override, + }); + const release = () => { + source.release(); + plain.release(); + wrapped.release(); + }; try { - const plainFrame = wrap(source.handle); - frames.push(plainFrame); - const wrappedFrame = wrap(source.handle, { colorSpace: override }); - frames.push(wrappedFrame); - const module = device.createShaderModule({ code: /* wgsl */ ` struct VsOut { @@ -142,36 +121,27 @@ describe("createNativeBufferFromPointer colorSpace", () => { minFilter: "linear", }); - const SIZE = 64; - const BYTES_PER_ROW = SIZE * 4; - - // Samples `frame` onto a 64x64 RGBA texture and reads it back. - const draw = ( - frame: Frame, - sourceColorSpace?: typeof override, - ): Promise => { - const externalTexture = device.importExternalTexture({ - source: frame, - ...(sourceColorSpace ? { sourceColorSpace } : {}), - } as unknown as GPUExternalTextureDescriptor); + // Each draw fills a 2x1 target, whose pixel centers sample the + // middle of the left (red) and right (green) halves of the frame, + // and lands in its own 256-byte row of one readback buffer. + const draws = [ + { source: plain }, + { source: wrapped }, + { source: plain, sourceColorSpace: override }, + ]; + const readback = device.createBuffer({ + size: 256 * draws.length, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + }); + const encoder = device.createCommandEncoder(); + const externalTextures = draws.map((descriptor, i) => { + const externalTexture = device.importExternalTexture(descriptor); const target = device.createTexture({ - size: [SIZE, SIZE], + size: [2, 1], format: "rgba8unorm", usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, }); - const readback = device.createBuffer({ - size: BYTES_PER_ROW * SIZE, - usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, - }); - const bindGroup = device.createBindGroup({ - layout: pipeline.getBindGroupLayout(0), - entries: [ - { binding: 0, resource: externalTexture }, - { binding: 1, resource: sampler }, - ], - }); - const encoder = device.createCommandEncoder(); const pass = encoder.beginRenderPass({ colorAttachments: [ { @@ -183,59 +153,46 @@ describe("createNativeBufferFromPointer colorSpace", () => { ], }); pass.setPipeline(pipeline); - pass.setBindGroup(0, bindGroup); + pass.setBindGroup( + 0, + device.createBindGroup({ + layout: pipeline.getBindGroupLayout(0), + entries: [ + { binding: 0, resource: externalTexture }, + { binding: 1, resource: sampler }, + ], + }), + ); pass.draw(3); pass.end(); encoder.copyTextureToBuffer( { texture: target }, - { buffer: readback, bytesPerRow: BYTES_PER_ROW }, - [SIZE, SIZE], + { buffer: readback, offset: 256 * i, bytesPerRow: 256 }, + [2, 1], ); - device.queue.submit([encoder.finish()]); - externalTexture.destroy(); - - return readback.mapAsync(GPUMapMode.READ).then(() => { + return externalTexture; + }); + device.queue.submit([encoder.finish()]); + externalTextures.forEach((externalTexture) => + externalTexture.destroy(), + ); + + return readback + .mapAsync(GPUMapMode.READ) + .then(() => { const data = new Uint8Array(readback.getMappedRange()); - const pixel = (x: number, y: number): Rgba => { - const i = y * BYTES_PER_ROW + x * 4; - return [data[i], data[i + 1], data[i + 2], data[i + 3]]; + const samples = (i: number): Samples => ({ + left: Array.from(data.subarray(256 * i, 256 * i + 4)), + right: Array.from(data.subarray(256 * i + 4, 256 * i + 8)), + }); + return { + kind: "ok" as const, + plain: samples(0), + wrapped: samples(1), + imported: samples(2), }; - const midY = SIZE / 2; - const samples = { - left: pixel(SIZE / 4, midY), - right: pixel((SIZE * 3) / 4, midY), - }; - readback.unmap(); - readback.destroy(); - target.destroy(); - return samples; - }); - }; - - return draw(plainFrame) - .then((plain) => - draw(wrappedFrame).then((wrapped) => - draw(plainFrame, override).then((imported) => ({ - kind: "ok" as const, - plain, - wrapped, - imported, - })), - ), - ) - .then( - (samples) => { - release(); - return samples; - }, - (e: unknown) => { - release(); - return { - kind: "fail" as const, - reason: `${(e as Error).message ?? e}`, - }; - }, - ); + }) + .finally(release); } catch (e) { release(); return { kind: "fail", reason: `${(e as Error).message ?? e}` }; @@ -251,27 +208,13 @@ describe("createNativeBufferFromPointer colorSpace", () => { if (result.kind === "fail") { throw new Error(`NativeBufferColorSpace: ${result.reason}`); } - console.log( - `NativeBufferColorSpace: ${JSON.stringify({ - plain: result.plain, - wrapped: result.wrapped, - imported: result.imported, - })}`, - ); + console.log(`NativeBufferColorSpace: ${JSON.stringify(result)}`); - // The same conversion as sourceColorSpace, to the level: both resolve - // the same color space for the same buffer. + // `plain` is not checked: it is off only where the platform guesses + // another color space than the frame's (BT.601 by default), and the log + // shows it. + expectColor(result.wrapped.left, [255, 0, 0, 255]); + expectColor(result.wrapped.right, [0, 255, 0, 255]); expect(result.wrapped).toEqual(result.imported); - // And not the buffer's own: the override really took effect. Full range - // BT.2020 is far from limited range BT.709 / BT.601 for saturated red and - // green, so the largest channel difference is well above rounding. - const distance = (a: Rgba, b: Rgba) => - Math.max(...a.map((channel, i) => Math.abs(channel - b[i]))); - expect(distance(result.wrapped.left, result.plain.left)).toBeGreaterThan( - 10, - ); - expect(distance(result.wrapped.right, result.plain.right)).toBeGreaterThan( - 10, - ); }); }); From b864996fdd21a96e76db033d70a7f70ae34b6a28 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 12:16:42 +0200 Subject: [PATCH 6/9] =?UTF-8?q?test(=F0=9F=8E=9E=EF=B8=8F):=20name=20what?= =?UTF-8?q?=20each=20import=20of=20the=20NativeBufferColorSpace=20spec=20c?= =?UTF-8?q?hecks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The three imports are named (withoutColorSpace, withColorSpace, withSourceColorSpace), the color space is the test frame's own, and a color mismatch shows both pixels. --- .../__tests__/NativeBufferColorSpace.spec.ts | 149 ++++++++++-------- 1 file changed, 87 insertions(+), 62 deletions(-) diff --git a/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts index e37bd0a759..e407bddb4f 100644 --- a/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts +++ b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts @@ -3,33 +3,50 @@ import { client } from "./setup"; // A pixel as [r, g, b, a], 0..255. type Rgba = number[]; -type Samples = { left: Rgba; right: Rgba }; +// The middle of the left and right halves of the test frame. +type Halves = { left: Rgba; right: Rgba }; type EvalResult = | { kind: "skip"; reason: string } | { kind: "fail"; reason: string } - | { kind: "ok"; plain: Samples; wrapped: Samples; imported: Samples }; + | { + kind: "ok"; + withoutColorSpace: Halves; + withColorSpace: Halves; + withSourceColorSpace: Halves; + }; -// How the test frame is encoded: red on the left half, green on the right, in -// BT.709 narrow range. Its AHardwareBuffer carries no color metadata, so -// wrapped without options it is read with the platform's guess (BT.601 -// narrow when the driver has none), as a buffer from another library is. -const OVERRIDE = { matrix: "rec709", range: "narrow" } as const; +// The test frame is red on the left and green on the right, encoded in +// BT.709 narrow range, but its AHardwareBuffer does not say so: wrapped +// without a colorSpace it is read with the platform's guess, as a buffer +// from another library is. +const TEST_FRAME_COLOR_SPACE = { matrix: "rec709", range: "narrow" } as const; +const TEST_FRAME_COLORS: Halves = { + left: [255, 0, 0, 255], + right: [0, 255, 0, 255], +}; -const expectColor = (actual: Rgba, expected: Rgba) => { - expected.forEach((channel, i) => { - expect(Math.abs(actual[i] - channel)).toBeLessThanOrEqual(8); - }); +// Within 8 levels per channel; on a mismatch, Jest shows both pixels. +const expectColors = (actual: Halves, expected: Halves) => { + const close = (a: Rgba, b: Rgba) => + a.every((channel, i) => Math.abs(channel - b[i]) <= 8); + if ( + !close(actual.left, expected.left) || + !close(actual.right, expected.right) + ) { + expect(actual).toEqual(expected); + } }; describe("createNativeBufferFromPointer colorSpace", () => { - // Wrapping with the option must read the buffer with the color space it is - // given, as importExternalTexture's sourceColorSpace does. Android only: the - // pointer is the test frame's AHardwareBuffer*, and on Apple platforms - // nothing in JS gives a CVPixelBufferRef to wrap. - it("reads a buffer without color metadata with the color space it is given", async () => { - const result = await client.eval<{ override: typeof OVERRIDE }, EvalResult>( - ({ device, override }) => { + // Android only: the pointer is the test frame's AHardwareBuffer*. On Apple + // platforms nothing in JS gives a CVPixelBufferRef to wrap. + it("reads a buffer without color metadata with the colorSpace it is given", async () => { + const result = await client.eval< + { testFrameColorSpace: typeof TEST_FRAME_COLOR_SPACE }, + EvalResult + >( + ({ device, testFrameColorSpace }) => { if ( !device.features.has( "shared-texture-memory-ahardware-buffer" as GPUFeatureName, @@ -51,26 +68,28 @@ describe("createNativeBufferFromPointer colorSpace", () => { }; } - let source: ReturnType; + let testFrame: ReturnType; try { - source = RNWebGPU.createTestVideoFrame(64, 64, "nv12"); + testFrame = RNWebGPU.createTestVideoFrame(64, 64, "nv12"); } catch (e) { const message = `${(e as Error).message ?? e}`; - // The platform cannot allocate or fill the YUV layout (Android - // before API 29). + // Android before API 29 cannot allocate or fill the YUV layout. if (message.indexOf("unsupported") !== -1) { return { kind: "skip", reason: message }; } return { kind: "fail", reason: message }; } - const plain = RNWebGPU.createNativeBufferFromPointer(source.handle); - const wrapped = RNWebGPU.createNativeBufferFromPointer(source.handle, { - colorSpace: override, - }); - const release = () => { - source.release(); - plain.release(); - wrapped.release(); + const pointer = testFrame.handle; + const wrappedWithoutColorSpace = + RNWebGPU.createNativeBufferFromPointer(pointer); + const wrappedWithColorSpace = RNWebGPU.createNativeBufferFromPointer( + pointer, + { colorSpace: testFrameColorSpace }, + ); + const releaseFrames = () => { + testFrame.release(); + wrappedWithoutColorSpace.release(); + wrappedWithColorSpace.release(); }; try { @@ -121,22 +140,26 @@ describe("createNativeBufferFromPointer colorSpace", () => { minFilter: "linear", }); - // Each draw fills a 2x1 target, whose pixel centers sample the - // middle of the left (red) and right (green) halves of the frame, - // and lands in its own 256-byte row of one readback buffer. - const draws = [ - { source: plain }, - { source: wrapped }, - { source: plain, sourceColorSpace: override }, - ]; + const imports = { + withoutColorSpace: { source: wrappedWithoutColorSpace }, + withColorSpace: { source: wrappedWithColorSpace }, + withSourceColorSpace: { + source: wrappedWithoutColorSpace, + sourceColorSpace: testFrameColorSpace, + }, + }; + const names = Object.keys(imports) as (keyof typeof imports)[]; + // One 256-byte row (the copy alignment) per import. + const ROW = 256; const readback = device.createBuffer({ - size: 256 * draws.length, + size: ROW * names.length, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, }); const encoder = device.createCommandEncoder(); - const externalTextures = draws.map((descriptor, i) => { - const externalTexture = device.importExternalTexture(descriptor); - const target = device.createTexture({ + const externalTextures = names.map((name, row) => { + const externalTexture = device.importExternalTexture(imports[name]); + // Two pixels, whose centers sample the middle of each half. + const halves = device.createTexture({ size: [2, 1], format: "rgba8unorm", usage: @@ -145,7 +168,7 @@ describe("createNativeBufferFromPointer colorSpace", () => { const pass = encoder.beginRenderPass({ colorAttachments: [ { - view: target.createView(), + view: halves.createView(), clearValue: { r: 0, g: 0, b: 0, a: 1 }, loadOp: "clear", storeOp: "store", @@ -166,8 +189,8 @@ describe("createNativeBufferFromPointer colorSpace", () => { pass.draw(3); pass.end(); encoder.copyTextureToBuffer( - { texture: target }, - { buffer: readback, offset: 256 * i, bytesPerRow: 256 }, + { texture: halves }, + { buffer: readback, offset: ROW * row, bytesPerRow: ROW }, [2, 1], ); return externalTexture; @@ -180,25 +203,28 @@ describe("createNativeBufferFromPointer colorSpace", () => { return readback .mapAsync(GPUMapMode.READ) .then(() => { - const data = new Uint8Array(readback.getMappedRange()); - const samples = (i: number): Samples => ({ - left: Array.from(data.subarray(256 * i, 256 * i + 4)), - right: Array.from(data.subarray(256 * i + 4, 256 * i + 8)), - }); + const bytes = new Uint8Array(readback.getMappedRange()); + const halvesOf = (name: keyof typeof imports): Halves => { + const start = ROW * names.indexOf(name); + return { + left: Array.from(bytes.subarray(start, start + 4)), + right: Array.from(bytes.subarray(start + 4, start + 8)), + }; + }; return { kind: "ok" as const, - plain: samples(0), - wrapped: samples(1), - imported: samples(2), + withoutColorSpace: halvesOf("withoutColorSpace"), + withColorSpace: halvesOf("withColorSpace"), + withSourceColorSpace: halvesOf("withSourceColorSpace"), }; }) - .finally(release); + .finally(releaseFrames); } catch (e) { - release(); + releaseFrames(); return { kind: "fail", reason: `${(e as Error).message ?? e}` }; } }, - { override: OVERRIDE }, + { testFrameColorSpace: TEST_FRAME_COLOR_SPACE }, ); if (result.kind === "skip") { @@ -210,11 +236,10 @@ describe("createNativeBufferFromPointer colorSpace", () => { } console.log(`NativeBufferColorSpace: ${JSON.stringify(result)}`); - // `plain` is not checked: it is off only where the platform guesses - // another color space than the frame's (BT.601 by default), and the log - // shows it. - expectColor(result.wrapped.left, [255, 0, 0, 255]); - expectColor(result.wrapped.right, [0, 255, 0, 255]); - expect(result.wrapped).toEqual(result.imported); + // withoutColorSpace is logged, not checked: its colors are off only where + // the platform's guess is not BT.709 (it is BT.601 when the driver has + // none). + expectColors(result.withColorSpace, TEST_FRAME_COLORS); + expect(result.withColorSpace).toEqual(result.withSourceColorSpace); }); }); From 711936399c3d8be423facdc76f30b83b17b8e0e9 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 12:37:30 +0200 Subject: [PATCH 7/9] =?UTF-8?q?refactor(=F0=9F=8E=9E=EF=B8=8F):=20a=20type?= =?UTF-8?q?d=20signature=20for=20createNativeBufferFromPointer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The options are a CreateNativeBufferFromPointerOptions descriptor with its own JSIConverter, whose colorSpace is parsed like sourceColorSpace, instead of reading the raw jsi::Value arguments by hand. --- packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h | 60 +++++++------------ .../CreateNativeBufferFromPointerOptions.h | 46 ++++++++++++++ 2 files changed, 68 insertions(+), 38 deletions(-) create mode 100644 packages/webgpu/cpp/rnwgpu/api/descriptors/CreateNativeBufferFromPointerOptions.h diff --git a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h index 3c067b23f9..a7ad9c07b3 100644 --- a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h +++ b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h @@ -14,10 +14,10 @@ #include "ArrayBuffer.h" #include "Canvas.h" +#include "CreateNativeBufferFromPointerOptions.h" #include "GPU.h" #include "GPUCanvasContext.h" #include "GPUDevice.h" -#include "GPUExternalTextureDescriptor.h" #include "GPUSharedFenceState.h" #include "GPUTexture.h" #include "ImageBitmap.h" @@ -320,46 +320,30 @@ class RNWebGPU : public NativeObject { // Wrap a CVPixelBufferRef / AHardwareBuffer* pointer (typed as void* via // BigInt on the JS side) into one of our VideoFrames. The native side - // CFRetains / acquires so the caller can release immediately. - // - // createNativeBufferFromPointer(pointer, { colorSpace? }): `colorSpace` (a - // NativeBufferColorSpace, as importExternalTexture's sourceColorSpace) says - // how to read a YUV buffer that carries no color information of its own, as - // an AHardwareBuffer from a MediaCodec ImageReader. The members it sets - // replace what the buffer says. - jsi::Value createNativeBufferFromPointer(jsi::Runtime &runtime, - const jsi::Value & /*thisVal*/, - const jsi::Value *args, - size_t count) { - if (count < 1 || !args[0].isBigInt()) { - throw jsi::JSError(runtime, "createNativeBufferFromPointer: expected a " - "pointer (BigInt)"); - } - void *pointer = JSIConverter::fromJSI(runtime, args[0], false); + // CFRetains / acquires so the caller can release immediately. The members + // of `options.colorSpace` replace what the buffer says about its own. + std::shared_ptr createNativeBufferFromPointer( + void *pointer, + std::optional> + options) { auto handle = _platformContext->wrapNativeBuffer(pointer); - if (count > 1 && args[1].isObject()) { - auto colorSpace = - args[1].getObject(runtime).getProperty(runtime, "colorSpace"); - if (colorSpace.isObject()) { - auto override = external_texture_color_space::parse( - runtime, colorSpace.getObject(runtime)); - auto &reported = handle.colorSpace; - if (override.matrix) { - reported.matrix = override.matrix; - } - if (override.range) { - reported.range = override.range; - } - if (override.primaries) { - reported.primaries = override.primaries; - } - if (override.transfer) { - reported.transfer = override.transfer; - } + if (options && (*options)->colorSpace) { + const auto &given = *(*options)->colorSpace; + auto &reported = handle.colorSpace; + if (given.matrix) { + reported.matrix = given.matrix; + } + if (given.range) { + reported.range = given.range; + } + if (given.primaries) { + reported.primaries = given.primaries; + } + if (given.transfer) { + reported.transfer = given.transfer; } } - return JSIConverter>::toJSI( - runtime, std::make_shared(std::move(handle))); + return std::make_shared(std::move(handle)); } // createNativeBuffer(width, height, { format?, colorSpace? }): an empty diff --git a/packages/webgpu/cpp/rnwgpu/api/descriptors/CreateNativeBufferFromPointerOptions.h b/packages/webgpu/cpp/rnwgpu/api/descriptors/CreateNativeBufferFromPointerOptions.h new file mode 100644 index 0000000000..89a6f39c7c --- /dev/null +++ b/packages/webgpu/cpp/rnwgpu/api/descriptors/CreateNativeBufferFromPointerOptions.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include + +#include "GPUExternalTextureDescriptor.h" +#include "JSIConverter.h" +#include "PlatformContext.h" + +namespace jsi = facebook::jsi; + +namespace rnwgpu { + +// The options of createNativeBufferFromPointer(). `colorSpace` (a +// NativeBufferColorSpace, as importExternalTexture's sourceColorSpace) says +// how to read a YUV buffer that carries no color information of its own, as +// an AHardwareBuffer from a MediaCodec ImageReader. The members it sets +// replace what the buffer says. +struct CreateNativeBufferFromPointerOptions { + std::optional colorSpace; +}; + +template <> +struct JSIConverter> { + static std::shared_ptr + fromJSI(jsi::Runtime &runtime, const jsi::Value &arg, bool outOfBounds) { + auto result = std::make_shared(); + if (!outOfBounds && arg.isObject()) { + auto prop = arg.getObject(runtime).getProperty(runtime, "colorSpace"); + if (prop.isObject()) { + result->colorSpace = external_texture_color_space::parse( + runtime, prop.getObject(runtime)); + } + } + return result; + } + static jsi::Value + toJSI(jsi::Runtime &runtime, + std::shared_ptr arg) { + throw std::runtime_error( + "Invalid CreateNativeBufferFromPointerOptions::toJSI()"); + } +}; + +} // namespace rnwgpu From 599829d54abc22083ce96ab95aedc83c4d2240dc Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 13:36:22 +0200 Subject: [PATCH 8/9] =?UTF-8?q?fix(=F0=9F=8E=9E=EF=B8=8F):=20name=20colorS?= =?UTF-8?q?pace=20or=20sourceColorSpace=20in=20color=20space=20errors,=20a?= =?UTF-8?q?nd=20document=20the=20option?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit external_texture_color_space::parse takes the member it parses, so a bad value passed to createNativeBufferFromPointer says colorSpace.matrix rather than sourceColorSpace.matrix. The API docs show the options and when to pass a colorSpace. --- .../content/api/gpu-device-extensions.mdx | 2 +- apps/docs/content/api/native-buffer.mdx | 13 ++++++- .../CreateNativeBufferFromPointerOptions.h | 2 +- .../GPUExternalTextureDescriptor.h | 36 +++++++++++-------- 4 files changed, 35 insertions(+), 18 deletions(-) diff --git a/apps/docs/content/api/gpu-device-extensions.mdx b/apps/docs/content/api/gpu-device-extensions.mdx index fd33195fac..8e5b6ff4f6 100644 --- a/apps/docs/content/api/gpu-device-extensions.mdx +++ b/apps/docs/content/api/gpu-device-extensions.mdx @@ -139,7 +139,7 @@ An external texture built over a texture of a shared memory does not open an acc Its descriptor is the same as with a frame as the source (`colorSpace`, `rotation`, `mirrored`, plus `sourceColorSpace`, `cropOrigin` and `cropSize`, see below). When the producer drops the buffer, destroy the external texture, the texture and the memory, in that order. -On Android, a buffer from another library (wrapped with `createNativeBufferFromPointer`) carries no color metadata: pass `sourceColorSpace` when you know it, or the conversion assumes what the platform reports for the buffer, BT.601 limited range by default. +On Android, a buffer from another library (wrapped with `createNativeBufferFromPointer`) carries no color metadata: pass `sourceColorSpace` when you know it (or `colorSpace` to `createNativeBufferFromPointer`), or the conversion assumes what the platform reports for the buffer, BT.601 limited range by default. ## dawnToggles diff --git a/apps/docs/content/api/native-buffer.mdx b/apps/docs/content/api/native-buffer.mdx index 4418404e6f..f0da617f5d 100644 --- a/apps/docs/content/api/native-buffer.mdx +++ b/apps/docs/content/api/native-buffer.mdx @@ -36,12 +36,23 @@ The width and height are integers from 1 to 16384. ## createNativeBufferFromPointer ```ts -createNativeBufferFromPointer(pointer: bigint): NativeBuffer +createNativeBufferFromPointer(pointer: bigint, options?: CreateNativeBufferFromPointerOptions): NativeBuffer ``` Wraps a buffer produced by another library (a `CVPixelBufferRef` on Apple platforms, an `AHardwareBuffer*` on Android, for instance VisionCamera's `frame.getNativeBuffer().pointer`) into a `NativeBuffer` that holds a reference of its own until released. It runs on the JS thread; on a worklet runtime, such as a frame processor, call `RNWebGPU.createNativeBufferFromPointer(pointer)` instead (see [Vision Camera](/docs/integrations/vision-camera)). +A YUV buffer may carry no color information of its own, as an `AHardwareBuffer` from a MediaCodec `ImageReader`, and is then read with the platform's guess (BT.601 limited range on Android when the driver has none). +When you know how it is encoded, pass `colorSpace`, a [`NativeBufferColorSpace`](/api/gpu-device-extensions#gpuexternaltexture-extensions) like `sourceColorSpace` in `importExternalTexture()`; the members it sets replace what the buffer says: + +```ts +const frame = createNativeBufferFromPointer(pointer, { + colorSpace: { matrix: "rec709", range: "narrow" }, +}); +``` + + + `createTestVideoFrame(width, height)` allocates a frame filled with a test pattern, for tests and examples that need a frame without a camera or a video. ## NativeBufferView diff --git a/packages/webgpu/cpp/rnwgpu/api/descriptors/CreateNativeBufferFromPointerOptions.h b/packages/webgpu/cpp/rnwgpu/api/descriptors/CreateNativeBufferFromPointerOptions.h index 89a6f39c7c..569be704b8 100644 --- a/packages/webgpu/cpp/rnwgpu/api/descriptors/CreateNativeBufferFromPointerOptions.h +++ b/packages/webgpu/cpp/rnwgpu/api/descriptors/CreateNativeBufferFromPointerOptions.h @@ -30,7 +30,7 @@ struct JSIConverter> { auto prop = arg.getObject(runtime).getProperty(runtime, "colorSpace"); if (prop.isObject()) { result->colorSpace = external_texture_color_space::parse( - runtime, prop.getObject(runtime)); + runtime, prop.getObject(runtime), "colorSpace"); } } return result; diff --git a/packages/webgpu/cpp/rnwgpu/api/descriptors/GPUExternalTextureDescriptor.h b/packages/webgpu/cpp/rnwgpu/api/descriptors/GPUExternalTextureDescriptor.h index 6fb696311a..a3c3ce73f6 100644 --- a/packages/webgpu/cpp/rnwgpu/api/descriptors/GPUExternalTextureDescriptor.h +++ b/packages/webgpu/cpp/rnwgpu/api/descriptors/GPUExternalTextureDescriptor.h @@ -51,7 +51,8 @@ namespace external_texture_color_space { // The JS names of the members of a source color space, the Dawn enums // spelled the way the frame producers report them (see // NativeBufferColorSpace in src/types.ts). -inline wgpu::ColorSpaceYCbCrMatrixDawn parseMatrix(const std::string &name) { +inline wgpu::ColorSpaceYCbCrMatrixDawn parseMatrix(const std::string &owner, + const std::string &name) { if (name == "identity") { return wgpu::ColorSpaceYCbCrMatrixDawn::Identity; } @@ -64,12 +65,13 @@ inline wgpu::ColorSpaceYCbCrMatrixDawn parseMatrix(const std::string &name) { if (name == "rec2020") { return wgpu::ColorSpaceYCbCrMatrixDawn::Rec2020; } - throw std::runtime_error("sourceColorSpace.matrix: unknown value '" + name + + throw std::runtime_error(owner + ".matrix: unknown value '" + name + "' (expected 'identity', 'rec601', 'rec709' or " "'rec2020')"); } -inline wgpu::ColorSpaceYCbCrRangeDawn parseRange(const std::string &name) { +inline wgpu::ColorSpaceYCbCrRangeDawn parseRange(const std::string &owner, + const std::string &name) { if (name == "identity") { return wgpu::ColorSpaceYCbCrRangeDawn::Identity; } @@ -79,11 +81,12 @@ inline wgpu::ColorSpaceYCbCrRangeDawn parseRange(const std::string &name) { if (name == "full") { return wgpu::ColorSpaceYCbCrRangeDawn::Full; } - throw std::runtime_error("sourceColorSpace.range: unknown value '" + name + + throw std::runtime_error(owner + ".range: unknown value '" + name + "' (expected 'identity', 'narrow' or 'full')"); } -inline wgpu::ColorSpacePrimariesDawn parsePrimaries(const std::string &name) { +inline wgpu::ColorSpacePrimariesDawn parsePrimaries(const std::string &owner, + const std::string &name) { if (name == "srgb") { return wgpu::ColorSpacePrimariesDawn::SRGB; } @@ -99,13 +102,13 @@ inline wgpu::ColorSpacePrimariesDawn parsePrimaries(const std::string &name) { if (name == "display-p3") { return wgpu::ColorSpacePrimariesDawn::DisplayP3; } - throw std::runtime_error("sourceColorSpace.primaries: unknown value '" + - name + + throw std::runtime_error(owner + ".primaries: unknown value '" + name + "' (expected 'srgb', 'rec709', 'rec601', " "'rec2020' or 'display-p3')"); } -inline wgpu::ColorSpaceTransferDawn parseTransfer(const std::string &name) { +inline wgpu::ColorSpaceTransferDawn parseTransfer(const std::string &owner, + const std::string &name) { if (name == "identity") { return wgpu::ColorSpaceTransferDawn::Identity; } @@ -127,13 +130,16 @@ inline wgpu::ColorSpaceTransferDawn parseTransfer(const std::string &name) { if (name == "bt-1886") { return wgpu::ColorSpaceTransferDawn::BT_1886; } - throw std::runtime_error("sourceColorSpace.transfer: unknown value '" + name + + throw std::runtime_error(owner + ".transfer: unknown value '" + name + "' (expected 'identity', 'srgb', 'display-p3', " "'smpte-170m', 'hlg', 'pq' or 'bt-1886')"); } +// `owner` names the member being parsed in the error messages +// ("sourceColorSpace", "colorSpace"). inline VideoFrameColorSpace parse(jsi::Runtime &runtime, - const jsi::Object &value) { + const jsi::Object &value, + const std::string &owner) { VideoFrameColorSpace colorSpace; auto member = [&](const char *name) -> std::optional { if (!value.hasProperty(runtime, name)) { @@ -146,16 +152,16 @@ inline VideoFrameColorSpace parse(jsi::Runtime &runtime, return prop.asString(runtime).utf8(runtime); }; if (auto matrix = member("matrix")) { - colorSpace.matrix = parseMatrix(*matrix); + colorSpace.matrix = parseMatrix(owner, *matrix); } if (auto range = member("range")) { - colorSpace.range = parseRange(*range); + colorSpace.range = parseRange(owner, *range); } if (auto primaries = member("primaries")) { - colorSpace.primaries = parsePrimaries(*primaries); + colorSpace.primaries = parsePrimaries(owner, *primaries); } if (auto transfer = member("transfer")) { - colorSpace.transfer = parseTransfer(*transfer); + colorSpace.transfer = parseTransfer(owner, *transfer); } return colorSpace; } @@ -204,7 +210,7 @@ struct JSIConverter> { auto prop = value.getProperty(runtime, "sourceColorSpace"); if (prop.isObject()) { result->sourceColorSpace = external_texture_color_space::parse( - runtime, prop.getObject(runtime)); + runtime, prop.getObject(runtime), "sourceColorSpace"); } } if (value.hasProperty(runtime, "rotation")) { From 2684b691754cf30e401092de7bfe056c7b012c49 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 13:39:16 +0200 Subject: [PATCH 9/9] =?UTF-8?q?docs(=F0=9F=93=9A):=20say=20what=20a=20buff?= =?UTF-8?q?er=20without=20color=20metadata=20gets=20before=20how=20to=20fi?= =?UTF-8?q?x=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/docs/content/api/gpu-device-extensions.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/docs/content/api/gpu-device-extensions.mdx b/apps/docs/content/api/gpu-device-extensions.mdx index 8e5b6ff4f6..3c5b925552 100644 --- a/apps/docs/content/api/gpu-device-extensions.mdx +++ b/apps/docs/content/api/gpu-device-extensions.mdx @@ -139,7 +139,7 @@ An external texture built over a texture of a shared memory does not open an acc Its descriptor is the same as with a frame as the source (`colorSpace`, `rotation`, `mirrored`, plus `sourceColorSpace`, `cropOrigin` and `cropSize`, see below). When the producer drops the buffer, destroy the external texture, the texture and the memory, in that order. -On Android, a buffer from another library (wrapped with `createNativeBufferFromPointer`) carries no color metadata: pass `sourceColorSpace` when you know it (or `colorSpace` to `createNativeBufferFromPointer`), or the conversion assumes what the platform reports for the buffer, BT.601 limited range by default. +On Android, a buffer from another library (wrapped with `createNativeBufferFromPointer`) carries no color metadata, so the conversion assumes what the platform reports for the buffer, BT.601 limited range by default. When you know how the buffer is encoded, pass its color space as `colorSpace` to `createNativeBufferFromPointer`, or as `sourceColorSpace` here. ## dawnToggles