1use super::*;
2
3#[derive(Clone, Copy, Debug)]
4pub struct VideoInfo {
5 pub width: u32,
6 pub height: u32,
7 pub fps: f64,
8 pub nb_frames: i64,
9}
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12#[repr(u32)]
13pub enum YuvMatrix {
14 Bt709 = 0,
15 Bt601 = 1,
16 Bt2020 = 2,
17}
18
19impl YuvMatrix {
20 pub fn from_u32(v: u32) -> Self {
21 match v {
22 1 => Self::Bt601,
23 2 => Self::Bt2020,
24 _ => Self::Bt709,
25 }
26 }
27}
28
29/// Compact 8-bit 4:2:0 bi-planar NV12 video frame (`Y` + interleaved `CbCr`) with
30/// colorimetry and rotation metadata for direct single-pass GPU conversion.
31#[derive(Clone, Debug)]
32pub struct Nv12Frame {
33 /// Unrotated raw sensor dimensions `[raw_w, raw_h]`.
34 pub raw_size: [u32; 2],
35 /// Rotated display dimensions `[out_w, out_h]`.
36 pub display_size: [u32; 2],
37 /// Clockwise rotation in degrees (`0`, `90`, `180`, or `270`).
38 pub rot_deg: u32,
39 /// YCbCr-to-RGB matrix (`BT.709`, `BT.601`, or `BT.2020`).
40 pub matrix: YuvMatrix,
41 /// `true` for full-range (`0..255`), `false` for video-range (`Y: 16..235`, `UV: 16..240`).
42 pub is_full_range: bool,
43 /// Tightly packed 8-bit luma plane (`raw_w * raw_h` bytes).
44 pub y: Vec<u8>,
45 /// Tightly packed interleaved 8-bit CbCr plane (`uv_w * uv_h * 2` bytes).
46 pub uv: Vec<u8>,
47}
48
49impl Nv12Frame {
50 pub fn uv_size(&self) -> [u32; 2] {
51 [self.raw_size[0].div_ceil(2), self.raw_size[1].div_ceil(2)]
52 }
53
54 pub fn byte_size(&self) -> u64 {
55 (self.y.len() + self.uv.len()) as u64
56 }
57
58 /// Reference CPU NV12 -> RGBA8 conversion matching `nv12_to_rgba.wgsl`
59 /// (center-aligned bilinear chroma sampling, rotation, and ITU-R matrix).
60 /// Used only by legacy CPU-only callers (`load_clip`, `VideoDecoder::decode_frame`, tests).
61 pub fn to_rgba8(&self) -> Vec<u8> {
62 let [raw_w, raw_h] = self.raw_size;
63 let [out_w, out_h] = self.display_size;
64 let [uv_w, uv_h] = self.uv_size();
65 let total_px = (out_w as usize).saturating_mul(out_h as usize);
66 let mut out = vec![0u8; total_px * 4];
67 if raw_w == 0 || raw_h == 0 || uv_w == 0 || uv_h == 0 || out_w == 0 || out_h == 0 {
68 return out;
69 }
70 if self.y.len() < (raw_w as usize) * (raw_h as usize)
71 || self.uv.len() < (uv_w as usize) * (uv_h as usize) * 2
72 {
73 return out;
74 }
75
76 let sample_uv = |u_norm: f32, v_norm: f32| -> (f32, f32) {
77 let fx = u_norm * (uv_w as f32) - 0.5;
78 let fy = v_norm * (uv_h as f32) - 0.5;
79 let x0 = (fx.floor() as i32).clamp(0, uv_w as i32 - 1) as usize;
80 let y0 = (fy.floor() as i32).clamp(0, uv_h as i32 - 1) as usize;
81 let x1 = (x0 + 1).min(uv_w as usize - 1);
82 let y1 = (y0 + 1).min(uv_h as usize - 1);
83 let tx = fx - fx.floor();
84 let ty = fy - fy.floor();
85 let wx = if fx < 0.0 {
86 0.0
87 } else if fx >= (uv_w as f32 - 1.0) {
88 0.0
89 } else {
90 tx
91 };
92 let wy = if fy < 0.0 {
93 0.0
94 } else if fy >= (uv_h as f32 - 1.0) {
95 0.0
96 } else {
97 ty
98 };
99
100 let read_pair = |x: usize, y: usize| -> (f32, f32) {
101 let idx = (y * (uv_w as usize) + x) * 2;
102 (self.uv[idx] as f32 / 255.0, self.uv[idx + 1] as f32 / 255.0)
103 };
104 let (c00, r00) = read_pair(x0, y0);
105 let (c10, r10) = read_pair(x1, y0);
106 let (c01, r01) = read_pair(x0, y1);
107 let (c11, r11) = read_pair(x1, y1);
108
109 let c0 = c00 + (c10 - c00) * wx;
110 let c1 = c01 + (c11 - c01) * wx;
111 let cb = c0 + (c1 - c0) * wy;
112
113 let r0 = r00 + (r10 - r00) * wx;
114 let r1 = r01 + (r11 - r01) * wx;
115 let cr = r0 + (r1 - r0) * wy;
116 (cb, cr)
117 };
118
119 let inv_raw_w = 1.0 / (raw_w as f32);
120 let inv_raw_h = 1.0 / (raw_h as f32);
121 let rw = raw_w as usize;
122
123 for dy in 0..out_h {
124 for dx in 0..out_w {
125 let (sx, sy) = match self.rot_deg {
126 90 => (dy, raw_h.saturating_sub(1).saturating_sub(dx)),
127 180 => (
128 raw_w.saturating_sub(1).saturating_sub(dx),
129 raw_h.saturating_sub(1).saturating_sub(dy),
130 ),
131 270 => (raw_w.saturating_sub(1).saturating_sub(dy), dx),
132 _ => (dx, dy),
133 };
134 let sx = sx.min(raw_w - 1);
135 let sy = sy.min(raw_h - 1);
136
137 let y_raw = self.y[(sy as usize) * rw + (sx as usize)] as f32 / 255.0;
138 let (cb_raw, cr_raw) =
139 sample_uv((sx as f32 + 0.5) * inv_raw_w, (sy as f32 + 0.5) * inv_raw_h);
140
141 let (y, cb, cr) = if self.is_full_range {
142 (y_raw, cb_raw - (128.0 / 255.0), cr_raw - (128.0 / 255.0))
143 } else {
144 (
145 (y_raw - (16.0 / 255.0)) * (255.0 / 219.0),
146 (cb_raw - (128.0 / 255.0)) * (255.0 / 224.0),
147 (cr_raw - (128.0 / 255.0)) * (255.0 / 224.0),
148 )
149 };
150
151 let (r, g, b) = match self.matrix {
152 YuvMatrix::Bt601 => (
153 y + 1.402_f32 * cr,
154 y - 0.344_136_29_f32 * cb - 0.714_136_29_f32 * cr,
155 y + 1.772_f32 * cb,
156 ),
157 YuvMatrix::Bt2020 => (
158 y + 1.4746_f32 * cr,
159 y - 0.164_553_13_f32 * cb - 0.571_353_13_f32 * cr,
160 y + 1.8814_f32 * cb,
161 ),
162 YuvMatrix::Bt709 => (
163 y + 1.5748_f32 * cr,
164 y - 0.187_324_27_f32 * cb - 0.468_124_27_f32 * cr,
165 y + 1.8556_f32 * cb,
166 ),
167 };
168
169 let dst = ((dy as usize) * (out_w as usize) + (dx as usize)) * 4;
170 out[dst] = (r.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
171 out[dst + 1] = (g.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
172 out[dst + 2] = (b.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
173 out[dst + 3] = 255;
174 }
175 }
176 out
177 }
178}
179
180pub enum DecodedVideoFrame {
181 Rgba(Vec<u8>),
182 Nv12(Nv12Frame),
183}
184
185pub trait VideoDecoder: Send {
186 fn info(&self) -> VideoInfo;
187 fn decode_frame(&mut self, frame_idx: i64) -> Option<Vec<u8>>;
188 fn decode_frame_native(&mut self, frame_idx: i64) -> Option<DecodedVideoFrame> {
189 self.decode_frame(frame_idx).map(DecodedVideoFrame::Rgba)
190 }
191 fn backend_name(&self) -> &'static str;
192}
193
194#[cfg(target_os = "macos")]
195mod av_ffi {
196 use std::ffi::c_char;
197
198 #[repr(C)]
199 pub struct AvVideoDecoder {
200 _private: [u8; 0],
201 }
202
203 unsafe extern "C" {
204 pub fn av_video_open(
205 path: *const c_char,
206 out_w: *mut u32,
207 out_h: *mut u32,
208 out_fps: *mut f64,
209 out_nb_frames: *mut i64,
210 ) -> *mut AvVideoDecoder;
211
212 pub fn av_video_is_nv12(
213 dec: *mut AvVideoDecoder,
214 out_raw_w: *mut u32,
215 out_raw_h: *mut u32,
216 out_rotation: *mut u32,
217 ) -> i32;
218
219 pub fn av_video_decode_frame(
220 dec: *mut AvVideoDecoder,
221 frame_idx: i64,
222 out_rgba: *mut u8,
223 out_len: usize,
224 ) -> i32;
225
226 pub fn av_video_decode_nv12_frame(
227 dec: *mut AvVideoDecoder,
228 frame_idx: i64,
229 out_y: *mut u8,
230 out_y_len: usize,
231 out_uv: *mut u8,
232 out_uv_len: usize,
233 out_matrix: *mut u32,
234 out_full_range: *mut u32,
235 ) -> i32;
236
237 pub fn av_video_close(dec: *mut AvVideoDecoder);
238 }
239}
240
241#[cfg(target_os = "macos")]
242pub struct AvFoundationDecoder {
243 ptr: *mut av_ffi::AvVideoDecoder,
244 info: VideoInfo,
245 nv12_info: Option<([u32; 2], u32)>,
246}
247
248#[cfg(target_os = "macos")]
249unsafe impl Send for AvFoundationDecoder {}
250
251#[cfg(target_os = "macos")]
252impl Drop for AvFoundationDecoder {
253 fn drop(&mut self) {
254 if !self.ptr.is_null() {
255 unsafe { av_ffi::av_video_close(self.ptr) };
256 self.ptr = std::ptr::null_mut();
257 }
258 }
259}
260
261#[cfg(target_os = "macos")]
262impl AvFoundationDecoder {
263 pub fn open(path: &Path) -> Option<Self> {
264 use std::ffi::CString;
265 let path_str = path.to_str()?;
266 let c_path = CString::new(path_str).ok()?;
267 let mut width = 0u32;
268 let mut height = 0u32;
269 let mut fps = 0.0f64;
270 let mut nb_frames = 0i64;
271 let ptr = unsafe {
272 av_ffi::av_video_open(
273 c_path.as_ptr(),
274 &mut width,
275 &mut height,
276 &mut fps,
277 &mut nb_frames,
278 )
279 };
280 if ptr.is_null() || width == 0 || height == 0 {
281 if !ptr.is_null() {
282 unsafe { av_ffi::av_video_close(ptr) };
283 }
284 return None;
285 }
286 let mut raw_w = 0u32;
287 let mut raw_h = 0u32;
288 let mut rot_deg = 0u32;
289 let is_nv12 = unsafe {
290 av_ffi::av_video_is_nv12(ptr, &mut raw_w, &mut raw_h, &mut rot_deg) != 0
291 };
292 let nv12_info = if is_nv12 && raw_w > 0 && raw_h > 0 {
293 Some(([raw_w, raw_h], rot_deg))
294 } else {
295 None
296 };
297 Some(Self {
298 ptr,
299 info: VideoInfo {
300 width,
301 height,
302 fps: if fps > 0.0 { fps } else { 30.0 },
303 nb_frames,
304 },
305 nv12_info,
306 })
307 }
308
309 pub fn is_nv12(&self) -> bool {
310 self.nv12_info.is_some()
311 }
312
313 pub fn decode_nv12_frame(&mut self, frame_idx: i64) -> Option<Nv12Frame> {
314 let ([raw_w, raw_h], rot_deg) = self.nv12_info?;
315 let y_len = (raw_w as usize).checked_mul(raw_h as usize)?;
316 let uv_w = raw_w.div_ceil(2) as usize;
317 let uv_h = raw_h.div_ceil(2) as usize;
318 let uv_len = uv_w.checked_mul(uv_h)?.checked_mul(2)?;
319 let mut y = vec![0u8; y_len];
320 let mut uv = vec![0u8; uv_len];
321 let mut matrix = 0u32;
322 let mut full_range = 0u32;
323 let ok = unsafe {
324 av_ffi::av_video_decode_nv12_frame(
325 self.ptr,
326 frame_idx.max(0),
327 y.as_mut_ptr(),
328 y_len,
329 uv.as_mut_ptr(),
330 uv_len,
331 &mut matrix,
332 &mut full_range,
333 )
334 };
335 if ok != 0 {
336 Some(Nv12Frame {
337 raw_size: [raw_w, raw_h],
338 display_size: [self.info.width, self.info.height],
339 rot_deg,
340 matrix: YuvMatrix::from_u32(matrix),
341 is_full_range: full_range != 0,
342 y,
343 uv,
344 })
345 } else {
346 None
347 }
348 }
349}
350
351#[cfg(target_os = "macos")]
352impl VideoDecoder for AvFoundationDecoder {
353 fn info(&self) -> VideoInfo {
354 self.info
355 }
356
357 fn decode_frame(&mut self, frame_idx: i64) -> Option<Vec<u8>> {
358 if self.nv12_info.is_some() {
359 return self.decode_nv12_frame(frame_idx).map(|f| f.to_rgba8());
360 }
361 let len = (self.info.width as usize)
362 .checked_mul(self.info.height as usize)?
363 .checked_mul(4)?;
364 let mut buf = vec![0u8; len];
365 let ok = unsafe {
366 av_ffi::av_video_decode_frame(self.ptr, frame_idx.max(0), buf.as_mut_ptr(), len)
367 };
368 if ok != 0 {
369 Some(buf)
370 } else {
371 None
372 }
373 }
374
375 fn decode_frame_native(&mut self, frame_idx: i64) -> Option<DecodedVideoFrame> {
376 if self.nv12_info.is_some() {
377 self.decode_nv12_frame(frame_idx).map(DecodedVideoFrame::Nv12)
378 } else {
379 self.decode_frame(frame_idx).map(DecodedVideoFrame::Rgba)
380 }
381 }
382
383 fn backend_name(&self) -> &'static str {
384 "AVFoundation/VideoToolbox"
385 }
386}
387
388pub struct FfmpegDecoder {
389 path: PathBuf,
390 info: VideoInfo,
391}
392
393impl FfmpegDecoder {
394 pub fn open(path: &Path) -> Option<Self> {
395 let info = probe_video(path)?;
396 Some(Self {
397 path: path.to_path_buf(),
398 info,
399 })
400 }
401}
402
403impl VideoDecoder for FfmpegDecoder {
404 fn info(&self) -> VideoInfo {
405 self.info
406 }
407
408 fn decode_frame(&mut self, frame_idx: i64) -> Option<Vec<u8>> {
409 decode_video_frame(&self.path, self.info, frame_idx)
410 }
411
412 fn backend_name(&self) -> &'static str {
413 "ffmpeg"
414 }
415}
416
417/// Opens a hardware-accelerated video decoder (`AVFoundation`/`VideoToolbox` on macOS),
418/// falling back to `ffmpeg` for unsupported containers or codecs.
419pub fn open_video_decoder(path: &Path) -> Option<Box<dyn VideoDecoder>> {
420 #[cfg(target_os = "macos")]
421 {
422 if let Some(av) = AvFoundationDecoder::open(path) {
423 return Some(Box::new(av));
424 }
425 }
426 FfmpegDecoder::open(path).map(|ff| Box::new(ff) as Box<dyn VideoDecoder>)
427}
428
429pub(super) fn is_video_path(path: &Path) -> bool {
430 let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
431 return false;
432 };
433 matches!(
434 ext.to_ascii_lowercase().as_str(),
435 "mov" | "mp4" | "m4v" | "mkv" | "avi" | "webm" | "mxf"
436 )
437}
438
439pub(super) fn probe_video(path: &Path) -> Option<VideoInfo> {
440 let out = Command::new("ffprobe")
441 .args([
442 "-v",
443 "error",
444 "-select_streams",
445 "v:0",
446 "-show_entries",
447 "stream=width,height,r_frame_rate,nb_frames",
448 "-of",
449 "default=noprint_wrappers=1",
450 ])
451 .arg(path)
452 .output()
453 .ok()?;
454 if !out.status.success() {
455 return None;
456 }
457 let text = String::from_utf8_lossy(&out.stdout);
458 let mut width = 0u32;
459 let mut height = 0u32;
460 let mut fps = 30.0_f64;
461 let mut nb_frames = 0i64;
462 for line in text.lines() {
463 if let Some((k, v)) = line.split_once('=') {
464 match k.trim() {
465 "width" => width = v.trim().parse().unwrap_or(0),
466 "height" => height = v.trim().parse().unwrap_or(0),
467 "nb_frames" => nb_frames = v.trim().parse().unwrap_or(0),
468 "r_frame_rate" => {
469 if let Some((n, d)) = v.trim().split_once('/') {
470 let num: f64 = n.parse().unwrap_or(30.0);
471 let den: f64 = d.parse().unwrap_or(1.0);
472 if den > 0.0 && num > 0.0 {
473 fps = num / den;
474 }
475 } else if let Ok(r) = v.trim().parse::<f64>() {
476 if r > 0.0 {
477 fps = r;
478 }
479 }
480 }
481 _ => {}
482 }
483 }
484 }
485 if width == 0 || height == 0 {
486 return None;
487 }
488 Some(VideoInfo { width, height, fps, nb_frames })
489}
490
491pub(super) fn decode_video_frame(path: &Path, info: VideoInfo, frame_idx: i64) -> Option<Vec<u8>> {
492 let idx = frame_idx.max(0);
493 let ts = if idx == 0 {
494 0.0
495 } else {
496 ((idx as f64) - 0.005) / info.fps.max(1.0)
497 };
498 let out = Command::new("ffmpeg")
499 .args([
500 "-v",
501 "error",
502 "-ss",
503 &format!("{ts:.6}"),
504 "-i",
505 ])
506 .arg(path)
507 .args([
508 "-frames:v",
509 "1",
510 "-f",
511 "rawvideo",
512 "-pix_fmt",
513 "rgba",
514 "-",
515 ])
516 .output()
517 .ok()?;
518 if !out.status.success() {
519 return None;
520 }
521 let expected = (info.width as usize) * (info.height as usize) * 4;
522 if out.stdout.len() < expected {
523 return None;
524 }
525 let mut buf = out.stdout;
526 buf.truncate(expected);
527 Some(buf)
528}