edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·380.6 MiB·e18142d·Tahinli·3 hours ago·4543 commits
| 1 | //! The decoding core: start-code parsing, picture management, slice and |
| 2 | //! macroblock decoding, reconstruction and display-order output. |
| 3 | |
| 4 | use std::collections::VecDeque; |
| 5 | |
| 6 | use ec_core::error::{Error, Result}; |
| 7 | use ec_core::frame::{ColorInfo, Interlace, PixelFormat, Plane, VideoFrame}; |
| 8 | use ec_core::timebase::Timestamp; |
| 9 | |
| 10 | use crate::bits::Bits; |
| 11 | use crate::block::{BlockParams, decode_inter, decode_intra}; |
| 12 | use crate::header::*; |
| 13 | use crate::idct::{idct_add, idct_add_dc, idct_put, idct_put_dc}; |
| 14 | use crate::mc::{Image, predict}; |
| 15 | use crate::tables::*; |
| 16 | |
| 17 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 18 | enum SliceError { |
| 19 | Picture, |
| 20 | Address, |
| 21 | Quant, |
| 22 | Bitstream, |
| 23 | } |
| 24 | |
| 25 | /// Facts about a decoded picture that [`VideoFrame`] cannot carry. |
| 26 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 27 | pub struct PictureInfo { |
| 28 | /// Coding type of the picture (of the first field for field pairs). |
| 29 | pub picture_type: PictureType, |
| 30 | /// temporal_reference of the picture. |
| 31 | pub temporal_reference: u16, |
| 32 | /// top_field_first from the picture coding extension (false for MPEG-1). |
| 33 | pub top_field_first: bool, |
| 34 | /// repeat_first_field: display the first field again after the second. |
| 35 | pub repeat_first_field: bool, |
| 36 | /// progressive_frame: the two fields come from one instant. |
| 37 | pub progressive_frame: bool, |
| 38 | /// progressive_sequence from the sequence extension (true for MPEG-1). |
| 39 | pub progressive_sequence: bool, |
| 40 | /// True when the frame was coded as two field pictures. |
| 41 | pub field_pictures: bool, |
| 42 | /// True for MPEG-1 syntax (no sequence extension). |
| 43 | pub mpeg1: bool, |
| 44 | /// True when some macroblocks were missing or damaged and were concealed. |
| 45 | pub corrupt: bool, |
| 46 | /// The GOP header preceding this picture had closed_gop set. |
| 47 | pub closed_gop: bool, |
| 48 | } |
| 49 | |
| 50 | struct Pic { |
| 51 | planes: [Vec<u8>; 3], |
| 52 | stride: [usize; 3], |
| 53 | height: [usize; 3], |
| 54 | meta: Option<Meta>, |
| 55 | emitted: bool, |
| 56 | } |
| 57 | |
| 58 | #[derive(Clone)] |
| 59 | struct Meta { |
| 60 | pts: Option<Timestamp>, |
| 61 | info: PictureInfo, |
| 62 | interlace: Interlace, |
| 63 | } |
| 64 | |
| 65 | /// Frame under construction (one or two pictures). |
| 66 | struct CurFrame { |
| 67 | idx: usize, |
| 68 | ptype: PictureType, |
| 69 | first_structure: Structure, |
| 70 | waiting_second: bool, |
| 71 | pts: Option<Timestamp>, |
| 72 | tr: u16, |
| 73 | tff: bool, |
| 74 | rff: bool, |
| 75 | progressive_frame: bool, |
| 76 | corrupt: bool, |
| 77 | field_pictures: bool, |
| 78 | closed_gop: bool, |
| 79 | } |
| 80 | |
| 81 | /// State of the picture (frame or field) being decoded. |
| 82 | struct PicState { |
| 83 | hdr: PictureHeader, |
| 84 | mb_done: Vec<bool>, |
| 85 | rows: usize, |
| 86 | parity: usize, |
| 87 | second_field: bool, |
| 88 | } |
| 89 | |
| 90 | #[derive(Clone, Copy, Default, PartialEq, Eq)] |
| 91 | enum MotionKind { |
| 92 | #[default] |
| 93 | Frame, |
| 94 | FieldInFrame, |
| 95 | DualFrame, |
| 96 | Field16, |
| 97 | Mv16x8, |
| 98 | DualField, |
| 99 | } |
| 100 | |
| 101 | #[derive(Clone, Copy, Default)] |
| 102 | struct Motion { |
| 103 | /// [s][r][t] |
| 104 | mv: [[[i32; 2]; 2]; 2], |
| 105 | sel: [[u8; 2]; 2], |
| 106 | dmv: [i32; 2], |
| 107 | kind: MotionKind, |
| 108 | fwd: bool, |
| 109 | bwd: bool, |
| 110 | } |
| 111 | |
| 112 | struct MbInfo { |
| 113 | intra: bool, |
| 114 | m: Motion, |
| 115 | dct_field: bool, |
| 116 | cbp: u32, |
| 117 | last: [usize; 8], |
| 118 | } |
| 119 | |
| 120 | pub(crate) struct Core { |
| 121 | pub(crate) seq: Option<SequenceInfo>, |
| 122 | qm: QuantMatrices, |
| 123 | pool: Vec<Pic>, |
| 124 | ref_old: Option<usize>, |
| 125 | ref_new: Option<usize>, |
| 126 | cur: Option<CurFrame>, |
| 127 | pic: Option<PicState>, |
| 128 | pending_hdr: Option<PictureHeader>, |
| 129 | pending_pts: Option<Timestamp>, |
| 130 | pub(crate) out: VecDeque<(VideoFrame, PictureInfo)>, |
| 131 | buf: Vec<u8>, |
| 132 | marks: Vec<(usize, Option<Timestamp>)>, |
| 133 | closed_gop: bool, |
| 134 | unsupported: Option<Error>, |
| 135 | seq_changed: bool, |
| 136 | /// Pictures dropped because a reference was missing. |
| 137 | pub(crate) dropped: u64, |
| 138 | } |
| 139 | |
| 140 | const MAX_OUT: usize = 64; |
| 141 | const MAX_BUF: usize = 1 << 26; |
| 142 | |
| 143 | impl Core { |
| 144 | pub(crate) fn new() -> Core { |
| 145 | Core { |
| 146 | seq: None, |
| 147 | qm: QuantMatrices::default(), |
| 148 | pool: Vec::new(), |
| 149 | ref_old: None, |
| 150 | ref_new: None, |
| 151 | cur: None, |
| 152 | pic: None, |
| 153 | pending_hdr: None, |
| 154 | pending_pts: None, |
| 155 | out: VecDeque::new(), |
| 156 | buf: Vec::new(), |
| 157 | marks: Vec::new(), |
| 158 | closed_gop: false, |
| 159 | unsupported: None, |
| 160 | seq_changed: false, |
| 161 | dropped: 0, |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | /// Drop everything but the stream parameters' defaults (seek). |
| 166 | pub(crate) fn reset(&mut self) { |
| 167 | self.pool.clear(); |
| 168 | self.ref_old = None; |
| 169 | self.ref_new = None; |
| 170 | self.cur = None; |
| 171 | self.pic = None; |
| 172 | self.pending_hdr = None; |
| 173 | self.out.clear(); |
| 174 | self.buf.clear(); |
| 175 | self.marks.clear(); |
| 176 | self.unsupported = None; |
| 177 | } |
| 178 | |
| 179 | // ------------------------------------------------------------------ |
| 180 | // Byte stream |
| 181 | // ------------------------------------------------------------------ |
| 182 | |
| 183 | /// Append stream bytes (arbitrary chunking) and decode every complete unit. |
| 184 | pub(crate) fn push(&mut self, data: &[u8], pts: Option<Timestamp>) -> Result<()> { |
| 185 | if self.buf.len() + data.len() > MAX_BUF { |
| 186 | // No start code for a very long time: the data is not video. |
| 187 | self.buf.clear(); |
| 188 | self.marks.clear(); |
| 189 | } |
| 190 | self.marks.push((self.buf.len(), pts)); |
| 191 | self.buf.extend_from_slice(data); |
| 192 | self.process(false) |
| 193 | } |
| 194 | |
| 195 | /// Decode the trailing unit too (the caller knows the data is complete). |
| 196 | pub(crate) fn push_complete(&mut self, data: &[u8], pts: Option<Timestamp>) -> Result<()> { |
| 197 | self.push(data, pts)?; |
| 198 | self.process(true) |
| 199 | } |
| 200 | |
| 201 | fn pts_at(&self, off: usize) -> Option<Timestamp> { |
| 202 | self.marks.iter().rev().find(|m| m.0 <= off).and_then(|m| m.1) |
| 203 | } |
| 204 | |
| 205 | fn process(&mut self, all: bool) -> Result<()> { |
| 206 | let buf = std::mem::take(&mut self.buf); |
| 207 | let mut starts: Vec<usize> = Vec::new(); |
| 208 | let mut k = 2usize; |
| 209 | while k < buf.len() { |
| 210 | if buf[k] == 1 && buf[k - 1] == 0 && buf[k - 2] == 0 { |
| 211 | if k + 1 < buf.len() { |
| 212 | starts.push(k - 2); |
| 213 | } |
| 214 | k += 3; |
| 215 | } else { |
| 216 | k += 1; |
| 217 | } |
| 218 | } |
| 219 | let units = if all { starts.len() } else { starts.len().saturating_sub(1) }; |
| 220 | for k in 0..units { |
| 221 | let s = starts[k]; |
| 222 | let e = if k + 1 < starts.len() { starts[k + 1] } else { buf.len() }; |
| 223 | let pts = self.pts_at(s); |
| 224 | // A start code can begin on the previous code byte (00 00 01 00 00 01): empty payload. |
| 225 | self.unit(buf[s + 3], &buf[(s + 4).min(e)..e], pts); |
| 226 | } |
| 227 | let keep_from = if all { |
| 228 | buf.len() |
| 229 | } else if units < starts.len() { |
| 230 | starts[units] |
| 231 | } else { |
| 232 | // No complete start code yet: keep a possible partial start code. |
| 233 | buf.len().saturating_sub(3) |
| 234 | }; |
| 235 | self.buf = buf[keep_from..].to_vec(); |
| 236 | let n = keep_from; |
| 237 | for m in &mut self.marks { |
| 238 | m.0 = m.0.saturating_sub(n); |
| 239 | } |
| 240 | // Keep only the last mark at offset 0. |
| 241 | while self.marks.len() > 1 && self.marks[1].0 == 0 { |
| 242 | self.marks.remove(0); |
| 243 | } |
| 244 | if all { |
| 245 | self.marks.clear(); |
| 246 | } |
| 247 | match self.unsupported.take() { |
| 248 | Some(e) => Err(e), |
| 249 | None => Ok(()), |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | fn fail(&mut self, e: Error) { |
| 254 | if self.unsupported.is_none() { |
| 255 | self.unsupported = Some(e); |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | fn unit(&mut self, code: u8, payload: &[u8], pts: Option<Timestamp>) { |
| 260 | match code { |
| 261 | 0x00 => { |
| 262 | self.end_picture(); |
| 263 | if self.cur.as_ref().is_some_and(|c| !c.waiting_second) { |
| 264 | self.finish_frame(); |
| 265 | } |
| 266 | match parse_picture_header(payload) { |
| 267 | Ok(h) => { |
| 268 | self.pending_hdr = Some(h); |
| 269 | self.pending_pts = pts; |
| 270 | } |
| 271 | Err(e) => { |
| 272 | self.pending_hdr = None; |
| 273 | self.fail(e); |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | 0xB3 => { |
| 278 | self.end_picture(); |
| 279 | self.finish_frame(); |
| 280 | let mut qm = QuantMatrices::default(); |
| 281 | match parse_sequence_header(payload, &mut qm) { |
| 282 | Ok(mut s) => { |
| 283 | let changed = self |
| 284 | .seq |
| 285 | .as_ref() |
| 286 | .is_none_or(|o| o.width != s.width || o.height != s.height); |
| 287 | if !changed && let Some(o) = self.seq.as_ref() { |
| 288 | // The header carries no chroma format; keep the extension's. |
| 289 | s.chroma_format = o.chroma_format; |
| 290 | } |
| 291 | if changed { |
| 292 | self.flush_output(); |
| 293 | self.ref_old = None; |
| 294 | self.ref_new = None; |
| 295 | self.pool.clear(); |
| 296 | } |
| 297 | self.seq = Some(s); |
| 298 | self.qm = qm; |
| 299 | self.seq_changed = true; |
| 300 | } |
| 301 | Err(e) => self.fail(e), |
| 302 | } |
| 303 | } |
| 304 | 0xB5 => self.extension(payload), |
| 305 | 0xB8 => { |
| 306 | self.end_picture(); |
| 307 | self.finish_frame(); |
| 308 | let mut b = Bits::new(payload); |
| 309 | b.skip(25); |
| 310 | self.closed_gop = b.read1(); |
| 311 | } |
| 312 | 0xB7 => { |
| 313 | self.end_picture(); |
| 314 | self.finish_frame(); |
| 315 | } |
| 316 | 0x01..=0xAF => self.slice(code, payload), |
| 317 | _ => {} |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | fn extension(&mut self, payload: &[u8]) { |
| 322 | let mut b = Bits::new(payload); |
| 323 | let id = b.read(4); |
| 324 | match id { |
| 325 | 1 => { |
| 326 | if let Some(seq) = self.seq.as_mut() { |
| 327 | // Sequence extension right after a sequence header. |
| 328 | let mut s2 = seq.clone(); |
| 329 | match parse_sequence_extension(&mut b, &mut s2) { |
| 330 | Ok(()) => { |
| 331 | let changed = s2.width != seq.width || s2.height != seq.height || s2.chroma_format != seq.chroma_format; |
| 332 | *seq = s2; |
| 333 | if changed { |
| 334 | self.cur = None; |
| 335 | self.pool.clear(); |
| 336 | self.ref_old = None; |
| 337 | self.ref_new = None; |
| 338 | } |
| 339 | } |
| 340 | Err(e) => self.fail(e), |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | 3 => { |
| 345 | let cf = self.seq.as_ref().map_or(1, |s| s.chroma_format); |
| 346 | let mut qm = self.qm.clone(); |
| 347 | match parse_quant_matrix_extension(&mut b, &mut qm, cf) { |
| 348 | Ok(()) => self.qm = qm, |
| 349 | Err(e) => self.fail(e), |
| 350 | } |
| 351 | } |
| 352 | 5 => self.fail(Error::unsupported( |
| 353 | "MPEG-2 scalable extension", |
| 354 | "SNR, spatial and temporal scalability layers are not decoded", |
| 355 | )), |
| 356 | 8 => { |
| 357 | if let Some(h) = self.pending_hdr.as_mut() |
| 358 | && let Err(e) = parse_picture_coding_extension(&mut b, h) { |
| 359 | self.pending_hdr = None; |
| 360 | self.fail(e); |
| 361 | } |
| 362 | } |
| 363 | _ => {} |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | // ------------------------------------------------------------------ |
| 368 | // Picture management |
| 369 | // ------------------------------------------------------------------ |
| 370 | |
| 371 | fn alloc_pic(&mut self) -> usize { |
| 372 | let seq = self.seq.as_ref().expect("sequence"); |
| 373 | let mw = seq.mb_width() * 16; |
| 374 | let mh = seq.mb_height() * 16; |
| 375 | let (sx, sy) = chroma_shift(seq.chroma_format); |
| 376 | let cw = mw >> sx; |
| 377 | let ch = mh >> sy; |
| 378 | let busy = |i: usize, c: &Core| { |
| 379 | Some(i) == c.ref_old |
| 380 | || Some(i) == c.ref_new |
| 381 | || c.cur.as_ref().is_some_and(|f| f.idx == i) |
| 382 | }; |
| 383 | let new_pic = || Pic { |
| 384 | planes: [vec![128; mw * mh], vec![128; cw * ch], vec![128; cw * ch]], |
| 385 | stride: [mw, cw, cw], |
| 386 | height: [mh, ch, ch], |
| 387 | meta: None, |
| 388 | emitted: false, |
| 389 | }; |
| 390 | for i in 0..self.pool.len() { |
| 391 | if !busy(i, self) { |
| 392 | let p = &mut self.pool[i]; |
| 393 | // The MB rows can change without a resize: never reuse planes of another geometry. |
| 394 | if p.stride != [mw, cw, cw] || p.height != [mh, ch, ch] { |
| 395 | *p = new_pic(); |
| 396 | } |
| 397 | p.meta = None; |
| 398 | p.emitted = false; |
| 399 | return i; |
| 400 | } |
| 401 | } |
| 402 | self.pool.push(new_pic()); |
| 403 | self.pool.len() - 1 |
| 404 | } |
| 405 | |
| 406 | fn begin_picture(&mut self) -> bool { |
| 407 | let Some(hdr) = self.pending_hdr.take() else { |
| 408 | return false; |
| 409 | }; |
| 410 | let Some(seq) = self.seq.clone() else { |
| 411 | return false; |
| 412 | }; |
| 413 | if seq.width > MAX_DIMENSION |
| 414 | || seq.height > MAX_DIMENSION |
| 415 | || seq.width * seq.height > MAX_AREA |
| 416 | { |
| 417 | self.fail(Error::unsupported( |
| 418 | format!("{}x{} MPEG video", seq.width, seq.height), |
| 419 | "picture larger than the decoder's allocation bound", |
| 420 | )); |
| 421 | return false; |
| 422 | } |
| 423 | if seq.mpeg2 && !hdr.has_extension { |
| 424 | self.fail(Error::corrupt("MPEG-2 picture without picture_coding_extension")); |
| 425 | return false; |
| 426 | } |
| 427 | if seq.chroma_format != 1 && seq.chroma_format != 2 { |
| 428 | self.fail(Error::unsupported( |
| 429 | format!("MPEG-2 chroma_format {}", seq.chroma_format), |
| 430 | "only 4:2:0 and 4:2:2 are decoded", |
| 431 | )); |
| 432 | return false; |
| 433 | } |
| 434 | let rows_frame = seq.mb_height(); |
| 435 | // Second field of the frame in progress? |
| 436 | let mut second = false; |
| 437 | if let Some(cf) = self.cur.as_ref() |
| 438 | && cf.waiting_second |
| 439 | && hdr.structure != Structure::Frame |
| 440 | && hdr.structure != cf.first_structure |
| 441 | { |
| 442 | second = true; |
| 443 | } |
| 444 | if !second { |
| 445 | self.finish_frame(); |
| 446 | } |
| 447 | let ptype = hdr.picture_type; |
| 448 | if !second { |
| 449 | // Reference availability. |
| 450 | let missing = match ptype { |
| 451 | PictureType::I => false, |
| 452 | PictureType::P => self.ref_new.is_none(), |
| 453 | PictureType::B => self.ref_new.is_none(), |
| 454 | }; |
| 455 | if ptype == PictureType::B && self.ref_old.is_none() && self.ref_new.is_some() { |
| 456 | // Leading B pictures of an open GOP: the forward reference is |
| 457 | // gone. Not decodable correctly. |
| 458 | self.dropped += 1; |
| 459 | self.cur = None; |
| 460 | self.pic = None; |
| 461 | return false; |
| 462 | } |
| 463 | if missing { |
| 464 | // P (or B) without any reference: predict from mid-grey. |
| 465 | let g = self.alloc_pic(); |
| 466 | self.ref_new = Some(g); |
| 467 | self.ref_old = None; |
| 468 | self.pool[g].emitted = true; |
| 469 | } |
| 470 | let idx = self.alloc_pic(); |
| 471 | self.cur = Some(CurFrame { |
| 472 | idx, |
| 473 | ptype, |
| 474 | first_structure: hdr.structure, |
| 475 | waiting_second: false, |
| 476 | pts: self.pending_pts.take(), |
| 477 | tr: hdr.temporal_reference, |
| 478 | tff: if hdr.structure == Structure::Frame { |
| 479 | hdr.top_field_first |
| 480 | } else { |
| 481 | hdr.structure == Structure::Top |
| 482 | }, |
| 483 | rff: hdr.repeat_first_field, |
| 484 | progressive_frame: hdr.progressive_frame || !seq.mpeg2, |
| 485 | corrupt: missing, |
| 486 | field_pictures: hdr.structure != Structure::Frame, |
| 487 | closed_gop: self.closed_gop, |
| 488 | }); |
| 489 | } else if let Some(cf) = self.cur.as_mut() { |
| 490 | cf.waiting_second = false; |
| 491 | } |
| 492 | let parity = match hdr.structure { |
| 493 | Structure::Bottom => 1, |
| 494 | _ => 0, |
| 495 | }; |
| 496 | let rows = if hdr.structure == Structure::Frame { |
| 497 | rows_frame |
| 498 | } else { |
| 499 | rows_frame / 2 |
| 500 | }; |
| 501 | self.pic = Some(PicState { |
| 502 | hdr, |
| 503 | mb_done: vec![false; rows * seq.mb_width()], |
| 504 | rows, |
| 505 | parity, |
| 506 | second_field: second, |
| 507 | }); |
| 508 | true |
| 509 | } |
| 510 | |
| 511 | /// Finish the picture being decoded: conceal macroblocks that never arrived. |
| 512 | fn end_picture(&mut self) { |
| 513 | let Some(st) = self.pic.take() else { |
| 514 | return; |
| 515 | }; |
| 516 | let Some(seq) = self.seq.clone() else { |
| 517 | return; |
| 518 | }; |
| 519 | let Some(cf) = self.cur.as_mut() else { |
| 520 | return; |
| 521 | }; |
| 522 | let mw = seq.mb_width(); |
| 523 | let missing = st.mb_done.iter().filter(|d| !**d).count(); |
| 524 | if missing > 0 { |
| 525 | cf.corrupt = true; |
| 526 | let (sx, sy) = chroma_shift(seq.chroma_format); |
| 527 | let refidx = self.ref_new.filter(|&r| r != cf.idx); |
| 528 | for (addr, done) in st.mb_done.iter().enumerate() { |
| 529 | if *done { |
| 530 | continue; |
| 531 | } |
| 532 | let mb_x = addr % mw; |
| 533 | let mb_y = addr / mw; |
| 534 | conceal_mb(&mut self.pool, cf.idx, refidx, st.hdr.structure, st.parity, mb_x, mb_y, sx, sy); |
| 535 | } |
| 536 | } |
| 537 | if st.hdr.structure != Structure::Frame { |
| 538 | // Wait for the second field. |
| 539 | if !st.second_field { |
| 540 | cf.waiting_second = true; |
| 541 | } |
| 542 | } |
| 543 | cf.progressive_frame &= st.hdr.progressive_frame || !seq.mpeg2; |
| 544 | } |
| 545 | |
| 546 | /// Complete the frame under construction: update references, emit output. |
| 547 | fn finish_frame(&mut self) { |
| 548 | let Some(cf) = self.cur.take() else { |
| 549 | return; |
| 550 | }; |
| 551 | let Some(seq) = self.seq.as_ref() else { |
| 552 | return; |
| 553 | }; |
| 554 | let interlace = if cf.progressive_frame { |
| 555 | Interlace::Progressive |
| 556 | } else if cf.tff { |
| 557 | Interlace::TopFieldFirst |
| 558 | } else { |
| 559 | Interlace::BottomFieldFirst |
| 560 | }; |
| 561 | let info = PictureInfo { |
| 562 | picture_type: cf.ptype, |
| 563 | temporal_reference: cf.tr, |
| 564 | top_field_first: cf.tff, |
| 565 | repeat_first_field: cf.rff, |
| 566 | progressive_frame: cf.progressive_frame, |
| 567 | progressive_sequence: seq.progressive_sequence, |
| 568 | field_pictures: cf.field_pictures, |
| 569 | mpeg1: !seq.mpeg2, |
| 570 | corrupt: cf.corrupt, |
| 571 | closed_gop: cf.closed_gop, |
| 572 | }; |
| 573 | self.pool[cf.idx].meta = Some(Meta { |
| 574 | pts: cf.pts, |
| 575 | info, |
| 576 | interlace, |
| 577 | }); |
| 578 | match cf.ptype { |
| 579 | PictureType::B => self.emit(cf.idx), |
| 580 | _ => { |
| 581 | if let Some(prev) = self.ref_new { |
| 582 | self.emit(prev); |
| 583 | } |
| 584 | self.ref_old = self.ref_new; |
| 585 | self.ref_new = Some(cf.idx); |
| 586 | } |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | fn emit(&mut self, idx: usize) { |
| 591 | let Some(seq) = self.seq.as_ref() else { |
| 592 | return; |
| 593 | }; |
| 594 | let p = &mut self.pool[idx]; |
| 595 | if p.emitted { |
| 596 | return; |
| 597 | } |
| 598 | p.emitted = true; |
| 599 | let Some(meta) = p.meta.clone() else { |
| 600 | return; |
| 601 | }; |
| 602 | let (w, h) = (seq.width as usize, seq.height as usize); |
| 603 | let (sx, sy) = chroma_shift(seq.chroma_format); |
| 604 | let format = if seq.chroma_format == 1 { |
| 605 | PixelFormat::I420 |
| 606 | } else { |
| 607 | PixelFormat::I422 |
| 608 | }; |
| 609 | let dims = [(w, h), (w.div_ceil(1 << sx), h.div_ceil(1 << sy)), (w.div_ceil(1 << sx), h.div_ceil(1 << sy))]; |
| 610 | let mut planes = Vec::with_capacity(3); |
| 611 | for (c, &(pw, ph)) in dims.iter().enumerate() { |
| 612 | let stride = p.stride[c]; |
| 613 | // A picture decoded under different sequence parameters is dropped, not read out of range. |
| 614 | if ph == 0 || p.planes[c].len() < (ph - 1) * stride + pw { |
| 615 | return; |
| 616 | } |
| 617 | let mut data = Vec::with_capacity(pw * ph); |
| 618 | for y in 0..ph { |
| 619 | data.extend_from_slice(&p.planes[c][y * stride..y * stride + pw]); |
| 620 | } |
| 621 | planes.push(Plane::new(data, pw)); |
| 622 | } |
| 623 | let mut f = VideoFrame { |
| 624 | format, |
| 625 | width: w as u32, |
| 626 | height: h as u32, |
| 627 | planes, |
| 628 | color: ColorInfo::default(), |
| 629 | pts: meta.pts, |
| 630 | interlace: meta.interlace, |
| 631 | }; |
| 632 | f.color = ColorInfo::default(); |
| 633 | if self.out.len() >= MAX_OUT { |
| 634 | self.out.pop_front(); |
| 635 | } |
| 636 | self.out.push_back((f, meta.info)); |
| 637 | } |
| 638 | |
| 639 | fn flush_output(&mut self) { |
| 640 | if let Some(r) = self.ref_new { |
| 641 | self.emit(r); |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | /// End of stream: decode what is buffered and drain the reorder delay. |
| 646 | pub(crate) fn flush(&mut self) -> Result<()> { |
| 647 | let r = self.process(true); |
| 648 | self.end_picture(); |
| 649 | self.finish_frame(); |
| 650 | self.flush_output(); |
| 651 | r |
| 652 | } |
| 653 | |
| 654 | // ------------------------------------------------------------------ |
| 655 | // Slices |
| 656 | // ------------------------------------------------------------------ |
| 657 | |
| 658 | fn slice(&mut self, code: u8, payload: &[u8]) { |
| 659 | if self.pic.is_none() { |
| 660 | if self.pending_hdr.is_none() { |
| 661 | return; |
| 662 | } |
| 663 | if !self.begin_picture() { |
| 664 | return; |
| 665 | } |
| 666 | } |
| 667 | if self.cur.is_none() { |
| 668 | return; |
| 669 | } |
| 670 | let _ = self.decode_slice(code, payload); |
| 671 | } |
| 672 | |
| 673 | #[allow(clippy::too_many_lines)] |
| 674 | fn decode_slice(&mut self, code: u8, data: &[u8]) -> std::result::Result<(), SliceError> { |
| 675 | let seq = self.seq.clone().ok_or(SliceError::Picture)?; |
| 676 | let t = tables(); |
| 677 | let mut st = self.pic.take().ok_or(SliceError::Picture)?; |
| 678 | let r = self.slice_inner(&seq, t, &mut st, code, data); |
| 679 | self.pic = Some(st); |
| 680 | r |
| 681 | } |
| 682 | |
| 683 | fn slice_inner( |
| 684 | &mut self, |
| 685 | seq: &SequenceInfo, |
| 686 | t: &Tables, |
| 687 | st: &mut PicState, |
| 688 | code: u8, |
| 689 | data: &[u8], |
| 690 | ) -> std::result::Result<(), SliceError> { |
| 691 | let hdr = st.hdr.clone(); |
| 692 | let mpeg1 = !seq.mpeg2; |
| 693 | let mut b = Bits::new(data); |
| 694 | let mut mb_row = code as usize - 1; |
| 695 | if seq.height > 2800 { |
| 696 | mb_row += (b.read(3) as usize) << 7; |
| 697 | } |
| 698 | let mw = seq.mb_width(); |
| 699 | if mb_row >= st.rows { |
| 700 | return Err(SliceError::Address); |
| 701 | } |
| 702 | let qcode = b.read(5) as usize; |
| 703 | if qcode == 0 { |
| 704 | return Err(SliceError::Quant); |
| 705 | } |
| 706 | while b.read1() { |
| 707 | b.skip(8); |
| 708 | } |
| 709 | let cur_idx = self.cur.as_ref().ok_or(SliceError::Picture)?.idx; |
| 710 | // The picture must match this slice's geometry, or macroblock rows fall outside its planes. |
| 711 | if self.pool[cur_idx].height[0] != seq.mb_height() * 16 { |
| 712 | return Err(SliceError::Picture); |
| 713 | } |
| 714 | let ptype = hdr.picture_type; |
| 715 | let field_pic = hdr.structure != Structure::Frame; |
| 716 | let total = st.rows * mw; |
| 717 | let scan: &[u8; 64] = if hdr.alternate_scan { &ALT_SCAN } else { &ZIGZAG }; |
| 718 | let qscale_of = |code: usize| -> i32 { |
| 719 | if mpeg1 { |
| 720 | code as i32 |
| 721 | } else if hdr.q_scale_type { |
| 722 | NONLINEAR_QSCALE[code & 31] as i32 |
| 723 | } else { |
| 724 | (code as i32) * 2 |
| 725 | } |
| 726 | }; |
| 727 | let mut qscale = qscale_of(qcode); |
| 728 | let dc_reset = if mpeg1 { 128 } else { 1 << (7 + hdr.intra_dc_precision as i32) }; |
| 729 | let dc_mult = if mpeg1 { 8 } else { 8 >> hdr.intra_dc_precision }; |
| 730 | let mut dc_pred = [dc_reset; 3]; |
| 731 | let mut pmv = [[[0i32; 2]; 2]; 2]; // [r][s][t] |
| 732 | let mut motion = Motion { fwd: true, ..Motion::default() }; |
| 733 | let mut addr: isize = (mb_row * mw) as isize - 1; |
| 734 | let mut first = true; |
| 735 | let nblocks = if seq.chroma_format == 1 { 6 } else { 8 }; |
| 736 | let mut blocks = [[0i16; 64]; 8]; |
| 737 | |
| 738 | loop { |
| 739 | // macroblock_address_increment |
| 740 | let mut inc = 0usize; |
| 741 | loop { |
| 742 | let v = b.vlc(&t.mba).ok_or(SliceError::Bitstream)?; |
| 743 | if v == 34 { |
| 744 | inc += 33; |
| 745 | } else if v == 35 { |
| 746 | // MPEG-1 macroblock stuffing |
| 747 | } else { |
| 748 | inc += v as usize; |
| 749 | break; |
| 750 | } |
| 751 | if b.overrun() { |
| 752 | return Err(SliceError::Bitstream); |
| 753 | } |
| 754 | } |
| 755 | if first { |
| 756 | addr += inc as isize; |
| 757 | first = false; |
| 758 | } else { |
| 759 | // skipped macroblocks |
| 760 | for _ in 1..inc { |
| 761 | addr += 1; |
| 762 | if addr as usize >= total { |
| 763 | return Err(SliceError::Address); |
| 764 | } |
| 765 | let a = addr as usize; |
| 766 | // Skipped macroblock. |
| 767 | dc_pred = [dc_reset; 3]; |
| 768 | let mut m = motion; |
| 769 | if ptype == PictureType::B { |
| 770 | // Same directions and vectors as the previous macroblock, |
| 771 | // predicted frame-wise (field-wise from the same-parity |
| 772 | // field in a field picture). |
| 773 | m.kind = if field_pic { MotionKind::Field16 } else { MotionKind::Frame }; |
| 774 | for s2 in 0..2 { |
| 775 | m.mv[s2][0] = pmv[0][s2]; |
| 776 | m.mv[s2][1] = pmv[0][s2]; |
| 777 | m.sel[s2] = [st.parity as u8; 2]; |
| 778 | } |
| 779 | } |
| 780 | if ptype == PictureType::P { |
| 781 | pmv = [[[0; 2]; 2]; 2]; |
| 782 | m = Motion::default(); |
| 783 | m.fwd = true; |
| 784 | m.kind = if field_pic { MotionKind::Field16 } else { MotionKind::Frame }; |
| 785 | let sel = st.parity as u8; |
| 786 | m.sel = [[sel; 2]; 2]; |
| 787 | motion = m; |
| 788 | } |
| 789 | if ptype == PictureType::I { |
| 790 | return Err(SliceError::Address); |
| 791 | } |
| 792 | let info = MbInfo { intra: false, m, dct_field: false, cbp: 0, last: [0; 8] }; |
| 793 | self.recon_mb(seq, &hdr, st, cur_idx, a % mw, a / mw, &info, &mut blocks); |
| 794 | st.mb_done[a] = true; |
| 795 | } |
| 796 | addr += 1; |
| 797 | } |
| 798 | if addr < 0 || addr as usize >= total { |
| 799 | return Err(SliceError::Bitstream); |
| 800 | } |
| 801 | let a = addr as usize; |
| 802 | let mb_x = a % mw; |
| 803 | let mb_y = a / mw; |
| 804 | |
| 805 | // macroblock_type |
| 806 | let ti = match ptype { |
| 807 | PictureType::I => 0, |
| 808 | PictureType::P => 1, |
| 809 | PictureType::B => 2, |
| 810 | }; |
| 811 | let flags = b.vlc(&t.mbtype[ti]).ok_or(SliceError::Bitstream)? as u16; |
| 812 | let intra = flags & MB_INTRA != 0; |
| 813 | let mut m = Motion { fwd: flags & MB_FWD != 0, bwd: flags & MB_BWD != 0, ..Motion::default() }; |
| 814 | let mut dct_field = false; |
| 815 | let mut kind_code = 0u32; |
| 816 | if !mpeg1 && (m.fwd || m.bwd) { |
| 817 | if hdr.structure == Structure::Frame && hdr.frame_pred_frame_dct { |
| 818 | kind_code = 2; // frame-based |
| 819 | } else { |
| 820 | kind_code = b.read(2); |
| 821 | if kind_code == 0 { |
| 822 | return Err(SliceError::Bitstream); |
| 823 | } |
| 824 | } |
| 825 | } else if mpeg1 { |
| 826 | kind_code = 2; |
| 827 | } |
| 828 | if !mpeg1 && hdr.structure == Structure::Frame && !hdr.frame_pred_frame_dct && (intra || flags & MB_PAT != 0) { |
| 829 | dct_field = b.read1(); |
| 830 | } |
| 831 | if flags & MB_QUANT != 0 { |
| 832 | let qc = b.read(5) as usize; |
| 833 | if qc == 0 { |
| 834 | return Err(SliceError::Quant); |
| 835 | } |
| 836 | qscale = qscale_of(qc); |
| 837 | } |
| 838 | m.kind = if field_pic { |
| 839 | match kind_code { |
| 840 | 1 => MotionKind::Field16, |
| 841 | 2 => MotionKind::Mv16x8, |
| 842 | _ => MotionKind::DualField, |
| 843 | } |
| 844 | } else { |
| 845 | match kind_code { |
| 846 | 1 => MotionKind::FieldInFrame, |
| 847 | 2 => MotionKind::Frame, |
| 848 | _ => MotionKind::DualFrame, |
| 849 | } |
| 850 | }; |
| 851 | if intra && hdr.concealment_motion_vectors { |
| 852 | m.kind = if field_pic { MotionKind::Field16 } else { MotionKind::Frame }; |
| 853 | } |
| 854 | // Motion vectors. |
| 855 | if m.fwd || (intra && hdr.concealment_motion_vectors) { |
| 856 | read_motion(&mut b, t, &hdr, mpeg1, &mut m, &mut pmv, 0)?; |
| 857 | } |
| 858 | if m.bwd { |
| 859 | read_motion(&mut b, t, &hdr, mpeg1, &mut m, &mut pmv, 1)?; |
| 860 | } |
| 861 | if intra && hdr.concealment_motion_vectors { |
| 862 | b.skip(1); |
| 863 | } |
| 864 | if intra { |
| 865 | if !hdr.concealment_motion_vectors { |
| 866 | pmv = [[[0; 2]; 2]; 2]; |
| 867 | } |
| 868 | m.fwd = false; |
| 869 | m.bwd = false; |
| 870 | } else { |
| 871 | if ptype == PictureType::P && !m.fwd { |
| 872 | // No motion compensation: zero vector. |
| 873 | pmv = [[[0; 2]; 2]; 2]; |
| 874 | m.fwd = true; |
| 875 | m.kind = if field_pic { MotionKind::Field16 } else { MotionKind::Frame }; |
| 876 | m.sel = [[st.parity as u8; 2]; 2]; |
| 877 | m.mv = [[[0; 2]; 2]; 2]; |
| 878 | } |
| 879 | dc_pred = [dc_reset; 3]; |
| 880 | } |
| 881 | // coded_block_pattern |
| 882 | let mut cbp = 0u32; |
| 883 | if intra { |
| 884 | cbp = (1 << nblocks) - 1; |
| 885 | } else if flags & MB_PAT != 0 { |
| 886 | cbp = b.vlc(&t.cbp).ok_or(SliceError::Bitstream)?; |
| 887 | if seq.chroma_format == 2 { |
| 888 | cbp = (cbp << 2) | b.read(2); |
| 889 | } |
| 890 | } |
| 891 | // Blocks. |
| 892 | let mut last = [0usize; 8]; |
| 893 | let mut ok = true; |
| 894 | for i in 0..nblocks { |
| 895 | if cbp & (1 << (nblocks - 1 - i)) == 0 { |
| 896 | continue; |
| 897 | } |
| 898 | let comp = if i < 4 { 0 } else { 1 + (i & 1) }; |
| 899 | let chroma = i >= 4; |
| 900 | let (matrix, _) = if intra { |
| 901 | (if chroma { &self.qm.chroma_intra } else { &self.qm.intra }, 0) |
| 902 | } else { |
| 903 | (if chroma { &self.qm.chroma_non_intra } else { &self.qm.non_intra }, 0) |
| 904 | }; |
| 905 | let p = BlockParams { mpeg1, qscale, matrix, scan, alt_vlc: hdr.intra_vlc_format }; |
| 906 | let r = if intra { |
| 907 | let tbl = if comp == 0 { &t.dc_luma } else { &t.dc_chroma }; |
| 908 | let size = match b.vlc(tbl) { |
| 909 | Some(s) => s, |
| 910 | None => { |
| 911 | ok = false; |
| 912 | break; |
| 913 | } |
| 914 | }; |
| 915 | let mut diff = 0i32; |
| 916 | if size > 0 { |
| 917 | let v = b.read(size) as i32; |
| 918 | diff = if v < (1 << (size - 1)) { v - (1 << size) + 1 } else { v }; |
| 919 | } |
| 920 | dc_pred[comp] += diff; |
| 921 | decode_intra(&mut b, t, &p, &mut blocks[i], dc_pred[comp] * dc_mult) |
| 922 | } else { |
| 923 | decode_inter(&mut b, t, &p, &mut blocks[i]) |
| 924 | }; |
| 925 | match r { |
| 926 | Some(l) => last[i] = l, |
| 927 | None => { |
| 928 | ok = false; |
| 929 | break; |
| 930 | } |
| 931 | } |
| 932 | if b.overrun() { |
| 933 | ok = false; |
| 934 | break; |
| 935 | } |
| 936 | } |
| 937 | if !ok { |
| 938 | for blk in blocks.iter_mut() { |
| 939 | *blk = [0; 64]; |
| 940 | } |
| 941 | return Err(SliceError::Bitstream); |
| 942 | } |
| 943 | let info = MbInfo { intra, m, dct_field, cbp, last }; |
| 944 | self.recon_mb(seq, &hdr, st, cur_idx, mb_x, mb_y, &info, &mut blocks); |
| 945 | st.mb_done[a] = true; |
| 946 | if !intra { |
| 947 | motion = m; |
| 948 | } else if ptype == PictureType::B { |
| 949 | // A skipped macroblock after an intra one repeats nothing useful. |
| 950 | motion = Motion { fwd: true, ..Motion::default() }; |
| 951 | } |
| 952 | if b.overrun() { |
| 953 | return Err(SliceError::Bitstream); |
| 954 | } |
| 955 | if b.peek(23) == 0 { |
| 956 | break; |
| 957 | } |
| 958 | } |
| 959 | Ok(()) |
| 960 | } |
| 961 | |
| 962 | fn ref_for(&self, ptype: PictureType, s: usize, field: Option<u8>, st: &PicState, cur: usize) -> usize { |
| 963 | match ptype { |
| 964 | PictureType::I => cur, |
| 965 | PictureType::P => { |
| 966 | if st.hdr.structure != Structure::Frame |
| 967 | && st.second_field |
| 968 | && field.is_some_and(|f| f as usize != st.parity) |
| 969 | { |
| 970 | cur |
| 971 | } else { |
| 972 | self.ref_new.unwrap_or(cur) |
| 973 | } |
| 974 | } |
| 975 | PictureType::B => { |
| 976 | if s == 0 { |
| 977 | self.ref_old.or(self.ref_new).unwrap_or(cur) |
| 978 | } else { |
| 979 | self.ref_new.unwrap_or(cur) |
| 980 | } |
| 981 | } |
| 982 | } |
| 983 | } |
| 984 | |
| 985 | /// Build the inter prediction of a macroblock into `pred` (pitch 16). |
| 986 | #[allow(clippy::too_many_arguments)] |
| 987 | fn build_pred( |
| 988 | &self, |
| 989 | pred: &mut [[u8; 256]; 3], |
| 990 | seq: &SequenceInfo, |
| 991 | hdr: &PictureHeader, |
| 992 | st: &PicState, |
| 993 | cur: usize, |
| 994 | mb_x: usize, |
| 995 | mb_y: usize, |
| 996 | m: &Motion, |
| 997 | ) { |
| 998 | let (sx, sy) = chroma_shift(seq.chroma_format); |
| 999 | let mut dirs_done = 0; |
| 1000 | for s in 0..2 { |
| 1001 | if !(if s == 0 { m.fwd } else { m.bwd }) { |
| 1002 | continue; |
| 1003 | } |
| 1004 | let mut parts: [Option<Part>; 4] = [None; 4]; |
| 1005 | let mut np = 0; |
| 1006 | let mut push = |p: Part| { |
| 1007 | parts[np] = Some(p); |
| 1008 | np += 1; |
| 1009 | }; |
| 1010 | let mvv = |r: usize| (m.mv[s][r][0], m.mv[s][r][1]); |
| 1011 | let ptype = hdr.picture_type; |
| 1012 | match m.kind { |
| 1013 | MotionKind::Frame => { |
| 1014 | let (x, y) = mvv(0); |
| 1015 | push(Part { dst0: 0, step: 1, rows: 16, src: self.ref_for(ptype, s, None, st, cur), field: None, src_row: (mb_y * 16) as i32, mvx: x, mvy: y, avg: false }); |
| 1016 | } |
| 1017 | MotionKind::FieldInFrame => { |
| 1018 | for (r, &f) in m.sel[s].iter().enumerate() { |
| 1019 | let (x, y) = mvv(r); |
| 1020 | push(Part { dst0: r, step: 2, rows: 8, src: self.ref_for(ptype, s, Some(f), st, cur), field: Some(f), src_row: (mb_y * 8) as i32, mvx: x, mvy: y, avg: false }); |
| 1021 | } |
| 1022 | } |
| 1023 | MotionKind::DualFrame => { |
| 1024 | let (x, y) = mvv(0); |
| 1025 | for p in 0..2usize { |
| 1026 | let mm = if (p == 0) == hdr.top_field_first { 1 } else { 3 }; |
| 1027 | let e = if p == 0 { -1 } else { 1 }; |
| 1028 | let ox = ((x * mm + (x > 0) as i32) >> 1) + m.dmv[0]; |
| 1029 | let oy = ((y * mm + (y > 0) as i32) >> 1) + m.dmv[1] + e; |
| 1030 | let src = self.ref_for(ptype, s, Some(p as u8), st, cur); |
| 1031 | push(Part { dst0: p, step: 2, rows: 8, src, field: Some(p as u8), src_row: (mb_y * 8) as i32, mvx: x, mvy: y, avg: false }); |
| 1032 | push(Part { dst0: p, step: 2, rows: 8, src, field: Some(1 - p as u8), src_row: (mb_y * 8) as i32, mvx: ox, mvy: oy, avg: true }); |
| 1033 | } |
| 1034 | } |
| 1035 | MotionKind::Field16 => { |
| 1036 | let (x, y) = mvv(0); |
| 1037 | let f = m.sel[s][0]; |
| 1038 | push(Part { dst0: 0, step: 1, rows: 16, src: self.ref_for(ptype, s, Some(f), st, cur), field: Some(f), src_row: (mb_y * 16) as i32, mvx: x, mvy: y, avg: false }); |
| 1039 | } |
| 1040 | MotionKind::Mv16x8 => { |
| 1041 | for (r, &f) in m.sel[s].iter().enumerate() { |
| 1042 | let (x, y) = mvv(r); |
| 1043 | push(Part { dst0: 8 * r, step: 1, rows: 8, src: self.ref_for(ptype, s, Some(f), st, cur), field: Some(f), src_row: (mb_y * 16 + 8 * r) as i32, mvx: x, mvy: y, avg: false }); |
| 1044 | } |
| 1045 | } |
| 1046 | MotionKind::DualField => { |
| 1047 | let (x, y) = mvv(0); |
| 1048 | let p = st.parity as u8; |
| 1049 | let e = if p == 0 { -1 } else { 1 }; |
| 1050 | let ox = ((x + (x > 0) as i32) >> 1) + m.dmv[0]; |
| 1051 | let oy = ((y + (y > 0) as i32) >> 1) + m.dmv[1] + e; |
| 1052 | let src_same = self.ref_for(ptype, s, Some(p), st, cur); |
| 1053 | let src_opp = self.ref_for(ptype, s, Some(1 - p), st, cur); |
| 1054 | push(Part { dst0: 0, step: 1, rows: 16, src: src_same, field: Some(p), src_row: (mb_y * 16) as i32, mvx: x, mvy: y, avg: false }); |
| 1055 | push(Part { dst0: 0, step: 1, rows: 16, src: src_opp, field: Some(1 - p), src_row: (mb_y * 16) as i32, mvx: ox, mvy: oy, avg: true }); |
| 1056 | } |
| 1057 | } |
| 1058 | for part in parts.iter().take(np).flatten() { |
| 1059 | let pic = &self.pool[part.src]; |
| 1060 | for c in 0..3 { |
| 1061 | let (csx, csy) = if c == 0 { (0, 0) } else { (sx, sy) }; |
| 1062 | let w = 16 >> csx; |
| 1063 | let rows = part.rows >> csy; |
| 1064 | let (cmx, cmy) = ( |
| 1065 | if csx == 1 { part.mvx / 2 } else { part.mvx }, |
| 1066 | if csy == 1 { part.mvy / 2 } else { part.mvy }, |
| 1067 | ); |
| 1068 | let x = (mb_x * w) as i32 + (cmx >> 1); |
| 1069 | let y = (part.src_row >> csy) + (cmy >> 1); |
| 1070 | let height = pic.height[c]; |
| 1071 | let img = Image { |
| 1072 | data: &pic.planes[c], |
| 1073 | stride: pic.stride[c], |
| 1074 | w: pic.stride[c], |
| 1075 | h: if part.field.is_some() { height / 2 } else { height }, |
| 1076 | field: part.field, |
| 1077 | }; |
| 1078 | let dst0 = if part.step == 2 { part.dst0 } else { part.dst0 >> csy }; |
| 1079 | predict(&img, x, y, cmx & 1 != 0, cmy & 1 != 0, w, rows, &mut pred[c], dst0, part.step, part.avg || dirs_done > 0); |
| 1080 | } |
| 1081 | } |
| 1082 | dirs_done += 1; |
| 1083 | } |
| 1084 | } |
| 1085 | |
| 1086 | /// Reconstruct one macroblock into the current picture. |
| 1087 | #[allow(clippy::too_many_arguments)] |
| 1088 | fn recon_mb( |
| 1089 | &mut self, |
| 1090 | seq: &SequenceInfo, |
| 1091 | hdr: &PictureHeader, |
| 1092 | st: &PicState, |
| 1093 | cur: usize, |
| 1094 | mb_x: usize, |
| 1095 | mb_y: usize, |
| 1096 | info: &MbInfo, |
| 1097 | blocks: &mut [[i16; 64]; 8], |
| 1098 | ) { |
| 1099 | let (sx, sy) = chroma_shift(seq.chroma_format); |
| 1100 | let field_pic = hdr.structure != Structure::Frame; |
| 1101 | let mut pred = [[0u8; 256]; 3]; |
| 1102 | if !info.intra { |
| 1103 | self.build_pred(&mut pred, seq, hdr, st, cur, mb_x, mb_y, &info.m); |
| 1104 | } |
| 1105 | let nblocks = if seq.chroma_format == 1 { 6 } else { 8 }; |
| 1106 | let pic = &mut self.pool[cur]; |
| 1107 | let mut origin = [0usize; 3]; |
| 1108 | let mut ls = [0usize; 3]; |
| 1109 | for c in 0..3 { |
| 1110 | let (w, h) = if c == 0 { (16, 16) } else { (16 >> sx, 16 >> sy) }; |
| 1111 | let stride = pic.stride[c]; |
| 1112 | if field_pic { |
| 1113 | ls[c] = 2 * stride; |
| 1114 | origin[c] = (mb_y * h * 2 + st.parity) * stride + mb_x * w; |
| 1115 | } else { |
| 1116 | ls[c] = stride; |
| 1117 | origin[c] = mb_y * h * stride + mb_x * w; |
| 1118 | } |
| 1119 | if !info.intra { |
| 1120 | let plane = &mut pic.planes[c]; |
| 1121 | for r in 0..h { |
| 1122 | let o = origin[c] + r * ls[c]; |
| 1123 | plane[o..o + w].copy_from_slice(&pred[c][r * 16..r * 16 + w]); |
| 1124 | } |
| 1125 | } |
| 1126 | } |
| 1127 | let dct_field = info.dct_field; |
| 1128 | for i in 0..nblocks { |
| 1129 | if info.cbp & (1 << (nblocks - 1 - i)) == 0 { |
| 1130 | continue; |
| 1131 | } |
| 1132 | let (c, off, bs) = if i < 4 { |
| 1133 | if dct_field { |
| 1134 | (0, origin[0] + (i >> 1) * ls[0] + (i & 1) * 8, 2 * ls[0]) |
| 1135 | } else { |
| 1136 | (0, origin[0] + (i >> 1) * 8 * ls[0] + (i & 1) * 8, ls[0]) |
| 1137 | } |
| 1138 | } else { |
| 1139 | let c = 1 + (i & 1); |
| 1140 | if seq.chroma_format == 1 { |
| 1141 | (c, origin[c], ls[c]) |
| 1142 | } else { |
| 1143 | let lower = (i >= 6) as usize; |
| 1144 | if dct_field { |
| 1145 | (c, origin[c] + lower * ls[c], 2 * ls[c]) |
| 1146 | } else { |
| 1147 | (c, origin[c] + lower * 8 * ls[c], ls[c]) |
| 1148 | } |
| 1149 | } |
| 1150 | }; |
| 1151 | let dst = &mut pic.planes[c][off..]; |
| 1152 | let blk = &mut blocks[i]; |
| 1153 | if info.last[i] == 0 { |
| 1154 | let dc = blk[0]; |
| 1155 | if info.intra { |
| 1156 | idct_put_dc(dc, dst, bs); |
| 1157 | } else { |
| 1158 | idct_add_dc(dc, dst, bs); |
| 1159 | } |
| 1160 | } else if info.intra { |
| 1161 | idct_put(blk, dst, bs); |
| 1162 | } else { |
| 1163 | idct_add(blk, dst, bs); |
| 1164 | } |
| 1165 | *blk = [0; 64]; |
| 1166 | } |
| 1167 | } |
| 1168 | } |
| 1169 | |
| 1170 | #[derive(Clone, Copy)] |
| 1171 | struct Part { |
| 1172 | dst0: usize, |
| 1173 | step: usize, |
| 1174 | rows: usize, |
| 1175 | src: usize, |
| 1176 | field: Option<u8>, |
| 1177 | src_row: i32, |
| 1178 | mvx: i32, |
| 1179 | mvy: i32, |
| 1180 | avg: bool, |
| 1181 | } |
| 1182 | |
| 1183 | fn decode_component(b: &mut Bits, t: &Tables, f_code: u8, pred: i32) -> Option<i32> { |
| 1184 | if f_code == 0 || f_code > 9 { |
| 1185 | return None; |
| 1186 | } |
| 1187 | let code = b.vlc(&t.motion)? as i32; |
| 1188 | if code == 0 { |
| 1189 | // ffmpeg returns the prediction unchanged (no range wrap) on a zero delta |
| 1190 | return Some(pred); |
| 1191 | } |
| 1192 | let r_size = (f_code - 1) as u32; |
| 1193 | let mut delta = 0; |
| 1194 | if code != 0 { |
| 1195 | let neg = b.read1(); |
| 1196 | let res = if r_size > 0 { b.read(r_size) as i32 } else { 0 }; |
| 1197 | delta = ((code - 1) << r_size) + res + 1; |
| 1198 | if neg { |
| 1199 | delta = -delta; |
| 1200 | } |
| 1201 | } |
| 1202 | let f = 1i32 << r_size; |
| 1203 | let (lo, range) = (-16 * f, 32 * f); |
| 1204 | // Full modulo wrap (as ffmpeg's sign_extend): the prediction can lie |
| 1205 | // outside the range after a field vector was stored doubled. |
| 1206 | let v = (pred + delta - lo).rem_euclid(range) + lo; |
| 1207 | Some(v) |
| 1208 | } |
| 1209 | |
| 1210 | fn read_motion( |
| 1211 | b: &mut Bits, |
| 1212 | t: &Tables, |
| 1213 | hdr: &PictureHeader, |
| 1214 | mpeg1: bool, |
| 1215 | m: &mut Motion, |
| 1216 | pmv: &mut [[[i32; 2]; 2]; 2], |
| 1217 | s: usize, |
| 1218 | ) -> std::result::Result<(), SliceError> { |
| 1219 | let field_pic = hdr.structure != Structure::Frame; |
| 1220 | let dual = matches!(m.kind, MotionKind::DualFrame | MotionKind::DualField); |
| 1221 | let field_fmt = field_pic || m.kind != MotionKind::Frame; |
| 1222 | let frame_field = !field_pic && field_fmt; |
| 1223 | let n = if matches!(m.kind, MotionKind::FieldInFrame | MotionKind::Mv16x8) { 2 } else { 1 }; |
| 1224 | let shift = if mpeg1 && hdr.full_pel[s] { 1 } else { 0 }; |
| 1225 | for r in 0..n { |
| 1226 | if field_fmt && !dual { |
| 1227 | m.sel[s][r] = b.read1() as u8; |
| 1228 | } |
| 1229 | for tc in 0..2 { |
| 1230 | let mut pred = pmv[r][s][tc]; |
| 1231 | if tc == 1 && frame_field { |
| 1232 | pred >>= 1; |
| 1233 | } |
| 1234 | let v = decode_component(b, t, hdr.f_code[s][tc], pred).ok_or(SliceError::Bitstream)?; |
| 1235 | pmv[r][s][tc] = if tc == 1 && frame_field { v << 1 } else { v }; |
| 1236 | m.mv[s][r][tc] = v << shift; |
| 1237 | if dual { |
| 1238 | m.dmv[tc] = if b.read1() { 1 - 2 * (b.read1() as i32) } else { 0 }; |
| 1239 | } |
| 1240 | } |
| 1241 | } |
| 1242 | if n == 1 { |
| 1243 | pmv[1][s] = pmv[0][s]; |
| 1244 | m.mv[s][1] = m.mv[s][0]; |
| 1245 | m.sel[s][1] = m.sel[s][0]; |
| 1246 | } |
| 1247 | if b.overrun() { Err(SliceError::Bitstream) } else { Ok(()) } |
| 1248 | } |
| 1249 | |
| 1250 | #[allow(clippy::too_many_arguments)] |
| 1251 | fn conceal_mb( |
| 1252 | pool: &mut [Pic], |
| 1253 | cur: usize, |
| 1254 | refidx: Option<usize>, |
| 1255 | structure: Structure, |
| 1256 | parity: usize, |
| 1257 | mb_x: usize, |
| 1258 | mb_y: usize, |
| 1259 | sx: usize, |
| 1260 | sy: usize, |
| 1261 | ) { |
| 1262 | let field_pic = structure != Structure::Frame; |
| 1263 | for c in 0..3 { |
| 1264 | let (w, h) = if c == 0 { (16, 16) } else { (16 >> sx, 16 >> sy) }; |
| 1265 | let stride = pool[cur].stride[c]; |
| 1266 | for r in 0..h { |
| 1267 | let line = if field_pic { (mb_y * h + r) * 2 + parity } else { mb_y * h + r }; |
| 1268 | let o = line * stride + mb_x * w; |
| 1269 | // Corrupt streams can address rows past the picture (field/odd-height cases). |
| 1270 | if pool[cur].planes[c].len() < o + w { |
| 1271 | continue; |
| 1272 | } |
| 1273 | match refidx { |
| 1274 | Some(ri) if ri != cur => { |
| 1275 | let (a, bsl) = if ri < cur { |
| 1276 | let (l, rr) = pool.split_at_mut(cur); |
| 1277 | (&l[ri].planes[c], &mut rr[0].planes[c]) |
| 1278 | } else { |
| 1279 | let (l, rr) = pool.split_at_mut(ri); |
| 1280 | (&rr[0].planes[c], &mut l[cur].planes[c]) |
| 1281 | }; |
| 1282 | if a.len() >= o + w { |
| 1283 | bsl[o..o + w].copy_from_slice(&a[o..o + w]); |
| 1284 | } |
| 1285 | } |
| 1286 | _ => pool[cur].planes[c][o..o + w].fill(128), |
| 1287 | } |
| 1288 | } |
| 1289 | } |
| 1290 | } |
| 1291 | |
| 1292 | fn chroma_shift(cf: u8) -> (usize, usize) { |
| 1293 | match cf { |
| 1294 | 1 => (1, 1), |
| 1295 | 2 => (1, 0), |
| 1296 | _ => (0, 0), |
| 1297 | } |
| 1298 | } |