forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

entropy.rs315 lines, 11.1 KiBHistoryRawDownload
1//! One writing surface over both entropy coders, mirroring
2//! [`crate::entropy::Entropy`] on the decoding side.
3//!
4//! The macroblock coder writes syntax elements, not bits: which coder is in
5//! force changes the bins, the contexts and — for skipped macroblocks — the
6//! shape of the slice data itself (`mb_skip_run` against `mb_skip_flag`), and
7//! none of that belongs in the mode decision.
8
9use ec_core::BitWriter;
10
11use crate::entropy::{BlockCat, MbCtx};
12
13use super::cabac_enc::CabacEnc;
14use super::vlc::{write_cbp, write_residual_block};
15
16/// CAVLC's 4x4 sub-block `j` of an 8x8 block in 8x8 zigzag order (7.3.5.3.1,
17/// 8.5.7): coefficient `i` of sub-block `j` is `c8[4 * i + j]`.
18pub(crate) fn sub_block_4x4(c8: &[i32; 64], j: usize) -> [i32; 16] {
19 std::array::from_fn(|i| c8[4 * i + j])
20}
21
22#[derive(Clone)]
23pub(crate) enum EncEntropy {
24 Cavlc {
25 w: BitWriter,
26 /// Macroblocks skipped since the last coded one (7.3.4).
27 skip_run: u32,
28 },
29 Cabac(Box<CabacEnc>),
30}
31
32/// Append the bits of `src` from bit `from` to its end onto `dst`, bit for
33/// bit. `from` is the bit alignment `src` was started at, so that PCM
34/// alignment inside the appended bits is the same as in `dst`.
35pub(crate) fn append_bits(dst: &mut BitWriter, src: &BitWriter, from: u64) {
36 let bytes = src.as_bytes();
37 for pos in from..src.bit_len() {
38 let byte = bytes[(pos / 8) as usize];
39 dst.write_bit(byte >> (7 - pos % 8) & 1 == 1);
40 }
41}
42
43/// An empty writer at the same bit alignment as `w`, so that a write made into
44/// it costs exactly the bits it would cost in `w`.
45pub(crate) fn aligned_empty(w: &BitWriter) -> BitWriter {
46 let mut fresh = BitWriter::new();
47 for _ in 0..w.bit_len() % 8 {
48 fresh.write_bit(false);
49 }
50 fresh
51}
52
53impl EncEntropy {
54 /// A copy of this coder's state for measuring what a write costs. The
55 /// output buffer is not copied, so the cost is independent of how much of
56 /// the slice has been written; `bit_len` differences are the same as on
57 /// the real writer.
58 pub(crate) fn probe_copy(&self) -> EncEntropy {
59 match self {
60 EncEntropy::Cavlc { w, skip_run } => EncEntropy::Cavlc {
61 w: aligned_empty(w),
62 skip_run: *skip_run,
63 },
64 EncEntropy::Cabac(c) => EncEntropy::Cabac(Box::new(c.probe_copy())),
65 }
66 }
67
68 /// Take over `trial`, a [`EncEntropy::probe_copy`] of this coder taken
69 /// before the trial's writes, together with the bits those writes made.
70 /// The result is the same as having made the trial's writes to `self`:
71 /// the trial's state replaces this one and its bits are appended after
72 /// this coder's bits. Only valid while `self` is unchanged since the probe.
73 pub(crate) fn adopt(&mut self, trial: EncEntropy) {
74 match (self, trial) {
75 (
76 EncEntropy::Cavlc { w, skip_run },
77 EncEntropy::Cavlc {
78 w: tw,
79 skip_run: tskip,
80 },
81 ) => {
82 let from = w.bit_len() % 8;
83 append_bits(w, &tw, from);
84 *skip_run = tskip;
85 }
86 (EncEntropy::Cabac(c), EncEntropy::Cabac(t)) => c.adopt(*t),
87 _ => unreachable!("adopt across entropy coders"),
88 }
89 }
90
91 /// A CAVLC writer continuing after the slice header.
92 pub(crate) fn cavlc(w: BitWriter) -> EncEntropy {
93 EncEntropy::Cavlc { w, skip_run: 0 }
94 }
95
96 /// A CABAC writer: `cabac_alignment_one_bit`s to the byte boundary, then
97 /// the context and engine initialisation of 9.3.1.
98 pub(crate) fn cabac(mut w: BitWriter, slice_qp: i32, init_column: usize) -> EncEntropy {
99 while !w.is_byte_aligned() {
100 w.write_bit(true);
101 }
102 EncEntropy::Cabac(Box::new(CabacEnc::new(w, slice_qp, init_column)))
103 }
104
105 /// Bits written so far, for the row-level rate control.
106 pub(crate) fn bit_len(&self) -> u64 {
107 match self {
108 EncEntropy::Cavlc { w, .. } => w.bit_len(),
109 EncEntropy::Cabac(c) => c.bit_len(),
110 }
111 }
112
113 /// Publish the neighbourhood of the macroblock about to be written.
114 pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) {
115 if let EncEntropy::Cabac(c) = self {
116 c.begin_mb(ctx);
117 }
118 }
119
120 /// Declare whether this macroblock is intra coded (9.3.3.1.1.9).
121 pub(crate) fn set_intra(&mut self, intra: bool) {
122 if let EncEntropy::Cabac(c) = self {
123 c.set_intra(intra);
124 }
125 }
126
127 /// This macroblock is a skipped one.
128 pub(crate) fn skipped_mb(&mut self, inc: usize) {
129 match self {
130 EncEntropy::Cavlc { skip_run, .. } => *skip_run += 1,
131 EncEntropy::Cabac(c) => c.mb_skip_flag(true, inc),
132 }
133 }
134
135 /// This macroblock is coded; in a P slice that closes any run of skips.
136 pub(crate) fn coded_mb(&mut self, p_slice: bool, inc: usize) {
137 if !p_slice {
138 return;
139 }
140 match self {
141 EncEntropy::Cavlc { w, skip_run } => {
142 w.write_ue(*skip_run);
143 *skip_run = 0;
144 }
145 EncEntropy::Cabac(c) => c.mb_skip_flag(false, inc),
146 }
147 }
148
149 /// `mb_type`, in the slice's own numbering.
150 pub(crate) fn mb_type(&mut self, p_slice: bool, value: u32) {
151 match self {
152 EncEntropy::Cavlc { w, .. } => w.write_ue(value),
153 EncEntropy::Cabac(c) => {
154 if p_slice {
155 c.mb_type_p(value);
156 } else {
157 c.mb_type_i(value);
158 }
159 }
160 }
161 }
162
163 /// One `sub_mb_type` of a P macroblock (Table 7-17).
164 pub(crate) fn sub_mb_type_p(&mut self, value: u32) {
165 match self {
166 EncEntropy::Cavlc { w, .. } => w.write_ue(value),
167 EncEntropy::Cabac(c) => c.sub_mb_type_p(value),
168 }
169 }
170
171 /// One 4x4 intra prediction mode: `None` selects the predicted mode.
172 pub(crate) fn intra4x4_pred_mode(&mut self, rem: Option<u8>) {
173 match self {
174 EncEntropy::Cavlc { w, .. } => match rem {
175 None => w.write_bit(true),
176 Some(r) => {
177 w.write_bit(false);
178 w.write_bits(u32::from(r), 3);
179 }
180 },
181 EncEntropy::Cabac(c) => c.intra4x4_pred_mode(rem),
182 }
183 }
184
185 /// `transform_size_8x8_flag` (7.3.5), where the decoder reads it: after
186 /// mb_type for an Intra_NxN macroblock, after coded_block_pattern for an
187 /// eligible inter one.
188 pub(crate) fn transform_size_8x8_flag(&mut self, flag: bool) {
189 match self {
190 EncEntropy::Cavlc { w, .. } => w.write_bit(flag),
191 EncEntropy::Cabac(c) => c.transform_size_8x8_flag(flag),
192 }
193 }
194
195 pub(crate) fn intra_chroma_pred_mode(&mut self, mode: u8) {
196 match self {
197 EncEntropy::Cavlc { w, .. } => w.write_ue(u32::from(mode)),
198 EncEntropy::Cabac(c) => c.intra_chroma_pred_mode(mode),
199 }
200 }
201
202 pub(crate) fn coded_block_pattern(&mut self, luma: u8, chroma: u8, intra: bool) {
203 match self {
204 EncEntropy::Cavlc { w, .. } => write_cbp(w, luma, chroma, intra),
205 EncEntropy::Cabac(c) => c.coded_block_pattern(luma, chroma),
206 }
207 }
208
209 pub(crate) fn mb_qp_delta(&mut self, delta: i32) {
210 match self {
211 EncEntropy::Cavlc { w, .. } => w.write_se(delta),
212 EncEntropy::Cabac(c) => c.mb_qp_delta(delta),
213 }
214 }
215
216 /// One `mvd_lX` component; `inc` is the 9.3.3.1.1.7 increment, unused by
217 /// CAVLC.
218 pub(crate) fn mvd(&mut self, comp: usize, inc: usize, value: i32) {
219 match self {
220 EncEntropy::Cavlc { w, .. } => w.write_se(value),
221 EncEntropy::Cabac(c) => c.mvd(comp, inc, value),
222 }
223 }
224
225 /// One residual block in scan order; returns its non-zero count, which the
226 /// caller records for the neighbours.
227 ///
228 /// `Luma8x8` (64 coefficients, 8x8 zigzag order) is CABAC only; the decoder
229 /// records its count in all four 4x4 slots. Under CAVLC the caller writes
230 /// the four [`sub_block_4x4`] blocks as `Luma4x4`, each with its own nC
231 /// and its own count (decoder.rs finish_macroblock, CAVLC branch).
232 pub(crate) fn residual_block(
233 &mut self,
234 coeff: &[i32],
235 cat: BlockCat,
236 na: Option<u8>,
237 nb: Option<u8>,
238 ) -> u8 {
239 if cat == BlockCat::Luma8x8 {
240 let EncEntropy::Cabac(c) = self else {
241 unreachable!("CAVLC codes an 8x8 block as four interleaved 4x4 blocks");
242 };
243 return c.residual_block_8x8(coeff.try_into().expect("64 coefficients"));
244 }
245 match self {
246 EncEntropy::Cavlc { w, .. } => {
247 let nc = if matches!(cat, BlockCat::ChromaDc(_)) {
248 -1
249 } else {
250 match (na, nb) {
251 (Some(a), Some(b)) => (i32::from(a) + i32::from(b) + 1) >> 1,
252 (Some(a), None) => i32::from(a),
253 (None, Some(b)) => i32::from(b),
254 (None, None) => 0,
255 }
256 };
257 write_residual_block(w, coeff, cat.max_num_coeff(), nc)
258 }
259 EncEntropy::Cabac(c) => c.residual_block(coeff, cat, na, nb),
260 }
261 }
262
263 /// What [`Self::residual_block`] would spend on `coeff`, in 1/256ths of a
264 /// bit, without writing it. `None` under CAVLC, whose cost a caller can
265 /// only estimate.
266 pub(crate) fn residual_block_8x8_cost(&self, coeff: &[i32; 64]) -> Option<u32> {
267 match self {
268 EncEntropy::Cavlc { .. } => None,
269 EncEntropy::Cabac(c) => Some(c.residual_block_8x8_cost(coeff)),
270 }
271 }
272
273 pub(crate) fn residual_block_cost(
274 &self,
275 coeff: &[i32],
276 cat: BlockCat,
277 na: Option<u8>,
278 nb: Option<u8>,
279 ) -> Option<u32> {
280 match self {
281 EncEntropy::Cavlc { .. } => None,
282 EncEntropy::Cabac(c) => Some(c.residual_block_cost(coeff, cat, na, nb)),
283 }
284 }
285
286 pub(crate) fn is_cabac(&self) -> bool {
287 matches!(self, EncEntropy::Cabac(_))
288 }
289
290 /// `end_of_slice_flag` after a macroblock (CABAC only).
291 pub(crate) fn end_of_slice(&mut self, last: bool) {
292 if let (EncEntropy::Cabac(c), false) = (self, last) {
293 c.not_end_of_slice();
294 }
295 }
296
297 /// Close the slice and hand back its RBSP.
298 pub(crate) fn finish(self, p_slice: bool) -> Vec<u8> {
299 match self {
300 EncEntropy::Cavlc { mut w, skip_run } => {
301 if p_slice && skip_run > 0 {
302 // A slice ending in skipped macroblocks says so with a
303 // final mb_skip_run; writing one when nothing was skipped
304 // would instead promise another macroblock (7.3.4).
305 w.write_ue(skip_run);
306 }
307 w.write_bit(true); // rbsp_stop_one_bit
308 w.align_to_byte();
309 w.into_bytes()
310 }
311 // EncodeFlush already wrote the stop bit (9.3.4.6).
312 EncEntropy::Cabac(c) => c.finish().into_bytes(),
313 }
314 }
315}