Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 39 additions & 13 deletions packages/webgpu/cpp/rnwgpu/api/GPUQueue.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,30 @@ void GPUQueue::copyExternalImageToTexture(
throw std::runtime_error("Invalid input for GPUQueue::writeTexture()");
}

const auto origin = source->origin.value_or(nullptr);
// GPUOrigin2D coordinates are [EnforceRange] unsigned long: negative,
// NaN, or out-of-range doubles must be rejected here because casting
// them to an unsigned integer is undefined behavior.
constexpr double kMaxOrigin =
static_cast<double>(std::numeric_limits<uint32_t>::max());
if (origin && (!(origin->x >= 0) || !(origin->y >= 0) ||
origin->x > kMaxOrigin || origin->y > kMaxOrigin)) {
throw std::runtime_error(
"The source origin must be a non-negative integer coordinate.");
}
const size_t sourceOriginX =
origin ? static_cast<size_t>(origin->x) : 0;
const size_t sourceOriginY =
origin ? static_cast<size_t>(origin->y) : 0;
if (sourceOriginX > source->source->getWidth() ||
sz.width > source->source->getWidth() - sourceOriginX ||
sourceOriginY > source->source->getHeight() ||
sz.height > source->source->getHeight() - sourceOriginY ||
sz.depthOrArrayLayers > 1) {
throw std::runtime_error(
"The source copy region is outside the ImageBitmap.");
}

