use std::ops::Range;
use super::{Checked, Layout, OutputOptions, Part, RegionKind};
use crate::audio::{self, FRAME_BYTES_PER_CHANNEL};
use crate::error::{Error, OutputRefusal, Slot};
use crate::toc::{Area, LoudspeakerLayout, Toc};
const BLOCK: u64 = 4096;
const HEADER: usize = 92;
const SAMPLES_PER_BYTE: u64 = 8;
const SAMPLE_RATE: u32 = 2_822_400;
const MAX_ROW: usize = 6 * BLOCK as usize;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DsfBitsPerSample {
One,
Eight,
}
#[derive(Clone, Debug)]
pub(super) struct DsfData {
channels: u8,
start: u64,
stream: u64,
skip: u64,
reverse: bool,
}
impl DsfData {
pub(super) fn bytes(&self) -> (u64, u64) {
(self.start, self.start + self.stream)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct DsfChainFile {
pub range: (u32, u32),
pub chain: (u32, u32),
pub bytes: (u64, u64),
}
impl DsfChainFile {
pub fn is_last(&self) -> bool {
self.range.1 == self.chain.1
}
}
fn chain_start(a1: u32, a: u32) -> u64 {
let per = FRAME_BYTES_PER_CHANNEL as u64;
per * u64::from(a1) + BLOCK * (per * u64::from(a - a1) / BLOCK)
}
pub(super) fn chain_bytes(a1: u32, end: u32, a: u32, b: u32) -> (u64, u64) {
let q = if b == end { FRAME_BYTES_PER_CHANNEL as u64 * u64::from(end) } else { chain_start(a1, b) };
(chain_start(a1, a), q)
}
pub fn plan_dsf_chain(
toc: &Toc,
slot: Slot,
bounds: &[u32],
) -> Result<Vec<Result<DsfChainFile, Error>>, Error> {
let area = toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
if bounds.len() < 2 {
return Err(Error::InvalidArgument("a chain needs at least one range: two bounds"));
}
let mut errors: Vec<Option<Error>> =
bounds.windows(2).map(|w| audio::check_range(area, w[0], w[1], toc.sectors).err()).collect();
let mut files = Vec::with_capacity(errors.len());
let mut i = 0;
while i < errors.len() {
let j = (i..errors.len()).find(|&j| errors[j].is_some()).unwrap_or(errors.len());
let chain = (bounds[i], bounds[j]);
for k in i..j {
let range = (bounds[k], bounds[k + 1]);
let bytes = chain_bytes(chain.0, chain.1, range.0, range.1);
files.push(Ok(DsfChainFile { range, chain, bytes }));
}
if let Some(e) = errors.get_mut(j).and_then(Option::take) {
files.push(Err(e));
}
i = j + 1;
}
Ok(files)
}
fn channel_type(area: &Area, options: &OutputOptions) -> Result<u32, Error> {
match area.loudspeaker_layout() {
LoudspeakerLayout::Stereo => Ok(2),
LoudspeakerLayout::ThreeTwo => Ok(6),
LoudspeakerLayout::FivePointOne => Ok(7),
LoudspeakerLayout::Unspecified { channels, config } => {
let t = options
.dsf_unspecified_channel_type
.ok_or(Error::OutputRefused(OutputRefusal::UnspecifiedLayout { channels, config }))?;
let count = match t {
1 => 1,
2 => 2,
3 => 3,
4 | 5 => 4,
6 => 5,
7 => 6,
_ => return Err(Error::InvalidArgument("DSF channel types are 1 to 7")),
};
if count != channels {
return Err(Error::InvalidArgument(
"the DSF channel type must have the area's channel count",
));
}
Ok(t)
}
}
}
pub(super) fn build(
layout: &mut Layout,
area: &Area,
options: &OutputOptions,
tag: Option<Vec<u8>>,
) -> Result<(), Error> {
let channel_type = channel_type(area, options)?;
let c = u64::from(layout.channels);
let per = FRAME_BYTES_PER_CHANNEL as u64;
let (start, end) = match layout.chain {
Some((a1, chain_end)) => chain_bytes(a1, chain_end, layout.first, layout.end),
None => (per * u64::from(layout.first), per * u64::from(layout.end)),
};
layout.base = (start / per) as u32;
let skip = start - per * u64::from(layout.base);
let stream = end - start;
let blocks = stream.div_ceil(BLOCK);
let n = BLOCK * blocks * c;
let m = tag.as_ref().map_or(0, |t| t.len() as u64);
let total = HEADER as u64 + n + m;
let pointer = if m > 0 { HEADER as u64 + n } else { 0 };
let bits = match options.dsf_bits_per_sample {
DsfBitsPerSample::One => 1,
DsfBitsPerSample::Eight => 8,
};
let mut h = Vec::with_capacity(HEADER);
h.extend_from_slice(b"DSD ");
h.extend_from_slice(&28u64.to_le_bytes());
h.extend_from_slice(&total.to_le_bytes());
h.extend_from_slice(&pointer.to_le_bytes());
h.extend_from_slice(b"fmt ");
h.extend_from_slice(&52u64.to_le_bytes());
h.extend_from_slice(&1u32.to_le_bytes());
h.extend_from_slice(&0u32.to_le_bytes());
h.extend_from_slice(&channel_type.to_le_bytes());
h.extend_from_slice(&u32::from(layout.channels).to_le_bytes());
h.extend_from_slice(&SAMPLE_RATE.to_le_bytes());
h.extend_from_slice(&(bits as u32).to_le_bytes());
h.extend_from_slice(&(stream * SAMPLES_PER_BYTE).to_le_bytes());
h.extend_from_slice(&(BLOCK as u32).to_le_bytes());
h.extend_from_slice(&0u32.to_le_bytes());
h.extend_from_slice(b"data");
h.extend_from_slice(&(n + 12).to_le_bytes());
debug_assert_eq!(h.len(), HEADER);
layout.push(RegionKind::Header, HEADER as u64, Part::Bytes(h));
let data = DsfData { channels: layout.channels, start, stream, skip, reverse: bits == 1 };
layout.push(RegionKind::SoundData, n, Part::Dsf(data));
if let Some(tag) = tag.filter(|t| !t.is_empty()) {
layout.push(RegionKind::Trailer, tag.len() as u64, Part::Bytes(tag));
}
Ok(())
}
impl DsfData {
fn row(&self) -> u64 {
BLOCK * u64::from(self.channels)
}
pub(super) fn positions(&self, range: Range<u64>) -> Range<u32> {
let row = self.row();
let lo = range.start / row * BLOCK;
let hi = ((range.end - 1) / row + 1).saturating_mul(BLOCK).min(self.stream);
if lo >= hi {
return 0..0;
}
let per = FRAME_BYTES_PER_CHANNEL as u64;
((lo + self.skip) / per) as u32..((hi - 1 + self.skip) / per + 1) as u32
}
#[inline(always)]
pub(super) fn fill(
&self,
offset: u64,
out: &mut [u8],
first: u32,
source: &mut Checked<'_>,
) -> Result<(), Error> {
let row = self.row() as usize;
let mut scratch = [0; MAX_ROW];
let mut done = 0;
while done < out.len() {
let o = offset + done as u64;
let j = o / row as u64;
let within = (o % row as u64) as usize;
let n = (row - within).min(out.len() - done);
let dst = &mut out[done..done + n];
if n == row {
self.fill_row(j, dst, first, source)?;
} else {
self.fill_row(j, &mut scratch[..row], first, source)?;
dst.copy_from_slice(&scratch[within..within + n]);
}
done += n;
}
Ok(())
}
#[inline(always)]
fn fill_row(&self, j: u64, out: &mut [u8], first: u32, source: &mut Checked<'_>) -> Result<(), Error> {
let per = FRAME_BYTES_PER_CHANNEL as u64;
let c = usize::from(self.channels);
let mut k = j * BLOCK;
let end = (k + BLOCK).min(self.stream);
let mut at = 0;
while k < end {
let timeline = k + self.skip;
let within = (timeline % per) as usize;
let n = (FRAME_BYTES_PER_CHANNEL - within).min((end - k) as usize);
let t = first + (timeline / per) as u32;
let content = source.content(t)?;
split(&content[within * c..(within + n) * c], out, at, n, c, self.reverse);
at += n;
k += n as u64;
}
if at < BLOCK as usize {
for block in out.chunks_exact_mut(BLOCK as usize) {
block[at..].fill(0);
}
}
Ok(())
}
}
#[inline(always)]
fn split(src: &[u8], row: &mut [u8], at: usize, n: usize, c: usize, reverse: bool) {
let mut blocks = row.chunks_exact_mut(BLOCK as usize).map(|b| &mut b[at..at + n]);
let mut next = || blocks.next().unwrap_or_default();
macro_rules! split {
($c:literal, $pat:pat, $zip:expr, $($o:ident $i:literal),+) => {{
$(let $o = next().iter_mut();)+
if reverse {
for (f, $pat) in src.chunks_exact($c).zip($zip) {
$(*$o = f[$i].reverse_bits();)+
}
} else {
for (f, $pat) in src.chunks_exact($c).zip($zip) {
$(*$o = f[$i];)+
}
}
}};
}
match c {
1 => split!(1, a, a, a 0),
2 => split!(2, (a, b), a.zip(b), a 0, b 1),
3 => split!(3, ((a, b), d), a.zip(b).zip(d), a 0, b 1, d 2),
4 => split!(4, (((a, b), d), e), a.zip(b).zip(d).zip(e), a 0, b 1, d 2, e 3),
5 => split5(src, [next(), next(), next(), next(), next()], reverse),
6 => {
split!(6, (((((a, b), d), e), g), h), a.zip(b).zip(d).zip(e).zip(g).zip(h), a 0, b 1, d 2, e 3, g 4, h 5)
}
_ => {}
}
}
#[inline(always)]
fn split5(src: &[u8], out: [&mut [u8]; 5], reverse: bool) {
const B: [u32; 4] = [0xFF, 0xFF00, 0xFF_0000, 0xFF00_0000];
let [a, b, d, e, g] = out;
let whole = a.len() / 4 * 4;
let (src, src_rest) = src.split_at(whole * 5);
let (a, a_rest) = a.split_at_mut(whole);
let (b, b_rest) = b.split_at_mut(whole);
let (d, d_rest) = d.split_at_mut(whole);
let (e, e_rest) = e.split_at_mut(whole);
let (g, g_rest) = g.split_at_mut(whole);
let word = |s: &[u8], k: usize| {
s.get(4 * k..4 * k + 4).and_then(|w| w.try_into().ok()).map_or(0, u32::from_le_bytes)
};
let words = a
.chunks_exact_mut(4)
.zip(b.chunks_exact_mut(4))
.zip(d.chunks_exact_mut(4))
.zip(e.chunks_exact_mut(4))
.zip(g.chunks_exact_mut(4));
macro_rules! words {
($f:expr) => {
for (s, ((((a, b), d), e), g)) in src.chunks_exact(20).zip(words) {
let [w0, w1, w2, w3, w4] = [word(s, 0), word(s, 1), word(s, 2), word(s, 3), word(s, 4)];
let f = $f;
a.copy_from_slice(&f((w0 & B[0]) | (w1 & B[1]) | (w2 & B[2]) | (w3 & B[3])).to_le_bytes());
b.copy_from_slice(
&f(((w0 & B[1]) | (w1 & B[2]) | (w2 & B[3])) >> 8 | w4 << 24).to_le_bytes(),
);
d.copy_from_slice(
&f(((w0 & B[2]) | (w1 & B[3])) >> 16 | ((w3 & B[0]) | (w4 & B[1])) << 16).to_le_bytes(),
);
e.copy_from_slice(
&f(w0 >> 24 | ((w2 & B[0]) | (w3 & B[1]) | (w4 & B[2])) << 8).to_le_bytes(),
);
g.copy_from_slice(&f((w1 & B[0]) | (w2 & B[1]) | (w3 & B[2]) | (w4 & B[3])).to_le_bytes());
}
};
}
if reverse {
words!(|w: u32| w.reverse_bits().swap_bytes());
} else {
words!(|w: u32| w);
}
let rest =
a_rest.iter_mut().zip(b_rest.iter_mut()).zip(d_rest.iter_mut()).zip(e_rest.iter_mut()).zip(g_rest);
for (f, ((((a, b), d), e), g)) in src_rest.chunks_exact(5).zip(rest) {
for (o, &v) in [a, b, d, e, g].into_iter().zip(f) {
*o = if reverse { v.reverse_bits() } else { v };
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use std::borrow::Cow;
use super::super::{Checked, PositionSource};
use super::{BLOCK, DsfData};
use crate::audio::FRAME_BYTES_PER_CHANNEL;
use crate::error::Error;
#[test]
fn reversal_matches_the_example_of_8_2_3() {
assert_eq!([0x00, 0x01, 0x02, 0x03, 0x04].map(u8::reverse_bits), [0x00, 0x80, 0x40, 0xC0, 0x20]);
}
struct Made(u8, Vec<(u32, Vec<u8>)>);
impl PositionSource for Made {
fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
let i = match self.1.iter().position(|(u, _)| *u == t) {
Some(i) => i,
None => {
let len = usize::from(self.0) * FRAME_BYTES_PER_CHANNEL;
let content =
(0..len).map(|i| (i as u32 * 131 + t * 7919 + i as u32 / 255) as u8).collect();
self.1.push((t, content));
self.1.len() - 1
}
};
Ok(Cow::Borrowed(&self.1[i].1))
}
}
fn fill_blocks(
data: &DsfData,
offset: u64,
out: &mut [u8],
first: u32,
source: &mut Checked<'_>,
) -> Result<(), Error> {
let row = data.row();
let c = usize::from(data.channels);
let per = FRAME_BYTES_PER_CHANNEL as u64;
let mut done = 0;
while done < out.len() {
let o = offset + done as u64;
let channel = ((o % row) / BLOCK) as usize;
let mut k = o / row * BLOCK + o % BLOCK;
let run =
usize::try_from(BLOCK - o % BLOCK).map_or(out.len() - done, |r| r.min(out.len() - done));
let block = &mut out[done..done + run];
let mut at = 0;
while at < run {
if k >= data.stream {
block[at..].fill(0);
break;
}
let timeline = k + data.skip;
let within = (timeline % per) as usize;
let n = (run - at)
.min(FRAME_BYTES_PER_CHANNEL - within)
.min(usize::try_from(data.stream - k).unwrap_or(usize::MAX));
let t = first + (timeline / per) as u32;
let content = source.content(t)?;
let src = content[within * c + channel..].iter().step_by(c);
for (dst, &b) in block[at..at + n].iter_mut().zip(src) {
*dst = if data.reverse { b.reverse_bits() } else { b };
}
at += n;
k += n as u64;
}
done += run;
}
Ok(())
}
#[test]
fn partial_row_asks_for_every_position_of_its_row() {
struct Failing {
made: Made,
bad: u32,
}
impl PositionSource for Failing {
fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
if t == self.bad {
return Err(Error::InvalidArgument("the bad position"));
}
self.made.content(t)
}
}
let first = 3;
let len = 2 * FRAME_BYTES_PER_CHANNEL;
let row = 2 * BLOCK;
let data = DsfData { channels: 2, start: 0, stream: 3 * BLOCK, skip: 0, reverse: true };
assert_eq!(data.positions(row..row + 64), 0..2);
let mut source = Failing { made: Made(2, Vec::new()), bad: first + 1 };
let mut part = [0; 64];
let result = data.fill(row, &mut part, first, &mut Checked { inner: &mut source, len });
assert!(matches!(result, Err(Error::InvalidArgument("the bad position"))));
fill_blocks(&data, row, &mut part, first, &mut Checked { inner: &mut source, len }).unwrap();
data.fill(0, &mut part, first, &mut Checked { inner: &mut source, len }).unwrap();
let data = DsfData { channels: 2, start: 0, stream: BLOCK + 10, skip: 0, reverse: true };
let mut source = Failing { made: Made(2, Vec::new()), bad: first };
let mut pad = [0xAA; 1];
let result = data.fill(row + 20, &mut pad, first, &mut Checked { inner: &mut source, len });
assert!(matches!(result, Err(Error::InvalidArgument("the bad position"))));
fill_blocks(&data, row + 20, &mut pad, first, &mut Checked { inner: &mut source, len }).unwrap();
assert_eq!(pad, [0]);
}
#[test]
fn rows_equal_blocks() {
let per = FRAME_BYTES_PER_CHANNEL as u64;
let (channels, streams): (&[u8], &[(u64, u64)]) = if cfg!(miri) {
(&[1, 2, 6], &[(1000, per + 17), (4095, 2 * BLOCK)])
} else {
(
&[1, 2, 3, 4, 5, 6],
&[(0, 5 * per), (1000, 4 * per + 17), (4095, 3 * BLOCK), (8, 9 * BLOCK + 8)],
)
};
for &channels in channels {
for reverse in [false, true] {
for &(skip, stream) in streams {
let data = DsfData { channels, start: skip, stream, skip, reverse };
let size = (BLOCK * stream.div_ceil(BLOCK) * u64::from(channels)) as usize;
let mut source = Made(channels, Vec::new());
let len = usize::from(channels) * FRAME_BYTES_PER_CHANNEL;
let (mut rows, mut blocks) = (vec![0xAA; size], vec![0x55; size]);
data.fill(0, &mut rows, 3, &mut Checked { inner: &mut source, len }).unwrap();
fill_blocks(&data, 0, &mut blocks, 3, &mut Checked { inner: &mut source, len }).unwrap();
assert!(
rows == blocks,
"{channels} channels, reverse {reverse}, skip {skip}, S {stream}"
);
for (at, n) in
[(1, size - 2), (4097, 3 * 4096 * usize::from(channels)), (size - 5000, 5000)]
{
let n = n.min(size - at);
let mut part = vec![0; n];
data.fill(at as u64, &mut part, 3, &mut Checked { inner: &mut source, len }).unwrap();
assert!(part == blocks[at..at + n], "{channels} channels: {at}+{n}");
}
}
}
}
}
}