File size: 5,971 Bytes
3f22414 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | /**
* GpuFrameExtractor — uploads a video/image frame to a GPU texture and
* extracts CHW float32 tiles via a compute shader, avoiding CPU-side
* getImageData() + extractTileCHW() entirely.
*
* Usage:
* const extractor = new GpuFrameExtractor(device);
* extractor.uploadFrame(videoElement, width, height);
* const gpuBuffer = extractor.extractTile(tx, ty, tw, th, modelValueRange);
* // gpuBuffer contains CHW float32 data for the tile
* extractor.destroy();
*/
const SHADER = /* wgsl */ `
struct Params {
tileX: u32,
tileY: u32,
tileW: u32,
tileH: u32,
scale: f32,
}
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var<storage, read_write> out: array<f32>;
@group(0) @binding(2) var<uniform> params: Params;
@compute @workgroup_size(16, 16)
fn main(@builtin(global_invocation_id) gid: vec3u) {
let col = gid.x;
let row = gid.y;
if (col >= params.tileW || row >= params.tileH) { return; }
let pixel = textureLoad(src, vec2u(params.tileX + col, params.tileY + row), 0);
let plane = params.tileW * params.tileH;
let idx = row * params.tileW + col;
// Texture values are [0,1]; scale converts to model's expected range
// (1.0 keeps [0,1], 255.0 produces [0,255]).
out[idx] = pixel.r * params.scale;
out[plane + idx] = pixel.g * params.scale;
out[2u * plane + idx] = pixel.b * params.scale;
}
`;
const PARAMS_SIZE = 5 * 4;
const PARAMS_BUFFER_SIZE = Math.ceil(PARAMS_SIZE / 16) * 16;
export class GpuFrameExtractor {
#device;
#pipeline;
#bindGroupLayout;
#paramsBuffer;
#frameTexture = null;
#tileBuffer = null;
#tileBufferSize = 0;
#lost = false;
constructor(device) {
this.#device = device;
this.#initPipeline();
this.#device.lost.then((info) => {
this.#lost = true;
console.warn('[GpuFrameExtractor] GPU device lost:', info.message);
});
}
get lost() { return this.#lost; }
/**
* Upload a frame source to the internal GPU texture.
* Accepts HTMLVideoElement, HTMLImageElement, HTMLCanvasElement,
* ImageBitmap, VideoFrame, OffscreenCanvas — anything valid for
* copyExternalImageToTexture().
*/
uploadFrame(source, width, height) {
if (this.#frameTexture &&
(this.#frameTexture.width !== width || this.#frameTexture.height !== height)) {
this.#frameTexture.destroy();
this.#frameTexture = null;
}
if (!this.#frameTexture) {
this.#frameTexture = this.#device.createTexture({
size: [width, height],
format: 'rgba8unorm',
usage:
GPUTextureUsage.TEXTURE_BINDING |
GPUTextureUsage.COPY_DST |
GPUTextureUsage.RENDER_ATTACHMENT,
});
}
this.#device.queue.copyExternalImageToTexture(
{ source },
{ texture: this.#frameTexture },
[width, height],
);
}
/**
* Run the compute shader to extract a tile as CHW float32 into a
* reusable GPU storage buffer.
*
* @param {number} tx - source tile X
* @param {number} ty - source tile Y
* @param {number} tw - tile width
* @param {number} th - tile height
* @param {number} modelValueRange - upper bound of the model's expected value range (1 or 255);
* texture values are [0,1] so this acts as a multiplier.
* @returns {GPUBuffer} containing 3×tw×th float32 values in CHW order
*/
extractTile(tx, ty, tw, th, modelValueRange) {
const byteSize = 3 * tw * th * 4;
if (this.#tileBufferSize < byteSize) {
this.#tileBuffer?.destroy();
this.#tileBuffer = this.#device.createBuffer({
size: byteSize,
usage:
GPUBufferUsage.STORAGE |
GPUBufferUsage.COPY_SRC |
GPUBufferUsage.COPY_DST,
});
this.#tileBufferSize = byteSize;
}
const paramsData = new ArrayBuffer(PARAMS_BUFFER_SIZE);
const u32 = new Uint32Array(paramsData);
const f32 = new Float32Array(paramsData);
u32[0] = tx;
u32[1] = ty;
u32[2] = tw;
u32[3] = th;
f32[4] = modelValueRange;
this.#device.queue.writeBuffer(this.#paramsBuffer, 0, paramsData);
const bindGroup = this.#device.createBindGroup({
layout: this.#bindGroupLayout,
entries: [
{ binding: 0, resource: this.#frameTexture.createView() },
{ binding: 1, resource: { buffer: this.#tileBuffer, size: byteSize } },
{ binding: 2, resource: { buffer: this.#paramsBuffer } },
],
});
const encoder = this.#device.createCommandEncoder();
const pass = encoder.beginComputePass();
pass.setPipeline(this.#pipeline);
pass.setBindGroup(0, bindGroup);
pass.dispatchWorkgroups(Math.ceil(tw / 16), Math.ceil(th / 16));
pass.end();
this.#device.queue.submit([encoder.finish()]);
return this.#tileBuffer;
}
destroy() {
this.#frameTexture?.destroy();
this.#frameTexture = null;
this.#tileBuffer?.destroy();
this.#tileBuffer = null;
this.#paramsBuffer?.destroy();
this.#paramsBuffer = null;
}
#initPipeline() {
const module = this.#device.createShaderModule({ code: SHADER });
this.#bindGroupLayout = this.#device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
texture: { sampleType: 'float' },
},
{
binding: 1,
visibility: GPUShaderStage.COMPUTE,
buffer: { type: 'storage' },
},
{
binding: 2,
visibility: GPUShaderStage.COMPUTE,
buffer: { type: 'uniform' },
},
],
});
this.#pipeline = this.#device.createComputePipeline({
layout: this.#device.createPipelineLayout({
bindGroupLayouts: [this.#bindGroupLayout],
}),
compute: { module, entryPoint: 'main' },
});
this.#paramsBuffer = this.#device.createBuffer({
size: PARAMS_BUFFER_SIZE,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
}
}
|