use crate::audio::FRAME_BYTES_PER_CHANNEL;
use crate::dispatch::{self, Isa};
pub const NB: usize = 37_632;
#[deprecated(since = "0.6.0", note = "use `audio::FRAME_BYTES_PER_CHANNEL`; to be removed before 1.0")]
pub const FL: usize = FRAME_BYTES_PER_CHANNEL;
#[deprecated(since = "0.6.0", note = "use `audio::MAX_CHANNELS`, a `u8`; to be removed before 1.0")]
pub const MAX_CHANNELS: usize = MAX_NCH;
const MAX_NCH: usize = crate::audio::MAX_CHANNELS as usize;
const MAX_ORDER: usize = 128;
const MAX_PTABLE_LEN: usize = 64;
const HISTORY_BYTES: usize = MAX_ORDER / 8;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, thiserror::Error)]
#[non_exhaustive]
pub enum DstError {
#[error("frame-too-short")]
FrameTooShort,
#[error("stuffing")]
Stuffing,
#[error("header-truncated")]
HeaderTruncated,
#[error("resolution")]
Resolution,
#[error("segment-length")]
SegmentLength,
#[error("too-many-segments")]
TooManySegments,
#[error("table-number")]
TableNumber,
#[error("too-many-tables")]
TooManyTables,
#[error("channel-mapping")]
ChannelMapping,
#[error("segment-count-mismatch")]
SegmentCountMismatch,
#[error("coefficient-coding")]
CoefficientCoding,
#[error("coefficient-range")]
CoefficientRange,
#[error("ptable-coding")]
PtableCoding,
#[error("ptable-range")]
PtableRange,
#[error("arithmetic-code")]
ArithmeticCode,
#[error("unread-code-bits")]
UnreadCodeBits,
#[error("code-out-of-range")]
CodeOutOfRange,
#[error("invalid decoder arguments")]
InvalidArguments,
}
impl DstError {
pub fn rule(self) -> u8 {
match self {
DstError::FrameTooShort => 1,
DstError::Stuffing => 2,
DstError::HeaderTruncated => 3,
DstError::Resolution => 4,
DstError::SegmentLength => 5,
DstError::TooManySegments => 6,
DstError::TableNumber => 7,
DstError::TooManyTables => 8,
DstError::ChannelMapping => 9,
DstError::SegmentCountMismatch => 10,
DstError::CoefficientCoding => 11,
DstError::CoefficientRange => 12,
DstError::PtableCoding => 13,
DstError::PtableRange => 14,
DstError::ArithmeticCode => 15,
DstError::UnreadCodeBits => 16,
DstError::CodeOutOfRange => 17,
DstError::InvalidArguments => 0,
}
}
}
fn bitlen(x: u32) -> u32 {
32 - x.leading_zeros()
}
struct Bits<'a> {
data: &'a [u8],
pos: usize,
len: usize,
}
impl<'a> Bits<'a> {
fn new(data: &'a [u8]) -> Self {
Bits { data, pos: 0, len: data.len().saturating_mul(8) }
}
fn bit_at(data: &[u8], i: usize) -> u32 {
data.get(i / 8).map_or(0, |b| u32::from((b >> (7 - i % 8)) & 1))
}
fn bit(&mut self) -> Result<u32, DstError> {
if self.pos >= self.len {
return Err(DstError::HeaderTruncated);
}
let b = Self::bit_at(self.data, self.pos);
self.pos += 1;
Ok(b)
}
fn read(&mut self, n: u32) -> Result<u32, DstError> {
let n = n as usize;
if self.len - self.pos < n {
return Err(DstError::HeaderTruncated);
}
let mut v = 0u32;
for _ in 0..n {
v = (v << 1) | Self::bit_at(self.data, self.pos);
self.pos += 1;
}
Ok(v)
}
fn read_tc9(&mut self) -> Result<i32, DstError> {
let v = self.read(9)? as i32;
Ok(if v >= 256 { v - 512 } else { v })
}
fn rice(&mut self, m: u32) -> Result<i64, DstError> {
let mut q: i64 = 0;
while self.bit()? == 0 {
q += 1;
}
let lsb = i64::from(self.read(m)?);
let u = (q << m) + lsb;
if u == 0 {
return Ok(0);
}
Ok(if self.bit()? == 1 { -u } else { u })
}
}
#[derive(Clone, Debug, Default)]
struct Segmentation {
starts: [Vec<u32>; MAX_NCH],
}
impl Segmentation {
fn count(&self, c: usize) -> usize {
self.starts.get(c).map_or(0, Vec::len)
}
}
#[derive(Clone, Copy)]
enum Kind {
Filter,
Ptable,
}
impl Kind {
fn lmin_bytes(self) -> u32 {
match self {
Kind::Filter => 128,
Kind::Ptable => 4,
}
}
fn max_explicit(self, shared: bool) -> usize {
match (self, shared) {
(Kind::Filter, true) => 4,
(Kind::Filter, false) => 3,
(Kind::Ptable, _) => 7,
}
}
}
fn read_segmentation(bits: &mut Bits<'_>, kind: Kind, nch: usize) -> Result<Segmentation, DstError> {
let shared = bits.bit()? == 1;
let lmin = kind.lmin_bytes();
let rmax = FRAME_BYTES_PER_CHANNEL as u32 - lmin;
let mut resolution: Option<u32> = None;
let mut seg = Segmentation::default();
let read_channels = if shared { 1 } else { nch };
for c in 0..read_channels {
let mut rem = rmax;
let mut starts = vec![0u32];
let mut pos = 0u32;
loop {
if bits.bit()? == 1 {
break;
}
if starts.len() > kind.max_explicit(shared) {
return Err(DstError::TooManySegments);
}
let r = match resolution {
Some(r) => r,
None => {
let r = bits.read(bitlen(rmax))?;
if r == 0 || r > rmax {
return Err(DstError::Resolution);
}
resolution = Some(r);
r
}
};
let l = bits.read(bitlen(rem / r))?;
let bytes = r * l;
if bytes < lmin || bytes > rem {
return Err(DstError::SegmentLength);
}
rem -= bytes;
pos += 8 * bytes;
starts.push(pos);
}
if let Some(slot) = seg.starts.get_mut(c) {
*slot = starts;
}
}
if shared {
let first = seg.starts[0].clone();
for c in 1..nch {
seg.starts[c].clone_from(&first);
}
}
Ok(seg)
}
fn read_mapping(
bits: &mut Bits<'_>,
seg: &Segmentation,
nch: usize,
) -> Result<(Vec<Vec<u8>>, usize), DstError> {
let shared = bits.bit()? == 1;
let mut t: u32 = 1;
let mut index = |bits: &mut Bits<'_>| -> Result<u8, DstError> {
let v = bits.read(bitlen(t))?;
if v > t {
return Err(DstError::TableNumber);
}
if v == t {
t += 1;
}
Ok(v as u8)
};
let mut map: Vec<Vec<u8>> = Vec::with_capacity(nch);
if shared {
let mut first = vec![0u8];
for _ in 1..seg.count(0) {
first.push(index(bits)?);
}
for c in 0..nch {
if seg.count(c) != seg.count(0) {
return Err(DstError::ChannelMapping);
}
map.push(first.clone());
}
} else {
for c in 0..nch {
let mut m = Vec::with_capacity(seg.count(c));
for j in 0..seg.count(c) {
m.push(if c == 0 && j == 0 { 0 } else { index(bits)? });
}
map.push(m);
}
}
let count = t as usize;
if count > 2 * nch {
return Err(DstError::TooManyTables);
}
Ok((map, count))
}
const COEF_PRED: [[i64; 3]; 3] = [[-8, 0, 0], [-16, 8, 0], [-9, -5, 6]];
const PTABLE_PRED: [[i64; 3]; 3] = [[-8, 0, 0], [-16, 8, 0], [-24, 24, -8]];
fn round8(x: i64) -> i64 {
(x + 4).div_euclid(8)
}
#[derive(Clone, Debug)]
struct Filter {
order: usize,
coefs: [i32; MAX_ORDER],
}
type Row = [i16; 8];
type ByteTable = [Row; 256];
static ZERO_TABLES: [ByteTable; HISTORY_BYTES] = [[[0; 8]; 256]; HISTORY_BYTES];
const HISTORY_FILL: u8 = 0xAA;
const WINDOW: usize = HISTORY_BYTES * MAX_NCH;
pub const MAX_LANES: usize = 4;
pub fn lanes(channels: u8) -> usize {
let avx512 = cfg!(target_feature = "avx512cd");
match channels {
1 => {
if avx512 {
3
} else {
4
}
}
3 if !avx512 => 3,
6 if avx512 => 3,
2..=6 => 2,
_ => 1,
}
}
#[derive(Debug, Default)]
struct Lane {
tables: Vec<ByteTable>,
filled: Vec<usize>,
partial: Vec<[i16; 256]>,
luts: Vec<Lut>,
probes: Vec<Probe>,
code: Vec<u8>,
hist: Vec<u8>,
}
#[derive(Debug)]
pub struct DstDecoder {
lanes: Vec<Lane>,
isa: Isa,
}
impl Default for DstDecoder {
fn default() -> Self {
DstDecoder::new()
}
}
impl DstDecoder {
pub fn new() -> Self {
DstDecoder { lanes: Vec::new(), isa: Isa::detect() }
}
#[cfg(test)]
pub(crate) fn with_isa(isa: Isa) -> Self {
DstDecoder { lanes: Vec::new(), isa }
}
pub fn decode(&mut self, frame: &[u8], channels: u8, out: &mut [u8]) -> Result<(), DstError> {
let mut result = [Ok(())];
self.decode_group(&[frame], channels, &mut [out], &mut result);
result[0]
}
pub fn decode_many(
&mut self,
frames: &[&[u8]],
channels: u8,
outs: &mut [&mut [u8]],
) -> Vec<Result<(), DstError>> {
let mut results = vec![Err(DstError::InvalidArguments); frames.len()];
let n = frames.len().min(outs.len());
let groups = frames[..n].chunks(MAX_LANES).zip(outs[..n].chunks_mut(MAX_LANES));
for ((frames, outs), results) in groups.zip(results.chunks_mut(MAX_LANES)) {
self.decode_group(frames, channels, outs, results);
}
results
}
fn decode_group(
&mut self,
frames: &[&[u8]],
channels: u8,
outs: &mut [&mut [u8]],
results: &mut [Result<(), DstError>],
) {
dispatch::decode_group(self.isa, self, frames, channels, outs, results);
}
#[inline(always)]
pub(crate) fn group<const INLINE_RUN: bool>(
&mut self,
frames: &[&[u8]],
channels: u8,
outs: &mut [&mut [u8]],
results: &mut [Result<(), DstError>],
) {
if self.lanes.len() < frames.len() {
self.lanes.resize_with(frames.len(), Lane::default);
}
let nch = usize::from(channels);
let mut live: Vec<Live<'_, '_>> = Vec::with_capacity(frames.len());
let lanes = self.lanes.iter_mut().zip(frames).zip(outs.iter_mut());
for ((i, ((lane, frame), out)), result) in lanes.enumerate().zip(results.iter_mut()) {
match Coded::start(lane, frame, nch, out) {
Ok(Some(coded)) => live.push(Live { index: i, coded, out }),
Ok(None) => *result = Ok(()),
Err(e) => *result = Err(e),
}
}
let mut spans: Vec<Span<'_>> = Vec::with_capacity(live.len());
loop {
let mut i = 0;
spans.clear();
while let Some(lv) = live.get_mut(i) {
if lv.coded.n >= NB {
let lv = live.swap_remove(i);
results[lv.index] = lv.coded.finish(lv.out);
continue;
}
let span = lv.coded.span();
if span.half {
lv.coded.run_general(&span);
} else {
spans.push(span);
i += 1;
}
}
if live.is_empty() {
break;
}
let bytes = live.iter().zip(&spans).map(|(lv, s)| (s.end - lv.coded.n) / 8).min().unwrap_or(0);
let used = spans.iter().map(|s| s.most).max().unwrap_or(0);
let mut runs: Vec<LaneRun<'_, '_>> =
live.iter_mut().zip(&spans).map(|(lv, s)| lv.coded.lane_run(s)).collect();
macro_rules! by_tables {
($k:literal, $n:literal) => {
match (used, INLINE_RUN) {
(0..=4, false) => run::<$k, $n, 4>(&mut runs, bytes),
(5..=8, false) => run::<$k, $n, 8>(&mut runs, bytes),
(_, false) => run::<$k, $n, 16>(&mut runs, bytes),
(_, true) if const { $k * $n <= UNROLL_BYTE } => {
run_inline::<$k, $n>(&mut runs, bytes, used)
}
(0..=4, true) => run_inline::<$k, $n>(&mut runs, bytes, 4),
(5..=8, true) => run_inline::<$k, $n>(&mut runs, bytes, 8),
(_, true) => run_inline::<$k, $n>(&mut runs, bytes, 16),
}
};
}
macro_rules! by_channels {
($k:literal) => {
match nch {
1 => by_tables!($k, 1),
2 => by_tables!($k, 2),
3 => by_tables!($k, 3),
4 => by_tables!($k, 4),
5 => by_tables!($k, 5),
_ => by_tables!($k, 6),
}
};
}
match runs.len() {
1 => by_channels!(1),
2 => by_channels!(2),
3 => by_channels!(3),
_ => by_channels!(4),
}
drop(runs);
for lv in &mut live {
lv.coded.advance(lv.coded.n + 8 * bytes);
}
}
}
}
impl Lane {
fn build_tables(&mut self, filters: &[Filter]) {
self.tables.resize(filters.len() * HISTORY_BYTES, [[0; 8]; 256]);
self.filled.resize(filters.len(), 0);
self.partial.resize(filters.len(), [0; 256]);
for (f, filter) in filters.iter().enumerate() {
let a = |i: usize| filter.coefs.get(i).map_or(0, |&v| v as i16);
let used = filter.order.div_ceil(8);
for d in 0..used {
let table = &mut self.tables[f * HISTORY_BYTES + d];
let mut first = [0i16; 8];
let mut cols = [[0i16; 8]; 8];
for (r, f) in first.iter_mut().enumerate() {
for (b, col) in cols.iter_mut().enumerate() {
let v = a(8 * d + r + b);
*f -= v;
col[r] = 2 * v;
}
}
table[0] = first;
for byte in 1..256usize {
let col = &cols[byte.trailing_zeros() as usize];
let prev = table[byte & (byte - 1)];
table[byte] = core::array::from_fn(|r| prev[r].wrapping_add(col[r]));
}
}
for d in used..self.filled[f] {
self.tables[f * HISTORY_BYTES + d] = [[0; 8]; 256];
}
self.filled[f] = used;
let partial = &mut self.partial[f];
for r in 0..8 {
for bits in 0..1usize << r {
partial[(1 << r) | bits] =
(0..r).map(|i| if (bits >> i) & 1 == 1 { a(i) } else { -a(i) }).sum();
}
}
}
}
fn build_luts(&mut self, ptables: &[Vec<u32>]) {
self.luts.resize(ptables.len(), [0; LUT_LEN]);
for (lut, p) in self.luts.iter_mut().zip(ptables) {
let used = &mut lut[..LUT_USED];
used.fill(p.last().copied().unwrap_or(128) as u8);
for (slot, &v) in used.iter_mut().zip(p) {
*slot = v as u8;
}
}
}
}
struct Live<'b, 'o> {
index: usize,
coded: Coded<'b>,
out: &'o mut [u8],
}
struct Coded<'b> {
nch: usize,
fseg: Segmentation,
pseg: Segmentation,
fmap: Vec<Vec<u8>>,
pmap: Vec<Vec<u8>>,
orders: Vec<usize>,
nh: [usize; MAX_NCH],
tables: &'b [ByteTable],
partial: &'b [[i16; 256]],
luts: &'b [Lut],
probes: &'b mut [Probe],
keys: [(usize, usize); MAX_NCH],
arith: Arith<'b>,
hist: &'b mut [u8],
fidx: [usize; MAX_NCH],
pidx: [usize; MAX_NCH],
n: usize,
fs: usize,
}
#[derive(Clone, Copy)]
struct Span<'t> {
end: usize,
half: bool,
used: [usize; MAX_NCH],
most: usize,
tabs: [&'t [ByteTable; HISTORY_BYTES]; MAX_NCH],
partial: [&'t [i16; 256]; MAX_NCH],
luts: [&'t Lut; MAX_NCH],
keys: [(usize, usize); MAX_NCH],
}
impl<'b> Coded<'b> {
fn start(lane: &'b mut Lane, frame: &[u8], nch: usize, out: &mut [u8]) -> Result<Option<Self>, DstError> {
if !(1..=MAX_NCH).contains(&nch) || out.len() != nch * FRAME_BYTES_PER_CHANNEL {
return Err(DstError::InvalidArguments);
}
if frame.len() <= 1 {
return Err(DstError::FrameTooShort);
}
if frame[0] & 0x80 == 0 {
return plain(frame, out).map(|()| None);
}
let mut bits = Bits::new(frame);
bits.pos = 1;
let same_segmentation = bits.bit()? == 1;
let fseg = read_segmentation(&mut bits, Kind::Filter, nch)?;
let pseg =
if same_segmentation { fseg.clone() } else { read_segmentation(&mut bits, Kind::Ptable, nch)? };
let same_mapping = bits.bit()? == 1;
let (fmap, nf) = read_mapping(&mut bits, &fseg, nch)?;
let (pmap, np) = if same_mapping {
for c in 0..nch {
if pseg.count(c) != fseg.count(c) {
return Err(DstError::SegmentCountMismatch);
}
}
(fmap.clone(), nf)
} else {
read_mapping(&mut bits, &pseg, nch)?
};
let mut half = [false; MAX_NCH];
for h in half.iter_mut().take(nch) {
*h = bits.bit()? == 1;
}
let mut filters = Vec::with_capacity(nf);
for _ in 0..nf {
filters.push(read_filter(&mut bits)?);
}
let mut ptables: Vec<Vec<u32>> = Vec::with_capacity(np);
for _ in 0..np {
ptables.push(read_ptable(&mut bits)?);
}
let header = bits.pos;
let total = frame.len().saturating_mul(8);
let fs = total - header;
if fs > 0 && Bits::bit_at(frame, header) == 1 {
return Err(DstError::ArithmeticCode);
}
lane.build_tables(&filters);
lane.build_luts(&ptables);
lane.hist.resize((HISTORY_BYTES + FRAME_BYTES_PER_CHANNEL) * nch + WINDOW, 0);
lane.hist[..HISTORY_BYTES * nch].fill(HISTORY_FILL);
lane.probes.resize(MAX_NCH, NO_PROBE);
let Lane { tables, partial, luts, probes, code, hist, .. } = lane;
let mut code = CodeBits::new(code, frame, header + 1, fs.saturating_sub(1));
let c = code.take12();
if c == 4095 {
return Err(DstError::CodeOutOfRange);
}
let mut arith = Arith { a: 4095 << 52, x: u64::from(c) << 52, code };
let a0 = filters.first().map_or(0, |f| f.coefs[0]);
let px = u32::from(((a0 & 0x7F) as u8).reverse_bits() >> 1) + 1;
arith.refill();
let _ = arith.decode(px);
let mut nh = [0usize; MAX_NCH];
for ch in 0..nch {
if half[ch] {
nh[ch] = filters[usize::from(fmap[ch][0])].order;
}
}
Ok(Some(Coded {
nch,
fseg,
pseg,
fmap,
pmap,
orders: filters.iter().map(|f| f.order).collect(),
nh,
tables,
partial,
luts,
probes,
keys: [(usize::MAX, usize::MAX); MAX_NCH],
arith,
hist,
fidx: [0; MAX_NCH],
pidx: [0; MAX_NCH],
n: 0,
fs,
}))
}
fn span(&self) -> Span<'b> {
let segment_end = |starts: &[u32], idx: usize| starts.get(idx + 1).map_or(NB, |&b| b as usize);
let mut span = Span {
end: NB,
half: false,
used: [0; MAX_NCH],
most: 0,
tabs: [&ZERO_TABLES; MAX_NCH],
partial: [&[0; 256]; MAX_NCH],
luts: [&NO_LUT; MAX_NCH],
keys: [(0, 0); MAX_NCH],
};
for ch in 0..self.nch {
span.end = span.end.min(segment_end(&self.fseg.starts[ch], self.fidx[ch]));
span.end = span.end.min(segment_end(&self.pseg.starts[ch], self.pidx[ch]));
if self.n < self.nh[ch] {
span.half = true;
span.end = span.end.min(self.nh[ch].next_multiple_of(8));
}
let q = usize::from(self.pmap[ch][self.pidx[ch]]);
span.luts[ch] = &self.luts[q];
let f = usize::from(self.fmap[ch][self.fidx[ch]]);
span.keys[ch] = (f, q);
span.used[ch] = self.orders[f].div_ceil(8);
span.most = span.most.max(span.used[ch]);
let tabs = self.tables.get(f * HISTORY_BYTES..(f + 1) * HISTORY_BYTES);
span.tabs[ch] = tabs.and_then(|t| t.try_into().ok()).unwrap_or(&ZERO_TABLES);
span.partial[ch] = &self.partial[f];
}
span
}
fn advance(&mut self, n: usize) {
let segment_end = |starts: &[u32], idx: usize| starts.get(idx + 1).map_or(NB, |&b| b as usize);
self.n = n;
for ch in 0..self.nch {
if segment_end(&self.fseg.starts[ch], self.fidx[ch]) == n {
self.fidx[ch] += 1;
}
if segment_end(&self.pseg.starts[ch], self.pidx[ch]) == n {
self.pidx[ch] += 1;
}
}
}
fn run_general(&mut self, span: &Span<'_>) {
run_general(self.n, span, self.nch, &self.nh, &mut self.arith, self.hist);
self.advance(span.end);
}
fn lane_run<'r>(&'r mut self, span: &Span<'b>) -> LaneRun<'r, 'b> {
for ch in 0..self.nch {
if self.keys[ch] != span.keys[ch] {
if let Some(p) = self.probes.get_mut(ch) {
p.fill(span.partial[ch], span.luts[ch], byte_lut(self.nch));
}
self.keys[ch] = span.keys[ch];
}
}
LaneRun {
start: self.n / 8,
tabs: span.tabs,
probes: self.probes.get(..MAX_NCH).and_then(|p| p.try_into().ok()).unwrap_or(&NO_PROBES),
arith: &mut self.arith,
hist: self.hist,
}
}
fn finish(self, out: &mut [u8]) -> Result<(), DstError> {
let ptr = 1 + self.arith.code.consumed();
if self.fs > ptr + 7 {
return Err(DstError::UnreadCodeBits);
}
let first = HISTORY_BYTES * self.nch;
if let Some(audio) = self.hist.get(first..first + out.len()) {
out.copy_from_slice(audio);
}
Ok(())
}
}
#[derive(Clone, Copy)]
struct Arith<'a> {
a: u64,
x: u64,
code: CodeBits<'a>,
}
impl Arith<'_> {
#[inline(always)]
fn refill(&mut self) {
self.x |= self.code.peek() >> 12;
}
#[inline(always)]
fn decode(&mut self, p: u32) -> u32 {
let a = self.a;
let t = (a >> 59) as u32;
let q = (t >> 1) | (t & 1);
let w0 = u64::from(q.wrapping_mul(p)) << 52;
let w1 = a.wrapping_sub(w0);
let zero = self.x >= w1;
let x = self.x.wrapping_sub(w1).min(self.x);
let a = if zero { w0 } else { w1 };
let k = a.leading_zeros();
self.a = a.wrapping_shl(k);
self.x = x.wrapping_shl(k);
self.code.skip(k);
u32::from(!zero)
}
#[inline(always)]
fn decode_table(&mut self, p: u32, q: &QTable) -> u32 {
let a = self.a;
let w0 = q[(a >> 59) as usize].wrapping_mul(u64::from(p));
let w1 = a.wrapping_sub(w0);
let zero = self.x >= w1;
let x = self.x.wrapping_sub(w1).min(self.x);
let a = if zero { w0 } else { w1 };
let k = a.leading_zeros();
self.a = a.wrapping_shl(k);
self.x = x.wrapping_shl(k);
self.code.skip(k);
u32::from(!zero)
}
#[inline(always)]
fn decode_scaled(&mut self, p: u64) -> u32 {
let t = (self.a >> 59) as u32;
let q = u64::from((t >> 1) | (t & 1));
let w0 = q.wrapping_mul(p);
let w1 = self.a.wrapping_sub(w0);
let zero = self.x >= w1;
let x = self.x.wrapping_sub(w1).min(self.x);
let a = if zero { w0 } else { w1 };
let k = a.leading_zeros();
self.a = a.wrapping_shl(k);
self.x = x.wrapping_shl(k);
self.code.skip(k);
u32::from(!zero)
}
}
#[inline(always)]
fn symbol(ar: &mut Arith<'_>, base: i16, partial: &[i16; 256], idx: u32, lut: &Lut, half: bool) -> u32 {
let spred = base.wrapping_add(partial[(idx & 0xFF) as usize]);
let sign = u32::from(spred < 0);
let p = if half { 128 } else { probability(spred, lut).0 };
sign ^ ar.decode(p)
}
#[inline(always)]
fn probability(spred: i16, lut: &Lut) -> (u32, u32) {
(u32::from(lut[usize::from(spred.unsigned_abs() >> 3)]), u32::from(spred < 0))
}
#[inline(always)]
fn probability_scaled(spred: i16, lut: &ScaledLut) -> (u64, u32) {
let j = usize::from(spred.unsigned_abs() >> 3).min(MAX_PTABLE_LEN - 1);
(lut[j], u32::from(spred < 0))
}
#[inline(always)]
fn window(hist: &[u8], m: usize, nch: usize) -> &[u8; WINDOW] {
hist.get(m * nch..m * nch + WINDOW).and_then(|w| w.try_into().ok()).unwrap_or(&[HISTORY_FILL; WINDOW])
}
#[inline(always)]
fn rows<const NCH: usize, const U: usize, const FROM: usize>(
tables: &[ByteTable; HISTORY_BYTES],
w: &[u8; WINDOW],
ch: usize,
) -> Row {
let mut sum = [0i16; 8];
add_rows::<NCH, FROM, FROM, U>(&mut sum, tables, w, ch);
sum
}
#[inline(always)]
fn add_rows<const NCH: usize, const FROM: usize, const LO: usize, const HI: usize>(
sum: &mut Row,
tables: &[ByteTable; HISTORY_BYTES],
w: &[u8; WINDOW],
ch: usize,
) {
#[allow(clippy::needless_range_loop)]
for d in LO..HI.min(HISTORY_BYTES) {
let byte = w[(HISTORY_BYTES - 1 + FROM - d) * NCH + ch];
let row = &tables[d][usize::from(byte)];
for r in 0..8 {
sum[r] = sum[r].wrapping_add(row[r]);
}
}
}
const UNROLL_BYTE: usize = 9;
#[derive(Clone, Copy)]
#[repr(align(16))]
struct Aligned([i16; 8]);
struct LaneRun<'r, 'b> {
start: usize,
tabs: [&'b [ByteTable; HISTORY_BYTES]; MAX_NCH],
probes: &'r [Probe; MAX_NCH],
arith: &'r mut Arith<'b>,
hist: &'r mut [u8],
}
#[inline(never)]
fn run<const K: usize, const NCH: usize, const U: usize>(lanes: &mut [LaneRun<'_, '_>], bytes: usize) {
run_inline::<K, NCH>(lanes, bytes, U);
}
#[inline(always)]
#[allow(clippy::needless_range_loop)]
fn shares<const K: usize, const NCH: usize, const FROM: usize>(
out: &mut [[Aligned; NCH]; K],
lanes: &[LaneRun<'_, '_>; K],
tabs: &[[&[ByteTable; HISTORY_BYTES]; NCH]; K],
at: usize,
u: usize,
) {
let windows: [&[u8; WINDOW]; K] =
core::array::from_fn(|l| window(lanes[l].hist, lanes[l].start + at, NCH));
for l in 0..K {
for ch in 0..NCH {
out[l][ch] = Aligned(rows::<NCH, 4, FROM>(tabs[l][ch], windows[l], ch));
}
}
if u > 4 {
for l in 0..K {
for ch in 0..NCH {
add_rows::<NCH, FROM, 4, 8>(&mut out[l][ch].0, tabs[l][ch], windows[l], ch);
}
}
}
if u > 8 {
for l in 0..K {
for ch in 0..NCH {
add_rows::<NCH, FROM, 8, 16>(&mut out[l][ch].0, tabs[l][ch], windows[l], ch);
}
}
}
}
#[inline(always)]
#[allow(clippy::needless_range_loop)]
fn run_inline<const K: usize, const NCH: usize>(lanes: &mut [LaneRun<'_, '_>], bytes: usize, u: usize) {
let Ok(lanes) = <&mut [LaneRun<'_, '_>; K]>::try_from(lanes) else {
return;
};
let mut ar: [Arith<'_>; K] = core::array::from_fn(|l| *lanes[l].arith);
let tabs: [[&[ByteTable; HISTORY_BYTES]; NCH]; K] =
core::array::from_fn(|l| core::array::from_fn(|ch| lanes[l].tabs[ch]));
let probes: [&[Probe; MAX_NCH]; K] = core::array::from_fn(|l| lanes[l].probes);
let mut base = [[Aligned([0i16; 8]); NCH]; K];
shares::<K, NCH, 0>(&mut base, lanes, &tabs, 0, u);
for i in 0..bytes {
let mut rest = [[Aligned([0i16; 8]); NCH]; K];
shares::<K, NCH, 1>(&mut rest, lanes, &tabs, i, u);
let mut cur = [[if K * NCH <= UNROLL_BYTE { 0u32 } else { 1 }; NCH]; K];
macro_rules! symbol {
($r:literal, $ch:literal, $l:literal) => {
if $ch < NCH && $l < K {
if ($r * NCH + $ch) % 6 == 0 {
ar[$l].refill();
}
let idx = ((1 << $r) | cur[$l][$ch]) as usize & 0xFF;
let probe = &probes[$l][$ch];
let spred = base[$l][$ch].0[$r].wrapping_add(probe.partial[idx]);
let y = if const { byte_lut(NCH) } {
let (p, sign) = probability(spred, &probe.lut);
sign ^ ar[$l].decode_table(p, &probes[$l][0].q)
} else {
let (p, sign) = probability_scaled(spred, &probe.scaled);
sign ^ ar[$l].decode_scaled(p)
};
cur[$l][$ch] = (cur[$l][$ch] << 1) | y;
}
};
}
macro_rules! lanes {
($r:literal, $ch:literal) => {
symbol!($r, $ch, 0);
symbol!($r, $ch, 1);
symbol!($r, $ch, 2);
symbol!($r, $ch, 3);
};
}
macro_rules! bit {
($r:literal) => {
lanes!($r, 0);
lanes!($r, 1);
lanes!($r, 2);
lanes!($r, 3);
lanes!($r, 4);
lanes!($r, 5);
};
}
macro_rules! symbol_at {
($r:ident, $ch:literal, $l:literal) => {
if $ch < NCH && $l < K {
if $ch == 0 {
ar[$l].refill();
}
let idx = cur[$l][$ch] as usize & 0xFF;
let probe = &probes[$l][$ch];
let spred = base[$l][$ch].0[$r].wrapping_add(probe.partial[idx]);
let y = if const { byte_lut(NCH) } {
let (p, sign) = probability(spred, &probe.lut);
sign ^ ar[$l].decode_table(p, &probes[$l][0].q)
} else {
let (p, sign) = probability_scaled(spred, &probe.scaled);
sign ^ ar[$l].decode_scaled(p)
};
cur[$l][$ch] = (cur[$l][$ch] << 1) | y;
}
};
}
macro_rules! lanes_at {
($r:ident, $ch:literal) => {
symbol_at!($r, $ch, 0);
symbol_at!($r, $ch, 1);
symbol_at!($r, $ch, 2);
symbol_at!($r, $ch, 3);
};
}
if K * NCH <= UNROLL_BYTE {
bit!(0);
bit!(1);
bit!(2);
bit!(3);
bit!(4);
bit!(5);
bit!(6);
bit!(7);
} else {
for r in 0..8 {
lanes_at!(r, 0);
lanes_at!(r, 1);
lanes_at!(r, 2);
lanes_at!(r, 3);
lanes_at!(r, 4);
lanes_at!(r, 5);
}
}
for l in 0..K {
let at = (HISTORY_BYTES + lanes[l].start + i) * NCH;
if let Some(dst) = lanes[l].hist.get_mut(at..at + NCH) {
for (d, &c) in dst.iter_mut().zip(cur[l].iter()) {
*d = c as u8;
}
}
for ch in 0..NCH {
let row = &tabs[l][ch][0][(cur[l][ch] & 0xFF) as usize];
base[l][ch] = Aligned(core::array::from_fn(|r| rest[l][ch].0[r].wrapping_add(row[r])));
}
}
}
for l in 0..K {
*lanes[l].arith = ar[l];
}
}
#[allow(clippy::needless_range_loop)]
fn run_general(
start: usize,
span: &Span<'_>,
nch: usize,
nh: &[usize; MAX_NCH],
arith: &mut Arith<'_>,
hist: &mut [u8],
) {
for m in start / 8..span.end / 8 {
let mut base = [[0i16; 8]; MAX_NCH];
for ch in 0..nch {
for d in 0..span.used[ch] {
let byte = hist.get((HISTORY_BYTES + m - 1 - d) * nch + ch).copied().unwrap_or(0);
let row = &span.tabs[ch][d][usize::from(byte)];
for r in 0..8 {
base[ch][r] = base[ch][r].wrapping_add(row[r]);
}
}
}
let mut cur = [0u32; MAX_NCH];
for r in 0..8u32 {
for ch in 0..nch {
arith.refill();
let half = 8 * m + (r as usize) < nh[ch];
let idx = (1 << r) | cur[ch];
let y = symbol(arith, base[ch][r as usize], span.partial[ch], idx, span.luts[ch], half);
cur[ch] = (cur[ch] << 1) | y;
}
}
let at = (HISTORY_BYTES + m) * nch;
if let Some(dst) = hist.get_mut(at..at + nch) {
for (d, &c) in dst.iter_mut().zip(cur.iter()) {
*d = c as u8;
}
}
}
}
const LUT_LEN: usize = 8192;
const LUT_USED: usize = 4097;
type Lut = [u8; LUT_LEN];
type ScaledLut = [u64; MAX_PTABLE_LEN];
type QTable = [u64; 32];
const fn q_table() -> QTable {
let mut q = [0; 32];
let mut t = 0;
while t < 32 {
q[t] = (((t >> 1) | (t & 1)) as u64) << 52;
t += 1;
}
q
}
const fn byte_lut(nch: usize) -> bool {
!matches!(nch, 3 | 4)
}
#[derive(Clone, Debug)]
#[repr(C, align(64))]
struct Probe {
partial: [i16; 256],
scaled: ScaledLut,
q: QTable,
lut: Lut,
}
impl Probe {
fn fill(&mut self, partial: &[i16; 256], lut: &Lut, byte: bool) {
self.partial = *partial;
if byte {
self.lut[..LUT_USED].copy_from_slice(&lut[..LUT_USED]);
} else {
for (s, &p) in self.scaled.iter_mut().zip(lut) {
*s = u64::from(p) << 52;
}
}
}
}
const NO_PROBE: Probe =
Probe { partial: [0; 256], scaled: [128 << 52; MAX_PTABLE_LEN], q: q_table(), lut: [128; LUT_LEN] };
static NO_PROBES: [Probe; MAX_NCH] = [NO_PROBE; MAX_NCH];
static NO_LUT: Lut = [128; LUT_LEN];
#[derive(Clone, Copy)]
struct CodeBits<'a> {
bytes: &'a [u8],
pos: usize,
}
const CODE_PADDING: usize = 8;
impl<'a> CodeBits<'a> {
fn new(buf: &'a mut Vec<u8>, frame: &[u8], start: usize, len: usize) -> Self {
buf.clear();
let shift = (start % 8) as u32;
let first = start / 8;
let nbytes = len.div_ceil(8);
let src = frame.get(first..).unwrap_or(&[]);
let realign = |hi: u8, lo: u8| (((u16::from(hi) << 8 | u16::from(lo)) << shift) >> 8) as u8;
buf.extend(src.windows(2).take(nbytes).map(|w| realign(w[0], w[1])));
if buf.len() < nbytes {
if let Some(&b) = src.get(buf.len()) {
buf.push(realign(b, 0));
}
}
buf.resize(nbytes, 0);
if len % 8 != 0 {
if let Some(last) = buf.last_mut() {
*last &= 0xFF << (8 - len % 8);
}
}
buf.extend_from_slice(&[0; CODE_PADDING]);
CodeBits { bytes: buf, pos: 0 }
}
#[inline(always)]
fn peek(&self) -> u64 {
let byte = self.pos / 8;
let word = self.bytes.get(byte..byte + 8).map_or(0, |w| {
let mut b = [0u8; 8];
b.copy_from_slice(w);
u64::from_be_bytes(b)
});
word << (self.pos % 8)
}
#[inline(always)]
fn skip(&mut self, k: u32) {
self.pos = self.pos.wrapping_add(k as usize);
}
fn take12(&mut self) -> u32 {
let v = (self.peek() >> 52) as u32;
self.skip(12);
v
}
fn consumed(&self) -> usize {
self.pos
}
}
fn plain(frame: &[u8], out: &mut [u8]) -> Result<(), DstError> {
if frame[0] & 0x3F != 0 {
return Err(DstError::Stuffing);
}
let payload = &frame[1..];
let n = payload.len().min(out.len());
out[..n].copy_from_slice(&payload[..n]);
out[n..].fill(0);
Ok(())
}
fn read_filter(bits: &mut Bits<'_>) -> Result<Filter, DstError> {
let order = bits.read(7)? as usize + 1;
let mut values = [0i64; MAX_ORDER];
if bits.bit()? == 0 {
for v in values.iter_mut().take(order) {
*v = i64::from(bits.read_tc9()?);
}
} else {
let method = bits.read(2)? as usize;
if method == 3 {
return Err(DstError::CoefficientCoding);
}
let k = method + 1;
if k >= order {
return Err(DstError::CoefficientCoding);
}
for v in values.iter_mut().take(k) {
*v = i64::from(bits.read_tc9()?);
}
let m = bits.read(3)?;
for i in k..order {
let r = bits.rice(m)?;
let x: i64 = (0..k).map(|t| COEF_PRED[method][t] * values[i - 1 - t]).sum();
let a = r - round8(x);
if !(-256..=255).contains(&a) {
return Err(DstError::CoefficientRange);
}
values[i] = a;
}
}
let mut coefs = [0i32; MAX_ORDER];
for (c, &v) in coefs.iter_mut().zip(values.iter()) {
*c = v as i32;
}
Ok(Filter { order, coefs })
}
fn read_ptable(bits: &mut Bits<'_>) -> Result<Vec<u32>, DstError> {
let len = bits.read(6)? as usize + 1;
if len == 1 {
return Ok(vec![128]);
}
let mut values = [0i64; MAX_PTABLE_LEN];
if bits.bit()? == 0 {
for v in values.iter_mut().take(len) {
*v = i64::from(bits.read(7)?) + 1;
}
} else {
let method = bits.read(2)? as usize;
if method == 3 {
return Err(DstError::PtableCoding);
}
let k = method + 1;
if k >= len {
return Err(DstError::PtableCoding);
}
for v in values.iter_mut().take(k) {
*v = i64::from(bits.read(7)?) + 1;
}
let m = bits.read(3)?;
for i in k..len {
let r = bits.rice(m)?;
let x: i64 = (0..k).map(|t| PTABLE_PRED[method][t] * values[i - 1 - t]).sum();
let p = r - round8(x);
if !(1..=128).contains(&p) {
return Err(DstError::PtableRange);
}
values[i] = p;
}
}
Ok(values[..len].iter().map(|&v| v as u32).collect())
}
pub fn decode(frame: &[u8], channels: u8, out: &mut [u8]) -> Result<(), DstError> {
DstDecoder::new().decode(frame, channels, out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_decoder_uses_the_detected_isa() {
assert_eq!(DstDecoder::new().isa, Isa::detect());
}
#[test]
fn bitlen_examples() {
assert_eq!([0, 1, 2, 3, 4, 7, 4576].map(bitlen), [0, 1, 2, 2, 3, 3, 13]);
}
#[cfg(all(
miri,
target_feature = "avx2",
target_feature = "bmi1",
target_feature = "bmi2",
target_feature = "lzcnt",
target_feature = "movbe"
))]
#[test]
fn miri_slice_selects_the_wrapper() {
assert_ne!(Isa::detect(), Isa::generic());
}
#[test]
fn round8_floors() {
assert_eq!(round8(-5), -1);
assert_eq!(round8(-4), 0);
}
#[test]
fn plain_frames() {
crate::dispatch::testutil::with_big_stack(plain_frames_body);
}
fn plain_frames_body() {
let mut out = vec![1u8; 2 * FRAME_BYTES_PER_CHANNEL];
decode(&[0x40, 7, 8], 2, &mut out).unwrap();
assert_eq!(&out[..3], &[7, 8, 0]);
assert!(out[2..].iter().all(|&b| b == 0));
assert_eq!(decode(&[0x01, 7], 2, &mut out), Err(DstError::Stuffing));
assert_eq!(decode(&[0x00], 2, &mut out), Err(DstError::FrameTooShort));
assert_eq!(decode(&[0x00, 1], 7, &mut out), Err(DstError::InvalidArguments));
}
#[test]
fn fast_loop_matches_general_1_frame() {
fast_loop_matches_general(1);
}
#[test]
fn fast_loop_matches_general_2_frames() {
fast_loop_matches_general(2);
}
#[test]
fn fast_loop_matches_general_3_frames() {
fast_loop_matches_general(3);
}
#[test]
fn fast_loop_matches_general_4_frames() {
fast_loop_matches_general(4);
}
fn fast_loop_matches_general(k: usize) {
assert!((1..=MAX_LANES).contains(&k));
let mut seed = 0x9E37_79B9_7F4A_7C15u64 ^ k as u64;
let mut rnd = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let code: Vec<u8> = (0..1024).map(|_| rnd() as u8).collect();
let mut random: Vec<ByteTable> = Vec::new();
for _ in 0..3 {
random.push(core::array::from_fn(|_| core::array::from_fn(|_| (rnd() % 4097) as i16 - 2048)));
}
let tables: Vec<[ByteTable; HISTORY_BYTES]> = (0..=HISTORY_BYTES)
.map(|used| core::array::from_fn(|d| if d < used { random[d % 3] } else { [[0; 8]; 256] }))
.collect();
let partials: Vec<[i16; 256]> =
(0..2).map(|_| core::array::from_fn(|_| (rnd() % 3585) as i16 - 1792)).collect();
let luts: Vec<Lut> = (0..2)
.map(|k| core::array::from_fn(|j| ((j.min(MAX_PTABLE_LEN - 1) * (k + 1) + k) % 128 + 1) as u8))
.collect();
let chunks: &[(usize, usize)] =
if cfg!(miri) { &[(0, 0), (8, 24)] } else { &[(0, 0), (8, 16), (24, 96)] };
for nch in 1..=MAX_NCH {
for u in [4, 8, 16] {
for &(start, end) in chunks {
let spans: Vec<Span<'_>> = (0..k)
.map(|l| {
let used = core::array::from_fn(|c| u - (c + l).min(u - 1));
Span {
end: end + 64 * l,
half: false,
used,
most: u,
tabs: core::array::from_fn(|c| &tables[used[c]]),
partial: core::array::from_fn(|c| &partials[(c + l) % 2]),
luts: core::array::from_fn(|c| &luts[(c + 2 * l) % 3 % 2]),
keys: [(0, 0); MAX_NCH],
}
})
.collect();
let starts: Vec<usize> = (0..k).map(|l| start + 64 * l).collect();
let len = (HISTORY_BYTES + FRAME_BYTES_PER_CHANNEL) * nch + WINDOW;
let hists: Vec<Vec<u8>> =
(0..k).map(|_| (0..len).map(|_| rnd() as u8).collect()).collect();
let mut results = Vec::new();
for general in [false, true] {
let mut bufs: Vec<Vec<u8>> = vec![Vec::new(); k];
let mut ars: Vec<Arith<'_>> = bufs
.iter_mut()
.enumerate()
.map(|(l, buf)| {
let from = &code[128 * l..];
Arith {
a: 4095 << 52,
x: 0,
code: CodeBits::new(buf, from, 0, from.len() * 8),
}
})
.collect();
let mut hists = hists.clone();
if general {
for l in 0..k {
run_general(
starts[l],
&spans[l],
nch,
&[0; MAX_NCH],
&mut ars[l],
&mut hists[l],
);
}
} else {
let bytes = (end - start) / 8;
let probes: Vec<[Probe; MAX_NCH]> = spans
.iter()
.map(|s| {
core::array::from_fn(|c| {
let mut p = NO_PROBE;
p.fill(s.partial[c], s.luts[c], byte_lut(nch));
p
})
})
.collect();
let mut runs: Vec<LaneRun<'_, '_>> = ars
.iter_mut()
.zip(hists.iter_mut())
.enumerate()
.map(|(l, (arith, hist))| LaneRun {
start: starts[l] / 8,
tabs: spans[l].tabs,
probes: &probes[l],
arith,
hist,
})
.collect();
macro_rules! by_tables {
($k:literal, $n:literal) => {
match u {
4 => run::<$k, $n, 4>(&mut runs, bytes),
8 => run::<$k, $n, 8>(&mut runs, bytes),
_ => run::<$k, $n, 16>(&mut runs, bytes),
}
};
}
macro_rules! by_channels {
($k:literal) => {
match nch {
1 => by_tables!($k, 1),
2 => by_tables!($k, 2),
3 => by_tables!($k, 3),
4 => by_tables!($k, 4),
5 => by_tables!($k, 5),
_ => by_tables!($k, 6),
}
};
}
match k {
1 => by_channels!(1),
2 => by_channels!(2),
3 => by_channels!(3),
_ => by_channels!(4),
}
}
let state: Vec<_> = ars
.iter_mut()
.map(|ar| {
ar.refill();
(ar.a, ar.x, ar.code.pos)
})
.collect();
results.push((state, hists));
}
assert!(
results[0] == results[1],
"{k} frames, {nch} channels, {u} tables, chunk {start}..{end}"
);
}
}
}
}
#[test]
fn rice_codes() {
let data = [0b0110_1000];
let mut b = Bits::new(&data);
assert_eq!(b.rice(2), Ok(-6));
let data = [0b1000_0000];
let mut b = Bits::new(&data);
assert_eq!(b.rice(0), Ok(0));
assert_eq!(b.pos, 1);
let mut b = Bits::new(&[0u8]);
assert_eq!(b.rice(0), Err(DstError::HeaderTruncated));
}
#[test]
fn q_table_step_matches_decode() {
let (a_step, p_step) = if cfg!(miri) { (97, 13) } else { (1, 1) };
let q = q_table();
for a in (2048u64..4096).step_by(a_step) {
for p in (1u32..=128).step_by(p_step) {
let w1 = a - ((a >> 8) | ((a >> 7) & 1)) * u64::from(p);
for c in [0, w1 - 1, w1, a - 1] {
let arith = Arith { a: a << 52, x: c << 52, code: CodeBits { bytes: &[], pos: 0 } };
let (mut one, mut two) = (arith, arith);
assert_eq!(one.decode(p), two.decode_table(p, &q));
assert_eq!((one.a, one.x, one.code.pos), (two.a, two.x, two.code.pos));
}
}
}
}
}