forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

weighted.rs229 lines, 8.9 KiBHistoryRawDownload
1//! Weighted sample prediction (8.5.3.3.4): the default and explicit combinations
2//! of the interpolated `predSamplesLX` arrays into clipped output samples, and the
3//! derivation of `LumaWeightLX` and `ChromaWeightLX` from a parsed
4//! `pred_weight_table()` (7.4.7.3).
5
6use super::mc::{Block, PlaneMut, check_depth, check_out};
7use ec_core::error::{Error, Result};
8use ec_h265_syntax::PredWeightTable;
9
10/// One weight and its offset for one component of one reference picture.
11/// `o` already carries the `<< (BitDepth - 8)` of the explicit formula.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13pub struct Weight {
14 /// `LumaWeightLX` or `ChromaWeightLX`.
15 pub w: i32,
16 /// `o0` or `o1` of 8.5.3.3.4.3, after the bit depth shift.
17 pub o: i32,
18}
19
20/// The explicit weights of one slice: a denominator per component and, per list
21/// and reference index, a weight for Y, Cb and Cr.
22#[derive(Clone, Debug, Default, PartialEq, Eq)]
23pub struct ExplicitWeights {
24 /// `luma_log2_weight_denom` for Y, `ChromaLog2WeightDenom` for Cb and Cr.
25 pub log2_denom: [u32; 3],
26 /// `entries[list][ref_idx][component]`.
27 pub entries: [Vec<[Weight; 3]>; 2],
28}
29
30impl ExplicitWeights {
31 /// Derive the weights of a slice from its parsed `pred_weight_table()`.
32 ///
33 /// A reference whose luma (or chroma) weight flag was 0 gets the default
34 /// weight `2^denom` with offset 0. Offsets are scaled by
35 /// `1 << (BitDepth - 8)`, or not scaled with `high_precision_offsets`.
36 pub fn from_table(
37 table: &PredWeightTable,
38 bit_depth_luma: u32,
39 bit_depth_chroma: u32,
40 high_precision_offsets: bool,
41 ) -> Result<ExplicitWeights> {
42 check_depth(bit_depth_luma)?;
43 check_depth(bit_depth_chroma)?;
44 let luma_denom = table.luma_log2_weight_denom;
45 let chroma_denom = i64::from(luma_denom) + i64::from(table.delta_chroma_log2_weight_denom);
46 if luma_denom > 7 || !(0..=7).contains(&chroma_denom) {
47 return Err(Error::corrupt(
48 "HEVC pred_weight_table: weight denominator out of range",
49 ));
50 }
51 let chroma_denom = chroma_denom as u32;
52 // WpOffsetBdShift (7-56): 0 with high_precision_offsets_enabled_flag.
53 let shift_y = if high_precision_offsets {
54 0
55 } else {
56 bit_depth_luma - 8
57 };
58 let shift_c = if high_precision_offsets {
59 0
60 } else {
61 bit_depth_chroma - 8
62 };
63 let mut entries: [Vec<[Weight; 3]>; 2] = [Vec::new(), Vec::new()];
64 for (list, src) in [&table.l0, &table.l1].into_iter().enumerate() {
65 entries[list] = src
66 .iter()
67 .map(|e| -> Result<[Weight; 3]> {
68 let luma = match e.luma {
69 Some((dw, off)) => Weight {
70 w: (1 << luma_denom) + check_delta_weight(dw)?,
71 o: check_offset(off, bit_depth_luma, high_precision_offsets)?
72 << shift_y,
73 },
74 None => Weight {
75 w: 1 << luma_denom,
76 o: 0,
77 },
78 };
79 let mut out = [luma, Weight::default(), Weight::default()];
80 for (c, slot) in out.iter_mut().skip(1).enumerate() {
81 *slot = match e.chroma {
82 // `ChromaOffset` is already derived by 7-56 in the parser.
83 Some(pair) => {
84 let (dw, off) = pair[c];
85 Weight {
86 w: (1 << chroma_denom) + check_delta_weight(dw)?,
87 o: check_offset(off, bit_depth_chroma, high_precision_offsets)?
88 << shift_c,
89 }
90 }
91 None => Weight {
92 w: 1 << chroma_denom,
93 o: 0,
94 },
95 };
96 }
97 Ok(out)
98 })
99 .collect::<Result<Vec<_>>>()?;
100 }
101 Ok(ExplicitWeights {
102 log2_denom: [luma_denom, chroma_denom, chroma_denom],
103 entries,
104 })
105 }
106
107 /// The weight of `component` for `refIdxLX` `ref_idx` in list `list`.
108 pub fn lookup(&self, list: usize, ref_idx: usize, component: usize) -> Result<Weight> {
109 self.entries
110 .get(list)
111 .and_then(|l| l.get(ref_idx))
112 .map(|w| w[component])
113 .ok_or_else(|| {
114 Error::corrupt(format!(
115 "HEVC weighted prediction: no weights for list {list} index {ref_idx}"
116 ))
117 })
118 }
119}
120
121/// A coded `delta_luma_weight` or `delta_chroma_weight` lies in `-128..=127` (7.4.7.3).
122fn check_delta_weight(dw: i32) -> Result<i32> {
123 if (-128..=127).contains(&dw) {
124 Ok(dw)
125 } else {
126 Err(Error::corrupt(
127 "HEVC pred_weight_table: weight delta outside its range",
128 ))
129 }
130}
131
132/// Luma and chroma offsets are coded in `-128..=127` (7-54, 7-56 with the
133/// high-precision flag clear), or in `-(1 << (BitDepth - 1))..(1 << (BitDepth - 1))` with it.
134fn check_offset(o: i32, bit_depth: u32, high_precision: bool) -> Result<i32> {
135 let half = 1i32 << if high_precision { bit_depth - 1 } else { 7 };
136 if (-half..half).contains(&o) {
137 Ok(o)
138 } else {
139 Err(Error::corrupt(
140 "HEVC pred_weight_table: offset outside its range",
141 ))
142 }
143}
144
145/// Combine the interpolated arrays of one component into the output rectangle.
146///
147/// `pred[list]` is `Some` for each list in use, holding `blk.width * blk.height`
148/// values in row-major order. `explicit` carries `log2Wd`'s base denominator and
149/// the weights of both lists (the unused one is ignored); `None` selects the
150/// default weighted prediction.
151pub fn store(
152 dst: &mut PlaneMut<'_>,
153 blk: Block,
154 pred: [Option<&[i32]>; 2],
155 explicit: Option<(u32, [Weight; 2])>,
156) -> Result<()> {
157 check_out(dst, blk)?;
158 let bd = dst.bit_depth;
159 let max = (1i32 << bd) - 1;
160 // Equations of 8.5.3.3.4.2, with shift1 = 14 - bitDepth and shift2 = 15 - bitDepth.
161 let shift1 = 14 - bd;
162 let shift2 = 15 - bd;
163 let w = blk.width;
164 for r in 0..blk.height {
165 let base = (blk.y + r - dst.origin) * dst.stride + blk.x;
166 let row = &mut dst.samples[base..base + w];
167 let span = r * w..(r + 1) * w;
168 match (pred, explicit) {
169 ([Some(p), Some(q)], None) => {
170 bi_default(&p[span.clone()], &q[span], row, shift2, max);
171 }
172 ([Some(p), Some(q)], Some((denom, wt))) => {
173 bi_explicit(&p[span.clone()], &q[span], row, denom + shift1, wt, max);
174 }
175 ([Some(p), None], None) | ([None, Some(p)], None) => {
176 uni_default(&p[span], row, shift1, max);
177 }
178 ([Some(p), None], Some((denom, wt))) => {
179 uni_explicit(&p[span], row, denom + shift1, wt[0], max);
180 }
181 ([None, Some(p)], Some((denom, wt))) => {
182 uni_explicit(&p[span], row, denom + shift1, wt[1], max);
183 }
184 _ => {
185 return Err(Error::corrupt(
186 "HEVC weighted prediction: no prediction array for the block",
187 ));
188 }
189 }
190 }
191 Ok(())
192}
193
194/// Default uni-prediction: `Clip3(0, max, (predSamples + offset1) >> shift1)`.
195fn uni_default(pred: &[i32], out: &mut [u16], shift1: u32, max: i32) {
196 let offset1 = 1i32 << (shift1 - 1);
197 for (o, &p) in out.iter_mut().zip(pred) {
198 *o = ((p + offset1) >> shift1).clamp(0, max) as u16;
199 }
200}
201
202/// Default bi-prediction: `Clip3(0, max, (p0 + p1 + offset2) >> shift2)`.
203fn bi_default(p0: &[i32], p1: &[i32], out: &mut [u16], shift2: u32, max: i32) {
204 let offset2 = 1i32 << (shift2 - 1);
205 for ((o, &a), &b) in out.iter_mut().zip(p0).zip(p1) {
206 *o = ((a + b + offset2) >> shift2).clamp(0, max) as u16;
207 }
208}
209
210/// Explicit uni-prediction (8-252 and 8-253): `log2wd` is `denom + shift1`.
211fn uni_explicit(pred: &[i32], out: &mut [u16], log2wd: u32, wt: Weight, max: i32) {
212 for (o, &p) in out.iter_mut().zip(pred) {
213 let v = if log2wd >= 1 {
214 ((p * wt.w + (1 << (log2wd - 1))) >> log2wd) + wt.o
215 } else {
216 p * wt.w + wt.o
217 };
218 *o = v.clamp(0, max) as u16;
219 }
220}
221
222/// Explicit bi-prediction (8-254): `(p0*w0 + p1*w1 + ((o0 + o1 + 1) << log2wd)) >> (log2wd + 1)`.
223fn bi_explicit(p0: &[i32], p1: &[i32], out: &mut [u16], log2wd: u32, wt: [Weight; 2], max: i32) {
224 let [a, b] = wt;
225 let round = (a.o + b.o + 1) << log2wd;
226 for ((o, &p), &q) in out.iter_mut().zip(p0).zip(p1) {
227 *o = ((p * a.w + q * b.w + round) >> (log2wd + 1)).clamp(0, max) as u16;
228 }
229}