Skip to main content

oa/video/
ops.rs

1//! Tier-1 native-YUV frame geometry operations.
2//!
3//! Every operation keeps frames device-planar and per-plane: luma, planar
4//! chroma, and interleaved NV12 chroma pairs are each resampled with one
5//! `resample` dispatch. Ops express their transform in luma-space map
6//! parameters; chroma-space parameters derive from the centered 4:2:0 siting
7//! rule, so kernel count stays flat across formats.
8
9use std::rc::Rc;
10
11use crate::{
12	DType, Error, Matrix, OpAttribute, Result,
13	runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch},
14};
15
16use super::{
17	VideoColorInfo, VideoFrame, VideoInterpolation, VideoPixelFormat,
18	plane::{DevicePlanar, plane_extents},
19};
20
21/// Axis along which [`flip`] mirrors or [`stack`] joins frames.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum VideoAxis {
24	/// Left-right direction (x).
25	Horizontal,
26	/// Top-bottom direction (y).
27	Vertical,
28}
29
30impl VideoAxis {
31	fn token(self) -> &'static str {
32		match self {
33			Self::Horizontal => "horizontal",
34			Self::Vertical => "vertical",
35		}
36	}
37}
38
39/// Luma-space resampling description shared by all tier-1 ops.
40///
41/// `sx = (dst + 0.5) * scale + off` in each axis; `swap` transposes the
42/// coordinate assignment for quarter turns. `valid` bounds the destination
43/// window that receives sampled content; outside pixels take the plane fill.
44#[derive(Clone, Copy)]
45struct PlaneMap {
46	scale_x: f64,
47	scale_y: f64,
48	off_x: f64,
49	off_y: f64,
50	valid: [f64; 4],
51	swap: bool,
52	dst_off_x: usize,
53	dst_off_y: usize,
54	local_w: usize,
55	local_h: usize,
56	fill: [u8; 3],
57}
58
59impl PlaneMap {
60	fn identity(fill: [u8; 3]) -> Self {
61		Self {
62			scale_x: 1.0,
63			scale_y: 1.0,
64			off_x: -0.5,
65			off_y: -0.5,
66			valid: [0.0; 4],
67			swap: false,
68			dst_off_x: 0,
69			dst_off_y: 0,
70			local_w: 0,
71			local_h: 0,
72			fill,
73		}
74	}
75
76	/// Map parameters for a plane at resolution `factor` of luma (0.5 chroma).
77	fn at(&self, factor: f64) -> Self {
78		let shift = (factor - 1.0) * 0.5;
79		Self {
80			scale_x: self.scale_x,
81			scale_y: self.scale_y,
82			off_x: factor * self.off_x + shift,
83			off_y: factor * self.off_y + shift,
84			valid: [
85				factor * self.valid[0],
86				factor * self.valid[1],
87				factor * self.valid[2],
88				factor * self.valid[3],
89			],
90			swap: self.swap,
91			dst_off_x: (self.dst_off_x as f64 * factor).floor() as usize,
92			dst_off_y: (self.dst_off_y as f64 * factor).floor() as usize,
93			local_w: (self.local_w as f64 * factor).ceil() as usize,
94			local_h: (self.local_h as f64 * factor).ceil() as usize,
95			fill: self.fill,
96		}
97	}
98}
99
100fn require_device_planar<'a>(frame: &'a VideoFrame, operation: &str) -> Result<&'a DevicePlanar> {
101	let planar = frame.device_planar().ok_or_else(|| {
102		Error::invalid_argument(format!(
103			"{operation} requires device-planar frames; stage host frames with VideoFrame::upload"
104		))
105	})?;
106	if !matches!(
107		planar.format,
108		VideoPixelFormat::Yuv420Planar8 | VideoPixelFormat::Nv12
109	) {
110		return Err(Error::missing_capability(format!(
111			"{operation} requires 8-bit I420 or NV12 planes"
112		)));
113	}
114	Ok(planar)
115}
116
117fn u32_field(value: usize, operation: &str, what: &str) -> Result<u32> {
118	u32::try_from(value).map_err(|_| Error::out_of_range(format!("{operation} {what} exceeds u32")))
119}
120
121fn require_even(value: usize, operation: &str, what: &str) -> Result<()> {
122	if !value.is_multiple_of(2) {
123		return Err(Error::invalid_argument(format!(
124			"{operation} requires even {what} for 4:2:0 chroma alignment"
125		)));
126	}
127	Ok(())
128}
129
130/// Semantic-recording fields for one `resample` operation.
131struct ResampleOp {
132	mode: &'static str,
133	params: String,
134	interpolation: VideoInterpolation,
135	operation: &'static str,
136}
137
138/// One op's per-plane resample dispatches under the `resample` contract,
139/// producing a new device-planar frame.
140///
141/// `frames` are the source planes in order; `maps` holds one luma-space map
142/// per frame; `fills` holds each frame's YUV code fill. `out_width` and
143/// `out_height` are the destination luma extent. Each plane's output extent,
144/// stride and element grouping follow the format's plane rules.
145fn run_resample(
146	frames: &[&VideoFrame],
147	maps: &[PlaneMap],
148	out_width: usize,
149	out_height: usize,
150	op: ResampleOp,
151) -> Result<VideoFrame> {
152	let ResampleOp {
153		mode,
154		params,
155		interpolation,
156		operation,
157	} = op;
158	let first = require_device_planar(frames[0], operation)?;
159	let format = first.format;
160	let runtime = first.planes[0].runtime();
161	let timing = frames[0].timing();
162	let color = frames[0].color_info();
163	let mut planars = Vec::with_capacity(frames.len());
164	for frame in frames {
165		let planar = require_device_planar(frame, operation)?;
166		if planar.format != format {
167			return Err(Error::invalid_argument(format!(
168				"{operation} requires frames of one pixel format"
169			)));
170		}
171		if !planar.planes[0].runtime().same_as(runtime) {
172			return Err(Error::invalid_argument(format!(
173				"{operation} requires frames from one runtime"
174			)));
175		}
176		planars.push(planar);
177	}
178	let extents = plane_extents(format, out_width, out_height)?;
179	let mut output_planes = Vec::with_capacity(extents.len());
180	for extent in &extents {
181		let elements = extent
182			.width
183			.checked_mul(extent.height)
184			.ok_or_else(|| Error::out_of_range(format!("{operation} plane extent overflows")))?;
185		output_planes.push(Matrix::allocate(
186			runtime,
187			vec![extent.height, extent.width],
188			elements,
189			DType::U8,
190		)?);
191	}
192	let mut semantic_inputs: Vec<&Matrix> = Vec::new();
193	let mut semantic_outputs: Vec<&Matrix> = Vec::new();
194	let mut bindings: Vec<Vec<BufferBinding>> = Vec::new();
195	let mut pushes = Vec::new();
196	for (planar, map) in planars.iter().zip(maps.iter()) {
197		for (plane_index, src) in planar.planes.iter().enumerate() {
198			let factor = if plane_index == 0 { 1.0 } else { 0.5 };
199			let plane_map = map.at(factor);
200			let nv12_uv = format == VideoPixelFormat::Nv12 && plane_index == 1;
201			let elem_stride = if nv12_uv { 2usize } else { 1usize };
202			let src_component = 0usize;
203			let (src_w, src_h) = if plane_index == 0 {
204				(planar.width, planar.height)
205			} else {
206				(planar.width.div_ceil(2), planar.height.div_ceil(2))
207			};
208			let (local_w, local_h) = if map.local_w == 0 {
209				(
210					(out_width as f64 * factor).ceil() as usize,
211					(out_height as f64 * factor).ceil() as usize,
212				)
213			} else {
214				(plane_map.local_w, plane_map.local_h)
215			};
216			let dst_row_stride = if nv12_uv {
217				extents[plane_index].width / 2
218			} else {
219				extents[plane_index].width
220			};
221			let valid = if map.valid == [0.0; 4] {
222				[0.0, 0.0, local_w as f64, local_h as f64]
223			} else {
224				plane_map.valid
225			};
226			let fill = plane_map.fill[plane_index.min(2)];
227			bindings.push(vec![
228				BufferBinding::read(src.storage()),
229				BufferBinding::write(output_planes[plane_index].storage()),
230			]);
231			pushes.push((
232				[
233					PushConstant::U32(u32_field(src_w, operation, "source width")?),
234					PushConstant::U32(u32_field(src_h, operation, "source height")?),
235					PushConstant::U32(elem_stride as u32),
236					PushConstant::U32(elem_stride as u32),
237					PushConstant::U32(src_component as u32),
238					PushConstant::U32(0),
239					PushConstant::U32(elem_stride as u32),
240					PushConstant::U32(u32_field(local_w, operation, "output width")?),
241					PushConstant::U32(u32_field(local_h, operation, "output height")?),
242					PushConstant::U32(u32_field(dst_row_stride, operation, "output stride")?),
243					PushConstant::U32(u32_field(plane_map.dst_off_x, operation, "offset")?),
244					PushConstant::U32(u32_field(plane_map.dst_off_y, operation, "offset")?),
245					PushConstant::U32(u32::from(plane_map.swap)),
246					PushConstant::U32(interpolation.mode()),
247					PushConstant::U32(u32::from(fill)),
248					PushConstant::F32(plane_map.off_x as f32),
249					PushConstant::F32(plane_map.off_y as f32),
250					PushConstant::F32(plane_map.scale_x as f32),
251					PushConstant::F32(plane_map.scale_y as f32),
252					PushConstant::F32(valid[0] as f32),
253					PushConstant::F32(valid[1] as f32),
254					PushConstant::F32(valid[2] as f32),
255					PushConstant::F32(valid[3] as f32),
256				],
257				u32_field(local_w, operation, "dispatch")?.div_ceil(16),
258				u32_field(local_h, operation, "dispatch")?.div_ceil(16),
259			));
260			semantic_inputs.push(src);
261			semantic_outputs.push(&output_planes[plane_index]);
262		}
263	}
264	let dispatch_list: Vec<ComputeDispatch> = pushes
265		.iter()
266		.enumerate()
267		.map(|(index, (push, wg_x, wg_y))| ComputeDispatch {
268			kernel: KernelId::VideoResample,
269			buffers: &bindings[index],
270			push_constants: push,
271			workgroups: [*wg_x, *wg_y, 1],
272			indirect: None,
273		})
274		.collect();
275	let attributes = [
276		OpAttribute::Enum {
277			name: "mode".into(),
278			value: mode.into(),
279		},
280		OpAttribute::Enum {
281			name: "interpolation".into(),
282			value: interpolation.token().into(),
283		},
284		OpAttribute::UnsignedInteger {
285			name: "out_width".into(),
286			value: u64::from(u32_field(out_width, operation, "output width")?),
287		},
288		OpAttribute::UnsignedInteger {
289			name: "out_height".into(),
290			value: u64::from(u32_field(out_height, operation, "output height")?),
291		},
292		OpAttribute::String {
293			name: "params".into(),
294			value: params,
295		},
296	];
297	runtime.record_split_semantic(
298		&dispatch_list,
299		SemanticDispatch {
300			contract: crate::core::operation::video::RESAMPLE,
301			inputs: &semantic_inputs,
302			outputs: &semantic_outputs,
303			attributes: &attributes,
304		},
305	)?;
306	Ok(VideoFrame::from_device_planar(
307		DevicePlanar {
308			planes: Rc::new(output_planes),
309			format,
310			width: out_width,
311			height: out_height,
312		},
313		timing,
314		color,
315	))
316}
317
318/// Extract a luma-space region; chroma extents follow the format's rules.
319///
320/// `x` and `y` must be even so chroma stays subsample-aligned.
321///
322/// # Errors
323///
324/// Returns an error for a non-device-planar frame, odd offsets, or a region
325/// outside the visible extent.
326pub fn crop(frame: &VideoFrame, region: super::VideoRegion) -> Result<VideoFrame> {
327	const OPERATION: &str = "video::crop";
328	let planar = require_device_planar(frame, OPERATION)?;
329	require_even(region.x as usize, OPERATION, "crop x")?;
330	require_even(region.y as usize, OPERATION, "crop y")?;
331	let right = u64::from(region.x) + u64::from(region.width);
332	let bottom = u64::from(region.y) + u64::from(region.height);
333	if region.width == 0
334		|| region.height == 0
335		|| right > planar.width as u64
336		|| bottom > planar.height as u64
337	{
338		return Err(Error::invalid_argument(format!(
339			"{OPERATION} region must be a non-empty area inside the visible extent"
340		)));
341	}
342	let mut map = PlaneMap::identity([0, 128, 128]);
343	map.off_x = f64::from(region.x) - 0.5;
344	map.off_y = f64::from(region.y) - 0.5;
345	run_resample(
346		&[frame],
347		&[map],
348		region.width as usize,
349		region.height as usize,
350		ResampleOp {
351			mode: "crop",
352			params: format!(
353				"{},{},{},{}",
354				region.x, region.y, region.width, region.height
355			),
356			interpolation: VideoInterpolation::Nearest,
357			operation: OPERATION,
358		},
359	)
360}
361
362/// Stretch a frame to a new extent in luma space; chroma planes follow.
363///
364/// # Errors
365///
366/// Returns an error for a non-device-planar frame or a zero extent.
367pub fn resize(
368	frame: &VideoFrame,
369	width: u32,
370	height: u32,
371	interpolation: VideoInterpolation,
372) -> Result<VideoFrame> {
373	const OPERATION: &str = "video::resize";
374	let planar = require_device_planar(frame, OPERATION)?;
375	if width == 0 || height == 0 {
376		return Err(Error::invalid_argument(format!(
377			"{OPERATION} requires a non-zero extent"
378		)));
379	}
380	let mut map = PlaneMap::identity([0, 128, 128]);
381	map.scale_x = planar.width as f64 / f64::from(width);
382	map.scale_y = planar.height as f64 / f64::from(height);
383	run_resample(
384		&[frame],
385		&[map],
386		width as usize,
387		height as usize,
388		ResampleOp {
389			mode: "resize",
390			params: format!("{width}x{height}"),
391			interpolation,
392			operation: OPERATION,
393		},
394	)
395}
396
397/// Mirror a frame along one axis in place-size output.
398///
399/// # Errors
400///
401/// Returns an error for a non-device-planar frame.
402pub fn flip(frame: &VideoFrame, axis: VideoAxis) -> Result<VideoFrame> {
403	const OPERATION: &str = "video::flip";
404	let planar = require_device_planar(frame, OPERATION)?;
405	let mut map = PlaneMap::identity([0, 128, 128]);
406	match axis {
407		VideoAxis::Horizontal => {
408			map.scale_x = -1.0;
409			map.off_x = planar.width as f64 - 0.5;
410		}
411		VideoAxis::Vertical => {
412			map.scale_y = -1.0;
413			map.off_y = planar.height as f64 - 0.5;
414		}
415	}
416	run_resample(
417		&[frame],
418		&[map],
419		planar.width,
420		planar.height,
421		ResampleOp {
422			mode: "flip",
423			params: axis.token().to_string(),
424			interpolation: VideoInterpolation::Nearest,
425			operation: OPERATION,
426		},
427	)
428}
429
430/// Rotate a frame ninety degrees clockwise.
431///
432/// # Errors
433///
434/// Returns an error for a non-device-planar frame.
435pub fn rotate90(frame: &VideoFrame) -> Result<VideoFrame> {
436	const OPERATION: &str = "video::rotate90";
437	let planar = require_device_planar(frame, OPERATION)?;
438	let mut map = PlaneMap::identity([0, 128, 128]);
439	// Clockwise: dst (x, y) samples src (y, h-1-x) via the swapped mapping.
440	map.swap = true;
441	map.off_y = -0.5;
442	map.off_x = planar.height as f64 - 0.5;
443	map.scale_x = -1.0;
444	map.scale_y = 1.0;
445	run_resample(
446		&[frame],
447		&[map],
448		planar.height,
449		planar.width,
450		ResampleOp {
451			mode: "rotate90",
452			params: "clockwise".to_string(),
453			interpolation: VideoInterpolation::Nearest,
454			operation: OPERATION,
455		},
456	)
457}
458
459/// Border extents for [`pad`]: left, top, right, bottom in luma pixels.
460#[derive(Clone, Copy, Debug, PartialEq, Eq)]
461pub struct VideoPadding {
462	pub left: u32,
463	pub top: u32,
464	pub right: u32,
465	pub bottom: u32,
466}
467
468/// Extend a frame with a constant border. `fill` is a YUV code triplet in
469/// the frame's component range. `left` and `top` must be even so chroma
470/// stays subsample-aligned.
471///
472/// # Errors
473///
474/// Returns an error for a non-device-planar frame, odd offsets, or extent
475/// overflow.
476pub fn pad(frame: &VideoFrame, padding: VideoPadding, fill: [u8; 3]) -> Result<VideoFrame> {
477	const OPERATION: &str = "video::pad";
478	let planar = require_device_planar(frame, OPERATION)?;
479	require_even(padding.left as usize, OPERATION, "left padding")?;
480	require_even(padding.top as usize, OPERATION, "top padding")?;
481	let out_width = (planar.width as u64)
482		.checked_add(u64::from(padding.left) + u64::from(padding.right))
483		.ok_or_else(|| Error::out_of_range(format!("{OPERATION} output width overflows")))?;
484	let out_height = (planar.height as u64)
485		.checked_add(u64::from(padding.top) + u64::from(padding.bottom))
486		.ok_or_else(|| Error::out_of_range(format!("{OPERATION} output height overflows")))?;
487	if out_width == 0
488		|| out_height == 0
489		|| out_width > u64::from(u32::MAX)
490		|| out_height > u64::from(u32::MAX)
491	{
492		return Err(Error::invalid_argument(format!(
493			"{OPERATION} requires a positive output extent"
494		)));
495	}
496	let mut map = PlaneMap::identity(fill);
497	map.off_x = -f64::from(padding.left) - 0.5;
498	map.off_y = -f64::from(padding.top) - 0.5;
499	map.valid = [
500		f64::from(padding.left),
501		f64::from(padding.top),
502		f64::from(padding.left) + planar.width as f64,
503		f64::from(padding.top) + planar.height as f64,
504	];
505	run_resample(
506		&[frame],
507		&[map],
508		out_width as usize,
509		out_height as usize,
510		ResampleOp {
511			mode: "pad",
512			params: format!(
513				"{},{},{},{}",
514				padding.left, padding.top, padding.right, padding.bottom
515			),
516			interpolation: VideoInterpolation::Nearest,
517			operation: OPERATION,
518		},
519	)
520}
521
522/// Aspect-preserving resize into a fixed extent with a constant fill. `fill`
523/// is a YUV code triplet in the frame's component range.
524///
525/// # Errors
526///
527/// Returns an error for a non-device-planar frame or a zero extent.
528pub fn letterbox(
529	frame: &VideoFrame,
530	width: u32,
531	height: u32,
532	fill: [u8; 3],
533	interpolation: VideoInterpolation,
534) -> Result<VideoFrame> {
535	const OPERATION: &str = "video::letterbox";
536	let planar = require_device_planar(frame, OPERATION)?;
537	if width == 0 || height == 0 {
538		return Err(Error::invalid_argument(format!(
539			"{OPERATION} requires a non-zero extent"
540		)));
541	}
542	let scale =
543		(f64::from(width) / planar.width as f64).min(f64::from(height) / planar.height as f64);
544	let map_w = planar.width as f64 * scale;
545	let map_h = planar.height as f64 * scale;
546	let ix0 = (f64::from(width) - map_w) * 0.5;
547	let iy0 = (f64::from(height) - map_h) * 0.5;
548	let mut map = PlaneMap::identity(fill);
549	map.scale_x = planar.width as f64 / map_w;
550	map.scale_y = planar.height as f64 / map_h;
551	map.off_x = -ix0 * map.scale_x - 0.5;
552	map.off_y = -iy0 * map.scale_y - 0.5;
553	map.valid = [ix0, iy0, ix0 + map_w, iy0 + map_h];
554	run_resample(
555		&[frame],
556		&[map],
557		width as usize,
558		height as usize,
559		ResampleOp {
560			mode: "letterbox",
561			params: format!("{width}x{height}"),
562			interpolation,
563			operation: OPERATION,
564		},
565	)
566}
567
568/// Convert a frame between `Nv12` and `Yuv420Planar8` plane layouts without
569/// changing content, extent, or component ranges.
570///
571/// Each plane is repacked by a `resample` dispatch at identity mapping;
572/// NV12's interleaved chroma pair splits into two dispatches (or merges from
573/// two) through per-component stride selection.
574///
575/// # Errors
576///
577/// Returns an error for a non-device-planar frame, a same-format or
578/// non-admitted target, or a runtime recording failure.
579pub fn convert_format(frame: &VideoFrame, format: VideoPixelFormat) -> Result<VideoFrame> {
580	const OPERATION: &str = "video::convert_format";
581	let planar = require_device_planar(frame, OPERATION)?;
582	if planar.format == format {
583		return Err(Error::invalid_argument(format!(
584			"{OPERATION} requires a different target format"
585		)));
586	}
587	let (interleaved_in, interleaved_out) = match (planar.format, format) {
588		(VideoPixelFormat::Nv12, VideoPixelFormat::Yuv420Planar8) => (true, false),
589		(VideoPixelFormat::Yuv420Planar8, VideoPixelFormat::Nv12) => (false, true),
590		_ => {
591			return Err(Error::missing_capability(format!(
592				"{OPERATION} supports only NV12 <-> I420 repacking before VNV-07 P010 work"
593			)));
594		}
595	};
596	let runtime = planar.planes[0].runtime();
597	let extents = plane_extents(format, planar.width, planar.height)?;
598	let mut output_planes = Vec::with_capacity(extents.len());
599	for extent in &extents {
600		let elements = extent
601			.width
602			.checked_mul(extent.height)
603			.ok_or_else(|| Error::out_of_range(format!("{OPERATION} plane extent overflows")))?;
604		output_planes.push(Matrix::allocate(
605			runtime,
606			vec![extent.height, extent.width],
607			elements,
608			DType::U8,
609		)?);
610	}
611	let chroma_w = planar.width.div_ceil(2);
612	let chroma_h = planar.height.div_ceil(2);
613	// (src_plane, src_stride, src_component, dst_plane, dst_stride, groups_w)
614	let mut jobs = vec![(
615		0usize,
616		1usize,
617		0usize,
618		0usize,
619		1usize,
620		0usize,
621		1usize,
622		planar.width,
623	)];
624	if interleaved_in {
625		jobs.push((1, 2, 0, 1, 1, 0, 1, chroma_w));
626		jobs.push((1, 2, 1, 2, 1, 0, 1, chroma_w));
627	} else {
628		jobs.push((1, 1, 0, 1, 2, 0, 1, chroma_w));
629		jobs.push((2, 1, 0, 1, 2, 1, 1, chroma_w));
630	}
631	let mut semantic_inputs: Vec<&Matrix> = Vec::new();
632	let mut semantic_outputs: Vec<&Matrix> = Vec::new();
633	let mut bindings: Vec<Vec<BufferBinding>> = Vec::new();
634	let mut pushes = Vec::new();
635	for (
636		src_plane,
637		src_stride,
638		src_component,
639		dst_plane,
640		dst_stride,
641		dst_component,
642		elem_count,
643		groups_w,
644	) in jobs
645	{
646		let src = &planar.planes[src_plane];
647		let dst = &output_planes[dst_plane];
648		let src_h = if src_plane == 0 {
649			planar.height
650		} else {
651			chroma_h
652		};
653		let dst_h = if dst_plane == 0 {
654			planar.height
655		} else {
656			chroma_h
657		};
658		let stride = if dst_stride == 2 {
659			groups_w
660		} else {
661			extents[dst_plane].width
662		};
663		bindings.push(vec![
664			BufferBinding::read(src.storage()),
665			BufferBinding::write(dst.storage()),
666		]);
667		pushes.push((
668			[
669				PushConstant::U32(u32_field(groups_w, OPERATION, "source width")?),
670				PushConstant::U32(u32_field(src_h, OPERATION, "source height")?),
671				PushConstant::U32(src_stride as u32),
672				PushConstant::U32(dst_stride as u32),
673				PushConstant::U32(src_component as u32),
674				PushConstant::U32(dst_component as u32),
675				PushConstant::U32(elem_count as u32),
676				PushConstant::U32(u32_field(groups_w, OPERATION, "output width")?),
677				PushConstant::U32(u32_field(dst_h, OPERATION, "output height")?),
678				PushConstant::U32(u32_field(stride, OPERATION, "output stride")?),
679				PushConstant::U32(0),
680				PushConstant::U32(0),
681				PushConstant::U32(0),
682				PushConstant::U32(0),
683				PushConstant::U32(0),
684				PushConstant::F32(-0.5),
685				PushConstant::F32(-0.5),
686				PushConstant::F32(1.0),
687				PushConstant::F32(1.0),
688				PushConstant::F32(0.0),
689				PushConstant::F32(0.0),
690				PushConstant::F32(groups_w as f32),
691				PushConstant::F32(dst_h as f32),
692			],
693			u32_field(groups_w, OPERATION, "dispatch")?.div_ceil(16),
694			u32_field(dst_h, OPERATION, "dispatch")?.div_ceil(16),
695		));
696		semantic_inputs.push(src);
697		if !(interleaved_out && dst_plane == 1 && dst_component == 1) {
698			semantic_outputs.push(dst);
699		}
700	}
701	let dispatch_list: Vec<ComputeDispatch> = pushes
702		.iter()
703		.enumerate()
704		.map(|(index, (push, wg_x, wg_y))| ComputeDispatch {
705			kernel: KernelId::VideoResample,
706			buffers: &bindings[index],
707			push_constants: push,
708			workgroups: [*wg_x, *wg_y, 1],
709			indirect: None,
710		})
711		.collect();
712	let attributes = [
713		OpAttribute::Enum {
714			name: "mode".into(),
715			value: "convert_format".into(),
716		},
717		OpAttribute::Enum {
718			name: "interpolation".into(),
719			value: "nearest".into(),
720		},
721		OpAttribute::UnsignedInteger {
722			name: "out_width".into(),
723			value: u64::from(u32_field(planar.width, OPERATION, "width")?),
724		},
725		OpAttribute::UnsignedInteger {
726			name: "out_height".into(),
727			value: u64::from(u32_field(planar.height, OPERATION, "height")?),
728		},
729		OpAttribute::String {
730			name: "params".into(),
731			value: format!("{format:?}"),
732		},
733	];
734	runtime.record_split_semantic(
735		&dispatch_list,
736		SemanticDispatch {
737			contract: crate::core::operation::video::RESAMPLE,
738			inputs: &semantic_inputs,
739			outputs: &semantic_outputs,
740			attributes: &attributes,
741		},
742	)?;
743	Ok(VideoFrame::from_device_planar(
744		DevicePlanar {
745			planes: Rc::new(output_planes),
746			format,
747			width: planar.width,
748			height: planar.height,
749		},
750		frame.timing(),
751		frame.color_info(),
752	))
753}
754
755/// One filled rectangle for [`overlay_boxes`].
756#[derive(Clone, Copy, Debug, PartialEq)]
757pub struct VideoBox {
758	/// Luma-space bounds; chroma edges scale down with centered siting.
759	pub region: super::VideoRegion,
760	/// YUV code triplet in the frame's component range.
761	pub fill: [u8; 3],
762}
763
764/// Draw rectangles into a new device-planar frame.
765///
766/// The base frame is copied once at identity; each box then writes its
767/// scaled region on luma and each chroma component with exclusive
768/// single-component dispatches. `border` draws a hollow ring of that width
769/// in luma pixels instead of filling.
770///
771/// # Errors
772///
773/// Returns an error for a non-device-planar frame, a box outside the
774/// visible extent, or a runtime recording failure.
775pub fn overlay_boxes(
776	frame: &VideoFrame,
777	boxes: &[VideoBox],
778	border: Option<u32>,
779) -> Result<VideoFrame> {
780	const OPERATION: &str = "video::overlay_boxes";
781	let planar = require_device_planar(frame, OPERATION)?;
782	let runtime = planar.planes[0].runtime();
783	for b in boxes {
784		let right = u64::from(b.region.x) + u64::from(b.region.width);
785		let bottom = u64::from(b.region.y) + u64::from(b.region.height);
786		if b.region.width == 0
787			|| b.region.height == 0
788			|| right > planar.width as u64
789			|| bottom > planar.height as u64
790		{
791			return Err(Error::invalid_argument(format!(
792				"{OPERATION} boxes must be non-empty regions inside the visible extent"
793			)));
794		}
795	}
796	// Identity copy into fresh output planes, then per-box writes.
797	let extents = plane_extents(planar.format, planar.width, planar.height)?;
798	let mut output_planes = Vec::with_capacity(extents.len());
799	for extent in &extents {
800		let elements = extent
801			.width
802			.checked_mul(extent.height)
803			.ok_or_else(|| Error::out_of_range(format!("{OPERATION} plane extent overflows")))?;
804		output_planes.push(Matrix::allocate(
805			runtime,
806			vec![extent.height, extent.width],
807			elements,
808			DType::U8,
809		)?);
810	}
811	let mut semantic_inputs: Vec<&Matrix> = Vec::new();
812	let mut semantic_outputs: Vec<&Matrix> = Vec::new();
813	let mut bindings: Vec<Vec<BufferBinding>> = Vec::new();
814	let mut pushes: Vec<([PushConstant; 11], u32, u32)> = Vec::new();
815	// (src storage, dst storage, plane_w, plane_h, elem_stride, src_comp, dst_comp, rect, fill, border)
816	struct Job<'a> {
817		src: &'a crate::runtime::Storage,
818		dst: &'a crate::runtime::Storage,
819		width: usize,
820		height: usize,
821		stride: u32,
822		src_comp: u32,
823		dst_comp: u32,
824	}
825	let mut jobs: Vec<Job> = Vec::new();
826	for (plane_index, src) in planar.planes.iter().enumerate() {
827		let stride = if planar.format == VideoPixelFormat::Nv12 && plane_index == 1 {
828			2u32
829		} else {
830			1
831		};
832		let (w, h) = if plane_index == 0 {
833			(planar.width, planar.height)
834		} else {
835			(planar.width.div_ceil(2), planar.height.div_ceil(2))
836		};
837		for comp in 0..stride {
838			jobs.push(Job {
839				src: src.storage(),
840				dst: output_planes[plane_index].storage(),
841				width: w,
842				height: h,
843				stride,
844				src_comp: comp,
845				dst_comp: comp,
846			});
847		}
848	}
849	for plane in planar.planes.iter() {
850		semantic_inputs.push(plane);
851	}
852	for plane in output_planes.iter() {
853		semantic_outputs.push(plane);
854	}
855	// First pass per plane-component: identity copy (empty rect).
856	for job in &jobs {
857		bindings.push(vec![
858			BufferBinding::read(job.src),
859			BufferBinding::write(job.dst),
860		]);
861		pushes.push((
862			[
863				PushConstant::U32(u32_field(job.width, OPERATION, "plane")?),
864				PushConstant::U32(u32_field(job.height, OPERATION, "plane")?),
865				PushConstant::U32(0),
866				PushConstant::U32(0),
867				PushConstant::U32(0),
868				PushConstant::U32(0),
869				PushConstant::U32(job.stride),
870				PushConstant::U32(job.src_comp),
871				PushConstant::U32(job.dst_comp),
872				PushConstant::U32(0),
873				PushConstant::U32(0),
874			],
875			u32_field(job.width, OPERATION, "dispatch")?.div_ceil(16),
876			u32_field(job.height, OPERATION, "dispatch")?.div_ceil(16),
877		));
878	}
879	// Per-box passes on each plane component.
880	for (plane_index, _src) in planar.planes.iter().enumerate() {
881		let factor = if plane_index == 0 { 1.0f64 } else { 0.5 };
882		let stride = if planar.format == VideoPixelFormat::Nv12 && plane_index == 1 {
883			2u32
884		} else {
885			1
886		};
887		let (w, h) = if plane_index == 0 {
888			(planar.width, planar.height)
889		} else {
890			(planar.width.div_ceil(2), planar.height.div_ceil(2))
891		};
892		for comp in 0..stride {
893			for b in boxes {
894				let rect = [
895					(b.region.x as f64 * factor) as u32,
896					(b.region.y as f64 * factor) as u32,
897					(b.region.width as f64 * factor).ceil() as u32,
898					(b.region.height as f64 * factor).ceil() as u32,
899				];
900				let fill = u32::from(if plane_index == 0 {
901					b.fill[0]
902				} else if plane_index == 1 {
903					b.fill[1]
904				} else {
905					b.fill[2]
906				});
907				let border_w = border.map(|w| (w as f64 * factor) as u32).unwrap_or(0);
908				bindings.push(vec![
909					BufferBinding::read(output_planes[plane_index].storage()),
910					BufferBinding::write(output_planes[plane_index].storage()),
911				]);
912				pushes.push((
913					[
914						PushConstant::U32(u32_field(w, OPERATION, "plane")?),
915						PushConstant::U32(u32_field(h, OPERATION, "plane")?),
916						PushConstant::U32(rect[0]),
917						PushConstant::U32(rect[1]),
918						PushConstant::U32(rect[2]),
919						PushConstant::U32(rect[3]),
920						PushConstant::U32(stride),
921						PushConstant::U32(comp),
922						PushConstant::U32(comp),
923						PushConstant::U32(fill),
924						PushConstant::U32(border_w),
925					],
926					u32_field(w, OPERATION, "dispatch")?.div_ceil(16),
927					u32_field(h, OPERATION, "dispatch")?.div_ceil(16),
928				));
929			}
930		}
931	}
932	let dispatch_list: Vec<ComputeDispatch> = pushes
933		.iter()
934		.enumerate()
935		.map(|(index, (push, wg_x, wg_y))| ComputeDispatch {
936			kernel: KernelId::VideoOverlayRect,
937			buffers: &bindings[index],
938			push_constants: push,
939			workgroups: [*wg_x, *wg_y, 1],
940			indirect: None,
941		})
942		.collect();
943	let attributes = [
944		OpAttribute::Enum {
945			name: "mode".into(),
946			value: "overlay_boxes".into(),
947		},
948		OpAttribute::UnsignedInteger {
949			name: "box_count".into(),
950			value: boxes.len() as u64,
951		},
952		OpAttribute::UnsignedInteger {
953			name: "border_width".into(),
954			value: u64::from(border.unwrap_or(0)),
955		},
956		OpAttribute::String {
957			name: "params".into(),
958			value: String::new(),
959		},
960	];
961	runtime.record_split_semantic(
962		&dispatch_list,
963		SemanticDispatch {
964			contract: crate::core::operation::video::OVERLAY,
965			inputs: &semantic_inputs,
966			outputs: &semantic_outputs,
967			attributes: &attributes,
968		},
969	)?;
970	Ok(VideoFrame::from_device_planar(
971		DevicePlanar {
972			planes: output_planes.clone().into(),
973			format: planar.format,
974			width: planar.width,
975			height: planar.height,
976		},
977		frame.timing(),
978		frame.color_info(),
979	))
980}
981
982/// Join frames of matching cross-extent along one axis.
983///
984/// Along-axis extents of all but the last frame must be even so chroma
985/// offsets stay subsample-aligned.
986///
987/// # Errors
988///
989/// Returns an error for an empty batch, non-device-planar frames, mixed
990/// formats or cross-extents, odd alignment, or extent overflow.
991pub fn stack(frames: &[VideoFrame], axis: VideoAxis) -> Result<VideoFrame> {
992	const OPERATION: &str = "video::stack";
993	if frames.is_empty() {
994		return Err(Error::invalid_argument(format!(
995			"{OPERATION} requires at least one frame"
996		)));
997	}
998	let first = require_device_planar(&frames[0], OPERATION)?;
999	let (cross, mut along) = match axis {
1000		VideoAxis::Horizontal => (first.height, first.width),
1001		VideoAxis::Vertical => (first.width, first.height),
1002	};
1003	for frame in &frames[1..] {
1004		let planar = require_device_planar(frame, OPERATION)?;
1005		let (frame_cross, frame_along) = match axis {
1006			VideoAxis::Horizontal => (planar.height, planar.width),
1007			VideoAxis::Vertical => (planar.width, planar.height),
1008		};
1009		if frame_cross != cross {
1010			return Err(Error::invalid_argument(format!(
1011				"{OPERATION} requires matching cross-axis extents"
1012			)));
1013		}
1014		require_even(along, OPERATION, "stacked extent")?;
1015		along = along
1016			.checked_add(frame_along)
1017			.ok_or_else(|| Error::out_of_range(format!("{OPERATION} extent overflows")))?;
1018	}
1019	let (out_width, out_height) = match axis {
1020		VideoAxis::Horizontal => (along, cross),
1021		VideoAxis::Vertical => (cross, along),
1022	};
1023	let mut maps = Vec::with_capacity(frames.len());
1024	let mut offset = 0usize;
1025	for frame in frames {
1026		let planar = require_device_planar(frame, OPERATION)?;
1027		let mut map = PlaneMap::identity([0, 128, 128]);
1028		map.local_w = planar.width;
1029		map.local_h = planar.height;
1030		match axis {
1031			VideoAxis::Horizontal => {
1032				map.dst_off_x = offset;
1033				offset += planar.width;
1034			}
1035			VideoAxis::Vertical => {
1036				map.dst_off_y = offset;
1037				offset += planar.height;
1038			}
1039		}
1040		maps.push(map);
1041	}
1042	let frame_refs: Vec<&VideoFrame> = frames.iter().collect();
1043	run_resample(
1044		&frame_refs,
1045		&maps,
1046		out_width,
1047		out_height,
1048		ResampleOp {
1049			mode: "stack",
1050			params: format!("{},{}", axis.token(), frames.len()),
1051			interpolation: VideoInterpolation::Nearest,
1052			operation: OPERATION,
1053		},
1054	)
1055}
1056
1057/// Per-plane dispatch plumbing shared by the single-input plane ops.
1058fn alloc_output(
1059	planar: &DevicePlanar,
1060	format: VideoPixelFormat,
1061	operation: &str,
1062) -> Result<(Rc<Vec<Matrix>>, Vec<super::plane::PlaneExtent>)> {
1063	let runtime = planar.planes[0].runtime();
1064	let extents = plane_extents(format, planar.width, planar.height)?;
1065	let mut planes = Vec::with_capacity(extents.len());
1066	for extent in &extents {
1067		let elements = extent
1068			.width
1069			.checked_mul(extent.height)
1070			.ok_or_else(|| Error::out_of_range(format!("{operation} plane extent overflows")))?;
1071		planes.push(Matrix::allocate(
1072			runtime,
1073			vec![extent.height, extent.width],
1074			elements,
1075			DType::U8,
1076		)?);
1077	}
1078	Ok((Rc::new(planes), extents))
1079}
1080
1081fn record_frame(
1082	planar: &DevicePlanar,
1083	format: VideoPixelFormat,
1084	planes: Rc<Vec<Matrix>>,
1085	dispatch_list: &[ComputeDispatch<'_>],
1086	semantic: SemanticDispatch<'_>,
1087	timing: super::VideoFrameTiming,
1088	color: super::VideoColorInfo,
1089) -> Result<VideoFrame> {
1090	let runtime = planar.planes[0].runtime();
1091	runtime.record_split_semantic(dispatch_list, semantic)?;
1092	Ok(VideoFrame::from_device_planar(
1093		DevicePlanar {
1094			planes,
1095			format,
1096			width: planar.width,
1097			height: planar.height,
1098		},
1099		timing,
1100		color,
1101	))
1102}
1103
1104/// Stencil `fill` onto a frame wherever the mask's luma byte is nonzero.
1105///
1106/// `mask` must be a device-planar frame of the same luma extent whose luma
1107/// plane is the stencil. Chroma components apply the mask at chroma
1108/// resolution; edge columns under odd extents follow the chroma rounding.
1109///
1110/// # Errors
1111///
1112/// Returns an error for non-device-planar inputs, mismatched extents, or a
1113/// runtime recording failure.
1114pub fn overlay_mask(frame: &VideoFrame, mask: &VideoFrame, fill: [u8; 3]) -> Result<VideoFrame> {
1115	const OPERATION: &str = "video::overlay_mask";
1116	let planar = require_device_planar(frame, OPERATION)?;
1117	let mask_planar = require_device_planar(mask, OPERATION)?;
1118	if mask_planar.width != planar.width || mask_planar.height != planar.height {
1119		return Err(Error::invalid_argument(format!(
1120			"{OPERATION} requires a mask of matching luma extent"
1121		)));
1122	}
1123	let runtime = planar.planes[0].runtime();
1124	if !mask_planar.planes[0].runtime().same_as(runtime) {
1125		return Err(Error::invalid_argument(format!(
1126			"{OPERATION} requires one runtime"
1127		)));
1128	}
1129	let (output_planes, _) = alloc_output(planar, planar.format, OPERATION)?;
1130	let mut semantic_inputs: Vec<&Matrix> = Vec::new();
1131	let mut semantic_outputs: Vec<&Matrix> = Vec::new();
1132	let mut bindings: Vec<Vec<BufferBinding>> = Vec::new();
1133	let mut pushes = Vec::new();
1134	for (plane_index, src) in planar.planes.iter().enumerate() {
1135		let stride = if planar.format == VideoPixelFormat::Nv12 && plane_index == 1 {
1136			2u32
1137		} else {
1138			1
1139		};
1140		let (w, h) = if plane_index == 0 {
1141			(planar.width, planar.height)
1142		} else {
1143			(planar.width.div_ceil(2), planar.height.div_ceil(2))
1144		};
1145		for comp in 0..stride {
1146			let fill_code = u32::from(if plane_index == 0 {
1147				fill[0]
1148			} else if comp == 0 {
1149				fill[1]
1150			} else {
1151				fill[2]
1152			});
1153			bindings.push(vec![
1154				BufferBinding::read(src.storage()),
1155				BufferBinding::read(mask_planar.planes[0].storage()),
1156				BufferBinding::write(output_planes[plane_index].storage()),
1157			]);
1158			pushes.push((
1159				[
1160					PushConstant::U32(u32_field(w, OPERATION, "plane")?),
1161					PushConstant::U32(u32_field(h, OPERATION, "plane")?),
1162					PushConstant::U32(stride),
1163					PushConstant::U32(comp),
1164					PushConstant::U32(0),
1165					PushConstant::U32(0),
1166					PushConstant::U32(fill_code),
1167					PushConstant::U32(u32_field(mask_planar.width, OPERATION, "mask")?),
1168					PushConstant::U32(u32_field(mask_planar.height, OPERATION, "mask")?),
1169					PushConstant::U32(if plane_index == 0 { 0 } else { 2 }),
1170				],
1171				u32_field(w, OPERATION, "dispatch")?.div_ceil(16),
1172				u32_field(h, OPERATION, "dispatch")?.div_ceil(16),
1173			));
1174		}
1175		semantic_inputs.push(src);
1176		semantic_inputs.push(&mask_planar.planes[0]);
1177		semantic_outputs.push(&output_planes[plane_index]);
1178	}
1179	let dispatch_list: Vec<ComputeDispatch> = pushes
1180		.iter()
1181		.enumerate()
1182		.map(|(index, (push, wg_x, wg_y))| ComputeDispatch {
1183			kernel: KernelId::VideoBlend,
1184			buffers: &bindings[index],
1185			push_constants: push,
1186			workgroups: [*wg_x, *wg_y, 1],
1187			indirect: None,
1188		})
1189		.collect();
1190	let attributes = [
1191		OpAttribute::Enum {
1192			name: "mode".into(),
1193			value: "stencil".into(),
1194		},
1195		OpAttribute::UnsignedInteger {
1196			name: "alpha".into(),
1197			value: 0,
1198		},
1199		OpAttribute::UnsignedInteger {
1200			name: "fill".into(),
1201			value: u64::from(fill[0]) << 16 | u64::from(fill[1]) << 8 | u64::from(fill[2]),
1202		},
1203		OpAttribute::String {
1204			name: "params".into(),
1205			value: String::new(),
1206		},
1207	];
1208	record_frame(
1209		planar,
1210		planar.format,
1211		output_planes.clone(),
1212		&dispatch_list,
1213		SemanticDispatch {
1214			contract: crate::core::operation::video::BLEND,
1215			inputs: &semantic_inputs,
1216			outputs: &semantic_outputs,
1217			attributes: &attributes,
1218		},
1219		frame.timing(),
1220		frame.color_info(),
1221	)
1222}
1223
1224/// Per-component stencil from a device-resident score map: where the
1225/// `scores` value at the mask coordinate is at or above `threshold` the fill
1226/// code is written, otherwise the base byte is copied.
1227///
1228/// `scores` must be an F32 matrix with exactly `width * height` elements at
1229/// the frame's luma extent; chroma planes sample it at scaled luma
1230/// coordinates. `fill` is the Y, U, V code triple written where the score
1231/// passes. The score map stays on the device — this is the GPU-resident
1232/// overlay edge for segmentation-style model output inside a captured plan.
1233///
1234/// # Errors
1235///
1236/// Returns an error if the frame is not device-planar, if the score matrix
1237/// is not F32 or does not match the luma extent, if the runtimes differ, or
1238/// if the region arithmetic overflows.
1239pub fn overlay_scores(
1240	frame: &VideoFrame,
1241	scores: &Matrix,
1242	threshold: f32,
1243	fill: [u8; 3],
1244) -> Result<VideoFrame> {
1245	const OPERATION: &str = "video::overlay_scores";
1246	let planar = require_device_planar(frame, OPERATION)?;
1247	if scores.dtype() != DType::F32 {
1248		return Err(Error::invalid_argument(format!(
1249			"{OPERATION} requires an F32 score map"
1250		)));
1251	}
1252	let luma_elements = planar
1253		.width
1254		.checked_mul(planar.height)
1255		.ok_or_else(|| Error::out_of_range(format!("{OPERATION} luma extent overflows")))?;
1256	if scores.element_count() != luma_elements {
1257		return Err(Error::invalid_argument(format!(
1258			"{OPERATION} requires exactly width * height score elements"
1259		)));
1260	}
1261	let runtime = planar.planes[0].runtime();
1262	if !scores.runtime().same_as(runtime) {
1263		return Err(Error::invalid_argument(format!(
1264			"{OPERATION} requires one runtime"
1265		)));
1266	}
1267	let (output_planes, _) = alloc_output(planar, planar.format, OPERATION)?;
1268	let mut semantic_inputs: Vec<&Matrix> = Vec::new();
1269	let mut semantic_outputs: Vec<&Matrix> = Vec::new();
1270	let mut bindings: Vec<Vec<BufferBinding>> = Vec::new();
1271	let mut pushes = Vec::new();
1272	for (plane_index, src) in planar.planes.iter().enumerate() {
1273		let stride = if planar.format == VideoPixelFormat::Nv12 && plane_index == 1 {
1274			2u32
1275		} else {
1276			1
1277		};
1278		let (w, h) = if plane_index == 0 {
1279			(planar.width, planar.height)
1280		} else {
1281			(planar.width.div_ceil(2), planar.height.div_ceil(2))
1282		};
1283		for comp in 0..stride {
1284			let fill_code = u32::from(if plane_index == 0 {
1285				fill[0]
1286			} else if comp == 0 {
1287				fill[1]
1288			} else {
1289				fill[2]
1290			});
1291			bindings.push(vec![
1292				BufferBinding::read(src.storage()),
1293				BufferBinding::read(scores.storage()),
1294				BufferBinding::write(output_planes[plane_index].storage()),
1295			]);
1296			pushes.push((
1297				[
1298					PushConstant::U32(u32_field(w, OPERATION, "plane")?),
1299					PushConstant::U32(u32_field(h, OPERATION, "plane")?),
1300					PushConstant::U32(stride),
1301					PushConstant::U32(comp),
1302					PushConstant::F32(threshold),
1303					PushConstant::U32(fill_code),
1304					PushConstant::U32(u32_field(planar.width, OPERATION, "mask")?),
1305					PushConstant::U32(u32_field(planar.height, OPERATION, "mask")?),
1306					PushConstant::U32(if plane_index == 0 { 0 } else { 2 }),
1307				],
1308				u32_field(w, OPERATION, "dispatch")?.div_ceil(16),
1309				u32_field(h, OPERATION, "dispatch")?.div_ceil(16),
1310			));
1311		}
1312		semantic_inputs.push(src);
1313		semantic_inputs.push(scores);
1314		semantic_outputs.push(&output_planes[plane_index]);
1315	}
1316	let dispatch_list: Vec<ComputeDispatch> = pushes
1317		.iter()
1318		.enumerate()
1319		.map(|(index, (push, wg_x, wg_y))| ComputeDispatch {
1320			kernel: KernelId::VideoScoreBlend,
1321			buffers: &bindings[index],
1322			push_constants: push,
1323			workgroups: [*wg_x, *wg_y, 1],
1324			indirect: None,
1325		})
1326		.collect();
1327	let attributes = [
1328		OpAttribute::Enum {
1329			name: "mode".into(),
1330			value: "stencil".into(),
1331		},
1332		OpAttribute::Float {
1333			name: "threshold".into(),
1334			value: f64::from(threshold),
1335		},
1336		OpAttribute::UnsignedInteger {
1337			name: "fill".into(),
1338			value: u64::from(fill[0]) << 16 | u64::from(fill[1]) << 8 | u64::from(fill[2]),
1339		},
1340		OpAttribute::String {
1341			name: "params".into(),
1342			value: String::new(),
1343		},
1344	];
1345	record_frame(
1346		planar,
1347		planar.format,
1348		output_planes.clone(),
1349		&dispatch_list,
1350		SemanticDispatch {
1351			contract: crate::core::operation::video::SCORE_BLEND,
1352			inputs: &semantic_inputs,
1353			outputs: &semantic_outputs,
1354			attributes: &attributes,
1355		},
1356		frame.timing(),
1357		frame.color_info(),
1358	)
1359}
1360
1361/// Alpha-composite `front` over `back` plane-by-plane; `alpha` is 0-255.
1362///
1363/// Both frames must share format, extent, and runtime. Each component blends
1364/// with rounding `(front*a + back*(255-a) + 127) / 255`.
1365///
1366/// # Errors
1367///
1368/// Returns an error for non-device-planar inputs, mismatched frames, or a
1369/// runtime recording failure.
1370pub fn composite(back: &VideoFrame, front: &VideoFrame, alpha: u8) -> Result<VideoFrame> {
1371	const OPERATION: &str = "video::composite";
1372	let planar = require_device_planar(back, OPERATION)?;
1373	let front_planar = require_device_planar(front, OPERATION)?;
1374	if front_planar.format != planar.format
1375		|| front_planar.width != planar.width
1376		|| front_planar.height != planar.height
1377	{
1378		return Err(Error::invalid_argument(format!(
1379			"{OPERATION} requires matching format and extent"
1380		)));
1381	}
1382	let runtime = planar.planes[0].runtime();
1383	if !front_planar.planes[0].runtime().same_as(runtime) {
1384		return Err(Error::invalid_argument(format!(
1385			"{OPERATION} requires one runtime"
1386		)));
1387	}
1388	let (output_planes, _) = alloc_output(planar, planar.format, OPERATION)?;
1389	let mut semantic_inputs: Vec<&Matrix> = Vec::new();
1390	let mut semantic_outputs: Vec<&Matrix> = Vec::new();
1391	let mut bindings: Vec<Vec<BufferBinding>> = Vec::new();
1392	let mut pushes = Vec::new();
1393	for (plane_index, src) in planar.planes.iter().enumerate() {
1394		let stride = if planar.format == VideoPixelFormat::Nv12 && plane_index == 1 {
1395			2u32
1396		} else {
1397			1
1398		};
1399		let (w, h) = if plane_index == 0 {
1400			(planar.width, planar.height)
1401		} else {
1402			(planar.width.div_ceil(2), planar.height.div_ceil(2))
1403		};
1404		for comp in 0..stride {
1405			bindings.push(vec![
1406				BufferBinding::read(src.storage()),
1407				BufferBinding::read(front_planar.planes[plane_index].storage()),
1408				BufferBinding::write(output_planes[plane_index].storage()),
1409			]);
1410			pushes.push((
1411				[
1412					PushConstant::U32(u32_field(w, OPERATION, "plane")?),
1413					PushConstant::U32(u32_field(h, OPERATION, "plane")?),
1414					PushConstant::U32(stride),
1415					PushConstant::U32(comp),
1416					PushConstant::U32(1),
1417					PushConstant::U32(u32::from(alpha)),
1418					PushConstant::U32(0),
1419					PushConstant::U32(0),
1420					PushConstant::U32(0),
1421					PushConstant::U32(0),
1422				],
1423				u32_field(w, OPERATION, "dispatch")?.div_ceil(16),
1424				u32_field(h, OPERATION, "dispatch")?.div_ceil(16),
1425			));
1426		}
1427		semantic_inputs.push(src);
1428		semantic_inputs.push(&front_planar.planes[plane_index]);
1429		semantic_outputs.push(&output_planes[plane_index]);
1430	}
1431	let dispatch_list: Vec<ComputeDispatch> = pushes
1432		.iter()
1433		.enumerate()
1434		.map(|(index, (push, wg_x, wg_y))| ComputeDispatch {
1435			kernel: KernelId::VideoBlend,
1436			buffers: &bindings[index],
1437			push_constants: push,
1438			workgroups: [*wg_x, *wg_y, 1],
1439			indirect: None,
1440		})
1441		.collect();
1442	let attributes = [
1443		OpAttribute::Enum {
1444			name: "mode".into(),
1445			value: "alpha".into(),
1446		},
1447		OpAttribute::UnsignedInteger {
1448			name: "alpha".into(),
1449			value: u64::from(alpha),
1450		},
1451		OpAttribute::UnsignedInteger {
1452			name: "fill".into(),
1453			value: 0,
1454		},
1455		OpAttribute::String {
1456			name: "params".into(),
1457			value: String::new(),
1458		},
1459	];
1460	record_frame(
1461		planar,
1462		planar.format,
1463		output_planes.clone(),
1464		&dispatch_list,
1465		SemanticDispatch {
1466			contract: crate::core::operation::video::BLEND,
1467			inputs: &semantic_inputs,
1468			outputs: &semantic_outputs,
1469			attributes: &attributes,
1470		},
1471		back.timing(),
1472		back.color_info(),
1473	)
1474}
1475
1476/// Convert a frame's component range between limited and full.
1477///
1478/// The frame's color metadata is updated to the target range; `Unspecified`
1479/// input uses BT.709 limited as the source. Same-range requests return a
1480/// copy at identity.
1481///
1482/// # Errors
1483///
1484/// Returns an error for a non-device-planar frame or a runtime recording
1485/// failure.
1486pub fn convert_range(frame: &VideoFrame, range: super::VideoColorRange) -> Result<VideoFrame> {
1487	const OPERATION: &str = "video::convert_range";
1488	let planar = require_device_planar(frame, OPERATION)?;
1489	let source = match frame.color_info().range() {
1490		super::VideoColorRange::Unspecified => super::VideoColorRange::Limited,
1491		explicit => explicit,
1492	};
1493	let direction = match (source, range) {
1494		(super::VideoColorRange::Limited, super::VideoColorRange::Full) => 0u32,
1495		(super::VideoColorRange::Full, super::VideoColorRange::Limited) => 1u32,
1496		(super::VideoColorRange::Unspecified, _) | (_, super::VideoColorRange::Unspecified) => {
1497			return Err(Error::invalid_argument(format!(
1498				"{OPERATION} requires resolved source and target ranges"
1499			)));
1500		}
1501		_ => u32::MAX,
1502	};
1503	let (output_planes, _) = alloc_output(planar, planar.format, OPERATION)?;
1504	let mut semantic_inputs: Vec<&Matrix> = Vec::new();
1505	let mut semantic_outputs: Vec<&Matrix> = Vec::new();
1506	let mut bindings: Vec<Vec<BufferBinding>> = Vec::new();
1507	let mut pushes = Vec::new();
1508	for (plane_index, src) in planar.planes.iter().enumerate() {
1509		let stride = if planar.format == VideoPixelFormat::Nv12 && plane_index == 1 {
1510			2u32
1511		} else {
1512			1
1513		};
1514		let (w, h) = if plane_index == 0 {
1515			(planar.width, planar.height)
1516		} else {
1517			(planar.width.div_ceil(2), planar.height.div_ceil(2))
1518		};
1519		let kind = if plane_index == 0 { 0u32 } else { 1u32 };
1520		for comp in 0..stride {
1521			bindings.push(vec![
1522				BufferBinding::read(src.storage()),
1523				BufferBinding::write(output_planes[plane_index].storage()),
1524			]);
1525			pushes.push((
1526				[
1527					PushConstant::U32(u32_field(w, OPERATION, "plane")?),
1528					PushConstant::U32(u32_field(h, OPERATION, "plane")?),
1529					PushConstant::U32(stride),
1530					PushConstant::U32(comp),
1531					PushConstant::U32(kind),
1532					PushConstant::U32(if direction == u32::MAX { 2 } else { direction }),
1533				],
1534				u32_field(w, OPERATION, "dispatch")?.div_ceil(16),
1535				u32_field(h, OPERATION, "dispatch")?.div_ceil(16),
1536			));
1537		}
1538		semantic_inputs.push(src);
1539		semantic_outputs.push(&output_planes[plane_index]);
1540	}
1541	let dispatch_list: Vec<ComputeDispatch> = pushes
1542		.iter()
1543		.enumerate()
1544		.map(|(index, (push, wg_x, wg_y))| ComputeDispatch {
1545			kernel: KernelId::VideoRangeConvert,
1546			buffers: &bindings[index],
1547			push_constants: push,
1548			workgroups: [*wg_x, *wg_y, 1],
1549			indirect: None,
1550		})
1551		.collect();
1552	let attributes = [
1553		OpAttribute::Enum {
1554			name: "mode".into(),
1555			value: if direction == 0 {
1556				"limited_to_full"
1557			} else if direction == 1 {
1558				"full_to_limited"
1559			} else {
1560				"copy"
1561			}
1562			.into(),
1563		},
1564		OpAttribute::Enum {
1565			name: "source_range".into(),
1566			value: match source {
1567				super::VideoColorRange::Full => "full",
1568				_ => "limited",
1569			}
1570			.into(),
1571		},
1572		OpAttribute::Enum {
1573			name: "target_range".into(),
1574			value: match range {
1575				super::VideoColorRange::Full => "full",
1576				_ => "limited",
1577			}
1578			.into(),
1579		},
1580		OpAttribute::String {
1581			name: "params".into(),
1582			value: String::new(),
1583		},
1584	];
1585	let result = record_frame(
1586		planar,
1587		planar.format,
1588		output_planes.clone(),
1589		&dispatch_list,
1590		SemanticDispatch {
1591			contract: crate::core::operation::video::RANGE_CONVERT,
1592			inputs: &semantic_inputs,
1593			outputs: &semantic_outputs,
1594			attributes: &attributes,
1595		},
1596		frame.timing(),
1597		VideoColorInfo::new(frame.color_info().matrix(), range),
1598	)?;
1599	Ok(result)
1600}
1601
1602/// Threshold a frame's luma plane; chroma planes are copied unchanged.
1603///
1604/// `value >= threshold` maps to `high`, otherwise `low`.
1605///
1606/// # Errors
1607///
1608/// Returns an error for a non-device-planar frame or a runtime recording
1609/// failure.
1610pub fn threshold(frame: &VideoFrame, threshold: u8, low: u8, high: u8) -> Result<VideoFrame> {
1611	const OPERATION: &str = "video::threshold";
1612	let planar = require_device_planar(frame, OPERATION)?;
1613	let (output_planes, _) = alloc_output(planar, planar.format, OPERATION)?;
1614	let mut semantic_inputs: Vec<&Matrix> = Vec::new();
1615	let mut semantic_outputs: Vec<&Matrix> = Vec::new();
1616	let mut bindings: Vec<Vec<BufferBinding>> = Vec::new();
1617	let mut pushes = Vec::new();
1618	for (plane_index, src) in planar.planes.iter().enumerate() {
1619		let stride = if planar.format == VideoPixelFormat::Nv12 && plane_index == 1 {
1620			2u32
1621		} else {
1622			1
1623		};
1624		let (w, h) = if plane_index == 0 {
1625			(planar.width, planar.height)
1626		} else {
1627			(planar.width.div_ceil(2), planar.height.div_ceil(2))
1628		};
1629		for comp in 0..stride {
1630			let is_luma = plane_index == 0;
1631			bindings.push(vec![
1632				BufferBinding::read(src.storage()),
1633				BufferBinding::write(output_planes[plane_index].storage()),
1634			]);
1635			pushes.push((
1636				[
1637					PushConstant::U32(u32_field(w, OPERATION, "plane")?),
1638					PushConstant::U32(u32_field(h, OPERATION, "plane")?),
1639					PushConstant::U32(stride),
1640					PushConstant::U32(comp),
1641					PushConstant::U32(if is_luma { 0 } else { 3 }),
1642					PushConstant::U32(u32::from(threshold)),
1643					PushConstant::U32(u32::from(low)),
1644					PushConstant::U32(u32::from(high)),
1645				],
1646				u32_field(w, OPERATION, "dispatch")?.div_ceil(16),
1647				u32_field(h, OPERATION, "dispatch")?.div_ceil(16),
1648			));
1649		}
1650		semantic_inputs.push(src);
1651		semantic_outputs.push(&output_planes[plane_index]);
1652	}
1653	let dispatch_list: Vec<ComputeDispatch> = pushes
1654		.iter()
1655		.enumerate()
1656		.map(|(index, (push, wg_x, wg_y))| ComputeDispatch {
1657			kernel: KernelId::VideoLumaMap,
1658			buffers: &bindings[index],
1659			push_constants: push,
1660			workgroups: [*wg_x, *wg_y, 1],
1661			indirect: None,
1662		})
1663		.collect();
1664	let attributes = [
1665		OpAttribute::Enum {
1666			name: "mode".into(),
1667			value: "threshold".into(),
1668		},
1669		OpAttribute::UnsignedInteger {
1670			name: "threshold".into(),
1671			value: u64::from(threshold),
1672		},
1673		OpAttribute::UnsignedInteger {
1674			name: "low".into(),
1675			value: u64::from(low),
1676		},
1677		OpAttribute::UnsignedInteger {
1678			name: "high".into(),
1679			value: u64::from(high),
1680		},
1681	];
1682	record_frame(
1683		planar,
1684		planar.format,
1685		output_planes.clone(),
1686		&dispatch_list,
1687		SemanticDispatch {
1688			contract: crate::core::operation::video::LUMA_MAP,
1689			inputs: &semantic_inputs,
1690			outputs: &semantic_outputs,
1691			attributes: &attributes,
1692		},
1693		frame.timing(),
1694		frame.color_info(),
1695	)
1696}