1//! Single-pass GPU NV12 -> RGBA (+ rotation) compute pipeline with pooled Y/UV upload textures.
2//!
3//! Declared as a submodule inside `eval/io.rs` so `eval/mod.rs` stays untouched.
4
5use crate::cache::CachedTexture;
6use crate::media::Nv12Frame;
7use bytemuck::{Pod, Zeroable};
8use std::collections::HashMap;
9use std::num::NonZeroU64;
10
11const NV12_WGSL: &str = include_str!("../shaders/nv12_to_rgba.wgsl");
12const NV12_UNIFORM_SLOTS_PER_CHUNK: u32 = 512;
13#[cfg(not(target_arch = "wasm32"))]
14const MAX_POOLED_PLANE_SIZES: usize = 8;
15
16#[repr(C)]
17#[derive(Clone, Copy, Pod, Zeroable)]
18struct Nv12UniformParams {
19 raw_w: u32,
20 raw_h: u32,
21 out_w: u32,
22 out_h: u32,
23 rot_deg: u32,
24 matrix_id: u32,
25 full_range: u32,
26 _pad: u32,
27}
28
29struct Nv12FormatPipeline {
30 bgl: wgpu::BindGroupLayout,
31 pipeline: wgpu::ComputePipeline,
32}
33
34struct Nv12PlanePair {
35 y_tex: wgpu::Texture,
36 y_view: wgpu::TextureView,
37 uv_tex: wgpu::Texture,
38 uv_view: wgpu::TextureView,
39 #[cfg(not(target_arch = "wasm32"))]
40 bytes: u64,
41 #[cfg(not(target_arch = "wasm32"))]
42 last_used: u64,
43}
44
45impl Nv12PlanePair {
46 fn new(device: &wgpu::Device, raw_w: u32, raw_h: u32) -> Self {
47 let uv_w = raw_w.div_ceil(2);
48 let uv_h = raw_h.div_ceil(2);
49 let y_tex = device.create_texture(&wgpu::TextureDescriptor {
50 label: Some("nv12-y-plane"),
51 size: wgpu::Extent3d {
52 width: raw_w,
53 height: raw_h,
54 depth_or_array_layers: 1,
55 },
56 mip_level_count: 1,
57 sample_count: 1,
58 dimension: wgpu::TextureDimension::D2,
59 format: wgpu::TextureFormat::R8Unorm,
60 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
61 view_formats: &[],
62 });
63 let y_view = y_tex.create_view(&wgpu::TextureViewDescriptor::default());
64
65 let uv_tex = device.create_texture(&wgpu::TextureDescriptor {
66 label: Some("nv12-uv-plane"),
67 size: wgpu::Extent3d {
68 width: uv_w,
69 height: uv_h,
70 depth_or_array_layers: 1,
71 },
72 mip_level_count: 1,
73 sample_count: 1,
74 dimension: wgpu::TextureDimension::D2,
75 format: wgpu::TextureFormat::Rg8Unorm,
76 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
77 view_formats: &[],
78 });
79 let uv_view = uv_tex.create_view(&wgpu::TextureViewDescriptor::default());
80 #[cfg(not(target_arch = "wasm32"))]
81 let bytes = u64::from(raw_w)
82 .saturating_mul(u64::from(raw_h))
83 .saturating_add(u64::from(uv_w).saturating_mul(u64::from(uv_h)).saturating_mul(2));
84
85 Self {
86 y_tex,
87 y_view,
88 uv_tex,
89 uv_view,
90 #[cfg(not(target_arch = "wasm32"))]
91 bytes,
92 #[cfg(not(target_arch = "wasm32"))]
93 last_used: 0,
94 }
95 }
96}
97
98pub(crate) struct Nv12Pipelines {
99 sampler: wgpu::Sampler,
100 uniform_chunks: Vec<wgpu::Buffer>,
101 uniform_stride: u32,
102 uniform_cursor: u32,
103 pipelines: HashMap<wgpu::TextureFormat, Nv12FormatPipeline>,
104 #[cfg(not(target_arch = "wasm32"))]
105 plane_pool: HashMap<(u32, u32), Nv12PlanePair>,
106 #[cfg(not(target_arch = "wasm32"))]
107 tick: u64,
108}
109
110impl Nv12Pipelines {
111 fn new(device: &wgpu::Device) -> Self {
112 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
113 label: Some("nv12-uv-linear-sampler"),
114 address_mode_u: wgpu::AddressMode::ClampToEdge,
115 address_mode_v: wgpu::AddressMode::ClampToEdge,
116 address_mode_w: wgpu::AddressMode::ClampToEdge,
117 mag_filter: wgpu::FilterMode::Linear,
118 min_filter: wgpu::FilterMode::Linear,
119 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
120 ..Default::default()
121 });
122
123 let align = device.limits().min_uniform_buffer_offset_alignment.max(32);
124 let raw_size = std::mem::size_of::<Nv12UniformParams>() as u32;
125 let uniform_stride = raw_size.div_ceil(align) * align;
126
127 Self {
128 sampler,
129 uniform_chunks: Vec::new(),
130 uniform_stride,
131 uniform_cursor: 0,
132 pipelines: HashMap::new(),
133 #[cfg(not(target_arch = "wasm32"))]
134 plane_pool: HashMap::new(),
135 #[cfg(not(target_arch = "wasm32"))]
136 tick: 0,
137 }
138 }
139
140 pub(crate) fn reset_uniform_cursor(&mut self) {
141 self.uniform_cursor = 0;
142 }
143
144 pub(crate) fn trim_uniform_chunks(&mut self, max_chunks: usize) {
145 self.uniform_cursor = 0;
146 if self.uniform_chunks.len() > max_chunks {
147 self.uniform_chunks.truncate(max_chunks);
148 }
149 }
150
151 pub(crate) fn vram_bytes(&self) -> u64 {
152 let uniform_bytes: u64 = self.uniform_chunks.iter().map(wgpu::Buffer::size).sum();
153 #[cfg(not(target_arch = "wasm32"))]
154 let plane_bytes: u64 = self.plane_pool.values().map(|p| p.bytes).sum();
155 #[cfg(target_arch = "wasm32")]
156 let plane_bytes: u64 = 0;
157 uniform_bytes.saturating_add(plane_bytes)
158 }
159
160 pub(crate) fn clear_plane_pool(&mut self) {
161 #[cfg(not(target_arch = "wasm32"))]
162 {
163 self.plane_pool.clear();
164 self.tick = 0;
165 }
166 }
167
168 fn alloc_uniform_slot(
169 &mut self,
170 device: &wgpu::Device,
171 queue: &wgpu::Queue,
172 params: &Nv12UniformParams,
173 ) -> (usize, u32) {
174 let slot_global = self.uniform_cursor;
175 let chunk_idx = (slot_global / NV12_UNIFORM_SLOTS_PER_CHUNK) as usize;
176 let slot_in_chunk = slot_global % NV12_UNIFORM_SLOTS_PER_CHUNK;
177 while chunk_idx >= self.uniform_chunks.len() {
178 let size = u64::from(NV12_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);
179 let buf = device.create_buffer(&wgpu::BufferDescriptor {
180 label: Some("nv12-uniform-ring"),
181 size,
182 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
183 mapped_at_creation: false,
184 });
185 self.uniform_chunks.push(buf);
186 }
187 let dyn_offset = slot_in_chunk * self.uniform_stride;
188 queue.write_buffer(
189 &self.uniform_chunks[chunk_idx],
190 u64::from(dyn_offset),
191 bytemuck::bytes_of(params),
192 );
193 self.uniform_cursor = slot_global + 1;
194 (chunk_idx, dyn_offset)
195 }
196
197 fn ensure_pipeline(&mut self, device: &wgpu::Device, dst_format: wgpu::TextureFormat) {
198 if self.pipelines.contains_key(&dst_format) {
199 return;
200 }
201 let storage_fmt = match dst_format {
202 wgpu::TextureFormat::Rgba16Float => "rgba16float",
203 wgpu::TextureFormat::Rgba32Float => "rgba32float",
204 _ => "rgba8unorm",
205 };
206 let src = if storage_fmt == "rgba8unorm" {
207 std::borrow::Cow::Borrowed(NV12_WGSL)
208 } else {
209 std::borrow::Cow::Owned(NV12_WGSL.replace(
210 "texture_storage_2d<rgba8unorm, write>",
211 &format!("texture_storage_2d<{storage_fmt}, write>"),
212 ))
213 };
214
215 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
216 label: Some("nv12-to-rgba-wgsl"),
217 source: wgpu::ShaderSource::Wgsl(src),
218 });
219
220 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
221 label: Some("nv12-to-rgba-bgl"),
222 entries: &[
223 wgpu::BindGroupLayoutEntry {
224 binding: 0,
225 visibility: wgpu::ShaderStages::COMPUTE,
226 ty: wgpu::BindingType::Texture {
227 sample_type: wgpu::TextureSampleType::Float { filterable: false },
228 view_dimension: wgpu::TextureViewDimension::D2,
229 multisampled: false,
230 },
231 count: None,
232 },
233 wgpu::BindGroupLayoutEntry {
234 binding: 1,
235 visibility: wgpu::ShaderStages::COMPUTE,
236 ty: wgpu::BindingType::Texture {
237 sample_type: wgpu::TextureSampleType::Float { filterable: true },
238 view_dimension: wgpu::TextureViewDimension::D2,
239 multisampled: false,
240 },
241 count: None,
242 },
243 wgpu::BindGroupLayoutEntry {
244 binding: 2,
245 visibility: wgpu::ShaderStages::COMPUTE,
246 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
247 count: None,
248 },
249 wgpu::BindGroupLayoutEntry {
250 binding: 3,
251 visibility: wgpu::ShaderStages::COMPUTE,
252 ty: wgpu::BindingType::StorageTexture {
253 access: wgpu::StorageTextureAccess::WriteOnly,
254 format: dst_format,
255 view_dimension: wgpu::TextureViewDimension::D2,
256 },
257 count: None,
258 },
259 wgpu::BindGroupLayoutEntry {
260 binding: 4,
261 visibility: wgpu::ShaderStages::COMPUTE,
262 ty: wgpu::BindingType::Buffer {
263 ty: wgpu::BufferBindingType::Uniform,
264 has_dynamic_offset: true,
265 min_binding_size: NonZeroU64::new(
266 std::mem::size_of::<Nv12UniformParams>() as u64,
267 ),
268 },
269 count: None,
270 },
271 ],
272 });
273
274 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
275 label: Some("nv12-to-rgba-layout"),
276 bind_group_layouts: &[Some(&bgl)],
277 immediate_size: 0,
278 });
279
280 let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
281 label: Some("nv12-to-rgba-pipeline"),
282 layout: Some(&layout),
283 module: &module,
284 entry_point: Some("nv12_to_rgba"),
285 compilation_options: wgpu::PipelineCompilationOptions::default(),
286 cache: None,
287 });
288
289 self.pipelines.insert(dst_format, Nv12FormatPipeline { bgl, pipeline });
290 }
291
292 #[cfg(not(target_arch = "wasm32"))]
293 fn acquire_pooled_planes(
294 &mut self,
295 device: &wgpu::Device,
296 raw_w: u32,
297 raw_h: u32,
298 ) -> &Nv12PlanePair {
299 self.tick = self.tick.wrapping_add(1);
300 let tick = self.tick;
301 let key = (raw_w, raw_h);
302 if !self.plane_pool.contains_key(&key) {
303 if self.plane_pool.len() >= MAX_POOLED_PLANE_SIZES {
304 if let Some(oldest) = self
305 .plane_pool
306 .iter()
307 .min_by_key(|(_, p)| p.last_used)
308 .map(|(&k, _)| k)
309 {
310 self.plane_pool.remove(&oldest);
311 }
312 }
313 self.plane_pool
314 .insert(key, Nv12PlanePair::new(device, raw_w, raw_h));
315 }
316 let pair = self.plane_pool.get_mut(&key).expect("just inserted");
317 pair.last_used = tick;
318 pair
319 }
320
321 #[allow(clippy::too_many_arguments)]
322 fn encode_dispatch(
323 &mut self,
324 device: &wgpu::Device,
325 queue: &wgpu::Queue,
326 enc: &mut wgpu::CommandEncoder,
327 y_view: &wgpu::TextureView,
328 uv_view: &wgpu::TextureView,
329 nv12: &Nv12Frame,
330 dst: &CachedTexture,
331 ) {
332 self.ensure_pipeline(device, dst.format);
333
334 let params = Nv12UniformParams {
335 raw_w: nv12.raw_size[0],
336 raw_h: nv12.raw_size[1],
337 out_w: dst.size[0],
338 out_h: dst.size[1],
339 rot_deg: nv12.rot_deg,
340 matrix_id: nv12.matrix as u32,
341 full_range: u32::from(nv12.is_full_range),
342 _pad: 0,
343 };
344 let (chunk_idx, dyn_offset) = self.alloc_uniform_slot(device, queue, &params);
345
346 let fp = &self.pipelines[&dst.format];
347 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
348 label: Some("nv12-to-rgba-bg"),
349 layout: &fp.bgl,
350 entries: &[
351 wgpu::BindGroupEntry {
352 binding: 0,
353 resource: wgpu::BindingResource::TextureView(y_view),
354 },
355 wgpu::BindGroupEntry {
356 binding: 1,
357 resource: wgpu::BindingResource::TextureView(uv_view),
358 },
359 wgpu::BindGroupEntry {
360 binding: 2,
361 resource: wgpu::BindingResource::Sampler(&self.sampler),
362 },
363 wgpu::BindGroupEntry {
364 binding: 3,
365 resource: wgpu::BindingResource::TextureView(&dst.view),
366 },
367 wgpu::BindGroupEntry {
368 binding: 4,
369 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
370 buffer: &self.uniform_chunks[chunk_idx],
371 offset: 0,
372 size: NonZeroU64::new(std::mem::size_of::<Nv12UniformParams>() as u64),
373 }),
374 },
375 ],
376 });
377
378 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
379 label: Some("nv12-to-rgba-pass"),
380 timestamp_writes: None,
381 });
382 pass.set_pipeline(&fp.pipeline);
383 pass.set_bind_group(0, &bg, &[dyn_offset]);
384 pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1);
385 }
386}
387
388#[cfg(not(target_arch = "wasm32"))]
389fn stage_plane_into_buffer(
390 media: &crate::media::MediaCache,
391 device: &wgpu::Device,
392 data: &[u8],
393 width: u32,
394 height: u32,
395 bytes_per_pixel: u32,
396) -> Option<(wgpu::Buffer, u32)> {
397 let unpadded_bpr = width.checked_mul(bytes_per_pixel)?;
398 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
399 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
400 let needed = u64::from(padded_bpr).checked_mul(u64::from(height))?;
401 let buf = media.acquire_upload_staging(device, needed)?;
402 let cap = buf.size();
403 let copied = if let Ok(mut view) = buf.slice(..needed).get_mapped_range_mut() {
404 if padded_bpr == unpadded_bpr {
405 let total = (unpadded_bpr as usize) * (height as usize);
406 if data.len() >= total {
407 view.slice(..total).copy_from_slice(&data[..total]);
408 true
409 } else {
410 false
411 }
412 } else {
413 let src_stride = unpadded_bpr as usize;
414 let dst_stride = padded_bpr as usize;
415 if data.len() >= src_stride * (height as usize) {
416 let mut wo = view.slice(..needed as usize);
417 for (row_idx, src_row) in data
418 .chunks_exact(src_stride)
419 .take(height as usize)
420 .enumerate()
421 {
422 let off = row_idx * dst_stride;
423 wo.slice(off..off + src_stride).copy_from_slice(src_row);
424 }
425 true
426 } else {
427 false
428 }
429 }
430 } else {
431 false
432 };
433 if copied {
434 buf.unmap();
435 Some((buf, padded_bpr))
436 } else {
437 drop(buf);
438 media.release_failed_upload_staging(cap);
439 None
440 }
441}
442
443/// Uploads NV12 Y (`R8Unorm`) and UV (`Rg8Unorm`) planes and runs a single-pass compute shader
444/// writing rotated, color-converted RGBA directly into `dst` (`Rgba8Unorm`, `Rgba16Float`, or
445/// `Rgba32Float`).
446pub(super) fn upload_and_convert_nv12(
447 engine: &crate::Engine,
448 enc: &mut wgpu::CommandEncoder,
449 nv12: &Nv12Frame,
450 dst: &CachedTexture,
451) {
452 let [raw_w, raw_h] = nv12.raw_size;
453 let [uv_w, uv_h] = nv12.uv_size();
454 if raw_w == 0 || raw_h == 0 || uv_w == 0 || uv_h == 0 || dst.size[0] == 0 || dst.size[1] == 0 {
455 return;
456 }
457
458 #[cfg(not(target_arch = "wasm32"))]
459 {
460 // Prefer pooled Y/UV textures + in-order `copy_buffer_to_texture` via `UploadStagingPool`:
461 // zero per-frame GPU texture allocations and zero write hazards even with multiple NV12
462 // loaders sharing the same `CommandEncoder`.
463 let staged_y = stage_plane_into_buffer(&engine.media, &engine.device, &nv12.y, raw_w, raw_h, 1);
464 let staged_uv = if staged_y.is_some() {
465 stage_plane_into_buffer(&engine.media, &engine.device, &nv12.uv, uv_w, uv_h, 2)
466 } else {
467 None
468 };
469
470 match (staged_y, staged_uv) {
471 (Some((y_buf, y_bpr)), Some((uv_buf, uv_bpr))) => {
472 engine.media.with_nv12_gpu_state(
473 || Nv12Pipelines::new(&engine.device),
474 |pipe| {
475 pipe.acquire_pooled_planes(&engine.device, raw_w, raw_h);
476 let pair = &pipe.plane_pool[&(raw_w, raw_h)];
477 enc.copy_buffer_to_texture(
478 wgpu::TexelCopyBufferInfo {
479 buffer: &y_buf,
480 layout: wgpu::TexelCopyBufferLayout {
481 offset: 0,
482 bytes_per_row: Some(y_bpr),
483 rows_per_image: Some(raw_h),
484 },
485 },
486 pair.y_tex.as_image_copy(),
487 wgpu::Extent3d {
488 width: raw_w,
489 height: raw_h,
490 depth_or_array_layers: 1,
491 },
492 );
493 enc.copy_buffer_to_texture(
494 wgpu::TexelCopyBufferInfo {
495 buffer: &uv_buf,
496 layout: wgpu::TexelCopyBufferLayout {
497 offset: 0,
498 bytes_per_row: Some(uv_bpr),
499 rows_per_image: Some(uv_h),
500 },
501 },
502 pair.uv_tex.as_image_copy(),
503 wgpu::Extent3d {
504 width: uv_w,
505 height: uv_h,
506 depth_or_array_layers: 1,
507 },
508 );
509 let y_view = pair.y_view.clone();
510 let uv_view = pair.uv_view.clone();
511 pipe.encode_dispatch(
512 &engine.device,
513 &engine.queue,
514 enc,
515 &y_view,
516 &uv_view,
517 nv12,
518 dst,
519 );
520 },
521 );
522 engine.media.recycle_upload_staging(y_buf);
523 engine.media.recycle_upload_staging(uv_buf);
524 return;
525 }
526 (Some((y_buf, _)), None) => {
527 engine.media.recycle_upload_staging(y_buf);
528 }
529 _ => {}
530 }
531
532 // Fallback when staging pool is temporarily exhausted (or on wasm32): use fresh textures with
533 // `queue.write_texture` so multiple dispatches in one encoder cannot overwrite each other.
534 }
535
536 let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h);
537 engine.queue.write_texture(
538 fresh.y_tex.as_image_copy(),
539 &nv12.y,
540 wgpu::TexelCopyBufferLayout {
541 offset: 0,
542 bytes_per_row: Some(raw_w),
543 rows_per_image: Some(raw_h),
544 },
545 wgpu::Extent3d {
546 width: raw_w,
547 height: raw_h,
548 depth_or_array_layers: 1,
549 },
550 );
551 engine.queue.write_texture(
552 fresh.uv_tex.as_image_copy(),
553 &nv12.uv,
554 wgpu::TexelCopyBufferLayout {
555 offset: 0,
556 bytes_per_row: Some(uv_w * 2),
557 rows_per_image: Some(uv_h),
558 },
559 wgpu::Extent3d {
560 width: uv_w,
561 height: uv_h,
562 depth_or_array_layers: 1,
563 },
564 );
565 engine.media.with_nv12_gpu_state(
566 || Nv12Pipelines::new(&engine.device),
567 |pipe| {
568 pipe.encode_dispatch(
569 &engine.device,
570 &engine.queue,
571 enc,
572 &fresh.y_view,
573 &fresh.uv_view,
574 nv12,
575 dst,
576 );
577 },
578 );
579}
580
581#[cfg(all(test, not(target_arch = "wasm32")))]
582mod tests {
583 use super::*;
584 use crate::Engine;
585 use crate::media::YuvMatrix;
586 use model::{BitDepth, Comp};
587
588 fn make_pattern_nv12(
589 raw_w: u32,
590 raw_h: u32,
591 rot_deg: u32,
592 matrix: YuvMatrix,
593 is_full_range: bool,
594 ) -> Nv12Frame {
595 let uv_w = raw_w.div_ceil(2);
596 let uv_h = raw_h.div_ceil(2);
597 let mut y = vec![0u8; (raw_w * raw_h) as usize];
598 let mut uv = vec![128u8; (uv_w * uv_h * 2) as usize];
599
600 let (y_min, y_max) = if is_full_range { (0.0_f32, 255.0_f32) } else { (16.0_f32, 235.0_f32) };
601 let (c_min, c_max) = if is_full_range { (0.0_f32, 255.0_f32) } else { (16.0_f32, 240.0_f32) };
602
603 for py in 0..raw_h {
604 for px in 0..raw_w {
605 let fx = px as f32 / raw_w.saturating_sub(1).max(1) as f32;
606 let fy = py as f32 / raw_h.saturating_sub(1).max(1) as f32;
607 let luma = y_min + (y_max - y_min) * (0.15 + 0.7 * (0.5 * fx + 0.5 * fy));
608 y[(py * raw_w + px) as usize] = luma.round().clamp(0.0, 255.0) as u8;
609 }
610 }
611 for cy in 0..uv_h {
612 for cx in 0..uv_w {
613 let fx = cx as f32 / uv_w.saturating_sub(1).max(1) as f32;
614 let fy = cy as f32 / uv_h.saturating_sub(1).max(1) as f32;
615 let cb = c_min + (c_max - c_min) * (0.2 + 0.6 * fx);
616 let cr = c_min + (c_max - c_min) * (0.8 - 0.6 * fy);
617 let idx = ((cy * uv_w + cx) * 2) as usize;
618 uv[idx] = cb.round().clamp(0.0, 255.0) as u8;
619 uv[idx + 1] = cr.round().clamp(0.0, 255.0) as u8;
620 }
621 }
622
623 let display_size = if rot_deg == 90 || rot_deg == 270 {
624 [raw_h, raw_w]
625 } else {
626 [raw_w, raw_h]
627 };
628 Nv12Frame {
629 raw_size: [raw_w, raw_h],
630 display_size,
631 rot_deg,
632 matrix,
633 is_full_range,
634 y,
635 uv,
636 }
637 }
638
639 fn make_quadrant_nv12(raw_w: u32, raw_h: u32, rot_deg: u32) -> Nv12Frame {
640 let uv_w = raw_w.div_ceil(2);
641 let uv_h = raw_h.div_ceil(2);
642 let mut y = vec![0u8; (raw_w * raw_h) as usize];
643 let mut uv = vec![128u8; (uv_w * uv_h * 2) as usize];
644 // BT.709 video-range YCbCr for pure Red, Green, Blue, Yellow:
645 // Red: Y=63, Cb=102, Cr=240
646 // Green: Y=173, Cb=42, Cr=26
647 // Blue: Y=32, Cb=240, Cr=118
648 // Yellow: Y=219, Cb=16, Cr=138
649 let quad = |x: u32, y_pos: u32, w: u32, h: u32| -> (u8, u8, u8) {
650 match (x < w / 2, y_pos < h / 2) {
651 (true, true) => (63, 102, 240), // top-left: Red
652 (false, true) => (173, 42, 26), // top-right: Green
653 (true, false) => (32, 240, 118), // bottom-left: Blue
654 (false, false) => (219, 16, 138), // bottom-right: Yellow
655 }
656 };
657 for py in 0..raw_h {
658 for px in 0..raw_w {
659 let (yv, _, _) = quad(px, py, raw_w, raw_h);
660 y[(py * raw_w + px) as usize] = yv;
661 }
662 }
663 for cy in 0..uv_h {
664 for cx in 0..uv_w {
665 let (_, cb, cr) = quad(cx * 2, cy * 2, raw_w, raw_h);
666 let idx = ((cy * uv_w + cx) * 2) as usize;
667 uv[idx] = cb;
668 uv[idx + 1] = cr;
669 }
670 }
671 let display_size = if rot_deg == 90 || rot_deg == 270 {
672 [raw_h, raw_w]
673 } else {
674 [raw_w, raw_h]
675 };
676 Nv12Frame {
677 raw_size: [raw_w, raw_h],
678 display_size,
679 rot_deg,
680 matrix: YuvMatrix::Bt709,
681 is_full_range: false,
682 y,
683 uv,
684 }
685 }
686
687 fn run_gpu_nv12(engine: &Engine, frame: &Nv12Frame, depth: BitDepth) -> Vec<u8> {
688 let mut enc = engine
689 .device
690 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
691 label: Some("nv12-test-enc"),
692 });
693 let dst = engine.alloc_tex(frame.display_size, depth, 0);
694 upload_and_convert_nv12(engine, &mut enc, frame, &dst);
695 engine.queue.submit(Some(enc.finish()));
696 engine.media.flush_upload_staging_after_submit(&engine.device);
697 engine.readback_rgba(&dst).expect("readback_rgba")
698 }
699
700 #[test]
701 fn nv12_gpu_matches_cpu_reference_all_matrices_ranges_and_formats() {
702 let engine = Engine::new_headless().expect("headless engine");
703 for &(raw_w, raw_h) in &[(32u32, 24u32), (17u32, 13u32)] {
704 for &matrix in &[YuvMatrix::Bt709, YuvMatrix::Bt601, YuvMatrix::Bt2020] {
705 for &full_range in &[false, true] {
706 let frame = make_pattern_nv12(raw_w, raw_h, 0, matrix, full_range);
707 let expected = frame.to_rgba8();
708 for &depth in &[BitDepth::Int8, BitDepth::Float16, BitDepth::Float32] {
709 let got = run_gpu_nv12(&engine, &frame, depth);
710 assert_eq!(got.len(), expected.len());
711 let mut max_diff = 0u8;
712 for (i, (&g, &e)) in got.iter().zip(expected.iter()).enumerate() {
713 if i % 4 == 3 {
714 assert_eq!(g, 255, "NV12 alpha must be 255");
715 }
716 max_diff = max_diff.max(g.abs_diff(e));
717 }
718 assert!(
719 max_diff <= 2,
720 "NV12 mismatch ({raw_w}x{raw_h}, {matrix:?}, full={full_range}, {depth:?}): max_diff={max_diff}"
721 );
722 }
723 }
724 }
725 }
726 }
727
728 #[test]
729 fn nv12_gpu_matches_cpu_reference_all_four_rotations() {
730 let engine = Engine::new_headless().expect("headless engine");
731 for &rot_deg in &[0u32, 90, 180, 270] {
732 let frame = make_quadrant_nv12(24, 16, rot_deg);
733 let expected = frame.to_rgba8();
734 let got = run_gpu_nv12(&engine, &frame, BitDepth::Int8);
735 assert_eq!(got.len(), expected.len());
736 let mut max_diff = 0u8;
737 for (&g, &e) in got.iter().zip(expected.iter()) {
738 max_diff = max_diff.max(g.abs_diff(e));
739 }
740 assert!(
741 max_diff <= 2,
742 "rotation {rot_deg} mismatch vs CPU reference: max_diff={max_diff}"
743 );
744
745 // Spot-check interior of each rotated quadrant against expected primary colors.
746 let [ow, oh] = frame.display_size;
747 let px = |x: u32, y: u32| -> [u8; 4] {
748 let i = ((y * ow + x) * 4) as usize;
749 [got[i], got[i + 1], got[i + 2], got[i + 3]]
750 };
751 let tl = px(2, 2);
752 let tr = px(ow - 3, 2);
753 let bl = px(2, oh - 3);
754 let br = px(ow - 3, oh - 3);
755 match rot_deg {
756 0 => {
757 assert!(tl[0] > 200 && tl[1] < 30 && tl[2] < 30, "0° TL should be red: {tl:?}");
758 assert!(tr[1] > 200 && tr[0] < 30 && tr[2] < 30, "0° TR should be green: {tr:?}");
759 assert!(bl[2] > 200 && bl[0] < 30 && bl[1] < 30, "0° BL should be blue: {bl:?}");
760 assert!(br[0] > 200 && br[1] > 200 && br[2] < 30, "0° BR should be yellow: {br:?}");
761 }
762 90 => {
763 // 90° CW: BL(blue)->TL, TL(red)->TR, BR(yellow)->BL, TR(green)->BR
764 assert!(tl[2] > 200 && tl[0] < 30, "90° TL should be blue: {tl:?}");
765 assert!(tr[0] > 200 && tr[1] < 30, "90° TR should be red: {tr:?}");
766 assert!(bl[0] > 200 && bl[1] > 200 && bl[2] < 30, "90° BL should be yellow: {bl:?}");
767 assert!(br[1] > 200 && br[0] < 30, "90° BR should be green: {br:?}");
768 }
769 180 => {
770 assert!(tl[0] > 200 && tl[1] > 200 && tl[2] < 30, "180° TL should be yellow: {tl:?}");
771 assert!(tr[2] > 200 && tr[0] < 30, "180° TR should be blue: {tr:?}");
772 assert!(bl[1] > 200 && bl[0] < 30, "180° BL should be green: {bl:?}");
773 assert!(br[0] > 200 && br[1] < 30, "180° BR should be red: {br:?}");
774 }
775 270 => {
776 // 270° CW (90° CCW): TR(green)->TL, BR(yellow)->TR, TL(red)->BL, BL(blue)->BR
777 assert!(tl[1] > 200 && tl[0] < 30, "270° TL should be green: {tl:?}");
778 assert!(tr[0] > 200 && tr[1] > 200 && tr[2] < 30, "270° TR should be yellow: {tr:?}");
779 assert!(bl[0] > 200 && bl[1] < 30, "270° BL should be red: {bl:?}");
780 assert!(br[2] > 200 && br[0] < 30, "270° BR should be blue: {br:?}");
781 }
782 _ => unreachable!(),
783 }
784 }
785 }
786
787 #[test]
788 fn nv12_multiple_dispatches_same_encoder_no_hazard() {
789 let engine = Engine::new_headless().expect("headless engine");
790 let red = Nv12Frame {
791 raw_size: [16, 16],
792 display_size: [16, 16],
793 rot_deg: 0,
794 matrix: YuvMatrix::Bt709,
795 is_full_range: false,
796 y: vec![63u8; 16 * 16],
797 uv: [102u8, 240u8].repeat(8 * 8),
798 };
799 let blue = Nv12Frame {
800 raw_size: [16, 16],
801 display_size: [16, 16],
802 rot_deg: 0,
803 matrix: YuvMatrix::Bt709,
804 is_full_range: false,
805 y: vec![32u8; 16 * 16],
806 uv: [240u8, 118u8].repeat(8 * 8),
807 };
808
809 let mut enc = engine
810 .device
811 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
812 label: Some("nv12-multi-dispatch"),
813 });
814 let dst_red = engine.alloc_tex([16, 16], BitDepth::Float16, 0);
815 let dst_blue = engine.alloc_tex([16, 16], BitDepth::Float16, 0);
816 upload_and_convert_nv12(&engine, &mut enc, &red, &dst_red);
817 upload_and_convert_nv12(&engine, &mut enc, &blue, &dst_blue);
818 engine.queue.submit(Some(enc.finish()));
819 engine.media.flush_upload_staging_after_submit(&engine.device);
820
821 let r_px = engine.readback_rgba(&dst_red).expect("readback red");
822 let b_px = engine.readback_rgba(&dst_blue).expect("readback blue");
823 assert!(r_px[0] > 220 && r_px[1] < 20 && r_px[2] < 20, "first dispatch corrupted: {:?}", &r_px[..4]);
824 assert!(b_px[2] > 220 && b_px[0] < 20 && b_px[1] < 20, "second dispatch corrupted: {:?}", &b_px[..4]);
825 }
826
827 #[test]
828 fn nv12_uniform_chunk_ring_grows_past_512_resets_trims_and_tracks_vram() {
829 let mut engine = Engine::new_headless().expect("headless engine");
830 let red_0 = Nv12Frame {
831 raw_size: [8, 8],
832 display_size: [8, 8],
833 rot_deg: 0,
834 matrix: YuvMatrix::Bt709,
835 is_full_range: false,
836 y: vec![63u8; 8 * 8],
837 uv: [102u8, 240u8].repeat(4 * 4),
838 };
839 let blue_180 = Nv12Frame {
840 raw_size: [8, 8],
841 display_size: [8, 8],
842 rot_deg: 180,
843 matrix: YuvMatrix::Bt709,
844 is_full_range: false,
845 y: vec![32u8; 8 * 8],
846 uv: [240u8, 118u8].repeat(4 * 4),
847 };
848
849 let mut enc = engine
850 .device
851 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
852 label: Some("nv12-ring-growth-test"),
853 });
854 let dst_first = engine.alloc_tex([8, 8], BitDepth::Int8, 0);
855 let dst_mid = engine.alloc_tex([8, 8], BitDepth::Int8, 0);
856 let dst_last = engine.alloc_tex([8, 8], BitDepth::Int8, 0);
857
858 // Dispatch >512 times in a single CommandEncoder so the uniform ring must grow to a 2nd chunk
859 // without wrapping and clobbering slot 0!
860 upload_and_convert_nv12(&engine, &mut enc, &red_0, &dst_first);
861 for _ in 1..NV12_UNIFORM_SLOTS_PER_CHUNK {
862 upload_and_convert_nv12(&engine, &mut enc, &blue_180, &dst_mid);
863 }
864 // Slot 512 (index 0 of chunk 1) + slot 513 (index 1 of chunk 1)
865 upload_and_convert_nv12(&engine, &mut enc, &blue_180, &dst_mid);
866 upload_and_convert_nv12(&engine, &mut enc, &blue_180, &dst_last);
867
868 let (chunks_before_trim, cursor_before_reset, vram_before_bust) =
869 engine.media.with_nv12_gpu_state(
870 || unreachable!("already initialized"),
871 |pipe| (pipe.uniform_chunks.len(), pipe.uniform_cursor, pipe.vram_bytes()),
872 );
873 assert_eq!(chunks_before_trim, 2, "expected 2 uniform chunks for 514 dispatches");
874 assert_eq!(cursor_before_reset, NV12_UNIFORM_SLOTS_PER_CHUNK + 2);
875 assert!(vram_before_bust > 0);
876 assert!(engine.vram_bytes() >= vram_before_bust);
877
878 engine.queue.submit(Some(enc.finish()));
879 engine.reset_uniform_cursors();
880 engine.media.flush_upload_staging_after_submit(&engine.device);
881
882 // Verify slot 0 (red) was NOT clobbered by slot 512 (blue) and slot 513 (blue) is intact!
883 let first_px = engine.readback_rgba(&dst_first).expect("readback first");
884 let last_px = engine.readback_rgba(&dst_last).expect("readback last");
885 assert!(first_px[0] > 220 && first_px[2] < 20, "slot 0 clobbered: {:?}", &first_px[..4]);
886 assert!(last_px[2] > 220 && last_px[0] < 20, "slot 513 corrupted: {:?}", &last_px[..4]);
887
888 let cursor_after_reset = engine.media.with_nv12_gpu_state(
889 || unreachable!("already initialized"),
890 |pipe| pipe.uniform_cursor,
891 );
892 assert_eq!(cursor_after_reset, 0);
893
894 // Trim chunks to 1 and verify VRAM drops cleanly; then bust_gpu_cache clears plane pool.
895 engine.media.trim_nv12_uniform_chunks(1);
896 let chunks_after_trim = engine.media.with_nv12_gpu_state(
897 || unreachable!("already initialized"),
898 |pipe| pipe.uniform_chunks.len(),
899 );
900 assert_eq!(chunks_after_trim, 1);
901
902 let vram_before_clear = engine.media.nv12_vram_bytes();
903 engine.bust_gpu_cache();
904 let (planes_after_bust, vram_after_bust) = engine.media.with_nv12_gpu_state(
905 || unreachable!("already initialized"),
906 |pipe| (pipe.plane_pool.len(), pipe.vram_bytes()),
907 );
908 assert_eq!(planes_after_bust, 0);
909 assert!(vram_after_bust < vram_before_clear);
910 }
911
912 #[cfg(target_os = "macos")]
913 #[test]
914 fn nv12_synthetic_mp4_decode_and_eval_loader() {
915 use crate::media::{AvFoundationDecoder, FfmpegDecoder, VideoDecoder};
916 use std::process::Command;
917
918 let dir = std::env::temp_dir().join(format!("fission_nv12_test_{}", std::process::id()));
919 let _ = std::fs::remove_dir_all(&dir);
920 std::fs::create_dir_all(&dir).unwrap();
921
922 let mp4_path = dir.join("bars_bt709.mp4");
923 let ok_mp4 = Command::new("ffmpeg")
924 .args([
925 "-y",
926 "-v",
927 "error",
928 "-f",
929 "lavfi",
930 "-i",
931 "smptehdbars=size=128x96:rate=24:duration=0.25",
932 "-vf",
933 "scale=out_color_matrix=bt709:out_range=tv,format=yuv420p",
934 "-c:v",
935 "libx264",
936 "-crf",
937 "10",
938 "-colorspace",
939 "bt709",
940 "-color_primaries",
941 "bt709",
942 "-color_trc",
943 "bt709",
944 "-color_range",
945 "tv",
946 ])
947 .arg(&mp4_path)
948 .status()
949 .is_ok_and(|s| s.success());
950 if !ok_mp4 {
951 let _ = std::fs::remove_dir_all(&dir);
952 return;
953 }
954
955 // 1. Verify AvFoundationDecoder selects NV12 for opaque 8-bit 4:2:0 H.264 MP4.
956 let mut av_dec = AvFoundationDecoder::open(&mp4_path).expect("AvFoundationDecoder::open");
957 assert!(av_dec.is_nv12(), "8-bit opaque H.264 yuv420p should use NV12 fast path");
958 let nv12 = av_dec.decode_nv12_frame(0).expect("decode_nv12_frame(0)");
959 assert_eq!(nv12.raw_size, [128, 96]);
960 assert_eq!(nv12.display_size, [128, 96]);
961 assert_eq!(nv12.rot_deg, 0);
962 assert_eq!(nv12.matrix, YuvMatrix::Bt709);
963 assert!(!nv12.is_full_range);
964 assert_eq!(nv12.byte_size(), (128 * 96 + 64 * 48 * 2) as u64);
965
966 // Verify EOF frame-hold returns valid last frame when requesting past EOF.
967 let eof_frame = av_dec.decode_nv12_frame(999).expect("EOF frame hold");
968 assert_eq!(eof_frame.raw_size, [128, 96]);
969 assert_eq!(eof_frame.y.len(), 128 * 96);
970
971 // 2. Verify rotated 90° H.264 MP4 decodes as NV12 with raw sensor dims + rot_deg = 90
972 // and rotated display dimensions [96, 128].
973 let rot_mp4 = dir.join("bars_rot90.mp4");
974 let ok_rot = Command::new("ffmpeg")
975 .args([
976 "-y",
977 "-v",
978 "error",
979 "-display_rotation",
980 "270", // FFmpeg display_rotation is CCW; 270 CCW == 90 CW preferredTransform
981 "-i",
982 ])
983 .arg(&mp4_path)
984 .args(["-c", "copy"])
985 .arg(&rot_mp4)
986 .status()
987 .is_ok_and(|s| s.success());
988 if ok_rot {
989 let mut rot_dec = AvFoundationDecoder::open(&rot_mp4).expect("open rot90 mp4");
990 assert!(rot_dec.is_nv12(), "rotated 8-bit H.264 should use NV12");
991 let rot_frame = rot_dec.decode_nv12_frame(0).expect("decode rot90 frame");
992 assert_eq!(rot_frame.raw_size, [128, 96]);
993 assert_eq!(rot_frame.display_size, [96, 128]);
994 assert_eq!(rot_frame.rot_deg, 90);
995 }
996
997 // 2. Verify ProRes 4444 alpha MOV stays on BGRA path (NOT NV12).
998 let alpha_mov = dir.join("alpha_4444.mov");
999 let ok_alpha = Command::new("ffmpeg")
1000 .args([
1001 "-y",
1002 "-v",
1003 "error",
1004 "-f",
1005 "lavfi",
1006 "-i",
1007 "color=c=red@0.5:size=32x32:rate=24:duration=0.1,format=yuva444p10le",
1008 "-c:v",
1009 "prores_ks",
1010 "-profile:v",
1011 "4",
1012 "-pix_fmt",
1013 "yuva444p10le",
1014 ])
1015 .arg(&alpha_mov)
1016 .status()
1017 .is_ok_and(|s| s.success());
1018 if ok_alpha {
1019 if let Some(alpha_dec) = AvFoundationDecoder::open(&alpha_mov) {
1020 assert!(
1021 !alpha_dec.is_nv12(),
1022 "ProRes 4444 alpha video must NOT use NV12 path"
1023 );
1024 }
1025 }
1026
1027 // 3. Evaluate Loader through GPU Engine (HiQ Float16) and compare vs ffmpeg reference.
1028 let esc = mp4_path.to_string_lossy().replace('\\', "\\\\");
1029 let comp_src = format!(
1030 r#"Composition {{
1031CurrentTime = 0,
1032RenderRange = {{ 0, 5 }},
1033GlobalRange = {{ 0, 5 }},
1034Tools = ordered() {{
1035 V = Loader {{
1036 Clips = {{
1037 Clip {{
1038 ID = "Clip1",
1039 Filename = "{esc}",
1040 FormatID = "QuickTimeMovies",
1041 Length = 6,
1042 GlobalStart = 0,
1043 GlobalEnd = 5,
1044 }},
1045 }},
1046 }},
1047}},
1048}}"#
1049 );
1050 let comp = Comp::from_fusion_str(&comp_src).expect("parse comp");
1051 let target = comp.find_node("V").expect("V");
1052 let mut engine = Engine::new_headless().expect("headless engine");
1053 let (tex, _) = engine.evaluate(&comp, target, 0.0);
1054 let gpu_rgba = engine.readback_rgba(&tex).expect("readback");
1055
1056 let mut ff = FfmpegDecoder::open(&mp4_path).expect("FfmpegDecoder");
1057 let ff_rgba = ff.decode_frame(0).expect("ff decode 0");
1058 assert_eq!(gpu_rgba.len(), ff_rgba.len());
1059 let mae: f64 = gpu_rgba
1060 .iter()
1061 .zip(ff_rgba.iter())
1062 .map(|(&a, &b)| (a as i32 - b as i32).abs() as f64)
1063 .sum::<f64>()
1064 / gpu_rgba.len() as f64;
1065 assert!(
1066 mae < 2.5,
1067 "GPU NV12 Loader output diverged from ffmpeg reference: MAE={mae:.2}/255"
1068 );
1069
1070 let _ = std::fs::remove_dir_all(&dir);
1071 }
1072}