use std::fmt;
use std::sync::Arc;
#[derive(Clone, PartialEq)]
pub struct DrumSample {
pub(crate) data: Arc<[f32]>,
pub(crate) rate: u32,
pub(crate) root_key: Option<u8>,
}
impl fmt::Debug for DrumSample {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DrumSample")
.field("frames", &self.data.len())
.field("rate", &self.rate)
.field("root_key", &self.root_key)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SampleError {
NotWav,
Unsupported {
format: u16,
bits: u16,
},
NoChannels,
Empty,
TooLong,
BadRate,
NotDrum(u8),
BadSlot(u8),
}
impl crate::text::Localized for SampleError {
fn text_key(&self) -> &'static str {
match self {
SampleError::NotWav => "err-sample-not-wav",
SampleError::Unsupported { .. } => "err-sample-unsupported",
SampleError::NoChannels => "err-sample-no-channels",
SampleError::Empty => "err-sample-empty",
SampleError::TooLong => "err-sample-too-long",
SampleError::BadRate => "err-sample-bad-rate",
SampleError::NotDrum(_) => "err-sample-not-drum",
SampleError::BadSlot(_) => "err-sample-bad-slot",
}
}
fn text_args(&self, f: &mut dyn FnMut(&'static str, crate::text::TextArg<'_>)) {
use crate::text::TextArg::Int;
match self {
SampleError::Unsupported { format, bits } => {
f("format", Int(*format as i64));
f("bits", Int(*bits as i64));
}
SampleError::TooLong => f("max", Int(MAX_SAMPLE_SECS as i64)),
SampleError::NotDrum(t) => f("tone", Int(*t as i64)),
SampleError::BadSlot(s) => f("slot", Int(*s as i64)),
_ => {}
}
}
fn catalogs(&self) -> &'static [crate::text::Catalog] {
crate::synth::va::text_table::CATALOGS
}
}
impl core::fmt::Display for SampleError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
crate::text::write_localized(f, self, crate::text::DEFAULT_LANG)
}
}
impl std::error::Error for SampleError {}
pub(crate) fn check_wav(
path: &str,
bytes: &[u8],
) -> Result<(), crate::compiler::diagnostic::Message> {
use crate::msg;
DrumSample::from_wav(bytes)
.map(|_| ())
.map_err(|e| match e {
SampleError::NotWav => msg!("E0604-not-wav", path = path),
SampleError::Unsupported { format, bits } => {
msg!(
"E0604-unsupported",
path = path,
format = format,
bits = bits
)
}
SampleError::NoChannels => msg!("E0604-no-channels", path = path),
SampleError::Empty => msg!("E0604-empty", path = path),
SampleError::TooLong => msg!("E0604-too-long", path = path, max = MAX_SAMPLE_SECS),
SampleError::BadRate => msg!("E0604-bad-rate", path = path),
SampleError::NotDrum(_) | SampleError::BadSlot(_) => msg!("E0604-not-wav", path = path),
})
}
pub const MAX_SAMPLE_SECS: u32 = 10;
impl DrumSample {
pub fn from_mono(samples: &[f32], sample_rate: u32) -> Result<Self, SampleError> {
if sample_rate == 0 {
return Err(SampleError::BadRate);
}
if samples.is_empty() {
return Err(SampleError::Empty);
}
if samples.len() as u64 > sample_rate as u64 * MAX_SAMPLE_SECS as u64 {
return Err(SampleError::TooLong);
}
let data: Arc<[f32]> = samples
.iter()
.map(|v| {
if v.is_finite() {
v.clamp(-1.0, 1.0)
} else {
0.0
}
})
.collect();
Ok(DrumSample {
data,
rate: sample_rate,
root_key: None,
})
}
pub fn from_wav(bytes: &[u8]) -> Result<Self, SampleError> {
let (samples, rate) = decode_wav(bytes)?;
DrumSample::from_mono(&samples, rate)
}
pub fn with_root_key(mut self, key: u8) -> Self {
self.root_key = Some(key.min(127));
self
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
pub fn sample_rate(&self) -> u32 {
self.rate
}
pub fn secs(&self) -> f32 {
self.data.len() as f32 / self.rate as f32
}
}
fn u16le(b: &[u8], i: usize) -> Option<u16> {
Some(u16::from_le_bytes(b.get(i..i + 2)?.try_into().ok()?))
}
fn u32le(b: &[u8], i: usize) -> Option<u32> {
Some(u32::from_le_bytes(b.get(i..i + 4)?.try_into().ok()?))
}
fn decode_wav(b: &[u8]) -> Result<(Vec<f32>, u32), SampleError> {
if b.len() < 12 || &b[0..4] != b"RIFF" || &b[8..12] != b"WAVE" {
return Err(SampleError::NotWav);
}
let mut fmt: Option<(u16, u16, u32, u16)> = None;
let mut data: Option<&[u8]> = None;
let mut i = 12;
while i + 8 <= b.len() {
let id = &b[i..i + 4];
let size = u32le(b, i + 4).ok_or(SampleError::NotWav)? as usize;
let body = b.get(i + 8..(i + 8).saturating_add(size).min(b.len()));
let body = body.ok_or(SampleError::NotWav)?;
match id {
b"fmt " => {
let mut format = u16le(body, 0).ok_or(SampleError::NotWav)?;
let channels = u16le(body, 2).ok_or(SampleError::NotWav)?;
let rate = u32le(body, 4).ok_or(SampleError::NotWav)?;
let bits = u16le(body, 14).ok_or(SampleError::NotWav)?;
if format == 0xFFFE {
format = u16le(body, 24).ok_or(SampleError::NotWav)?;
}
fmt = Some((format, channels, rate, bits));
}
b"data" => data = Some(body),
_ => {}
}
i = i + 8 + size + (size & 1);
}
let (format, channels, rate, bits) = fmt.ok_or(SampleError::NotWav)?;
let data = data.ok_or(SampleError::NotWav)?;
if channels == 0 {
return Err(SampleError::NoChannels);
}
if rate == 0 {
return Err(SampleError::BadRate);
}
let read: fn(&[u8]) -> f32 = match (format, bits) {
(1, 8) => |s| (s[0] as f32 - 128.0) / 128.0,
(1, 16) => |s| i16::from_le_bytes([s[0], s[1]]) as f32 / 32768.0,
(1, 24) => |s| (i32::from_le_bytes([0, s[0], s[1], s[2]]) >> 8) as f32 / 8_388_608.0,
(1, 32) => |s| i32::from_le_bytes([s[0], s[1], s[2], s[3]]) as f32 / 2_147_483_648.0,
(3, 32) => |s| f32::from_le_bytes([s[0], s[1], s[2], s[3]]),
_ => return Err(SampleError::Unsupported { format, bits }),
};
let width = bits as usize / 8;
let frame = width * channels as usize;
if data.len() / frame > rate as usize * MAX_SAMPLE_SECS as usize {
return Err(SampleError::TooLong);
}
let out: Vec<f32> = data
.chunks_exact(frame)
.map(|f| {
let sum: f32 = f.chunks_exact(width).map(read).sum();
sum / channels as f32
})
.collect();
if out.is_empty() {
return Err(SampleError::Empty);
}
Ok((out, rate))
}