oxedyne/fe2o3/fe2o3_graphics/src/h264/mod.rs
42.7 KiB, 117 runs
created by r1870400018:21078, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! An H.264 decoder, for the first frame of a film. |
| 2 | //! |
| 3 | //! A photograph library that holds films has to draw something for each of them, and the something |
| 4 | //! is the first frame. Getting it means decoding H.264 (ITU-T H.264 | ISO/IEC 14496-10), because |
| 5 | //! there is no thumbnail in the file to read instead. This module is that decoder. It is built for |
| 6 | //! **intra** coding only: the first coded picture of every film is an IDR, an IDR refers to nothing |
| 7 | //! but itself, and so everything about motion, reference pictures and prediction between frames is |
| 8 | //! absent by construction rather than unimplemented. |
| 9 | //! |
| 10 | //! # What the films in one real library actually are |
| 11 | //! |
| 12 | //! Every film in a family library was measured before any of this was designed: 7,242 files, 6,036 |
| 13 | //! named `.mp4` and 1,206 named `.mov`. The `avcC` or `hvcC` record of each was read out of its |
| 14 | //! sample description and its parameter sets parsed. They are not one thing: |
| 15 | //! |
| 16 | //! | Codec | Films | |
| 17 | //! |---|---| |
| 18 | //! | HEVC (H.265) | 5,385 | |
| 19 | //! | **H.264** | **1,658** | |
| 20 | //! | Motion JPEG | 196 | |
| 21 | //! | MPEG-4 Part 2 | 2 | |
| 22 | //! |
| 23 | //! Of the 1,658 that are H.264, the split that shapes this module is the **entropy coder**, and it |
| 24 | //! is the measurement that mattered most: |
| 25 | //! |
| 26 | //! | Profile | Films | Entropy coder | 8x8 transform | |
| 27 | //! |---|---|---|---| |
| 28 | //! | Baseline (66) | 711 | CAVLC | no | |
| 29 | //! | Main (77) | 86 | CABAC | no | |
| 30 | //! | High (100) | 861 | CABAC | yes | |
| 31 | //! |
| 32 | //! **947 films are CABAC and 711 are CAVLC.** H.264 has two entropy coders where HEVC has one, and |
| 33 | //! neither of these is the rare case: a decoder that implements only the arithmetic coder, on the |
| 34 | //! reasoning that HEVC has no other, would refuse two films in every five. Both are needed, and |
| 35 | //! they share nothing but the syntax elements they code -- CAVLC is a set of published |
| 36 | //! variable-length code tables read with a bit reader, CABAC is an adaptive arithmetic decoder. |
| 37 | //! That is the equivalent here of the wavefront discovery in [`crate::hevc`], and it doubles the |
| 38 | //! entropy layer rather than widening it. |
| 39 | //! |
| 40 | //! Everything else about the corpus is uniform, and each of these is asserted where it is read |
| 41 | //! rather than assumed: |
| 42 | //! |
| 43 | //! - **Eight bits**, luma and chroma alike, in all 1,658. |
| 44 | //! - **4:2:0** (`chroma_format_idc` of 1) in all 1,658. |
| 45 | //! - **Frames, never fields**: `frame_mbs_only_flag` is 1 in all 1,658, so there is no field |
| 46 | //! coding and no macroblock-adaptive frame/field coding anywhere in the library. |
| 47 | //! - **One slice group** in all 1,658, so no slice-group map and no macroblock-to-slice-group |
| 48 | //! indirection. |
| 49 | //! - `constrained_intra_pred_flag` **off** in all 1,658, which for an all-intra picture changes |
| 50 | //! nothing but is checked because it would if a P slice ever arrived. |
| 51 | //! - **Four-byte NAL length prefixes** (`lengthSizeMinusOne` of 3) in all 1,658. |
| 52 | //! - **Scaling lists**: 1,625 films carry none at all, 24 carry sequence-level lists and 9 carry |
| 53 | //! picture-level lists. Absent is the common case but not the only one, and the fall-back rules |
| 54 | //! of Table 7-2 mean "not present" does not mean "flat" -- it means "inherit", and at the head of |
| 55 | //! each fall-back chain it means the *default* matrices of Tables 7-3 and 7-4, which are not |
| 56 | //! flat. A decoder that reads absence as no scaling quantises every block of those 33 films |
| 57 | //! wrongly and produces pictures that are recognisable and wrong. |
| 58 | //! |
| 59 | //! And the first coded picture of every one of the 1,658 was extracted and its NAL units read: |
| 60 | //! **every one is an IDR carrying I slices only**. Most are one slice -- 1,566 of them -- but 83 |
| 61 | //! carry two and 9 carry eight, so slices are not a formality: each restarts the entropy coder, and |
| 62 | //! a macroblock in another slice is unavailable for prediction however close it sits. |
| 63 | //! |
| 64 | //! Resolutions run 1920x1088 (669 films), 1280x720 (462), 640x480 (103), 1088x1920 (96), 720x480 |
| 65 | //! (85), 848x480 (77), down a tail to 176x144 (21), with 9 at 3840x2160. |
| 66 | //! |
| 67 | //! # What is decoded, and what is not |
| 68 | //! |
| 69 | //! **Both entropy coders are complete and verified.** The container reading, the parameter sets, the |
| 70 | //! slice headers, both entropy layers, the macroblock layer, all four families of intra prediction, |
| 71 | //! all four inverse transforms and the deblocking filter are here. Every one of the 1,658 H.264 |
| 72 | //! films in the library decodes to a picture identical to FFmpeg's own, luma and chroma, every |
| 73 | //! sample: 711 coded with the variable-length coder and 947 with the arithmetic one. |
| 74 | //! |
| 75 | //! Everything below the entropy layer -- prediction, transforms, the deblocking filter, the |
| 76 | //! macroblock walk -- is shared between the two, so what [`cabac`] adds is the arithmetic decoder |
| 77 | //! itself, its context variables, and the binarisation of each syntax element: clause 9.3 and the |
| 78 | //! I-slice column of Tables 9-12 to 9-24. |
| 79 | //! |
| 80 | //! Its dangerous part is those tables: 261 pairs of signed numbers for an intra 4:2:0 slice, each of |
| 81 | //! which **produces a picture rather than an error if it is wrong**, since the decoder stays in step |
| 82 | //! with the encoder and hands back samples that look decoded. They are transcribed by hand and then |
| 83 | //! held to the specification's own text entry by entry, which is the check that would catch a |
| 84 | //! misread; the count of rows a table gives up is what catches a value the text rendering dropped. |
| 85 | //! |
| 86 | //! Two things a picture that is nearly right will not tell you, and both are asserted instead. The |
| 87 | //! slices of a picture **tile** it, so a macroblock left undecoded means the coder lost the |
| 88 | //! bitstream -- which is the only outward sign it gives, because a desynchronised arithmetic decoder |
| 89 | //! goes on answering bins for as long as it is asked. And the six families of residual block must |
| 90 | //! not share a context variable, which an offset one place out would quietly arrange. |
| 91 | //! |
| 92 | //! # What a caller gets, and what it still has to do |
| 93 | //! |
| 94 | //! [`decode::picture`] hands back three planes of eight-bit samples, cropped to the size the |
| 95 | //! sequence parameter set says the picture is meant to be shown at. Two things remain the caller's: |
| 96 | //! |
| 97 | //! - **Turning it into something to look at.** The conversion out of 4:2:0 and out of the studio |
| 98 | //! range lives in [`crate::hevc::colour`], and is the same arithmetic for both codecs; it takes |
| 99 | //! that module's own picture type, so the two should be one type rather than two. They are not |
| 100 | //! yet, and until they are a caller must copy the planes across. |
| 101 | //! - **Turning it the right way up.** A phone writes the angle it was held at into the track |
| 102 | //! header rather than into the samples, and [`crate::mp4::Film::rotation`] reports it. A decoder |
| 103 | //! produces the picture as it was coded; nothing in a coded picture says which way is up. Two |
| 104 | //! further things a container may ask for and a coded picture knows nothing of are a clean |
| 105 | //! aperture, which crops the picture again beyond the sequence parameter set's own window, and a |
| 106 | //! presentation order that differs from the coded one -- nine films in the corpus show a |
| 107 | //! bidirectionally predicted picture *before* the first intra one, so "the opening frame" and |
| 108 | //! "the first sync sample" are two different pictures. |
| 109 | //! |
| 110 | //! # References |
| 111 | //! |
| 112 | //! Rec. ITU-T H.264 (08/2021). The NAL unit header is §7.3.1, the sequence parameter set §7.3.2.1.1, |
| 113 | //! the picture parameter set §7.3.2.2, the slice header §7.3.3, the macroblock layer §7.3.5, CAVLC |
| 114 | //! §9.2 and CABAC §9.3. The `avcC` record the parameter sets arrive in is ISO/IEC 14496-15 §5.3.3.1. |
| 115 | //! Every constant below names the clause it comes from, and the tests read the tables back out of a |
| 116 | //! text rendering of the specification where `H264_SPEC_TEXT` points at one. |
| 117 | //! |
| 118 | //! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\ |
| 119 | //! Anthropic Claude |
| 120 | |
| 121 | pub mod cabac; |
| 122 | pub mod cavlc; |
| 123 | pub mod decode; |
| 124 | pub mod filter; |
| 125 | pub mod intra; |
| 126 | pub mod transform; |
| 127 | |
| 128 | use oxedyne_fe2o3_core::prelude::*; |
| 129 | |
| 130 | // The largest picture this decoder will describe, in luma samples each way. Sixteen thousand is |
| 131 | // past every camera and well inside what the level limits allow; it is a ceiling against a |
| 132 | // parameter set that is a mistake, not a limit on real films. |
| 133 | pub const MAX_SIDE: u32 = 16_384; |
| 134 | |
| 135 | /// NAL unit types this decoder cares about (Table 7-1). |
| 136 | pub mod nal { |
| 137 | pub const SLICE: u8 = 1; // a coded slice of a picture that is not an IDR |
| 138 | pub const IDR: u8 = 5; // a coded slice of an IDR picture, the first frame of a film |
| 139 | pub const SEI: u8 = 6; // supplemental enhancement information, which changes no sample |
| 140 | pub const SPS: u8 = 7; |
| 141 | pub const PPS: u8 = 8; |
| 142 | pub const AUD: u8 = 9; // an access unit delimiter |
| 143 | pub const PREFIX: u8 = 14; // precedes a slice in a scalable stream |
| 144 | pub const SUBSET_SPS: u8 = 15; // for a scalable or multiview layer this decoder ignores |
| 145 | } |
| 146 | |
| 147 | /// One NAL unit: what it is, and its payload with the emulation prevention undone. |
| 148 | #[derive(Clone, Debug)] |
| 149 | pub struct Unit { |
| 150 | pub kind: u8, // the type, from the low five bits of the NAL unit header (§7.3.1) |
| 151 | pub ref_idc: u8, // nal_ref_idc: nought where nothing refers to this unit |
| 152 | pub body: Vec<u8>, // after the header, every emulation prevention byte removed |
| 153 | } |
| 154 | |
| 155 | /// Which kind of slice this is (§7.4.3, Table 7-6). |
| 156 | /// |
| 157 | /// The values run 0 to 9, where 5 to 9 repeat 0 to 4 with the added meaning that every slice of the |
| 158 | /// picture is of that type. Only the intra ones are decoded here; the rest are named so that a |
| 159 | /// refusal can say what it met. |
| 160 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 161 | pub enum SliceType { |
| 162 | P, // predicted from one earlier picture |
| 163 | B, // predicted from two |
| 164 | I, // intra: predicted only from this picture |
| 165 | Sp, // a switching P slice |
| 166 | Si, // a switching I slice |
| 167 | } |
| 168 | |
| 169 | impl SliceType { |
| 170 | |
| 171 | /// The type a `slice_type` codes, whichever of its two values it uses. |
| 172 | pub fn of(code: u32) -> Outcome<Self> { |
| 173 | Ok(match code % 5 { |
| 174 | 0 => Self::P, |
| 175 | 1 => Self::B, |
| 176 | 2 => Self::I, |
| 177 | 3 => Self::Sp, |
| 178 | 4 => Self::Si, |
| 179 | _ => return Err(err!( |
| 180 | "A slice_type of {} is outside the 0 to 9 the syntax allows.", code; |
| 181 | Invalid, Input, Decode)), |
| 182 | }) |
| 183 | } |
| 184 | |
| 185 | /// Is every macroblock of the slice coded without reference to another picture? |
| 186 | pub fn is_intra(self) -> bool { |
| 187 | matches!(self, Self::I | Self::Si) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | /// What a sequence parameter set says about the pictures that follow it (§7.3.2.1.1). |
| 192 | /// |
| 193 | /// Only the fields a still frame's decoder acts on are kept, plus the few that must be read to know |
| 194 | /// where the next field begins. A parameter set is a run of variable-length codes and there is no |
| 195 | /// skipping to a field without decoding everything in front of it. |
| 196 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 197 | pub struct Sps { |
| 198 | pub id: u8, // which set this is, as a picture parameter set names it |
| 199 | pub profile: u8, // profile_idc |
| 200 | pub level: u8, // level_idc |
| 201 | pub chroma: u8, // 0 monochrome, 1 for 4:2:0, 2 for 4:2:2, 3 for 4:4:4 |
| 202 | pub separate_planes: bool, // the three planes coded as separate monochrome pictures |
| 203 | pub luma_bits: u8, // bits a luma sample |
| 204 | pub chroma_bits: u8, // bits a chroma sample |
| 205 | pub qpprime_bypass: bool, // a lossless macroblock skips the transform at qp nought |
| 206 | pub mbs_w: u32, // the picture's width in macroblocks |
| 207 | pub map_units_h: u32, // height in map units, macroblock rows for a frame stream |
| 208 | pub frame_mbs_only: bool, // is every picture a frame rather than a field? |
| 209 | pub mbaff: bool, // may a macroblock pair be coded as two fields? |
| 210 | pub frame_num_bits: u32, // bits frame_num occupies in a slice header |
| 211 | pub poc_type: u32, // which of the three picture order count schemes is in use |
| 212 | pub poc_lsb_bits: u32, // bits the count's low half occupies, where it has one |
| 213 | pub delta_poc_always_zero: bool, // are the deltas all nought, under scheme one? |
| 214 | pub crop: [u32; 4], // left, right, top, bottom, in the units §7.4.2.1.1 counts |
| 215 | pub scaling: Option<Scaling>, // the scaling lists this sequence carries, if any |
| 216 | pub coded_w: u32, // coded width in luma samples, before cropping |
| 217 | pub coded_h: u32, // and coded height |
| 218 | pub width: u32, // the width the picture is meant to be shown at |
| 219 | pub height: u32, // and the height as shown |
| 220 | } |
| 221 | |
| 222 | /// What a picture parameter set says about the slices that reference it (§7.3.2.2). |
| 223 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 224 | pub struct Pps { |
| 225 | pub id: u8, // which set this is, as a slice header names it |
| 226 | pub sps_id: u8, // which sequence parameter set it belongs to |
| 227 | pub cabac: bool, // the arithmetic coder rather than the length tables |
| 228 | pub bottom_field_order: bool, // a slice header carries a second order count delta |
| 229 | pub slice_groups: u32, // how many slice groups the picture is cut into |
| 230 | pub init_qp: i32, // already offset by the 26 the syntax subtracts |
| 231 | pub cb_qp_offset: i32, // luma quantisation parameter to the Cb one |
| 232 | pub cr_qp_offset: i32, // the same for Cr, defaulting to the Cb one |
| 233 | pub deblocking_control: bool, // a slice header carries its own deblocking settings |
| 234 | pub constrained_intra: bool, // may an intra macroblock predict from an inter one? |
| 235 | pub redundant_pic_cnt: bool, // a slice header carries a redundant picture count |
| 236 | pub transform_8x8: bool, // may a macroblock use the eight-by-eight transform? |
| 237 | pub scaling: Option<Scaling>, // the scaling lists this picture carries, if any |
| 238 | } |
| 239 | |
| 240 | /// What one slice header says (§7.3.3). |
| 241 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 242 | pub struct Slice { |
| 243 | pub first_mb: u32, // the first macroblock this slice codes, in raster order |
| 244 | pub kind: SliceType, |
| 245 | pub all_same: bool, // every slice of the picture is of that kind |
| 246 | pub pps_id: u8, // which picture parameter set it references |
| 247 | pub idr: bool, // does this slice belong to an IDR picture? |
| 248 | pub qp: i32, // where the slice starts, already summed with the set's |
| 249 | pub deblocking: u32, // 0 on, 1 off, 2 off across slice edges |
| 250 | pub alpha_offset: i32, // added to the deblocking filter's first threshold |
| 251 | pub beta_offset: i32, // and to its second |
| 252 | pub cabac_init_idc: u32, // which table a non-intra slice's coder starts from |
| 253 | pub data_bit: usize, // where the entropy-coded data begins, bits into the payload |
| 254 | } |
| 255 | |
| 256 | /// A set of quantisation weights (§7.4.2.1.1.1, §8.5.9). |
| 257 | /// |
| 258 | /// Six four-by-four lists and six eight-by-eight ones, each held **in the order the syntax codes |
| 259 | /// them**, which is the inverse scanning order rather than raster. They are inverse-scanned into a |
| 260 | /// weight matrix where they are used, in [`transform`]. |
| 261 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 262 | pub struct Scaling { |
| 263 | pub l4: [[u8; 16]; 6], // ScalingList4x4[0..6], intra then inter Y, Cb, Cr |
| 264 | pub l8: [[u8; 64]; 6], // ScalingList8x8[0..6], the same order |
| 265 | } |
| 266 | |
| 267 | // The default four-by-four weights for an intra macroblock (Table 7-3). |
| 268 | pub const DEFAULT_4X4_INTRA: [u8; 16] = [ |
| 269 | 6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42, |
| 270 | ]; |
| 271 | |
| 272 | // The default four-by-four weights for an inter macroblock (Table 7-3). |
| 273 | pub const DEFAULT_4X4_INTER: [u8; 16] = [ |
| 274 | 10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34, |
| 275 | ]; |
| 276 | |
| 277 | // The default eight-by-eight weights for an intra macroblock (Table 7-4). |
| 278 | pub const DEFAULT_8X8_INTRA: [u8; 64] = [ |
| 279 | 6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18, 18, 18, 18, 23, |
| 280 | 23, 23, 23, 23, 23, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, |
| 281 | 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31, |
| 282 | 31, 33, 33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42, |
| 283 | ]; |
| 284 | |
| 285 | // The default eight-by-eight weights for an inter macroblock (Table 7-4). |
| 286 | pub const DEFAULT_8X8_INTER: [u8; 64] = [ |
| 287 | 9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19, 19, 19, 19, 21, |
| 288 | 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 24, 24, 24, 24, |
| 289 | 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27, |
| 290 | 27, 28, 28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35, |
| 291 | ]; |
| 292 | |
| 293 | impl Scaling { |
| 294 | |
| 295 | /// Flat weights, which is what a stream carrying no lists at all quantises against. |
| 296 | pub fn flat() -> Self { |
| 297 | Self { l4: [[16u8; 16]; 6], l8: [[16u8; 64]; 6] } |
| 298 | } |
| 299 | |
| 300 | /// The weights a sequence or picture parameter set codes (§7.4.2.1.1.1, Table 7-2). |
| 301 | /// |
| 302 | /// `fallback_a` chooses between the two fall-back rules: rule A is what a *sequence* parameter |
| 303 | /// set uses, and what a picture parameter set uses when its sequence carried no lists; rule B is |
| 304 | /// what a picture parameter set uses when its sequence did carry them, and inherits from the |
| 305 | /// sequence rather than from the defaults. |
| 306 | /// |
| 307 | /// **Not present does not mean flat.** At the head of each fall-back chain -- lists 0, 3, 6 and |
| 308 | /// 7 -- an absent list means the *default* matrix of Table 7-3 or 7-4, which is not flat; |
| 309 | /// elsewhere it means the list before it in the chain. Reading absence as no scaling produces a |
| 310 | /// picture that is recognisable and wrong. |
| 311 | fn read(b: &mut Bits, count: usize, prev: Option<&Scaling>, fallback_a: bool) -> Outcome<Self> { |
| 312 | let mut out = match (fallback_a, prev) { |
| 313 | (false, Some(p)) => p.clone(), |
| 314 | _ => Self::flat(), |
| 315 | }; |
| 316 | // Where a list is absent, what it falls back to. |
| 317 | for i in 0..count { |
| 318 | let present = res!(b.flag()); |
| 319 | if i < 6 { |
| 320 | let mut list = [0u8; 16]; |
| 321 | let mut default = false; |
| 322 | if present { |
| 323 | default = res!(read_list(b, &mut list)); |
| 324 | } |
| 325 | out.l4[i] = if !present { |
| 326 | match (i, fallback_a, prev) { |
| 327 | // The head of a chain, falling back on the defaults. |
| 328 | (0, _, _) => DEFAULT_4X4_INTRA, |
| 329 | (3, _, _) => DEFAULT_4X4_INTER, |
| 330 | // A picture set whose sequence carried lists inherits them. |
| 331 | (_, false, Some(p)) => p.l4[i], |
| 332 | // Otherwise the list before it in the chain. |
| 333 | _ => out.l4[i - 1], |
| 334 | } |
| 335 | } else if default { |
| 336 | if i < 3 { DEFAULT_4X4_INTRA } else { DEFAULT_4X4_INTER } |
| 337 | } else { |
| 338 | list |
| 339 | }; |
| 340 | } else { |
| 341 | let j = i - 6; |
| 342 | let mut list = [0u8; 64]; |
| 343 | let mut default = false; |
| 344 | if present { |
| 345 | default = res!(read_list(b, &mut list)); |
| 346 | } |
| 347 | out.l8[j] = if !present { |
| 348 | match (j, fallback_a, prev) { |
| 349 | (0, _, _) => DEFAULT_8X8_INTRA, |
| 350 | (1, _, _) => DEFAULT_8X8_INTER, |
| 351 | (_, false, Some(p)) => p.l8[j], |
| 352 | // The eight-by-eight chain steps two at a time, since the lists alternate |
| 353 | // intra and inter by colour component. |
| 354 | _ => out.l8[j - 2], |
| 355 | } |
| 356 | } else if default { |
| 357 | if j % 2 == 0 { DEFAULT_8X8_INTRA } else { DEFAULT_8X8_INTER } |
| 358 | } else { |
| 359 | list |
| 360 | }; |
| 361 | } |
| 362 | } |
| 363 | Ok(out) |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | /// Reads one scaling list, and says whether it asked for the default matrix (§7.3.2.1.1.1). |
| 368 | /// |
| 369 | /// A first delta that takes the running value to nought is the encoder's way of naming the default |
| 370 | /// matrix without carrying it; a later one means the list stops there and every entry after it |
| 371 | /// repeats the last. |
| 372 | fn read_list(b: &mut Bits, list: &mut [u8]) -> Outcome<bool> { |
| 373 | let mut last = 8i32; |
| 374 | let mut next = 8i32; |
| 375 | let mut default = false; |
| 376 | for j in 0..list.len() { |
| 377 | if next != 0 { |
| 378 | let delta = res!(b.se()); |
| 379 | next = (last + delta + 256).rem_euclid(256); |
| 380 | if j == 0 && next == 0 { |
| 381 | default = true; |
| 382 | } |
| 383 | } |
| 384 | let v = if next == 0 { last } else { next }; |
| 385 | if !(1..=255).contains(&v) { |
| 386 | return Err(err!( |
| 387 | "A scaling list entry of {} was coded, and the weights run from 1 to 255.", v; |
| 388 | Invalid, Input, Decode)); |
| 389 | } |
| 390 | list[j] = v as u8; |
| 391 | last = v; |
| 392 | } |
| 393 | Ok(default) |
| 394 | } |
| 395 | |
| 396 | /// The parameter sets carried in an `avcC` decoder configuration record (ISO/IEC 14496-15 §5.3.3.1). |
| 397 | #[derive(Clone, Debug)] |
| 398 | pub struct Config { |
| 399 | pub length_size: usize, // bytes prefixing each NAL unit in the film's own samples |
| 400 | pub sps: Vec<Unit>, |
| 401 | pub pps: Vec<Unit>, |
| 402 | } |
| 403 | |
| 404 | /// Reads an `avcC` record. |
| 405 | pub fn config(bytes: &[u8]) -> Outcome<Config> { |
| 406 | // version, profile, compatibility, level, then the length size and the parameter set counts. |
| 407 | if bytes.len() < 7 { |
| 408 | return Err(err!( |
| 409 | "An AVC decoder configuration record is {} bytes, and its fixed fields alone are 7.", |
| 410 | bytes.len(); |
| 411 | Invalid, Input, Decode)); |
| 412 | } |
| 413 | if bytes[0] != 1 { |
| 414 | return Err(err!( |
| 415 | "An AVC decoder configuration record of version {}, and this reads version 1.", |
| 416 | bytes[0]; |
| 417 | Invalid, Input, Unknown)); |
| 418 | } |
| 419 | let length_size = (bytes[4] & 0x03) as usize + 1; |
| 420 | if length_size == 3 { |
| 421 | return Err(err!( |
| 422 | "The configuration record names a NAL length of 3 bytes, which ISO/IEC 14496-15 does \ |
| 423 | not allow; it must be 1, 2 or 4."; |
| 424 | Invalid, Input, Decode)); |
| 425 | } |
| 426 | let mut at = 5usize; |
| 427 | let take = |at: &mut usize, count: usize, into: &mut Vec<Unit>| -> Outcome<()> { |
| 428 | for _ in 0..count { |
| 429 | if *at + 2 > bytes.len() { |
| 430 | return Err(err!( |
| 431 | "A configuration record ends inside a parameter set's length."; |
| 432 | Invalid, Input, Decode)); |
| 433 | } |
| 434 | let len = u16::from_be_bytes([bytes[*at], bytes[*at + 1]]) as usize; |
| 435 | *at += 2; |
| 436 | let end = match at.checked_add(len) { |
| 437 | Some(end) if end <= bytes.len() => end, |
| 438 | _ => return Err(err!( |
| 439 | "A parameter set says it is {} bytes and {} remain.", |
| 440 | len, bytes.len() - *at; |
| 441 | Invalid, Input, Decode)), |
| 442 | }; |
| 443 | into.push(res!(unit(&bytes[*at..end]))); |
| 444 | *at = end; |
| 445 | } |
| 446 | Ok(()) |
| 447 | }; |
| 448 | let mut sps = Vec::new(); |
| 449 | let mut pps = Vec::new(); |
| 450 | let n_sps = (bytes[5] & 0x1f) as usize; |
| 451 | at += 1; |
| 452 | res!(take(&mut at, n_sps, &mut sps)); |
| 453 | if at >= bytes.len() { |
| 454 | return Err(err!( |
| 455 | "A configuration record ends before its picture parameter set count."; |
| 456 | Invalid, Input, Decode)); |
| 457 | } |
| 458 | let n_pps = bytes[at] as usize; |
| 459 | at += 1; |
| 460 | res!(take(&mut at, n_pps, &mut pps)); |
| 461 | Ok(Config { length_size, sps, pps }) |
| 462 | } |
| 463 | |
| 464 | /// Splits a byte-stream of length-prefixed NAL units, as a sample carries them. |
| 465 | /// |
| 466 | /// `length_size` comes from the configuration record and is one, two or four. A unit that runs past |
| 467 | /// the end of the buffer is a truncated file and is refused rather than decoded as far as it goes: |
| 468 | /// half a coded picture is not half a picture, it is noise. |
| 469 | pub fn split_lengthed(bytes: &[u8], length_size: usize) -> Outcome<Vec<Unit>> { |
| 470 | if !matches!(length_size, 1 | 2 | 4) { |
| 471 | return Err(err!( |
| 472 | "A NAL unit length is coded in {} bytes, and only one, two and four are legal.", |
| 473 | length_size; |
| 474 | Invalid, Input, Decode)); |
| 475 | } |
| 476 | let mut out = Vec::new(); |
| 477 | let mut at = 0usize; |
| 478 | while at + length_size <= bytes.len() { |
| 479 | let mut len = 0usize; |
| 480 | for i in 0..length_size { |
| 481 | len = (len << 8) | bytes[at + i] as usize; |
| 482 | } |
| 483 | at += length_size; |
| 484 | if len == 0 { |
| 485 | return Err(err!("A NAL unit of no length."; Invalid, Input, Decode)); |
| 486 | } |
| 487 | let end = match at.checked_add(len) { |
| 488 | Some(end) if end <= bytes.len() => end, |
| 489 | _ => return Err(err!( |
| 490 | "A NAL unit says it is {} bytes and {} remain.", len, bytes.len() - at; |
| 491 | Invalid, Input, Decode)), |
| 492 | }; |
| 493 | out.push(res!(unit(&bytes[at..end]))); |
| 494 | at = end; |
| 495 | } |
| 496 | if at != bytes.len() { |
| 497 | return Err(err!( |
| 498 | "{} bytes are left over after the last NAL unit.", bytes.len() - at; |
| 499 | Invalid, Input, Decode)); |
| 500 | } |
| 501 | Ok(out) |
| 502 | } |
| 503 | |
| 504 | /// Splits an Annex B stream, where units are separated by start codes rather than lengths. |
| 505 | pub fn split_annex_b(bytes: &[u8]) -> Outcome<Vec<Unit>> { |
| 506 | let mut starts: Vec<usize> = Vec::new(); |
| 507 | let mut i = 0usize; |
| 508 | while i + 3 <= bytes.len() { |
| 509 | if bytes[i] == 0 && bytes[i + 1] == 0 && bytes[i + 2] == 1 { |
| 510 | starts.push(i + 3); |
| 511 | i += 3; |
| 512 | } else { |
| 513 | i += 1; |
| 514 | } |
| 515 | } |
| 516 | let mut out = Vec::with_capacity(starts.len()); |
| 517 | for (n, from) in starts.iter().enumerate() { |
| 518 | let to = match starts.get(n + 1) { |
| 519 | // Back off the start code of the next unit, and the trailing zero a four-byte start |
| 520 | // code puts in front of it. |
| 521 | Some(next) => { |
| 522 | let mut end = next - 3; |
| 523 | if end > *from && bytes[end - 1] == 0 { |
| 524 | end -= 1; |
| 525 | } |
| 526 | end |
| 527 | }, |
| 528 | None => bytes.len(), |
| 529 | }; |
| 530 | if to > *from { |
| 531 | out.push(res!(unit(&bytes[*from..to]))); |
| 532 | } |
| 533 | } |
| 534 | Ok(out) |
| 535 | } |
| 536 | |
| 537 | /// Reads one NAL unit: its one-byte header, and its payload unescaped (§7.3.1). |
| 538 | pub fn unit(raw: &[u8]) -> Outcome<Unit> { |
| 539 | if raw.len() < 2 { |
| 540 | return Err(err!( |
| 541 | "A NAL unit is {} bytes, and its header alone is one.", raw.len(); |
| 542 | Invalid, Input, Decode)); |
| 543 | } |
| 544 | if raw[0] & 0x80 != 0 { |
| 545 | return Err(err!( |
| 546 | "A NAL unit's forbidden bit is set, so this is not an H.264 stream."; |
| 547 | Invalid, Input, Decode)); |
| 548 | } |
| 549 | Ok(Unit { |
| 550 | ref_idc: (raw[0] >> 5) & 0x03, |
| 551 | kind: raw[0] & 0x1f, |
| 552 | body: rbsp(&raw[1..]), |
| 553 | }) |
| 554 | } |
| 555 | |
| 556 | /// Removes the emulation prevention bytes from a payload (§7.4.1). |
| 557 | /// |
| 558 | /// A `0x03` after two zero bytes is there only to stop the payload looking like a start code, and |
| 559 | /// is not part of the syntax. |
| 560 | pub fn rbsp(nal: &[u8]) -> Vec<u8> { |
| 561 | let mut out = Vec::with_capacity(nal.len()); |
| 562 | let mut zeros = 0usize; |
| 563 | for &b in nal { |
| 564 | if zeros >= 2 && b == 0x03 { |
| 565 | zeros = 0; |
| 566 | continue; |
| 567 | } |
| 568 | out.push(b); |
| 569 | zeros = if b == 0 { zeros + 1 } else { 0 }; |
| 570 | } |
| 571 | out |
| 572 | } |
| 573 | |
| 574 | // ------------------------------------------------------------------------ reading the bits |
| 575 | |
| 576 | /// A reader of the bits of an RBSP, most significant first. |
| 577 | pub struct Bits<'a> { |
| 578 | buf: &'a [u8], |
| 579 | pos: usize, // the next bit, counted from the first bit of the first byte |
| 580 | } |
| 581 | |
| 582 | impl<'a> Bits<'a> { |
| 583 | |
| 584 | pub fn new(buf: &'a [u8]) -> Self { |
| 585 | Self { buf, pos: 0 } |
| 586 | } |
| 587 | |
| 588 | pub fn at(buf: &'a [u8], pos: usize) -> Self { |
| 589 | Self { buf, pos } |
| 590 | } |
| 591 | |
| 592 | pub fn left(&self) -> usize { |
| 593 | (self.buf.len() * 8).saturating_sub(self.pos) |
| 594 | } |
| 595 | |
| 596 | pub fn consumed(&self) -> usize { |
| 597 | self.pos |
| 598 | } |
| 599 | |
| 600 | /// The next `n` bits as an unsigned integer, most significant first. |
| 601 | pub fn u(&mut self, n: usize) -> Outcome<u32> { |
| 602 | if n > 32 { |
| 603 | return Err(err!("A field of {} bits was asked for, and 32 is the widest.", n; Bug)); |
| 604 | } |
| 605 | let mut v = 0u32; |
| 606 | for _ in 0..n { |
| 607 | let byte = self.pos >> 3; |
| 608 | if byte >= self.buf.len() { |
| 609 | return Err(err!( |
| 610 | "The payload ends after {} bits, inside a field.", self.buf.len() * 8; |
| 611 | Invalid, Input, Decode)); |
| 612 | } |
| 613 | let bit = (self.buf[byte] >> (7 - (self.pos & 7))) & 1; |
| 614 | v = (v << 1) | bit as u32; |
| 615 | self.pos += 1; |
| 616 | } |
| 617 | Ok(v) |
| 618 | } |
| 619 | |
| 620 | pub fn flag(&mut self) -> Outcome<bool> { |
| 621 | Ok(res!(self.u(1)) == 1) |
| 622 | } |
| 623 | |
| 624 | /// The next `n` bits without moving on, zero-padded past the end. |
| 625 | /// |
| 626 | /// This is what a variable-length code table is looked up with: the longest code is peeked at |
| 627 | /// whole, matched, and only then are the bits it used given up. |
| 628 | pub fn peek(&self, n: usize) -> u32 { |
| 629 | let mut v = 0u32; |
| 630 | for i in 0..n.min(32) { |
| 631 | let p = self.pos + i; |
| 632 | let byte = p >> 3; |
| 633 | let bit = match self.buf.get(byte) { |
| 634 | Some(b) => (*b >> (7 - (p & 7))) & 1, |
| 635 | None => 0, |
| 636 | }; |
| 637 | v = (v << 1) | bit as u32; |
| 638 | } |
| 639 | v |
| 640 | } |
| 641 | |
| 642 | /// Steps over `n` bits, refusing to step past the end. |
| 643 | pub fn skip(&mut self, n: usize) -> Outcome<()> { |
| 644 | if n > self.left() { |
| 645 | return Err(err!( |
| 646 | "{} bits were stepped over and {} remain.", n, self.left(); |
| 647 | Invalid, Input, Decode)); |
| 648 | } |
| 649 | self.pos += n; |
| 650 | Ok(()) |
| 651 | } |
| 652 | |
| 653 | /// An unsigned Exp-Golomb code, §9.1. |
| 654 | pub fn ue(&mut self) -> Outcome<u32> { |
| 655 | let mut zeros = 0usize; |
| 656 | while res!(self.u(1)) == 0 { |
| 657 | zeros += 1; |
| 658 | if zeros > 31 { |
| 659 | return Err(err!( |
| 660 | "An Exp-Golomb code is prefixed by more than 31 zeroes, which no legal value \ |
| 661 | is."; |
| 662 | Invalid, Input, Decode)); |
| 663 | } |
| 664 | } |
| 665 | if zeros == 0 { |
| 666 | return Ok(0); |
| 667 | } |
| 668 | let rest = res!(self.u(zeros)) as u64; |
| 669 | let v = (1u64 << zeros) - 1 + rest; |
| 670 | if v > u32::MAX as u64 { |
| 671 | return Err(err!( |
| 672 | "An Exp-Golomb code decodes to {}, beyond what any field holds.", v; |
| 673 | Invalid, Input, Decode)); |
| 674 | } |
| 675 | Ok(v as u32) |
| 676 | } |
| 677 | |
| 678 | /// A signed Exp-Golomb code, §9.1.1. |
| 679 | pub fn se(&mut self) -> Outcome<i32> { |
| 680 | let k = res!(self.ue()); |
| 681 | let m = ((k as i64 + 1) / 2) as i32; |
| 682 | Ok(if k % 2 == 1 { m } else { -m }) |
| 683 | } |
| 684 | |
| 685 | /// Does any syntax remain before the trailing bits (§7.2, `more_rbsp_data`)? |
| 686 | /// |
| 687 | /// The payload ends with a one bit and then zeroes to the byte boundary, so what is left is |
| 688 | /// syntax only if there is a set bit somewhere after the current position other than that one. |
| 689 | /// The picture parameter set's last three fields are read or not on this answer alone, and |
| 690 | /// getting it wrong loses the eight-by-eight transform flag on every High profile film. |
| 691 | pub fn more_data(&self) -> bool { |
| 692 | let total = self.buf.len() * 8; |
| 693 | if self.pos >= total { |
| 694 | return false; |
| 695 | } |
| 696 | // The last set bit in the payload is the stop bit. |
| 697 | let mut last = total; |
| 698 | while last > 0 { |
| 699 | let p = last - 1; |
| 700 | let byte = p >> 3; |
| 701 | let bit = match self.buf.get(byte) { |
| 702 | Some(b) => (*b >> (7 - (p & 7))) & 1, |
| 703 | None => 0, |
| 704 | }; |
| 705 | if bit == 1 { |
| 706 | break; |
| 707 | } |
| 708 | last -= 1; |
| 709 | } |
| 710 | // `last` is one past the stop bit, so the syntax runs out at `last - 1`. |
| 711 | self.pos + 1 <= last.saturating_sub(1) |
| 712 | } |
| 713 | } |
| 714 | |
| 715 | // ------------------------------------------------------------------ the parameter sets |
| 716 | |
| 717 | /// Reads a sequence parameter set (§7.3.2.1.1). |
| 718 | pub fn sps(body: &[u8]) -> Outcome<Sps> { |
| 719 | let mut b = Bits::new(body); |
| 720 | let profile = res!(b.u(8)) as u8; |
| 721 | // Six constraint flags and two reserved bits. |
| 722 | res!(b.skip(8)); |
| 723 | let level = res!(b.u(8)) as u8; |
| 724 | let id = res!(b.ue()); |
| 725 | if id > 31 { |
| 726 | return Err(err!( |
| 727 | "A sequence parameter set numbered {}, and 31 is the highest.", id; |
| 728 | Invalid, Input, Decode)); |
| 729 | } |
| 730 | let mut chroma = 1u32; |
| 731 | let mut separate_planes = false; |
| 732 | let mut luma_bits = 8u32; |
| 733 | let mut chroma_bits = 8u32; |
| 734 | let mut qpprime_bypass = false; |
| 735 | let mut scaling = None; |
| 736 | // The profiles whose parameter sets carry a chroma format and scaling lists. Every other |
| 737 | // profile is 4:2:0 at eight bits with no lists. |
| 738 | if matches!(profile, 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135) { |
| 739 | chroma = res!(b.ue()); |
| 740 | if chroma == 3 { |
| 741 | separate_planes = res!(b.flag()); |
| 742 | } |
| 743 | luma_bits = res!(b.ue()) + 8; |
| 744 | chroma_bits = res!(b.ue()) + 8; |
| 745 | qpprime_bypass = res!(b.flag()); |
| 746 | if res!(b.flag()) { |
| 747 | let count = if chroma != 3 { 8 } else { 12 }; |
| 748 | scaling = Some(res!(Scaling::read(&mut b, count, None, true))); |
| 749 | } |
| 750 | } |
| 751 | if chroma > 3 { |
| 752 | return Err(err!( |
| 753 | "A chroma_format_idc of {} was coded, and 0 to 3 are the only ones defined.", chroma; |
| 754 | Invalid, Input, Decode)); |
| 755 | } |
| 756 | let frame_num_bits = res!(b.ue()) + 4; |
| 757 | if frame_num_bits > 16 { |
| 758 | return Err(err!( |
| 759 | "frame_num is coded in {} bits, and 16 is the most allowed.", frame_num_bits; |
| 760 | Invalid, Input, Decode)); |
| 761 | } |
| 762 | let poc_type = res!(b.ue()); |
| 763 | let mut poc_lsb_bits = 0u32; |
| 764 | let mut delta_poc_always_zero = false; |
| 765 | match poc_type { |
| 766 | 0 => { |
| 767 | poc_lsb_bits = res!(b.ue()) + 4; |
| 768 | if poc_lsb_bits > 16 { |
| 769 | return Err(err!( |
| 770 | "The picture order count's low half is {} bits, and 16 is the most allowed.", |
| 771 | poc_lsb_bits; |
| 772 | Invalid, Input, Decode)); |
| 773 | } |
| 774 | }, |
| 775 | 1 => { |
| 776 | delta_poc_always_zero = res!(b.flag()); |
| 777 | let _offset_non_ref = res!(b.se()); |
| 778 | let _offset_top_bottom = res!(b.se()); |
| 779 | let cycle = res!(b.ue()); |
| 780 | if cycle > 255 { |
| 781 | return Err(err!( |
| 782 | "A picture order count cycle of {} entries was coded, and 255 is the most \ |
| 783 | allowed.", cycle; |
| 784 | Invalid, Input, Decode)); |
| 785 | } |
| 786 | for _ in 0..cycle { |
| 787 | let _offset = res!(b.se()); |
| 788 | } |
| 789 | }, |
| 790 | 2 => {}, |
| 791 | other => return Err(err!( |
| 792 | "A picture order count type of {} was coded, and 0, 1 and 2 are the only ones \ |
| 793 | defined.", other; |
| 794 | Invalid, Input, Decode)), |
| 795 | } |
| 796 | let _max_num_ref_frames = res!(b.ue()); |
| 797 | let _gaps_allowed = res!(b.flag()); |
| 798 | let mbs_w = res!(b.ue()) + 1; |
| 799 | let map_units_h = res!(b.ue()) + 1; |
| 800 | let frame_mbs_only = res!(b.flag()); |
| 801 | let mbaff = if frame_mbs_only { false } else { res!(b.flag()) }; |
| 802 | let _direct_8x8 = res!(b.flag()); |
| 803 | let mut crop = [0u32; 4]; |
| 804 | if res!(b.flag()) { |
| 805 | for c in crop.iter_mut() { |
| 806 | *c = res!(b.ue()); |
| 807 | } |
| 808 | } |
| 809 | // The video usability information changes no sample, so it is not read. |
| 810 | |
| 811 | let coded_w = mbs_w * 16; |
| 812 | let coded_h = map_units_h * 16 * if frame_mbs_only { 1 } else { 2 }; |
| 813 | if coded_w > MAX_SIDE || coded_h > MAX_SIDE { |
| 814 | return Err(err!( |
| 815 | "A picture of {} by {} luma samples was coded, and {} each way is this decoder's \ |
| 816 | ceiling.", coded_w, coded_h, MAX_SIDE; |
| 817 | Invalid, Input, Size)); |
| 818 | } |
| 819 | // The crop offsets are counted in chroma samples across and in chroma samples times the field |
| 820 | // factor down (§7.4.2.1.1). |
| 821 | let (cw, ch) = match chroma { |
| 822 | 0 => (1u32, 1u32), |
| 823 | 1 => (2, 2), |
| 824 | 2 => (2, 1), |
| 825 | _ => (1, 1), |
| 826 | }; |
| 827 | let (unit_x, unit_y) = if chroma == 0 || separate_planes { |
| 828 | (1u32, if frame_mbs_only { 1 } else { 2 }) |
| 829 | } else { |
| 830 | (cw, ch * if frame_mbs_only { 1 } else { 2 }) |
| 831 | }; |
| 832 | let cut_w = unit_x * (crop[0] + crop[1]); |
| 833 | let cut_h = unit_y * (crop[2] + crop[3]); |
| 834 | if cut_w >= coded_w || cut_h >= coded_h { |
| 835 | return Err(err!( |
| 836 | "A cropping window takes {} by {} from a picture of {} by {}, leaving nothing.", |
| 837 | cut_w, cut_h, coded_w, coded_h; |
| 838 | Invalid, Input, Decode)); |
| 839 | } |
| 840 | Ok(Sps { |
| 841 | id: id as u8, |
| 842 | profile, |
| 843 | level, |
| 844 | chroma: chroma as u8, |
| 845 | separate_planes, |
| 846 | luma_bits: luma_bits as u8, |
| 847 | chroma_bits: chroma_bits as u8, |
| 848 | qpprime_bypass, |
| 849 | mbs_w, |
| 850 | map_units_h, |
| 851 | frame_mbs_only, |
| 852 | mbaff, |
| 853 | frame_num_bits, |
| 854 | poc_type, |
| 855 | poc_lsb_bits, |
| 856 | delta_poc_always_zero, |
| 857 | crop, |
| 858 | scaling, |
| 859 | coded_w, |
| 860 | coded_h, |
| 861 | width: coded_w - cut_w, |
| 862 | height: coded_h - cut_h, |
| 863 | }) |
| 864 | } |
| 865 | |
| 866 | /// Reads a picture parameter set (§7.3.2.2). |
| 867 | /// |
| 868 | /// The sequence parameter set it references has to be in hand, because the number of scaling lists |
| 869 | /// the set may carry depends on the chroma format, and because the lists themselves fall back on |
| 870 | /// the sequence's where it has any. |
| 871 | pub fn pps(body: &[u8], sets: &[Sps]) -> Outcome<Pps> { |
| 872 | let mut b = Bits::new(body); |
| 873 | let id = res!(b.ue()); |
| 874 | if id > 255 { |
| 875 | return Err(err!( |
| 876 | "A picture parameter set numbered {}, and 255 is the highest.", id; |
| 877 | Invalid, Input, Decode)); |
| 878 | } |
| 879 | let sps_id = res!(b.ue()); |
| 880 | let sps = match sets.iter().find(|s| s.id as u32 == sps_id) { |
| 881 | Some(s) => s, |
| 882 | None => return Err(err!( |
| 883 | "A picture parameter set references sequence parameter set {}, and the stream carries \ |
| 884 | {:?}.", sps_id, sets.iter().map(|s| s.id).collect::<Vec<_>>(); |
| 885 | Invalid, Input, Missing)), |
| 886 | }; |
| 887 | let cabac = res!(b.flag()); |
| 888 | let bottom_field_order = res!(b.flag()); |
| 889 | let slice_groups = res!(b.ue()) + 1; |
| 890 | if slice_groups > 1 { |
| 891 | return Err(err!( |
| 892 | "A picture is cut into {} slice groups, and this decoder reads one. Slice groups \ |
| 893 | reorder macroblocks through a map, and every film in the corpus this was written \ |
| 894 | against uses a single group.", slice_groups; |
| 895 | Invalid, Input, Unimplemented)); |
| 896 | } |
| 897 | let _num_ref_idx_l0 = res!(b.ue()); |
| 898 | let _num_ref_idx_l1 = res!(b.ue()); |
| 899 | let _weighted_pred = res!(b.flag()); |
| 900 | let _weighted_bipred = res!(b.u(2)); |
| 901 | let init_qp = res!(b.se()) + 26; |
| 902 | let _init_qs = res!(b.se()) + 26; |
| 903 | let cb_qp_offset = res!(b.se()); |
| 904 | let deblocking_control = res!(b.flag()); |
| 905 | let constrained_intra = res!(b.flag()); |
| 906 | let redundant_pic_cnt = res!(b.flag()); |
| 907 | let mut transform_8x8 = false; |
| 908 | let mut scaling = sps.scaling.clone(); |
| 909 | let mut cr_qp_offset = cb_qp_offset; |
| 910 | if b.more_data() { |
| 911 | transform_8x8 = res!(b.flag()); |
| 912 | if res!(b.flag()) { |
| 913 | let count = 6 + if sps.chroma != 3 { 2 } else { 6 } * usize::from(transform_8x8); |
| 914 | scaling = Some(res!(Scaling::read( |
| 915 | &mut b, count, sps.scaling.as_ref(), sps.scaling.is_none()))); |
| 916 | } |
| 917 | cr_qp_offset = res!(b.se()); |
| 918 | } |
| 919 | for (name, v) in [("chroma_qp_index_offset", cb_qp_offset), |
| 920 | ("second_chroma_qp_index_offset", cr_qp_offset)] { |
| 921 | if !(-12..=12).contains(&v) { |
| 922 | return Err(err!( |
| 923 | "A {} of {} was coded, and it runs from -12 to 12.", name, v; |
| 924 | Invalid, Input, Decode)); |
| 925 | } |
| 926 | } |
| 927 | if !(0..=51).contains(&init_qp) { |
| 928 | return Err(err!( |
| 929 | "A picture starts at a quantisation parameter of {}, and it runs from 0 to 51.", |
| 930 | init_qp; |
| 931 | Invalid, Input, Decode)); |
| 932 | } |
| 933 | Ok(Pps { |
| 934 | id: id as u8, |
| 935 | sps_id: sps_id as u8, |
| 936 | cabac, |
| 937 | bottom_field_order, |
| 938 | slice_groups, |
| 939 | init_qp, |
| 940 | cb_qp_offset, |
| 941 | cr_qp_offset, |
| 942 | deblocking_control, |
| 943 | constrained_intra, |
| 944 | redundant_pic_cnt, |
| 945 | transform_8x8, |
| 946 | scaling, |
| 947 | }) |
| 948 | } |
| 949 | |
| 950 | /// Reads a slice header (§7.3.3), leaving the reader at the first bit of the slice data. |
| 951 | /// |
| 952 | /// The header is read past rather than into wherever a field changes no sample: reference picture |
| 953 | /// list modification and the decoded reference picture marking both have to be *walked*, because |
| 954 | /// they are runs of variable-length codes and there is no skipping to what follows them. |
| 955 | pub fn slice(u: &Unit, sets: &[Sps], pics: &[Pps]) -> Outcome<Slice> { |
| 956 | let idr = u.kind == nal::IDR; |
| 957 | let mut b = Bits::new(&u.body); |
| 958 | let first_mb = res!(b.ue()); |
| 959 | let code = res!(b.ue()); |
| 960 | if code > 9 { |
| 961 | return Err(err!( |
| 962 | "A slice_type of {} was coded, and 0 to 9 are the only ones defined.", code; |
| 963 | Invalid, Input, Decode)); |
| 964 | } |
| 965 | let kind = res!(SliceType::of(code)); |
| 966 | let pps_id = res!(b.ue()); |
| 967 | let pps = match pics.iter().find(|p| p.id as u32 == pps_id) { |
| 968 | Some(p) => p, |
| 969 | None => return Err(err!( |
| 970 | "A slice references picture parameter set {}, and the stream carries {:?}.", |
| 971 | pps_id, pics.iter().map(|p| p.id).collect::<Vec<_>>(); |
| 972 | Invalid, Input, Missing)), |
| 973 | }; |
| 974 | let sps = match sets.iter().find(|s| s.id == pps.sps_id) { |
| 975 | Some(s) => s, |
| 976 | None => return Err(err!( |
| 977 | "A picture parameter set references sequence parameter set {}, which the stream does \ |
| 978 | not carry.", pps.sps_id; |
| 979 | Invalid, Input, Missing)), |
| 980 | }; |
| 981 | if sps.separate_planes { |
| 982 | let _colour_plane_id = res!(b.u(2)); |
| 983 | } |
| 984 | let _frame_num = res!(b.u(sps.frame_num_bits as usize)); |
| 985 | let mut field_pic = false; |
| 986 | if !sps.frame_mbs_only { |
| 987 | field_pic = res!(b.flag()); |
| 988 | if field_pic { |
| 989 | let _bottom_field = res!(b.flag()); |
| 990 | } |
| 991 | } |
| 992 | if field_pic { |
| 993 | return Err(err!( |
| 994 | "A slice codes a field rather than a frame. This decoder reads frames, and every film \ |
| 995 | in the corpus it was written against sets frame_mbs_only_flag."; |
| 996 | Invalid, Input, Unimplemented)); |
| 997 | } |
| 998 | if idr { |
| 999 | let _idr_pic_id = res!(b.ue()); |
| 1000 | } |
| 1001 | if sps.poc_type == 0 { |
| 1002 | let _poc_lsb = res!(b.u(sps.poc_lsb_bits as usize)); |
| 1003 | if pps.bottom_field_order && !field_pic { |
| 1004 | let _delta_poc_bottom = res!(b.se()); |
| 1005 | } |
| 1006 | } |
| 1007 | if sps.poc_type == 1 && !sps.delta_poc_always_zero { |
| 1008 | let _delta_poc_0 = res!(b.se()); |
| 1009 | if pps.bottom_field_order && !field_pic { |
| 1010 | let _delta_poc_1 = res!(b.se()); |
| 1011 | } |
| 1012 | } |
| 1013 | if pps.redundant_pic_cnt { |
| 1014 | let redundant = res!(b.ue()); |
| 1015 | if redundant != 0 { |
| 1016 | return Err(err!( |
| 1017 | "A redundant coded picture was met, at redundant_pic_cnt {}. This decoder reads \ |
| 1018 | the primary picture only.", redundant; |
| 1019 | Invalid, Input, Unimplemented)); |
| 1020 | } |
| 1021 | } |
| 1022 | if !kind.is_intra() { |
| 1023 | return Err(err!( |
| 1024 | "A {:?} slice was met, and this decoder reads intra slices. The first coded picture \ |
| 1025 | of a film is an IDR and every slice of it is intra; a {:?} slice means the caller \ |
| 1026 | handed over a picture that is not the first.", kind, kind; |
| 1027 | Invalid, Input, Unimplemented)); |
| 1028 | } |
| 1029 | // `ref_pic_list_modification`: an I slice codes only the two flags' absence, so for a slice |
| 1030 | // whose type is intra there is nothing here at all (§7.3.3.1). |
| 1031 | if u.ref_idc != 0 { |
| 1032 | // `dec_ref_pic_marking` (§7.3.3.3). |
| 1033 | if idr { |
| 1034 | let _no_output_of_prior_pics = res!(b.flag()); |
| 1035 | let _long_term_reference = res!(b.flag()); |
| 1036 | } else { |
| 1037 | if res!(b.flag()) { |
| 1038 | loop { |
| 1039 | let op = res!(b.ue()); |
| 1040 | if op == 0 { |
| 1041 | break; |
| 1042 | } |
| 1043 | if op > 6 { |
| 1044 | return Err(err!( |
| 1045 | "A memory management control operation of {} was coded, and 0 to 6 \ |
| 1046 | are the only ones defined.", op; |
| 1047 | Invalid, Input, Decode)); |
| 1048 | } |
| 1049 | if matches!(op, 1 | 3) { |
| 1050 | let _difference_of_pic_nums = res!(b.ue()); |
| 1051 | } |
| 1052 | if op == 2 { |
| 1053 | let _long_term_pic_num = res!(b.ue()); |
| 1054 | } |
| 1055 | if matches!(op, 3 | 6) { |
| 1056 | let _long_term_frame_idx = res!(b.ue()); |
| 1057 | } |
| 1058 | if op == 4 { |
| 1059 | let _max_long_term_frame_idx = res!(b.ue()); |
| 1060 | } |
| 1061 | } |
| 1062 | } |
| 1063 | } |
| 1064 | } |
| 1065 | // `cabac_init_idc` is coded only for a slice that is not intra, so it is never read here; it |
| 1066 | // is kept in the header for the shape of the thing and is always nought. An intra slice's |
| 1067 | // context variables come from the I-slice column of Tables 9-12 to 9-24, which no |
| 1068 | // `cabac_init_idc` chooses between. |
| 1069 | let cabac_init_idc = 0u32; |
| 1070 | let qp_delta = res!(b.se()); |
| 1071 | let qp = pps.init_qp + qp_delta; |
| 1072 | if !(0..=51).contains(&qp) { |
| 1073 | return Err(err!( |
| 1074 | "A slice starts at a quantisation parameter of {}, and it runs from 0 to 51.", qp; |
| 1075 | Invalid, Input, Decode)); |
| 1076 | } |
| 1077 | let mut deblocking = 0u32; |
| 1078 | let mut alpha_offset = 0i32; |
| 1079 | let mut beta_offset = 0i32; |
| 1080 | if pps.deblocking_control { |
| 1081 | deblocking = res!(b.ue()); |
| 1082 | if deblocking > 2 { |
| 1083 | return Err(err!( |
| 1084 | "A disable_deblocking_filter_idc of {} was coded, and 0, 1 and 2 are the only \ |
| 1085 | ones defined.", deblocking; |
| 1086 | Invalid, Input, Decode)); |
| 1087 | } |
| 1088 | if deblocking != 1 { |
| 1089 | alpha_offset = res!(b.se()) * 2; |
| 1090 | beta_offset = res!(b.se()) * 2; |
| 1091 | } |
| 1092 | } |
| 1093 | Ok(Slice { |
| 1094 | first_mb, |
| 1095 | kind, |
| 1096 | all_same: code >= 5, |
| 1097 | pps_id: pps_id as u8, |
| 1098 | idr, |
| 1099 | qp, |
| 1100 | deblocking, |
| 1101 | alpha_offset, |
| 1102 | beta_offset, |
| 1103 | cabac_init_idc, |
| 1104 | data_bit: b.consumed(), |
| 1105 | }) |
| 1106 | } |
| 1107 | |
| 1108 | #[cfg(test)] |
| 1109 | mod tests { |
| 1110 | use super::*; |
| 1111 | |
| 1112 | #[test] |
| 1113 | fn test_a_payload_gives_up_its_escapes_01() -> Outcome<()> { |
| 1114 | // Emulation prevention is the one transformation that stands between the bytes in the file |
| 1115 | // and every field read out of them, so it is checked on the three shapes that occur: a byte |
| 1116 | // that is escaped, a byte that looks escaped and is not, and a run of zeroes. |
| 1117 | req!(rbsp(&[0x00, 0x00, 0x03, 0x01]), vec![0x00, 0x00, 0x01]); |
| 1118 | // Not after two zeroes, so not an escape. |
| 1119 | req!(rbsp(&[0x00, 0x03, 0x01]), vec![0x00, 0x03, 0x01]); |
| 1120 | // The escape resets the count, so the next 0x03 needs two more zeroes in front of it. |
| 1121 | req!(rbsp(&[0x00, 0x00, 0x03, 0x00, 0x03]), vec![0x00, 0x00, 0x00, 0x03]); |
| 1122 | req!(rbsp(&[0x00, 0x00, 0x03, 0x00, 0x00, 0x03]), vec![0x00, 0x00, 0x00, 0x00]); |
| 1123 | Ok(()) |
| 1124 | } |
| 1125 | |
| 1126 | #[test] |
| 1127 | fn test_more_data_stops_at_the_trailing_bits_02() -> Outcome<()> { |
| 1128 | // The picture parameter set's last three fields -- the eight-by-eight transform flag among |
| 1129 | // them -- are read or not on this answer alone. On a High profile film the flag is on, so a |
| 1130 | // reader that says "no more data" one bit early decodes every one of them as a picture with |
| 1131 | // no eight-by-eight transform, which is a wrong picture rather than an error. |
| 1132 | // |
| 1133 | // A payload of one byte 0b1011_0000: three bits of syntax, then the stop bit, then padding. |
| 1134 | let buf = [0b1011_0000u8]; |
| 1135 | let mut b = Bits::new(&buf); |
| 1136 | for i in 0..3 { |
| 1137 | let more = b.more_data(); |
| 1138 | req!(more, true, "the payload ran out after {} bits of syntax and it holds three", i); |
| 1139 | let _ = res!(b.u(1)); |
| 1140 | } |
| 1141 | let more = b.more_data(); |
| 1142 | req!(more, false, "the stop bit was read as syntax"); |
| 1143 | |
| 1144 | // And a payload whose stop bit is the last bit of the last byte. |
| 1145 | let buf = [0xFFu8, 0x81]; |
| 1146 | let mut b = Bits::new(&buf); |
| 1147 | res!(b.skip(14)); |
| 1148 | req!(b.more_data(), true); |
| 1149 | res!(b.skip(1)); |
| 1150 | req!(b.more_data(), false, "the stop bit at the very end was read as syntax"); |
| 1151 | Ok(()) |
| 1152 | } |
| 1153 | |
| 1154 | #[test] |
| 1155 | fn test_an_absent_scaling_list_is_not_a_flat_one_03() -> Outcome<()> { |
| 1156 | // Table 7-2's fall-back rules. A sequence that turns the scaling matrices on and carries no |
| 1157 | // list of its own does not mean "no scaling"; it means the default matrices, which are not |
| 1158 | // flat. This is the difference, stated at the smallest scale: eight absent lists. |
| 1159 | // |
| 1160 | // One byte of eight zero bits: eight `seq_scaling_list_present_flag`s, all off. |
| 1161 | let buf = [0x00u8]; |
| 1162 | let mut b = Bits::new(&buf); |
| 1163 | let s = res!(Scaling::read(&mut b, 8, None, true)); |
| 1164 | req!(s.l4[0], DEFAULT_4X4_INTRA, "list 0 fell back on something other than the default"); |
| 1165 | // Lists 1 and 2 inherit from the one before them, so they are the intra default too. |
| 1166 | req!(s.l4[1], DEFAULT_4X4_INTRA); |
| 1167 | req!(s.l4[2], DEFAULT_4X4_INTRA); |
| 1168 | req!(s.l4[3], DEFAULT_4X4_INTER, "list 3 heads its own chain and did not take the default"); |
| 1169 | req!(s.l4[4], DEFAULT_4X4_INTER); |
| 1170 | req!(s.l4[5], DEFAULT_4X4_INTER); |
| 1171 | req!(s.l8[0], DEFAULT_8X8_INTRA); |
| 1172 | req!(s.l8[1], DEFAULT_8X8_INTER); |
| 1173 | // And the thing this is a guard against: none of them is flat. |
| 1174 | let flat = Scaling::flat(); |
| 1175 | let same = s.l4[0] == flat.l4[0]; |
| 1176 | req!(same, false, "an absent scaling list was read as no scaling at all"); |
| 1177 | Ok(()) |
| 1178 | } |
| 1179 | } |