edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 1 | //! Uncompressed video in AVI: `BI_RGB` 24/32-bit (bottom-up or, with a negative height, |
| 2 | //! top-down; rows padded to 4 bytes) and the common YUV FourCCs YUY2/YUYV, UYVY, I420/IYUV and |
| 3 | //! YV12. The demuxer keeps the `BITMAPINFOHEADER` as the stream's extradata; [`RawVideoDecoder`] |
| 4 | //! reads the layout from it and turns each packet into an upright [`VideoFrame`]: |
| 5 | //! RGB comes out as `Bgr8` / `Bgra8`, packed 4:2:2 as `I422` and YV12 as `I420` (lossless |
| 6 | //! repacking, byte-equal to ffmpeg's `-pix_fmt` conversion of the same data). |
| 7 | |
| 8 | #![allow(clippy::chunks_exact_to_as_chunks)] |
| 9 | |
| 10 | use std::collections::VecDeque; |
| 11 | |
| 12 | use ec_core::error::{Error, Result}; |
| 13 | use ec_core::frame::{Frame, PixelFormat, Plane, VideoFrame}; |
| 14 | use ec_core::packet::Packet; |
| 15 | use ec_core::registry::{CodecId, CodecParameters, Decoder}; |
| 16 | use ec_core::timebase::Timestamp; |
| 17 | |
| 18 | /// How a raw frame is stored. |
| 19 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 20 | pub(crate) enum Layout { |
| 21 | /// 24- or 32-bit BGR(A) DIB rows, padded to 4 bytes. |
| 22 | Dib { |
| 23 | bytes_per_pixel: usize, |
| 24 | top_down: bool, |
| 25 | }, |
| 26 | Yuy2, |
| 27 | Uyvy, |
| 28 | Yvyu, |
| 29 | I420, |
| 30 | Yv12, |
| 31 | Nv12, |
| 32 | /// 8-bit luma only (`Y800`, `Y8`, `GREY`), rows tight. |
| 33 | Gray8, |
| 34 | /// 8-bit palettised DIB (palette follows the header), expanded to `Bgr8`. |
| 35 | Pal8 { |
| 36 | top_down: bool, |
| 37 | }, |
| 38 | /// 15/16-bit BI_RGB (little-endian RGB555), rows padded to 4 bytes, expanded to `Bgr8`. |
| 39 | Rgb555 { |
| 40 | top_down: bool, |
| 41 | }, |
| 42 | /// v210: 10-bit 4:2:2, 6 pixels per 16 bytes, rows padded to 48 pixels. |
| 43 | V210, |
| 44 | // The QuickTime layouts below come from the `mov` marker (see `layout_of_mov`). |
| 45 | /// `raw ` 24-bit: packed RGB, rows tight. |
| 46 | MovRgb24, |
| 47 | /// `raw ` 32-bit: packed ARGB, rows tight; comes out as `Bgra8`. |
| 48 | MovArgb, |
| 49 | /// `raw ` 16-bit: big-endian RGB555, rows tight; comes out as `Bgr8`. |
| 50 | MovRgb555Be, |
| 51 | /// `yuv2`: YUYV with the chroma bytes offset by 128. |
| 52 | MovYuv2, |
| 53 | /// `v410`: packed 10-bit 4:4:4 (32-bit LE words U, Y, V), comes out as `I410`. |
| 54 | MovV410, |
| 55 | /// `b16g`: 16-bit big-endian gray, comes out as `Gray16` (little-endian). |
| 56 | MovGray16Be, |
| 57 | } |
| 58 | |
| 59 | impl Layout { |
| 60 | pub(crate) fn format(self) -> PixelFormat { |
| 61 | match self { |
| 62 | Layout::Dib { |
| 63 | bytes_per_pixel: 3, .. |
| 64 | } => PixelFormat::Bgr8, |
| 65 | Layout::Dib { .. } => PixelFormat::Bgra8, |
| 66 | Layout::Yuy2 | Layout::Uyvy | Layout::Yvyu | Layout::MovYuv2 => PixelFormat::I422, |
| 67 | Layout::I420 | Layout::Yv12 => PixelFormat::I420, |
| 68 | Layout::Nv12 => PixelFormat::Nv12, |
| 69 | Layout::Gray8 => PixelFormat::Gray8, |
| 70 | Layout::Pal8 { .. } | Layout::Rgb555 { .. } | Layout::MovRgb555Be => PixelFormat::Bgr8, |
| 71 | Layout::V210 => PixelFormat::I210, |
| 72 | Layout::MovRgb24 => PixelFormat::Rgb8, |
| 73 | Layout::MovArgb => PixelFormat::Bgra8, |
| 74 | Layout::MovV410 => PixelFormat::I410, |
| 75 | Layout::MovGray16Be => PixelFormat::Gray16, |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | /// The marker a QuickTime sample entry's synthesized 40-byte header carries in place of |
| 81 | /// `biSize` ("mov "): width at 4, height at 8, depth at 14, the sample entry FourCC at 16. |
| 82 | pub const MOV_MARKER: [u8; 4] = *b"mov "; |
| 83 | |
| 84 | /// The layout a QuickTime raw sample entry (`raw `, `2vuy`, `yuvs`, `yuv2`, `v210`, `v410`, `b16g`) with |
| 85 | /// `depth` bits states. |
| 86 | pub fn layout_of_mov(kind: &[u8; 4], depth: u16) -> Option<Layout> { |
| 87 | match kind { |
| 88 | b"raw " => match depth { |
| 89 | 24 => Some(Layout::MovRgb24), |
| 90 | 32 => Some(Layout::MovArgb), |
| 91 | 16 => Some(Layout::MovRgb555Be), |
| 92 | _ => None, |
| 93 | }, |
| 94 | b"2vuy" => Some(Layout::Uyvy), |
| 95 | b"yuvs" => Some(Layout::Yuy2), |
| 96 | b"yuv2" => Some(Layout::MovYuv2), |
| 97 | b"v210" => Some(Layout::V210), |
| 98 | b"v410" => Some(Layout::MovV410), |
| 99 | b"b16g" => Some(Layout::MovGray16Be), |
| 100 | _ => None, |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | /// The layout a `BITMAPINFOHEADER` (40+ bytes) with FourCC `comp` and `bits` per pixel states. |
| 105 | pub(crate) fn layout_of(comp: &[u8; 4], bits: u16, signed_height: i32) -> Option<Layout> { |
| 106 | let up: Vec<u8> = comp.iter().map(|b| b.to_ascii_uppercase()).collect(); |
| 107 | match &up[..] { |
| 108 | b"YUY2" | b"YUYV" | b"YUV2" | b"V422" => Some(Layout::Yuy2), |
| 109 | b"UYVY" | b"2VUY" => Some(Layout::Uyvy), |
| 110 | b"I420" | b"IYUV" => Some(Layout::I420), |
| 111 | b"YV12" => Some(Layout::Yv12), |
| 112 | b"YVYU" => Some(Layout::Yvyu), |
| 113 | b"NV12" => Some(Layout::Nv12), |
| 114 | b"Y800" | b"Y8 " | b"GREY" => Some(Layout::Gray8), |
| 115 | b"V210" => Some(Layout::V210), |
| 116 | _ if comp == &[0; 4] || up == b"RAW " || up == b"RGB " || up == b"BGR " => match bits { |
| 117 | 8 => Some(Layout::Pal8 { |
| 118 | top_down: signed_height < 0, |
| 119 | }), |
| 120 | 15 | 16 => Some(Layout::Rgb555 { |
| 121 | top_down: signed_height < 0, |
| 122 | }), |
| 123 | 24 => Some(Layout::Dib { |
| 124 | bytes_per_pixel: 3, |
| 125 | top_down: signed_height < 0, |
| 126 | }), |
| 127 | 32 => Some(Layout::Dib { |
| 128 | bytes_per_pixel: 4, |
| 129 | top_down: signed_height < 0, |
| 130 | }), |
| 131 | _ => None, |
| 132 | }, |
| 133 | _ => None, |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /// Append an RGB555 pixel as B, G, R bytes, widening each 5-bit field by bit replication. |
| 138 | fn push_rgb555(v: &mut Vec<u8>, px: u16) { |
| 139 | let ex = |x: u16| ((x << 3) | (x >> 2)) as u8; |
| 140 | v.extend_from_slice(&[ex(px & 31), ex((px >> 5) & 31), ex((px >> 10) & 31)]); |
| 141 | } |
| 142 | |
| 143 | /// Raw video decoder (`CodecId::RawVideo`): one packet is one frame. |
| 144 | pub struct RawVideoDecoder { |
| 145 | params: CodecParameters, |
| 146 | layout: Layout, |
| 147 | /// BGR palette entries for [`Layout::Pal8`]. |
| 148 | palette: Vec<[u8; 3]>, |
| 149 | width: usize, |
| 150 | height: usize, |
| 151 | out: VecDeque<VideoFrame>, |
| 152 | eof: bool, |
| 153 | } |
| 154 | |
| 155 | impl RawVideoDecoder { |
| 156 | /// A decoder for `params`, whose extradata is the stream's `BITMAPINFOHEADER` as the AVI |
| 157 | /// demuxer leaves it. |
| 158 | pub fn new(params: CodecParameters) -> Result<RawVideoDecoder> { |
| 159 | if params.codec != CodecId::RawVideo { |
| 160 | return Err(Error::unsupported( |
| 161 | format!("codec {:?}", params.codec), |
| 162 | "this decoder implements raw video only", |
| 163 | )); |
| 164 | } |
| 165 | let bih = params |
| 166 | .extradata |
| 167 | .as_ref() |
| 168 | .map(|b| b.to_vec()) |
| 169 | .filter(|b| b.len() >= 40) |
| 170 | .ok_or_else(|| Error::corrupt("raw video: missing BITMAPINFOHEADER"))?; |
| 171 | let le = |at: usize| u32::from_le_bytes([bih[at], bih[at + 1], bih[at + 2], bih[at + 3]]); |
| 172 | let width = le(4) as i32; |
| 173 | let signed_height = le(8) as i32; |
| 174 | let bits = u16::from_le_bytes([bih[14], bih[15]]); |
| 175 | let comp = [bih[16], bih[17], bih[18], bih[19]]; |
| 176 | let layout = if bih[..4] == MOV_MARKER { |
| 177 | layout_of_mov(&comp, bits) |
| 178 | } else { |
| 179 | layout_of(&comp, bits, signed_height) |
| 180 | } |
| 181 | .ok_or_else(|| Error::unsupported("raw video layout", "not a carried raw layout"))?; |
| 182 | if width <= 0 |
| 183 | || signed_height == 0 |
| 184 | || width > 1 << 16 |
| 185 | || signed_height.unsigned_abs() > 1 << 16 |
| 186 | { |
| 187 | return Err(Error::corrupt("raw video: bad dimensions")); |
| 188 | } |
| 189 | Ok(RawVideoDecoder { |
| 190 | params, |
| 191 | layout, |
| 192 | palette: bih[40..] |
| 193 | .chunks_exact(4) |
| 194 | .map(|c| [c[0], c[1], c[2]]) |
| 195 | .collect(), |
| 196 | width: width as usize, |
| 197 | height: signed_height.unsigned_abs() as usize, |
| 198 | out: VecDeque::new(), |
| 199 | eof: false, |
| 200 | }) |
| 201 | } |
| 202 | |
| 203 | /// Decode one frame's bytes. |
| 204 | pub fn decode(&self, data: &[u8]) -> Result<VideoFrame> { |
| 205 | let (w, h) = (self.width, self.height); |
| 206 | let short = || Error::corrupt("raw video: packet shorter than a frame"); |
| 207 | let cw = w.div_ceil(2); |
| 208 | let planes = match self.layout { |
| 209 | Layout::Dib { |
| 210 | bytes_per_pixel: bpp, |
| 211 | top_down, |
| 212 | } => { |
| 213 | let row = w * bpp; |
| 214 | let stride = (row + 3) & !3; |
| 215 | if data.len() < stride * (h - 1) + row { |
| 216 | return Err(short()); |
| 217 | } |
| 218 | let mut v = Vec::with_capacity(row * h); |
| 219 | for y in 0..h { |
| 220 | let src = if top_down { y } else { h - 1 - y }; |
| 221 | v.extend_from_slice(&data[src * stride..src * stride + row]); |
| 222 | } |
| 223 | vec![Plane::new(v, row)] |
| 224 | } |
| 225 | Layout::Yuy2 | Layout::Uyvy | Layout::Yvyu | Layout::MovYuv2 => { |
| 226 | let stride = cw * 4; |
| 227 | if data.len() < stride * h { |
| 228 | return Err(short()); |
| 229 | } |
| 230 | let (yo, uo, vo) = match self.layout { |
| 231 | Layout::Uyvy => (1, 0, 2), |
| 232 | Layout::Yvyu => (0, 3, 1), |
| 233 | _ => (0, 1, 3), |
| 234 | }; |
| 235 | let bias = if self.layout == Layout::MovYuv2 { |
| 236 | 0x80 |
| 237 | } else { |
| 238 | 0 |
| 239 | }; |
| 240 | let mut y = vec![0u8; w * h]; |
| 241 | let mut u = vec![0u8; cw * h]; |
| 242 | let mut v = vec![0u8; cw * h]; |
| 243 | for r in 0..h { |
| 244 | let row = &data[r * stride..(r + 1) * stride]; |
| 245 | for c in 0..cw { |
| 246 | let q = &row[c * 4..c * 4 + 4]; |
| 247 | y[r * w + 2 * c] = q[yo]; |
| 248 | if 2 * c + 1 < w { |
| 249 | y[r * w + 2 * c + 1] = q[yo + 2]; |
| 250 | } |
| 251 | u[r * cw + c] = q[uo] ^ bias; |
| 252 | v[r * cw + c] = q[vo] ^ bias; |
| 253 | } |
| 254 | } |
| 255 | vec![Plane::new(y, w), Plane::new(u, cw), Plane::new(v, cw)] |
| 256 | } |
| 257 | Layout::I420 | Layout::Yv12 => { |
| 258 | let ch = h.div_ceil(2); |
| 259 | let (ys, cs) = (w * h, cw * ch); |
| 260 | if data.len() < ys + 2 * cs { |
| 261 | return Err(short()); |
| 262 | } |
| 263 | let a = data[ys..ys + cs].to_vec(); |
| 264 | let b = data[ys + cs..ys + 2 * cs].to_vec(); |
| 265 | let (u, v) = if self.layout == Layout::I420 { |
| 266 | (a, b) |
| 267 | } else { |
| 268 | (b, a) |
| 269 | }; |
| 270 | vec![ |
| 271 | Plane::new(data[..ys].to_vec(), w), |
| 272 | Plane::new(u, cw), |
| 273 | Plane::new(v, cw), |
| 274 | ] |
| 275 | } |
| 276 | Layout::Nv12 => { |
| 277 | let ch = h.div_ceil(2); |
| 278 | if data.len() < w * h + 2 * cw * ch { |
| 279 | return Err(short()); |
| 280 | } |
| 281 | vec![ |
| 282 | Plane::new(data[..w * h].to_vec(), w), |
| 283 | Plane::new(data[w * h..w * h + 2 * cw * ch].to_vec(), 2 * cw), |
| 284 | ] |
| 285 | } |
| 286 | Layout::Gray8 | Layout::Pal8 { .. } | Layout::Rgb555 { .. } => { |
| 287 | let (bpp, top_down) = match self.layout { |
| 288 | Layout::Pal8 { top_down } => (1, top_down), |
| 289 | Layout::Rgb555 { top_down } => (2, top_down), |
| 290 | _ => (1, true), |
| 291 | }; |
| 292 | let row = w * bpp; |
| 293 | let stride = if self.layout == Layout::Gray8 { |
| 294 | row |
| 295 | } else { |
| 296 | (row + 3) & !3 |
| 297 | }; |
| 298 | if data.len() < stride * (h - 1) + row { |
| 299 | return Err(short()); |
| 300 | } |
| 301 | let mut v = Vec::with_capacity( |
| 302 | row * h |
| 303 | * if bpp == 1 && self.layout != Layout::Gray8 { |
| 304 | 3 |
| 305 | } else { |
| 306 | 1 |
| 307 | }, |
| 308 | ); |
| 309 | for y in 0..h { |
| 310 | let src = if top_down { y } else { h - 1 - y }; |
| 311 | let line = &data[src * stride..src * stride + row]; |
| 312 | match self.layout { |
| 313 | Layout::Gray8 => v.extend_from_slice(line), |
| 314 | Layout::Pal8 { .. } => { |
| 315 | for &i in line { |
| 316 | v.extend_from_slice( |
| 317 | self.palette.get(usize::from(i)).unwrap_or(&[0; 3]), |
| 318 | ); |
| 319 | } |
| 320 | } |
| 321 | _ => { |
| 322 | for px in line.chunks_exact(2) { |
| 323 | push_rgb555(&mut v, u16::from_le_bytes([px[0], px[1]])); |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | let stride_out = if self.layout == Layout::Gray8 { w } else { w * 3 }; |
| 329 | vec![Plane::new(v, stride_out)] |
| 330 | } |
| 331 | Layout::V210 => { |
| 332 | let stride = w.div_ceil(48) * 128; |
| 333 | if data.len() < stride * h { |
| 334 | return Err(short()); |
| 335 | } |
| 336 | let mut y = vec![0u8; w * h * 2]; |
| 337 | let mut u = vec![0u8; cw * h * 2]; |
| 338 | let mut v = vec![0u8; cw * h * 2]; |
| 339 | for r in 0..h { |
| 340 | let row = &data[r * stride..(r + 1) * stride]; |
| 341 | let put = |p: &mut [u8], at: usize, lim: usize, val: u32| { |
| 342 | if at < lim { |
| 343 | p[(r * lim + at) * 2..(r * lim + at) * 2 + 2] |
| 344 | .copy_from_slice(&(val as u16).to_le_bytes()); |
| 345 | } |
| 346 | }; |
| 347 | for (g, blk) in row.chunks_exact(16).enumerate() { |
| 348 | let wd = |i: usize| { |
| 349 | u32::from_le_bytes([ |
| 350 | blk[4 * i], |
| 351 | blk[4 * i + 1], |
| 352 | blk[4 * i + 2], |
| 353 | blk[4 * i + 3], |
| 354 | ]) |
| 355 | }; |
| 356 | let f = |x: u32, k: u32| (x >> (10 * k)) & 0x3ff; |
| 357 | let (w0, w1, w2, w3) = (wd(0), wd(1), wd(2), wd(3)); |
| 358 | let ys = [f(w0, 1), f(w1, 0), f(w1, 2), f(w2, 1), f(w3, 0), f(w3, 2)]; |
| 359 | let us = [f(w0, 0), f(w1, 1), f(w2, 2)]; |
| 360 | let vs = [f(w0, 2), f(w2, 0), f(w3, 1)]; |
| 361 | for (i, val) in ys.iter().enumerate() { |
| 362 | put(&mut y, g * 6 + i, w, *val); |
| 363 | } |
| 364 | for i in 0..3 { |
| 365 | put(&mut u, g * 3 + i, cw, us[i]); |
| 366 | put(&mut v, g * 3 + i, cw, vs[i]); |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 | vec![ |
| 371 | Plane::new(y, w * 2), |
| 372 | Plane::new(u, cw * 2), |
| 373 | Plane::new(v, cw * 2), |
| 374 | ] |
| 375 | } |
| 376 | Layout::MovRgb24 => { |
| 377 | if data.len() < w * h * 3 { |
| 378 | return Err(short()); |
| 379 | } |
| 380 | vec![Plane::new(data[..w * h * 3].to_vec(), w * 3)] |
| 381 | } |
| 382 | Layout::MovArgb => { |
| 383 | if data.len() < w * h * 4 { |
| 384 | return Err(short()); |
| 385 | } |
| 386 | let mut v = Vec::with_capacity(w * h * 4); |
| 387 | for px in data[..w * h * 4].chunks_exact(4) { |
| 388 | v.extend_from_slice(&[px[3], px[2], px[1], px[0]]); |
| 389 | } |
| 390 | vec![Plane::new(v, w * 4)] |
| 391 | } |
| 392 | Layout::MovRgb555Be => { |
| 393 | if data.len() < w * h * 2 { |
| 394 | return Err(short()); |
| 395 | } |
| 396 | let mut v = Vec::with_capacity(w * h * 3); |
| 397 | for px in data[..w * h * 2].chunks_exact(2) { |
| 398 | push_rgb555(&mut v, u16::from_be_bytes([px[0], px[1]])); |
| 399 | } |
| 400 | vec![Plane::new(v, w * 3)] |
| 401 | } |
| 402 | Layout::MovV410 => { |
| 403 | if data.len() < w * h * 4 { |
| 404 | return Err(short()); |
| 405 | } |
| 406 | let n = w * h; |
| 407 | let (mut y, mut u, mut v) = ( |
| 408 | Vec::with_capacity(n * 2), |
| 409 | Vec::with_capacity(n * 2), |
| 410 | Vec::with_capacity(n * 2), |
| 411 | ); |
| 412 | for px in data[..n * 4].chunks_exact(4) { |
| 413 | let val = u32::from_le_bytes([px[0], px[1], px[2], px[3]]); |
| 414 | u.extend_from_slice(&(((val >> 2) & 0x3ff) as u16).to_le_bytes()); |
| 415 | y.extend_from_slice(&(((val >> 12) & 0x3ff) as u16).to_le_bytes()); |
| 416 | v.extend_from_slice(&(((val >> 22) & 0x3ff) as u16).to_le_bytes()); |
| 417 | } |
| 418 | vec![ |
| 419 | Plane::new(y, w * 2), |
| 420 | Plane::new(u, w * 2), |
| 421 | Plane::new(v, w * 2), |
| 422 | ] |
| 423 | } |
| 424 | Layout::MovGray16Be => { |
| 425 | if data.len() < w * h * 2 { |
| 426 | return Err(short()); |
| 427 | } |
| 428 | let v: Vec<u8> = data[..w * h * 2] |
| 429 | .chunks_exact(2) |
| 430 | .flat_map(|p| [p[1], p[0]]) |
| 431 | .collect(); |
| 432 | vec![Plane::new(v, w * 2)] |
| 433 | } |
| 434 | }; |
| 435 | VideoFrame::try_new(self.layout.format(), w as u32, h as u32, planes) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | impl Decoder for RawVideoDecoder { |
| 440 | fn codec_parameters(&self) -> &CodecParameters { |
| 441 | &self.params |
| 442 | } |
| 443 | |
| 444 | fn send_packet(&mut self, packet: &Packet) -> Result<()> { |
| 445 | self.eof = false; |
| 446 | let mut f = self.decode(&packet.data)?; |
| 447 | f.pts = packet.pts.map(|t| Timestamp::new(t, packet.time_base)); |
| 448 | self.out.push_back(f); |
| 449 | Ok(()) |
| 450 | } |
| 451 | |
| 452 | fn receive_frame(&mut self) -> Result<Frame> { |
| 453 | match self.out.pop_front() { |
| 454 | Some(f) => Ok(Frame::Video(f)), |
| 455 | None if self.eof => Err(Error::Eof), |
| 456 | None => Err(Error::NeedMore), |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | fn flush(&mut self) -> Result<()> { |
| 461 | self.eof = true; |
| 462 | Ok(()) |
| 463 | } |
| 464 | |
| 465 | fn reset(&mut self) { |
| 466 | self.out.clear(); |
| 467 | self.eof = false; |
| 468 | } |
| 469 | } |