1use crate::defaults::{MAX_TEMPO_MILLI, MIN_TEMPO_MILLI, PPQ, TEMPO, TEMPO_MILLI, VOLUME};
28use crate::duty::DutyChannel;
29use crate::envelope::{EnvChannel, Envelope};
30use crate::notice::{JumpAt, NoticeMask, NoticeQueue, SeqNotice};
31use crate::pitch::{Detune, DetuneSteps, PitchChannel, PitchFx, Vibrato, PACKED_STEP_LEN};
32use crate::{Synth, WAVE_LEN};
33
34mod header;
35mod render;
36mod state;
37mod tables;
38mod transport;
39mod validate;
40
41use header::*;
42use state::*;
43use tables::*;
44use validate::*;
45
46pub const VERSION: u8 = 1;
51
52pub const MAX_ENVELOPES: usize = 255;
54
55pub const MAX_VIBRATOS: usize = 255;
57
58pub const MAX_DETUNES: usize = 255;
60
61pub const MAX_ARPS: usize = 255;
63
64pub const MAX_WAVES: usize = 255;
66
67pub const MAX_DUTIES: usize = 255;
69
70pub const VIBRATO_ENTRY_LEN: usize = 3;
72
73pub const FLAG_LOOP: u8 = 1;
75
76pub const FLAG_FRAME_50: u8 = 2;
78
79pub const FLAG_MARKERS: u8 = 4;
81
82pub const FLAG_EXTENSIONS: u8 = 8;
88
89pub const MAX_EXTENSIONS: usize = 255;
91
92pub const EXT_BLOCK_REQUIRED: u8 = 0x80;
94
95pub const EXT_BLOCK_WAVES: u8 = EXT_BLOCK_REQUIRED | 1;
98
99pub const EXT_BLOCK_DUTIES: u8 = EXT_BLOCK_REQUIRED | 2;
103
104pub const MAX_MARKERS: usize = 255;
106
107pub const MAX_TRACKS: usize = 26;
109
110pub const MAX_REF_DEPTH: usize = 4;
112
113pub const INITIAL_KEY: u8 = 60;
115
116pub mod op {
118 pub const NOTE_REL: u8 = 0;
120 pub const NOTE_WAIT: u8 = 1;
122 pub const WAIT: u8 = 2;
124 pub const VOLUME: u8 = 3;
126 pub const OFF_WAIT: u8 = 4;
128 pub const TONE: u8 = 5;
130 pub const LEGATO_REL: u8 = 6;
132 pub const EXT: u8 = 7;
134}
135
136pub mod ext {
138 pub const NOTE_ABS: u8 = 0;
140 pub const LEGATO_ABS: u8 = 1;
142 pub const PARAM: u8 = 2;
144 pub const TEMPO: u8 = 3;
146 pub const WAIT_LONG: u8 = 4;
148 pub const REF: u8 = 5;
150 pub const LOOP: u8 = 6;
152 pub const CHANNEL: u8 = 7;
154 pub const ENVELOPE: u8 = 8;
156 pub const VIBRATO: u8 = 9;
158 pub const DETUNE: u8 = 10;
160 pub const PORTAMENTO: u8 = 11;
163 pub const ARP: u8 = 12;
165 pub const TEMPO_FINE: u8 = 13;
167 pub const WAVE: u8 = 14;
170 pub const DUTY: u8 = 15;
174 pub const ESCAPE: u8 = 31;
177}
178
179pub const fn ext_byte(e: u8) -> u8 {
181 (op::EXT << 5) | e
182}
183
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum DecodeError {
187 Truncated,
189 Version(u8),
191 Tracks(u8),
193 Header,
195 BadOp { track: u8, at: u32 },
197 BadRef { track: u8, at: u32 },
199 BadLoop { track: u8 },
201 TooComplex,
203}
204
205impl crate::text::Localized for DecodeError {
206 fn text_key(&self) -> &'static str {
207 match self {
208 DecodeError::Truncated => "err-decode-truncated",
209 DecodeError::Version(_) => "err-decode-version",
210 DecodeError::Tracks(_) => "err-decode-tracks",
211 DecodeError::Header => "err-decode-header",
212 DecodeError::BadOp { .. } => "err-decode-bad-op",
213 DecodeError::BadRef { .. } => "err-decode-bad-ref",
214 DecodeError::BadLoop { .. } => "err-decode-bad-loop",
215 DecodeError::TooComplex => "err-decode-too-complex",
216 }
217 }
218
219 fn text_args(&self, f: &mut dyn FnMut(&'static str, crate::text::TextArg<'_>)) {
220 use crate::text::TextArg::Int;
221 match *self {
222 DecodeError::Version(v) => f("version", Int(v as i64)),
223 DecodeError::Tracks(n) => f("count", Int(n as i64)),
224 DecodeError::BadOp { track, at } | DecodeError::BadRef { track, at } => {
225 f("track", Int(track as i64));
226 f("at", Int(at as i64));
227 }
228 DecodeError::BadLoop { track } => f("track", Int(track as i64)),
229 _ => {}
230 }
231 }
232
233 fn catalogs(&self) -> &'static [crate::text::Catalog] {
234 crate::text::table::CATALOGS
235 }
236}
237
238impl core::fmt::Display for DecodeError {
239 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
240 crate::text::write_localized(f, self, crate::text::DEFAULT_LANG)
241 }
242}
243
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub struct Header {
247 pub synth: u8,
249 pub tracks: u8,
250 pub unit: u32,
252 pub length: u32,
254 pub loop_at: Option<u32>,
256 pub version: u8,
258 pub ppq: u32,
260 pub envelopes: u8,
262 pub vibratos: u8,
264 pub detunes: u8,
266 pub arps: u8,
268 pub waves: u8,
270 pub duties: u8,
272 pub extensions: u8,
274 pub frame_hz: u8,
276 pub markers: u8,
278 pub meter: (u8, u8),
280}
281
282impl Header {
283 pub fn beat_ticks(&self) -> u64 {
285 (self.ppq as u64 * 4 / self.meter.1.max(1) as u64).max(1)
286 }
287
288 pub fn bar_ticks(&self) -> u64 {
290 self.beat_ticks() * self.meter.0.max(1) as u64
291 }
292}
293
294#[derive(Debug, Clone, Copy)]
296struct Tables {
297 env: usize,
298 vib: usize,
299 det: usize,
300 arp: usize,
301 envelopes: u8,
302 vibratos: u8,
303 detunes: u8,
304 arps: u8,
305 wave: usize,
307 waves: u8,
308 duty: usize,
310 duties: u8,
311 markers: usize,
313}
314
315pub mod synth_id {
317 pub const BASIC: u8 = 0;
318 pub const AY_3_8912: u8 = 1;
319 pub const YM2149: u8 = 2;
320 pub const OTHER: u8 = 255;
321}
322
323pub fn read_varint(data: &[u8], pos: &mut usize) -> Option<u32> {
325 let mut v: u32 = 0;
326 for i in 0..5 {
327 let b = *data.get(*pos)?;
328 *pos += 1;
329 let part = (b & 0x7f) as u32;
330 if i == 4 && part > 0x0f {
331 return None;
332 }
333 v |= part << (7 * i);
334 if b & 0x80 == 0 {
335 return Some(v);
336 }
337 }
338 None
339}
340
341const SCALE_ONE: u64 = 1000;
343
344pub const TEMPO_SCALE_MIN: u32 = 10;
346
347pub const TEMPO_SCALE_MAX: u32 = 100_000;
348
349pub const NOTICE_CAPACITY: usize = 16;
351
352pub struct Sequencer<'a, const TRACKS: usize = 8> {
355 data: &'a [u8],
356 header: Header,
357 tables: Tables,
359 cursors: [Cursor; TRACKS],
360 sample_rate: u32,
361 tick: u64,
362 acc: u64,
363 tempo: u32,
365 started: bool,
366 finished: bool,
367 looping: bool,
368 loop_limit: Option<u32>,
369 loops_done: u32,
370 audible: u32,
371 volume: f32,
372 fingerprint: (u32, u32),
374 x: Extra,
375}
376
377fn fingerprint(data: &[u8]) -> (u32, u32) {
379 let mut h: u32 = 0x811c_9dc5;
380 for &b in data {
381 h ^= b as u32;
382 h = h.wrapping_mul(0x0100_0193);
383 }
384 (data.len() as u32, h)
385}
386
387impl<'a, const TRACKS: usize> Sequencer<'a, TRACKS> {
388 pub fn new(data: &'a [u8], sample_rate: u32) -> Result<Self, DecodeError> {
390 let mut ranges = [(0usize, 0usize); TRACKS];
391 let (header, tables) = read_header(data, &mut ranges)?;
392 let mut cursors = [Cursor::EMPTY; TRACKS];
393 let mut budget: u32 = 10_000_000;
394 for t in 0..header.tracks as usize {
395 let (start, end) = ranges[t];
396 let found = validate_track(data, t as u8, (start, end), &tables, &mut budget)?;
397 if header.loop_at.is_some() && found.is_none() {
398 return Err(DecodeError::BadLoop { track: t as u8 });
399 }
400 let c = &mut cursors[t];
401 c.start = start;
402 c.end = end;
403 c.env = EnvChannel::with_frame_hz(header.frame_hz);
404 c.duty = DutyChannel::with_frame_hz(header.frame_hz);
405 c.pitch = PitchChannel::with_frame_hz(header.frame_hz);
406 if let Some((units, pos, block)) = found {
407 if Some(units) != header.loop_at.map(|l| l as u64) {
408 return Err(DecodeError::BadLoop { track: t as u8 });
409 }
410 c.loop_pos = Some(pos);
411 c.loop_block = block;
412 }
413 c.rewind();
414 }
415 let mut s = Sequencer {
416 data,
417 header,
418 tables,
419 cursors,
420 sample_rate: sample_rate.max(1),
421 tick: 0,
422 acc: 0,
423 tempo: TEMPO_MILLI,
424 started: false,
425 finished: false,
426 looping: false,
427 loop_limit: None,
428 loops_done: 0,
429 audible: u32::MAX,
430 volume: 1.0,
431 fingerprint: fingerprint(data),
432 x: Extra::NEW,
433 };
434 s.finished = s.length_ticks() == 0;
435 s.reset_points(0);
436 Ok(s)
437 }
438
439 pub fn unbind(self) -> Sequencer<'static, TRACKS> {
445 Sequencer {
446 data: &[],
447 header: self.header,
448 tables: self.tables,
449 cursors: self.cursors,
450 sample_rate: self.sample_rate,
451 tick: self.tick,
452 acc: self.acc,
453 tempo: self.tempo,
454 started: self.started,
455 finished: self.finished,
456 looping: self.looping,
457 loop_limit: self.loop_limit,
458 loops_done: self.loops_done,
459 audible: self.audible,
460 volume: self.volume,
461 fingerprint: self.fingerprint,
462 x: self.x,
463 }
464 }
465
466 pub fn bind<'b>(self, data: &'b [u8]) -> Option<Sequencer<'b, TRACKS>> {
471 if fingerprint(data) != self.fingerprint {
472 return None;
473 }
474 Some(Sequencer {
475 data,
476 header: self.header,
477 tables: self.tables,
478 cursors: self.cursors,
479 sample_rate: self.sample_rate,
480 tick: self.tick,
481 acc: self.acc,
482 tempo: self.tempo,
483 started: self.started,
484 finished: self.finished,
485 looping: self.looping,
486 loop_limit: self.loop_limit,
487 loops_done: self.loops_done,
488 audible: self.audible,
489 volume: self.volume,
490 fingerprint: self.fingerprint,
491 x: self.x,
492 })
493 }
494
495 pub fn header(&self) -> &Header {
496 &self.header
497 }
498
499 fn length_ticks(&self) -> u64 {
500 self.header.length as u64 * self.header.unit as u64
501 }
502
503 pub fn position(&self) -> u64 {
505 self.tick
506 }
507
508 pub fn is_finished(&self) -> bool {
509 self.finished
510 }
511
512 pub fn loops_done(&self) -> u32 {
513 self.loops_done
514 }
515
516 pub fn set_looping(&mut self, on: bool) {
518 self.looping = on;
519 }
520
521 pub fn set_loop_limit(&mut self, n: Option<u32>) {
523 self.loop_limit = n;
524 }
525
526 pub fn set_audible(&mut self, mask: u32) {
528 self.audible = mask;
529 }
530
531 pub fn set_volume(&mut self, v: f32) {
533 self.volume = if v.is_finite() && v > 0.0 { v } else { 0.0 };
534 }
535
536 pub fn audible(&self) -> u32 {
538 self.audible
539 }
540
541 pub fn volume(&self) -> f32 {
543 self.volume
544 }
545}