Skip to content

Commit eec4e08

Browse files
authored
fix(webgpu): wait on each 2D canvas copy's own Metal event (#292)
copyExternalImageToTexture from a Metal 2D canvas signalled one shared MTLEvent with a global counter, from each canvas's own command queue. Queues finish in any order, so a later canvas's signal could satisfy the wait for an earlier copy and wgpu sampled the intermediate texture before it was written (magenta / blank PixiJS text on iOS). Each copy now gets its own event, kept alive until wgpu's submission completes. Android (per-copy SYNC_FD) and Linux (per-frame fd) already sync per copy. Specs: a slow canvas copied before a quick one, and many resized text canvases compared against getImageData.
1 parent 488a15b commit eec4e08

2 files changed

Lines changed: 161 additions & 68 deletions

File tree

‎crates/canvas-c/src/webgpu/gpu_queue.rs‎

Lines changed: 31 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -465,33 +465,6 @@ unsafe fn copy_context_on_gpu_linux(
465465
)
466466
}
467467

468-
/// Signalled by a 2D canvas's queue once its copy for WebGPU is written; wgpu's queue waits on it.
469-
#[cfg(all(
470-
feature = "metal",
471-
any(
472-
target_os = "ios",
473-
target_os = "macos",
474-
target_os = "visionos",
475-
target_os = "tvos"
476-
)
477-
))]
478-
struct CopyEvent {
479-
device: usize,
480-
event: objc2::rc::Retained<objc2::runtime::ProtocolObject<dyn objc2_metal::MTLEvent>>,
481-
value: u64,
482-
}
483-
484-
#[cfg(all(
485-
feature = "metal",
486-
any(
487-
target_os = "ios",
488-
target_os = "macos",
489-
target_os = "visionos",
490-
target_os = "tvos"
491-
)
492-
))]
493-
unsafe impl Send for CopyEvent {}
494-
495468
/// Metal objects are thread safe; these only cross to the 2D render thread.
496469
#[cfg(all(
497470
feature = "metal",
@@ -561,8 +534,6 @@ unsafe fn copy_context_on_gpu(
561534
MTLTextureDescriptor, MTLTextureUsage,
562535
};
563536

564-
static EVENT: Mutex<Option<CopyEvent>> = Mutex::new(None);
565-
566537
let destination_texture = &(*destination.texture).texture;
567538
if !destination_texture
568539
.descriptor()
@@ -587,27 +558,11 @@ unsafe fn copy_context_on_gpu(
587558
return false;
588559
};
589560

