replay: a surface's pictures fill its shapes at their first use, as the product's lazy fill does

m2v.externalWriteDone (a decoded picture landed in a receiver buffer) no longer refills the
buffer's shapes at once. As the product's per-shape form does after a video command buffer, every
shape of the buffer owes a fill from it, its own write lost; the first command buffer whose
encoders use a texture of the buffer (a binding, a pass's attachment, a blit, a useResource)
fills every owing shape of the buffers it uses before its commit, by blits in a command buffer of
the player's own committed then. A picture another lands over before any use is never copied.
The eager form copied every picture at its landing, so a burst of pictures landing at one present
was copied there whether used or not.

New counters: surface_pictures_filled (pictures a fill took) and surface_pictures_unfilled (those
another landed over before any use, or whose buffer went first); the surfaces line also gives the
pictures not used yet. The copy-from-guest-RAM comment now names the product's fill from the
pages, not a refill. docs/REPLAY-STREAM.md sections 4 and 10 say so.

Verified: the new device test a_surface_picture_fills_its_shapes_at_their_first_use (two pictures
land before a kernel reads the texture: one fill of one shape, the second picture read, the first
never copied) runs in the check that follows this commit; not yet run. The eager form fails it
(two refills).
This commit is contained in:
Anees Iqbal committed 2026-11-19 05:26:09 -08:00
1 parent 8a2a6d71c4
commit 0c36de79d9
5 files changed
+219 -53

No files matched your search

@@ -172,6 +172,7 @@ impl NewRuntime {
self.skip_encoder("ParallelRenderCommandEncoder".to_owned())
}
"commit" => {
self.surface_fill_owed(call)?;
self.copy_named(call)?;
let queue = self.queue_for(call)?;
self.commit(&queue, command_buffer, call.receiver)
@@ -1942,7 +1942,7 @@ impl NewRuntime {
self.substitute(call, &descriptor, |s| &mut s.tiled)
}
"newTextureWithDescriptor:iosurface:plane:" => self.surface_texture(call, buffer),
"m2v.externalWriteDone" => self.external_write_done(call, buffer),
"m2v.externalWriteDone" => self.external_write_done(call),
_ => Err(refuse(call, "not played on a buffer")),
}
}
@@ -43,13 +43,17 @@
//! shapes, or dirty. Besides:
//! - A copy from the guest's RAM into the buffer also copies the bytes into every shape they
//! reach, in the copy's own blit encoder: the guest's bytes win over a shape's write not yet in
//! the buffer, as the product's refill does.
//! the buffer, as the CPU's bytes win in the product's fill of the buffer from the pages.
//! - A recorded CPU write into the buffer reaches the texels it covers of every shape through the
//! runtime's upload, which orders it as Metal orders a CPU write.
//! - `m2v.externalWriteDone` on a receiver buffer, another API's write landed in it (a decoded
//! picture), refills every shape of the buffer from it, by a blit in a command buffer of the
//! play's own committed then. From the first such record, the recorded CPU writes into that
//! buffer, which stand for the other API's, reach its shapes only this way.
//! picture): every shape of the buffer owes a fill from it, its own write lost, as the product's
//! shapes owe one after a video command buffer. The first command buffer whose encoders use a
//! texture of an owing shape's buffer fills, before its commit, every owing shape of the buffers
//! it uses, by blits in a command buffer of the play's own committed then; a picture no command
//! buffer used before the next one landed is never copied, counted. From the first such record,
//! the recorded CPU writes into that buffer, which stand for the other API's, reach its shapes
//! only this way.
//! - Any other command that names a receiver buffer as a buffer is refused: the buffer does not
//! hold the texels.
//! - A texture of a format that reads across a surface's planes (a two-plane YCbCr or XR10 format
@@ -194,6 +198,8 @@ struct Entry {
live: usize,
/// Written since it was last copied into the buffer, by a committed command buffer.
dirty: bool,
/// Owes a fill from the buffer: another API wrote the buffer since its last fill.
owed: bool,
/// When a texture of it was last made or let go (`Surfaces::tick`).
used: u64,
}
@@ -224,6 +230,11 @@ pub(super) struct Surfaces {
encoders: HashMap<u64, Notes>,
/// Each command buffer's shapes its ended encoders may have written, dirty at its commit.
pending: HashMap<u64, Vec<(Span, Shape)>>,
/// Each command buffer's receiver buffers whose textures its encoders use, filled where
/// owing at its commit.
used: HashMap<u64, HashSet<u64>>,
/// Each receiver buffer's pictures landed since its shapes were last filled.
landed: HashMap<u64, u64>,
/// The receiver buffers another API writes (`m2v.externalWriteDone`).
external: HashSet<u64>,
/// The queue of the play's own that the fills at a making and the refills go on.
@@ -265,10 +276,13 @@ struct Counts {
declared_writes: u64,
/// Recorded CPU writes into a buffer after a shape's making.
cpu_writes: u64,
/// `m2v.externalWriteDone` records, the shapes they refilled and the bytes of those.
/// `m2v.externalWriteDone` records; the shapes filled for them at a use, and the bytes of
/// those; the pictures a fill took, and those another landed over before any use.
external_writes: u64,
refills: u64,
refill_bytes: u64,
pictures_filled: u64,
pictures_unfilled: u64,
/// The GPU time of the refills' command buffers seen complete, and the longest one's.
refill_nanos: u64,
refill_max_nanos: u64,
@@ -352,6 +366,10 @@ impl Surfaces {
self.writable.remove(&object);
self.encoders.remove(&object);
self.pending.remove(&object);
self.used.remove(&object);
if let Some(landed) = self.landed.remove(&object) {
self.counts.pictures_unfilled += landed;
}
let Some((span, shape)) = self.views.remove(&object) else {
return;
};
@@ -436,13 +454,15 @@ impl Surfaces {
}
/// The executed counters.
pub(super) fn counted(&self) -> [(&'static str, u64); 24] {
pub(super) fn counted(&self) -> [(&'static str, u64); 26] {
let c = &self.counts;
[
("surface_external_writes", c.external_writes),
("surface_refills", c.refills),
("surface_refill_bytes", c.refill_bytes),
("surface_refill_gpu_nanos", c.refill_nanos),
("surface_pictures_filled", c.pictures_filled),
("surface_pictures_unfilled", c.pictures_unfilled),
("surface_textures", c.views),
("surface_shapes", c.made),
("surface_shapes_found", c.found),
@@ -474,7 +494,8 @@ impl Surfaces {
as views, {} order-case shapes, {} dropped); {} overlap copies ({} bytes), {} straddled texels, {} \
unordered writes, {} usage writes and {} declared slot writes (writes through an \
argument buffer with no use named unseen, not counted); {} dirty shapes written back ({} bytes); {} CPU writes, \
{} external writes refilling {} shapes ({} bytes, {} ns of GPU time, the longest \
{} external writes, {} of them filled at a use and {} landed over before any (and \
{} not used yet), filling {} shapes ({} bytes, {} ns of GPU time, the longest \
command buffer {} ns), {} copies from the guest's RAM into a shape and {} back, {} \
bytes in all; {} refused for a format a plain shape does not view as, {} declaring \
pixel-format-view usage over a plain shape; {} across planes skipped",
@@ -493,6 +514,9 @@ impl Surfaces {
c.written_back_bytes,
c.cpu_writes,
c.external_writes,
c.pictures_filled,
c.pictures_unfilled,
self.landed.values().sum::<u64>(),
c.refills,
c.refill_bytes,
c.refill_nanos,
@@ -682,6 +706,7 @@ impl NewRuntime {
texture: texture.clone(),
live: 0,
dirty: false,
owed: false,
used: surfaces.tick,
});
let ranges = surfaces.receivers.entry(span.buffer).or_default();
@@ -739,38 +764,83 @@ impl NewRuntime {
}
/// `m2v.externalWriteDone` on buffer `buffer`: another API's write landed in it, and every
/// shape of its planes takes its bytes again, by one blit encoder in a command buffer of the
/// play's own committed now. The one place the record's position decides.
/// shape of its planes owes a fill from it, its own write lost, made at the first commit
/// that uses one (`surface_fill_owed`). The one place the record's position decides.
pub(super) fn external_write_done(
&mut self,
call: &Call,
buffer: &rt::Buffer,
) -> Result<Option<(Object, Made)>, PlayError> {
self.surfaces.counts.external_writes += 1;
self.surfaces.external.insert(call.receiver);
let shapes = (self.surfaces).shapes_of(call.receiver, |_, _| true);
if shapes.is_empty() {
return Ok(None);
let surfaces = &mut self.surfaces;
surfaces.counts.external_writes += 1;
surfaces.external.insert(call.receiver);
let spans = surfaces
.receivers
.get(&call.receiver)
.cloned()
.unwrap_or_default();
let mut any = false;
for span in spans {
for entry in surfaces.ranges.get_mut(&span).into_iter().flatten() {
entry.owed = true;
entry.dirty = false;
any = true;
}
}
if any {
*surfaces.landed.entry(call.receiver).or_default() += 1;
}
Ok(None)
}
/// Before command buffer `call.receiver` commits: every owing shape of the receiver buffers
/// its encoders used is filled from its buffer, by blits in a command buffer of the play's own
/// committed now, ahead of it.
pub(super) fn surface_fill_owed(&mut self, call: &Call) -> Result<(), PlayError> {
let Some(used) = self.surfaces.used.remove(&call.receiver) else {
return Ok(());
};
let mut owing = Vec::new();
for id in used {
let shapes = (self.surfaces).shapes_of(id, |_, entry| entry.owed);
if !shapes.is_empty() {
owing.push((id, self.buffer_of(call, id)?, shapes));
}
}
if owing.is_empty() {
return Ok(());
}
let queue = self.surface_queue(call)?;
let command_buffer = queue.command_buffer().map_err(failed(call))?;
let mut blit = command_buffer
.blit_command_encoder()
.map_err(failed(call))?;
for (span, shape, entry) in &shapes {
let layout = span.layout(shape.height);
(blit.copy_from_buffer(buffer, layout, shape.size(), entry, ORIGIN))
.map_err(failed(call))?;
self.surfaces.counts.refills += 1;
self.surfaces.counts.refill_bytes += shape.bytes();
self.surfaces.counts.bytes += shape.bytes();
for (_, buffer, shapes) in &owing {
for (span, shape, entry) in shapes {
let layout = span.layout(shape.height);
(blit.copy_from_buffer(buffer, layout, shape.size(), entry, ORIGIN))
.map_err(failed(call))?;
}
}
blit.end_encoding();
self.surfaces.refilling.push_back(command_buffer.clone());
self.commit(&queue, command_buffer, 0)
.map_err(failed(call))?;
self.surfaces.clean(&shapes);
Ok(None)
let surfaces = &mut self.surfaces;
for (id, _, shapes) in &owing {
for (span, shape, _) in shapes {
if let Some(entry) = surfaces.entry(span, *shape) {
entry.owed = false;
}
surfaces.counts.refills += 1;
surfaces.counts.refill_bytes += shape.bytes();
surfaces.counts.bytes += shape.bytes();
}
if let Some(landed) = surfaces.landed.remove(id) {
surfaces.counts.pictures_filled += 1;
surfaces.counts.pictures_unfilled += landed.saturating_sub(1);
}
}
Ok(())
}
/// Before `call` plays: refused where it names a receiver buffer as a buffer, other than a
@@ -813,6 +883,8 @@ impl NewRuntime {
let views = &self.surfaces.views;
let attached = pass.textures().filter_map(|id| views.get(&id).copied());
notes.written.extend(attached);
let used = self.surfaces.used.entry(call.receiver).or_default();
used.extend(notes.written.iter().map(|(span, _)| span.buffer));
}
}
self.surfaces.encoders.insert(call.result, notes);
@@ -833,6 +905,18 @@ impl NewRuntime {
pub(super) fn surface_encoded(&mut self, call: &Call) {
let (selector, encoder) = (&*call.selector, call.receiver);
let object = |at: usize| call.args.get(at).and_then(Value::as_object);
if let Some(notes) = self.surfaces.encoders.get(&encoder) {
let mut named = Vec::new();
super::super::covers::named(&call.args, &mut named);
let views = &self.surfaces.views;
let buffers: Vec<u64> = (named.iter().filter_map(|id| views.get(id)))
.map(|(span, _)| span.buffer)
.collect();
if !buffers.is_empty() {
let command_buffer = notes.command_buffer;
(self.surfaces.used.entry(command_buffer).or_default()).extend(buffers);
}
}
if let Some((stage, ranged)) = binding(selector) {
let bound: Vec<(u64, Option<u64>)> = match ranged {
false => {
@@ -814,6 +814,31 @@ fn surface_textures_take_the_reserved_index_their_descriptor_names() {
);
}
/// A command buffer of queue #2 whose kernel (#5) reads `from` and writes the inverse into
/// `to`, waited for.
fn invert(
w: &mut StreamWriter<File>,
command_buffer: u64,
from: u64,
to: u64,
) -> std::io::Result<()> {
let encoder = command_buffer + 1;
w.call("commandBuffer", 2, command_buffer, &[], &[])?;
w.call("computeCommandEncoder", command_buffer, encoder, &[], &[])?;
let state = [Value::Object(5)];
w.call("setComputePipelineState:", encoder, 0, &state, &[])?;
for (texture, index) in [(from, 0), (to, 1)] {
let bind = [Value::Object(texture), Value::Uint(index)];
w.call("setTexture:atIndex:", encoder, 0, &bind, &[])?;
}
let size = |n| uints(&[("width", n), ("height", n), ("depth", 1)]);
let dispatch = "dispatchThreadgroups:threadsPerThreadgroup:";
w.call(dispatch, encoder, 0, &[size(1), size(2)], &[])?;
w.call("endEncoding", encoder, 0, &[], &[])?;
w.call("commit", command_buffer, 0, &[], &[])?;
w.call(WAIT_COMPLETED, command_buffer, 0, &[], &[])
}
/// Two textures over plane 0 of one surface (#6, 2 by 2 texels, 8 bytes a row): #8, RGBA8Unorm,
/// which a kernel writes the inverse of #7's texels into, and #9, BGRA8Unorm, a view of the same
/// shape, which a later command buffer's kernel reads and writes the inverse of into #10, so that
@@ -825,30 +850,6 @@ fn surface_textures_take_the_reserved_index_their_descriptor_names() {
/// #8's shape through the buffer, so a kernel reading #8 into #24 reads it in #8's first column.
#[test]
fn textures_over_one_surface_share_its_texels() {
/// A command buffer of queue #2 whose kernel (#5) reads `from` and writes the inverse into
/// `to`, waited for.
fn invert(
w: &mut StreamWriter<File>,
command_buffer: u64,
from: u64,
to: u64,
) -> std::io::Result<()> {
let encoder = command_buffer + 1;
w.call("commandBuffer", 2, command_buffer, &[], &[])?;
w.call("computeCommandEncoder", command_buffer, encoder, &[], &[])?;
let state = [Value::Object(5)];
w.call("setComputePipelineState:", encoder, 0, &state, &[])?;
for (texture, index) in [(from, 0), (to, 1)] {
let bind = [Value::Object(texture), Value::Uint(index)];
w.call("setTexture:atIndex:", encoder, 0, &bind, &[])?;
}
let size = |n| uints(&[("width", n), ("height", n), ("depth", 1)]);
let dispatch = "dispatchThreadgroups:threadsPerThreadgroup:";
w.call(dispatch, encoder, 0, &[size(1), size(2)], &[])?;
w.call("endEncoding", encoder, 0, &[], &[])?;
w.call("commit", command_buffer, 0, &[], &[])?;
w.call(WAIT_COMPLETED, command_buffer, 0, &[], &[])
}
let dir = ScratchDir::new("rt-replay-surface-views").unwrap();
let source = [0x10, 0x20, 0x30, 0x40].repeat(4);
let written_through = [0xEF, 0xDF, 0xCF, 0x40].repeat(4);
@@ -1027,6 +1028,81 @@ fn textures_over_one_surface_share_its_texels() {
assert_eq!(receivers, [(6, true)], "{lines:?}");
}
/// A surface's pictures fill its shapes at their first use, not at their landing: over Shared
/// buffer #6 (2 by 2 RGBA8Unorm texels, 8 bytes a row), #8 is a texture of plane 0 that a kernel
/// reads. Two pictures land (`m2v.write` of the bytes, then `m2v.externalWriteDone`) before any
/// command buffer uses #8: the first is never copied, and the kernel that then reads #8 into #10
/// reads the second, filled once before its command buffer.
#[test]
fn a_surface_picture_fills_its_shapes_at_their_first_use() {
let dir = ScratchDir::new("rt-replay-surface-lazy").unwrap();
let first = [0x10, 0x20, 0x30, 0x40].repeat(4);
let second = [0x50, 0x60, 0x70, 0x80].repeat(4);
let path = written(&dir, |w| {
let library = w.blob(&library(&dir, &[("invert_texels", 2, 0)]))?;
w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?;
w.call("newCommandQueue", 1, 2, &[], &[])?;
w.call(
"newLibraryWithData:error:",
1,
3,
&[Value::Blob(library)],
&[],
)?;
let kernel = [Value::Str("invert_texels".into())];
w.call("newFunctionWithName:", 3, 4, &kernel, &[])?;
let made = "newComputePipelineStateWithFunction:error:";
w.call(made, 1, 5, &[Value::Object(4)], &[])?;
let pages = [Value::Uint(16), Value::Uint(0)];
w.call("newBufferWithLength:options:", 1, 6, &pages, &[])?;
let texture = |usage| {
uints(&[
("textureType", 2),
("pixelFormat", 70),
("width", 2),
("height", 2),
("usage", usage),
("storageMode", 0),
])
};
let plane = Value::Map(vec![
("plane".into(), Value::Uint(0)),
("offset".into(), Value::Uint(0)),
("bytesPerRow".into(), Value::Uint(8)),
("planar".into(), Value::Bool(false)),
("facts".into(), Value::Nil),
]);
let surface = "newTextureWithDescriptor:iosurface:plane:";
w.call(surface, 6, 8, &[texture(1), plane], &[])?;
for picture in [&first, &second] {
let bytes = [Value::Uint(0), Value::Bytes(picture.clone())];
w.call("m2v.write", 6, 0, &bytes, &[])?;
w.call("m2v.externalWriteDone", 6, 0, &[], &[])?;
}
w.call("newTextureWithDescriptor:", 1, 10, &[texture(2)], &[])?;
invert(w, 11, 8, 10)
});
let (report, lines, rows) = play_then("surface-lazy", &path, |backend| {
let bytes = backend.read(10).unwrap();
let pitch = bytes.len() / 2;
[&bytes[..8], &bytes[pitch..pitch + 8]].concat()
});
let inverse: Vec<u8> = (second.chunks(4))
.flat_map(|t| [0xFF - t[0], 0xFF - t[1], 0xFF - t[2], t[3]])
.collect();
assert_eq!(rows, inverse, "{lines:?}");
let executed = &report.total.executed;
let counted = |key: &str| executed.get(key).copied().unwrap_or(0);
let counts = [
"surface_external_writes",
"surface_refills",
"surface_pictures_filled",
"surface_pictures_unfilled",
]
.map(counted);
assert_eq!(counts, [2, 1, 1, 1], "{executed:?}");
}
/// Textures over plane 0 of one surface (#2), 2 by 2, none declaring shader write: #3,
/// RGBA8Unorm, makes a plain shape, and #4, its sRGB sibling, is a view of it; then `last`, a
/// texture of BGRA8Unorm over the plane or a view of #3 as BGRA8Unorm, is refused and counted:
+9 -4
View File
@@ -141,7 +141,7 @@ and the (name id, value) answer pairs.
| `m2v.newExportableBufferOfLength` | `[length, options, alignedByte]` | the same buffer in an allocation of its own, which another API imports; result 0 where the host made none | the same, and nothing at result 0 |
| `m2v.newDmaBufBufferOfLengthPaddingUnobserved` | `[length, options, alignedByte]` | the same, also exported as a dma-buf for video decoding; the video's writes arrive as a later commit's writes (section 6); result 0 where the host made none | the same, and nothing at result 0 |
| `m2v.newCommandQueueUnshared` | `[]` | a queue the host kept apart | `newCommandQueue` |
| `m2v.externalWriteDone` | `[]`, on an exported buffer | another API's write into the buffer landed (a decoded picture) | nothing where the textures over the buffer read it in place; the new runtime's backend refills the textures over it (section 10) |
| `m2v.externalWriteDone` | `[]`, on an exported buffer | another API's write into the buffer landed (a decoded picture) | nothing where the textures over the buffer read it in place; the new runtime's backend fills the textures over it at their next use (section 10) |
## 5. Memory and addresses
@@ -778,8 +778,12 @@ counted from 0), completes the work committed so far, reports as at the stream's
every shape they reach, in the copy's own blit encoder, the guest's bytes winning over a shape's
write not yet in the buffer. A recorded CPU write reaches the texels it covers of every shape
through the runtime's upload (`Texture::replace_region`), until the buffer's first
`m2v.externalWriteDone`; that record refills every shape of its buffer from the buffer, by a blit
in a command buffer of the backend's own committed then. Another call that names a receiver
`m2v.externalWriteDone`. That record (a picture landed) makes every shape of its buffer owe a
fill from the buffer, its own write lost, as the product's shapes owe one after a video command
buffer: the first command buffer whose encoders use a texture of the buffer fills every owing
shape of the buffers it uses before its commit, by blits in a command buffer of the backend's
own committed then, and a picture that another one lands over before any use is never copied
(`surface_pictures_filled`, `surface_pictures_unfilled`). Another call that names a receiver
buffer as a buffer is refused, and a texture of a format that reads across a surface's two planes
(a two-plane YCbCr or XR10 format) is skipped (`skipped_surfaces_across_planes`). The counts
(`surface_textures`, `surface_shapes`, `surface_shapes_found`, `surface_order_shapes`,
@@ -787,7 +791,8 @@ counted from 0), completes the work committed so far, reports as at the stream's
`surface_overlap_copies`, `surface_overlap_bytes`, `surface_straddled`,
`surface_unordered_writes`, `surface_usage_writes`, `surface_declared_writes`,
`surface_cpu_writes`, `surface_external_writes`, `surface_refills`, `surface_refill_bytes`,
`surface_refill_gpu_nanos`, `surface_copies_in`, `surface_copies_out`, `surface_bytes`,
`surface_refill_gpu_nanos`, `surface_pictures_filled`, `surface_pictures_unfilled`,
`surface_copies_in`, `surface_copies_out`, `surface_bytes`,
`surface_format_refusals`, `surface_plain_format_views`) are the player's work, among its
executed counters; `surface_refill_gpu_nanos` is the GPU time of the refills' command buffers, counted in the frame whose end first sees each
complete. The report's `surfaces` line gives them with the longest refill command buffer. A