Software encoder, I and P pictures, CAVLC, slice-parallel
Browse files at this commit6d2222858f45f42c011ffd30fef0d36036437f30Parent: 46b6e85- feat
- software encoder, I and P pictures, CAVLC, slice-parallel
9 changed files +3338 -87
- crates/ec-h264/src/decoder.rs +129 -37
- crates/ec-h264/src/enc/headers.rs +271 -0
- crates/ec-h264/src/enc/mb.rs +1332 -0
- crates/ec-h264/src/enc/mod.rs +657 -0
- crates/ec-h264/src/enc/quant.rs +258 -0
- crates/ec-h264/src/enc/rc.rs +172 -0
- crates/ec-h264/src/enc/vlc.rs +323 -0
- crates/ec-h264/src/inter.rs +192 -48
- crates/ec-h264/src/lib.rs +4 -2
crates/ec-h264/src/decoder.rsmodified+129 -37
| @@ -886,14 +886,14 @@ impl SliceCtx { | ||
| 886 | 886 | /// filter of 8.3.2.2.1, which changes its end taps when the corner sample is |
| 887 | 887 | /// missing. |
| 888 | 888 | #[derive(Clone, Copy)] |
| 889 | -struct MbNeighbors { | |
| 890 | - a: bool, | |
| 891 | - b: bool, | |
| 892 | - c: bool, | |
| 893 | - d: bool, | |
| 889 | +pub(crate) struct MbNeighbors { | |
| 890 | + pub a: bool, | |
| 891 | + pub b: bool, | |
| 892 | + pub c: bool, | |
| 893 | + pub d: bool, | |
| 894 | 894 | } |
| 895 | 895 | |
| 896 | -fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNeighbors { | |
| 896 | +pub(crate) fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNeighbors { | |
| 897 | 897 | let w = pic.mb_w; |
| 898 | 898 | let addr = mb_y * w + mb_x; |
| 899 | 899 | let same = |a: usize| pic.mb_slice[a] == slice_id; |
| @@ -923,7 +923,12 @@ fn intra_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, n: MbNeighbors) -> M | ||
| 923 | 923 | /// global block coords `(bx, by)`, `None` when that neighbour is unavailable |
| 924 | 924 | /// (clause 6.4.11.4 plus the availability rules of 6.4.8). |
| 925 | 925 | #[inline] |
| 926 | -fn luma_nz_pair(pic: &Picture, n: &MbNeighbors, bx: usize, by: usize) -> (Option<u8>, Option<u8>) { | |
| 926 | +pub(crate) fn luma_nz_pair( | |
| 927 | + pic: &Picture, | |
| 928 | + n: &MbNeighbors, | |
| 929 | + bx: usize, | |
| 930 | + by: usize, | |
| 931 | +) -> (Option<u8>, Option<u8>) { | |
| 927 | 932 | let w4 = pic.mb_w * 4; |
| 928 | 933 | let left_avail = if bx.is_multiple_of(4) { n.a } else { true }; |
| 929 | 934 | let top_avail = if by.is_multiple_of(4) { n.b } else { true }; |
| @@ -935,7 +940,7 @@ fn luma_nz_pair(pic: &Picture, n: &MbNeighbors, bx: usize, by: usize) -> (Option | ||
| 935 | 940 | |
| 936 | 941 | /// The same for a chroma AC 4x4 block at global chroma block coords. |
| 937 | 942 | #[inline] |
| 938 | -fn chroma_nz_pair( | |
| 943 | +pub(crate) fn chroma_nz_pair( | |
| 939 | 944 | pic: &Picture, |
| 940 | 945 | n: &MbNeighbors, |
| 941 | 946 | comp: usize, |
| @@ -2083,6 +2088,12 @@ fn compensate( | ||
| 2083 | 2088 | let y0 = (mb_y * 16 + py * 4) as i32; |
| 2084 | 2089 | let (w, h) = (pw * 4, ph * 4); |
| 2085 | 2090 | |
| 2091 | + let wt = ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1); | |
| 2092 | + // 8.4.2.3.1 over one list is the identity, so the interpolation of that one | |
| 2093 | + // list IS the prediction: it is written straight into the picture at the | |
| 2094 | + // picture's own pitch, rather than into a temporary that is combined into a | |
| 2095 | + // second temporary and copied a third time. | |
| 2096 | + let direct = wt.is_default() && (use0 != use1); | |
| 2086 | 2097 | let mut part = [[0u8; 256]; 2]; |
| 2087 | 2098 | for list in 0..2 { |
| 2088 | 2099 | if ref_idx[list] < 0 { |
| @@ -2099,17 +2110,33 @@ fn compensate( | ||
| 2099 | 2110 | height: rp.y.height, |
| 2100 | 2111 | pad: rp.y.pad, |
| 2101 | 2112 | }; |
| 2102 | - mc_luma(&plane, x0, y0, mv[list], w, h, &mut part[list]); | |
| 2113 | + if direct { | |
| 2114 | + let stride = pic.y.stride; | |
| 2115 | + let origin = pic.y.at(x0 as usize, y0 as usize); | |
| 2116 | + mc_luma( | |
| 2117 | + &plane, | |
| 2118 | + x0, | |
| 2119 | + y0, | |
| 2120 | + mv[list], | |
| 2121 | + w, | |
| 2122 | + h, | |
| 2123 | + stride, | |
| 2124 | + &mut pic.y.data[origin..], | |
| 2125 | + ); | |
| 2126 | + } else { | |
| 2127 | + mc_luma(&plane, x0, y0, mv[list], w, h, w, &mut part[list]); | |
| 2128 | + } | |
| 2103 | 2129 | } |
| 2104 | - let wt = ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1); | |
| 2105 | - let mut out = [0u8; 256]; | |
| 2106 | - let (p0, p1) = part.split_at(1); | |
| 2107 | - combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h); | |
| 2108 | - let stride = pic.y.stride; | |
| 2109 | - let origin = pic.y.at(x0 as usize, y0 as usize); | |
| 2110 | - for row in 0..h { | |
| 2111 | - let dst = origin + row * stride; | |
| 2112 | - pic.y.data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]); | |
| 2130 | + if !direct { | |
| 2131 | + let mut out = [0u8; 256]; | |
| 2132 | + let (p0, p1) = part.split_at(1); | |
| 2133 | + combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h); | |
| 2134 | + let stride = pic.y.stride; | |
| 2135 | + let origin = pic.y.at(x0 as usize, y0 as usize); | |
| 2136 | + for row in 0..h { | |
| 2137 | + let dst = origin + row * stride; | |
| 2138 | + pic.y.data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]); | |
| 2139 | + } | |
| 2113 | 2140 | } |
| 2114 | 2141 | |
| 2115 | 2142 | // Chroma (8.4.1.4): for 4:2:0 frame coding the chroma vector is the luma |
| @@ -2117,6 +2144,8 @@ fn compensate( | ||
| 2117 | 2144 | let (cw, ch) = (w / 2, h / 2); |
| 2118 | 2145 | let (cx0, cy0) = (x0 / 2, y0 / 2); |
| 2119 | 2146 | for comp in 0..2 { |
| 2147 | + let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1); | |
| 2148 | + let direct = wt.is_default() && (use0 != use1); | |
| 2120 | 2149 | let mut cpart = [[0u8; 64]; 2]; |
| 2121 | 2150 | for list in 0..2 { |
| 2122 | 2151 | if ref_idx[list] < 0 { |
| @@ -2134,18 +2163,35 @@ fn compensate( | ||
| 2134 | 2163 | height: src.height, |
| 2135 | 2164 | pad: src.pad, |
| 2136 | 2165 | }; |
| 2137 | - mc_chroma(&plane, cx0, cy0, mv[list], cw, ch, &mut cpart[list]); | |
| 2166 | + if direct { | |
| 2167 | + let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; | |
| 2168 | + let stride = dst.stride; | |
| 2169 | + let origin = dst.at(cx0 as usize, cy0 as usize); | |
| 2170 | + mc_chroma( | |
| 2171 | + &plane, | |
| 2172 | + cx0, | |
| 2173 | + cy0, | |
| 2174 | + mv[list], | |
| 2175 | + cw, | |
| 2176 | + ch, | |
| 2177 | + stride, | |
| 2178 | + &mut dst.data[origin..], | |
| 2179 | + ); | |
| 2180 | + } else { | |
| 2181 | + mc_chroma(&plane, cx0, cy0, mv[list], cw, ch, cw, &mut cpart[list]); | |
| 2182 | + } | |
| 2138 | 2183 | } |
| 2139 | - let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1); | |
| 2140 | - let mut cout = [0u8; 64]; | |
| 2141 | - let (c0, c1) = cpart.split_at(1); | |
| 2142 | - combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch); | |
| 2143 | - let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; | |
| 2144 | - let stride = plane.stride; | |
| 2145 | - let origin = plane.at(cx0 as usize, cy0 as usize); | |
| 2146 | - for row in 0..ch { | |
| 2147 | - let dst = origin + row * stride; | |
| 2148 | - plane.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]); | |
| 2184 | + if !direct { | |
| 2185 | + let mut cout = [0u8; 64]; | |
| 2186 | + let (c0, c1) = cpart.split_at(1); | |
| 2187 | + combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch); | |
| 2188 | + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; | |
| 2189 | + let stride = plane.stride; | |
| 2190 | + let origin = plane.at(cx0 as usize, cy0 as usize); | |
| 2191 | + for row in 0..ch { | |
| 2192 | + let dst = origin + row * stride; | |
| 2193 | + plane.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]); | |
| 2194 | + } | |
| 2149 | 2195 | } |
| 2150 | 2196 | } |
| 2151 | 2197 | Ok(()) |
| @@ -2153,7 +2199,13 @@ fn compensate( | ||
| 2153 | 2199 | |
| 2154 | 2200 | /// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2), |
| 2155 | 2201 | /// including the top-right substitution rule. |
| 2156 | -fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) -> Nbr4 { | |
| 2202 | +pub(crate) fn gather_nbr4( | |
| 2203 | + pic: &Picture, | |
| 2204 | + nbr: &MbNeighbors, | |
| 2205 | + blk: usize, | |
| 2206 | + x: usize, | |
| 2207 | + y: usize, | |
| 2208 | +) -> Nbr4 { | |
| 2157 | 2209 | let (dx, dy) = BLK4_POS[blk]; |
| 2158 | 2210 | let stride = pic.y.stride; |
| 2159 | 2211 | let o = pic.y.at(x, y); |
| @@ -2239,7 +2291,7 @@ fn gather_nbr8(pic: &Picture, nbr: &MbNeighbors, blk8: usize, x: usize, y: usize | ||
| 2239 | 2291 | // index the plane as well as the strength arrays; iterating the arrays would |
| 2240 | 2292 | // hide which geometry each one names. |
| 2241 | 2293 | #[allow(clippy::needless_range_loop)] |
| 2242 | -fn deblock_picture(pic: &mut Picture) { | |
| 2294 | +pub(crate) fn deblock_picture(pic: &mut Picture) { | |
| 2243 | 2295 | let mb_w = pic.mb_w; |
| 2244 | 2296 | for mb_y in 0..pic.mb_h { |
| 2245 | 2297 | for mb_x in 0..mb_w { |
| @@ -2272,15 +2324,42 @@ fn deblock_picture(pic: &mut Picture) { | ||
| 2272 | 2324 | |e: usize| e.is_multiple_of(2) || pic.mb_flags[addr] & FLAG_TRANS8X8 == 0; |
| 2273 | 2325 | |
| 2274 | 2326 | // Boundary strengths, per 4-sample segment of each edge (8.7.2.1). |
| 2327 | + // | |
| 2328 | + // Both sides of an internal edge live in this macroblock, so the | |
| 2329 | + // whole 8.7.2.1 ladder is decided once for all 24 of them: an intra | |
| 2330 | + // macroblock gives 3 everywhere, and an inter macroblock with no | |
| 2331 | + // luma coefficients and one motion vector over the whole 16x16 | |
| 2332 | + // gives 0 everywhere. Only the two macroblock edges then need the | |
| 2333 | + // per-segment derivation. | |
| 2275 | 2334 | let mut bs_v = [[0u8; 4]; 4]; |
| 2276 | 2335 | let mut bs_h = [[0u8; 4]; 4]; |
| 2277 | - for e in 0..4 { | |
| 2278 | - for k in 0..4 { | |
| 2279 | - if e > 0 || filter_left { | |
| 2280 | - bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true); | |
| 2336 | + let cur_intra = pic.mb_flags[addr] & FLAG_INTER == 0; | |
| 2337 | + let internal_uniform = if cur_intra { | |
| 2338 | + Some(3) | |
| 2339 | + } else if pic.mb_cbp[addr] == 0 && uniform_motion(pic, mb_x, mb_y) { | |
| 2340 | + Some(0) | |
| 2341 | + } else { | |
| 2342 | + None | |
| 2343 | + }; | |
| 2344 | + for k in 0..4 { | |
| 2345 | + if filter_left { | |
| 2346 | + bs_v[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, true); | |
| 2347 | + } | |
| 2348 | + if filter_top { | |
| 2349 | + bs_h[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, false); | |
| 2350 | + } | |
| 2351 | + } | |
| 2352 | + for e in 1..4 { | |
| 2353 | + match internal_uniform { | |
| 2354 | + Some(bs) => { | |
| 2355 | + bs_v[e] = [bs; 4]; | |
| 2356 | + bs_h[e] = [bs; 4]; | |
| 2281 | 2357 | } |
| 2282 | - if e > 0 || filter_top { | |
| 2283 | - bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false); | |
| 2358 | + None => { | |
| 2359 | + for k in 0..4 { | |
| 2360 | + bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true); | |
| 2361 | + bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false); | |
| 2362 | + } | |
| 2284 | 2363 | } |
| 2285 | 2364 | } |
| 2286 | 2365 | } |
| @@ -2441,6 +2520,19 @@ fn deblock_picture(pic: &mut Picture) { | ||
| 2441 | 2520 | } |
| 2442 | 2521 | } |
| 2443 | 2522 | |
| 2523 | +/// True when every 4x4 block of this macroblock predicts from the same | |
| 2524 | +/// pictures with the same motion, so no internal edge can reach the motion | |
| 2525 | +/// clauses of 8.7.2.1. | |
| 2526 | +fn uniform_motion(pic: &Picture, mb_x: usize, mb_y: usize) -> bool { | |
| 2527 | + let w4 = pic.mb_w * 4; | |
| 2528 | + let first = mb_y * 4 * w4 + mb_x * 4; | |
| 2529 | + let (mv, id) = (pic.mv[first], pic.ref_id[first]); | |
| 2530 | + (0..4).all(|by| { | |
| 2531 | + let row = first + by * w4; | |
| 2532 | + (0..4).all(|bx| pic.mv[row + bx] == mv && pic.ref_id[row + bx] == id) | |
| 2533 | + }) | |
| 2534 | +} | |
| 2535 | + | |
| 2444 | 2536 | /// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1). |
| 2445 | 2537 | /// |
| 2446 | 2538 | /// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the |
crates/ec-h264/src/enc/headers.rsadded+271 -0
| @@ -0,0 +1,271 @@ | ||
| 1 | +//! Parameter sets and slice headers on the writing side (spec 7.3.2, 7.3.3). | |
| 2 | +//! | |
| 3 | +//! Only the subset this encoder emits is written: 8-bit 4:2:0 progressive, | |
| 4 | +//! CAVLC, one slice group, one reference, `pic_order_cnt_type` 2 — which is | |
| 5 | +//! the type that says decode order *is* output order, and costs no bits in | |
| 6 | +//! any slice header. The test at the bottom parses everything back through | |
| 7 | +//! [`ec_h264_syntax`], which is the same parser the decoder uses. | |
| 8 | + | |
| 9 | +use ec_core::BitWriter; | |
| 10 | +use ec_h264_syntax::SliceType; | |
| 11 | + | |
| 12 | +/// Geometry and timing of the sequence, everything the parameter sets need. | |
| 13 | +#[derive(Debug, Clone, Copy)] | |
| 14 | +pub(crate) struct SeqParams { | |
| 15 | + /// Displayed luma width. | |
| 16 | + pub width: u32, | |
| 17 | + /// Displayed luma height. | |
| 18 | + pub height: u32, | |
| 19 | + /// Coded width in macroblocks. | |
| 20 | + pub mb_w: u32, | |
| 21 | + /// Coded height in macroblocks. | |
| 22 | + pub mb_h: u32, | |
| 23 | + /// `(num_units_in_tick, time_scale)`; `time_scale` is twice the frame rate. | |
| 24 | + pub timing: (u32, u32), | |
| 25 | + /// Bits per second the level has to carry. | |
| 26 | + pub bitrate: u32, | |
| 27 | +} | |
| 28 | + | |
| 29 | +/// `log2_max_frame_num`, fixed: 8 bits of frame_num wrap far beyond the one | |
| 30 | +/// reference picture this encoder keeps. | |
| 31 | +pub(crate) const LOG2_MAX_FRAME_NUM: u32 = 8; | |
| 32 | + | |
| 33 | +/// Annex A levels as `(level_idc, MaxMBPS, MaxFS, MaxBR in kbit/s)`, in | |
| 34 | +/// ascending order; the first one that fits is what the SPS advertises. | |
| 35 | +const LEVELS: [(u8, u64, u64, u64); 16] = [ | |
| 36 | + (10, 1485, 99, 64), | |
| 37 | + (11, 3000, 396, 192), | |
| 38 | + (12, 6000, 396, 384), | |
| 39 | + (13, 11880, 396, 768), | |
| 40 | + (20, 11880, 396, 2000), | |
| 41 | + (21, 19800, 792, 4000), | |
| 42 | + (22, 20250, 1620, 4000), | |
| 43 | + (30, 40500, 1620, 10000), | |
| 44 | + (31, 108000, 3600, 14000), | |
| 45 | + (32, 216000, 5120, 20000), | |
| 46 | + (40, 245760, 8192, 20000), | |
| 47 | + (42, 522240, 8704, 50000), | |
| 48 | + (50, 589824, 22080, 135000), | |
| 49 | + (51, 983040, 36864, 240000), | |
| 50 | + (52, 2073600, 36864, 240000), | |
| 51 | + (62, 16711680, 139264, 800000), | |
| 52 | +]; | |
| 53 | + | |
| 54 | +fn level_idc(p: &SeqParams) -> u8 { | |
| 55 | + let frame_mbs = u64::from(p.mb_w) * u64::from(p.mb_h); | |
| 56 | + let fps = f64::from(p.timing.1) / (2.0 * f64::from(p.timing.0).max(1.0)); | |
| 57 | + let mbps = (frame_mbs as f64 * fps).ceil() as u64; | |
| 58 | + let kbps = u64::from(p.bitrate) / 1000; | |
| 59 | + for &(idc, max_mbps, max_fs, max_br) in &LEVELS { | |
| 60 | + if mbps <= max_mbps && frame_mbs <= max_fs && kbps <= max_br { | |
| 61 | + return idc; | |
| 62 | + } | |
| 63 | + } | |
| 64 | + 62 | |
| 65 | +} | |
| 66 | + | |
| 67 | +/// Write the sequence parameter set RBSP (7.3.2.1), Baseline profile with the | |
| 68 | +/// Main-profile constraint flag set: this encoder emits nothing (no FMO, no | |
| 69 | +/// ASO, no redundant slices, no interlace) that either profile forbids. | |
| 70 | +pub(crate) fn write_sps(p: &SeqParams) -> Vec<u8> { | |
| 71 | + let mut w = BitWriter::with_capacity(32); | |
| 72 | + w.write_bits(66, 8); // profile_idc: Baseline | |
| 73 | + w.write_bits(0b1100_0000, 8); // constraint_set0_flag, constraint_set1_flag | |
| 74 | + w.write_bits(u32::from(level_idc(p)), 8); | |
| 75 | + w.write_ue(0); // seq_parameter_set_id | |
| 76 | + w.write_ue(LOG2_MAX_FRAME_NUM - 4); | |
| 77 | + w.write_ue(2); // pic_order_cnt_type 2: output order is decode order | |
| 78 | + w.write_ue(1); // max_num_ref_frames | |
| 79 | + w.write_bit(false); // gaps_in_frame_num_value_allowed_flag | |
| 80 | + w.write_ue(p.mb_w - 1); | |
| 81 | + w.write_ue(p.mb_h - 1); | |
| 82 | + w.write_bit(true); // frame_mbs_only_flag | |
| 83 | + w.write_bit(true); // direct_8x8_inference_flag | |
| 84 | + let crop_right = (p.mb_w * 16 - p.width) / 2; // CropUnitX = 2 for 4:2:0 | |
| 85 | + let crop_bottom = (p.mb_h * 16 - p.height) / 2; // CropUnitY = 2, frame only | |
| 86 | + let cropping = crop_right != 0 || crop_bottom != 0; | |
| 87 | + w.write_bit(cropping); | |
| 88 | + if cropping { | |
| 89 | + w.write_ue(0); | |
| 90 | + w.write_ue(crop_right); | |
| 91 | + w.write_ue(0); | |
| 92 | + w.write_ue(crop_bottom); | |
| 93 | + } | |
| 94 | + // VUI: timing only, so a container-less stream still states its frame rate. | |
| 95 | + w.write_bit(true); // vui_parameters_present_flag | |
| 96 | + w.write_bit(false); // aspect_ratio_info_present_flag | |
| 97 | + w.write_bit(false); // overscan_info_present_flag | |
| 98 | + w.write_bit(false); // video_signal_type_present_flag | |
| 99 | + w.write_bit(false); // chroma_loc_info_present_flag | |
| 100 | + w.write_bit(true); // timing_info_present_flag | |
| 101 | + w.write_bits(p.timing.0, 32); | |
| 102 | + w.write_bits(p.timing.1, 32); | |
| 103 | + w.write_bit(true); // fixed_frame_rate_flag | |
| 104 | + w.write_bit(false); // nal_hrd_parameters_present_flag | |
| 105 | + w.write_bit(false); // vcl_hrd_parameters_present_flag | |
| 106 | + w.write_bit(false); // pic_struct_present_flag | |
| 107 | + w.write_bit(false); // bitstream_restriction_flag | |
| 108 | + trailing(&mut w); | |
| 109 | + w.into_bytes() | |
| 110 | +} | |
| 111 | + | |
| 112 | +/// Write the picture parameter set RBSP (7.3.2.2). | |
| 113 | +pub(crate) fn write_pps() -> Vec<u8> { | |
| 114 | + let mut w = BitWriter::with_capacity(8); | |
| 115 | + w.write_ue(0); // pic_parameter_set_id | |
| 116 | + w.write_ue(0); // seq_parameter_set_id | |
| 117 | + w.write_bit(false); // entropy_coding_mode_flag: CAVLC | |
| 118 | + w.write_bit(false); // bottom_field_pic_order_in_frame_present_flag | |
| 119 | + w.write_ue(0); // num_slice_groups_minus1 | |
| 120 | + w.write_ue(0); // num_ref_idx_l0_default_active_minus1 | |
| 121 | + w.write_ue(0); // num_ref_idx_l1_default_active_minus1 | |
| 122 | + w.write_bit(false); // weighted_pred_flag | |
| 123 | + w.write_bits(0, 2); // weighted_bipred_idc | |
| 124 | + w.write_se(0); // pic_init_qp_minus26 | |
| 125 | + w.write_se(0); // pic_init_qs_minus26 | |
| 126 | + w.write_se(0); // chroma_qp_index_offset | |
| 127 | + w.write_bit(false); // deblocking_filter_control_present_flag | |
| 128 | + w.write_bit(false); // constrained_intra_pred_flag | |
| 129 | + w.write_bit(false); // redundant_pic_cnt_present_flag | |
| 130 | + trailing(&mut w); | |
| 131 | + w.into_bytes() | |
| 132 | +} | |
| 133 | + | |
| 134 | +/// What one slice header says about the picture it opens. | |
| 135 | +#[derive(Debug, Clone, Copy)] | |
| 136 | +pub(crate) struct SliceParams { | |
| 137 | + pub first_mb: u32, | |
| 138 | + pub slice_type: SliceType, | |
| 139 | + pub frame_num: u32, | |
| 140 | + pub idr: bool, | |
| 141 | + /// `idr_pic_id`, alternating between consecutive IDR pictures. | |
| 142 | + pub idr_pic_id: u32, | |
| 143 | + pub qp: i32, | |
| 144 | +} | |
| 145 | + | |
| 146 | +/// Write a slice header (7.3.3) into `w`; slice data follows immediately. | |
| 147 | +pub(crate) fn write_slice_header(w: &mut BitWriter, s: &SliceParams) { | |
| 148 | + w.write_ue(s.first_mb); | |
| 149 | + // 5..=9 assert that every slice of this picture has the same type, which | |
| 150 | + // is true here: the picture is coded in one pass at one type. | |
| 151 | + w.write_ue(if s.slice_type == SliceType::I { 7 } else { 5 }); | |
| 152 | + w.write_ue(0); // pic_parameter_set_id | |
| 153 | + w.write_bits(s.frame_num, LOG2_MAX_FRAME_NUM); | |
| 154 | + if s.idr { | |
| 155 | + w.write_ue(s.idr_pic_id); | |
| 156 | + } | |
| 157 | + // pic_order_cnt_type 2: no picture order count in the header at all. | |
| 158 | + if s.slice_type == SliceType::P { | |
| 159 | + w.write_bit(false); // num_ref_idx_active_override_flag | |
| 160 | + w.write_bit(false); // ref_pic_list_modification_flag_l0 | |
| 161 | + } | |
| 162 | + // Every picture here is a reference picture (nal_ref_idc != 0). | |
| 163 | + if s.idr { | |
| 164 | + w.write_bit(false); // no_output_of_prior_pics_flag | |
| 165 | + w.write_bit(false); // long_term_reference_flag | |
| 166 | + } else { | |
| 167 | + w.write_bit(false); // adaptive_ref_pic_marking_mode_flag: sliding window | |
| 168 | + } | |
| 169 | + w.write_se(s.qp - 26); // slice_qp_delta, pic_init_qp_minus26 being 0 | |
| 170 | + // deblocking_filter_control_present_flag is 0: the filter is on, offsets 0. | |
| 171 | +} | |
| 172 | + | |
| 173 | +/// `rbsp_trailing_bits` (7.3.2.11). | |
| 174 | +pub(crate) fn trailing(w: &mut BitWriter) { | |
| 175 | + w.write_bit(true); | |
| 176 | + w.align_to_byte(); | |
| 177 | +} | |
| 178 | + | |
| 179 | +#[cfg(test)] | |
| 180 | +mod tests { | |
| 181 | + use super::*; | |
| 182 | + use ec_h264_syntax::{Pps, Sps}; | |
| 183 | + | |
| 184 | + fn params(width: u32, height: u32) -> SeqParams { | |
| 185 | + SeqParams { | |
| 186 | + width, | |
| 187 | + height, | |
| 188 | + mb_w: width.div_ceil(16), | |
| 189 | + mb_h: height.div_ceil(16), | |
| 190 | + timing: (1000, 60000), | |
| 191 | + bitrate: 8_000_000, | |
| 192 | + } | |
| 193 | + } | |
| 194 | + | |
| 195 | + /// The parameter sets this encoder writes are the ones the decoder's own | |
| 196 | + /// parser reads back, geometry, cropping and all. | |
| 197 | + #[test] | |
| 198 | + fn parameter_sets_parse_back() { | |
| 199 | + for (w, h) in [(1920, 1080), (640, 480), (854, 482), (16, 16)] { | |
| 200 | + let p = params(w, h); | |
| 201 | + let sps = Sps::parse(&write_sps(&p)).expect("SPS parses"); | |
| 202 | + assert_eq!((sps.width, sps.height), (w, h), "{w}x{h} crop"); | |
| 203 | + assert_eq!(sps.mb_width, p.mb_w); | |
| 204 | + assert_eq!(sps.mb_height, p.mb_h); | |
| 205 | + assert_eq!(sps.pic_order_cnt_type, 2); | |
| 206 | + assert_eq!(sps.max_num_ref_frames, 1); | |
| 207 | + assert!(sps.frame_mbs_only); | |
| 208 | + let vui = sps.vui.as_ref().expect("VUI present"); | |
| 209 | + assert_eq!(vui.timing_info, Some((1000, 60000, true))); | |
| 210 | + let pps = Pps::parse(&write_pps(), |_| Some(&sps)).expect("PPS parses"); | |
| 211 | + assert!(!pps.entropy_coding_mode); | |
| 212 | + assert_eq!(pps.pic_init_qp, 26); | |
| 213 | + } | |
| 214 | + } | |
| 215 | + | |
| 216 | + /// 1080p60 at 8 Mbit/s needs level 4.0; a small clip needs far less. | |
| 217 | + #[test] | |
| 218 | + fn level_follows_the_load() { | |
| 219 | + assert_eq!(level_idc(¶ms(1920, 1080)), 40); | |
| 220 | + let mut small = params(320, 240); | |
| 221 | + small.timing = (1000, 30000); | |
| 222 | + small.bitrate = 300_000; | |
| 223 | + assert!(level_idc(&small) <= 21); | |
| 224 | + } | |
| 225 | + | |
| 226 | + /// A slice header reads back at the values that were written. | |
| 227 | + #[test] | |
| 228 | + fn slice_header_parses_back() { | |
| 229 | + let p = params(320, 240); | |
| 230 | + let sps = Sps::parse(&write_sps(&p)).unwrap(); | |
| 231 | + let pps = Pps::parse(&write_pps(), |_| Some(&sps)).unwrap(); | |
| 232 | + for (idr, slice_type, first_mb, qp) in [ | |
| 233 | + (true, SliceType::I, 0u32, 30i32), | |
| 234 | + (false, SliceType::P, 40, 18), | |
| 235 | + ] { | |
| 236 | + let mut w = BitWriter::new(); | |
| 237 | + write_slice_header( | |
| 238 | + &mut w, | |
| 239 | + &SliceParams { | |
| 240 | + first_mb, | |
| 241 | + slice_type, | |
| 242 | + frame_num: 7, | |
| 243 | + idr, | |
| 244 | + idr_pic_id: 1, | |
| 245 | + qp, | |
| 246 | + }, | |
| 247 | + ); | |
| 248 | + trailing(&mut w); | |
| 249 | + let rbsp = w.into_bytes(); | |
| 250 | + let header = ec_h264_syntax::SliceHeader::parse( | |
| 251 | + &rbsp, | |
| 252 | + ec_h264_syntax::nal::NalHeader { | |
| 253 | + ref_idc: 1, | |
| 254 | + unit_type: if idr { | |
| 255 | + ec_h264_syntax::nal::NalUnitType::SliceIdr | |
| 256 | + } else { | |
| 257 | + ec_h264_syntax::nal::NalUnitType::Slice | |
| 258 | + }, | |
| 259 | + }, | |
| 260 | + &sps, | |
| 261 | + &pps, | |
| 262 | + ) | |
| 263 | + .expect("slice header parses"); | |
| 264 | + assert_eq!(header.first_mb_in_slice, first_mb); | |
| 265 | + assert_eq!(header.slice_type, slice_type); | |
| 266 | + assert!(header.all_slices_same_type); | |
| 267 | + assert_eq!(header.frame_num, 7); | |
| 268 | + assert_eq!(header.slice_qp, qp); | |
| 269 | + } | |
| 270 | + } | |
| 271 | +} |
crates/ec-h264/src/enc/mb.rsadded+1332 -0
| @@ -0,0 +1,1332 @@ | ||
| 1 | +//! Macroblock coding: mode decision, quantisation, reconstruction and syntax. | |
| 2 | +//! | |
| 3 | +//! Reconstruction here is the decoder's own: prediction comes from | |
| 4 | +//! [`crate::pred`] and [`crate::inter`], dequantisation and the inverse | |
| 5 | +//! transforms from [`crate::transform`], and the metadata every block writes | |
| 6 | +//! into [`crate::dpb::Picture`] is what the decoder writes at the same point. | |
| 7 | +//! The encoder therefore cannot drift from the decoder by construction — the | |
| 8 | +//! only thing it adds is the *choice* of mode and the forward quantiser. | |
| 9 | + | |
| 10 | +// A block index is simultaneously a bitstream position, a geometry key | |
| 11 | +// (BLK4_POS) and a grid coordinate here, exactly as in the decoder; iterating | |
| 12 | +// the arrays instead would hide which geometry each loop names. | |
| 13 | +#![allow(clippy::needless_range_loop)] | |
| 14 | + | |
| 15 | +use ec_core::BitWriter; | |
| 16 | +use ec_h264_syntax::SliceType; | |
| 17 | +use wide::i16x16; | |
| 18 | + | |
| 19 | +use crate::decoder::{MbNeighbors, chroma_nz_pair, gather_nbr4, luma_nz_pair, mb_neighbors}; | |
| 20 | +use crate::dpb::{BLK_SKIP, Picture}; | |
| 21 | +use crate::entropy::{FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP}; | |
| 22 | +use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma}; | |
| 23 | +use crate::mv::{MvCtx, predict_mv, write_block, write_intra_mb, write_mvd}; | |
| 24 | +use crate::pred::{PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; | |
| 25 | +use crate::tables::{BLK4_POS, CHROMA_QP}; | |
| 26 | +use crate::transform::{ | |
| 27 | + LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform, | |
| 28 | + unzigzag, unzigzag_ac15, | |
| 29 | +}; | |
| 30 | + | |
| 31 | +use super::quant::{ | |
| 32 | + forward_4x4, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_chroma_dc, | |
| 33 | + quant_luma_dc, | |
| 34 | +}; | |
| 35 | +use super::vlc::{write_cbp, write_residual_block}; | |
| 36 | + | |
| 37 | +/// Speed/quality ladder. Two rungs, because the two the incumbent exposed are | |
| 38 | +/// the two edith actually picks between. | |
| 39 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | |
| 40 | +pub enum Preset { | |
| 41 | + /// Diamond motion search, 16x16 partitions, intra 4x4 in I pictures only. | |
| 42 | + #[default] | |
| 43 | + Fast, | |
| 44 | + /// Wider search with a hexagon refinement and intra 4x4 everywhere. | |
| 45 | + Balanced, | |
| 46 | +} | |
| 47 | + | |
| 48 | +/// Source planes of one picture, edge-padded out to whole macroblocks. | |
| 49 | +pub(crate) struct Source { | |
| 50 | + pub y: Vec<u8>, | |
| 51 | + pub u: Vec<u8>, | |
| 52 | + pub v: Vec<u8>, | |
| 53 | + /// Luma row pitch, equal to the coded width. | |
| 54 | + pub stride: usize, | |
| 55 | + /// Chroma row pitch. | |
| 56 | + pub c_stride: usize, | |
| 57 | +} | |
| 58 | + | |
| 59 | +/// Everything one macroblock's coding reads and updates. | |
| 60 | +pub(crate) struct MbEnc<'a> { | |
| 61 | + pub src: &'a Source, | |
| 62 | + /// The single list-0 reference, absent in an I slice. | |
| 63 | + pub reference: Option<&'a Picture>, | |
| 64 | + pub slice_type: SliceType, | |
| 65 | + pub slice_id: u16, | |
| 66 | + /// QPY of the previous macroblock: the prediction chain of 7.4.5. | |
| 67 | + pub qp: i32, | |
| 68 | + /// What rate control wants this macroblock coded at. | |
| 69 | + pub target_qp: i32, | |
| 70 | + /// Lagrangian multiplier in the SATD domain. | |
| 71 | + pub lambda: i32, | |
| 72 | + pub preset: Preset, | |
| 73 | + /// Macroblocks skipped since the last coded one (`mb_skip_run`, 7.3.4). | |
| 74 | + pub skip_run: u32, | |
| 75 | + pub ls: LevelScale4x4, | |
| 76 | +} | |
| 77 | + | |
| 78 | +/// Quantised levels of one macroblock, scan order per block. | |
| 79 | +#[derive(Default)] | |
| 80 | +struct Levels { | |
| 81 | + /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16. | |
| 82 | + luma: [[i32; 16]; 16], | |
| 83 | + /// Non-zero count per luma block, Z-order. | |
| 84 | + luma_nz: [u8; 16], | |
| 85 | + /// Intra_16x16 luma DC, scan order. | |
| 86 | + dc: [i32; 16], | |
| 87 | + /// Chroma DC per component. | |
| 88 | + chroma_dc: [[i32; 16]; 2], | |
| 89 | + /// Chroma AC per component and block. | |
| 90 | + chroma: [[[i32; 16]; 4]; 2], | |
| 91 | + chroma_nz: [[u8; 4]; 2], | |
| 92 | + cbp_luma: u8, | |
| 93 | + cbp_chroma: u8, | |
| 94 | +} | |
| 95 | + | |
| 96 | +/// 4x4 Hadamard sum of absolute transformed differences between the source at | |
| 97 | +/// `(sx, sy)` and a 4x4 prediction. | |
| 98 | +fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 { | |
| 99 | + let mut d = [0i32; 16]; | |
| 100 | + for y in 0..4 { | |
| 101 | + for x in 0..4 { | |
| 102 | + d[y * 4 + x] = | |
| 103 | + i32::from(src[(sy + y) * sstride + sx + x]) - i32::from(pred[y * pstride + x]); | |
| 104 | + } | |
| 105 | + } | |
| 106 | + for i in 0..4 { | |
| 107 | + let o = i * 4; | |
| 108 | + let (a, b, c, e) = (d[o], d[o + 1], d[o + 2], d[o + 3]); | |
| 109 | + let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e); | |
| 110 | + d[o] = s0 + s1; | |
| 111 | + d[o + 1] = s0 - s1; | |
| 112 | + d[o + 2] = s2 + s3; | |
| 113 | + d[o + 3] = s2 - s3; | |
| 114 | + } | |
| 115 | + let mut sum = 0; | |
| 116 | + for j in 0..4 { | |
| 117 | + let (a, b, c, e) = (d[j], d[4 + j], d[8 + j], d[12 + j]); | |
| 118 | + let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e); | |
| 119 | + sum += (s0 + s1).abs() + (s0 - s1).abs() + (s2 + s3).abs() + (s2 - s3).abs(); | |
| 120 | + } | |
| 121 | + (sum + 2) >> 2 | |
| 122 | +} | |
| 123 | + | |
| 124 | +/// SATD of a whole 16x16 luma macroblock against the prediction already in the | |
| 125 | +/// picture plane. | |
| 126 | +fn satd16( | |
| 127 | + src: &[u8], | |
| 128 | + sstride: usize, | |
| 129 | + sx: usize, | |
| 130 | + sy: usize, | |
| 131 | + plane: &[u8], | |
| 132 | + pstride: usize, | |
| 133 | + po: usize, | |
| 134 | +) -> i32 { | |
| 135 | + let mut sum = 0; | |
| 136 | + for by in 0..4 { | |
| 137 | + for bx in 0..4 { | |
| 138 | + sum += satd4( | |
| 139 | + src, | |
| 140 | + sstride, | |
| 141 | + sx + bx * 4, | |
| 142 | + sy + by * 4, | |
| 143 | + &plane[po + by * 4 * pstride + bx * 4..], | |
| 144 | + pstride, | |
| 145 | + ); | |
| 146 | + } | |
| 147 | + } | |
| 148 | + sum | |
| 149 | +} | |
| 150 | + | |
| 151 | +#[allow(clippy::too_many_arguments)] | |
| 152 | +/// Sum of absolute differences of a 16x16 macroblock against a prediction of | |
| 153 | +/// any pitch, sixteen samples at a time: this is the motion search's inner | |
| 154 | +/// loop and nothing else in the encoder is called as often. | |
| 155 | +fn sad16( | |
| 156 | + src: &[u8], | |
| 157 | + sstride: usize, | |
| 158 | + sx: usize, | |
| 159 | + sy: usize, | |
| 160 | + pred: &[u8], | |
| 161 | + po: usize, | |
| 162 | + pstride: usize, | |
| 163 | +) -> i32 { | |
| 164 | + let mut acc = i16x16::ZERO; | |
| 165 | + for row in 0..16 { | |
| 166 | + let a = load16(src, (sy + row) * sstride + sx); | |
| 167 | + let b = load16(pred, po + row * pstride); | |
| 168 | + acc += (a - b).abs(); | |
| 169 | + } | |
| 170 | + let lanes = acc.to_array(); | |
| 171 | + lanes.iter().map(|&v| i32::from(v)).sum() | |
| 172 | +} | |
| 173 | + | |
| 174 | +/// Sixteen samples widened to 16-bit lanes; the tail past the slice is zero, | |
| 175 | +/// which only a caller reading past the plane could reach. | |
| 176 | +#[inline] | |
| 177 | +fn load16(data: &[u8], at: usize) -> i16x16 { | |
| 178 | + let mut a = [0i16; 16]; | |
| 179 | + if let Some(row) = data.get(at..at + 16) { | |
| 180 | + for (o, &b) in a.iter_mut().zip(row) { | |
| 181 | + *o = i16::from(b); | |
| 182 | + } | |
| 183 | + } | |
| 184 | + i16x16::from(a) | |
| 185 | +} | |
| 186 | + | |
| 187 | +/// Sum of absolute differences of a `w` x `h` block against a prediction with | |
| 188 | +/// its own pitch. | |
| 189 | +#[allow(clippy::too_many_arguments)] | |
| 190 | +fn sad( | |
| 191 | + src: &[u8], | |
| 192 | + sstride: usize, | |
| 193 | + sx: usize, | |
| 194 | + sy: usize, | |
| 195 | + pred: &[u8], | |
| 196 | + pstride: usize, | |
| 197 | + w: usize, | |
| 198 | + h: usize, | |
| 199 | +) -> i32 { | |
| 200 | + let mut sum = 0; | |
| 201 | + for y in 0..h { | |
| 202 | + let s = &src[(sy + y) * sstride + sx..]; | |
| 203 | + let p = &pred[y * pstride..]; | |
| 204 | + for x in 0..w { | |
| 205 | + sum += (i32::from(s[x]) - i32::from(p[x])).abs(); | |
| 206 | + } | |
| 207 | + } | |
| 208 | + sum | |
| 209 | +} | |
| 210 | + | |
| 211 | +/// Bits an exp-Golomb `se(v)` costs, for the motion-vector cost term. | |
| 212 | +#[inline] | |
| 213 | +pub(crate) fn se_bits(v: i32) -> i32 { | |
| 214 | + let k = if v > 0 { 2 * v - 1 } else { -2 * v } as u32; | |
| 215 | + (32 - (k + 1).leading_zeros()) as i32 * 2 - 1 | |
| 216 | +} | |
| 217 | + | |
| 218 | +/// Chroma QP of a luma QP under a zero `chroma_qp_index_offset`. | |
| 219 | +#[inline] | |
| 220 | +fn chroma_qp(qp: i32) -> i32 { | |
| 221 | + i32::from(CHROMA_QP[qp.clamp(0, 51) as usize]) | |
| 222 | +} | |
| 223 | + | |
| 224 | +/// Which intra 4x4 modes the available neighbours allow (8.3.1.2). | |
| 225 | +fn modes_allowed(have_top: bool, have_left: bool, have_tl: bool) -> [bool; 9] { | |
| 226 | + [ | |
| 227 | + have_top, | |
| 228 | + have_left, | |
| 229 | + true, | |
| 230 | + have_top, | |
| 231 | + have_top && have_left && have_tl, | |
| 232 | + have_top && have_left && have_tl, | |
| 233 | + have_top && have_left && have_tl, | |
| 234 | + have_top, | |
| 235 | + have_left, | |
| 236 | + ] | |
| 237 | +} | |
| 238 | + | |
| 239 | +/// Code one macroblock: decide its mode, reconstruct it into `pic` and write | |
| 240 | +/// its syntax into `w`. | |
| 241 | +pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut BitWriter, mb_addr: usize) { | |
| 242 | + let mb_x = mb_addr % pic.mb_w; | |
| 243 | + let mb_y = mb_addr / pic.mb_w; | |
| 244 | + let nbr = mb_neighbors(pic, mb_x, mb_y, e.slice_id); | |
| 245 | + | |
| 246 | + // Clear this macroblock's motion state, as the decoder does before parsing. | |
| 247 | + let w4 = pic.mb_w * 4; | |
| 248 | + for py in 0..4 { | |
| 249 | + let base = (mb_y * 4 + py) * w4 + mb_x * 4; | |
| 250 | + for idx in base..base + 4 { | |
| 251 | + pic.mv[idx] = [[0; 2]; 2]; | |
| 252 | + pic.ref_idx[idx] = [-1; 2]; | |
| 253 | + pic.ref_id[idx] = [-1; 2]; | |
| 254 | + pic.mvd_abs[idx] = [0; 4]; | |
| 255 | + pic.blk[idx] = 0; | |
| 256 | + } | |
| 257 | + } | |
| 258 | + | |
| 259 | + let mut inter: Option<InterChoice> = None; | |
| 260 | + if e.slice_type == SliceType::P { | |
| 261 | + inter = Some(choose_inter(pic, e, mb_x, mb_y)); | |
| 262 | + } | |
| 263 | + | |
| 264 | + // Intra cost against the inter one: a P macroblock goes intra only when it | |
| 265 | + // is clearly cheaper, because an intra macroblock in a P picture also costs | |
| 266 | + // the next picture's prediction quality. Skipping the intra trial when the | |
| 267 | + // inter cost is already low was measured and dropped: it cost 0.7 dB on | |
| 268 | + // screen capture and bought no measurable time. | |
| 269 | + let intra_cost = intra_pre_cost(pic, e, &nbr, mb_x, mb_y); | |
| 270 | + let go_intra = match &inter { | |
| 271 | + None => true, | |
| 272 | + Some(i) => intra_cost.best() + e.lambda * 8 < i.cost, | |
| 273 | + }; | |
| 274 | + | |
| 275 | + if go_intra { | |
| 276 | + encode_intra_mb(pic, e, w, mb_addr, nbr, intra_cost); | |
| 277 | + } else { | |
| 278 | + let choice = inter.expect("a P macroblock has an inter choice"); | |
| 279 | + encode_inter_mb(pic, e, w, mb_addr, nbr, choice); | |
| 280 | + } | |
| 281 | +} | |
| 282 | + | |
| 283 | +/// The intra decision taken before any reconstruction: best Intra_16x16 mode, | |
| 284 | +/// and whether the 4x4 modes look cheaper. | |
| 285 | +struct IntraCost { | |
| 286 | + i16_mode: u8, | |
| 287 | + i16_cost: i32, | |
| 288 | + i4_cost: i32, | |
| 289 | + /// True when Intra_4x4 is allowed at all for this picture and preset. | |
| 290 | + allow_i4: bool, | |
| 291 | +} | |
| 292 | + | |
| 293 | +impl IntraCost { | |
| 294 | + fn best(&self) -> i32 { | |
| 295 | + if self.allow_i4 { | |
| 296 | + self.i16_cost.min(self.i4_cost) | |
| 297 | + } else { | |
| 298 | + self.i16_cost | |
| 299 | + } | |
| 300 | + } | |
| 301 | + | |
| 302 | + fn use_i4(&self) -> bool { | |
| 303 | + self.allow_i4 && self.i4_cost < self.i16_cost | |
| 304 | + } | |
| 305 | +} | |
| 306 | + | |
| 307 | +/// Estimate both intra costs. The 4x4 estimate predicts from the *source* | |
| 308 | +/// samples inside the macroblock (they are written into the plane first), which | |
| 309 | +/// is the standard approximation: reconstruction is not available until the | |
| 310 | +/// mode is chosen, and the two differ by less than the decision margin. | |
| 311 | +fn intra_pre_cost( | |
| 312 | + pic: &mut Picture, | |
| 313 | + e: &MbEnc<'_>, | |
| 314 | + nbr: &MbNeighbors, | |
| 315 | + mb_x: usize, | |
| 316 | + mb_y: usize, | |
| 317 | +) -> IntraCost { | |
| 318 | + let (sx, sy) = (mb_x * 16, mb_y * 16); | |
| 319 | + let stride = pic.y.stride; | |
| 320 | + let origin = pic.y.at(sx, sy); | |
| 321 | + let mut best = (i32::MAX, 2u8); | |
| 322 | + for mode in [2u8, 0, 1, 3] { | |
| 323 | + let ok = match mode { | |
| 324 | + 0 => nbr.b, | |
| 325 | + 1 => nbr.a, | |
| 326 | + 3 => nbr.a && nbr.b && nbr.d, | |
| 327 | + _ => true, | |
| 328 | + }; | |
| 329 | + if !ok { | |
| 330 | + continue; | |
| 331 | + } | |
| 332 | + let mut win = PlaneWindow { | |
| 333 | + data: &mut pic.y.data, | |
| 334 | + stride, | |
| 335 | + origin, | |
| 336 | + }; | |
| 337 | + pred_16x16(mode, &mut win, nbr.b, nbr.a); | |
| 338 | + let cost = satd16(&e.src.y, e.src.stride, sx, sy, &pic.y.data, stride, origin); | |
| 339 | + if cost < best.0 { | |
| 340 | + best = (cost, mode); | |
| 341 | + } | |
| 342 | + } | |
| 343 | + | |
| 344 | + let allow_i4 = e.slice_type == SliceType::I || e.preset == Preset::Balanced; | |
| 345 | + let mut i4_cost = i32::MAX; | |
| 346 | + if allow_i4 { | |
| 347 | + // Source samples stand in for the not-yet-reconstructed neighbours. | |
| 348 | + for y in 0..16 { | |
| 349 | + let dst = origin + y * stride; | |
| 350 | + let s = (sy + y) * e.src.stride + sx; | |
| 351 | + pic.y.data[dst..dst + 16].copy_from_slice(&e.src.y[s..s + 16]); | |
| 352 | + } | |
| 353 | + let mut sum = 0; | |
| 354 | + for blk in 0..16 { | |
| 355 | + let (dx, dy) = BLK4_POS[blk]; | |
| 356 | + let (x, y) = (sx + dx as usize * 4, sy + dy as usize * 4); | |
| 357 | + let n = gather_nbr4(pic, nbr, blk, x, y); | |
| 358 | + let have_tl = match (dx, dy) { | |
| 359 | + (0, 0) => nbr.d, | |
| 360 | + (0, _) => nbr.a, | |
| 361 | + (_, 0) => nbr.b, | |
| 362 | + _ => true, | |
| 363 | + }; | |
| 364 | + let allowed = modes_allowed(n.have_top, n.have_left, have_tl); | |
| 365 | + let mut best4 = i32::MAX; | |
| 366 | + let mut p = [0u8; 16]; | |
| 367 | + for mode in 0..9u8 { | |
| 368 | + if !allowed[mode as usize] { | |
| 369 | + continue; | |
| 370 | + } | |
| 371 | + pred_4x4(mode, &n, &mut p); | |
| 372 | + let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + e.lambda * 3; | |
| 373 | + best4 = best4.min(c); | |
| 374 | + } | |
| 375 | + sum += best4; | |
| 376 | + } | |
| 377 | + // Sixteen mode signals and a coded_block_pattern the 16x16 form does | |
| 378 | + // not pay for. | |
| 379 | + i4_cost = sum + e.lambda * 16; | |
| 380 | + } | |
| 381 | + IntraCost { | |
| 382 | + i16_mode: best.1, | |
| 383 | + i16_cost: best.0, | |
| 384 | + i4_cost, | |
| 385 | + allow_i4, | |
| 386 | + } | |
| 387 | +} | |
| 388 | + | |
| 389 | +/// The inter decision for a P macroblock. | |
| 390 | +struct InterChoice { | |
| 391 | + mv: [i16; 2], | |
| 392 | + mvp: [i16; 2], | |
| 393 | + /// The P_Skip motion vector of 8.4.1.1. | |
| 394 | + skip_mv: [i16; 2], | |
| 395 | + cost: i32, | |
| 396 | + /// The skip candidate is at least as good as the searched one. | |
| 397 | + prefer_skip: bool, | |
| 398 | +} | |
| 399 | + | |
| 400 | +/// Motion search plus the skip candidate. | |
| 401 | +fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> InterChoice { | |
| 402 | + let reference = e.reference.expect("a P slice has a reference"); | |
| 403 | + let ctx = MvCtx { | |
| 404 | + mb_x, | |
| 405 | + mb_y, | |
| 406 | + slice_id: e.slice_id, | |
| 407 | + written: 0, | |
| 408 | + }; | |
| 409 | + let n = ctx.neighbours(pic, 0, 0, 4, 0); | |
| 410 | + let mvp = predict_mv(&n, 0, 4, 4, 0); | |
| 411 | + // P_Skip (8.4.1.1): zero when either neighbour is missing or is itself a | |
| 412 | + // zero-motion reference-0 partition. | |
| 413 | + let a = ctx.at(pic, mb_x as i32 * 4 - 1, mb_y as i32 * 4, 0); | |
| 414 | + let b = ctx.at(pic, mb_x as i32 * 4, mb_y as i32 * 4 - 1, 0); | |
| 415 | + let zero = |nb: &crate::mv::Nb| nb.ref_idx == 0 && nb.mv == [0, 0]; | |
| 416 | + let skip_mv = if !a.avail || !b.avail || zero(&a) || zero(&b) { | |
| 417 | + [0, 0] | |
| 418 | + } else { | |
| 419 | + mvp | |
| 420 | + }; | |
| 421 | + | |
| 422 | + let plane = RefPlane { | |
| 423 | + data: &reference.y.data, | |
| 424 | + stride: reference.y.stride, | |
| 425 | + origin: reference.y.origin, | |
| 426 | + width: reference.y.width, | |
| 427 | + height: reference.y.height, | |
| 428 | + pad: reference.y.pad, | |
| 429 | + }; | |
| 430 | + let (sx, sy) = (mb_x * 16, mb_y * 16); | |
| 431 | + let mut buf = [0u8; 256]; | |
| 432 | + let sw = e.src.stride; | |
| 433 | + // Whole-sample candidates read the reference plane in place; only the | |
| 434 | + // sub-sample refinement pays for interpolation. The search runs on SAD, | |
| 435 | + // which is what a search can afford; the winner is re-costed on SATD below | |
| 436 | + // because the intra candidates are SATD and the two scales differ. | |
| 437 | + let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 { | |
| 438 | + let bits = e.lambda | |
| 439 | + * (se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1]))) | |
| 440 | + / 2; | |
| 441 | + if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 { | |
| 442 | + let o = integer_origin( | |
| 443 | + &plane, | |
| 444 | + sx as i32 + (mv[0] >> 2) as i32, | |
| 445 | + sy as i32 + (mv[1] >> 2) as i32, | |
| 446 | + 16, | |
| 447 | + 16, | |
| 448 | + ); | |
| 449 | + return sad16(&e.src.y, sw, sx, sy, plane.data, o, plane.stride) + bits; | |
| 450 | + } | |
| 451 | + mc_luma(&plane, sx as i32, sy as i32, mv, 16, 16, 16, &mut buf); | |
| 452 | + let d = if satd { | |
| 453 | + satd16(&e.src.y, sw, sx, sy, &buf, 16, 0) | |
| 454 | + } else { | |
| 455 | + sad16(&e.src.y, sw, sx, sy, &buf, 0, 16) | |
| 456 | + }; | |
| 457 | + d + bits | |
| 458 | + }; | |
| 459 | + | |
| 460 | + // Candidates: the predictor, the skip vector, zero, and the vectors of the | |
| 461 | + // neighbouring partitions. | |
| 462 | + let mut best = ([0i16; 2], i32::MAX); | |
| 463 | + for cand in [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv] { | |
| 464 | + let c = cost_of(cand, false); | |
| 465 | + if c < best.1 { | |
| 466 | + best = (cand, c); | |
| 467 | + } | |
| 468 | + } | |
| 469 | + // A macroblock the prediction already fits is not searched further: on real | |
| 470 | + // content most of them are, and the search is the encoder's hot loop. | |
| 471 | + // A macroblock the prediction already fits within half a level a sample is | |
| 472 | + // not searched further: on real content most of them are, and this doubles | |
| 473 | + // the encoder's speed for 0.2 dB (measured, 1080p screen capture; camera | |
| 474 | + // content shows no loss at all). | |
| 475 | + const GOOD_ENOUGH: i32 = 16 * 16 / 2; | |
| 476 | + if best.1 > GOOD_ENOUGH { | |
| 477 | + // Diamond refinement at whole samples, coarse to fine. | |
| 478 | + let range = match e.preset { | |
| 479 | + Preset::Fast => 16i16, | |
| 480 | + Preset::Balanced => 48, | |
| 481 | + }; | |
| 482 | + let mut step = 4i16 * 4; // four whole samples, in quarter units | |
| 483 | + while step >= 4 { | |
| 484 | + let mut improved = true; | |
| 485 | + while improved { | |
| 486 | + improved = false; | |
| 487 | + for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] { | |
| 488 | + let cand = [best.0[0] + dx, best.0[1] + dy]; | |
| 489 | + if (cand[0] - mvp[0]).abs() > range * 4 || (cand[1] - mvp[1]).abs() > range * 4 | |
| 490 | + { | |
| 491 | + continue; | |
| 492 | + } | |
| 493 | + let c = cost_of(cand, false); | |
| 494 | + if c < best.1 { | |
| 495 | + best = (cand, c); | |
| 496 | + improved = true; | |
| 497 | + } | |
| 498 | + } | |
| 499 | + } | |
| 500 | + step /= 2; | |
| 501 | + } | |
| 502 | + // Half then quarter sample. | |
| 503 | + for step in [2i16, 1] { | |
| 504 | + let mut improved = true; | |
| 505 | + while improved { | |
| 506 | + improved = false; | |
| 507 | + for (dx, dy) in [ | |
| 508 | + (step, 0), | |
| 509 | + (-step, 0), | |
| 510 | + (0, step), | |
| 511 | + (0, -step), | |
| 512 | + (step, step), | |
| 513 | + (-step, -step), | |
| 514 | + (step, -step), | |
| 515 | + (-step, step), | |
| 516 | + ] { | |
| 517 | + let cand = [best.0[0] + dx, best.0[1] + dy]; | |
| 518 | + let c = cost_of(cand, false); | |
| 519 | + if c < best.1 { | |
| 520 | + best = (cand, c); | |
| 521 | + improved = true; | |
| 522 | + } | |
| 523 | + } | |
| 524 | + if e.preset == Preset::Fast { | |
| 525 | + break; | |
| 526 | + } | |
| 527 | + } | |
| 528 | + } | |
| 529 | + } | |
| 530 | + | |
| 531 | + // Re-cost both candidates on SATD for the comparison against intra, and | |
| 532 | + // for the skip decision (which trades a whole macroblock of bits). | |
| 533 | + let searched = cost_of(best.0, true); | |
| 534 | + let skip_cost = cost_of(skip_mv, true) - e.lambda * 4; | |
| 535 | + InterChoice { | |
| 536 | + mv: best.0, | |
| 537 | + mvp, | |
| 538 | + skip_mv, | |
| 539 | + cost: searched.min(skip_cost), | |
| 540 | + prefer_skip: skip_cost <= searched, | |
| 541 | + } | |
| 542 | +} | |
| 543 | + | |
| 544 | +/// Motion-compensate a whole macroblock into the picture planes. | |
| 545 | +fn compensate_mb(pic: &mut Picture, reference: &Picture, mb_x: usize, mb_y: usize, mv: [i16; 2]) { | |
| 546 | + let (x0, y0) = ((mb_x * 16) as i32, (mb_y * 16) as i32); | |
| 547 | + let plane = RefPlane { | |
| 548 | + data: &reference.y.data, | |
| 549 | + stride: reference.y.stride, | |
| 550 | + origin: reference.y.origin, | |
| 551 | + width: reference.y.width, | |
| 552 | + height: reference.y.height, | |
| 553 | + pad: reference.y.pad, | |
| 554 | + }; | |
| 555 | + let stride = pic.y.stride; | |
| 556 | + let origin = pic.y.at(mb_x * 16, mb_y * 16); | |
| 557 | + mc_luma( | |
| 558 | + &plane, | |
| 559 | + x0, | |
| 560 | + y0, | |
| 561 | + mv, | |
| 562 | + 16, | |
| 563 | + 16, | |
| 564 | + stride, | |
| 565 | + &mut pic.y.data[origin..], | |
| 566 | + ); | |
| 567 | + for comp in 0..2 { | |
| 568 | + let src = if comp == 0 { | |
| 569 | + &reference.cb | |
| 570 | + } else { | |
| 571 | + &reference.cr | |
| 572 | + }; | |
| 573 | + let plane = RefPlane { | |
| 574 | + data: &src.data, | |
| 575 | + stride: src.stride, | |
| 576 | + origin: src.origin, | |
| 577 | + width: src.width, | |
| 578 | + height: src.height, | |
| 579 | + pad: src.pad, | |
| 580 | + }; | |
| 581 | + let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; | |
| 582 | + let stride = dst.stride; | |
| 583 | + let origin = dst.at(mb_x * 8, mb_y * 8); | |
| 584 | + mc_chroma( | |
| 585 | + &plane, | |
| 586 | + x0 / 2, | |
| 587 | + y0 / 2, | |
| 588 | + mv, | |
| 589 | + 8, | |
| 590 | + 8, | |
| 591 | + stride, | |
| 592 | + &mut dst.data[origin..], | |
| 593 | + ); | |
| 594 | + } | |
| 595 | +} | |
| 596 | + | |
| 597 | +/// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock, | |
| 598 | +/// prediction already in the plane. | |
| 599 | +fn code_luma_4x4( | |
| 600 | + pic: &mut Picture, | |
| 601 | + e: &MbEnc<'_>, | |
| 602 | + mb_x: usize, | |
| 603 | + mb_y: usize, | |
| 604 | + qp: i32, | |
| 605 | + intra: bool, | |
| 606 | + lv: &mut Levels, | |
| 607 | +) { | |
| 608 | + let stride = pic.y.stride; | |
| 609 | + for blk in 0..16 { | |
| 610 | + let (dx, dy) = BLK4_POS[blk]; | |
| 611 | + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); | |
| 612 | + let origin = pic.y.at(x, y); | |
| 613 | + let mut d = [0i32; 16]; | |
| 614 | + for ry in 0..4 { | |
| 615 | + for rx in 0..4 { | |
| 616 | + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) | |
| 617 | + - i32::from(pic.y.data[origin + ry * stride + rx]); | |
| 618 | + } | |
| 619 | + } | |
| 620 | + forward_4x4(&mut d); | |
| 621 | + let nz = quant_4x4(&d, qp, intra, false, &mut lv.luma[blk]); | |
| 622 | + lv.luma_nz[blk] = nz; | |
| 623 | + if nz > 0 { | |
| 624 | + lv.cbp_luma |= 1 << (blk >> 2); | |
| 625 | + let mut raster = [0i32; 16]; | |
| 626 | + unzigzag(&lv.luma[blk], &mut raster); | |
| 627 | + dequant_4x4(&mut raster, &e.ls, qp, false); | |
| 628 | + let mut resid = [0i32; 16]; | |
| 629 | + inverse_transform_4x4(&raster, &mut resid); | |
| 630 | + add_residual_4x4(&mut pic.y.data, stride, origin, &resid); | |
| 631 | + } | |
| 632 | + } | |
| 633 | +} | |
| 634 | + | |
| 635 | +/// The Intra_16x16 luma path (8.5.10 in reverse then forward again). | |
| 636 | +fn code_luma_i16( | |
| 637 | + pic: &mut Picture, | |
| 638 | + e: &MbEnc<'_>, | |
| 639 | + mb_x: usize, | |
| 640 | + mb_y: usize, | |
| 641 | + qp: i32, | |
| 642 | + lv: &mut Levels, | |
| 643 | +) { | |
| 644 | + let stride = pic.y.stride; | |
| 645 | + let mut dc = [0i32; 16]; | |
| 646 | + let mut ac = [[0i32; 16]; 16]; | |
| 647 | + for blk in 0..16 { | |
| 648 | + let (dx, dy) = BLK4_POS[blk]; | |
| 649 | + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); | |
| 650 | + let origin = pic.y.at(x, y); | |
| 651 | + let mut d = [0i32; 16]; | |
| 652 | + for ry in 0..4 { | |
| 653 | + for rx in 0..4 { | |
| 654 | + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) | |
| 655 | + - i32::from(pic.y.data[origin + ry * stride + rx]); | |
| 656 | + } | |
| 657 | + } | |
| 658 | + forward_4x4(&mut d); | |
| 659 | + dc[dy as usize * 4 + dx as usize] = d[0]; | |
| 660 | + let nz = quant_4x4(&d, qp, true, true, &mut lv.luma[blk]); | |
| 661 | + lv.luma_nz[blk] = nz; | |
| 662 | + ac[blk] = lv.luma[blk]; | |
| 663 | + if nz > 0 { | |
| 664 | + lv.cbp_luma = 15; | |
| 665 | + } | |
| 666 | + } | |
| 667 | + if lv.cbp_luma == 0 { | |
| 668 | + for blk in 0..16 { | |
| 669 | + lv.luma[blk] = [0; 16]; | |
| 670 | + lv.luma_nz[blk] = 0; | |
| 671 | + } | |
| 672 | + } | |
| 673 | + forward_hadamard_4x4(&mut dc); | |
| 674 | + quant_luma_dc(&dc, qp, &mut lv.dc); | |
| 675 | + | |
| 676 | + // Reconstruct exactly as the decoder does: DC through 8.5.10, then each | |
| 677 | + // block's AC with the DC substituted at raster position 0. | |
| 678 | + let mut raster = [0i32; 16]; | |
| 679 | + unzigzag(&lv.dc, &mut raster); | |
| 680 | + luma_dc_transform(&mut raster, &e.ls, qp); | |
| 681 | + let dc_recon = raster; | |
| 682 | + for blk in 0..16 { | |
| 683 | + let (dx, dy) = BLK4_POS[blk]; | |
| 684 | + let dc_blk = dc_recon[dy as usize * 4 + dx as usize]; | |
| 685 | + let tc = lv.luma_nz[blk]; | |
| 686 | + if tc == 0 && dc_blk == 0 { | |
| 687 | + continue; | |
| 688 | + } | |
| 689 | + let mut raster = [0i32; 16]; | |
| 690 | + if tc > 0 { | |
| 691 | + unzigzag_ac15(&ac[blk], &mut raster); | |
| 692 | + dequant_4x4(&mut raster, &e.ls, qp, true); | |
| 693 | + } | |
| 694 | + raster[0] = dc_blk; | |
| 695 | + let mut resid = [0i32; 16]; | |
| 696 | + inverse_transform_4x4(&raster, &mut resid); | |
| 697 | + let origin = pic | |
| 698 | + .y | |
| 699 | + .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); | |
| 700 | + add_residual_4x4(&mut pic.y.data, stride, origin, &resid); | |
| 701 | + } | |
| 702 | +} | |
| 703 | + | |
| 704 | +/// Chroma residual for both components (8.5.11 + the AC path). | |
| 705 | +fn code_chroma( | |
| 706 | + pic: &mut Picture, | |
| 707 | + e: &MbEnc<'_>, | |
| 708 | + mb_x: usize, | |
| 709 | + mb_y: usize, | |
| 710 | + qp_y: i32, | |
| 711 | + intra: bool, | |
| 712 | + lv: &mut Levels, | |
| 713 | +) { | |
| 714 | + let qp_c = chroma_qp(qp_y); | |
| 715 | + let mut dc_lists = [[0i32; 4]; 2]; | |
| 716 | + let mut ac = [[[0i32; 16]; 4]; 2]; | |
| 717 | + let mut any_ac = false; | |
| 718 | + for comp in 0..2 { | |
| 719 | + let (plane, src) = if comp == 0 { | |
| 720 | + (&pic.cb, &e.src.u) | |
| 721 | + } else { | |
| 722 | + (&pic.cr, &e.src.v) | |
| 723 | + }; | |
| 724 | + let stride = plane.stride; | |
| 725 | + for blk in 0..4 { | |
| 726 | + let (x, y) = (mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4); | |
| 727 | + let origin = plane.at(x, y); | |
| 728 | + let mut d = [0i32; 16]; | |
| 729 | + for ry in 0..4 { | |
| 730 | + for rx in 0..4 { | |
| 731 | + d[ry * 4 + rx] = i32::from(src[(y + ry) * e.src.c_stride + x + rx]) | |
| 732 | + - i32::from(plane.data[origin + ry * stride + rx]); | |
| 733 | + } | |
| 734 | + } | |
| 735 | + forward_4x4(&mut d); | |
| 736 | + dc_lists[comp][blk] = d[0]; | |
| 737 | + let nz = quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk]); | |
| 738 | + lv.chroma_nz[comp][blk] = nz; | |
| 739 | + if nz > 0 { | |
| 740 | + any_ac = true; | |
| 741 | + } | |
| 742 | + } | |
| 743 | + } | |
| 744 | + let mut any_dc = false; | |
| 745 | + for comp in 0..2 { | |
| 746 | + forward_hadamard_2x2(&mut dc_lists[comp]); | |
| 747 | + let nz = quant_chroma_dc(&dc_lists[comp], qp_c, intra, &mut lv.chroma_dc[comp]); | |
| 748 | + if nz > 0 { | |
| 749 | + any_dc = true; | |
| 750 | + } | |
| 751 | + } | |
| 752 | + lv.cbp_chroma = if any_ac { | |
| 753 | + 2 | |
| 754 | + } else if any_dc { | |
| 755 | + 1 | |
| 756 | + } else { | |
| 757 | + 0 | |
| 758 | + }; | |
| 759 | + if lv.cbp_chroma < 2 { | |
| 760 | + lv.chroma_nz = [[0; 4]; 2]; | |
| 761 | + } else { | |
| 762 | + lv.chroma = ac; | |
| 763 | + } | |
| 764 | + if lv.cbp_chroma == 0 { | |
| 765 | + return; | |
| 766 | + } | |
| 767 | + for comp in 0..2 { | |
| 768 | + let mut dc = [ | |
| 769 | + lv.chroma_dc[comp][0], | |
| 770 | + lv.chroma_dc[comp][1], | |
| 771 | + lv.chroma_dc[comp][2], | |
| 772 | + lv.chroma_dc[comp][3], | |
| 773 | + ]; | |
| 774 | + chroma_dc_transform_420(&mut dc, &e.ls, qp_c); | |
| 775 | + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; | |
| 776 | + let stride = plane.stride; | |
| 777 | + for blk in 0..4 { | |
| 778 | + let tc = lv.chroma_nz[comp][blk]; | |
| 779 | + if tc == 0 && dc[blk] == 0 { | |
| 780 | + continue; | |
| 781 | + } | |
| 782 | + let mut raster = [0i32; 16]; | |
| 783 | + if tc > 0 { | |
| 784 | + unzigzag_ac15(&lv.chroma[comp][blk], &mut raster); | |
| 785 | + dequant_4x4(&mut raster, &e.ls, qp_c, true); | |
| 786 | + } | |
| 787 | + raster[0] = dc[blk]; | |
| 788 | + let mut resid = [0i32; 16]; | |
| 789 | + inverse_transform_4x4(&raster, &mut resid); | |
| 790 | + let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4); | |
| 791 | + add_residual_4x4(&mut plane.data, stride, origin, &resid); | |
| 792 | + } | |
| 793 | + } | |
| 794 | +} | |
| 795 | + | |
| 796 | +/// Pick the chroma prediction mode by SATD, leaving the winner in the planes. | |
| 797 | +fn choose_chroma_mode( | |
| 798 | + pic: &mut Picture, | |
| 799 | + e: &MbEnc<'_>, | |
| 800 | + nbr: &MbNeighbors, | |
| 801 | + mb_x: usize, | |
| 802 | + mb_y: usize, | |
| 803 | +) -> u8 { | |
| 804 | + let mut best = (i32::MAX, 0u8); | |
| 805 | + for mode in [0u8, 1, 2, 3] { | |
| 806 | + let ok = match mode { | |
| 807 | + 1 => nbr.a, | |
| 808 | + 2 => nbr.b, | |
| 809 | + 3 => nbr.a && nbr.b && nbr.d, | |
| 810 | + _ => true, | |
| 811 | + }; | |
| 812 | + if !ok { | |
| 813 | + continue; | |
| 814 | + } | |
| 815 | + let mut cost = 0; | |
| 816 | + for comp in 0..2 { | |
| 817 | + let (plane, src) = if comp == 0 { | |
| 818 | + (&mut pic.cb, &e.src.u) | |
| 819 | + } else { | |
| 820 | + (&mut pic.cr, &e.src.v) | |
| 821 | + }; | |
| 822 | + let stride = plane.stride; | |
| 823 | + let origin = plane.at(mb_x * 8, mb_y * 8); | |
| 824 | + let mut win = PlaneWindow { | |
| 825 | + data: &mut plane.data, | |
| 826 | + stride, | |
| 827 | + origin, | |
| 828 | + }; | |
| 829 | + pred_chroma_8x8(mode, &mut win, nbr.b, nbr.a); | |
| 830 | + cost += sad( | |
| 831 | + src, | |
| 832 | + e.src.c_stride, | |
| 833 | + mb_x * 8, | |
| 834 | + mb_y * 8, | |
| 835 | + &plane.data[origin..], | |
| 836 | + stride, | |
| 837 | + 8, | |
| 838 | + 8, | |
| 839 | + ); | |
| 840 | + } | |
| 841 | + if cost < best.0 { | |
| 842 | + best = (cost, mode); | |
| 843 | + } | |
| 844 | + } | |
| 845 | + // Leave the chosen mode's prediction in place. | |
| 846 | + for comp in 0..2 { | |
| 847 | + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; | |
| 848 | + let stride = plane.stride; | |
| 849 | + let origin = plane.at(mb_x * 8, mb_y * 8); | |
| 850 | + let mut win = PlaneWindow { | |
| 851 | + data: &mut plane.data, | |
| 852 | + stride, | |
| 853 | + origin, | |
| 854 | + }; | |
| 855 | + pred_chroma_8x8(best.1, &mut win, nbr.b, nbr.a); | |
| 856 | + } | |
| 857 | + best.1 | |
| 858 | +} | |
| 859 | + | |
| 860 | +/// Code an intra macroblock, Intra_16x16 or Intra_4x4. | |
| 861 | +fn encode_intra_mb( | |
| 862 | + pic: &mut Picture, | |
| 863 | + e: &mut MbEnc<'_>, | |
| 864 | + w: &mut BitWriter, | |
| 865 | + mb_addr: usize, | |
| 866 | + nbr: MbNeighbors, | |
| 867 | + cost: IntraCost, | |
| 868 | +) { | |
| 869 | + let mb_x = mb_addr % pic.mb_w; | |
| 870 | + let mb_y = mb_addr / pic.mb_w; | |
| 871 | + let w4 = pic.mb_w * 4; | |
| 872 | + let (bx0, by0) = (mb_x * 4, mb_y * 4); | |
| 873 | + let qp = e.target_qp; | |
| 874 | + write_intra_mb(pic, mb_x, mb_y); | |
| 875 | + let mut lv = Levels::default(); | |
| 876 | + let use_i4 = cost.use_i4(); | |
| 877 | + let mut modes = [2u8; 16]; | |
| 878 | + let mut pred_modes = [2u8; 16]; | |
| 879 | + | |
| 880 | + if use_i4 { | |
| 881 | + // Per block: choose the mode against reconstructed neighbours, then | |
| 882 | + // reconstruct it immediately — the next block predicts from it. | |
| 883 | + for blk in 0..16 { | |
| 884 | + let (dx, dy) = BLK4_POS[blk]; | |
| 885 | + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); | |
| 886 | + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); | |
| 887 | + let left_avail = if dx == 0 { nbr.a } else { true }; | |
| 888 | + let top_avail = if dy == 0 { nbr.b } else { true }; | |
| 889 | + let predicted = if left_avail && top_avail { | |
| 890 | + pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx]) | |
| 891 | + } else { | |
| 892 | + 2 | |
| 893 | + }; | |
| 894 | + pred_modes[blk] = predicted; | |
| 895 | + let n = gather_nbr4(pic, &nbr, blk, x, y); | |
| 896 | + let have_tl = match (dx, dy) { | |
| 897 | + (0, 0) => nbr.d, | |
| 898 | + (0, _) => nbr.a, | |
| 899 | + (_, 0) => nbr.b, | |
| 900 | + _ => true, | |
| 901 | + }; | |
| 902 | + let allowed = modes_allowed(n.have_top, n.have_left, have_tl); | |
| 903 | + let mut best = (i32::MAX, predicted.min(2)); | |
| 904 | + let mut p = [0u8; 16]; | |
| 905 | + for mode in 0..9u8 { | |
| 906 | + if !allowed[mode as usize] { | |
| 907 | + continue; | |
| 908 | + } | |
| 909 | + pred_4x4(mode, &n, &mut p); | |
| 910 | + let bits = if mode == predicted { 1 } else { 4 }; | |
| 911 | + let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + e.lambda * bits; | |
| 912 | + if c < best.0 { | |
| 913 | + best = (c, mode); | |
| 914 | + } | |
| 915 | + } | |
| 916 | + let mode = best.1; | |
| 917 | + modes[blk] = mode; | |
| 918 | + pic.i4_modes[by * w4 + bx] = mode; | |
| 919 | + // Prediction into the plane, then residual and reconstruction. | |
| 920 | + pred_4x4(mode, &n, &mut p); | |
| 921 | + let stride = pic.y.stride; | |
| 922 | + let origin = pic.y.at(x, y); | |
| 923 | + for ry in 0..4 { | |
| 924 | + let row = origin + ry * stride; | |
| 925 | + pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); | |
| 926 | + } | |
| 927 | + let mut d = [0i32; 16]; | |
| 928 | + for ry in 0..4 { | |
| 929 | + for rx in 0..4 { | |
| 930 | + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) | |
| 931 | + - i32::from(p[ry * 4 + rx]); | |
| 932 | + } | |
| 933 | + } | |
| 934 | + forward_4x4(&mut d); | |
| 935 | + let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]); | |
| 936 | + lv.luma_nz[blk] = nz; | |
| 937 | + if nz > 0 { | |
| 938 | + lv.cbp_luma |= 1 << (blk >> 2); | |
| 939 | + let mut raster = [0i32; 16]; | |
| 940 | + unzigzag(&lv.luma[blk], &mut raster); | |
| 941 | + dequant_4x4(&mut raster, &e.ls, qp, false); | |
| 942 | + let mut resid = [0i32; 16]; | |
| 943 | + inverse_transform_4x4(&raster, &mut resid); | |
| 944 | + add_residual_4x4(&mut pic.y.data, stride, origin, &resid); | |
| 945 | + } | |
| 946 | + } | |
| 947 | + } else { | |
| 948 | + for dy in 0..4 { | |
| 949 | + let base = (by0 + dy) * w4 + bx0; | |
| 950 | + pic.i4_modes[base..base + 4].fill(2); | |
| 951 | + } | |
| 952 | + let stride = pic.y.stride; | |
| 953 | + let origin = pic.y.at(mb_x * 16, mb_y * 16); | |
| 954 | + let mut win = PlaneWindow { | |
| 955 | + data: &mut pic.y.data, | |
| 956 | + stride, | |
| 957 | + origin, | |
| 958 | + }; | |
| 959 | + pred_16x16(cost.i16_mode, &mut win, nbr.b, nbr.a); | |
| 960 | + code_luma_i16(pic, e, mb_x, mb_y, qp, &mut lv); | |
| 961 | + } | |
| 962 | + | |
| 963 | + let chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y); | |
| 964 | + code_chroma(pic, e, mb_x, mb_y, qp, true, &mut lv); | |
| 965 | + | |
| 966 | + // ---- syntax ---- | |
| 967 | + if e.slice_type == SliceType::P { | |
| 968 | + w.write_ue(e.skip_run); | |
| 969 | + e.skip_run = 0; | |
| 970 | + } | |
| 971 | + let intra_type = if use_i4 { | |
| 972 | + 0 | |
| 973 | + } else { | |
| 974 | + 1 + u32::from(cost.i16_mode) | |
| 975 | + + 4 * u32::from(lv.cbp_chroma) | |
| 976 | + + if lv.cbp_luma != 0 { 12 } else { 0 } | |
| 977 | + }; | |
| 978 | + let offset = if e.slice_type == SliceType::P { 5 } else { 0 }; | |
| 979 | + w.write_ue(intra_type + offset); | |
| 980 | + if use_i4 { | |
| 981 | + for blk in 0..16 { | |
| 982 | + if modes[blk] == pred_modes[blk] { | |
| 983 | + w.write_bit(true); | |
| 984 | + } else { | |
| 985 | + w.write_bit(false); | |
| 986 | + let rem = if modes[blk] > pred_modes[blk] { | |
| 987 | + modes[blk] - 1 | |
| 988 | + } else { | |
| 989 | + modes[blk] | |
| 990 | + }; | |
| 991 | + w.write_bits(u32::from(rem), 3); | |
| 992 | + } | |
| 993 | + } | |
| 994 | + } | |
| 995 | + w.write_ue(u32::from(chroma_mode)); | |
| 996 | + if use_i4 { | |
| 997 | + write_cbp(w, lv.cbp_luma, lv.cbp_chroma, true); | |
| 998 | + } | |
| 999 | + finish_mb( | |
| 1000 | + pic, | |
| 1001 | + e, | |
| 1002 | + w, | |
| 1003 | + mb_addr, | |
| 1004 | + &nbr, | |
| 1005 | + &lv, | |
| 1006 | + MbRecord { | |
| 1007 | + intra: true, | |
| 1008 | + is_i16: !use_i4, | |
| 1009 | + chroma_mode, | |
| 1010 | + qp, | |
| 1011 | + }, | |
| 1012 | + ); | |
| 1013 | +} | |
| 1014 | + | |
| 1015 | +/// Squared error of the whole macroblock against the source, luma and chroma: | |
| 1016 | +/// the distortion term of the skip decision. | |
| 1017 | +fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { | |
| 1018 | + let mut sum = 0i64; | |
| 1019 | + let stride = pic.y.stride; | |
| 1020 | + let origin = pic.y.at(mb_x * 16, mb_y * 16); | |
| 1021 | + for row in 0..16 { | |
| 1022 | + let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16; | |
| 1023 | + for x in 0..16 { | |
| 1024 | + let d = i64::from(e.src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]); | |
| 1025 | + sum += d * d; | |
| 1026 | + } | |
| 1027 | + } | |
| 1028 | + for comp in 0..2 { | |
| 1029 | + let (plane, src) = if comp == 0 { | |
| 1030 | + (&pic.cb, &e.src.u) | |
| 1031 | + } else { | |
| 1032 | + (&pic.cr, &e.src.v) | |
| 1033 | + }; | |
| 1034 | + let stride = plane.stride; | |
| 1035 | + let origin = plane.at(mb_x * 8, mb_y * 8); | |
| 1036 | + for row in 0..8 { | |
| 1037 | + let s = (mb_y * 8 + row) * e.src.c_stride + mb_x * 8; | |
| 1038 | + for x in 0..8 { | |
| 1039 | + let d = i64::from(src[s + x]) - i64::from(plane.data[origin + row * stride + x]); | |
| 1040 | + sum += d * d; | |
| 1041 | + } | |
| 1042 | + } | |
| 1043 | + } | |
| 1044 | + sum | |
| 1045 | +} | |
| 1046 | + | |
| 1047 | +/// Rough bit cost of a macroblock's residual, for the skip decision: a level | |
| 1048 | +/// costs its magnitude's exp-Golomb-ish width, a coded block its token. | |
| 1049 | +fn estimate_bits(lv: &Levels) -> i64 { | |
| 1050 | + let mut bits = 10i64; | |
| 1051 | + let block = |b: &[i32]| -> i64 { | |
| 1052 | + let mut n = 0i64; | |
| 1053 | + for &l in b { | |
| 1054 | + if l != 0 { | |
| 1055 | + n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1; | |
| 1056 | + } | |
| 1057 | + } | |
| 1058 | + if n > 0 { n + 6 } else { 2 } | |
| 1059 | + }; | |
| 1060 | + for blk in 0..16 { | |
| 1061 | + if lv.cbp_luma & (1 << (blk >> 2)) != 0 { | |
| 1062 | + bits += block(&lv.luma[blk]); | |
| 1063 | + } | |
| 1064 | + } | |
| 1065 | + if lv.cbp_chroma != 0 { | |
| 1066 | + for comp in 0..2 { | |
| 1067 | + bits += block(&lv.chroma_dc[comp][..4]); | |
| 1068 | + if lv.cbp_chroma == 2 { | |
| 1069 | + for blk in 0..4 { | |
| 1070 | + bits += block(&lv.chroma[comp][blk][..15]); | |
| 1071 | + } | |
| 1072 | + } | |
| 1073 | + } | |
| 1074 | + } | |
| 1075 | + bits | |
| 1076 | +} | |
| 1077 | + | |
| 1078 | +/// Lagrangian multiplier in the squared-error domain, paired with | |
| 1079 | +/// [`super::lambda_for`] in the SATD one. | |
| 1080 | +fn lambda_ssd(qp: i32) -> f64 { | |
| 1081 | + 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() | |
| 1082 | +} | |
| 1083 | + | |
| 1084 | +/// Code a P macroblock: skip, or one 16x16 partition. | |
| 1085 | +fn encode_inter_mb( | |
| 1086 | + pic: &mut Picture, | |
| 1087 | + e: &mut MbEnc<'_>, | |
| 1088 | + w: &mut BitWriter, | |
| 1089 | + mb_addr: usize, | |
| 1090 | + nbr: MbNeighbors, | |
| 1091 | + choice: InterChoice, | |
| 1092 | +) { | |
| 1093 | + let mb_x = mb_addr % pic.mb_w; | |
| 1094 | + let mb_y = mb_addr / pic.mb_w; | |
| 1095 | + let reference = e.reference.expect("a P macroblock has a reference"); | |
| 1096 | + let ref_id = reference.id; | |
| 1097 | + let qp = e.target_qp; | |
| 1098 | + let mv = if choice.prefer_skip { | |
| 1099 | + choice.skip_mv | |
| 1100 | + } else { | |
| 1101 | + choice.mv | |
| 1102 | + }; | |
| 1103 | + | |
| 1104 | + compensate_mb(pic, reference, mb_x, mb_y, mv); | |
| 1105 | + // Skipping is only *available* on the P_Skip vector, and only worth taking | |
| 1106 | + // when the residual it drops is worth less than the bits it saves: on | |
| 1107 | + // static content a macroblock whose residual is pure quantisation churn | |
| 1108 | + // costs bits every picture and improves nothing. | |
| 1109 | + let may_skip = mv == choice.skip_mv; | |
| 1110 | + let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y)); | |
| 1111 | + let mut lv = Levels::default(); | |
| 1112 | + code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); | |
| 1113 | + code_chroma(pic, e, mb_x, mb_y, qp, false, &mut lv); | |
| 1114 | + let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0; | |
| 1115 | + let skip = match ssd_skip { | |
| 1116 | + None => false, | |
| 1117 | + Some(_) if empty => true, | |
| 1118 | + Some(ssd_skip) => { | |
| 1119 | + let coded = | |
| 1120 | + ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64; | |
| 1121 | + if ssd_skip as f64 <= coded { | |
| 1122 | + // Put the prediction back: the residual has been added to it. | |
| 1123 | + compensate_mb(pic, reference, mb_x, mb_y, mv); | |
| 1124 | + true | |
| 1125 | + } else { | |
| 1126 | + false | |
| 1127 | + } | |
| 1128 | + } | |
| 1129 | + }; | |
| 1130 | + | |
| 1131 | + let mut ctx = MvCtx { | |
| 1132 | + mb_x, | |
| 1133 | + mb_y, | |
| 1134 | + slice_id: e.slice_id, | |
| 1135 | + written: 0, | |
| 1136 | + }; | |
| 1137 | + let w4 = pic.mb_w * 4; | |
| 1138 | + if skip { | |
| 1139 | + for py in 0..4 { | |
| 1140 | + for px in 0..4 { | |
| 1141 | + write_block( | |
| 1142 | + pic, | |
| 1143 | + &mut ctx, | |
| 1144 | + px, | |
| 1145 | + py, | |
| 1146 | + [mv, [0, 0]], | |
| 1147 | + [0, -1], | |
| 1148 | + [ref_id, -1], | |
| 1149 | + BLK_SKIP, | |
| 1150 | + ); | |
| 1151 | + } | |
| 1152 | + } | |
| 1153 | + for dy in 0..4 { | |
| 1154 | + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; | |
| 1155 | + pic.nz_y[base..base + 4].fill(0); | |
| 1156 | + pic.i4_modes[base..base + 4].fill(2); | |
| 1157 | + } | |
| 1158 | + for comp in 0..2 { | |
| 1159 | + for dy in 0..2 { | |
| 1160 | + let base = (mb_y * 2 + dy) * pic.mb_w * 2 + mb_x * 2; | |
| 1161 | + pic.nz_c[comp][base..base + 2].fill(0); | |
| 1162 | + } | |
| 1163 | + } | |
| 1164 | + pic.mb_qp[mb_addr] = e.qp as u8; | |
| 1165 | + pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_INTER | FLAG_SKIP; | |
| 1166 | + pic.mb_cbp[mb_addr] = 0; | |
| 1167 | + pic.mb_dc_cbf[mb_addr] = 0; | |
| 1168 | + pic.mb_slice[mb_addr] = e.slice_id; | |
| 1169 | + pic.decoded_mbs += 1; | |
| 1170 | + e.skip_run += 1; | |
| 1171 | + return; | |
| 1172 | + } | |
| 1173 | + | |
| 1174 | + let mvd = [mv[0] - choice.mvp[0], mv[1] - choice.mvp[1]]; | |
| 1175 | + for py in 0..4 { | |
| 1176 | + for px in 0..4 { | |
| 1177 | + write_block( | |
| 1178 | + pic, | |
| 1179 | + &mut ctx, | |
| 1180 | + px, | |
| 1181 | + py, | |
| 1182 | + [mv, [0, 0]], | |
| 1183 | + [0, -1], | |
| 1184 | + [ref_id, -1], | |
| 1185 | + 0, | |
| 1186 | + ); | |
| 1187 | + write_mvd(pic, mb_x, mb_y, px, py, 0, mvd); | |
| 1188 | + } | |
| 1189 | + } | |
| 1190 | + for dy in 0..4 { | |
| 1191 | + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; | |
| 1192 | + pic.i4_modes[base..base + 4].fill(2); | |
| 1193 | + } | |
| 1194 | + | |
| 1195 | + // ---- syntax ---- | |
| 1196 | + w.write_ue(e.skip_run); | |
| 1197 | + e.skip_run = 0; | |
| 1198 | + w.write_ue(0); // mb_type P_L0_16x16 | |
| 1199 | + // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded. | |
| 1200 | + w.write_se(i32::from(mvd[0])); | |
| 1201 | + w.write_se(i32::from(mvd[1])); | |
| 1202 | + write_cbp(w, lv.cbp_luma, lv.cbp_chroma, false); | |
| 1203 | + finish_mb( | |
| 1204 | + pic, | |
| 1205 | + e, | |
| 1206 | + w, | |
| 1207 | + mb_addr, | |
| 1208 | + &nbr, | |
| 1209 | + &lv, | |
| 1210 | + MbRecord { | |
| 1211 | + intra: false, | |
| 1212 | + is_i16: false, | |
| 1213 | + chroma_mode: 0, | |
| 1214 | + qp, | |
| 1215 | + }, | |
| 1216 | + ); | |
| 1217 | +} | |
| 1218 | + | |
| 1219 | +/// What the residual writer needs to know about the macroblock it closes. | |
| 1220 | +struct MbRecord { | |
| 1221 | + intra: bool, | |
| 1222 | + is_i16: bool, | |
| 1223 | + chroma_mode: u8, | |
| 1224 | + /// The QP the residual was quantised at. | |
| 1225 | + qp: i32, | |
| 1226 | +} | |
| 1227 | + | |
| 1228 | +/// mb_qp_delta, the residual blocks and the per-macroblock metadata: the | |
| 1229 | +/// writing half of [`crate::decoder::finish_macroblock`]. | |
| 1230 | +fn finish_mb( | |
| 1231 | + pic: &mut Picture, | |
| 1232 | + e: &mut MbEnc<'_>, | |
| 1233 | + w: &mut BitWriter, | |
| 1234 | + mb_addr: usize, | |
| 1235 | + nbr: &MbNeighbors, | |
| 1236 | + lv: &Levels, | |
| 1237 | + m: MbRecord, | |
| 1238 | +) { | |
| 1239 | + let mb_x = mb_addr % pic.mb_w; | |
| 1240 | + let mb_y = mb_addr / pic.mb_w; | |
| 1241 | + let w4 = pic.mb_w * 4; | |
| 1242 | + let w2 = pic.mb_w * 2; | |
| 1243 | + let (bx0, by0) = (mb_x * 4, mb_y * 4); | |
| 1244 | + let (cx0, cy0) = (mb_x * 2, mb_y * 2); | |
| 1245 | + | |
| 1246 | + let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || m.is_i16; | |
| 1247 | + let qp_y = if coded { | |
| 1248 | + w.write_se(m.qp - e.qp); | |
| 1249 | + e.qp = m.qp; | |
| 1250 | + m.qp | |
| 1251 | + } else { | |
| 1252 | + // No residual: the QP prediction chain is untouched (7.4.5), and the | |
| 1253 | + // deblocking filter uses the chain value. | |
| 1254 | + e.qp | |
| 1255 | + }; | |
| 1256 | + pic.mb_qp[mb_addr] = qp_y as u8; | |
| 1257 | + pic.mb_flags[mb_addr] = FLAG_DECODED | |
| 1258 | + | if m.is_i16 { FLAG_I16 } else { 0 } | |
| 1259 | + | if m.intra { 0 } else { FLAG_INTER } | |
| 1260 | + | if m.intra && m.chroma_mode != 0 { | |
| 1261 | + FLAG_CHROMA_PRED | |
| 1262 | + } else { | |
| 1263 | + 0 | |
| 1264 | + }; | |
| 1265 | + pic.mb_cbp[mb_addr] = lv.cbp_luma | (lv.cbp_chroma << 4); | |
| 1266 | + pic.mb_slice[mb_addr] = e.slice_id; | |
| 1267 | + pic.decoded_mbs += 1; | |
| 1268 | + | |
| 1269 | + let mut dc_cbf = 0u8; | |
| 1270 | + // Luma DC (Intra_16x16 only), then the luma blocks in Z-order. | |
| 1271 | + if m.is_i16 { | |
| 1272 | + let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0); | |
| 1273 | + let nc = nc_of(na, nb); | |
| 1274 | + let tc = write_residual_block(w, &lv.dc, 16, nc); | |
| 1275 | + dc_cbf |= u8::from(tc != 0); | |
| 1276 | + } | |
| 1277 | + for blk in 0..16 { | |
| 1278 | + let (dx, dy) = BLK4_POS[blk]; | |
| 1279 | + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); | |
| 1280 | + let group = 1 << (blk >> 2); | |
| 1281 | + let coded_block = if m.is_i16 { | |
| 1282 | + lv.cbp_luma != 0 | |
| 1283 | + } else { | |
| 1284 | + lv.cbp_luma & group != 0 | |
| 1285 | + }; | |
| 1286 | + let tc = if coded_block { | |
| 1287 | + let (na, nb) = luma_nz_pair(pic, nbr, bx, by); | |
| 1288 | + let nc = nc_of(na, nb); | |
| 1289 | + let (levels, max) = if m.is_i16 { | |
| 1290 | + (&lv.luma[blk][..15], 15) | |
| 1291 | + } else { | |
| 1292 | + (&lv.luma[blk][..16], 16) | |
| 1293 | + }; | |
| 1294 | + write_residual_block(w, levels, max, nc) | |
| 1295 | + } else { | |
| 1296 | + 0 | |
| 1297 | + }; | |
| 1298 | + pic.nz_y[by * w4 + bx] = tc; | |
| 1299 | + } | |
| 1300 | + // Chroma DC then chroma AC, in bitstream order. | |
| 1301 | + if lv.cbp_chroma != 0 { | |
| 1302 | + for comp in 0..2 { | |
| 1303 | + let tc = write_residual_block(w, &lv.chroma_dc[comp][..4], 4, -1); | |
| 1304 | + dc_cbf |= u8::from(tc != 0) << (1 + comp); | |
| 1305 | + } | |
| 1306 | + } | |
| 1307 | + for comp in 0..2 { | |
| 1308 | + for blk in 0..4 { | |
| 1309 | + let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); | |
| 1310 | + let tc = if lv.cbp_chroma == 2 { | |
| 1311 | + let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy); | |
| 1312 | + let nc = nc_of(na, nb); | |
| 1313 | + write_residual_block(w, &lv.chroma[comp][blk][..15], 15, nc) | |
| 1314 | + } else { | |
| 1315 | + 0 | |
| 1316 | + }; | |
| 1317 | + pic.nz_c[comp][cy * w2 + cx] = tc; | |
| 1318 | + } | |
| 1319 | + } | |
| 1320 | + pic.mb_dc_cbf[mb_addr] = dc_cbf; | |
| 1321 | +} | |
| 1322 | + | |
| 1323 | +/// nC from the two neighbouring non-zero counts (9.2.1). | |
| 1324 | +#[inline] | |
| 1325 | +fn nc_of(na: Option<u8>, nb: Option<u8>) -> i32 { | |
| 1326 | + match (na, nb) { | |
| 1327 | + (Some(a), Some(b)) => (i32::from(a) + i32::from(b) + 1) >> 1, | |
| 1328 | + (Some(a), None) => i32::from(a), | |
| 1329 | + (None, Some(b)) => i32::from(b), | |
| 1330 | + (None, None) => 0, | |
| 1331 | + } | |
| 1332 | +} |
crates/ec-h264/src/enc/mod.rsadded+657 -0
| @@ -0,0 +1,657 @@ | ||
| 1 | +//! The H.264 encoder: I and P pictures, CAVLC, 8-bit 4:2:0 progressive. | |
| 2 | +//! | |
| 3 | +//! # Shared reconstruction | |
| 4 | +//! | |
| 5 | +//! There is no second reconstruction path here. Prediction, dequantisation, | |
| 6 | +//! the inverse transforms and the deblocking filter are the decoder's own | |
| 7 | +//! modules, and the encoder fills the very same [`Picture`] the decoder fills, | |
| 8 | +//! macroblock metadata included. Encoder and decoder therefore agree on every | |
| 9 | +//! reconstructed sample by construction, not by testing — the tests only check | |
| 10 | +//! that nothing broke the property. | |
| 11 | +//! | |
| 12 | +//! # Parallelism | |
| 13 | +//! | |
| 14 | +//! A picture is cut into one slice per worker, each slice a band of whole | |
| 15 | +//! macroblock rows. A slice is independent by definition (no prediction | |
| 16 | +//! crosses its boundary), so each worker owns a private picture buffer, writes | |
| 17 | +//! its own bitstream and never reads another worker's samples; motion | |
| 18 | +//! compensation reads the *previous* picture, which is finished and immutable. | |
| 19 | +//! The bands are stitched together afterwards and the deblocking filter runs | |
| 20 | +//! once over the whole picture, across slice boundaries exactly as a decoder | |
| 21 | +//! runs it. No `unsafe`, no shared mutable state at all. | |
| 22 | + | |
| 23 | +mod headers; | |
| 24 | +mod mb; | |
| 25 | +mod quant; | |
| 26 | +mod rc; | |
| 27 | +mod vlc; | |
| 28 | + | |
| 29 | +use ec_core::BitWriter; | |
| 30 | +use ec_core::error::{Error, Result}; | |
| 31 | +use ec_h264_syntax::nal::{NalUnitType, escape_rbsp}; | |
| 32 | +use ec_h264_syntax::{SliceType, Sps}; | |
| 33 | + | |
| 34 | +use crate::decoder::deblock_picture; | |
| 35 | +use crate::dpb::{Picture, SliceParams as DeblockParams}; | |
| 36 | +use crate::transform::LevelScale4x4; | |
| 37 | + | |
| 38 | +use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps}; | |
| 39 | +use mb::{MbEnc, Source, encode_mb}; | |
| 40 | +use rc::RateControl; | |
| 41 | + | |
| 42 | +pub use mb::Preset; | |
| 43 | + | |
| 44 | +/// Encoder settings. | |
| 45 | +#[derive(Debug, Clone)] | |
| 46 | +pub struct EncoderConfig { | |
| 47 | + /// Displayed luma width; must be even. | |
| 48 | + pub width: u32, | |
| 49 | + /// Displayed luma height; must be even. | |
| 50 | + pub height: u32, | |
| 51 | + /// Frames per second, for the VUI timing and the bit budget. | |
| 52 | + pub framerate: f32, | |
| 53 | + /// Target bits per second. Zero means constant quantiser ([`Self::qp`]). | |
| 54 | + pub bitrate: u32, | |
| 55 | + /// Pictures between IDR pictures; 1 codes every picture as an IDR. | |
| 56 | + pub gop_size: u32, | |
| 57 | + /// Consecutive B pictures. Only 0 is coded today (see the crate note); | |
| 58 | + /// a non-zero value is accepted and coded as 0 rather than refused. | |
| 59 | + pub bframes: u32, | |
| 60 | + /// Speed/quality rung. | |
| 61 | + pub preset: Preset, | |
| 62 | + /// Worker threads, which is also the number of slices per picture; 0 means | |
| 63 | + /// as many as the machine has. | |
| 64 | + pub threads: usize, | |
| 65 | + /// Quantiser for constant-QP mode (`bitrate` zero). | |
| 66 | + pub qp: i32, | |
| 67 | +} | |
| 68 | + | |
| 69 | +impl EncoderConfig { | |
| 70 | + /// Defaults for `width x height`: 30 fps, constant QP 26, every core. | |
| 71 | + pub fn new(width: u32, height: u32) -> EncoderConfig { | |
| 72 | + EncoderConfig { | |
| 73 | + width, | |
| 74 | + height, | |
| 75 | + framerate: 30.0, | |
| 76 | + bitrate: 0, | |
| 77 | + gop_size: 250, | |
| 78 | + bframes: 0, | |
| 79 | + preset: Preset::Fast, | |
| 80 | + threads: 0, | |
| 81 | + qp: 26, | |
| 82 | + } | |
| 83 | + } | |
| 84 | +} | |
| 85 | + | |
| 86 | +/// One coded picture: an Annex-B access unit and what it cost. | |
| 87 | +#[derive(Debug, Clone, Default)] | |
| 88 | +pub struct EncodedPicture { | |
| 89 | + /// The access unit, with 4-byte start codes; parameter sets ride along on | |
| 90 | + /// every IDR so that every IDR is a seek point. | |
| 91 | + pub au: Vec<u8>, | |
| 92 | + /// True when the picture is an IDR. | |
| 93 | + pub key_frame: bool, | |
| 94 | + /// The quantiser the picture was coded at. | |
| 95 | + pub qp: i32, | |
| 96 | +} | |
| 97 | + | |
| 98 | +/// A software H.264 encoder. | |
| 99 | +pub struct Encoder { | |
| 100 | + cfg: EncoderConfig, | |
| 101 | + sps: Sps, | |
| 102 | + sps_nal: Vec<u8>, | |
| 103 | + pps_nal: Vec<u8>, | |
| 104 | + /// The previous reconstruction, which every P picture predicts from. | |
| 105 | + reference: Picture, | |
| 106 | + /// One private picture per worker; worker 0's doubles as the picture the | |
| 107 | + /// other bands are stitched into. | |
| 108 | + workers: Vec<Picture>, | |
| 109 | + src: Source, | |
| 110 | + rc: RateControl, | |
| 111 | + threads: usize, | |
| 112 | + coded_width: usize, | |
| 113 | + coded_height: usize, | |
| 114 | + frames: u64, | |
| 115 | + frame_num: u32, | |
| 116 | + idr_pic_id: u32, | |
| 117 | + next_id: i32, | |
| 118 | + /// True once a reference picture exists. | |
| 119 | + have_reference: bool, | |
| 120 | +} | |
| 121 | + | |
| 122 | +/// A picture handed to the encoder: three planes, no padding assumptions. | |
| 123 | +#[derive(Debug, Clone, Copy)] | |
| 124 | +pub struct PictureView<'a> { | |
| 125 | + pub width: u32, | |
| 126 | + pub height: u32, | |
| 127 | + /// Luma plane, `width` samples per row unless `y_stride` says otherwise. | |
| 128 | + pub y: &'a [u8], | |
| 129 | + pub u: &'a [u8], | |
| 130 | + pub v: &'a [u8], | |
| 131 | + /// Row pitches; zero means "tightly packed". | |
| 132 | + pub y_stride: usize, | |
| 133 | + pub c_stride: usize, | |
| 134 | +} | |
| 135 | + | |
| 136 | +impl<'a> PictureView<'a> { | |
| 137 | + /// A tightly packed I420 picture. | |
| 138 | + pub fn i420(width: u32, height: u32, y: &'a [u8], u: &'a [u8], v: &'a [u8]) -> PictureView<'a> { | |
| 139 | + PictureView { | |
| 140 | + width, | |
| 141 | + height, | |
| 142 | + y, | |
| 143 | + u, | |
| 144 | + v, | |
| 145 | + y_stride: width as usize, | |
| 146 | + c_stride: width.div_ceil(2) as usize, | |
| 147 | + } | |
| 148 | + } | |
| 149 | +} | |
| 150 | + | |
| 151 | +impl Encoder { | |
| 152 | + /// Build an encoder for `cfg`, refusing what it cannot code. | |
| 153 | + pub fn new(cfg: EncoderConfig) -> Result<Encoder> { | |
| 154 | + if cfg.width < 16 || cfg.height < 16 { | |
| 155 | + return Err(Error::unsupported( | |
| 156 | + "picture smaller than one macroblock", | |
| 157 | + "H.264 codes 16x16 macroblocks; encode at 16x16 or larger", | |
| 158 | + )); | |
| 159 | + } | |
| 160 | + if !cfg.width.is_multiple_of(2) || !cfg.height.is_multiple_of(2) { | |
| 161 | + return Err(Error::unsupported( | |
| 162 | + "odd picture dimensions", | |
| 163 | + "4:2:0 chroma is half resolution in both directions, and the \ | |
| 164 | + frame cropping offsets are in two-sample units (7.4.2.1.1); \ | |
| 165 | + encode at even width and height", | |
| 166 | + )); | |
| 167 | + } | |
| 168 | + if cfg.width > 8192 || cfg.height > 8192 { | |
| 169 | + return Err(Error::unsupported( | |
| 170 | + "picture larger than 8192 samples", | |
| 171 | + "no level defines a picture this large for this profile", | |
| 172 | + )); | |
| 173 | + } | |
| 174 | + let mb_w = cfg.width.div_ceil(16); | |
| 175 | + let mb_h = cfg.height.div_ceil(16); | |
| 176 | + let fps = f64::from(cfg.framerate.max(1.0)); | |
| 177 | + // A rational tick close to the requested rate; time_scale is twice the | |
| 178 | + // frame rate for progressive frames (E.2.1). | |
| 179 | + let timing = rational_timing(fps); | |
| 180 | + let seq = SeqParams { | |
| 181 | + width: cfg.width, | |
| 182 | + height: cfg.height, | |
| 183 | + mb_w, | |
| 184 | + mb_h, | |
| 185 | + timing, | |
| 186 | + bitrate: cfg.bitrate, | |
| 187 | + }; | |
| 188 | + let sps_rbsp = write_sps(&seq); | |
| 189 | + let sps = Sps::parse(&sps_rbsp)?; | |
| 190 | + let pps_rbsp = write_pps(); | |
| 191 | + let threads = if cfg.threads == 0 { | |
| 192 | + std::thread::available_parallelism().map_or(1, |n| n.get()) | |
| 193 | + } else { | |
| 194 | + cfg.threads | |
| 195 | + } | |
| 196 | + .clamp(1, mb_h as usize); | |
| 197 | + let workers = (0..threads).map(|_| Picture::default()).collect(); | |
| 198 | + let fixed_qp = (cfg.bitrate == 0).then_some(cfg.qp.clamp(0, 51)); | |
| 199 | + Ok(Encoder { | |
| 200 | + sps_nal: annex_b(NalUnitType::Sps, 3, &sps_rbsp), | |
| 201 | + pps_nal: annex_b(NalUnitType::Pps, 3, &pps_rbsp), | |
| 202 | + sps, | |
| 203 | + reference: Picture::default(), | |
| 204 | + workers, | |
| 205 | + src: Source { | |
| 206 | + y: Vec::new(), | |
| 207 | + u: Vec::new(), | |
| 208 | + v: Vec::new(), | |
| 209 | + stride: mb_w as usize * 16, | |
| 210 | + c_stride: mb_w as usize * 8, | |
| 211 | + }, | |
| 212 | + rc: RateControl::new(cfg.bitrate, fps, cfg.gop_size, fixed_qp), | |
| 213 | + threads, | |
| 214 | + coded_width: mb_w as usize * 16, | |
| 215 | + coded_height: mb_h as usize * 16, | |
| 216 | + frames: 0, | |
| 217 | + frame_num: 0, | |
| 218 | + idr_pic_id: 0, | |
| 219 | + next_id: 0, | |
| 220 | + have_reference: false, | |
| 221 | + cfg, | |
| 222 | + }) | |
| 223 | + } | |
| 224 | + | |
| 225 | + /// The configuration in force. | |
| 226 | + pub fn config(&self) -> &EncoderConfig { | |
| 227 | + &self.cfg | |
| 228 | + } | |
| 229 | + | |
| 230 | + /// The reconstruction of the last coded picture, cropped, as I420 planes. | |
| 231 | + /// This is what a conformant decoder produces for that picture — the tests | |
| 232 | + /// compare it against this crate's decoder and against ffmpeg. | |
| 233 | + pub fn reconstruction(&self) -> Option<(Vec<u8>, Vec<u8>, Vec<u8>)> { | |
| 234 | + if !self.have_reference { | |
| 235 | + return None; | |
| 236 | + } | |
| 237 | + let pic = &self.reference; | |
| 238 | + let (w, h) = (self.cfg.width as usize, self.cfg.height as usize); | |
| 239 | + let mut y = Vec::with_capacity(w * h); | |
| 240 | + for row in 0..h { | |
| 241 | + let o = pic.y.at(0, row); | |
| 242 | + y.extend_from_slice(&pic.y.data[o..o + w]); | |
| 243 | + } | |
| 244 | + let (cw, ch) = (w / 2, h / 2); | |
| 245 | + let mut planes = [Vec::with_capacity(cw * ch), Vec::with_capacity(cw * ch)]; | |
| 246 | + for (comp, out) in planes.iter_mut().enumerate() { | |
| 247 | + let plane = if comp == 0 { &pic.cb } else { &pic.cr }; | |
| 248 | + for row in 0..ch { | |
| 249 | + let o = plane.at(0, row); | |
| 250 | + out.extend_from_slice(&plane.data[o..o + cw]); | |
| 251 | + } | |
| 252 | + } | |
| 253 | + let [u, v] = planes; | |
| 254 | + Some((y, u, v)) | |
| 255 | + } | |
| 256 | + | |
| 257 | + /// Code one picture, in display order, and hand back its access unit. | |
| 258 | + pub fn encode(&mut self, frame: &PictureView<'_>) -> Result<EncodedPicture> { | |
| 259 | + if frame.width != self.cfg.width || frame.height != self.cfg.height { | |
| 260 | + return Err(Error::corrupt("frame size differs from the encoder's")); | |
| 261 | + } | |
| 262 | + self.pad_source(frame)?; | |
| 263 | + let idr = self.cfg.gop_size <= 1 | |
| 264 | + || self | |
| 265 | + .frames | |
| 266 | + .is_multiple_of(u64::from(self.cfg.gop_size.max(1))); | |
| 267 | + let idr = idr || !self.have_reference; | |
| 268 | + let qp = self.rc.frame_qp(idr); | |
| 269 | + if idr { | |
| 270 | + self.frame_num = 0; | |
| 271 | + } | |
| 272 | + let slice_type = if idr { SliceType::I } else { SliceType::P }; | |
| 273 | + | |
| 274 | + let mb_w = self.sps.mb_width as usize; | |
| 275 | + let mb_h = self.sps.mb_height as usize; | |
| 276 | + let bands = split_bands(mb_h, self.threads); | |
| 277 | + let picture_id = self.next_id; | |
| 278 | + self.next_id = self.next_id.wrapping_add(1); | |
| 279 | + | |
| 280 | + // Per-band coding. Every worker owns its picture and its bitstream; | |
| 281 | + // the only shared state is the immutable reference picture and source. | |
| 282 | + let sps = &self.sps; | |
| 283 | + let src = &self.src; | |
| 284 | + let cfg = &self.cfg; | |
| 285 | + let rc = &self.rc; | |
| 286 | + let reference = (!idr).then_some(&self.reference); | |
| 287 | + let frame_num = self.frame_num; | |
| 288 | + let idr_pic_id = self.idr_pic_id; | |
| 289 | + let target = rc.frame_target(idr); | |
| 290 | + let total_mbs = (mb_w * mb_h) as f64; | |
| 291 | + | |
| 292 | + let mut outputs: Vec<Vec<u8>> = Vec::new(); | |
| 293 | + std::thread::scope(|scope| { | |
| 294 | + let mut handles = Vec::with_capacity(bands.len()); | |
| 295 | + for (slice_id, (&(row0, row1), worker)) in | |
| 296 | + bands.iter().zip(self.workers.iter_mut()).enumerate() | |
| 297 | + { | |
| 298 | + handles.push(scope.spawn(move || { | |
| 299 | + worker.start(sps); | |
| 300 | + worker.id = picture_id; | |
| 301 | + let band_mbs = ((row1 - row0) * mb_w) as f64; | |
| 302 | + code_band( | |
| 303 | + worker, | |
| 304 | + BandJob { | |
| 305 | + src, | |
| 306 | + reference, | |
| 307 | + cfg, | |
| 308 | + rc, | |
| 309 | + slice_id: slice_id as u16, | |
| 310 | + slice_type, | |
| 311 | + first_mb: (row0 * mb_w) as u32, | |
| 312 | + rows: (row0, row1), | |
| 313 | + qp, | |
| 314 | + frame_num, | |
| 315 | + idr, | |
| 316 | + idr_pic_id, | |
| 317 | + band_target: target * band_mbs / total_mbs, | |
| 318 | + }, | |
| 319 | + ) | |
| 320 | + })); | |
| 321 | + } | |
| 322 | + for h in handles { | |
| 323 | + outputs.push(h.join().expect("a band worker panicked")); | |
| 324 | + } | |
| 325 | + }); | |
| 326 | + | |
| 327 | + // Stitch the bands into worker 0's picture, then filter the whole | |
| 328 | + // picture the way a decoder does. | |
| 329 | + let (first, rest) = self.workers.split_at_mut(1); | |
| 330 | + let master = &mut first[0]; | |
| 331 | + master.slices.clear(); | |
| 332 | + for _ in 0..bands.len() { | |
| 333 | + master.slices.push(DeblockParams { | |
| 334 | + disable_deblock_idc: 0, | |
| 335 | + alpha_offset: 0, | |
| 336 | + beta_offset: 0, | |
| 337 | + cb_qp_offset: 0, | |
| 338 | + cr_qp_offset: 0, | |
| 339 | + }); | |
| 340 | + } | |
| 341 | + for (band, worker) in bands.iter().skip(1).zip(rest.iter()) { | |
| 342 | + merge_band(master, worker, *band); | |
| 343 | + } | |
| 344 | + deblock_picture(master); | |
| 345 | + master.extend_borders(); | |
| 346 | + master.complete = true; | |
| 347 | + std::mem::swap(master, &mut self.reference); | |
| 348 | + self.have_reference = true; | |
| 349 | + | |
| 350 | + // Assemble the access unit. | |
| 351 | + let mut au = Vec::with_capacity(outputs.iter().map(Vec::len).sum::<usize>() + 64); | |
| 352 | + if idr { | |
| 353 | + au.extend_from_slice(&self.sps_nal); | |
| 354 | + au.extend_from_slice(&self.pps_nal); | |
| 355 | + } | |
| 356 | + let unit = if idr { | |
| 357 | + NalUnitType::SliceIdr | |
| 358 | + } else { | |
| 359 | + NalUnitType::Slice | |
| 360 | + }; | |
| 361 | + for rbsp in &outputs { | |
| 362 | + au.extend_from_slice(&annex_b(unit, 3, rbsp)); | |
| 363 | + } | |
| 364 | + | |
| 365 | + let bits = au.len() as u64 * 8; | |
| 366 | + self.rc.update(idr, qp, bits); | |
| 367 | + self.frames += 1; | |
| 368 | + self.frame_num = (self.frame_num + 1) % (1 << headers::LOG2_MAX_FRAME_NUM); | |
| 369 | + if idr { | |
| 370 | + self.idr_pic_id ^= 1; | |
| 371 | + } | |
| 372 | + Ok(EncodedPicture { | |
| 373 | + au, | |
| 374 | + key_frame: idr, | |
| 375 | + qp, | |
| 376 | + }) | |
| 377 | + } | |
| 378 | + | |
| 379 | + /// Copy the caller's planes into whole-macroblock buffers, replicating the | |
| 380 | + /// edge where the picture does not fill the last macroblock. | |
| 381 | + fn pad_source(&mut self, f: &PictureView<'_>) -> Result<()> { | |
| 382 | + let (w, h) = (f.width as usize, f.height as usize); | |
| 383 | + let (cw, ch) = (w / 2, h / 2); | |
| 384 | + let y_stride = if f.y_stride == 0 { w } else { f.y_stride }; | |
| 385 | + let c_stride = if f.c_stride == 0 { cw } else { f.c_stride }; | |
| 386 | + if f.y.len() < y_stride * (h - 1) + w | |
| 387 | + || f.u.len() < c_stride * (ch - 1) + cw | |
| 388 | + || f.v.len() < c_stride * (ch - 1) + cw | |
| 389 | + { | |
| 390 | + return Err(Error::corrupt("source plane shorter than its stated size")); | |
| 391 | + } | |
| 392 | + pad_plane( | |
| 393 | + &mut self.src.y, | |
| 394 | + f.y, | |
| 395 | + y_stride, | |
| 396 | + w, | |
| 397 | + h, | |
| 398 | + self.coded_width, | |
| 399 | + self.coded_height, | |
| 400 | + ); | |
| 401 | + pad_plane( | |
| 402 | + &mut self.src.u, | |
| 403 | + f.u, | |
| 404 | + c_stride, | |
| 405 | + cw, | |
| 406 | + ch, | |
| 407 | + self.coded_width / 2, | |
| 408 | + self.coded_height / 2, | |
| 409 | + ); | |
| 410 | + pad_plane( | |
| 411 | + &mut self.src.v, | |
| 412 | + f.v, | |
| 413 | + c_stride, | |
| 414 | + cw, | |
| 415 | + ch, | |
| 416 | + self.coded_width / 2, | |
| 417 | + self.coded_height / 2, | |
| 418 | + ); | |
| 419 | + self.src.stride = self.coded_width; | |
| 420 | + self.src.c_stride = self.coded_width / 2; | |
| 421 | + Ok(()) | |
| 422 | + } | |
| 423 | +} | |
| 424 | + | |
| 425 | +/// Everything one band worker needs. | |
| 426 | +struct BandJob<'a> { | |
| 427 | + src: &'a Source, | |
| 428 | + reference: Option<&'a Picture>, | |
| 429 | + cfg: &'a EncoderConfig, | |
| 430 | + rc: &'a RateControl, | |
| 431 | + slice_id: u16, | |
| 432 | + slice_type: SliceType, | |
| 433 | + first_mb: u32, | |
| 434 | + /// Macroblock rows `[start, end)`. | |
| 435 | + rows: (usize, usize), | |
| 436 | + qp: i32, | |
| 437 | + frame_num: u32, | |
| 438 | + idr: bool, | |
| 439 | + idr_pic_id: u32, | |
| 440 | + band_target: f64, | |
| 441 | +} | |
| 442 | + | |
| 443 | +/// Code one slice into its own RBSP. | |
| 444 | +fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> { | |
| 445 | + let mb_w = pic.mb_w; | |
| 446 | + let mut w = BitWriter::with_capacity(4096); | |
| 447 | + write_slice_header( | |
| 448 | + &mut w, | |
| 449 | + &SliceParams { | |
| 450 | + first_mb: job.first_mb, | |
| 451 | + slice_type: job.slice_type, | |
| 452 | + frame_num: job.frame_num, | |
| 453 | + idr: job.idr, | |
| 454 | + idr_pic_id: job.idr_pic_id, | |
| 455 | + qp: job.qp, | |
| 456 | + }, | |
| 457 | + ); | |
| 458 | + let header_bits = w.bit_len(); | |
| 459 | + let mut e = MbEnc { | |
| 460 | + src: job.src, | |
| 461 | + reference: job.reference, | |
| 462 | + slice_type: job.slice_type, | |
| 463 | + slice_id: job.slice_id, | |
| 464 | + qp: job.qp, | |
| 465 | + target_qp: job.qp, | |
| 466 | + lambda: lambda_for(job.qp), | |
| 467 | + preset: job.cfg.preset, | |
| 468 | + skip_run: 0, | |
| 469 | + ls: LevelScale4x4::new(&[16; 16]), | |
| 470 | + }; | |
| 471 | + let rows = job.rows.1 - job.rows.0; | |
| 472 | + for (n, mb_y) in (job.rows.0..job.rows.1).enumerate() { | |
| 473 | + // Row-level rate control: what this band has spent against its | |
| 474 | + // pro-rata budget. | |
| 475 | + if n > 0 { | |
| 476 | + let spent = w.bit_len() - header_bits; | |
| 477 | + let expected = job.band_target * n as f64 / rows as f64; | |
| 478 | + let delta = job.rc.row_delta(spent, expected); | |
| 479 | + e.target_qp = (job.qp + delta).clamp(10, 51); | |
| 480 | + e.lambda = lambda_for(e.target_qp); | |
| 481 | + } | |
| 482 | + for mb_x in 0..mb_w { | |
| 483 | + encode_mb(pic, &mut e, &mut w, mb_y * mb_w + mb_x); | |
| 484 | + } | |
| 485 | + } | |
| 486 | + if job.slice_type == SliceType::P && e.skip_run > 0 { | |
| 487 | + // A slice that ends in skipped macroblocks says so with a final | |
| 488 | + // mb_skip_run; writing one when nothing was skipped would instead tell | |
| 489 | + // the decoder another macroblock follows (7.3.4). | |
| 490 | + w.write_ue(e.skip_run); | |
| 491 | + } | |
| 492 | + headers::trailing(&mut w); | |
| 493 | + w.into_bytes() | |
| 494 | +} | |
| 495 | + | |
| 496 | +/// Lagrangian multiplier for mode decision in the SATD domain. | |
| 497 | +fn lambda_for(qp: i32) -> i32 { | |
| 498 | + // 2^((qp - 12) / 6), the usual ladder, floored at 1. | |
| 499 | + (((f64::from(qp) - 12.0) / 6.0).exp2().round() as i32).max(1) | |
| 500 | +} | |
| 501 | + | |
| 502 | +/// Split `mb_h` macroblock rows into at most `n` contiguous bands. | |
| 503 | +fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> { | |
| 504 | + let n = n.clamp(1, mb_h); | |
| 505 | + let mut out = Vec::with_capacity(n); | |
| 506 | + let mut row = 0; | |
| 507 | + for i in 0..n { | |
| 508 | + let end = (i + 1) * mb_h / n; | |
| 509 | + out.push((row, end)); | |
| 510 | + row = end; | |
| 511 | + } | |
| 512 | + out | |
| 513 | +} | |
| 514 | + | |
| 515 | +/// Copy one band's samples and macroblock metadata from a worker picture into | |
| 516 | +/// the picture the deblocking filter will run over. | |
| 517 | +fn merge_band(dst: &mut Picture, src: &Picture, (row0, row1): (usize, usize)) { | |
| 518 | + let mb_w = dst.mb_w; | |
| 519 | + // Planes. | |
| 520 | + for (d, s, mb_size) in [ | |
| 521 | + (&mut dst.y, &src.y, 16usize), | |
| 522 | + (&mut dst.cb, &src.cb, 8), | |
| 523 | + (&mut dst.cr, &src.cr, 8), | |
| 524 | + ] { | |
| 525 | + let stride = d.stride; | |
| 526 | + let start = d.at(0, row0 * mb_size); | |
| 527 | + let rows = (row1 - row0) * mb_size; | |
| 528 | + let width = d.width; | |
| 529 | + for r in 0..rows { | |
| 530 | + let o = start + r * stride; | |
| 531 | + d.data[o..o + width].copy_from_slice(&s.data[o..o + width]); | |
| 532 | + } | |
| 533 | + } | |
| 534 | + // Per-macroblock arrays. | |
| 535 | + let mb_range = row0 * mb_w..row1 * mb_w; | |
| 536 | + dst.mb_qp[mb_range.clone()].copy_from_slice(&src.mb_qp[mb_range.clone()]); | |
| 537 | + dst.mb_flags[mb_range.clone()].copy_from_slice(&src.mb_flags[mb_range.clone()]); | |
| 538 | + dst.mb_cbp[mb_range.clone()].copy_from_slice(&src.mb_cbp[mb_range.clone()]); | |
| 539 | + dst.mb_dc_cbf[mb_range.clone()].copy_from_slice(&src.mb_dc_cbf[mb_range.clone()]); | |
| 540 | + dst.mb_slice[mb_range.clone()].copy_from_slice(&src.mb_slice[mb_range]); | |
| 541 | + // Per-4x4-block arrays. | |
| 542 | + let b = row0 * 4 * mb_w * 4..row1 * 4 * mb_w * 4; | |
| 543 | + dst.nz_y[b.clone()].copy_from_slice(&src.nz_y[b.clone()]); | |
| 544 | + dst.i4_modes[b.clone()].copy_from_slice(&src.i4_modes[b.clone()]); | |
| 545 | + dst.mv[b.clone()].copy_from_slice(&src.mv[b.clone()]); | |
| 546 | + dst.ref_idx[b.clone()].copy_from_slice(&src.ref_idx[b.clone()]); | |
| 547 | + dst.ref_id[b.clone()].copy_from_slice(&src.ref_id[b.clone()]); | |
| 548 | + dst.mvd_abs[b.clone()].copy_from_slice(&src.mvd_abs[b.clone()]); | |
| 549 | + dst.blk[b.clone()].copy_from_slice(&src.blk[b]); | |
| 550 | + // Per-chroma-block arrays. | |
| 551 | + let c = row0 * 2 * mb_w * 2..row1 * 2 * mb_w * 2; | |
| 552 | + for comp in 0..2 { | |
| 553 | + let (d, s) = (&mut dst.nz_c[comp], &src.nz_c[comp]); | |
| 554 | + d[c.clone()].copy_from_slice(&s[c.clone()]); | |
| 555 | + } | |
| 556 | + dst.decoded_mbs += (row1 - row0) * mb_w; | |
| 557 | +} | |
| 558 | + | |
| 559 | +/// Copy `src` into a `out_w` x `out_h` buffer, replicating the right and | |
| 560 | +/// bottom edges into the padding. | |
| 561 | +fn pad_plane( | |
| 562 | + out: &mut Vec<u8>, | |
| 563 | + src: &[u8], | |
| 564 | + stride: usize, | |
| 565 | + w: usize, | |
| 566 | + h: usize, | |
| 567 | + out_w: usize, | |
| 568 | + out_h: usize, | |
| 569 | +) { | |
| 570 | + out.clear(); | |
| 571 | + out.resize(out_w * out_h, 0); | |
| 572 | + for row in 0..out_h { | |
| 573 | + let sr = row.min(h - 1); | |
| 574 | + let line = &src[sr * stride..sr * stride + w]; | |
| 575 | + let dst = &mut out[row * out_w..row * out_w + out_w]; | |
| 576 | + dst[..w].copy_from_slice(line); | |
| 577 | + if out_w > w { | |
| 578 | + let edge = line[w - 1]; | |
| 579 | + dst[w..].fill(edge); | |
| 580 | + } | |
| 581 | + } | |
| 582 | +} | |
| 583 | + | |
| 584 | +/// Wrap an RBSP as one Annex-B NAL unit with a 4-byte start code. | |
| 585 | +fn annex_b(unit: NalUnitType, ref_idc: u8, rbsp: &[u8]) -> Vec<u8> { | |
| 586 | + let mut out = Vec::with_capacity(rbsp.len() + 8); | |
| 587 | + out.extend_from_slice(&[0, 0, 0, 1]); | |
| 588 | + out.push((ref_idc << 5) | unit_code(unit)); | |
| 589 | + escape_rbsp(rbsp, &mut out); | |
| 590 | + out | |
| 591 | +} | |
| 592 | + | |
| 593 | +/// `nal_unit_type` of the units this encoder emits. | |
| 594 | +fn unit_code(unit: NalUnitType) -> u8 { | |
| 595 | + match unit { | |
| 596 | + NalUnitType::Slice => 1, | |
| 597 | + NalUnitType::SliceIdr => 5, | |
| 598 | + NalUnitType::Sps => 7, | |
| 599 | + NalUnitType::Pps => 8, | |
| 600 | + _ => 0, | |
| 601 | + } | |
| 602 | +} | |
| 603 | + | |
| 604 | +/// A `(num_units_in_tick, time_scale)` pair for a frame rate, exact for the | |
| 605 | +/// broadcast rates (23.976, 29.97, 59.94) and within a part in 10^5 otherwise. | |
| 606 | +fn rational_timing(fps: f64) -> (u32, u32) { | |
| 607 | + for (num, den) in [ | |
| 608 | + (24000u32, 1001u32), | |
| 609 | + (30000, 1001), | |
| 610 | + (60000, 1001), | |
| 611 | + (120000, 1001), | |
| 612 | + ] { | |
| 613 | + if (fps - f64::from(num) / f64::from(den)).abs() < 1e-3 { | |
| 614 | + return (den, num * 2); | |
| 615 | + } | |
| 616 | + } | |
| 617 | + let scaled = (fps * 1000.0).round().max(1.0); | |
| 618 | + (1000, (scaled * 2.0).min(f64::from(u32::MAX)) as u32) | |
| 619 | +} | |
| 620 | + | |
| 621 | +#[cfg(test)] | |
| 622 | +mod tests { | |
| 623 | + use super::*; | |
| 624 | + | |
| 625 | + #[test] | |
| 626 | + fn bands_cover_every_row_once() { | |
| 627 | + for mb_h in [1usize, 5, 68, 135] { | |
| 628 | + for threads in [1usize, 3, 12, 200] { | |
| 629 | + let bands = split_bands(mb_h, threads); | |
| 630 | + assert!(!bands.is_empty()); | |
| 631 | + assert_eq!(bands[0].0, 0); | |
| 632 | + assert_eq!(bands.last().unwrap().1, mb_h); | |
| 633 | + for pair in bands.windows(2) { | |
| 634 | + assert_eq!(pair[0].1, pair[1].0); | |
| 635 | + } | |
| 636 | + assert!(bands.iter().all(|&(a, b)| a < b), "empty band: {bands:?}"); | |
| 637 | + } | |
| 638 | + } | |
| 639 | + } | |
| 640 | + | |
| 641 | + #[test] | |
| 642 | + fn timing_is_exact_for_broadcast_rates() { | |
| 643 | + assert_eq!(rational_timing(24000.0 / 1001.0), (1001, 48000)); | |
| 644 | + assert_eq!(rational_timing(30000.0 / 1001.0), (1001, 60000)); | |
| 645 | + assert_eq!(rational_timing(25.0), (1000, 50000)); | |
| 646 | + } | |
| 647 | + | |
| 648 | + /// Odd dimensions are refused by name rather than coded wrong. | |
| 649 | + #[test] | |
| 650 | + fn odd_dimensions_are_refused() { | |
| 651 | + let Err(err) = Encoder::new(EncoderConfig::new(641, 480)) else { | |
| 652 | + panic!("an odd width must be refused"); | |
| 653 | + }; | |
| 654 | + assert!(matches!(err, Error::Unsupported { .. }), "{err}"); | |
| 655 | + assert!(Encoder::new(EncoderConfig::new(640, 480)).is_ok()); | |
| 656 | + } | |
| 657 | +} |
crates/ec-h264/src/enc/quant.rsadded+258 -0
| @@ -0,0 +1,258 @@ | ||
| 1 | +//! Forward transforms and quantisation. | |
| 2 | +//! | |
| 3 | +//! Nothing here is normative: the standard specifies only the *inverse* | |
| 4 | +//! transforms, which the decoder side of this crate already implements | |
| 5 | +//! ([`crate::transform`]). The forward direction is chosen so that the | |
| 6 | +//! round trip through the normative inverse lands back on the source, and | |
| 7 | +//! that is what the tests at the bottom check across the whole QP range. | |
| 8 | +//! | |
| 9 | +//! The multiplier table pairs with `normAdjust4x4` (Table 8-15 through the | |
| 10 | +//! `LevelScale` of Equation 8-313): `MF[m][class] * normAdjust4x4[m][class] * | |
| 11 | +//! 16 ~= 2^21`, which is what makes `level = (|c| * MF + f) >> (15 + qp / 6)` | |
| 12 | +//! invert the decoder's dequantisation. | |
| 13 | + | |
| 14 | +use crate::tables::{NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4}; | |
| 15 | + | |
| 16 | +/// Quantisation multipliers per `qp % 6`, indexed by the same position class | |
| 17 | +/// as [`NORM_ADJUST_CLASS_4X4`] (0 = even/even, 1 = odd/odd, 2 = mixed). | |
| 18 | +const MF: [[i32; 3]; 6] = [ | |
| 19 | + [13107, 5243, 8066], | |
| 20 | + [11916, 4660, 7490], | |
| 21 | + [10082, 4194, 6554], | |
| 22 | + [9362, 3647, 5825], | |
| 23 | + [8192, 3355, 5243], | |
| 24 | + [7282, 2893, 4559], | |
| 25 | +]; | |
| 26 | + | |
| 27 | +/// Rounding offset numerator: an intra block rounds at 1/3 of a step, an inter | |
| 28 | +/// block at 1/6 — the classic asymmetry, which spends bits where prediction is | |
| 29 | +/// weakest. Measured against 1/3 and 1/2 for the inter case on 1080p camera | |
| 30 | +/// and screen-capture clips: 1/6 is level or ahead at matched bitrate. | |
| 31 | +#[inline] | |
| 32 | +fn round_offset(qbits: u32, intra: bool) -> i32 { | |
| 33 | + (1i32 << qbits) / if intra { 3 } else { 6 } | |
| 34 | +} | |
| 35 | + | |
| 36 | +/// Forward 4x4 core transform (the inverse of spec 8.5.12.2), raster in and | |
| 37 | +/// out, integer and exact. | |
| 38 | +pub(crate) fn forward_4x4(d: &mut [i32; 16]) { | |
| 39 | + for i in 0..4 { | |
| 40 | + let o = i * 4; | |
| 41 | + let (a, b, c, e) = (d[o], d[o + 1], d[o + 2], d[o + 3]); | |
| 42 | + let (s0, s1, s2, s3) = (a + e, b + c, b - c, a - e); | |
| 43 | + d[o] = s0 + s1; | |
| 44 | + d[o + 1] = 2 * s3 + s2; | |
| 45 | + d[o + 2] = s0 - s1; | |
| 46 | + d[o + 3] = s3 - 2 * s2; | |
| 47 | + } | |
| 48 | + for j in 0..4 { | |
| 49 | + let (a, b, c, e) = (d[j], d[4 + j], d[8 + j], d[12 + j]); | |
| 50 | + let (s0, s1, s2, s3) = (a + e, b + c, b - c, a - e); | |
| 51 | + d[j] = s0 + s1; | |
| 52 | + d[4 + j] = 2 * s3 + s2; | |
| 53 | + d[8 + j] = s0 - s1; | |
| 54 | + d[12 + j] = s3 - 2 * s2; | |
| 55 | + } | |
| 56 | +} | |
| 57 | + | |
| 58 | +/// Forward 4x4 Hadamard over the sixteen luma DC coefficients of an | |
| 59 | +/// Intra_16x16 macroblock (the inverse of spec 8.5.10), raster in and out. | |
| 60 | +pub(crate) fn forward_hadamard_4x4(d: &mut [i32; 16]) { | |
| 61 | + for i in 0..4 { | |
| 62 | + let o = i * 4; | |
| 63 | + let (a, b, c, e) = (d[o], d[o + 1], d[o + 2], d[o + 3]); | |
| 64 | + d[o] = a + b + c + e; | |
| 65 | + d[o + 1] = a + b - c - e; | |
| 66 | + d[o + 2] = a - b - c + e; | |
| 67 | + d[o + 3] = a - b + c - e; | |
| 68 | + } | |
| 69 | + for j in 0..4 { | |
| 70 | + let (a, b, c, e) = (d[j], d[4 + j], d[8 + j], d[12 + j]); | |
| 71 | + d[j] = a + b + c + e; | |
| 72 | + d[4 + j] = a + b - c - e; | |
| 73 | + d[8 + j] = a - b - c + e; | |
| 74 | + d[12 + j] = a - b + c - e; | |
| 75 | + } | |
| 76 | +} | |
| 77 | + | |
| 78 | +/// Forward 2x2 Hadamard over the four chroma DC coefficients (the inverse of | |
| 79 | +/// spec 8.5.11). | |
| 80 | +pub(crate) fn forward_hadamard_2x2(d: &mut [i32; 4]) { | |
| 81 | + let (a, b, c, e) = (d[0], d[1], d[2], d[3]); | |
| 82 | + d[0] = a + b + c + e; | |
| 83 | + d[1] = a - b + c - e; | |
| 84 | + d[2] = a + b - c - e; | |
| 85 | + d[3] = a - b - c + e; | |
| 86 | +} | |
| 87 | + | |
| 88 | +/// Quantise a transformed 4x4 block into scan (zig-zag) order. | |
| 89 | +/// | |
| 90 | +/// `skip_dc` leaves scan position 0 out and writes the fifteen AC levels into | |
| 91 | +/// `out[0..15]`, which is the layout the AC residual blocks of Intra_16x16 and | |
| 92 | +/// chroma use. Returns the number of non-zero levels. | |
| 93 | +pub(crate) fn quant_4x4( | |
| 94 | + coef: &[i32; 16], | |
| 95 | + qp: i32, | |
| 96 | + intra: bool, | |
| 97 | + skip_dc: bool, | |
| 98 | + out: &mut [i32; 16], | |
| 99 | +) -> u8 { | |
| 100 | + let m = (qp % 6) as usize; | |
| 101 | + let qbits = 15 + (qp / 6) as u32; | |
| 102 | + let f = round_offset(qbits, intra); | |
| 103 | + let start = usize::from(skip_dc); | |
| 104 | + let mut nz = 0; | |
| 105 | + *out = [0; 16]; | |
| 106 | + for k in start..16 { | |
| 107 | + let raster = ZIGZAG_4X4[k] as usize; | |
| 108 | + let c = coef[raster]; | |
| 109 | + let mf = MF[m][NORM_ADJUST_CLASS_4X4[raster] as usize]; | |
| 110 | + let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32; | |
| 111 | + if level != 0 { | |
| 112 | + nz += 1; | |
| 113 | + } | |
| 114 | + out[k - start] = if c < 0 { -level } else { level }; | |
| 115 | + } | |
| 116 | + nz | |
| 117 | +} | |
| 118 | + | |
| 119 | +/// Quantise the sixteen Hadamard-transformed luma DC coefficients into scan | |
| 120 | +/// order. Two extra bits of shift pay for the gain of the forward Hadamard, | |
| 121 | +/// which the decoder's inverse (8.5.10, a `>> 6` where the AC path shifts by | |
| 122 | +/// four) takes back out. | |
| 123 | +pub(crate) fn quant_luma_dc(coef: &[i32; 16], qp: i32, out: &mut [i32; 16]) -> u8 { | |
| 124 | + let qbits = 17 + (qp / 6) as u32; | |
| 125 | + let mf = MF[(qp % 6) as usize][0]; | |
| 126 | + let f = round_offset(qbits, true); | |
| 127 | + let mut nz = 0; | |
| 128 | + *out = [0; 16]; | |
| 129 | + for k in 0..16 { | |
| 130 | + let c = coef[ZIGZAG_4X4[k] as usize]; | |
| 131 | + let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32; | |
| 132 | + if level != 0 { | |
| 133 | + nz += 1; | |
| 134 | + } | |
| 135 | + out[k] = if c < 0 { -level } else { level }; | |
| 136 | + } | |
| 137 | + nz | |
| 138 | +} | |
| 139 | + | |
| 140 | +/// Quantise the four Hadamard-transformed chroma DC coefficients (raster | |
| 141 | +/// order, which is also their scan order). | |
| 142 | +pub(crate) fn quant_chroma_dc(coef: &[i32; 4], qp: i32, intra: bool, out: &mut [i32; 16]) -> u8 { | |
| 143 | + let qbits = 16 + (qp / 6) as u32; | |
| 144 | + let mf = MF[(qp % 6) as usize][0]; | |
| 145 | + let f = round_offset(qbits, intra); | |
| 146 | + let mut nz = 0; | |
| 147 | + *out = [0; 16]; | |
| 148 | + for k in 0..4 { | |
| 149 | + let c = coef[k]; | |
| 150 | + let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32; | |
| 151 | + if level != 0 { | |
| 152 | + nz += 1; | |
| 153 | + } | |
| 154 | + out[k] = if c < 0 { -level } else { level }; | |
| 155 | + } | |
| 156 | + nz | |
| 157 | +} | |
| 158 | + | |
| 159 | +#[cfg(test)] | |
| 160 | +mod tests { | |
| 161 | + use super::*; | |
| 162 | + use crate::transform::{ | |
| 163 | + LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, | |
| 164 | + luma_dc_transform, unzigzag, | |
| 165 | + }; | |
| 166 | + | |
| 167 | + fn ls() -> LevelScale4x4 { | |
| 168 | + LevelScale4x4::new(&[16; 16]) | |
| 169 | + } | |
| 170 | + | |
| 171 | + /// A residual quantised at QP and put back through the *normative* inverse | |
| 172 | + /// comes back within the quantiser step, at every QP: this is the property | |
| 173 | + /// that makes the forward direction a valid inverse of clause 8.5, and a | |
| 174 | + /// wrong multiplier or shift breaks it by orders of magnitude. | |
| 175 | + #[test] | |
| 176 | + fn ac_round_trip_within_a_quantiser_step() { | |
| 177 | + let ls = ls(); | |
| 178 | + for qp in 0..52 { | |
| 179 | + let mut worst = 0i32; | |
| 180 | + for seed in 0..8u32 { | |
| 181 | + let src: [i32; 16] = std::array::from_fn(|i| { | |
| 182 | + let v = (seed.wrapping_mul(2654435761).wrapping_add(i as u32 * 40503)) >> 24; | |
| 183 | + (v as i32 % 61) - 30 | |
| 184 | + }); | |
| 185 | + let mut coef = src; | |
| 186 | + forward_4x4(&mut coef); | |
| 187 | + let mut scan = [0i32; 16]; | |
| 188 | + quant_4x4(&coef, qp, true, false, &mut scan); | |
| 189 | + let mut raster = [0i32; 16]; | |
| 190 | + unzigzag(&scan, &mut raster); | |
| 191 | + dequant_4x4(&mut raster, &ls, qp, false); | |
| 192 | + let mut out = [0i32; 16]; | |
| 193 | + inverse_transform_4x4(&raster, &mut out); | |
| 194 | + for i in 0..16 { | |
| 195 | + worst = worst.max((out[i] - src[i]).abs()); | |
| 196 | + } | |
| 197 | + } | |
| 198 | + // The reconstruction error of a dead-zone quantiser is bounded by | |
| 199 | + // one step, which doubles every six QP. | |
| 200 | + let step = 1 << (qp / 6); | |
| 201 | + assert!( | |
| 202 | + worst <= 2 + 2 * step, | |
| 203 | + "qp {qp}: worst error {worst} over step {step}" | |
| 204 | + ); | |
| 205 | + } | |
| 206 | + } | |
| 207 | + | |
| 208 | + /// The same for the Intra_16x16 luma DC path: a flat residual across the | |
| 209 | + /// whole macroblock survives Hadamard, quantisation and the decoder's | |
| 210 | + /// 8.5.10 inverse. | |
| 211 | + #[test] | |
| 212 | + fn luma_dc_round_trip() { | |
| 213 | + let ls = ls(); | |
| 214 | + for qp in 0..52 { | |
| 215 | + for &x in &[-40i32, -7, 3, 25] { | |
| 216 | + // Every 4x4 block of a flat macroblock has DC = 16 * x. | |
| 217 | + let dc: [i32; 16] = [16 * x; 16]; | |
| 218 | + let mut had = dc; | |
| 219 | + forward_hadamard_4x4(&mut had); | |
| 220 | + let mut scan = [0i32; 16]; | |
| 221 | + quant_luma_dc(&had, qp, &mut scan); | |
| 222 | + let mut raster = [0i32; 16]; | |
| 223 | + unzigzag(&scan, &mut raster); | |
| 224 | + luma_dc_transform(&mut raster, &ls, qp); | |
| 225 | + // Each block reconstructs (dc + 32) >> 6 flat samples. | |
| 226 | + let recon = (raster[0] + 32) >> 6; | |
| 227 | + let step = 1 << (qp / 6); | |
| 228 | + assert!( | |
| 229 | + (recon - x).abs() <= 2 + 2 * step, | |
| 230 | + "qp {qp} x {x}: recon {recon}" | |
| 231 | + ); | |
| 232 | + } | |
| 233 | + } | |
| 234 | + } | |
| 235 | + | |
| 236 | + /// And the chroma DC path (2x2 Hadamard, 8.5.11). | |
| 237 | + #[test] | |
| 238 | + fn chroma_dc_round_trip() { | |
| 239 | + let ls = ls(); | |
| 240 | + for qp in 0..40 { | |
| 241 | + for &x in &[-30i32, -4, 9, 21] { | |
| 242 | + let dc: [i32; 4] = [16 * x; 4]; | |
| 243 | + let mut had = dc; | |
| 244 | + forward_hadamard_2x2(&mut had); | |
| 245 | + let mut scan = [0i32; 16]; | |
| 246 | + quant_chroma_dc(&had, qp, true, &mut scan); | |
| 247 | + let mut c: [i32; 4] = [scan[0], scan[1], scan[2], scan[3]]; | |
| 248 | + chroma_dc_transform_420(&mut c, &ls, qp); | |
| 249 | + let recon = (c[0] + 32) >> 6; | |
| 250 | + let step = 1 << (qp / 6); | |
| 251 | + assert!( | |
| 252 | + (recon - x).abs() <= 2 + 2 * step, | |
| 253 | + "qp {qp} x {x}: recon {recon}" | |
| 254 | + ); | |
| 255 | + } | |
| 256 | + } | |
| 257 | + } | |
| 258 | +} |
crates/ec-h264/src/enc/rc.rsadded+172 -0
| @@ -0,0 +1,172 @@ | ||
| 1 | +//! Rate control: one QP per picture from a bit model, refined per macroblock | |
| 2 | +//! row inside each slice. | |
| 3 | +//! | |
| 4 | +//! The model is the classic one: at a fixed complexity a picture's size scales | |
| 5 | +//! as `2^(-QP/6)`, so `complexity = bits * 2^(QP/6)` measured on the last | |
| 6 | +//! picture of the same type predicts the QP that hits the next target. A | |
| 7 | +//! leaky-bucket term pulls the stream back when the model is wrong, which is | |
| 8 | +//! what makes the average bitrate hold over a clip rather than per picture. | |
| 9 | + | |
| 10 | +/// Constant-quantiser mode is a bitrate of zero: nothing to control. | |
| 11 | +#[derive(Debug, Clone)] | |
| 12 | +pub(crate) struct RateControl { | |
| 13 | + /// Bits per picture at the configured bitrate and frame rate. | |
| 14 | + base: f64, | |
| 15 | + /// Virtual buffer occupancy in bits, positive when the stream is ahead of | |
| 16 | + /// its budget. | |
| 17 | + buffer: f64, | |
| 18 | + /// `bits * 2^(qp / 6)` of the last coded picture, per type (0 = I, 1 = P). | |
| 19 | + complexity: [f64; 2], | |
| 20 | + /// The QP the last picture of each type was coded at. | |
| 21 | + last_qp: [f64; 2], | |
| 22 | + /// Extra share of the group of pictures an IDR is allowed to borrow, as a | |
| 23 | + /// multiple of one picture's budget. | |
| 24 | + i_share: f64, | |
| 25 | + /// Pictures per group, over which that share is repaid. | |
| 26 | + gop: f64, | |
| 27 | + fixed: Option<i32>, | |
| 28 | +} | |
| 29 | + | |
| 30 | +impl RateControl { | |
| 31 | + pub(crate) fn new(bitrate: u32, fps: f64, gop: u32, fixed_qp: Option<i32>) -> RateControl { | |
| 32 | + let base = if bitrate == 0 || fps <= 0.0 { | |
| 33 | + 0.0 | |
| 34 | + } else { | |
| 35 | + f64::from(bitrate) / fps | |
| 36 | + }; | |
| 37 | + // An intra picture costs many times a predicted one and every picture | |
| 38 | + // of the group predicts from it, so it borrows a slice of each of them | |
| 39 | + // — without this the bucket saturates on the IDR alone and the next | |
| 40 | + // half second is coded at a quantiser nothing justifies. | |
| 41 | + let i_share = (0.15 * f64::from(gop.saturating_sub(1))).clamp(0.0, 8.0); | |
| 42 | + RateControl { | |
| 43 | + base, | |
| 44 | + i_share, | |
| 45 | + gop: f64::from(gop.max(1)), | |
| 46 | + buffer: 0.0, | |
| 47 | + complexity: [0.0; 2], | |
| 48 | + last_qp: [26.0; 2], | |
| 49 | + fixed: fixed_qp.or(if base == 0.0 { Some(26) } else { None }), | |
| 50 | + } | |
| 51 | + } | |
| 52 | + | |
| 53 | + /// QP for the next picture. | |
| 54 | + pub(crate) fn frame_qp(&self, idr: bool) -> i32 { | |
| 55 | + if let Some(qp) = self.fixed { | |
| 56 | + return qp; | |
| 57 | + } | |
| 58 | + let kind = usize::from(!idr); | |
| 59 | + let target = self.frame_target(idr); | |
| 60 | + let mut qp = if self.complexity[kind] > 0.0 { | |
| 61 | + 6.0 * (self.complexity[kind] / target).log2() | |
| 62 | + } else if idr { | |
| 63 | + self.last_qp[1] | |
| 64 | + } else { | |
| 65 | + // First P picture: start from the I picture's quantiser. | |
| 66 | + self.last_qp[0] + 2.0 | |
| 67 | + }; | |
| 68 | + // Never move far in one step; a jumpy quantiser looks worse than a | |
| 69 | + // slightly wrong one. | |
| 70 | + // Asymmetric: a picture that costs less than its budget should reach | |
| 71 | + // the quantiser it can afford quickly (on static content that is where | |
| 72 | + // all the quality comes from), while a picture that overspends is | |
| 73 | + // pulled back gently, because a visible quantiser jump costs more than | |
| 74 | + // a few frames of debt. | |
| 75 | + let (down, up) = if idr { (6.0, 6.0) } else { (4.0, 2.0) }; | |
| 76 | + qp = qp.clamp(self.last_qp[kind] - down, self.last_qp[kind] + up); | |
| 77 | + // Leaky bucket: 1.5 QP per picture of debt, capped. | |
| 78 | + qp += (self.buffer / (self.base.max(1.0) * 4.0) * 2.0).clamp(-2.0, 2.0); | |
| 79 | + qp.round().clamp(10.0, 51.0) as i32 | |
| 80 | + } | |
| 81 | + | |
| 82 | + /// Record what the picture actually cost. | |
| 83 | + pub(crate) fn update(&mut self, idr: bool, qp: i32, bits: u64) { | |
| 84 | + if self.fixed.is_some() { | |
| 85 | + return; | |
| 86 | + } | |
| 87 | + let kind = usize::from(!idr); | |
| 88 | + let bits = bits as f64; | |
| 89 | + let c = bits * (f64::from(qp) / 6.0).exp2(); | |
| 90 | + self.complexity[kind] = if self.complexity[kind] == 0.0 { | |
| 91 | + c | |
| 92 | + } else { | |
| 93 | + // Smoothed: one anomalous picture must not whipsaw the next. | |
| 94 | + 0.7 * self.complexity[kind] + 0.3 * c | |
| 95 | + }; | |
| 96 | + self.last_qp[kind] = f64::from(qp); | |
| 97 | + // The budget a picture of this type was given, not the flat average: | |
| 98 | + // an IDR that lands on its (large) target must not push the bucket. | |
| 99 | + let target = self.frame_target(idr); | |
| 100 | + self.buffer = (self.buffer + bits - target).clamp(-4.0 * self.base, 8.0 * self.base); | |
| 101 | + } | |
| 102 | + | |
| 103 | + /// Per-macroblock-row correction inside a slice: `spent` and `expected` are | |
| 104 | + /// bits so far and the pro-rata budget. | |
| 105 | + /// | |
| 106 | + /// This is the *fast* loop, and it has to be: on content whose bit cost | |
| 107 | + /// falls off a cliff with the quantiser — a screen capture, where dropping | |
| 108 | + /// one QP step re-codes half the picture — the picture-level model can | |
| 109 | + /// mispredict by an order of magnitude, and only a correction inside the | |
| 110 | + /// picture keeps that from blowing the budget and whipsawing the next | |
| 111 | + /// second of video. Asymmetric on purpose: overspending is capped hard, | |
| 112 | + /// underspending is given back gently. | |
| 113 | + pub(crate) fn row_delta(&self, spent: u64, expected: f64) -> i32 { | |
| 114 | + if self.fixed.is_some() || expected <= 0.0 { | |
| 115 | + return 0; | |
| 116 | + } | |
| 117 | + let ratio = (spent as f64 / expected).max(1e-3); | |
| 118 | + let delta = 6.0 * ratio.log2(); | |
| 119 | + delta.round().clamp(-2.0, 6.0) as i32 | |
| 120 | + } | |
| 121 | + | |
| 122 | + /// Bits the picture is aiming for, for the per-row budget. | |
| 123 | + pub(crate) fn frame_target(&self, idr: bool) -> f64 { | |
| 124 | + if idr { | |
| 125 | + self.base * (1.0 + self.i_share) | |
| 126 | + } else { | |
| 127 | + // What each predicted picture of the group gives back to the IDR, | |
| 128 | + // so that the group as a whole still costs `gop * base`. | |
| 129 | + self.base * (1.0 - self.i_share / (self.gop - 1.0).max(1.0)).max(0.3) | |
| 130 | + } | |
| 131 | + } | |
| 132 | +} | |
| 133 | + | |
| 134 | +#[cfg(test)] | |
| 135 | +mod tests { | |
| 136 | + use super::*; | |
| 137 | + | |
| 138 | + /// A constant-bitrate run converges: fed pictures that always cost what the | |
| 139 | + /// model says, the quantiser settles and the buffer does not run away. | |
| 140 | + #[test] | |
| 141 | + fn converges_to_the_target() { | |
| 142 | + let mut rc = RateControl::new(4_000_000, 25.0, 25, None); | |
| 143 | + // A synthetic source whose complexity is fixed. | |
| 144 | + let complexity = 8.0e6; | |
| 145 | + let mut qps = Vec::new(); | |
| 146 | + for f in 0..60 { | |
| 147 | + let idr = f == 0; | |
| 148 | + let qp = rc.frame_qp(idr); | |
| 149 | + let bits = (complexity * (-f64::from(qp) / 6.0).exp2()) as u64; | |
| 150 | + rc.update(idr, qp, bits); | |
| 151 | + qps.push(qp); | |
| 152 | + } | |
| 153 | + let tail = &qps[40..]; | |
| 154 | + let spread = tail.iter().max().unwrap() - tail.iter().min().unwrap(); | |
| 155 | + assert!(spread <= 2, "quantiser still hunting: {tail:?}"); | |
| 156 | + assert!( | |
| 157 | + rc.buffer.abs() < 2.0 * rc.base, | |
| 158 | + "buffer ran away: {}", | |
| 159 | + rc.buffer | |
| 160 | + ); | |
| 161 | + } | |
| 162 | + | |
| 163 | + /// A bitrate of zero is constant-QP mode, and nothing moves it. | |
| 164 | + #[test] | |
| 165 | + fn zero_bitrate_is_constant_qp() { | |
| 166 | + let mut rc = RateControl::new(0, 25.0, 25, Some(31)); | |
| 167 | + assert_eq!(rc.frame_qp(true), 31); | |
| 168 | + rc.update(true, 31, 10_000_000); | |
| 169 | + assert_eq!(rc.frame_qp(false), 31); | |
| 170 | + assert_eq!(rc.row_delta(1_000_000, 1.0), 0); | |
| 171 | + } | |
| 172 | +} |
crates/ec-h264/src/enc/vlc.rsadded+323 -0
| @@ -0,0 +1,323 @@ | ||
| 1 | +//! CAVLC writing (spec 9.2): the exact inverse of [`crate::cavlc`]. | |
| 2 | +//! | |
| 3 | +//! Every code table here is *derived at compile time from the decoder's own | |
| 4 | +//! tables* — the reverse maps below are `const fn` walks of | |
| 5 | +//! [`crate::tables`], so an encoder code and the decoder code it must match | |
| 6 | +//! cannot drift apart. The round-trip test at the bottom re-decodes what this | |
| 7 | +//! module writes with [`crate::cavlc::residual_block`]. | |
| 8 | + | |
| 9 | +use ec_core::BitWriter; | |
| 10 | + | |
| 11 | +use crate::tables::{ | |
| 12 | + CBP_INTER_420, CBP_INTRA_420, COEFF_TOKEN_CHROMA_DC, COEFF_TOKEN_NC0, COEFF_TOKEN_NC2, | |
| 13 | + COEFF_TOKEN_NC4, CoeffTokenEntry, RUN_BEFORE, TOTAL_ZEROS_4X4, TOTAL_ZEROS_CHROMA_DC, VlcEntry, | |
| 14 | +}; | |
| 15 | + | |
| 16 | +/// `(length, code)` of one VLC codeword; length 0 marks a combination the | |
| 17 | +/// table does not contain. | |
| 18 | +type Code = (u8, u16); | |
| 19 | + | |
| 20 | +/// Reverse `coeff_token` table: `[total_coeff][trailing_ones]`. | |
| 21 | +type CoeffTokenRev = [[Code; 4]; 17]; | |
| 22 | + | |
| 23 | +const fn rev_coeff_token(t: &[CoeffTokenEntry]) -> CoeffTokenRev { | |
| 24 | + let mut out = [[(0u8, 0u16); 4]; 17]; | |
| 25 | + let mut i = 0; | |
| 26 | + while i < t.len() { | |
| 27 | + let (len, code, tc, t1) = t[i]; | |
| 28 | + out[tc as usize][t1 as usize] = (len, code); | |
| 29 | + i += 1; | |
| 30 | + } | |
| 31 | + out | |
| 32 | +} | |
| 33 | + | |
| 34 | +const fn rev_vlc<const N: usize>(t: &[VlcEntry]) -> [Code; N] { | |
| 35 | + let mut out = [(0u8, 0u16); N]; | |
| 36 | + let mut i = 0; | |
| 37 | + while i < t.len() { | |
| 38 | + let (len, code, value) = t[i]; | |
| 39 | + out[value as usize] = (len, code); | |
| 40 | + i += 1; | |
| 41 | + } | |
| 42 | + out | |
| 43 | +} | |
| 44 | + | |
| 45 | +const fn rev_vlc_table<const R: usize, const N: usize>(t: &[&[VlcEntry]; R]) -> [[Code; N]; R] { | |
| 46 | + let mut out = [[(0u8, 0u16); N]; R]; | |
| 47 | + let mut i = 0; | |
| 48 | + while i < R { | |
| 49 | + out[i] = rev_vlc::<N>(t[i]); | |
| 50 | + i += 1; | |
| 51 | + } | |
| 52 | + out | |
| 53 | +} | |
| 54 | + | |
| 55 | +static COEFF_TOKEN: [CoeffTokenRev; 3] = [ | |
| 56 | + rev_coeff_token(COEFF_TOKEN_NC0), | |
| 57 | + rev_coeff_token(COEFF_TOKEN_NC2), | |
| 58 | + rev_coeff_token(COEFF_TOKEN_NC4), | |
| 59 | +]; | |
| 60 | +static COEFF_TOKEN_CDC: CoeffTokenRev = rev_coeff_token(COEFF_TOKEN_CHROMA_DC); | |
| 61 | +static TOTAL_ZEROS: [[Code; 16]; 15] = rev_vlc_table(&TOTAL_ZEROS_4X4); | |
| 62 | +static TOTAL_ZEROS_CDC: [[Code; 4]; 3] = rev_vlc_table(&TOTAL_ZEROS_CHROMA_DC); | |
| 63 | +static RUNS: [[Code; 15]; 7] = rev_vlc_table(&RUN_BEFORE); | |
| 64 | + | |
| 65 | +#[inline] | |
| 66 | +fn write_code(w: &mut BitWriter, c: Code) { | |
| 67 | + debug_assert!(c.0 > 0, "VLC combination absent from the table"); | |
| 68 | + w.write_bits(u32::from(c.1), u32::from(c.0)); | |
| 69 | +} | |
| 70 | + | |
| 71 | +/// `coeff_token` (9.2.1). `nc` is the neighbour count, -1 for 4:2:0 chroma DC. | |
| 72 | +fn write_coeff_token(w: &mut BitWriter, nc: i32, total_coeff: u8, trailing_ones: u8) { | |
| 73 | + if nc == -1 { | |
| 74 | + write_code( | |
| 75 | + w, | |
| 76 | + COEFF_TOKEN_CDC[total_coeff as usize][trailing_ones as usize], | |
| 77 | + ); | |
| 78 | + return; | |
| 79 | + } | |
| 80 | + if nc >= 8 { | |
| 81 | + // Fixed-length 6-bit form. | |
| 82 | + let v = if total_coeff == 0 { | |
| 83 | + 3 | |
| 84 | + } else { | |
| 85 | + u32::from(total_coeff - 1) * 4 + u32::from(trailing_ones) | |
| 86 | + }; | |
| 87 | + w.write_bits(v, 6); | |
| 88 | + return; | |
| 89 | + } | |
| 90 | + let table = match nc { | |
| 91 | + 0..=1 => 0, | |
| 92 | + 2..=3 => 1, | |
| 93 | + _ => 2, | |
| 94 | + }; | |
| 95 | + write_code( | |
| 96 | + w, | |
| 97 | + COEFF_TOKEN[table][total_coeff as usize][trailing_ones as usize], | |
| 98 | + ); | |
| 99 | +} | |
| 100 | + | |
| 101 | +/// Base value and suffix width of one `level_prefix` under `suffix_length`, | |
| 102 | +/// read straight off the decoder's reconstruction in [`crate::cavlc`]. | |
| 103 | +#[inline] | |
| 104 | +fn level_range(prefix: u32, suffix_length: u32) -> (i64, u32) { | |
| 105 | + if prefix >= 15 { | |
| 106 | + let mut base = (15i64 << suffix_length) + if suffix_length == 0 { 15 } else { 0 }; | |
| 107 | + if prefix >= 16 { | |
| 108 | + base += (1i64 << (prefix - 3)) - 4096; | |
| 109 | + } | |
| 110 | + (base, prefix - 3) | |
| 111 | + } else if prefix == 14 && suffix_length == 0 { | |
| 112 | + (14, 4) | |
| 113 | + } else { | |
| 114 | + ((i64::from(prefix)) << suffix_length, suffix_length) | |
| 115 | + } | |
| 116 | +} | |
| 117 | + | |
| 118 | +/// `level_prefix` + `level_suffix` (9.2.2.1) for one `levelCode`, choosing the | |
| 119 | +/// shortest prefix whose range contains it. | |
| 120 | +fn write_level_code(w: &mut BitWriter, level_code: i64, suffix_length: u32) { | |
| 121 | + for prefix in 0..=25u32 { | |
| 122 | + let (base, size) = level_range(prefix, suffix_length); | |
| 123 | + if level_code >= base && level_code < base + (1i64 << size) { | |
| 124 | + w.write_bits64(0, prefix); | |
| 125 | + w.write_bit(true); | |
| 126 | + if size > 0 { | |
| 127 | + w.write_bits64((level_code - base) as u64, size); | |
| 128 | + } | |
| 129 | + return; | |
| 130 | + } | |
| 131 | + } | |
| 132 | + debug_assert!(false, "level {level_code} outside every level_prefix range"); | |
| 133 | +} | |
| 134 | + | |
| 135 | +/// Write one CAVLC residual block (9.2) from `coeff[0..max_num_coeff]` in scan | |
| 136 | +/// order. Returns TotalCoeff, which the caller records as the block's non-zero | |
| 137 | +/// count for its neighbours. | |
| 138 | +pub(crate) fn write_residual_block( | |
| 139 | + w: &mut BitWriter, | |
| 140 | + coeff: &[i32], | |
| 141 | + max_num_coeff: usize, | |
| 142 | + nc: i32, | |
| 143 | +) -> u8 { | |
| 144 | + debug_assert!(max_num_coeff <= 16); | |
| 145 | + // Scan positions of the non-zero levels, lowest frequency first. | |
| 146 | + let mut pos = [0usize; 16]; | |
| 147 | + let mut total_coeff = 0usize; | |
| 148 | + for (k, &c) in coeff.iter().take(max_num_coeff).enumerate() { | |
| 149 | + if c != 0 { | |
| 150 | + pos[total_coeff] = k; | |
| 151 | + total_coeff += 1; | |
| 152 | + } | |
| 153 | + } | |
| 154 | + if total_coeff == 0 { | |
| 155 | + write_coeff_token(w, nc, 0, 0); | |
| 156 | + return 0; | |
| 157 | + } | |
| 158 | + // Trailing ones: up to three +-1 levels at the high-frequency end. | |
| 159 | + let mut trailing_ones = 0usize; | |
| 160 | + while trailing_ones < 3 | |
| 161 | + && trailing_ones < total_coeff | |
| 162 | + && coeff[pos[total_coeff - 1 - trailing_ones]].abs() == 1 | |
| 163 | + { | |
| 164 | + trailing_ones += 1; | |
| 165 | + } | |
| 166 | + write_coeff_token(w, nc, total_coeff as u8, trailing_ones as u8); | |
| 167 | + | |
| 168 | + // 9.2.2: levels, highest frequency first. | |
| 169 | + for i in 0..trailing_ones { | |
| 170 | + w.write_bit(coeff[pos[total_coeff - 1 - i]] < 0); | |
| 171 | + } | |
| 172 | + let mut suffix_length = u32::from(total_coeff > 10 && trailing_ones < 3); | |
| 173 | + for i in trailing_ones..total_coeff { | |
| 174 | + let level = i64::from(coeff[pos[total_coeff - 1 - i]]); | |
| 175 | + let mut level_code = if level > 0 { | |
| 176 | + 2 * level - 2 | |
| 177 | + } else { | |
| 178 | + -2 * level - 1 | |
| 179 | + }; | |
| 180 | + if i == trailing_ones && trailing_ones < 3 { | |
| 181 | + level_code -= 2; | |
| 182 | + } | |
| 183 | + write_level_code(w, level_code, suffix_length); | |
| 184 | + if suffix_length == 0 { | |
| 185 | + suffix_length = 1; | |
| 186 | + } | |
| 187 | + if level.unsigned_abs() > (3 << (suffix_length - 1)) && suffix_length < 6 { | |
| 188 | + suffix_length += 1; | |
| 189 | + } | |
| 190 | + } | |
| 191 | + | |
| 192 | + // 9.2.3 / 9.2.4: total_zeros then the runs, highest frequency first. | |
| 193 | + let total_zeros = pos[total_coeff - 1] + 1 - total_coeff; | |
| 194 | + if total_coeff < max_num_coeff { | |
| 195 | + if nc == -1 { | |
| 196 | + write_code(w, TOTAL_ZEROS_CDC[total_coeff - 1][total_zeros]); | |
| 197 | + } else { | |
| 198 | + write_code(w, TOTAL_ZEROS[total_coeff - 1][total_zeros]); | |
| 199 | + } | |
| 200 | + } | |
| 201 | + let mut zeros_left = total_zeros; | |
| 202 | + for i in 0..total_coeff - 1 { | |
| 203 | + if zeros_left == 0 { | |
| 204 | + break; | |
| 205 | + } | |
| 206 | + let k = total_coeff - 1 - i; | |
| 207 | + let run = pos[k] - pos[k - 1] - 1; | |
| 208 | + write_code(w, RUNS[zeros_left.min(7) - 1][run]); | |
| 209 | + zeros_left -= run; | |
| 210 | + } | |
| 211 | + total_coeff as u8 | |
| 212 | +} | |
| 213 | + | |
| 214 | +/// `coded_block_pattern` as me(v) (9.1.2, Table 9-4). | |
| 215 | +pub(crate) fn write_cbp(w: &mut BitWriter, cbp_luma: u8, cbp_chroma: u8, intra: bool) { | |
| 216 | + let cbp = cbp_luma | (cbp_chroma << 4); | |
| 217 | + let table: &[u8] = if intra { | |
| 218 | + &CBP_INTRA_420 | |
| 219 | + } else { | |
| 220 | + &CBP_INTER_420 | |
| 221 | + }; | |
| 222 | + let code = table | |
| 223 | + .iter() | |
| 224 | + .position(|&v| v == cbp) | |
| 225 | + .expect("every 4:2:0 coded_block_pattern has a code number"); | |
| 226 | + w.write_ue(code as u32); | |
| 227 | +} | |
| 228 | + | |
| 229 | +#[cfg(test)] | |
| 230 | +mod tests { | |
| 231 | + use super::*; | |
| 232 | + use crate::bits::BitCursor; | |
| 233 | + use crate::cavlc::residual_block; | |
| 234 | + | |
| 235 | + fn round_trip(levels: &[i32], max_num_coeff: usize, nc: i32) { | |
| 236 | + let mut w = BitWriter::new(); | |
| 237 | + let tc = write_residual_block(&mut w, levels, max_num_coeff, nc); | |
| 238 | + // A stop bit keeps `more_rbsp_data` honest and gives the reader room. | |
| 239 | + w.write_bit(true); | |
| 240 | + w.align_to_byte(); | |
| 241 | + let bytes = w.into_bytes(); | |
| 242 | + let mut r = BitCursor::new(&bytes, 0); | |
| 243 | + let mut out = [0i32; 16]; | |
| 244 | + let got = residual_block(&mut r, &mut out, max_num_coeff, nc).expect("decodes"); | |
| 245 | + assert_eq!(got, tc, "TotalCoeff mismatch for {levels:?}"); | |
| 246 | + for (k, &want) in levels.iter().take(max_num_coeff).enumerate() { | |
| 247 | + assert_eq!(out[k], want, "position {k} of {levels:?}"); | |
| 248 | + } | |
| 249 | + } | |
| 250 | + | |
| 251 | + /// Every block this writer emits decodes back to the same levels, over a | |
| 252 | + /// spread that covers empty blocks, trailing ones, long runs, the | |
| 253 | + /// suffix-length ladder and the escape codes. | |
| 254 | + #[test] | |
| 255 | + fn residual_blocks_round_trip() { | |
| 256 | + let mut state = 0x1234_5678u32; | |
| 257 | + let mut rand = move |m: u32| { | |
| 258 | + state = state.wrapping_mul(1664525).wrapping_add(1013904223); | |
| 259 | + (state >> 16) % m | |
| 260 | + }; | |
| 261 | + for &(max, nc) in &[ | |
| 262 | + (16usize, 0i32), | |
| 263 | + (16, 2), | |
| 264 | + (16, 5), | |
| 265 | + (16, 9), | |
| 266 | + (15, 0), | |
| 267 | + (15, 3), | |
| 268 | + (4, -1), | |
| 269 | + ] { | |
| 270 | + for trial in 0..400 { | |
| 271 | + let mut levels = [0i32; 16]; | |
| 272 | + let density = 1 + rand(max as u32); | |
| 273 | + for level in levels.iter_mut().take(max) { | |
| 274 | + if rand(max as u32) < density { | |
| 275 | + // Magnitudes spread over the whole ladder including | |
| 276 | + // the 4096-wide escape. | |
| 277 | + let mag = match trial % 5 { | |
| 278 | + 0 => 1, | |
| 279 | + 1 => 1 + rand(3) as i32, | |
| 280 | + 2 => 1 + rand(40) as i32, | |
| 281 | + 3 => 1 + rand(600) as i32, | |
| 282 | + _ => 1 + rand(9000) as i32, | |
| 283 | + }; | |
| 284 | + *level = if rand(2) == 0 { mag } else { -mag }; | |
| 285 | + } | |
| 286 | + } | |
| 287 | + round_trip(&levels, max, nc); | |
| 288 | + } | |
| 289 | + } | |
| 290 | + } | |
| 291 | + | |
| 292 | + /// The all-zero block, the single-coefficient block and a fully populated | |
| 293 | + /// block are the boundary cases of 9.2.3 (no total_zeros is written when | |
| 294 | + /// TotalCoeff = maxNumCoeff). | |
| 295 | + #[test] | |
| 296 | + fn boundary_blocks_round_trip() { | |
| 297 | + round_trip(&[0; 16], 16, 0); | |
| 298 | + let mut one = [0i32; 16]; | |
| 299 | + one[15] = -1; | |
| 300 | + round_trip(&one, 16, 4); | |
| 301 | + round_trip(&[1; 16], 16, 0); | |
| 302 | + round_trip(&[-3; 16], 16, 8); | |
| 303 | + round_trip(&[2, 0, 0, -1], 4, -1); | |
| 304 | + } | |
| 305 | + | |
| 306 | + /// The coded_block_pattern code numbers invert the decoder's tables. | |
| 307 | + #[test] | |
| 308 | + fn cbp_codes_invert() { | |
| 309 | + for &(luma, chroma) in &[(0u8, 0u8), (15, 2), (3, 1), (5, 0), (15, 0)] { | |
| 310 | + for intra in [true, false] { | |
| 311 | + let mut w = BitWriter::new(); | |
| 312 | + write_cbp(&mut w, luma, chroma, intra); | |
| 313 | + w.write_bit(true); | |
| 314 | + w.align_to_byte(); | |
| 315 | + let bytes = w.into_bytes(); | |
| 316 | + let mut r = BitCursor::new(&bytes, 0); | |
| 317 | + let code = r.read_ue().unwrap() as usize; | |
| 318 | + let table = if intra { CBP_INTRA_420 } else { CBP_INTER_420 }; | |
| 319 | + assert_eq!(table[code], luma | (chroma << 4)); | |
| 320 | + } | |
| 321 | + } | |
| 322 | + } | |
| 323 | +} |
crates/ec-h264/src/inter.rsmodified+192 -48
| @@ -98,11 +98,22 @@ fn load8(data: &[u8], at: usize) -> i16x8 { | ||
| 98 | 98 | i16x8::from(a) |
| 99 | 99 | } |
| 100 | 100 | |
| 101 | -/// The 6-tap half-sample filter of Equations 8-241/8-242 over sixteen | |
| 102 | -/// neighbouring positions at once, the taps spaced `step` apart. | |
| 101 | +/// The same 6-tap filter over eight neighbouring positions. | |
| 103 | 102 | /// |
| 104 | -/// The unrounded result of Equation 8-241 spans -2550..10710, so 16-bit lanes | |
| 105 | -/// hold it exactly and one row of a partition is one vector. | |
| 103 | +/// Eight lanes is one SSE2 register, which is the widest vector this crate can | |
| 104 | +/// assume without a target feature it is not allowed to require. A partition | |
| 105 | +/// narrower than sixteen samples therefore costs half or a quarter as much | |
| 106 | +/// here as it does in the sixteen-lane form, where the surplus lanes are | |
| 107 | +/// computed and then discarded. | |
| 108 | +#[inline] | |
| 109 | +fn tap6_8(data: &[u8], at: usize, step: usize) -> i16x8 { | |
| 110 | + let l = |k: isize| load8(data, (at as isize + k * step as isize) as usize); | |
| 111 | + let five = i16x8::splat(5); | |
| 112 | + let twenty = i16x8::splat(20); | |
| 113 | + l(-2) - five * l(-1) + twenty * l(0) + twenty * l(1) - five * l(2) + l(3) | |
| 114 | +} | |
| 115 | + | |
| 116 | +/// The same filter over sixteen positions, for a full-width partition. | |
| 106 | 117 | #[inline] |
| 107 | 118 | fn tap6_16(data: &[u8], at: usize, step: usize) -> i16x16 { |
| 108 | 119 | let l = |k: isize| load16(data, (at as isize + k * step as isize) as usize); |
| @@ -113,7 +124,18 @@ fn tap6_16(data: &[u8], at: usize, step: usize) -> i16x16 { | ||
| 113 | 124 | |
| 114 | 125 | /// `Clip1Y( ( v + 16 ) >> 5 )` over a row, storing the first `dst.len()` lanes. |
| 115 | 126 | #[inline] |
| 116 | -fn store_half(dst: &mut [u8], v: i16x16) { | |
| 127 | +fn store_half8(dst: &mut [u8], v: i16x8) { | |
| 128 | + let c = ((v + i16x8::splat(16)) >> 5u32) | |
| 129 | + .max(i16x8::ZERO) | |
| 130 | + .min(i16x8::splat(255)); | |
| 131 | + for (o, &s) in dst.iter_mut().zip(c.as_array()) { | |
| 132 | + *o = s as u8; | |
| 133 | + } | |
| 134 | +} | |
| 135 | + | |
| 136 | +/// The same over sixteen lanes. | |
| 137 | +#[inline] | |
| 138 | +fn store_half16(dst: &mut [u8], v: i16x16) { | |
| 117 | 139 | let c = ((v + i16x16::splat(16)) >> 5u32) |
| 118 | 140 | .max(i16x16::ZERO) |
| 119 | 141 | .min(i16x16::splat(255)); |
| @@ -122,6 +144,40 @@ fn store_half(dst: &mut [u8], v: i16x16) { | ||
| 122 | 144 | } |
| 123 | 145 | } |
| 124 | 146 | |
| 147 | +/// One 6-tap half-sample pass over a `w` x `h` block whose top-left sample is | |
| 148 | +/// `base`, into a `w`-pitch buffer. `step` is the tap spacing: 1 for the | |
| 149 | +/// horizontal filter, the plane stride for the vertical one. | |
| 150 | +/// | |
| 151 | +/// A partition is 16, 8 or 4 samples wide, so the narrow widths take a single | |
| 152 | +/// eight-lane vector rather than a sixteen-lane one whose upper half is | |
| 153 | +/// discarded. | |
| 154 | +#[inline] | |
| 155 | +fn half_block( | |
| 156 | + dst: &mut [u8], | |
| 157 | + data: &[u8], | |
| 158 | + base: usize, | |
| 159 | + stride: usize, | |
| 160 | + step: usize, | |
| 161 | + w: usize, | |
| 162 | + h: usize, | |
| 163 | +) { | |
| 164 | + if w == 16 { | |
| 165 | + for row in 0..h { | |
| 166 | + store_half16( | |
| 167 | + &mut dst[row * 16..row * 16 + 16], | |
| 168 | + tap6_16(data, base + row * stride, step), | |
| 169 | + ); | |
| 170 | + } | |
| 171 | + } else { | |
| 172 | + for row in 0..h { | |
| 173 | + store_half8( | |
| 174 | + &mut dst[row * w..row * w + w], | |
| 175 | + tap6_8(data, base + row * stride, step), | |
| 176 | + ); | |
| 177 | + } | |
| 178 | + } | |
| 179 | +} | |
| 180 | + | |
| 125 | 181 | /// Eight intermediate values as 32-bit lanes, zero past the end. |
| 126 | 182 | #[inline] |
| 127 | 183 | fn load_inter8(v: &[i16], at: usize) -> i32x8 { |
| @@ -170,6 +226,33 @@ fn avg_rows(out: &mut [u8], a: &[u8], b: &[u8], n: usize) { | ||
| 170 | 226 | } |
| 171 | 227 | } |
| 172 | 228 | |
| 229 | +/// The same average, written into a destination of pitch `os` from two | |
| 230 | +/// `w`-pitch sources. | |
| 231 | +#[inline] | |
| 232 | +fn avg_rows_to(out: &mut [u8], os: usize, a: &[u8], b: &[u8], w: usize, h: usize) { | |
| 233 | + if os == w { | |
| 234 | + avg_rows(out, a, b, w * h); | |
| 235 | + return; | |
| 236 | + } | |
| 237 | + for row in 0..h { | |
| 238 | + avg_rows( | |
| 239 | + &mut out[row * os..row * os + w], | |
| 240 | + &a[row * w..], | |
| 241 | + &b[row * w..], | |
| 242 | + w, | |
| 243 | + ); | |
| 244 | + } | |
| 245 | +} | |
| 246 | + | |
| 247 | +/// Copy `w` x `h` samples from a `w`-pitch source into an `os`-pitch | |
| 248 | +/// destination. | |
| 249 | +#[inline] | |
| 250 | +fn copy_rows(out: &mut [u8], os: usize, src: &[u8], w: usize, h: usize) { | |
| 251 | + for row in 0..h { | |
| 252 | + out[row * os..row * os + w].copy_from_slice(&src[row * w..row * w + w]); | |
| 253 | + } | |
| 254 | +} | |
| 255 | + | |
| 173 | 256 | #[inline] |
| 174 | 257 | fn clip8(v: i32) -> u8 { |
| 175 | 258 | v.clamp(0, 255) as u8 |
| @@ -184,9 +267,27 @@ fn avg(a: u8, b: u8) -> u8 { | ||
| 184 | 267 | /// plus the five taps of the horizontal filter. |
| 185 | 268 | const TMP_W: usize = 16 + 5; |
| 186 | 269 | |
| 270 | +/// Index of the top-left sample of a whole-sample block, clamped exactly as | |
| 271 | +/// [`mc_luma`] clamps it. | |
| 272 | +/// | |
| 273 | +/// A motion search spends most of its time on whole-sample positions, where | |
| 274 | +/// prediction is a copy; this lets it read the reference plane in place | |
| 275 | +/// instead of copying every candidate into a buffer first. | |
| 276 | +#[inline] | |
| 277 | +pub(crate) fn integer_origin(r: &RefPlane<'_>, x: i32, y: i32, w: usize, h: usize) -> usize { | |
| 278 | + let xi = clamp_origin(x, w, r.width, r.pad, 2, 3); | |
| 279 | + let yi = clamp_origin(y, h, r.height, r.pad, 2, 3); | |
| 280 | + r.at(xi, yi) | |
| 281 | +} | |
| 282 | + | |
| 187 | 283 | /// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose |
| 188 | 284 | /// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter |
| 189 | -/// samples. Writes `w` x `h` prediction samples into `out` at pitch `w`. | |
| 285 | +/// samples. Writes `w` x `h` prediction samples into `out` at pitch `os`. | |
| 286 | +/// | |
| 287 | +/// The pitch is a parameter so that the single-list, default-weight case — | |
| 288 | +/// which is most of a P slice — interpolates straight into the picture instead | |
| 289 | +/// of into a temporary that is then copied there. | |
| 290 | +#[allow(clippy::too_many_arguments)] | |
| 190 | 291 | pub(crate) fn mc_luma( |
| 191 | 292 | r: &RefPlane<'_>, |
| 192 | 293 | x: i32, |
| @@ -194,6 +295,7 @@ pub(crate) fn mc_luma( | ||
| 194 | 295 | mv: [i16; 2], |
| 195 | 296 | w: usize, |
| 196 | 297 | h: usize, |
| 298 | + os: usize, | |
| 197 | 299 | out: &mut [u8], |
| 198 | 300 | ) { |
| 199 | 301 | let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize); |
| @@ -206,7 +308,7 @@ pub(crate) fn mc_luma( | ||
| 206 | 308 | if fx == 0 && fy == 0 { |
| 207 | 309 | for row in 0..h { |
| 208 | 310 | let src = base + row * stride; |
| 209 | - out[row * w..row * w + w].copy_from_slice(&r.data[src..src + w]); | |
| 311 | + out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]); | |
| 210 | 312 | } |
| 211 | 313 | return; |
| 212 | 314 | } |
| @@ -221,19 +323,13 @@ pub(crate) fn mc_luma( | ||
| 221 | 323 | if need_b { |
| 222 | 324 | // "s" is the same filter one row down, so row fy>>1 selects b or s. |
| 223 | 325 | let row0 = yi + if fy == 3 { 1 } else { 0 }; |
| 224 | - for row in 0..h { | |
| 225 | - let src = r.at(xi, row0 + row as i32); | |
| 226 | - store_half(&mut bb[row * w..row * w + w], tap6_16(r.data, src, 1)); | |
| 227 | - } | |
| 326 | + half_block(&mut bb, r.data, r.at(xi, row0), stride, 1, w, h); | |
| 228 | 327 | } |
| 229 | 328 | let mut hh = [0u8; 16 * 17]; |
| 230 | 329 | if need_h { |
| 231 | 330 | // "m" is the same filter one column right, so column fx>>1 selects h or m. |
| 232 | 331 | let col0 = xi + if fx == 3 { 1 } else { 0 }; |
| 233 | - for row in 0..h { | |
| 234 | - let src = r.at(col0, yi + row as i32); | |
| 235 | - store_half(&mut hh[row * w..row * w + w], tap6_16(r.data, src, stride)); | |
| 236 | - } | |
| 332 | + half_block(&mut hh, r.data, r.at(col0, yi), stride, stride, w, h); | |
| 237 | 333 | } |
| 238 | 334 | let mut jj = [0u8; 16 * 16]; |
| 239 | 335 | if need_j { |
| @@ -243,10 +339,15 @@ pub(crate) fn mc_luma( | ||
| 243 | 339 | let mut inter = [0i16; TMP_W * (16 + 5)]; |
| 244 | 340 | for row in 0..h + 5 { |
| 245 | 341 | let src = r.at(xi, yi + row as i32 - 2); |
| 246 | - let v = tap6_16(r.data, src, 1); | |
| 247 | 342 | let base = row * TMP_W; |
| 248 | - for (o, &t) in inter[base..base + w].iter_mut().zip(v.as_array()) { | |
| 249 | - *o = t; | |
| 343 | + if w == 16 { | |
| 344 | + let v = tap6_16(r.data, src, 1); | |
| 345 | + inter[base..base + 16].copy_from_slice(v.as_array()); | |
| 346 | + } else { | |
| 347 | + let v = tap6_8(r.data, src, 1); | |
| 348 | + for (o, &t) in inter[base..base + w].iter_mut().zip(v.as_array()) { | |
| 349 | + *o = t; | |
| 350 | + } | |
| 250 | 351 | } |
| 251 | 352 | } |
| 252 | 353 | for row in 0..h { |
| @@ -261,13 +362,12 @@ pub(crate) fn mc_luma( | ||
| 261 | 362 | // Table 8-12: each quarter position is one of the half-sample arrays, or |
| 262 | 363 | // the average of two of them. Resolving it once per partition rather than |
| 263 | 364 | // once per sample is what keeps the copy loops straight. |
| 264 | - let n = w * h; | |
| 265 | 365 | match (fx, fy) { |
| 266 | - (2, 0) => out[..n].copy_from_slice(&bb[..n]), | |
| 267 | - (0, 2) => out[..n].copy_from_slice(&hh[..n]), | |
| 268 | - (2, 2) => out[..n].copy_from_slice(&jj[..n]), | |
| 269 | - (2, 1) | (2, 3) => avg_rows(out, &bb, &jj, n), | |
| 270 | - (1, 2) | (3, 2) => avg_rows(out, &hh, &jj, n), | |
| 366 | + (2, 0) => copy_rows(out, os, &bb, w, h), | |
| 367 | + (0, 2) => copy_rows(out, os, &hh, w, h), | |
| 368 | + (2, 2) => copy_rows(out, os, &jj, w, h), | |
| 369 | + (2, 1) | (2, 3) => avg_rows_to(out, os, &bb, &jj, w, h), | |
| 370 | + (1, 2) | (3, 2) => avg_rows_to(out, os, &hh, &jj, w, h), | |
| 271 | 371 | (1, 0) | (3, 0) | (0, 1) | (0, 3) => { |
| 272 | 372 | // Averaged with an integer sample one row or column over. |
| 273 | 373 | let (dx, dy) = match (fx, fy) { |
| @@ -278,17 +378,54 @@ pub(crate) fn mc_luma( | ||
| 278 | 378 | let half: &[u8] = if fy == 0 { &bb } else { &hh }; |
| 279 | 379 | for row in 0..h { |
| 280 | 380 | let src = base + (row + dy) * stride + dx; |
| 381 | + let s = &r.data[src..src + w]; | |
| 382 | + let hl = &half[row * w..row * w + w]; | |
| 383 | + let dst = &mut out[row * os..row * os + w]; | |
| 281 | 384 | for col in 0..w { |
| 282 | - out[row * w + col] = avg(r.data[src + col], half[row * w + col]); | |
| 385 | + dst[col] = avg(s[col], hl[col]); | |
| 283 | 386 | } |
| 284 | 387 | } |
| 285 | 388 | } |
| 286 | 389 | // Diagonal quarter positions: the two nearest half samples. |
| 287 | - _ => avg_rows(out, &bb, &hh, n), | |
| 390 | + _ => avg_rows_to(out, os, &bb, &hh, w, h), | |
| 391 | + } | |
| 392 | +} | |
| 393 | + | |
| 394 | +/// Equation 8-270 over a block of statically known width. | |
| 395 | +/// | |
| 396 | +/// The width is a const parameter because a chroma block is 2, 4 or 8 samples | |
| 397 | +/// wide and the 2x2 case dominates real streams: with `W` known the row slices | |
| 398 | +/// have constant length, which drops the bounds checks and lets the smallest | |
| 399 | +/// blocks compile to a handful of scalar multiplies instead of a vector setup | |
| 400 | +/// whose lanes are then thrown away. | |
| 401 | +#[inline] | |
| 402 | +fn chroma_rows<const W: usize>( | |
| 403 | + data: &[u8], | |
| 404 | + base: usize, | |
| 405 | + stride: usize, | |
| 406 | + h: usize, | |
| 407 | + wt: [u16; 4], | |
| 408 | + os: usize, | |
| 409 | + out: &mut [u8], | |
| 410 | +) { | |
| 411 | + for row in 0..h { | |
| 412 | + let src = base + row * stride; | |
| 413 | + let p = &data[src..src + W + 1]; | |
| 414 | + let q = &data[src + stride..src + stride + W + 1]; | |
| 415 | + let dst = &mut out[row * os..row * os + W]; | |
| 416 | + for c in 0..W { | |
| 417 | + let v = u16::from(p[c]) * wt[0] | |
| 418 | + + u16::from(p[c + 1]) * wt[1] | |
| 419 | + + u16::from(q[c]) * wt[2] | |
| 420 | + + u16::from(q[c + 1]) * wt[3] | |
| 421 | + + 32; | |
| 422 | + dst[c] = (v >> 6) as u8; | |
| 423 | + } | |
| 288 | 424 | } |
| 289 | 425 | } |
| 290 | 426 | |
| 291 | 427 | /// Chroma eighth-sample interpolation (Equation 8-270) of a `w` x `h` block. |
| 428 | +#[allow(clippy::too_many_arguments)] | |
| 292 | 429 | pub(crate) fn mc_chroma( |
| 293 | 430 | r: &RefPlane<'_>, |
| 294 | 431 | x: i32, |
| @@ -296,32 +433,32 @@ pub(crate) fn mc_chroma( | ||
| 296 | 433 | mv: [i16; 2], |
| 297 | 434 | w: usize, |
| 298 | 435 | h: usize, |
| 436 | + os: usize, | |
| 299 | 437 | out: &mut [u8], |
| 300 | 438 | ) { |
| 301 | - let (fx, fy) = ((mv[0] & 7) as i16, (mv[1] & 7) as i16); | |
| 439 | + let (fx, fy) = ((mv[0] & 7) as u16, (mv[1] & 7) as u16); | |
| 302 | 440 | let xi = clamp_origin(x + (mv[0] as i32 >> 3), w, r.width, r.pad, 0, 1); |
| 303 | 441 | let yi = clamp_origin(y + (mv[1] as i32 >> 3), h, r.height, r.pad, 0, 1); |
| 304 | 442 | let stride = r.stride; |
| 305 | 443 | let base = r.at(xi, yi); |
| 306 | - // The four weights sum to 64, so the weighted sum of Equation 8-270 never | |
| 307 | - // exceeds 64 * 255 and the whole bilinear fits in 16-bit lanes. A chroma | |
| 308 | - // block is at most eight samples wide, which is one vector per row. | |
| 309 | - let wa = i16x8::splat((8 - fx) * (8 - fy)); | |
| 310 | - let wb = i16x8::splat(fx * (8 - fy)); | |
| 311 | - let wc = i16x8::splat((8 - fx) * fy); | |
| 312 | - let wd = i16x8::splat(fx * fy); | |
| 313 | - let round = i16x8::splat(32); | |
| 314 | - for row in 0..h { | |
| 315 | - let src = base + row * stride; | |
| 316 | - let v = (load8(r.data, src) * wa | |
| 317 | - + load8(r.data, src + 1) * wb | |
| 318 | - + load8(r.data, src + stride) * wc | |
| 319 | - + load8(r.data, src + stride + 1) * wd | |
| 320 | - + round) | |
| 321 | - >> 6u32; | |
| 322 | - for (o, &s) in out[row * w..row * w + w].iter_mut().zip(v.as_array()) { | |
| 323 | - *o = s as u8; | |
| 444 | + | |
| 445 | + // Full sample: a straight copy. A zero motion vector is the most common | |
| 446 | + // vector in real content, and it lands here. | |
| 447 | + if fx == 0 && fy == 0 { | |
| 448 | + for row in 0..h { | |
| 449 | + let src = base + row * stride; | |
| 450 | + out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]); | |
| 324 | 451 | } |
| 452 | + return; | |
| 453 | + } | |
| 454 | + | |
| 455 | + // The four weights sum to 64, so the weighted sum of Equation 8-270 never | |
| 456 | + // exceeds 64 * 255 and the whole bilinear fits in 16-bit lanes. | |
| 457 | + let wt = [(8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy]; | |
| 458 | + match w { | |
| 459 | + 2 => chroma_rows::<2>(r.data, base, stride, h, wt, os, out), | |
| 460 | + 4 => chroma_rows::<4>(r.data, base, stride, h, wt, os, out), | |
| 461 | + _ => chroma_rows::<8>(r.data, base, stride, h, wt, os, out), | |
| 325 | 462 | } |
| 326 | 463 | } |
| 327 | 464 | |
| @@ -345,7 +482,9 @@ impl Weights { | ||
| 345 | 482 | o: [0, 0], |
| 346 | 483 | }; |
| 347 | 484 | |
| 348 | - fn is_default(&self) -> bool { | |
| 485 | + /// True when 8.4.2.3.1 applies, so a single-list prediction is its own | |
| 486 | + /// final prediction and needs no combining pass at all. | |
| 487 | + pub(crate) fn is_default(&self) -> bool { | |
| 349 | 488 | *self == Weights::DEFAULT |
| 350 | 489 | } |
| 351 | 490 | } |
| @@ -353,6 +492,11 @@ impl Weights { | ||
| 353 | 492 | /// Combine the list predictions of one partition into the final prediction |
| 354 | 493 | /// (spec 8.4.2.3). `p0`/`p1` hold `n` samples each; the entry for a list that |
| 355 | 494 | /// is not used is ignored. |
| 495 | +/// | |
| 496 | +/// The result is contiguous rather than written at the picture's pitch: the | |
| 497 | +/// bi-predictive average is the one case where the samples of several rows are | |
| 498 | +/// adjacent, and vectors that span the row boundary measured 6 to 9 per cent | |
| 499 | +/// fewer instructions on 1080p than a per-row average at picture pitch. | |
| 356 | 500 | pub(crate) fn combine( |
| 357 | 501 | out: &mut [u8], |
| 358 | 502 | p0: &[u8], |
| @@ -534,7 +678,7 @@ mod tests { | ||
| 534 | 678 | for fx in 0..4i16 { |
| 535 | 679 | for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] { |
| 536 | 680 | let mv = [fx - 20 * 4, fy + 12]; |
| 537 | - mc_luma(&r, px, py, mv, pw, ph, &mut ours); | |
| 681 | + mc_luma(&r, px, py, mv, pw, ph, pw, &mut ours); | |
| 538 | 682 | spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs); |
| 539 | 683 | assert_eq!( |
| 540 | 684 | ours[..pw * ph], |
| @@ -557,7 +701,7 @@ mod tests { | ||
| 557 | 701 | for fy in 0..8i16 { |
| 558 | 702 | for fx in 0..8i16 { |
| 559 | 703 | let mv = [fx, fy]; |
| 560 | - mc_chroma(&r, px, py, mv, 8, 8, &mut ours); | |
| 704 | + mc_chroma(&r, px, py, mv, 8, 8, 8, &mut ours); | |
| 561 | 705 | for row in 0..8i32 { |
| 562 | 706 | for col in 0..8i32 { |
| 563 | 707 | let s = |dx: i32, dy: i32| -> i32 { |
crates/ec-h264/src/lib.rsmodified+4 -2
| @@ -1,6 +1,6 @@ | ||
| 1 | -//! H.264 software decoder. | |
| 1 | +//! H.264 software decoder and encoder. | |
| 2 | 2 | //! |
| 3 | -//! Current scope: I, P and B slices under both entropy coders (CAVLC and | |
| 3 | +//! Decoder scope: I, P and B slices under both entropy coders (CAVLC and | |
| 4 | 4 | //! CABAC) of 8-bit 4:2:0 progressive streams — intra prediction, inter |
| 5 | 5 | //! prediction with the full decoded picture buffer of clause 8.2, weighted |
| 6 | 6 | //! prediction, and the in-loop deblocking filter — decoded bit-exactly against |
| @@ -41,6 +41,7 @@ mod codec; | ||
| 41 | 41 | mod deblock; |
| 42 | 42 | mod decoder; |
| 43 | 43 | mod dpb; |
| 44 | +mod enc; | |
| 44 | 45 | mod entropy; |
| 45 | 46 | mod inter; |
| 46 | 47 | mod mv; |
| @@ -51,3 +52,4 @@ mod transform; | ||
| 51 | 52 | pub use codec::H264Decoder; |
| 52 | 53 | pub use decoder::{Decoder, NalOutcome, OutputOrder}; |
| 53 | 54 | pub use ec_core::error::{Error, Result}; |
| 55 | +pub use enc::{EncodedPicture, Encoder, EncoderConfig, PictureView, Preset}; |