590-
let (event, value) = {
591-
let Ok(mut slot) = EVENT.lock() else {
592-
return false;
593-
};
594-
let device_key = Retained::as_ptr(&device) as usize;
595-
if slot.as_ref().map(|e| e.device) != Some(device_key) {
596-
let Some(event) = device.newEvent() else {
597-
return false;
598-
};
599-
*slot = Some(CopyEvent {
600-
device: device_key,
601-
event,
602-
value: 0,
603-
});
604-
}
605-
let Some(entry) = slot.as_mut() else {
606-
return false;
607-
};
608-
entry.value += 1;
609-
(entry.event.clone(), entry.value)
561+
// One event per copy: canvases signal from their own queues, in no set order.
562+
let Some(event) = device.newEvent() else {
563+
return false;
610564
};
565+
let value = 1;
611566

612567
let context = &mut *(copy.source as *mut crate::c2d::CanvasRenderingContext2D);
613568
if context.metal_device() != Retained::as_ptr(&device) as usize {
@@ -653,31 +608,39 @@ unsafe fn copy_context_on_gpu(
653608
command_buffer.commit();
654609
}
655610

656-
let Some(source) = super::gpu_native_texture::import_platform_texture(
611+
let source = super::gpu_native_texture::import_platform_texture(
657612
&queue.device_id,
658613
Retained::as_ptr(&texture) as *mut c_void,
659614
width,
660615
height,
661-
) else {
662-
return false;
663-
};
616+
);
664617

665618
// Skia's surface is premultiplied.
666-
super::gpu_native_texture::blit_texture_with(
667-
queue,
668-
&source,
669-
width,
670-
height,
671-
copy.origin.x,
672-
copy.origin.y,
673-
copy.flip_y,
674-
!copy.premultiplied_alpha,
675-
destination_texture,
676-
destination.mip_level,
677-
destination.origin.z,
678-
(destination.origin.x, destination.origin.y),
679-
size,
680-
)
619+
let copied = source.is_some_and(|source| {
620+
super::gpu_native_texture::blit_texture_with(
621+
queue,
622+
&source,
623+
width,
624+
height,
625+
copy.origin.x,
626+
copy.origin.y,
627+
copy.flip_y,
628+
!copy.premultiplied_alpha,
629+
destination_texture,
630+
destination.mip_level,
631+
destination.origin.z,
632+
(destination.origin.x, destination.origin.y),
633+
size,
634+
)
635+
});
636+
637+
// Metal may not retain an event a command buffer waits on.
638+
let keep_event = SendRetained(event);
639+
queue
640+
.queue
641+
.id
642+
.on_submitted_work_done(Box::new(move || drop(keep_event)));
643+
copied
681644
}
682645

683646
#[no_mangle]

‎tools/demo/canvas/spec/canvassource.ts‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,136 @@ void main() { gl_FragColor = texture2D(tex, uv); }`,
424424
}
425425
});
426426

427+
test('copyExternalImageToTexture matches getImageData for many redrawn 2d canvases', async () => {
428+
const device = await getDevice();
429+
ok(device, 'no webgpu device');
430+
431+
// Like PixiJS text: many odd sized canvases, redrawn and uploaded back to back with no sync in between.
432+
const draw = (ctx: any, i: number, round: number, width: number, height: number) => {
433+
ctx.clearRect(0, 0, width, height);
434+
ctx.fillStyle = `rgb(${(i * 20) % 256}, ${round * 90}, 160)`;
435+
ctx.fillRect(2, 2, width / 2, height - 4);
436+
ctx.fillStyle = 'white';
437+
ctx.font = '14px sans-serif';
438+
ctx.fillText(`T${i}r${round}`, 4, height - 6);
439+
};
440+
const sources = Array.from({ length: 12 }, (_, i) => make2D(40 + i * 7, 20 + i * 3));
441+
const copies: { texture: any; readback: any; bytesPerRow: number; bgra: boolean; width: number; height: number; i: number; round: number }[] = [];
442+
for (let round = 0; round < 5; round++) {
443+
// Frames go by between rounds, as in a render loop.
444+
await new Promise((resolve) => requestAnimationFrame(resolve));
445+
for (let i = 0; i < sources.length; i++) {
446+
const { canvas, ctx } = sources[i];
447+
// PixiJS resizes a text's canvas whenever its text changes.
448+
canvas.width = 40 + i * 7 + round * 5;
449+
canvas.height = 20 + i * 3 + (round % 2);
450+
const { width, height } = canvas;
451+
draw(ctx, i, round, width, height);
452+
const bgra = i % 2 === 1;
453+
const texture = device.createTexture({
454+
size: [width, height, 1],
455+
format: bgra ? 'bgra8unorm' : 'rgba8unorm',
456+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
457+
});
458+
device.queue.copyExternalImageToTexture({ source: canvas }, { texture, premultipliedAlpha: true }, [width, height, 1]);
459+
const bytesPerRow = Math.ceil((width * 4) / 256) * 256;
460+
const readback = device.createBuffer({ size: bytesPerRow * height, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
461+
copies.push({ texture, readback, bytesPerRow, bgra, width, height, i, round });
462+
}
463+
}
464+
const encoder = device.createCommandEncoder();
465+
for (const { texture, readback, bytesPerRow, width, height } of copies) {
466+
encoder.copyTextureToBuffer({ texture }, { buffer: readback, bytesPerRow }, { width, height, depthOrArrayLayers: 1 });
467+
}
468+
device.queue.submit([encoder.finish()]);
469+
470+
for (const { texture, readback, bytesPerRow, bgra, width, height, i, round } of copies) {
471+
await readback.mapAsync(GPUMapMode.READ);
472+
const pixels = new Uint8Array(readback.getMappedRange().slice(0));
473+
readback.unmap();
474+
readback.destroy();
475+
texture.destroy();
476+
const reference = make2D(width, height).ctx;
477+
draw(reference, i, round, width, height);
478+
const expected = reference.getImageData(0, 0, width, height).data;
479+
const label = `canvas ${i}, round ${round}`;
480+
481+
let bad = 0;
482+
let first = '';
483+
for (let y = 0; y < height; y++) {
484+
for (let x = 0; x < width; x++) {
485+
const e = (y * width + x) * 4;
486+
const a = expected[e + 3];
487+
const want = [Math.round((expected[e] * a) / 255), Math.round((expected[e + 1] * a) / 255), Math.round((expected[e + 2] * a) / 255), a];
488+
const o = y * bytesPerRow + x * 4;
489+
const got = bgra ? [pixels[o + 2], pixels[o + 1], pixels[o], pixels[o + 3]] : pixels.subarray(o, o + 4);
490+
if (!pixelNear(got, want, 12)) {
491+
if (!bad) {
492+
first = `at ${x},${y} expected ${describePixel(want)}, got ${describePixel(got)}`;
493+
}
494+
bad++;
495+
}
496+
}
497+
}
498+
ok(bad === 0, `${label}: ${bad} of ${width * height} pixels differ, first ${first}`);
499+
}
500+
});
501+
502+
test('copyExternalImageToTexture waits for each 2d canvas, not a later one', async () => {
503+
const device = await getDevice();
504+
ok(device, 'no webgpu device');
505+
506+
// A slow canvas copied first and a quick one after: the first copy must not finish early.
507+
const slow = make2D(1024, 1024);
508+
const quick = make2D(16, 16);
509+
const pending: { texture: any; readback: any; expected: number[]; label: string }[] = [];
510+
for (let round = 0; round < 6; round++) {
511+
const { ctx } = slow;
512+
ctx.clearRect(0, 0, 1024, 1024);
513+
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
514+
ctx.shadowBlur = 40;
515+
for (let j = 0; j < 60; j++) {
516+
ctx.fillStyle = `rgb(${j * 4}, 80, 200)`;
517+
ctx.beginPath();
518+
ctx.arc((j * 97) % 1024, (j * 61) % 1024, 120, 0, Math.PI * 2);
519+
ctx.fill();
520+
}
521+
ctx.shadowBlur = 0;
522+
const expected = [round * 40, 255 - round * 40, 60, 255];
523+
ctx.fillStyle = `rgb(${expected[0]}, ${expected[1]}, ${expected[2]})`;
524+
ctx.fillRect(480, 480, 64, 64);
525+
const texture = device.createTexture({
526+
size: [1024, 1024, 1],
527+
format: 'rgba8unorm',
528+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
529+
});
530+
device.queue.copyExternalImageToTexture({ source: slow.canvas }, { texture, premultipliedAlpha: true }, [1024, 1024, 1]);
531+
532+
quick.ctx.fillStyle = 'red';
533+
quick.ctx.fillRect(0, 0, 16, 16);
534+
const other = device.createTexture({
535+
size: [16, 16, 1],
536+
format: 'rgba8unorm',
537+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
538+
});
539+
device.queue.copyExternalImageToTexture({ source: quick.canvas }, { texture: other, premultipliedAlpha: true }, [16, 16, 1]);
540+
541+
const readback = device.createBuffer({ size: 256, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
542+
const encoder = device.createCommandEncoder();
543+
encoder.copyTextureToBuffer({ texture, origin: { x: 512, y: 512 } }, { buffer: readback, bytesPerRow: 256 }, { width: 1, height: 1, depthOrArrayLayers: 1 });
544+
device.queue.submit([encoder.finish()]);
545+
pending.push({ texture, readback, expected, label: `round ${round}` });
546+
}
547+
for (const { texture, readback, expected, label } of pending) {
548+
await readback.mapAsync(GPUMapMode.READ);
549+
const pixel = new Uint8Array(readback.getMappedRange().slice(0, 4));
550+
readback.unmap();
551+
readback.destroy();
552+
texture.destroy();
553+
ok(pixelNear(pixel, expected), `${label}: expected ${describePixel(expected)}, got ${describePixel(pixel)}`);
554+
}
555+
});
556+
427557
test('copyExternalImageToTexture accepts a webgl canvas', async () => {
428558
const device = await getDevice();
429559
ok(device, 'no webgpu device');

0 commit comments

Comments
 (0)