const bool flipY = source->flipY.value_or(false);
// premultipliedAlpha defaults to false per the WebGPU spec: an untagged
// destination expects straight alpha. Convert only when the ImageBitmap's
Expand All @@ -138,28 +162,30 @@ void GPUQueue::copyExternalImageToTexture(
const bool needsAlphaConversion =
bytesPerPixel == 4 && sourcePremultiplied != destinationPremultiplied;

if (flipY || needsAlphaConversion) {
uint32_t rowSize = bytesPerPixel * source->source->getWidth();
uint32_t totalSize = source->source->getSize();
if (sourceOriginX != 0 || sourceOriginY != 0 || flipY ||
needsAlphaConversion) {
uint32_t sourceRowSize = bytesPerPixel * source->source->getWidth();
uint32_t rowSize = bytesPerPixel * sz.width;
uint32_t totalSize = rowSize * sz.height;

// Stage a mutable copy so flipping and/or alpha conversion never touch the
// ImageBitmap's backing store.
// Stage only the selected subregion so transformations never touch the
// ImageBitmap's backing store or pixels outside the requested copy.
std::vector<uint8_t> staged(totalSize);
const uint8_t *src =
static_cast<const uint8_t *>(source->source->getData());
if (flipY) {
for (uint32_t row = 0; row < source->source->getHeight(); ++row) {
std::memcpy(staged.data() +
(source->source->getHeight() - 1 - row) * rowSize,
src + row * rowSize, rowSize);
}
} else {
std::memcpy(staged.data(), src, totalSize);
for (uint32_t row = 0; row < sz.height; ++row) {
const uint32_t sourceRow =
sourceOriginY + (flipY ? sz.height - 1 - row : row);
const uint32_t sourceOffset =
sourceRow * sourceRowSize + sourceOriginX * bytesPerPixel;
std::memcpy(staged.data() + row * rowSize, src + sourceOffset, rowSize);
}
if (needsAlphaConversion) {
convertAlpha(staged.data(), totalSize, sourcePremultiplied,
destinationPremultiplied);
}
layout.bytesPerRow = rowSize;
layout.rowsPerImage = sz.height;
_instance.WriteTexture(&dst, staged.data(), totalSize, &layout, &sz);
} else {
_instance.WriteTexture(&dst, source->source->getData(),
Expand Down
224 changes: 224 additions & 0 deletions packages/webgpu/src/__tests__/ImageBitmapOrigin.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
import { client, fixtureUrl } from "./setup";

interface OriginCase {
name: string;
fileName: string;
origin: [number, number];
copySize: [number, number];
flipY: boolean;
sourcePremultiplied: boolean;
}

const cases: OriginCase[] = [
{
name: "uses a non-zero horizontal origin",
fileName: "opaque-gradient.png",
origin: [8, 0],
copySize: [16, 32],
flipY: false,
sourcePremultiplied: false,
},
{
name: "uses a non-zero vertical origin",
fileName: "opaque-gradient.png",
origin: [0, 8],
copySize: [32, 16],
flipY: false,
sourcePremultiplied: false,
},
{
name: "combines origin with alpha conversion",
fileName: "alpha-gradient.png",
origin: [8, 4],
copySize: [16, 20],
flipY: false,
sourcePremultiplied: true,
},
{
name: "flips only the selected source region",
fileName: "opaque-gradient.png",
origin: [8, 4],
copySize: [16, 20],
flipY: true,
sourcePremultiplied: false,
},
{
name: "preserves the zero-origin path",
fileName: "opaque-gradient.png",
origin: [0, 0],
copySize: [16, 16],
flipY: false,
sourcePremultiplied: false,
},
];

describe("copyExternalImageToTexture source origin", () => {
it.each(cases)("$name", async (testCase) => {
const result = await client.eval(
({ device, url, origin, copySize, flipY, sourcePremultiplied }) => {
return fetch(url)
.then((response) => response.blob())
.then((blob) =>
createImageBitmap(blob, {
premultiplyAlpha: sourcePremultiplied ? "premultiply" : "none",
}),
)
.then((bitmap) => {
const fullTexture = device.createTexture({
size: [bitmap.width, bitmap.height],
format: "rgba8unorm",
usage:
GPUTextureUsage.COPY_DST |
GPUTextureUsage.COPY_SRC |
GPUTextureUsage.RENDER_ATTACHMENT,
});
const regionTexture = device.createTexture({
size: copySize,
format: "rgba8unorm",
usage:
GPUTextureUsage.COPY_DST |
GPUTextureUsage.COPY_SRC |
GPUTextureUsage.RENDER_ATTACHMENT,
});
device.queue.copyExternalImageToTexture(
{ source: bitmap },
{ texture: fullTexture, premultipliedAlpha: false },
[bitmap.width, bitmap.height],
);
device.queue.copyExternalImageToTexture(
{ source: bitmap, origin, flipY },
{ texture: regionTexture, premultipliedAlpha: false },
copySize,
);

const bytesPerRow = 256;
const fullOutput = device.createBuffer({
size: bytesPerRow * bitmap.height,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
});
const regionOutput = device.createBuffer({
size: bytesPerRow * copySize[1],
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
});
const encoder = device.createCommandEncoder();
encoder.copyTextureToBuffer(
{ texture: fullTexture },
{ buffer: fullOutput, bytesPerRow },
[bitmap.width, bitmap.height],
);
encoder.copyTextureToBuffer(
{ texture: regionTexture },
{ buffer: regionOutput, bytesPerRow },
copySize,
);
device.queue.submit([encoder.finish()]);

return Promise.all([
fullOutput.mapAsync(GPUMapMode.READ),
regionOutput.mapAsync(GPUMapMode.READ),
]).then(() => {
const readRows = (
buffer: GPUBuffer,
width: number,
height: number,
) => {
const mapped = new Uint8Array(buffer.getMappedRange());
const data: number[] = [];
for (let row = 0; row < height; row++) {
for (let column = 0; column < width * 4; column++) {
data.push(mapped[row * bytesPerRow + column]);
}
}
return data;
};
const full = readRows(fullOutput, bitmap.width, bitmap.height);
const region = readRows(regionOutput, copySize[0], copySize[1]);
const sourceWidth = bitmap.width;

fullOutput.unmap();
regionOutput.unmap();
fullOutput.destroy();
regionOutput.destroy();
fullTexture.destroy();
regionTexture.destroy();
bitmap.close();

return { full, region, sourceWidth };
});
});
},
{
url: fixtureUrl(testCase.fileName),
origin: testCase.origin,
copySize: testCase.copySize,
flipY: testCase.flipY,
sourcePremultiplied: testCase.sourcePremultiplied,
},
);

const expected: number[] = [];
const [originX, originY] = testCase.origin;
const [copyWidth, copyHeight] = testCase.copySize;
for (let row = 0; row < copyHeight; row++) {
const sourceRow = originY + (testCase.flipY ? copyHeight - 1 - row : row);
const start = (sourceRow * result.sourceWidth + originX) * 4;
expected.push(...result.full.slice(start, start + copyWidth * 4));
}
expect(result.region).toEqual(expected);
});

it.each([
{
name: "horizontal",
origin: [17, 0] as [number, number],
copySize: [16, 32] as [number, number],
},
{
name: "vertical",
origin: [0, 17] as [number, number],
copySize: [32, 16] as [number, number],
},
{
name: "negative-origin",
origin: [-1, 0] as [number, number],
copySize: [16, 16] as [number, number],
},
])("rejects an out-of-bounds $name region", async (testCase) => {
const didThrow = await client.eval(
({ device, url, origin, copySize }) => {
return fetch(url)
.then((response) => response.blob())
.then((blob) => createImageBitmap(blob))
.then((bitmap) => {
const texture = device.createTexture({
size: copySize,
format: "rgba8unorm",
usage:
GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
});
let threw = false;
try {
device.queue.copyExternalImageToTexture(
{ source: bitmap, origin },
{ texture },
copySize,
);
} catch {
threw = true;
} finally {
texture.destroy();
bitmap.close();
}
return threw;
});
},
{
url: fixtureUrl("opaque-gradient.png"),
origin: testCase.origin,
copySize: testCase.copySize,
},
);

expect(didThrow).toBe(true);
});
});
56 changes: 42 additions & 14 deletions packages/webgpu/src/__tests__/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -697,13 +697,42 @@ class NodeTestingClient implements TestingClient {
height: number;
premultiplied?: boolean;
};
origin?: number[] | { x?: number; y?: number };
flipY?: boolean;
},
destination: GPUTexelCopyTextureInfo & { premultipliedAlpha?: boolean },
copySize: GPUExtent3DStrict,
) => {
const { data, width, height, premultiplied } = source.source;
const rowSize = width * 4;
// Both origin and copySize accept the sequence and dictionary forms.
const origin = source.origin ?? {};
const originX = (Array.isArray(origin) ? origin[0] : origin.x) ?? 0;
const originY = (Array.isArray(origin) ? origin[1] : origin.y) ?? 0;
const extent = Array.isArray(copySize)
? {
width: copySize[0],
height: copySize[1],
depthOrArrayLayers: copySize[2],
}
: (copySize as GPUExtent3DDictStrict);
const copyWidth = extent.width;
const copyHeight = extent.height ?? 1;
const copyDepth = extent.depthOrArrayLayers ?? 1;
if (originX < 0 || originY < 0) {
throw new Error(
"The source origin must be a non-negative integer coordinate.",
);
}
if (
originX + copyWidth > width ||
originY + copyHeight > height ||
copyDepth > 1
) {
throw new Error("The source copy region is outside the ImageBitmap.");
}

const sourceRowSize = width * 4;
let rowSize = sourceRowSize;
let bytes = new Uint8Array(
data.buffer as ArrayBuffer,
data.byteOffset,
Expand All @@ -714,26 +743,25 @@ class NodeTestingClient implements TestingClient {
const needsConversion =
premultiplied !== undefined &&
premultiplied !== (destination.premultipliedAlpha === true);
if (flipY || needsConversion) {
const converted = new Uint8Array(bytes.length);
if (flipY) {
for (let row = 0; row < height; row++) {
converted.set(
bytes.subarray(row * rowSize, (row + 1) * rowSize),
(height - 1 - row) * rowSize,
);
}
} else {
converted.set(bytes);
if (originX !== 0 || originY !== 0 || flipY || needsConversion) {
rowSize = copyWidth * 4;
const staged = new Uint8Array(rowSize * copyHeight);
for (let row = 0; row < copyHeight; row++) {
const sourceRow = originY + (flipY ? copyHeight - 1 - row : row);
const sourceOffset = sourceRow * sourceRowSize + originX * 4;
staged.set(
bytes.subarray(sourceOffset, sourceOffset + rowSize),
row * rowSize,
);
}
if (needsConversion) {
convertAlpha(
converted,
staged,
premultiplied === true,
destination.premultipliedAlpha === true,
);
}
bytes = converted;
bytes = staged;
}
device.queue.writeTexture(
destination,
Expand Down
Loading