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;
let offset = per * u64::from(a - a1);
per * u64::from(a1) + if offset == 0 { 0 } else { BLOCK * ((offset - 1) / 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 (j0, j1) = (range.start / row, (range.end - 1) / row);
let (a, b) = ((range.start % row) as usize, ((range.end - 1) % row) as usize + 1);
let mut lo = u64::MAX;
let mut hi = if j0 == j1 { 0 } else { (j1 * BLOCK).min(self.stream) };
let rows = if j0 == j1 { [(j0, a, b), (j0, a, b)] } else { [(j0, a, row as usize), (j1, 0, b)] };
for (j, a, b) in rows {
for span in covered(a, b) {
let start = j * BLOCK + span.start as u64;
let end = (j * BLOCK + span.end as u64).min(self.stream);
if start < end {
lo = lo.min(start);
hi = hi.max(end);
}
}
}
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, 0..BLOCK as usize, dst, first, source)?;
} else {
let scratch = &mut scratch[..row];
for span in covered(within, within + n) {
if !span.is_empty() {
self.fill_row(j, span, scratch, first, source)?;
}
}
dst.copy_from_slice(&scratch[within..within + n]);
}
done += n;
}
Ok(())
}
#[inline(always)]
fn fill_row(
&self,
j: u64,
span: Range<usize>,
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 + span.start as u64;
let end = (j * BLOCK + span.end as u64).min(self.stream);
let mut at = span.start;
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 < span.end {
for block in out.chunks_exact_mut(BLOCK as usize) {
block[at..span.end].fill(0);
}
}
Ok(())
}
}
fn covered(a: usize, b: usize) -> [Range<usize>; 2] {
let block = BLOCK as usize;
let (first, last) = (a / block, (b - 1) / block);
let (x, y) = (a % block, (b - 1) % block + 1);
if first == last {
[x..y, 0..0]
} else if last > first + 1 || x <= y {
[0..block, 0..0]
} else {
[0..y, x..block]
}
}
#[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, chain_bytes};
use crate::audio::FRAME_BYTES_PER_CHANNEL;
use crate::error::Error;
#[test]
fn chain_boundary_on_a_block_carries_the_block_on() {
let per = FRAME_BYTES_PER_CHANNEL as u64;
let cases: &[(&[u32], u32, &[u64])] = &[
(&[128, 50, 60], 0, &[598_016, 237_568, 286_720]),
(&[127, 50, 60], 0, &[593_920, 237_568, 286_720]),
(&[128, 128, 60], 0, &[598_016, 602_112, 286_720]),
(&[256, 50, 60], 0, &[1_200_128, 237_568, 286_720]),
(&[50, 78, 60], 0, &[233_472, 364_544, 286_720]),
(&[128, 60], 50, &[598_016, 286_720]),
(&[50, 78], 0, &[233_472, 368_640]),
(&[128], 0, &[602_112]),
];
for &(frames, a1, want) in cases {
let mut bounds = vec![a1];
for f in frames {
bounds.push(bounds.last().unwrap() + f);
}
let end = *bounds.last().unwrap();
let files: Vec<(u64, u64)> =
bounds.windows(2).map(|r| chain_bytes(a1, end, r[0], r[1])).collect();
let sizes: Vec<u64> = files.iter().map(|(p, q)| BLOCK * (q - p).div_ceil(BLOCK)).collect();
assert_eq!(sizes, want, "chain {frames:?} from frame {a1}");
assert_eq!(files.first().unwrap().0, per * u64::from(a1));
assert_eq!(files.last().unwrap().1, per * u64::from(end));
for (i, w) in files.windows(2).enumerate() {
assert_eq!(w[0].1, w[1].0, "chain {frames:?}: gap after file {i}");
}
for (i, &(p, q)) in files.iter().enumerate() {
if i + 1 < files.len() {
assert!((q - p) % BLOCK == 0 && q - p >= BLOCK, "chain {frames:?}, file {i}: {}", q - p);
}
if i > 0 {
let carried = per * u64::from(bounds[i]) - p;
assert!((1..=BLOCK).contains(&carried), "chain {frames:?}, file {i}: carries {carried}");
}
}
}
}
#[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))
}
}
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)
}
}
struct Recording<'a> {
made: &'a mut Made,
asked: Vec<u32>,
}
impl PositionSource for Recording<'_> {
fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
self.asked.push(t);
self.made.content(t)
}
}
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_only_for_the_positions_it_covers() {
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..1);
let mut source = Failing { made: Made(2, Vec::new()), bad: first + 1 };
let (mut part, mut blocks) = ([0; 64], [0; 64]);
data.fill(row, &mut part, first, &mut Checked { inner: &mut source, len }).unwrap();
fill_blocks(&data, row, &mut blocks, first, &mut Checked { inner: &mut source, len }).unwrap();
assert_eq!(part, blocks);
data.fill(row + BLOCK, &mut part, first, &mut Checked { inner: &mut source, len }).unwrap();
let result = data.fill(row + 608, &mut part, first, &mut Checked { inner: &mut source, len });
assert!(matches!(result, Err(Error::InvalidArgument("the bad position"))));
let data = DsfData { channels: 2, start: 0, stream: BLOCK + 10, skip: 0, reverse: true };
assert!(data.positions(row + 20..row + 21).is_empty());
let mut source = Failing { made: Made(2, Vec::new()), bad: first };
let mut pad = [0xAA; 1];
data.fill(row + 20, &mut pad, first, &mut Checked { inner: &mut source, len }).unwrap();
assert_eq!(pad, [0]);
}
#[test]
fn partial_rows_ask_for_the_positions_of_blocks() {
let per = FRAME_BYTES_PER_CHANNEL;
let channels: &[u8] = if cfg!(miri) { &[2] } else { &[1, 2, 3, 4, 5, 6] };
let sizes: &[usize] = if cfg!(miri) { &[600, 4097] } else { &[1, 64, 600, 1024, 4000, 4097, 9000] };
for &channels in channels {
let c = usize::from(channels);
let stream = if cfg!(miri) { per + 17 } else { 3 * per + 17 } as u64;
let skip = 1000;
let data = DsfData { channels, start: skip, stream, skip, reverse: false };
let size = (BLOCK * stream.div_ceil(BLOCK)) as usize * c;
let len = c * per;
let mut made = Made(channels, Vec::new());
let row = 4096 * c;
let mut starts: Vec<usize> = Vec::new();
if cfg!(miri) {
starts.extend([4096 - 30, row - 30, per - 1030]);
} else {
let positions = [per - 1000, per - 1000 + 4096 * (c - 1), 2 * row + 216];
for edge in (0..size).step_by(BLOCK as usize).chain(positions) {
starts.extend([edge.saturating_sub(30), edge, edge + 100]);
}
}
for &at in &starts {
for &n in sizes {
let n = n.min(size.saturating_sub(at));
if n == 0 {
continue;
}
let range = at as u64..(at + n) as u64;
let mut asked = |blocks: bool, out: &mut [u8]| {
let mut source = Recording { made: &mut made, asked: Vec::new() };
let mut checked = Checked { inner: &mut source, len };
if blocks {
fill_blocks(&data, range.start, out, 7, &mut checked).unwrap();
} else {
data.fill(range.start, out, 7, &mut checked).unwrap();
}
let mut asked = source.asked;
asked.sort_unstable();
asked.dedup();
asked
};
let (mut rows, mut blocks) = (vec![0xAA; n], vec![0x55; n]);
let by_rows = asked(false, &mut rows);
let by_blocks = asked(true, &mut blocks);
assert!(rows == blocks, "{channels} channels: {at}+{n}");
assert_eq!(by_rows, by_blocks, "{channels} channels: {at}+{n}");
let positions = data.positions(range.clone());
let hull = by_rows.first().map_or(0..0, |&t| t - 7..by_rows[by_rows.len() - 1] - 7 + 1);
assert_eq!(positions, hull, "{channels} channels: {at}+{n}");
}
}
}
}
#[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}");
}
}
}
}
}
}