use std::ops::Range;
use super::markers::{self, Markers};
use super::tags::{ArtistTitleSource, TagItem, TagSet};
use super::{Checked, Layout, OutputOptions, Part, RegionKind, SourceTrack};
use super::{Tags, dsdiff_text};
use crate::audio::FRAME_BYTES_PER_CHANNEL;
use crate::error::Error;
use crate::toc::{Area, LoudspeakerLayout, Toc};
const SAMPLE_RATE: u32 = 2_822_400;
const FRAMES_PER_HOUR: u64 = 270_000;
pub(super) const MAX_TIME_FRAMES: u64 = 6_479_999;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PropertyChunk {
SampleRate,
Channels,
CompressionType,
AbsoluteStartTime,
LoudspeakerConfiguration,
}
impl PropertyChunk {
pub const TABLE_ORDER: [PropertyChunk; 5] = [
PropertyChunk::SampleRate,
PropertyChunk::Channels,
PropertyChunk::CompressionType,
PropertyChunk::AbsoluteStartTime,
PropertyChunk::LoudspeakerConfiguration,
];
}
pub(super) fn chunk(out: &mut Vec<u8>, id: &[u8; 4], data: &[u8]) {
chunk_head(out, id, data.len() as u64);
out.extend_from_slice(data);
if data.len() % 2 == 1 {
out.push(0);
}
}
pub(super) fn chunk_head(out: &mut Vec<u8>, id: &[u8; 4], d: u64) {
out.extend_from_slice(id);
out.extend_from_slice(&d.to_be_bytes());
}
pub(super) fn occupied(d: u64) -> u64 {
12 + d + d % 2
}
pub(super) fn time(g: u64) -> (u16, u8, u8, u32) {
((g / FRAMES_PER_HOUR) as u16, (g / 4500 % 60) as u8, (g / 75 % 60) as u8, (g % 75 * 37_632) as u32)
}
fn channels(area: &Area, options: &OutputOptions) -> Result<(Vec<[u8; 4]>, Option<u16>), Error> {
let lsco = |v| options.dsdiff_loudspeaker_configuration.then_some(v);
Ok(match area.loudspeaker_layout() {
LoudspeakerLayout::Stereo => (vec![*b"SLFT", *b"SRGT"], lsco(0)),
LoudspeakerLayout::ThreeTwo => (vec![*b"MLFT", *b"MRGT", *b"C ", *b"LS ", *b"RS "], lsco(3)),
LoudspeakerLayout::FivePointOne => {
(vec![*b"MLFT", *b"MRGT", *b"C ", *b"LFE ", *b"LS ", *b"RS "], lsco(4))
}
LoudspeakerLayout::Unspecified { channels, .. } => {
let numbers: Vec<u16> = match &options.dsdiff_unspecified_channel_numbers {
Some(n) => n.clone(),
None => (0..u16::from(channels)).collect(),
};
if numbers.len() != usize::from(channels) {
return Err(Error::InvalidArgument("give one DSDIFF channel number per channel"));
}
let mut seen = [false; 1000];
let mut ids = Vec::with_capacity(numbers.len());
for n in numbers {
let slot = seen
.get_mut(usize::from(n))
.ok_or(Error::InvalidArgument("DSDIFF channel numbers are 0 to 999"))?;
if std::mem::replace(slot, true) {
return Err(Error::InvalidArgument("DSDIFF channel numbers must be distinct"));
}
let d = |p: u16| b'0' + (n / p % 10) as u8;
ids.push([b'C', d(100), d(10), d(1)]);
}
(ids, options.dsdiff_unspecified_loudspeaker_configuration.then_some(65_535))
}
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum DsdiffDeparture {
D1,
D2,
}
const CMPR_DSD: (&[u8; 4], &[u8]) = (b"DSD ", b"not compressed");
const CMPR_DST: (&[u8; 4], &[u8]) = (b"DST ", b"DST Encoded");
fn property(area: &Area, options: &OutputOptions, n: u64, cmpr: (&[u8; 4], &[u8])) -> Result<Vec<u8>, Error> {
let (ids, lsco) = channels(area, options)?;
let order = options.dsdiff_property_order;
let mut sorted = order;
sorted.sort_by_key(|c| PropertyChunk::TABLE_ORDER.iter().position(|t| t == c));
if sorted != PropertyChunk::TABLE_ORDER {
return Err(Error::InvalidArgument("the property order must name each property chunk once"));
}
if let Some(a) = options.dsdiff_absolute_start {
if u64::from(a) + n > MAX_TIME_FRAMES {
return Err(Error::InvalidArgument(
"the absolute start time plus the range must stay below 24 hours",
));
}
}
let mut prop = b"SND ".to_vec();
for c in order {
match c {
PropertyChunk::SampleRate => chunk(&mut prop, b"FS ", &SAMPLE_RATE.to_be_bytes()),
PropertyChunk::Channels => {
let mut d = (ids.len() as u16).to_be_bytes().to_vec();
ids.iter().for_each(|id| d.extend_from_slice(id));
chunk(&mut prop, b"CHNL", &d);
}
PropertyChunk::CompressionType => {
let mut d = cmpr.0.to_vec();
d.push(cmpr.1.len() as u8);
d.extend_from_slice(cmpr.1);
if options.departs(DsdiffDeparture::D1) && d.len() % 2 == 1 {
d.push(0);
}
chunk(&mut prop, b"CMPR", &d);
}
PropertyChunk::AbsoluteStartTime => {
if let Some(a) = options.dsdiff_absolute_start {
let (h, m, s, samples) = time(u64::from(a));
let mut d = h.to_be_bytes().to_vec();
d.extend_from_slice(&[m, s]);
d.extend_from_slice(&samples.to_be_bytes());
chunk(&mut prop, b"ABSS", &d);
}
}
PropertyChunk::LoudspeakerConfiguration => {
if let Some(v) = lsco {
chunk(&mut prop, b"LSCO", &v.to_be_bytes());
}
}
}
}
let mut out = Vec::new();
chunk(&mut out, b"PROP", &prop);
Ok(out)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LocalChunk {
Property,
SoundData,
DstIndex,
EditedMasterInfo,
Comments,
}
impl LocalChunk {
pub const DEFAULT_ORDER: &'static [LocalChunk] = &[
LocalChunk::Property,
LocalChunk::Comments,
LocalChunk::EditedMasterInfo,
LocalChunk::SoundData,
LocalChunk::DstIndex,
];
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct CallerChunk {
id: [u8; 4],
data: Vec<u8>,
}
const RESERVED_IDS: [&[u8; 4]; 9] =
[b"FRM8", b"FVER", b"PROP", b"DSD ", b"DST ", b"DSTI", b"COMT", b"DIIN", b"MANF"];
impl CallerChunk {
pub fn new(id: [u8; 4], data: Vec<u8>) -> Result<CallerChunk, Error> {
if !id.iter().all(|b| (0x20..=0x7E).contains(b))
|| id.windows(2).any(|w| w[0] == b' ' && w[1] != b' ')
{
return Err(Error::InvalidArgument(
"a chunk ID is 4 bytes 0x20 to 0x7E, with no space before a non-space",
));
}
if RESERVED_IDS.contains(&&id) {
return Err(Error::InvalidArgument(
"a caller chunk may not have the ID of a chunk specification 8 defines",
));
}
Ok(CallerChunk { id, data })
}
pub fn id(&self) -> [u8; 4] {
self.id
}
pub fn data(&self) -> &[u8] {
&self.data
}
}
pub(super) enum Sound {
Dsd(DsdData, u64),
Dst(super::dsdiff_dst::DstData),
}
pub(super) fn assemble(
layout: &mut Layout,
toc: &Toc,
area: &Area,
options: &OutputOptions,
sound: Sound,
) -> Result<(), Error> {
let edited;
let options = if options.dsdiff_edited_master {
markers::check_edited_master(area, layout.first, layout.end)?;
if matches!(options.dsdiff_markers, Markers::Custom(_)) {
return Err(Error::InvalidArgument(
"an edited master has the program's markers, not custom ones",
));
}
if !options.dsdiff_loudspeaker_configuration {
return Err(Error::InvalidArgument("an edited master has LSCO"));
}
if !options.dsdiff_edited_master_id_written {
return Err(Error::InvalidArgument("an edited master has EMID"));
}
edited = OutputOptions {
dsdiff_absolute_start: Some(options.dsdiff_absolute_start.unwrap_or(0)),
dsdiff_edited_master_info: true,
dsdiff_artist_title: Some(options.dsdiff_artist_title.unwrap_or(true)),
source_track: SourceTrack::None,
..options.clone()
};
&edited
} else {
options
};
if let Some(r) = options.dsdiff_text_replacement {
markers::check_text(&[r])?;
}
let positions = u64::from(layout.end - layout.first);
let cmpr = match sound {
Sound::Dsd(..) => CMPR_DSD,
Sound::Dst(_) => CMPR_DST,
};
let prop = property(area, options, positions, cmpr)?;
let index = match &sound {
Sound::Dst(_) if options.dsdiff_dst_index => Some(12 * positions),
_ => None,
};
let diin = if options.dsdiff_edited_master_info {
let source = if options.dsdiff_edited_master {
None
} else {
layout.source.and_then(|n| area.track(u32::from(n)))
};
let list = match &options.dsdiff_markers {
Markers::FromToc => markers::from_toc(area, layout.first, layout.end, source, options),
Markers::Custom(list) => list.clone(),
};
let set = match &options.tags {
Tags::FromToc if options.dsdiff_artist_title == Some(true) => {
Some(TagSet::from_toc(toc, area, source, options))
}
Tags::Set(set) if options.dsdiff_artist_title == Some(true) => Some(set.clone()),
_ => None,
};
let first = |item| set.as_ref().and_then(|s| s.get(item).first().map(String::as_str));
let pick = |track: TagItem, album: TagItem| {
let track = || source.and_then(|_| first(track));
match options.dsdiff_artist_title_source {
ArtistTitleSource::Album => first(album),
ArtistTitleSource::Track => track(),
ArtistTitleSource::TrackThenAlbum => track().or_else(|| first(album)),
}
};
let artist = pick(TagItem::Performer, TagItem::AlbumArtist);
let title = pick(TagItem::TrackTitle, TagItem::Album);
markers::diin(layout, &list, artist, title, options)?
} else {
None
};
let comt = dsdiff_text::comt(layout.channels, options)?;
let written = |c: LocalChunk| match c {
LocalChunk::Property | LocalChunk::SoundData => true,
LocalChunk::Comments => comt.is_some(),
LocalChunk::EditedMasterInfo => diin.is_some(),
LocalChunk::DstIndex => index.is_some(),
};
let mut order: Vec<LocalChunk> = Vec::with_capacity(LocalChunk::DEFAULT_ORDER.len());
for &c in &options.dsdiff_local_order {
if order.contains(&c) {
return Err(Error::InvalidArgument("the local chunk order must name each chunk once"));
}
order.push(c);
}
if LocalChunk::DEFAULT_ORDER.iter().any(|&c| written(c) && !order.contains(&c)) {
return Err(Error::InvalidArgument("the local chunk order must name every chunk the file holds"));
}
order.retain(|&c| written(c));
let at = |c| order.iter().position(|&x| x == c);
if at(LocalChunk::Property) > at(LocalChunk::SoundData) {
return Err(Error::InvalidArgument("the property chunk must come before the sound data"));
}
let (sound_head, sound_d) = match &sound {
Sound::Dsd(_, d) => {
let mut h = b"DSD ".to_vec();
h.extend_from_slice(&d.to_be_bytes());
(h, *d)
}
Sound::Dst(dst) => (dst.head(), dst.data_size()),
};
let size_of = |c: LocalChunk| match c {
LocalChunk::Property => prop.len() as u64,
LocalChunk::Comments => comt.as_ref().map_or(0, |d| d.len() as u64),
LocalChunk::EditedMasterInfo => diin.as_ref().map_or(0, |d| d.len() as u64),
LocalChunk::SoundData => occupied(sound_d),
LocalChunk::DstIndex => index.map_or(0, occupied),
};
let callers: u64 = options.dsdiff_caller_chunks.iter().map(|c| occupied(c.data.len() as u64)).sum();
let frm8 = 4 + 16 + order.iter().map(|&c| size_of(c)).sum::<u64>() + callers;
let mut bytes = Vec::with_capacity(32 + prop.len());
chunk_head(&mut bytes, b"FRM8", frm8);
bytes.extend_from_slice(b"DSD ");
chunk(&mut bytes, b"FVER", &0x0105_0000u32.to_be_bytes());
let mut units = 32;
for &c in &order {
match c {
LocalChunk::SoundData => break,
c => units += size_of(c),
}
}
units += sound_head.len() as u64;
for &c in &order {
match c {
LocalChunk::Property => bytes.extend_from_slice(&prop),
LocalChunk::Comments => bytes.extend_from_slice(comt.as_deref().unwrap_or_default()),
LocalChunk::EditedMasterInfo => bytes.extend_from_slice(diin.as_deref().unwrap_or_default()),
LocalChunk::DstIndex => {
if let Sound::Dst(dst) = &sound {
let entries = dst.index(units, options.dsdiff_dst_index_offset);
chunk(&mut bytes, b"DSTI", &entries);
}
}
LocalChunk::SoundData => {
bytes.extend_from_slice(&sound_head);
let kind = if layout.regions.is_empty() { RegionKind::Header } else { RegionKind::Trailer };
layout.push(kind, bytes.len() as u64, Part::Bytes(std::mem::take(&mut bytes)));
let data = sound_d - (sound_head.len() as u64 - 12);
match &sound {
Sound::Dsd(d, _) => layout.push(RegionKind::SoundData, data, Part::Dsd(d.clone())),
Sound::Dst(d) => layout.push(RegionKind::SoundData, data, Part::Dst(d.clone())),
}
}
}
}
for c in &options.dsdiff_caller_chunks {
chunk(&mut bytes, &c.id, &c.data);
}
if !bytes.is_empty() {
layout.push(RegionKind::Trailer, bytes.len() as u64, Part::Bytes(bytes));
}
Ok(())
}
pub(super) fn build_dsd(
layout: &mut Layout,
toc: &Toc,
area: &Area,
options: &OutputOptions,
) -> Result<(), Error> {
let positions = u64::from(layout.end - layout.first);
let d = positions * u64::from(layout.channels) * FRAME_BYTES_PER_CHANNEL as u64;
assemble(layout, toc, area, options, Sound::Dsd(DsdData { channels: layout.channels }, d))
}
#[derive(Clone, Debug)]
pub(super) struct DsdData {
channels: u8,
}
impl DsdData {
fn frame(&self) -> u64 {
u64::from(self.channels) * FRAME_BYTES_PER_CHANNEL as u64
}
pub(super) fn positions(&self, range: Range<u64>) -> Range<u32> {
(range.start / self.frame()) as u32..((range.end - 1) / self.frame() + 1) as u32
}
#[inline(always)]
pub(super) fn fill(
&self,
offset: u64,
out: &mut [u8],
first: u32,
source: &mut Checked<'_>,
) -> Result<(), Error> {
let frame = self.frame();
let mut done = 0;
while done < out.len() {
let o = offset + done as u64;
let within = (o % frame) as usize;
let content = source.content(first + (o / frame) as u32)?;
let n = (content.len() - within).min(out.len() - done);
out[done..done + n].copy_from_slice(&content[within..within + n]);
done += n;
}
Ok(())
}
}