diff --git a/apps/docs/content/api/gpu-device-extensions.mdx b/apps/docs/content/api/gpu-device-extensions.mdx index fd33195fac..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 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 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/RNWebGPU.h b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h index 94a2fa2c93..889935b2e8 100644 --- a/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h +++ b/packages/webgpu/cpp/rnwgpu/api/RNWebGPU.h @@ -14,6 +14,7 @@ #include "ArrayBuffer.h" #include "Canvas.h" +#include "CreateNativeBufferFromPointerOptions.h" #include "GPU.h" #include "GPUCanvasContext.h" #include "GPUDevice.h" @@ -320,9 +321,29 @@ 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) { + // 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 (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 std::make_shared(std::move(handle)); } 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..569be704b8 --- /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), "colorSpace"); + } + } + return result; + } + static jsi::Value + toJSI(jsi::Runtime &runtime, + std::shared_ptr arg) { + throw std::runtime_error( + "Invalid CreateNativeBufferFromPointerOptions::toJSI()"); + } +}; + +} // namespace rnwgpu 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")) { diff --git a/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts new file mode 100644 index 0000000000..e407bddb4f --- /dev/null +++ b/packages/webgpu/src/__tests__/NativeBufferColorSpace.spec.ts @@ -0,0 +1,245 @@ +import { client } from "./setup"; + +// A pixel as [r, g, b, a], 0..255. +type Rgba = number[]; + +// 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"; + withoutColorSpace: Halves; + withColorSpace: Halves; + withSourceColorSpace: Halves; + }; + +// 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], +}; + +// 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", () => { + // 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, + ) + ) { + return { + kind: "skip", + reason: "the pointer of a test frame is an AHardwareBuffer only", + }; + } + if ( + !device.features.has( + "opaque-ycbcr-android-for-external-texture" as GPUFeatureName, + ) + ) { + return { + kind: "skip", + reason: "the device cannot sample YUV hardware buffers", + }; + } + + let testFrame: ReturnType; + try { + testFrame = RNWebGPU.createTestVideoFrame(64, 64, "nv12"); + } catch (e) { + const message = `${(e as Error).message ?? e}`; + // 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 pointer = testFrame.handle; + const wrappedWithoutColorSpace = + RNWebGPU.createNativeBufferFromPointer(pointer); + const wrappedWithColorSpace = RNWebGPU.createNativeBufferFromPointer( + pointer, + { colorSpace: testFrameColorSpace }, + ); + const releaseFrames = () => { + testFrame.release(); + wrappedWithoutColorSpace.release(); + wrappedWithColorSpace.release(); + }; + + try { + 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 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: ROW * names.length, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + }); + const encoder = device.createCommandEncoder(); + 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: + GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, + }); + const pass = encoder.beginRenderPass({ + colorAttachments: [ + { + view: halves.createView(), + clearValue: { r: 0, g: 0, b: 0, a: 1 }, + loadOp: "clear", + storeOp: "store", + }, + ], + }); + pass.setPipeline(pipeline); + 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: halves }, + { buffer: readback, offset: ROW * row, bytesPerRow: ROW }, + [2, 1], + ); + return externalTexture; + }); + device.queue.submit([encoder.finish()]); + externalTextures.forEach((externalTexture) => + externalTexture.destroy(), + ); + + return readback + .mapAsync(GPUMapMode.READ) + .then(() => { + 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, + withoutColorSpace: halvesOf("withoutColorSpace"), + withColorSpace: halvesOf("withColorSpace"), + withSourceColorSpace: halvesOf("withSourceColorSpace"), + }; + }) + .finally(releaseFrames); + } catch (e) { + releaseFrames(); + return { kind: "fail", reason: `${(e as Error).message ?? e}` }; + } + }, + { testFrameColorSpace: TEST_FRAME_COLOR_SPACE }, + ); + + 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(result)}`); + + // 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); + }); +}); diff --git a/packages/webgpu/src/index.tsx b/packages/webgpu/src/index.tsx index 8b07bf8f1f..1b484dca61 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 cce68820b6..49ec8a10ec 100644 --- a/packages/webgpu/src/types.ts +++ b/packages/webgpu/src/types.ts @@ -328,6 +328,19 @@ 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), as + * `sourceColorSpace` in `importExternalTexture()`. The members it sets + * replace what the buffer says. + */ + colorSpace?: NativeBufferColorSpace; +} + /** * The options of `createNativeBuffer()`. The buffer holds premultiplied * pixels. diff --git a/packages/webgpu/src/video.ts b/packages/webgpu/src/video.ts index 9238398dd5..31654f1d79 100644 --- a/packages/webgpu/src/video.ts +++ b/packages/webgpu/src/video.ts @@ -1,4 +1,5 @@ import type { + CreateNativeBufferFromPointerOptions, CreateNativeBufferOptions, CreateTestVideoPlayerOptions, NativeBuffer, @@ -58,9 +59,13 @@ export const createTestVideoPlayer = ( * 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, ); /**