use crate::defaults::{MAX_TEMPO_MILLI, MIN_TEMPO_MILLI, PPQ, TEMPO, TEMPO_MILLI, VOLUME};
use crate::duty::DutyChannel;
use crate::envelope::{EnvChannel, Envelope};
use crate::notice::{JumpAt, NoticeMask, NoticeQueue, SeqNotice};
use crate::pitch::{Detune, DetuneSteps, PitchChannel, PitchFx, Vibrato, PACKED_STEP_LEN};
use crate::{Synth, WAVE_LEN};
mod header;
mod render;
mod state;
mod tables;
mod transport;
mod validate;
use header::*;
use state::*;
use tables::*;
use validate::*;
pub const VERSION: u8 = 1;
pub const MAX_ENVELOPES: usize = 255;
pub const MAX_VIBRATOS: usize = 255;
pub const MAX_DETUNES: usize = 255;
pub const MAX_ARPS: usize = 255;
pub const MAX_WAVES: usize = 255;
pub const MAX_DUTIES: usize = 255;
pub const VIBRATO_ENTRY_LEN: usize = 3;
pub const FLAG_LOOP: u8 = 1;
pub const FLAG_FRAME_50: u8 = 2;
pub const FLAG_MARKERS: u8 = 4;
pub const FLAG_EXTENSIONS: u8 = 8;
pub const MAX_EXTENSIONS: usize = 255;
pub const EXT_BLOCK_REQUIRED: u8 = 0x80;
pub const EXT_BLOCK_WAVES: u8 = EXT_BLOCK_REQUIRED | 1;
pub const EXT_BLOCK_DUTIES: u8 = EXT_BLOCK_REQUIRED | 2;
pub const MAX_MARKERS: usize = 255;
pub const MAX_TRACKS: usize = 26;
pub const MAX_REF_DEPTH: usize = 4;
pub const INITIAL_KEY: u8 = 60;
pub mod op {
pub const NOTE_REL: u8 = 0;
pub const NOTE_WAIT: u8 = 1;
pub const WAIT: u8 = 2;
pub const VOLUME: u8 = 3;
pub const OFF_WAIT: u8 = 4;
pub const TONE: u8 = 5;
pub const LEGATO_REL: u8 = 6;
pub const EXT: u8 = 7;
}
pub mod ext {
pub const NOTE_ABS: u8 = 0;
pub const LEGATO_ABS: u8 = 1;
pub const PARAM: u8 = 2;
pub const TEMPO: u8 = 3;
pub const WAIT_LONG: u8 = 4;
pub const REF: u8 = 5;
pub const LOOP: u8 = 6;
pub const CHANNEL: u8 = 7;
pub const ENVELOPE: u8 = 8;
pub const VIBRATO: u8 = 9;
pub const DETUNE: u8 = 10;
pub const PORTAMENTO: u8 = 11;
pub const ARP: u8 = 12;
pub const TEMPO_FINE: u8 = 13;
pub const WAVE: u8 = 14;
pub const DUTY: u8 = 15;
pub const ESCAPE: u8 = 31;
}
pub const fn ext_byte(e: u8) -> u8 {
(op::EXT << 5) | e
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecodeError {
Truncated,
Version(u8),
Tracks(u8),
Header,
BadOp { track: u8, at: u32 },
BadRef { track: u8, at: u32 },
BadLoop { track: u8 },
TooComplex,
}
impl crate::text::Localized for DecodeError {
fn text_key(&self) -> &'static str {
match self {
DecodeError::Truncated => "err-decode-truncated",
DecodeError::Version(_) => "err-decode-version",
DecodeError::Tracks(_) => "err-decode-tracks",
DecodeError::Header => "err-decode-header",
DecodeError::BadOp { .. } => "err-decode-bad-op",
DecodeError::BadRef { .. } => "err-decode-bad-ref",
DecodeError::BadLoop { .. } => "err-decode-bad-loop",
DecodeError::TooComplex => "err-decode-too-complex",
}
}
fn text_args(&self, f: &mut dyn FnMut(&'static str, crate::text::TextArg<'_>)) {
use crate::text::TextArg::Int;
match *self {
DecodeError::Version(v) => f("version", Int(v as i64)),
DecodeError::Tracks(n) => f("count", Int(n as i64)),
DecodeError::BadOp { track, at } | DecodeError::BadRef { track, at } => {
f("track", Int(track as i64));
f("at", Int(at as i64));
}
DecodeError::BadLoop { track } => f("track", Int(track as i64)),
_ => {}
}
}
fn catalogs(&self) -> &'static [crate::text::Catalog] {
crate::text::table::CATALOGS
}
}
impl core::fmt::Display for DecodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
crate::text::write_localized(f, self, crate::text::DEFAULT_LANG)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Header {
pub synth: u8,
pub tracks: u8,
pub unit: u32,
pub length: u32,
pub loop_at: Option<u32>,
pub version: u8,
pub ppq: u32,
pub envelopes: u8,
pub vibratos: u8,
pub detunes: u8,
pub arps: u8,
pub waves: u8,
pub duties: u8,
pub extensions: u8,
pub frame_hz: u8,
pub markers: u8,
pub meter: (u8, u8),
}
impl Header {
pub fn beat_ticks(&self) -> u64 {
(self.ppq as u64 * 4 / self.meter.1.max(1) as u64).max(1)
}
pub fn bar_ticks(&self) -> u64 {
self.beat_ticks() * self.meter.0.max(1) as u64
}
}
#[derive(Debug, Clone, Copy)]
struct Tables {
env: usize,
vib: usize,
det: usize,
arp: usize,
envelopes: u8,
vibratos: u8,
detunes: u8,
arps: u8,
wave: usize,
waves: u8,
duty: usize,
duties: u8,
markers: usize,
}
pub mod synth_id {
pub const BASIC: u8 = 0;
pub const AY_3_8912: u8 = 1;
pub const YM2149: u8 = 2;
pub const OTHER: u8 = 255;
}
pub fn read_varint(data: &[u8], pos: &mut usize) -> Option<u32> {
let mut v: u32 = 0;
for i in 0..5 {
let b = *data.get(*pos)?;
*pos += 1;
let part = (b & 0x7f) as u32;
if i == 4 && part > 0x0f {
return None;
}
v |= part << (7 * i);
if b & 0x80 == 0 {
return Some(v);
}
}
None
}
const SCALE_ONE: u64 = 1000;
pub const TEMPO_SCALE_MIN: u32 = 10;
pub const TEMPO_SCALE_MAX: u32 = 100_000;
pub const NOTICE_CAPACITY: usize = 16;
pub struct Sequencer<'a, const TRACKS: usize = 8> {
data: &'a [u8],
header: Header,
tables: Tables,
cursors: [Cursor; TRACKS],
sample_rate: u32,
tick: u64,
acc: u64,
tempo: u32,
started: bool,
finished: bool,
looping: bool,
loop_limit: Option<u32>,
loops_done: u32,
audible: u32,
volume: f32,
fingerprint: (u32, u32),
x: Extra,
}
fn fingerprint(data: &[u8]) -> (u32, u32) {
let mut h: u32 = 0x811c_9dc5;
for &b in data {
h ^= b as u32;
h = h.wrapping_mul(0x0100_0193);
}
(data.len() as u32, h)
}
impl<'a, const TRACKS: usize> Sequencer<'a, TRACKS> {
pub fn new(data: &'a [u8], sample_rate: u32) -> Result<Self, DecodeError> {
let mut ranges = [(0usize, 0usize); TRACKS];
let (header, tables) = read_header(data, &mut ranges)?;
let mut cursors = [Cursor::EMPTY; TRACKS];
let mut budget: u32 = 10_000_000;
for t in 0..header.tracks as usize {
let (start, end) = ranges[t];
let found = validate_track(data, t as u8, (start, end), &tables, &mut budget)?;
if header.loop_at.is_some() && found.is_none() {
return Err(DecodeError::BadLoop { track: t as u8 });
}
let c = &mut cursors[t];
c.start = start;
c.end = end;
c.env = EnvChannel::with_frame_hz(header.frame_hz);
c.duty = DutyChannel::with_frame_hz(header.frame_hz);
c.pitch = PitchChannel::with_frame_hz(header.frame_hz);
if let Some((units, pos, block)) = found {
if Some(units) != header.loop_at.map(|l| l as u64) {
return Err(DecodeError::BadLoop { track: t as u8 });
}
c.loop_pos = Some(pos);
c.loop_block = block;
}
c.rewind();
}
let mut s = Sequencer {
data,
header,
tables,
cursors,
sample_rate: sample_rate.max(1),
tick: 0,
acc: 0,
tempo: TEMPO_MILLI,
started: false,
finished: false,
looping: false,
loop_limit: None,
loops_done: 0,
audible: u32::MAX,
volume: 1.0,
fingerprint: fingerprint(data),
x: Extra::NEW,
};
s.finished = s.length_ticks() == 0;
s.reset_points(0);
Ok(s)
}
pub fn unbind(self) -> Sequencer<'static, TRACKS> {
Sequencer {
data: &[],
header: self.header,
tables: self.tables,
cursors: self.cursors,
sample_rate: self.sample_rate,
tick: self.tick,
acc: self.acc,
tempo: self.tempo,
started: self.started,
finished: self.finished,
looping: self.looping,
loop_limit: self.loop_limit,
loops_done: self.loops_done,
audible: self.audible,
volume: self.volume,
fingerprint: self.fingerprint,
x: self.x,
}
}
pub fn bind<'b>(self, data: &'b [u8]) -> Option<Sequencer<'b, TRACKS>> {
if fingerprint(data) != self.fingerprint {
return None;
}
Some(Sequencer {
data,
header: self.header,
tables: self.tables,
cursors: self.cursors,
sample_rate: self.sample_rate,
tick: self.tick,
acc: self.acc,
tempo: self.tempo,
started: self.started,
finished: self.finished,
looping: self.looping,
loop_limit: self.loop_limit,
loops_done: self.loops_done,
audible: self.audible,
volume: self.volume,
fingerprint: self.fingerprint,
x: self.x,
})
}
pub fn header(&self) -> &Header {
&self.header
}
fn length_ticks(&self) -> u64 {
self.header.length as u64 * self.header.unit as u64
}
pub fn position(&self) -> u64 {
self.tick
}
pub fn is_finished(&self) -> bool {
self.finished
}
pub fn loops_done(&self) -> u32 {
self.loops_done
}
pub fn set_looping(&mut self, on: bool) {
self.looping = on;
}
pub fn set_loop_limit(&mut self, n: Option<u32>) {
self.loop_limit = n;
}
pub fn set_audible(&mut self, mask: u32) {
self.audible = mask;
}
pub fn set_volume(&mut self, v: f32) {
self.volume = if v.is_finite() && v > 0.0 { v } else { 0.0 };
}
pub fn audible(&self) -> u32 {
self.audible
}
pub fn volume(&self) -> f32 {
self.volume
}
}