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 | //! Picture assembly: slice tables, row groups, optional slice-parallel decode, weaving. |
| 2 | |
| 3 | use ec_core::error::{Error, Result}; |
| 4 | use ec_core::frame::{ColorInfo, Interlace, PixelFormat, Plane, VideoFrame}; |
| 5 | |
| 6 | use crate::header::{self, FrameInfo}; |
| 7 | use crate::slice::{RowBuf, Scratch, SliceCtx, SliceIn, decode_slices}; |
| 8 | use crate::tables::{INTERLACED_SCAN, PROGRESSIVE_SCAN}; |
| 9 | |
| 10 | /// Decoded alpha: 16-bit samples, `width` by `height`, full scale 0xFFFF (8-bit coded alpha is |
| 11 | /// replicated into both bytes). `data` holds `stride` samples per row. |
| 12 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 13 | pub struct AlphaPlane { |
| 14 | /// Samples per row visible. |
| 15 | pub width: u32, |
| 16 | /// Rows. |
| 17 | pub height: u32, |
| 18 | /// Samples between row starts. |
| 19 | pub stride: usize, |
| 20 | /// Little-endian-neutral native `u16` samples. |
| 21 | pub data: Vec<u16>, |
| 22 | } |
| 23 | |
| 24 | /// A decoded frame, its header facts and its alpha plane when the stream has one. |
| 25 | #[derive(Debug, Clone)] |
| 26 | pub struct DecodedFrame { |
| 27 | /// The picture: [`PixelFormat::I210`] (4:2:2) or [`PixelFormat::I412`] (4:4:4). |
| 28 | pub video: VideoFrame, |
| 29 | /// Alpha, when the frame header declares an alpha channel. |
| 30 | pub alpha: Option<AlphaPlane>, |
| 31 | /// Frame header facts. |
| 32 | pub info: FrameInfo, |
| 33 | } |
| 34 | |
| 35 | struct SliceDesc { |
| 36 | mb_x: usize, |
| 37 | mb_y: usize, |
| 38 | mb_count: usize, |
| 39 | start: usize, |
| 40 | end: usize, |
| 41 | } |
| 42 | |
| 43 | struct Pic { |
| 44 | slices: Vec<SliceDesc>, |
| 45 | mb_rows: usize, |
| 46 | } |
| 47 | |
| 48 | fn build_slices(frame: &[u8], p: &header::Picture, mb_width: usize, mb_rows: usize) -> Result<Pic> { |
| 49 | let mut slices = Vec::with_capacity(p.slice_count); |
| 50 | let mut off = p.data_at; |
| 51 | let mut n = 0usize; |
| 52 | for mb_y in 0..mb_rows { |
| 53 | let mut cnt = 1usize << p.log2_slice_mbs; |
| 54 | let mut mb_x = 0; |
| 55 | while mb_x < mb_width { |
| 56 | while mb_width - mb_x < cnt { |
| 57 | cnt >>= 1; |
| 58 | } |
| 59 | if n >= p.slice_count { |
| 60 | return Err(Error::corrupt("ProRes picture: fewer slices than the macroblock grid needs")); |
| 61 | } |
| 62 | let sz = usize::from(header::be16(frame, p.table_at + n * 2).unwrap_or(0)); |
| 63 | let end = off.checked_add(sz).filter(|&e| e <= p.end).ok_or_else(|| { |
| 64 | Error::corrupt("ProRes picture: slice sizes run past the picture") |
| 65 | })?; |
| 66 | slices.push(SliceDesc { mb_x, mb_y, mb_count: cnt, start: off, end }); |
| 67 | off = end; |
| 68 | mb_x += cnt; |
| 69 | n += 1; |
| 70 | } |
| 71 | } |
| 72 | if n != p.slice_count { |
| 73 | return Err(Error::corrupt(format!( |
| 74 | "ProRes picture: {} slices declared, macroblock grid needs {n}", |
| 75 | p.slice_count |
| 76 | ))); |
| 77 | } |
| 78 | Ok(Pic { slices, mb_rows }) |
| 79 | } |
| 80 | |
| 81 | fn decode_group( |
| 82 | cx: &SliceCtx, |
| 83 | frame: &[u8], |
| 84 | pic: &Pic, |
| 85 | r0: usize, |
| 86 | r1: usize, |
| 87 | mb_width: usize, |
| 88 | ) -> Result<RowBuf> { |
| 89 | let rows = (r1 - r0) * 16; |
| 90 | let ys = mb_width * 16; |
| 91 | let cs = if cx.is_444 { ys } else { mb_width * 8 }; |
| 92 | let mut rb = RowBuf { |
| 93 | y: vec![0; rows * ys * 2], |
| 94 | u: vec![0; rows * cs * 2], |
| 95 | v: vec![0; rows * cs * 2], |
| 96 | a: if cx.alpha_bits != 0 { vec![0; rows * ys] } else { Vec::new() }, |
| 97 | ys, |
| 98 | cs, |
| 99 | }; |
| 100 | let mut sc = Scratch::new(); |
| 101 | // Slices are stored row-major. |
| 102 | let first = pic.slices.partition_point(|s| s.mb_y < r0); |
| 103 | let list: Vec<SliceIn> = pic.slices[first..] |
| 104 | .iter() |
| 105 | .take_while(|s| s.mb_y < r1) |
| 106 | .map(|s| SliceIn { data: &frame[s.start..s.end], mb_count: s.mb_count, mb_x: s.mb_x, row: s.mb_y - r0 }) |
| 107 | .collect(); |
| 108 | for pair in list.chunks(2) { |
| 109 | decode_slices(cx, pair, &mut rb, &mut sc)?; |
| 110 | } |
| 111 | Ok(rb) |
| 112 | } |
| 113 | |
| 114 | /// Decode one picture (a frame, or one field) into row groups. |
| 115 | fn decode_picture(cx: &SliceCtx, frame: &[u8], pic: &Pic, mb_width: usize, threads: usize) -> Result<Vec<(usize, RowBuf)>> { |
| 116 | let rows = pic.mb_rows; |
| 117 | let nthreads = threads.clamp(1, 6).min(rows); |
| 118 | if nthreads <= 1 || pic.slices.len() < 8 { |
| 119 | return Ok(vec![(0, decode_group(cx, frame, pic, 0, rows, mb_width)?)]); |
| 120 | } |
| 121 | // Contiguous bands of rows, one per thread. |
| 122 | let mut bands = Vec::new(); |
| 123 | for t in 0..nthreads { |
| 124 | let (a, b) = (rows * t / nthreads, rows * (t + 1) / nthreads); |
| 125 | if a < b { |
| 126 | bands.push((a, b)); |
| 127 | } |
| 128 | } |
| 129 | let results: Vec<Result<RowBuf>> = std::thread::scope(|s| { |
| 130 | let hs: Vec<_> = bands |
| 131 | .iter() |
| 132 | .map(|&(a, b)| s.spawn(move || decode_group(cx, frame, pic, a, b, mb_width))) |
| 133 | .collect(); |
| 134 | hs.into_iter() |
| 135 | .map(|h| h.join().unwrap_or_else(|_| Err(Error::corrupt("ProRes: slice worker panicked")))) |
| 136 | .collect() |
| 137 | }); |
| 138 | let mut out = Vec::new(); |
| 139 | for (r, &(a, _)) in results.into_iter().zip(&bands) { |
| 140 | out.push((a, r?)); |
| 141 | } |
| 142 | Ok(out) |
| 143 | } |
| 144 | |
| 145 | pub fn decode_frame(data: &[u8], threads: usize) -> Result<DecodedFrame> { |
| 146 | let h = header::parse_frame(data)?; |
| 147 | let mut info = h.info.clone(); |
| 148 | let frame = &data[..h.end]; |
| 149 | let (w, hgt) = (info.width as usize, info.height as usize); |
| 150 | let mb_width = w.div_ceil(16); |
| 151 | let interlaced = info.interlace != Interlace::Progressive; |
| 152 | let mb_rows_frame = if interlaced { hgt.div_ceil(32) } else { hgt.div_ceil(16) }; |
| 153 | let npics = if interlaced { 2 } else { 1 }; |
| 154 | // Block storage is transposed (see `idct`), so the scan table is too. |
| 155 | let mut scan_t = [0u8; 64]; |
| 156 | for (t, &at) in scan_t.iter_mut().zip(if interlaced { &INTERLACED_SCAN } else { &PROGRESSIVE_SCAN }) { |
| 157 | *t = (at & 7) * 8 + (at >> 3); |
| 158 | } |
| 159 | let scan = &scan_t; |
| 160 | let is444 = info.is_444; |
| 161 | let cx = SliceCtx { |
| 162 | is_444: is444, |
| 163 | alpha_bits: info.alpha_bits, |
| 164 | scan, |
| 165 | qmat_luma: &h.qmat_luma, |
| 166 | qmat_chroma: &h.qmat_chroma, |
| 167 | b12: is444, |
| 168 | }; |
| 169 | |
| 170 | // Parse every picture header before allocating anything. |
| 171 | let mut pics = Vec::new(); |
| 172 | let mut at = h.pictures_at; |
| 173 | for i in 0..npics { |
| 174 | let p = header::parse_picture(frame, at, frame.len())?; |
| 175 | if i == 0 { |
| 176 | info.log2_slice_mbs = p.log2_slice_mbs as u8; |
| 177 | } |
| 178 | // Every slice needs at least its 6-byte header: bounds the picture area by the data. |
| 179 | if (p.end - p.data_at) < p.slice_count * 6 { |
| 180 | return Err(Error::corrupt("ProRes picture: slice data smaller than the slice headers")); |
| 181 | } |
| 182 | pics.push(build_slices(frame, &p, mb_width, mb_rows_frame)?); |
| 183 | at = p.end; |
| 184 | } |
| 185 | |
| 186 | let ypw = mb_width * 16; |
| 187 | let cpw = if is444 { ypw } else { mb_width * 8 }; |
| 188 | let total_rows = mb_rows_frame * 16 * npics; // padded frame height |
| 189 | let bytes = |rows: usize, pw: usize| vec![0u8; rows * pw * 2]; |
| 190 | let (mut py, mut pu, mut pv) = (Vec::new(), Vec::new(), Vec::new()); |
| 191 | let mut pa: Vec<u16> = Vec::new(); |
| 192 | |
| 193 | for (i, pic) in pics.iter().enumerate() { |
| 194 | let groups = decode_picture(&cx, frame, pic, mb_width, threads)?; |
| 195 | if npics == 1 && groups.len() == 1 { |
| 196 | // One group covers the whole frame: its buffers are the planes. |
| 197 | let (_, g) = groups.into_iter().next().unwrap(); |
| 198 | (py, pu, pv, pa) = (g.y, g.u, g.v, g.a); |
| 199 | continue; |
| 200 | } |
| 201 | if i == 0 { |
| 202 | py = bytes(total_rows, ypw); |
| 203 | pu = bytes(total_rows, cpw); |
| 204 | pv = bytes(total_rows, cpw); |
| 205 | if info.alpha_bits != 0 { |
| 206 | pa = vec![0; total_rows * ypw]; |
| 207 | } |
| 208 | } |
| 209 | // Field i lands on even lines when it is the top field, odd lines otherwise. |
| 210 | let bottom = interlaced && ((i == 0) == (info.interlace == Interlace::BottomFieldFirst)); |
| 211 | for (r0, g) in groups { |
| 212 | let rows = g.y.len() / (ypw * 2); |
| 213 | for r in 0..rows { |
| 214 | let line = (r0 * 16 + r) * npics + usize::from(bottom); |
| 215 | py[line * ypw * 2..(line + 1) * ypw * 2].copy_from_slice(&g.y[r * ypw * 2..(r + 1) * ypw * 2]); |
| 216 | pu[line * cpw * 2..(line + 1) * cpw * 2].copy_from_slice(&g.u[r * cpw * 2..(r + 1) * cpw * 2]); |
| 217 | pv[line * cpw * 2..(line + 1) * cpw * 2].copy_from_slice(&g.v[r * cpw * 2..(r + 1) * cpw * 2]); |
| 218 | if !pa.is_empty() { |
| 219 | pa[line * ypw..(line + 1) * ypw].copy_from_slice(&g.a[r * ypw..(r + 1) * ypw]); |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | let format = if is444 { PixelFormat::I412 } else { PixelFormat::I210 }; |
| 226 | let planes = vec![Plane::new(py, ypw * 2), Plane::new(pu, cpw * 2), Plane::new(pv, cpw * 2)]; |
| 227 | let mut video = VideoFrame::try_new(format, info.width, info.height, planes)?; |
| 228 | video.color = ColorInfo { |
| 229 | primaries: info.primaries, |
| 230 | transfer: info.transfer, |
| 231 | matrix: info.matrix, |
| 232 | full_range: false, |
| 233 | }; |
| 234 | video.interlace = info.interlace; |
| 235 | let alpha = (info.alpha_bits != 0).then_some(AlphaPlane { |
| 236 | width: info.width, |
| 237 | height: info.height, |
| 238 | stride: ypw, |
| 239 | data: pa, |
| 240 | }); |
| 241 | Ok(DecodedFrame { video, alpha, info }) |
| 242 | } |