]> git.nihav.org Git - nihav.git/blob - nihav-llaudio/src/codecs/apereader.rs
acd602bd1b4dc507fba9763df896e6f15c84542b
[nihav.git] / nihav-llaudio / src / codecs / apereader.rs
1 use nihav_core::codecs::{DecoderError, DecoderResult};
2 use nihav_core::io::bitreader::*;
3 use nihav_core::io::intcode::*;
4
5 pub struct RiceParams {
6 k: u8,
7 sum: u32
8 }
9
10 impl RiceParams {
11 pub fn new() -> Self {
12 let k = 10;
13 Self { k, sum: 1 << (k + 4) }
14 }
15 fn update(&mut self, val: u32) {
16 let limit = if self.k > 0 { 1 << (self.k + 4) } else { 0 };
17 self.sum -= (self.sum + 16) >> 5;
18 self.sum += (val + 1) / 2;
19 if self.sum < limit {
20 self.k -= 1;
21 } else if (self.sum >= (1 << (self.k + 5))) && (self.k < 27) {
22 self.k += 1;
23 }
24 }
25 fn update_old(&mut self, val: u32) {
26 let limit = if self.k > 0 { 1 << (self.k + 4) } else { 0 };
27 self.sum -= (self.sum + 8) >> 4;
28 self.sum += val;
29 if self.sum < limit {
30 self.k -= 1;
31 } else if (self.sum >= (1 << (self.k + 5))) && (self.k < 24) {
32 self.k += 1;
33 }
34 }
35 }
36
37 pub struct RiceCoder<'a> {
38 br: BitReader<'a>,
39 rice_x: RiceParams,
40 rice_y: RiceParams,
41 }
42
43 impl<'a> RiceCoder<'a> {
44 pub fn new(br: BitReader<'a>) -> Self {
45 Self {
46 br,
47 rice_x: RiceParams::new(),
48 rice_y: RiceParams::new(),
49 }
50 }
51 }
52
53 struct ARangeCoder<'a> {
54 src: &'a [u8],
55 pos: usize,
56 low: u32,
57 range: u32,
58 help: u32,
59 buffer: u32,
60 error: bool,
61 }
62
63 pub struct RangeCoder<'a> {
64 rc: ARangeCoder<'a>,
65 rice_x: RiceParams,
66 rice_y: RiceParams,
67 }
68
69 impl<'a> RangeCoder<'a> {
70 pub fn new(src: &'a [u8]) -> Self {
71 Self {
72 rc: ARangeCoder::new(src),
73 rice_x: RiceParams::new(),
74 rice_y: RiceParams::new(),
75 }
76 }
77 fn had_errors(&self) -> bool { self.rc.error }
78 }
79
80 const RANGE_BITS: u8 = 32;
81 const TOP: u32 = 1 << (RANGE_BITS - 1);
82 const BOTTOM: u32 = TOP >> 8;
83 const START_BITS: u8 = ((RANGE_BITS - 2) & 7) + 1;
84
85 const MAX_MODEL_VAL: u32 = 63;
86
87 impl<'a> ARangeCoder<'a> {
88 fn new(src: &'a [u8]) -> Self {
89 let buffer = u32::from(src[0]);
90 Self {
91 src: &src[1..],
92 pos: 0,
93 low: buffer >> (8 - START_BITS),
94 range: 1 << START_BITS,
95 help: 0,
96 buffer,
97 error: false,
98 }
99 }
100 fn reset(&mut self) {
101 if self.pos == 0 {
102 self.error = true;
103 } else {
104 self.pos -= 1;
105 }
106 if self.pos < self.src.len() - 1 {
107 self.buffer = u32::from(self.src[self.pos]);
108 self.pos += 1;
109 }
110 self.low = self.buffer >> (8 - START_BITS);
111 self.range = 1 << START_BITS;
112 self.help = 0;
113 }
114 fn normalise(&mut self) {
115 while self.range <= BOTTOM {
116 self.buffer <<= 8;
117 if self.pos < self.src.len() {
118 self.buffer |= u32::from(self.src[self.pos]);
119 self.pos += 1;
120 } else {
121 self.error = true;
122 }
123 self.low <<= 8;
124 self.low |= (self.buffer >> 1) & 0xFF;
125 self.range <<= 8;
126 }
127 }
128 fn get_freq(&mut self, freq: u32) -> u32 {
129 self.normalise();
130 self.help = self.range / freq;
131 self.low / self.help
132 }
133 fn get_bits(&mut self, bits: u8) -> u32 {
134 self.normalise();
135 self.help = self.range >> bits;
136 self.low / self.help
137 }
138 fn update(&mut self, interval: u32, low: u32) {
139 self.low -= self.help * low;
140 self.range = self.help * interval;
141 }
142 fn decode_freq(&mut self, freq: u32) -> u32 {
143 let sym = self.get_freq(freq);
144 self.update(1, sym);
145 sym
146 }
147 fn decode_bits(&mut self, bits: u8) -> u32 {
148 let sym = self.get_bits(bits);
149 self.update(1, sym);
150 sym
151 }
152 fn decode_symbol(&mut self, freqs: &[u32; 22]) -> u32 {
153 let bits = self.get_bits(16);
154 if bits > 65492 {
155 let sym = bits + MAX_MODEL_VAL - 65535;
156 self.update(1, bits);
157 if bits > 65536 {
158 self.error = true;
159 }
160 sym
161 } else {
162 let mut sym = 0usize;
163 while freqs[sym + 1] <= bits {
164 sym += 1;
165 }
166 self.update(freqs[sym + 1] - freqs[sym], freqs[sym]);
167 sym as u32
168 }
169 }
170 }
171
172 pub enum Coder<'a> {
173 Rice(RiceCoder<'a>),
174 Range(RangeCoder<'a>),
175 }
176
177 fn to_signed(val: u32) -> i32 {
178 if (val & 1) != 0 {
179 (val >> 1) as i32 + 1
180 } else {
181 -((val >> 1) as i32)
182 }
183 }
184
185 pub fn decode_mono_dummy(_c: &mut Coder, _l: &mut [i32]) -> DecoderResult<()> {
186 unreachable!();
187 }
188 pub fn decode_stereo_dummy(_c: &mut Coder, _l: &mut [i32], _r: &mut [i32]) -> DecoderResult<()> {
189 unreachable!();
190 }
191
192 fn new_k(val: u32) -> u8 {
193 (32 - (val | 1).leading_zeros()) as u8
194 }
195 fn rice_limit(k: u8) -> u32 { if k > 0 { 1 << (k + 4) } else { 0 } }
196 fn decode_channel_0000(br: &mut BitReader, dst: &mut [i32]) -> DecoderResult<()> {
197 let (part01, part2) = dst.split_at_mut(64);
198 let (part0, part1) = part01.split_at_mut(5);
199 let mut pos = 0;
200 let mut last = [0u32; 64];
201 let mut sum = 0;
202 for el in part0.iter_mut() {
203 let val = br.read_code(UintCodeType::Rice(10))?;
204 sum += val;
205 *el = to_signed(val);
206 last[pos] = val;
207 pos += 1;
208 }
209 if part1.is_empty() {
210 return Ok(());
211 }
212 let mut k = new_k(sum / 10);
213 let mut w = 12;
214 for el in part1.iter_mut() {
215 let val = br.read_code(UintCodeType::Rice(k))?;
216 sum += val;
217 *el = to_signed(val);
218 k = new_k(sum / w);
219 w += 2;
220 last[pos] = val;
221 pos += 1;
222 }
223 if part2.is_empty() {
224 return Ok(());
225 }
226 let mut top_limit = rice_limit(k + 1) * 4;
227 let mut bot_limit = rice_limit(k) * 4;
228 pos = 0;
229 for el in part2.iter_mut() {
230 let val = br.read_code(UintCodeType::Rice(k))?;
231 *el = to_signed(val);
232
233 sum = sum.wrapping_add(val.wrapping_sub(last[pos]));
234 while sum < bot_limit {
235 k -= 1;
236 bot_limit = rice_limit(k) * 4;
237 top_limit >>= 1;
238 }
239 while sum >= top_limit {
240 k += 1;
241 validate!(k < 24);
242 bot_limit = rice_limit(k) * 4;
243 top_limit <<= 1;
244 }
245
246 last[pos] = val;
247 pos = (pos + 1) & 63;
248 }
249
250 Ok(())
251 }
252 pub fn decode_mono_0000(c: &mut Coder, l: &mut [i32]) -> DecoderResult<()> {
253 if let Coder::Rice(ref mut rr) = c {
254 decode_channel_0000(&mut rr.br, l)
255 } else {
256 Err(DecoderError::Bug)
257 }
258 }
259 pub fn decode_stereo_0000(c: &mut Coder, l: &mut [i32], r: &mut [i32]) -> DecoderResult<()> {
260 if let Coder::Rice(ref mut rr) = c {
261 decode_channel_0000(&mut rr.br, l)?;
262 decode_channel_0000(&mut rr.br, r)?;
263 Ok(())
264 } else {
265 Err(DecoderError::Bug)
266 }
267 }
268
269 fn decode_value_3860(br: &mut BitReader, rice: &mut RiceParams) -> DecoderResult<i32> {
270 let overflow = br.read_code(UintCodeType::UnaryZeroes)?;
271
272 let val = (overflow << rice.k) | br.read(rice.k)?;
273 rice.update_old(val);
274 Ok(to_signed(val))
275 }
276 fn decode_value_3890(br: &mut BitReader, rice: &mut RiceParams) -> DecoderResult<i32> {
277 let mut overflow = br.read_code(UintCodeType::UnaryZeroes)?;
278 while overflow >= 16 {
279 overflow -= 16;
280 rice.k += 4;
281 }
282
283 let val = (overflow << rice.k) | br.read(rice.k)?;
284 rice.update_old(val);
285 Ok(to_signed(val))
286 }
287 pub fn decode_mono_3860(c: &mut Coder, l: &mut [i32]) -> DecoderResult<()> {
288 if let Coder::Rice(ref mut rr) = c {
289 for el in l.iter_mut() {
290 *el = decode_value_3860(&mut rr.br, &mut rr.rice_y)?;
291 }
292 Ok(())
293 } else {
294 Err(DecoderError::Bug)
295 }
296 }
297 pub fn decode_mono_3890(c: &mut Coder, l: &mut [i32]) -> DecoderResult<()> {
298 if let Coder::Rice(ref mut rr) = c {
299 for el in l.iter_mut() {
300 *el = decode_value_3860(&mut rr.br, &mut rr.rice_y)?;
301 }
302 Ok(())
303 } else {
304 Err(DecoderError::Bug)
305 }
306 }
307 pub fn decode_stereo_3860(c: &mut Coder, l: &mut [i32], r: &mut [i32]) -> DecoderResult<()> {
308 if let Coder::Rice(ref mut rr) = c {
309 for el in l.iter_mut() {
310 *el = decode_value_3860(&mut rr.br, &mut rr.rice_y)?;
311 }
312 for el in r.iter_mut() {
313 *el = decode_value_3860(&mut rr.br, &mut rr.rice_x)?;
314 }
315 Ok(())
316 } else {
317 Err(DecoderError::Bug)
318 }
319 }
320 pub fn decode_stereo_3890(c: &mut Coder, l: &mut [i32], r: &mut [i32]) -> DecoderResult<()> {
321 if let Coder::Rice(ref mut rr) = c {
322 for el in l.iter_mut() {
323 *el = decode_value_3890(&mut rr.br, &mut rr.rice_y)?;
324 }
325 for el in r.iter_mut() {
326 *el = decode_value_3890(&mut rr.br, &mut rr.rice_x)?;
327 }
328 Ok(())
329 } else {
330 Err(DecoderError::Bug)
331 }
332 }
333
334 const COUNTS_3900: &[u32; 22] = &[
335 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
336 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
337 65450, 65469, 65480, 65487, 65491, 65493
338 ];
339 fn decode_value_3900(rc: &mut ARangeCoder, rice: &mut RiceParams) -> i32 {
340 let mut overflow = rc.decode_symbol(COUNTS_3900);
341 let k = if overflow == MAX_MODEL_VAL {
342 overflow = 0;
343 rc.decode_bits(5) as u8
344 } else {
345 rice.k.saturating_sub(1)
346 };
347 let base = rc.decode_bits(k);
348 let val = base + (overflow << k);
349 rice.update(val);
350 to_signed(val)
351 }
352 fn decode_value_3910(rc: &mut ARangeCoder, rice: &mut RiceParams) -> i32 {
353 let mut overflow = rc.decode_symbol(COUNTS_3900);
354 let k = if overflow == MAX_MODEL_VAL {
355 overflow = 0;
356 rc.decode_bits(5) as u8
357 } else {
358 rice.k.saturating_sub(1)
359 };
360 let base = if k <= 16 {
361 rc.decode_bits(k)
362 } else if k <= 32 {
363 let low = rc.decode_bits(k);
364 let high = rc.decode_bits(k - 16);
365 (high << (k - 16)) | low
366 } else {
367 rc.error = true;
368 return 0;
369 };
370 let val = base + (overflow << k);
371 rice.update(val);
372 to_signed(val)
373 }
374 pub fn decode_mono_3900(c: &mut Coder, l: &mut [i32]) -> DecoderResult<()> {
375 if let Coder::Range(ref mut rc) = c {
376 for el in l.iter_mut() {
377 *el = decode_value_3900(&mut rc.rc, &mut rc.rice_y);
378 }
379 validate!(!rc.had_errors());
380 Ok(())
381 } else {
382 Err(DecoderError::Bug)
383 }
384 }
385 pub fn decode_mono_3910(c: &mut Coder, l: &mut [i32]) -> DecoderResult<()> {
386 if let Coder::Range(ref mut rc) = c {
387 for el in l.iter_mut() {
388 *el = decode_value_3910(&mut rc.rc, &mut rc.rice_y);
389 }
390 validate!(!rc.had_errors());
391 Ok(())
392 } else {
393 Err(DecoderError::Bug)
394 }
395 }
396 pub fn decode_stereo_3900(c: &mut Coder, l: &mut [i32], r: &mut [i32]) -> DecoderResult<()> {
397 if let Coder::Range(ref mut rc) = c {
398 for el in l.iter_mut() {
399 *el = decode_value_3900(&mut rc.rc, &mut rc.rice_y);
400 }
401 rc.rc.normalise();
402 validate!(!rc.had_errors() && rc.rc.pos < rc.rc.src.len());
403 rc.rc.reset();
404 for el in r.iter_mut() {
405 *el = decode_value_3900(&mut rc.rc, &mut rc.rice_x);
406 }
407 validate!(!rc.had_errors());
408 Ok(())
409 } else {
410 Err(DecoderError::Bug)
411 }
412 }
413 pub fn decode_stereo_3910(c: &mut Coder, l: &mut [i32], r: &mut [i32]) -> DecoderResult<()> {
414 if let Coder::Range(ref mut rc) = c {
415 for el in l.iter_mut() {
416 *el = decode_value_3910(&mut rc.rc, &mut rc.rice_y);
417 }
418 rc.rc.normalise();
419 validate!(!rc.had_errors() && rc.rc.pos < rc.rc.src.len());
420 rc.rc.reset();
421 for el in r.iter_mut() {
422 *el = decode_value_3910(&mut rc.rc, &mut rc.rice_x);
423 }
424 validate!(!rc.had_errors());
425 Ok(())
426 } else {
427 Err(DecoderError::Bug)
428 }
429 }
430 pub fn decode_stereo_3930(c: &mut Coder, l: &mut [i32], r: &mut [i32]) -> DecoderResult<()> {
431 if let Coder::Range(ref mut rc) = c {
432 for (l, r) in l.iter_mut().zip(r.iter_mut()) {
433 *l = decode_value_3910(&mut rc.rc, &mut rc.rice_y);
434 *r = decode_value_3910(&mut rc.rc, &mut rc.rice_x);
435 }
436 validate!(!rc.had_errors());
437 Ok(())
438 } else {
439 Err(DecoderError::Bug)
440 }
441 }
442
443 const COUNTS_3990: &[u32; 22] = &[
444 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
445 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
446 65485, 65488, 65490, 65491, 65492, 65493
447 ];
448 fn decode_value_3990(rc: &mut ARangeCoder, rice: &mut RiceParams) -> i32 {
449 let pivot = (rice.sum >> 5).max(1);
450 let mut overflow = rc.decode_symbol(COUNTS_3990);
451 if overflow == MAX_MODEL_VAL {
452 overflow = rc.decode_bits(16) << 16;
453 overflow |= rc.decode_bits(16);
454 }
455 let base = if pivot < (1 << 16) {
456 rc.decode_freq(pivot)
457 } else {
458 let shift = (16 - pivot.trailing_zeros()) as u8;
459 let hi = rc.decode_freq((pivot >> shift) + 1);
460 let lo = rc.decode_bits(shift);
461 (hi << shift) | lo
462 };
463 let val = base + overflow * pivot;
464 rice.update(val);
465 to_signed(val)
466 }
467 pub fn decode_mono_3990(c: &mut Coder, l: &mut [i32]) -> DecoderResult<()> {
468 if let Coder::Range(ref mut rc) = c {
469 for el in l.iter_mut() {
470 *el = decode_value_3990(&mut rc.rc, &mut rc.rice_y);
471 }
472 validate!(!rc.had_errors());
473 Ok(())
474 } else {
475 Err(DecoderError::Bug)
476 }
477 }
478 pub fn decode_stereo_3990(c: &mut Coder, l: &mut [i32], r: &mut [i32]) -> DecoderResult<()> {
479 if let Coder::Range(ref mut rc) = c {
480 for (l, r) in l.iter_mut().zip(r.iter_mut()) {
481 *l = decode_value_3990(&mut rc.rc, &mut rc.rice_y);
482 *r = decode_value_3990(&mut rc.rc, &mut rc.rice_x);
483 }
484 validate!(!rc.had_errors());
485 Ok(())
486 } else {
487 Err(DecoderError::Bug)
488 }
489 }