1 use nihav_core::codecs::*;
2 use nihav_core::io::byteio::*;
3 use nihav_core::io::bitreader::*;
4 use nihav_core::io::intcode::*;
6 const SAMPLE_RATES: [u32; 15] = [
7 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000,
8 32000, 44100, 48000, 64000, 88200, 96000, 192000
10 const WV_FLAG_MONO: u32 = 1 << 2;
11 const WV_FLAG_HYBRID: u32 = 1 << 3;
12 const WV_FLAG_JSTEREO: u32 = 1 << 4;
13 //const WV_FLAG_CH_DECORR: u32 = 1 << 5;
14 //const WV_FLAG_HYB_NOISE_SHAPING: u32 = 1 << 6;
15 const WV_FLAG_FLOATS: u32 = 1 << 7;
16 const WV_FLAG_EXT_INTEGERS: u32 = 1 << 8;
17 const WV_FLAG_HYB_BITRATE: u32 = 1 << 9;
18 //const WV_FLAG_HYB_BALANCED_NOISE: u32 = 1 << 10;
19 const WV_FLAG_START_BLOCK: u32 = 1 << 11;
20 const WV_FLAG_END_BLOCK: u32 = 1 << 12;
21 //const WV_FLAG_HAS_CRC: u32 = 1 << 28;
22 const WV_FLAG_FALSE_STEREO: u32 = 1 << 30;
23 const WV_FLAG_DSD_AUDIO: u32 = 1 << 31;
25 const WV_STREAM_FLAGS: u32 = 0x8000008B;
27 #[derive(Clone,Copy,Default)]
38 const WV_HEADER_SIZE: usize = 32;
41 fn parse(src: &[u8]) -> DecoderResult<Self> {
42 let mut mr = MemoryReader::new_read(src);
43 let mut br = ByteReader::new(&mut mr);
44 let tag = br.read_tag()?;
45 validate!(&tag == b"wvpk");
46 let mut hdr = Self::default();
47 hdr.size = br.read_u32le()? as usize;
48 validate!(hdr.size >= 24);
49 hdr.ver = br.read_u16le()?;
50 validate!(hdr.ver >= 0x402 || hdr.ver <= 0x410);
51 let top_idx = br.read_byte()?;
52 let top_samps = br.read_byte()?;
53 hdr.tot_samples = u64::from(br.read_u32le()?) | (u64::from(top_samps) << 32);
54 hdr.block_index = u64::from(br.read_u32le()?) | (u64::from(top_idx) << 32);
55 hdr.block_samples = br.read_u32le()?;
56 hdr.flags = br.read_u32le()?;
57 hdr.crc = br.read_u32le()?;
60 fn stream_eq(&self, rval: &Self) -> bool {
61 self.ver == rval.ver &&
62 (self.flags & WV_STREAM_FLAGS) == (rval.flags & WV_STREAM_FLAGS)
64 fn block_eq(&self, rval: &Self) -> bool {
65 self.stream_eq(rval) && self.block_index == rval.block_index &&
66 self.tot_samples == rval.tot_samples &&
67 self.block_samples == rval.block_samples
69 fn is_start_block(&self) -> bool {
70 (self.flags & WV_FLAG_START_BLOCK) != 0
72 fn is_end_block(&self) -> bool {
73 (self.flags & WV_FLAG_END_BLOCK) != 0
75 fn get_num_channels(&self) -> u8 {
76 if (self.flags & WV_FLAG_MONO) != 0 && (self.flags & WV_FLAG_FALSE_STEREO) == 0 { 1 } else { 2 }
78 fn get_sample_rate(&self) -> u32 {
79 let idx = ((self.flags >> 23) & 0xF) as usize;
86 fn get_size(&self) -> usize {
87 self.size - (WV_HEADER_SIZE - 8)
89 fn get_bits(&self) -> u8 {
90 (((self.flags & 3) + 1) * 8) as u8
94 fn wv_log2lin(val: i32) -> i32 {
97 let mant = 0x100 | i32::from(WV_EXP_TABLE[(aval & 0xFF) as usize]);
99 let aval = if exp >= 9 {
111 fn wv_lin2log(val: u32) -> u32 {
117 let val = val + (val >> 9);
118 let bits = 32 - val.leading_zeros();
120 (bits << 8) + u32::from(WV_LOG_TABLE[((val << (9 - bits)) & 0xFF) as usize])
122 (bits << 8) + u32::from(WV_LOG_TABLE[((val >> (bits - 9)) & 0xFF) as usize])
127 #[derive(Clone,Copy,Default)]
128 struct Decorrelator {
138 fn decorrelate_mono(&mut self, l: i32, pos: usize) -> i32 {
139 let mode = self.value;
140 let (a, npos) = if mode > 8 {
141 let a = if (mode & 1) != 0 {
142 2 * self.samples_a[0] - self.samples_a[1]
144 (3 * self.samples_a[0] - self.samples_a[1]) >> 1
146 self.samples_a[1] = self.samples_a[0];
149 (self.samples_a[pos], (pos + mode as usize) & 7)
151 let l2 = l + ((i64::from(self.weight_a) * i64::from(a) + 512) >> 10) as i32;
152 if (a != 0) && (l != 0) {
153 self.weight_a -= ((((l ^ a) >> 30) & 2) - 1) * self.delta;
155 self.samples_a[npos] = l2;
158 fn decorrelate_stereo(&mut self, l: i32, r: i32, pos: usize) -> (i32, i32) {
159 let mode = self.value;
161 let (a, b, npos) = if mode > 8 {
162 let (a, b) = if (mode & 1) != 0 {
163 (2 * self.samples_a[0] - self.samples_a[1],
164 2 * self.samples_b[0] - self.samples_b[1])
166 ((3 * self.samples_a[0] - self.samples_a[1]) >> 1,
167 (3 * self.samples_b[0] - self.samples_b[1]) >> 1)
169 self.samples_a[1] = self.samples_a[0];
170 self.samples_b[1] = self.samples_b[0];
173 (self.samples_a[pos], self.samples_b[pos], (pos + mode as usize) & 7)
175 let l2 = l + ((i64::from(self.weight_a) * i64::from(a) + 512) >> 10) as i32;
176 let r2 = r + ((i64::from(self.weight_b) * i64::from(b) + 512) >> 10) as i32;
177 if (a != 0) && (l != 0) {
178 self.weight_a -= ((((l ^ a) >> 30) & 2) - 1) * self.delta;
180 if (b != 0) && (r != 0) {
181 self.weight_b -= ((((r ^ b) >> 30) & 2) - 1) * self.delta;
183 self.samples_a[npos] = l2;
184 self.samples_b[npos] = r2;
186 } else if mode == -1 {
187 let l2 = l + ((i64::from(self.weight_a) * i64::from(self.samples_a[0]) + 512) >> 10) as i32;
188 let r2 = r + ((i64::from(self.weight_b) * i64::from(l2) + 512) >> 10) as i32;
189 self.update_weight_a(self.samples_a[0], l);
190 self.update_weight_b(l2, r);
191 self.samples_a[0] = r2;
194 let r2 = r + ((i64::from(self.weight_b) * i64::from(self.samples_b[0]) + 512) >> 10) as i32;
195 self.update_weight_b(self.samples_b[0], r);
196 let rr = if mode == -3 {
197 let nr = self.samples_a[0];
198 self.samples_a[0] = r2;
203 let l2 = l + ((i64::from(self.weight_a) * i64::from(rr) + 512) >> 10) as i32;
204 self.update_weight_a(rr, l);
205 self.samples_b[0] = l2;
209 fn update_weight_a(&mut self, l: i32, r: i32) {
210 if (l != 0) && (r != 0) {
212 self.weight_a = (self.weight_a - self.delta).max(-1024)
214 self.weight_a = (self.weight_a + self.delta).min(1024)
218 fn update_weight_b(&mut self, l: i32, r: i32) {
219 if (l != 0) && (r != 0) {
221 self.weight_b = (self.weight_b - self.delta).max(-1024)
223 self.weight_b = (self.weight_b + self.delta).min(1024)
231 median: [[u32; 3]; 2],
240 slow_level: [u32; 2],
250 fn read_biased_code(br: &mut BitReader) -> DecoderResult<u32> {
251 let val = br.read_code(UintCodeType::UnaryOnes)?;
257 Ok((1 << bits) | br.read(bits as u8)?)
260 fn read_tail(br: &mut BitReader, bits: u32) -> DecoderResult<u32> {
264 let p = 31 - bits.leading_zeros();
265 let esc = (1 << (p + 1)) - (bits + 1);
266 let val = br.read(p as u8)?;
270 Ok(val * 2 - esc + br.read(1)?)
276 fn read_sample(&mut self, br: &mut BitReader, channel: usize) -> DecoderResult<i32> {
277 if (self.median[0][0] < 2) && (self.median[1][0] < 2) && !self.zero && !self.one {
278 if self.num_zeroes > 0 {
279 self.num_zeroes -= 1;
280 if self.num_zeroes != 0 {
284 self.num_zeroes = read_biased_code(br)?;
285 if self.num_zeroes != 0 {
286 self.median = [[0; 3]; 2];
291 let val = if self.zero {
295 let mut val = br.read_code(UintCodeType::UnaryOnes)?;
296 validate!(val <= 16);
298 val += read_biased_code(br)?;
300 let one = (val & 1) != 0;
310 let (base, add) = match val {
312 let add = self.get_median(channel, 0) - 1;
313 self.dec_median(channel, 0);
317 let base = self.get_median(channel, 0);
318 let add = self.get_median(channel, 1) - 1;
319 self.inc_median(channel, 0);
320 self.dec_median(channel, 1);
324 let base = self.get_median(channel, 0) + self.get_median(channel, 1);
325 let add = self.get_median(channel, 2) - 1;
326 self.inc_median(channel, 0);
327 self.inc_median(channel, 1);
328 self.dec_median(channel, 2);
332 let base = self.get_median(channel, 0) + self.get_median(channel, 1) + self.get_median(channel, 2) * (val - 2);
333 let add = self.get_median(channel, 2) - 1;
334 self.inc_median(channel, 0);
335 self.inc_median(channel, 1);
336 self.inc_median(channel, 2);
340 let val = base + read_tail(br, add)?;
342 if !br.read_bool()? {
348 fn read_sample_hyb(&mut self, br: &mut BitReader, channel: usize) -> DecoderResult<i32> {
349 if (self.median[0][0] < 2) && (self.median[1][0] < 2) && !self.zero && !self.one {
350 if self.num_zeroes > 0 {
351 self.num_zeroes -= 1;
352 if self.num_zeroes != 0 {
353 self.decay_slev(channel);
357 self.num_zeroes = read_biased_code(br)?;
358 if self.num_zeroes != 0 {
359 self.median = [[0; 3]; 2];
360 self.decay_slev(channel);
365 let val = if self.zero {
369 let mut val = br.read_code(UintCodeType::UnaryOnes)?;
370 validate!(val <= 16);
372 val += read_biased_code(br)?;
374 let one = (val & 1) != 0;
385 self.update_error_limit();
388 let (mut base, mut add) = match val {
390 let add = self.get_median(channel, 0) - 1;
391 self.dec_median(channel, 0);
395 let base = self.get_median(channel, 0);
396 let add = self.get_median(channel, 1) - 1;
397 self.inc_median(channel, 0);
398 self.dec_median(channel, 1);
402 let base = self.get_median(channel, 0) + self.get_median(channel, 1);
403 let add = self.get_median(channel, 2) - 1;
404 self.inc_median(channel, 0);
405 self.inc_median(channel, 1);
406 self.dec_median(channel, 2);
410 let base = self.get_median(channel, 0) + self.get_median(channel, 1) + self.get_median(channel, 2) * (val - 2);
411 let add = self.get_median(channel, 2) - 1;
412 self.inc_median(channel, 0);
413 self.inc_median(channel, 1);
414 self.inc_median(channel, 2);
418 let val = if self.error_lim[channel] == 0 {
419 base + read_tail(br, add)?
421 let mut mid = (base * 2 + add + 1) >> 1;
422 while add > self.error_lim[channel] {
428 add = mid - base - 1;
430 mid = (base * 2 + add + 1) >> 1;
436 self.decay_slev(channel);
437 self.slow_level[channel] += wv_lin2log(val);
440 if !br.read_bool()? {
446 fn decay_slev(&mut self, channel: usize) {
447 self.slow_level[channel] -= (self.slow_level[channel] + 0x80) >> 8;
449 fn update_error_limit(&mut self) {
454 self.br_acc[i] += self.br_delta[i];
455 br[i] = self.br_acc[i] >> 16;
456 sl[i] = (self.slow_level[i] + 0x80) >> 8;
459 if self.stereo && self.has_hbr {
460 let balance = ((sl[1] as i32) - (sl[0] as i32) + (br[1] as i32) + 1) >> 1;
461 if balance > (br[0] as i32) {
464 } else if -balance > (br[0] as i32) {
468 br[1] = ((br[0] as i32) + balance) as u32;
469 br[0] = ((br[0] as i32) - balance) as u32;
473 self.error_lim[i] = if self.has_hbr {
474 if sl[i] + 0x100 > br[i] {
475 wv_log2lin((sl[i] + 0x100 - br[i]) as i32) as u32
480 wv_log2lin(br[i] as i32) as u32
484 fn get_median(&self, channel: usize, idx: usize) -> u32 {
485 (self.median[channel][idx] >> 4) + 1
487 fn inc_median(&mut self, channel: usize, idx: usize) {
488 self.median[channel][idx] += ((self.median[channel][idx] + (128 >> idx)) / (128 >> idx)) * 5;
490 fn dec_median(&mut self, channel: usize, idx: usize) {
491 self.median[channel][idx] -= ((self.median[channel][idx] + (128 >> idx) - 2) / (128 >> idx)) * 2;
493 fn produce_sample_common(&self, ebr: &mut BitReader, mut samp: i32) -> i32 {
496 if ebr.left() >= self.ebits as isize {
497 samp |= ebr.read(self.ebits).unwrap_or(0) as i32;
500 let bit = (samp & self.and) | self.or;
501 ((samp + bit) << self.shift) - bit
503 fn produce_sample(&self, ebr: &mut BitReader, samp: i32) -> i32 {
504 self.produce_sample_common(ebr, samp) << self.post_shift
506 fn produce_sample_hyb(&self, ebr: &mut BitReader, samp: i32) -> i32 {
507 self.produce_sample_common(ebr, samp).max(self.hyb_min).min(self.hyb_max) << self.post_shift
512 decorr: [Decorrelator; 16],
519 decorr: [Decorrelator::default(); 16],
523 fn reset(&mut self) {
524 self.decorr = [Decorrelator::default(); 16];
529 struct WavPackDecoder {
537 fn get_subblock(br: &mut ByteReader) -> DecoderResult<(u8, usize)> {
538 let id1 = br.read_byte()?;
540 let mut len = 2 * if (id1 & 0x80) == 0 {
541 br.read_byte()? as usize
543 br.read_u24le()? as usize
545 if (id1 & 0x40) != 0 {
553 fn set(&mut self, val: i32);
556 impl Output for i16 {
557 fn set(&mut self, val: i32) { *self = val as i16; }
559 impl Output for i32 {
560 fn set(&mut self, val: i32) { *self = val; }
563 fn unpack_mono<T: Output+Copy>(br: &mut BitReader, ebr: &mut BitReader, state: &mut DecState, decorr: &mut DecorrState, dst: &mut [T], len: usize) -> DecoderResult<u32> {
564 let mut crc = 0xFFFFFFFFu32;
566 for (i, dst) in dst[..len].iter_mut().enumerate() {
567 let mut l = state.read_sample(br, 0)?;
568 for decorr in decorr.decorr[..decorr.num_decorr].iter_mut() {
569 l = decorr.decorrelate_mono(l, i & 7);
571 crc = crc.wrapping_mul(3).wrapping_add(l as u32);
572 l = state.produce_sample(ebr, l);
579 #[allow(clippy::too_many_arguments)]
580 fn unpack_stereo<T: Output+Copy>(br: &mut BitReader, ebr: &mut BitReader, state: &mut DecState, decorr: &mut DecorrState, dst: &mut [T], off0: usize, off1: usize, len: usize, is_joint: bool) -> DecoderResult<u32> {
581 let mut crc = 0xFFFFFFFFu32;
584 let mut l = state.read_sample(br, 0)?;
585 let mut r = state.read_sample(br, 1)?;
586 for decorr in decorr.decorr[..decorr.num_decorr].iter_mut() {
587 let (pl, pr) = decorr.decorrelate_stereo(l, r, i & 7);
595 crc = crc.wrapping_mul(3).wrapping_add(l as u32).wrapping_mul(3).wrapping_add(r as u32);
596 l = state.produce_sample(ebr, l);
597 r = state.produce_sample(ebr, r);
598 dst[off0 + i].set(l);
599 dst[off1 + i].set(r);
605 fn unpack_mono_hyb<T: Output+Copy>(br: &mut BitReader, ebr: &mut BitReader, state: &mut DecState, decorr: &mut DecorrState, dst: &mut [T], len: usize) -> DecoderResult<u32> {
606 let mut crc = 0xFFFFFFFFu32;
608 for (i, dst) in dst[..len].iter_mut().enumerate() {
609 let mut l = state.read_sample_hyb(br, 0)?;
610 for decorr in decorr.decorr[..decorr.num_decorr].iter_mut() {
611 l = decorr.decorrelate_mono(l, i & 7);
613 crc = crc.wrapping_mul(3).wrapping_add(l as u32);
614 l = state.produce_sample_hyb(ebr, l);
621 #[allow(clippy::too_many_arguments)]
622 fn unpack_stereo_hyb<T: Output+Copy>(br: &mut BitReader, ebr: &mut BitReader, state: &mut DecState, decorr: &mut DecorrState, dst: &mut [T], off0: usize, off1: usize, len: usize, is_joint: bool) -> DecoderResult<u32> {
623 let mut crc = 0xFFFFFFFFu32;
626 let mut l = state.read_sample_hyb(br, 0)?;
627 let mut r = state.read_sample_hyb(br, 1)?;
628 for decorr in decorr.decorr[..decorr.num_decorr].iter_mut() {
629 let (pl, pr) = decorr.decorrelate_stereo(l, r, i & 7);
637 crc = crc.wrapping_mul(3).wrapping_add(l as u32).wrapping_mul(3).wrapping_add(r as u32);
638 l = state.produce_sample_hyb(ebr, l);
639 r = state.produce_sample_hyb(ebr, r);
640 dst[off0 + i].set(l);
641 dst[off1 + i].set(r);
647 impl WavPackDecoder {
650 ainfo: NAAudioInfo::new(0, 1, SND_S16P_FORMAT, 0),
651 chmap: NAChannelMap::new(),
652 header: WVHeader::default(),
654 dstate: DecorrState::new(),
657 #[allow(clippy::cognitive_complexity)]
658 fn decode_block(&mut self, hdr: &WVHeader, src: &[u8], start_ch: usize, abuf: &mut NABufferType) -> DecoderResult<()> {
659 let mut mr = MemoryReader::new_read(src);
660 let mut br = ByteReader::new(&mut mr);
661 let mut has_terms = false;
662 let mut has_weights = false;
663 let mut has_samples = false;
664 let mut has_hybrid = false;
665 let is_mono = (hdr.flags & (WV_FLAG_MONO | WV_FLAG_FALSE_STEREO)) != 0;
666 let cur_channels = if is_mono { 1 } else { 2 };
667 let mut data_pos = 0;
668 let mut data_len = 0;
669 let mut ebits_pos = 0;
670 let mut ebits_len = 0;
671 let mut dec_state = DecState::default();
673 dec_state.post_shift = if (hdr.get_bits() & 8) != 0 { 8 } else { 0 };
674 dec_state.post_shift += ((hdr.flags >> 13) & 0x1F) as u8;
675 validate!(dec_state.post_shift < 32);
676 dec_state.hyb_max = 0x7FFFFFFF >> (32 - hdr.get_bits());
677 dec_state.hyb_min = -dec_state.hyb_max - 1;
678 let is_hybrid = (hdr.flags & WV_FLAG_HYBRID) != 0;
679 let has_hybrid_br = (hdr.flags & WV_FLAG_HYB_BITRATE) != 0;
680 dec_state.has_hbr = has_hybrid_br;
681 dec_state.stereo = !is_mono;
682 while br.left() > 0 {
683 let (id, len) = get_subblock(&mut br)?;
685 0x02 => { //decorr terms
686 self.dstate.num_decorr = len;
687 validate!(self.dstate.num_decorr <= self.dstate.decorr.len());
688 for decorr in self.dstate.decorr[..self.dstate.num_decorr].iter_mut().rev() {
689 let val = br.read_byte()?;
690 decorr.value = i32::from(val & 0x1F) - 5;
691 decorr.delta = i32::from(val >> 5);
695 0x03 => { //decorr weights
696 validate!(has_terms);
697 validate!(len <= self.dstate.num_decorr * cur_channels);
698 for decorr in self.dstate.decorr[..self.dstate.num_decorr].iter_mut().rev().take(len / cur_channels) {
699 let val = br.read_byte()? as i8;
700 decorr.weight_a = i32::from(val) << 3;
701 if decorr.weight_a > 0 {
702 decorr.weight_a += (decorr.weight_a + 64) >> 7;
705 let val = br.read_byte()? as i8;
706 decorr.weight_b = i32::from(val) << 3;
707 if decorr.weight_b > 0 {
708 decorr.weight_b += (decorr.weight_b + 64) >> 7;
714 0x04 => { //decorr samples
715 validate!(has_weights);
716 let end = br.tell() + (len as u64);
717 for decorr in self.dstate.decorr[..self.dstate.num_decorr].iter_mut().rev() {
718 if br.tell() == end {
721 if decorr.value > 8 {
722 let a0 = br.read_u16le()? as i16;
723 let a1 = br.read_u16le()? as i16;
724 decorr.samples_a[0] = wv_log2lin(i32::from(a0));
725 decorr.samples_a[1] = wv_log2lin(i32::from(a1));
727 let b0 = br.read_u16le()? as i16;
728 let b1 = br.read_u16le()? as i16;
729 decorr.samples_b[0] = wv_log2lin(i32::from(b0));
730 decorr.samples_b[1] = wv_log2lin(i32::from(b1));
732 } else if decorr.value < 0 {
733 let a0 = br.read_u16le()? as i16;
734 let b0 = br.read_u16le()? as i16;
735 decorr.samples_a[0] = wv_log2lin(i32::from(a0));
736 decorr.samples_b[0] = wv_log2lin(i32::from(b0));
738 let len = decorr.value as usize;
740 let a = br.read_u16le()? as i16;
741 decorr.samples_a[i] = wv_log2lin(i32::from(a));
743 let b = br.read_u16le()? as i16;
744 decorr.samples_b[i] = wv_log2lin(i32::from(b));
751 0x05 => { //entropy vars
752 validate!(len == 6 * cur_channels);
753 for el in dec_state.median[0].iter_mut() {
754 *el = wv_log2lin(i32::from(br.read_u16le()? as i16)) as u32;
757 for el in dec_state.median[1].iter_mut() {
758 *el = wv_log2lin(i32::from(br.read_u16le()? as i16)) as u32;
762 0x06 => { //hybrid parameters
763 validate!(is_hybrid);
764 let end = br.tell() + (len as u64);
766 for el in dec_state.slow_level.iter_mut().take(cur_channels) {
767 *el = wv_log2lin(i32::from(br.read_u16le()? as i16)) as u32;
770 for el in dec_state.br_acc.iter_mut().take(cur_channels) {
771 *el = u32::from(br.read_u16le()?) << 16;
774 for el in dec_state.br_delta.iter_mut().take(cur_channels) {
775 *el = wv_log2lin(i32::from(br.read_u16le()? as i16)) as u32;
778 validate!(br.tell() == end);
782 validate!((hdr.flags & WV_FLAG_FLOATS) != 0);
783 return Err(DecoderError::NotImplemented);
786 validate!((hdr.flags & WV_FLAG_EXT_INTEGERS) != 0);
788 let ebits = br.read_byte()?;
789 let mode1 = br.read_byte()?;
790 let mode2 = br.read_byte()?;
791 let mode3 = br.read_byte()?;
793 dec_state.ebits = ebits;
794 } else if mode1 != 0 {
795 dec_state.shift = mode1;
796 } else if mode2 != 0 {
799 dec_state.shift = mode2;
800 } else if mode3 != 0 {
802 dec_state.shift = mode3;
804 if is_hybrid && hdr.get_bits() == 32 && dec_state.post_shift < 8 && dec_state.shift > 8 {
805 dec_state.post_shift += 8;
806 dec_state.shift -= 8;
807 dec_state.hyb_min >>= 8;
808 dec_state.hyb_max >>= 8;
811 0x0A => { // normal stream
812 validate!(has_samples);
813 data_pos = br.tell() as usize;
818 ebits_pos = br.tell() as usize;
822 0x0E => return Err(DecoderError::NotImplemented), // DSD
823 _ => { br.read_skip(len)?; },
829 validate!(data_pos > 0 && data_len > 0);
831 validate!(has_hybrid);
834 let mut br = BitReader::new(&src[data_pos..][..data_len], BitReaderMode::LE);
835 let mut ebr = BitReader::new(&src[ebits_pos..][..ebits_len], BitReaderMode::LE);
837 let is_fstereo = (hdr.flags & WV_FLAG_FALSE_STEREO) != 0;
839 NABufferType::AudioI16(ref mut adata) => {
840 let off0 = adata.get_offset(start_ch);
841 let off1 = adata.get_offset(start_ch + 1);
842 let dst = adata.get_data_mut().unwrap();
843 let crc = if !is_hybrid {
844 unpack_mono(&mut br, &mut ebr, &mut dec_state, &mut self.dstate, &mut dst[off0..], hdr.block_samples as usize)?
846 unpack_mono_hyb(&mut br, &mut ebr, &mut dec_state, &mut
847 self.dstate, &mut dst[off0..], hdr.block_samples as usize)?
850 return Err(DecoderError::ChecksumError);
853 for i in 0..(hdr.block_samples as usize) {
854 dst[off1 + i] = dst[off0 + i];
858 NABufferType::AudioI32(ref mut adata) => {
859 let off0 = adata.get_offset(start_ch);
860 let off1 = adata.get_offset(start_ch + 1);
861 let dst = adata.get_data_mut().unwrap();
862 let crc = if !is_hybrid {
863 unpack_mono(&mut br, &mut ebr, &mut dec_state, &mut self.dstate, &mut dst[off0..], hdr.block_samples as usize)?
865 unpack_mono_hyb(&mut br, &mut ebr, &mut dec_state, &mut
866 self.dstate, &mut dst[off0..], hdr.block_samples as usize)?
869 return Err(DecoderError::ChecksumError);
872 for i in 0..(hdr.block_samples as usize) {
873 dst[off1 + i] = dst[off0 + i];
880 let is_joint = (hdr.flags & WV_FLAG_JSTEREO) != 0;
882 NABufferType::AudioI16(ref mut adata) => {
883 let off0 = adata.get_offset(start_ch);
884 let off1 = adata.get_offset(start_ch + 1);
885 let dst = adata.get_data_mut().unwrap();
886 let crc = if !is_hybrid {
887 unpack_stereo(&mut br, &mut ebr, &mut dec_state, &mut self.dstate, dst, off0, off1, hdr.block_samples as usize, is_joint)?
889 unpack_stereo_hyb(&mut br, &mut ebr, &mut dec_state, &mut self.dstate, dst, off0, off1, hdr.block_samples as usize, is_joint)?
892 return Err(DecoderError::ChecksumError);
895 NABufferType::AudioI32(ref mut adata) => {
896 let off0 = adata.get_offset(start_ch);
897 let off1 = adata.get_offset(start_ch + 1);
898 let dst = adata.get_data_mut().unwrap();
899 let crc = if !is_hybrid {
900 unpack_stereo(&mut br, &mut ebr, &mut dec_state, &mut self.dstate, dst, off0, off1, hdr.block_samples as usize, is_joint)?
902 unpack_stereo_hyb(&mut br, &mut ebr, &mut dec_state, &mut self.dstate, dst, off0, off1, hdr.block_samples as usize, is_joint)?
905 return Err(DecoderError::ChecksumError);
916 impl NADecoder for WavPackDecoder {
917 fn init(&mut self, _supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()> {
918 if let NACodecTypeInfo::Audio(_ainfo) = info.get_properties() {
919 if let Some(buf) = info.get_extradata() {
920 let mut channels = 0;
921 let mut decl_channels = 0;
922 let mut channel_map = 0;
924 while off < buf.len() {
925 let hdr = WVHeader::parse(&buf[off..])?;
926 if (hdr.flags & (WV_FLAG_FLOATS | WV_FLAG_DSD_AUDIO)) != 0 {
927 return Err(DecoderError::NotImplemented);
930 off += WV_HEADER_SIZE;
931 let size = hdr.get_size();
932 let mut mr = MemoryReader::new_read(&buf[off..][..size]);
933 let mut br = ByteReader::new(&mut mr);
934 while br.left() > 0 {
935 let (id, len) = get_subblock(&mut br)?;
939 decl_channels = br.read_byte()?;
940 if decl_channels == 0 {
941 return Err(DecoderError::NotImplemented);
943 channel_map = match len {
944 2 => u32::from(br.read_byte()?),
945 3 => u32::from(br.read_u16le()?),
946 4 => br.read_u24le()?,
947 5 => br.read_u32le()?,
948 _ => return Err(DecoderError::NotImplemented),
951 _ => br.read_skip(len)?,
957 channels += hdr.get_num_channels();
959 if hdr.is_end_block() {
964 if decl_channels != 0 {
965 validate!(decl_channels == channels);
967 self.chmap = if channel_map != 0 {
968 NAChannelMap::from_ms_mapping(channel_map)
969 } else if channels == 1 {
970 NAChannelMap::from_str("C").unwrap()
971 } else if channels == 2 {
972 NAChannelMap::from_str("L,R").unwrap()
974 return Err(DecoderError::NotImplemented);
976 let bsamps = if self.header.block_samples == 0 {
977 self.header.get_sample_rate()
979 self.header.block_samples
982 let bits = self.header.get_bits();
983 let fmt = if (self.header.flags & WV_FLAG_FLOATS) != 0 {
985 } else if bits <= 16 {
991 self.ainfo = NAAudioInfo::new(self.header.get_sample_rate(), channels, fmt, bsamps);
994 Err(DecoderError::InvalidData)
997 Err(DecoderError::InvalidData)
1000 fn decode(&mut self, _supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef> {
1001 let info = pkt.get_stream().get_info();
1002 if let NACodecTypeInfo::Audio(_) = info.get_properties() {
1003 let pktbuf = pkt.get_buffer();
1004 validate!(pktbuf.len() > WV_HEADER_SIZE);
1005 let refhdr = WVHeader::parse(&pktbuf)?;
1007 if refhdr.block_samples == 0 {
1008 let mut frm = NAFrame::new_from_pkt(pkt, info, NABufferType::None);
1009 frm.set_frame_type(FrameType::Skip);
1010 frm.set_keyframe(false);
1011 return Ok(frm.into_ref());
1014 let mut abuf = alloc_audio_buffer(self.ainfo, refhdr.block_samples as usize, self.chmap.clone())?;
1015 let mut start_ch = 0;
1017 let mut first = true;
1018 let mut refhdr = WVHeader::default();
1020 let hdr = WVHeader::parse(&pktbuf[roff..])?;
1022 validate!(hdr.is_start_block());
1023 validate!(self.header.stream_eq(&hdr));
1027 validate!(refhdr.block_eq(&hdr));
1029 roff += WV_HEADER_SIZE;
1030 let blk_size = hdr.get_size();
1031 self.decode_block(&hdr, &pktbuf[roff..][..blk_size], start_ch, &mut abuf)?;
1033 if hdr.is_end_block() {
1036 start_ch += hdr.get_num_channels() as usize;
1038 let mut frm = NAFrame::new_from_pkt(pkt, info, abuf);
1039 frm.set_duration(Some(u64::from(refhdr.block_samples)));
1042 Err(DecoderError::InvalidData)
1045 fn flush(&mut self) {
1049 impl NAOptionHandler for WavPackDecoder {
1050 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
1051 fn set_options(&mut self, _options: &[NAOption]) { }
1052 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
1055 pub fn get_decoder() -> Box<dyn NADecoder + Send> {
1056 Box::new(WavPackDecoder::new())
1061 use nihav_core::codecs::RegisteredDecoders;
1062 use nihav_core::demuxers::RegisteredDemuxers;
1063 use nihav_codec_support::test::dec_video::*;
1064 use crate::llaudio_register_all_decoders;
1065 use crate::llaudio_register_all_demuxers;
1066 // samples come from the official WavPack test samples set
1068 fn test_wavpack_8bit() {
1069 let mut dmx_reg = RegisteredDemuxers::new();
1070 llaudio_register_all_demuxers(&mut dmx_reg);
1071 let mut dec_reg = RegisteredDecoders::new();
1072 llaudio_register_all_decoders(&mut dec_reg);
1074 test_decoding("wavpack", "wavpack", "assets/LLaudio/wv/8bit-partial.wv", Some(100000), &dmx_reg, &dec_reg,
1075 ExpectedTestResult::MD5([0x8157bf0f, 0xeb441905, 0xeb6b815d, 0x113480a8]));
1078 fn test_wavpack_12bit() {
1079 let mut dmx_reg = RegisteredDemuxers::new();
1080 llaudio_register_all_demuxers(&mut dmx_reg);
1081 let mut dec_reg = RegisteredDecoders::new();
1082 llaudio_register_all_decoders(&mut dec_reg);
1084 test_decoding("wavpack", "wavpack", "assets/LLaudio/wv/12bit-partial.wv", Some(100000), &dmx_reg, &dec_reg,
1085 ExpectedTestResult::MD5([0xe5faf18c, 0xbf2d3b12, 0x5b0b8f00, 0x162b805a]));
1088 fn test_wavpack_16bit() {
1089 let mut dmx_reg = RegisteredDemuxers::new();
1090 llaudio_register_all_demuxers(&mut dmx_reg);
1091 let mut dec_reg = RegisteredDecoders::new();
1092 llaudio_register_all_decoders(&mut dec_reg);
1094 test_decoding("wavpack", "wavpack", "assets/LLaudio/wv/16bit-partial.wv", Some(100000), &dmx_reg, &dec_reg,
1095 ExpectedTestResult::MD5([0xaf31b252, 0xdf8b282a, 0x2dc38947, 0xf64c68a1]));
1098 fn test_wavpack_24bit() {
1099 let mut dmx_reg = RegisteredDemuxers::new();
1100 llaudio_register_all_demuxers(&mut dmx_reg);
1101 let mut dec_reg = RegisteredDecoders::new();
1102 llaudio_register_all_decoders(&mut dec_reg);
1104 test_decoding("wavpack", "wavpack", "assets/LLaudio/wv/24bit-partial.wv", Some(100000), &dmx_reg, &dec_reg,
1105 ExpectedTestResult::MD5([0xf5649972, 0xfe757241, 0x383d5ded, 0x0176a75b]));
1108 fn test_wavpack_hybrid() {
1109 let mut dmx_reg = RegisteredDemuxers::new();
1110 llaudio_register_all_demuxers(&mut dmx_reg);
1111 let mut dec_reg = RegisteredDecoders::new();
1112 llaudio_register_all_decoders(&mut dec_reg);
1114 test_decoding("wavpack", "wavpack", "assets/LLaudio/wv/4.0_16-bit.wv", Some(100000), &dmx_reg, &dec_reg,
1115 ExpectedTestResult::MD5([0x9cfa469a, 0x54af50e1, 0xe45434d1, 0x1bf987e2]));
1118 fn test_wavpack_hybrid_32bit() {
1119 let mut dmx_reg = RegisteredDemuxers::new();
1120 llaudio_register_all_demuxers(&mut dmx_reg);
1121 let mut dec_reg = RegisteredDecoders::new();
1122 llaudio_register_all_decoders(&mut dec_reg);
1124 test_decoding("wavpack", "wavpack", "assets/LLaudio/wv/4.0_32-bit_int.wv", Some(100000), &dmx_reg, &dec_reg,
1125 ExpectedTestResult::MD5([0x21415549, 0xf48ddb55, 0xef5c4e7f, 0xa48d5ab9]));
1129 const WV_EXP_TABLE: [u8; 256] = [
1130 0x00, 0x01, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05,
1131 0x06, 0x06, 0x07, 0x08, 0x08, 0x09, 0x0a, 0x0b,
1132 0x0b, 0x0c, 0x0d, 0x0e, 0x0e, 0x0f, 0x10, 0x10,
1133 0x11, 0x12, 0x13, 0x13, 0x14, 0x15, 0x16, 0x16,
1134 0x17, 0x18, 0x19, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
1135 0x1d, 0x1e, 0x1f, 0x20, 0x20, 0x21, 0x22, 0x23,
1136 0x24, 0x24, 0x25, 0x26, 0x27, 0x28, 0x28, 0x29,
1137 0x2a, 0x2b, 0x2c, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
1138 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x35, 0x36,
1139 0x37, 0x38, 0x39, 0x3a, 0x3a, 0x3b, 0x3c, 0x3d,
1140 0x3e, 0x3f, 0x40, 0x41, 0x41, 0x42, 0x43, 0x44,
1141 0x45, 0x46, 0x47, 0x48, 0x48, 0x49, 0x4a, 0x4b,
1142 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x51, 0x52,
1143 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,
1144 0x5b, 0x5c, 0x5d, 0x5e, 0x5e, 0x5f, 0x60, 0x61,
1145 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
1146 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71,
1147 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
1148 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81,
1149 0x82, 0x83, 0x84, 0x85, 0x87, 0x88, 0x89, 0x8a,
1150 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92,
1151 0x93, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,
1152 0x9c, 0x9d, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4,
1153 0xa5, 0xa6, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad,
1154 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb6, 0xb7,
1155 0xb8, 0xb9, 0xba, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0,
1156 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc8, 0xc9, 0xca,
1157 0xcb, 0xcd, 0xce, 0xcf, 0xd0, 0xd2, 0xd3, 0xd4,
1158 0xd6, 0xd7, 0xd8, 0xd9, 0xdb, 0xdc, 0xdd, 0xde,
1159 0xe0, 0xe1, 0xe2, 0xe4, 0xe5, 0xe6, 0xe8, 0xe9,
1160 0xea, 0xec, 0xed, 0xee, 0xf0, 0xf1, 0xf2, 0xf4,
1161 0xf5, 0xf6, 0xf8, 0xf9, 0xfa, 0xfc, 0xfd, 0xff
1163 const WV_LOG_TABLE: [u8; 256] = [
1164 0x00, 0x01, 0x03, 0x04, 0x06, 0x07, 0x09, 0x0a,
1165 0x0b, 0x0d, 0x0e, 0x10, 0x11, 0x12, 0x14, 0x15,
1166 0x16, 0x18, 0x19, 0x1a, 0x1c, 0x1d, 0x1e, 0x20,
1167 0x21, 0x22, 0x24, 0x25, 0x26, 0x28, 0x29, 0x2a,
1168 0x2c, 0x2d, 0x2e, 0x2f, 0x31, 0x32, 0x33, 0x34,
1169 0x36, 0x37, 0x38, 0x39, 0x3b, 0x3c, 0x3d, 0x3e,
1170 0x3f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x47, 0x48,
1171 0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0x51,
1172 0x52, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,
1173 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63,
1174 0x64, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c,
1175 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x74, 0x75,
1176 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d,
1177 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85,
1178 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d,
1179 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95,
1180 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9b, 0x9c,
1181 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4,
1182 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xa9, 0xaa, 0xab,
1183 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb2,
1184 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xb9,
1185 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc0,
1186 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc6, 0xc7,
1187 0xc8, 0xc9, 0xca, 0xcb, 0xcb, 0xcc, 0xcd, 0xce,
1188 0xcf, 0xd0, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd4,
1189 0xd5, 0xd6, 0xd7, 0xd8, 0xd8, 0xd9, 0xda, 0xdb,
1190 0xdc, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe0, 0xe1,
1191 0xe2, 0xe3, 0xe4, 0xe4, 0xe5, 0xe6, 0xe7, 0xe7,
1192 0xe8, 0xe9, 0xea, 0xea, 0xeb, 0xec, 0xed, 0xee,
1193 0xee, 0xef, 0xf0, 0xf1, 0xf1, 0xf2, 0xf3, 0xf4,
1194 0xf4, 0xf5, 0xf6, 0xf7, 0xf7, 0xf8, 0xf9, 0xf9,
1195 0xfa, 0xfb, 0xfc, 0xfc, 0xfd, 0xfe, 0xff, 0xff