1use crate::{
12 DType, Error, ImageLayout, Matrix, OpAttribute, Result,
13 runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch},
14};
15
16use super::{VideoColorInfo, VideoColorMatrix, VideoColorRange, VideoFrame, VideoPixelFormat};
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum MatrixChannels {
21 Rgb,
23 Bgr,
25 Luma,
27 Yuv,
29}
30
31impl MatrixChannels {
32 fn count(self) -> usize {
33 match self {
34 Self::Luma => 1,
35 _ => 3,
36 }
37 }
38
39 fn mode(self) -> u32 {
40 match self {
41 Self::Luma => 0,
42 Self::Rgb => 1,
43 Self::Bgr => 2,
44 Self::Yuv => 3,
45 }
46 }
47
48 fn token(self) -> &'static str {
49 match self {
50 Self::Rgb => "rgb",
51 Self::Bgr => "bgr",
52 Self::Luma => "luma",
53 Self::Yuv => "yuv",
54 }
55 }
56}
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum VideoInterpolation {
61 Bilinear,
63 Nearest,
65}
66
67impl VideoInterpolation {
68 pub(crate) fn mode(self) -> u32 {
69 match self {
70 Self::Bilinear => 0,
71 Self::Nearest => 1,
72 }
73 }
74
75 pub(crate) fn token(self) -> &'static str {
76 match self {
77 Self::Bilinear => "bilinear",
78 Self::Nearest => "nearest",
79 }
80 }
81}
82
83#[derive(Clone, Copy, Debug, PartialEq)]
85pub enum VideoResize {
86 Stretch,
88 Letterbox { fill: [f32; 3] },
91 CenterCrop,
93}
94
95impl VideoResize {
96 fn token(self) -> &'static str {
97 match self {
98 Self::Stretch => "stretch",
99 Self::Letterbox { .. } => "letterbox",
100 Self::CenterCrop => "center_crop",
101 }
102 }
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub struct VideoRegion {
108 pub x: u32,
109 pub y: u32,
110 pub width: u32,
111 pub height: u32,
112}
113
114#[derive(Clone, Copy, Debug, PartialEq)]
116pub struct VideoMatrixConfig {
117 pub channels: MatrixChannels,
119 pub layout: ImageLayout,
121 pub crop: Option<VideoRegion>,
124 pub size: Option<(u32, u32)>,
126 pub resize: VideoResize,
128 pub interpolation: VideoInterpolation,
130 pub mean: [f32; 3],
132 pub std: [f32; 3],
134 pub unspecified_color: VideoColorInfo,
137}
138
139impl Default for VideoMatrixConfig {
140 fn default() -> Self {
141 Self {
142 channels: MatrixChannels::Rgb,
143 layout: ImageLayout::Nchw,
144 crop: None,
145 size: None,
146 resize: VideoResize::Stretch,
147 interpolation: VideoInterpolation::Bilinear,
148 mean: [0.0; 3],
149 std: [1.0; 3],
150 unspecified_color: VideoColorInfo::new(VideoColorMatrix::Bt709, VideoColorRange::Limited),
151 }
152 }
153}
154
155impl VideoMatrixConfig {
156 pub fn imagenet() -> Self {
158 Self {
159 mean: [0.485, 0.456, 0.406],
160 std: [0.229, 0.224, 0.225],
161 ..Self::default()
162 }
163 }
164}
165
166#[derive(Clone, Copy, PartialEq, Eq)]
168struct ResolvedColor {
169 matrix: VideoColorMatrix,
170 range: VideoColorRange,
171}
172
173fn resolve_color(frame: &VideoFrame, fallback: VideoColorInfo) -> Result<ResolvedColor> {
174 let color = frame.color_info();
175 let matrix = match color.matrix() {
176 VideoColorMatrix::Unspecified => fallback.matrix(),
177 explicit => explicit,
178 };
179 let range = match color.range() {
180 VideoColorRange::Unspecified => fallback.range(),
181 explicit => explicit,
182 };
183 let matrix = match matrix {
184 VideoColorMatrix::Unspecified => {
185 return Err(Error::invalid_argument(
186 "to_matrix requires resolved color metadata",
187 ));
188 }
189 explicit => explicit,
190 };
191 let range = match range {
192 VideoColorRange::Unspecified => {
193 return Err(Error::invalid_argument(
194 "to_matrix requires a resolved component range",
195 ));
196 }
197 explicit => explicit,
198 };
199 Ok(ResolvedColor { matrix, range })
200}
201
202fn color_space_index(matrix: VideoColorMatrix) -> u32 {
203 match matrix {
204 VideoColorMatrix::Bt601 => 0,
205 VideoColorMatrix::Bt709 => 1,
206 VideoColorMatrix::Bt2020 => 2,
207 VideoColorMatrix::Unspecified => 1,
208 }
209}
210
211fn color_token(matrix: VideoColorMatrix) -> &'static str {
212 match matrix {
213 VideoColorMatrix::Bt601 => "bt601",
214 VideoColorMatrix::Bt709 => "bt709",
215 VideoColorMatrix::Bt2020 => "bt2020",
216 VideoColorMatrix::Unspecified => "unspecified",
217 }
218}
219
220fn u32_field(value: usize, operation: &str, what: &str) -> Result<u32> {
221 u32::try_from(value).map_err(|_| Error::out_of_range(format!("{operation} {what} exceeds u32")))
222}
223
224pub fn to_matrix(frames: &[VideoFrame], config: &VideoMatrixConfig) -> Result<Matrix> {
239 const OPERATION: &str = "video::to_matrix";
240 if frames.is_empty() {
241 return Err(Error::invalid_argument(format!(
242 "{OPERATION} requires at least one frame"
243 )));
244 }
245 let first = frames[0].device_planar().ok_or_else(|| {
246 Error::invalid_argument(format!(
247 "{OPERATION} requires device-planar frames; stage host frames with VideoFrame::upload"
248 ))
249 })?;
250 let runtime = first.planes[0].runtime();
251 let format = first.format;
252 let frame_width = first.width;
253 let frame_height = first.height;
254 let color = resolve_color(&frames[0], config.unspecified_color)?;
255 let mut plane_inputs: Vec<&Matrix> = Vec::new();
256 let mut planars = Vec::with_capacity(frames.len());
257 for frame in frames {
258 let planar = frame.device_planar().ok_or_else(|| {
259 Error::invalid_argument(format!(
260 "{OPERATION} requires every frame to be device-planar"
261 ))
262 })?;
263 if planar.format != format || planar.width != frame_width || planar.height != frame_height {
264 return Err(Error::invalid_argument(format!(
265 "{OPERATION} requires identical format and extent in one batch"
266 )));
267 }
268 if !planar.planes[0].runtime().same_as(runtime) {
269 return Err(Error::invalid_argument(format!(
270 "{OPERATION} requires frames from one runtime"
271 )));
272 }
273 if resolve_color(frame, config.unspecified_color)? != color {
274 return Err(Error::invalid_argument(format!(
275 "{OPERATION} requires identical resolved color metadata in one batch"
276 )));
277 }
278 for plane in planar.planes.iter() {
279 u32_field(plane.num_elements(), OPERATION, "plane byte length")?;
280 }
281 plane_inputs.extend(planar.planes.iter());
282 planars.push(planar);
283 }
284
285 let crop = config.crop.unwrap_or(VideoRegion {
286 x: 0,
287 y: 0,
288 width: u32_field(frame_width, OPERATION, "width")?,
289 height: u32_field(frame_height, OPERATION, "height")?,
290 });
291 {
292 let right = u64::from(crop.x) + u64::from(crop.width);
293 let bottom = u64::from(crop.y) + u64::from(crop.height);
294 if crop.width == 0
295 || crop.height == 0
296 || right > frame_width as u64
297 || bottom > frame_height as u64
298 {
299 return Err(Error::invalid_argument(format!(
300 "{OPERATION} crop must be a non-empty region inside the visible extent"
301 )));
302 }
303 }
304 let (out_width, out_height) = config.size.unwrap_or((crop.width, crop.height));
305 if out_width == 0 || out_height == 0 {
306 return Err(Error::invalid_argument(format!(
307 "{OPERATION} requires a non-zero output extent"
308 )));
309 }
310 let batch = frames.len();
311 if matches!(config.layout, ImageLayout::Chw | ImageLayout::Hwc) && batch != 1 {
312 return Err(Error::invalid_argument(format!(
313 "{OPERATION} unbatched layouts require exactly one frame"
314 )));
315 }
316 if !matches!(
317 config.layout,
318 ImageLayout::Nchw | ImageLayout::Nhwc | ImageLayout::Chw | ImageLayout::Hwc
319 ) {
320 return Err(Error::invalid_argument(format!(
321 "{OPERATION} requires an NCHW, NHWC, CHW or HWC layout"
322 )));
323 }
324 let channel_count = config.channels.count();
325 let layout_packed = matches!(config.layout, ImageLayout::Nhwc | ImageLayout::Hwc);
326 let shape = match config.layout {
327 ImageLayout::Nchw => vec![
328 batch,
329 channel_count,
330 out_height as usize,
331 out_width as usize,
332 ],
333 ImageLayout::Nhwc => vec![
334 batch,
335 out_height as usize,
336 out_width as usize,
337 channel_count,
338 ],
339 ImageLayout::Chw => vec![channel_count, out_height as usize, out_width as usize],
340 ImageLayout::Hwc => vec![out_height as usize, out_width as usize, channel_count],
341 ImageLayout::Hw => unreachable!("layout checked above"),
342 };
343 let elements = shape.iter().try_fold(1usize, |total, axis| {
344 total
345 .checked_mul(*axis)
346 .ok_or_else(|| Error::out_of_range(format!("{OPERATION} output size overflows usize")))
347 })?;
348 let output = Matrix::allocate(runtime, shape, elements, DType::F32)?;
349
350 let crop_w = f64::from(crop.width);
354 let crop_h = f64::from(crop.height);
355 let out_w = f64::from(out_width);
356 let out_h = f64::from(out_height);
357 let (scale_x, scale_y, off_x, off_y, valid, fill) = match config.resize {
358 VideoResize::Stretch => (
359 crop_w / out_w,
360 crop_h / out_h,
361 f64::from(crop.x) - 0.5,
362 f64::from(crop.y) - 0.5,
363 (0.0f64, 0.0f64, out_w, out_h),
364 [0.0f32; 3],
365 ),
366 VideoResize::CenterCrop => {
367 let scale = (out_w / crop_w).max(out_h / crop_h);
368 let src_w = out_w / scale;
369 let src_h = out_h / scale;
370 let src_x = f64::from(crop.x) + (crop_w - src_w) * 0.5;
371 let src_y = f64::from(crop.y) + (crop_h - src_h) * 0.5;
372 (
373 src_w / out_w,
374 src_h / out_h,
375 src_x - 0.5,
376 src_y - 0.5,
377 (0.0f64, 0.0f64, out_w, out_h),
378 [0.0f32; 3],
379 )
380 }
381 VideoResize::Letterbox { fill } => {
382 let scale = (out_w / crop_w).min(out_h / crop_h);
383 let map_w = crop_w * scale;
384 let map_h = crop_h * scale;
385 let ix0 = (out_w - map_w) * 0.5;
386 let iy0 = (out_h - map_h) * 0.5;
387 (
388 crop_w / map_w,
389 crop_h / map_h,
390 f64::from(crop.x) - ix0 * (crop_w / map_w) - 0.5,
391 f64::from(crop.y) - iy0 * (crop_h / map_h) - 0.5,
392 (ix0, iy0, ix0 + map_w, iy0 + map_h),
393 fill,
394 )
395 }
396 };
397
398 let kernel = match format {
399 VideoPixelFormat::Yuv420Planar8 => KernelId::VideoToMatrixI420,
400 VideoPixelFormat::Nv12 => KernelId::VideoToMatrixNv12,
401 VideoPixelFormat::P010 => KernelId::VideoToMatrixP010,
402 VideoPixelFormat::Yuv420Planar10 | VideoPixelFormat::P012 => {
403 return Err(Error::missing_capability(format!(
404 "{OPERATION} supports I420, NV12, and P010"
405 )));
406 }
407 };
408 let color_mode =
409 color_space_index(color.matrix) * 2 + u32::from(matches!(color.range, VideoColorRange::Full));
410 let luma_width = u32_field(frame_width, OPERATION, "luma width")?;
411 let luma_height = u32_field(frame_height, OPERATION, "luma height")?;
412 let chroma_width = u32_field(frame_width.div_ceil(2), OPERATION, "chroma width")?;
413 let chroma_height = u32_field(frame_height.div_ceil(2), OPERATION, "chroma height")?;
414 let workgroups = [
415 out_width.div_ceil(16),
416 out_height.div_ceil(16),
417 channel_count as u32,
418 ];
419 let frame_span = channel_count
420 .checked_mul(out_height as usize)
421 .and_then(|span| span.checked_mul(out_width as usize))
422 .ok_or_else(|| Error::out_of_range(format!("{OPERATION} frame span overflows usize")))?;
423
424 let mut dispatches = Vec::with_capacity(batch);
425 let mut binding_store: Vec<Vec<BufferBinding>> = Vec::with_capacity(batch);
426 for (index, planar) in planars.iter().enumerate() {
427 let mut bindings = Vec::with_capacity(planar.planes.len() + 1);
428 for plane in planar.planes.iter() {
429 bindings.push(BufferBinding::read(plane.storage()));
430 }
431 bindings.push(BufferBinding::write(output.storage()));
432 binding_store.push(bindings);
433 let push = [
434 PushConstant::U32(out_width),
435 PushConstant::U32(out_height),
436 PushConstant::U32(u32_field(index * frame_span, OPERATION, "batch offset")?),
437 PushConstant::U32(config.channels.mode()),
438 PushConstant::U32(u32::from(layout_packed)),
439 PushConstant::U32(config.interpolation.mode()),
440 PushConstant::U32(luma_width),
441 PushConstant::U32(luma_height),
442 PushConstant::U32(chroma_width),
443 PushConstant::U32(chroma_height),
444 PushConstant::U32(color_mode),
445 PushConstant::F32(off_x as f32),
446 PushConstant::F32(off_y as f32),
447 PushConstant::F32(scale_x as f32),
448 PushConstant::F32(scale_y as f32),
449 PushConstant::F32(valid.0 as f32),
450 PushConstant::F32(valid.1 as f32),
451 PushConstant::F32(valid.2 as f32),
452 PushConstant::F32(valid.3 as f32),
453 PushConstant::F32(fill[0]),
454 PushConstant::F32(fill[1]),
455 PushConstant::F32(fill[2]),
456 PushConstant::F32(config.mean[0]),
457 PushConstant::F32(config.mean[1]),
458 PushConstant::F32(config.mean[2]),
459 PushConstant::F32(config.std[0]),
460 PushConstant::F32(config.std[1]),
461 PushConstant::F32(config.std[2]),
462 ];
463 dispatches.push((binding_store.len() - 1, push));
464 }
465 let dispatch_list: Vec<ComputeDispatch> = dispatches
466 .iter()
467 .map(|(binding_index, push)| ComputeDispatch {
468 kernel,
469 buffers: &binding_store[*binding_index],
470 push_constants: push,
471 workgroups,
472 indirect: None,
473 })
474 .collect();
475 let outputs = [&output];
476 let attributes = [
477 OpAttribute::Enum {
478 name: "channels".into(),
479 value: config.channels.token().into(),
480 },
481 OpAttribute::Enum {
482 name: "layout".into(),
483 value: if layout_packed { "nhwc" } else { "nchw" }.into(),
484 },
485 OpAttribute::Enum {
486 name: "interpolation".into(),
487 value: config.interpolation.token().into(),
488 },
489 OpAttribute::Enum {
490 name: "resize".into(),
491 value: config.resize.token().into(),
492 },
493 OpAttribute::Enum {
494 name: "color_space".into(),
495 value: color_token(color.matrix).into(),
496 },
497 OpAttribute::Boolean {
498 name: "full_range".into(),
499 value: matches!(color.range, VideoColorRange::Full),
500 },
501 OpAttribute::String {
502 name: "normalization".into(),
503 value: format!(
504 "{},{},{};{},{},{}",
505 config.mean[0], config.mean[1], config.mean[2], config.std[0], config.std[1], config.std[2]
506 ),
507 },
508 OpAttribute::String {
509 name: "crop".into(),
510 value: format!("{},{},{},{}", crop.x, crop.y, crop.width, crop.height),
511 },
512 ];
513 let semantic = SemanticDispatch {
514 contract: crate::core::operation::video::TO_MATRIX,
515 inputs: &plane_inputs,
516 outputs: &outputs,
517 attributes: &attributes,
518 };
519 if dispatches.len() == 1 {
520 let (binding_index, push) = &dispatches[0];
521 runtime.record_semantic(
522 ComputeDispatch {
523 kernel,
524 buffers: &binding_store[*binding_index],
525 push_constants: push,
526 workgroups,
527 indirect: None,
528 },
529 semantic,
530 )?;
531 } else {
532 runtime.record_split_semantic(&dispatch_list, semantic)?;
533 }
534 Ok(output)
535}
536
537impl VideoFrame {
538 pub fn to_matrix(&self, config: &VideoMatrixConfig) -> Result<Matrix> {
544 to_matrix(std::slice::from_ref(self), config)
545 }
546}