//! One operator: a phase counter, an envelope, and the log-sine arithmetic. //! //! Every rule names its section of `docs/spec.md`; `docs/provenance-audit.md` //! gives the chain behind each. PROVISIONAL marks a default no document or //! measurement settles; "emulator tier" means the default is ymfm's (BSD-3-Clause), //! named because nothing better is in an allowed source. CHOICE marks what no source //! speaks to. //! //! Transcribed from ym2612-python's `operator.py`. Where Rust forced a difference: //! //! - Python's unbounded integers are `i32` here; no value the operator holds or works out comes //! near its range (the largest is a 20-bit phase plus a multiplied 17-bit increment). //! Python's `&` and `>>` on negative integers are two's complement and arithmetic, as `i32`'s //! are, so the masks and shifts give the same results. //! - `inverted()` returns a `bool`, as Python's does; Python's truthiness tests are `!= 0`. use crate::tables::{DETUNE, ENVELOPE_INCREMENTS, ENVELOPE_SHIFT, EXPONENT, LOG_SINE}; /// Envelope phases (spec 7.1.1). pub const ATTACK: i32 = 0; pub const DECAY: i32 = 1; pub const SUSTAIN: i32 = 2; pub const RELEASE: i32 = 3; /// The envelope's quietest value: 10 bits (spec 7.1.1, measured). pub const MAX_ATTENUATION: i32 = 0x3FF; /// Sustain level 15 as a 10-bit attenuation (spec 7.4.7, contradiction C9, decision /// T6). PROVISIONAL: $3E0 is the manual's "93 dB"; Nemesis measured $3FF (p7967). pub const SUSTAIN_LEVEL_15: i32 = 0x3E0; /// SSG-EG works on the attenuation's top bit (spec 7.6, measured: p7967, p8025). pub const SSG_THRESHOLD: i32 = 0x200; /// Bits of the SSG-EG register (spec 3.2: documented). pub const SSG_ENABLE: i32 = 8; pub const SSG_ATTACK: i32 = 4; pub const SSG_ALTERNATE: i32 = 2; pub const SSG_HOLD: i32 = 1; /// One of a channel's four operators. All state is plain integers. /// /// Registers (spec 3.2): `detune` (3 bits, bit 2 the sign), `multiple`, /// `total_level`, `key_scale`, `attack_rate`, `tremolo` (the enable bit), /// `decay_rate`, `sustain_rate`, `sustain_level`, `release_rate`, `ssg`. /// /// Frequency, set by the chip from the channel's registers or, for channel 3 in /// its special mode, from the operator's own (spec 10.2): `f_number`, `block`, /// `key_code`. /// /// State: `phase` (the 20-bit counter, spec 5.1), `envelope_phase`, /// `attenuation` (10 bits, 0 loudest), `ssg_flag` (the SSG-EG inversion flag, /// spec 7.6.2), `key_request` (this operator's bit of the last $28 write), /// `key_state` (the key as last acted on). #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Operator { pub attack_rate: i32, pub attenuation: i32, pub block: i32, pub decay_rate: i32, pub detune: i32, pub envelope_phase: i32, pub f_number: i32, pub key_code: i32, pub key_request: i32, pub key_scale: i32, pub key_state: i32, pub multiple: i32, pub phase: i32, pub release_rate: i32, pub ssg: i32, pub ssg_flag: i32, pub sustain_level: i32, pub sustain_rate: i32, pub total_level: i32, pub tremolo: i32, } impl Default for Operator { fn default() -> Self { Self::new() } } impl Operator { pub fn new() -> Self { Operator { detune: 0, multiple: 0, total_level: 0, key_scale: 0, attack_rate: 0, tremolo: 0, decay_rate: 0, sustain_rate: 0, sustain_level: 0, release_rate: 0, ssg: 0, f_number: 0, block: 0, key_code: 0, phase: 0, // Spec 7.5, decision T14 (PROVISIONAL, emulator tier): release at the // quietest level, key off. envelope_phase: RELEASE, attenuation: MAX_ATTENUATION, ssg_flag: 0, key_request: 0, key_state: 0, } } // -- phase generator (spec 5) ------------------------------------------------ /// The 20-bit amount added to the phase each sample (spec 5.2 to 5.8). /// /// `f_number` is the 11-bit F-number after vibrato. All measured by Nemesis /// (p6177), with the worked values of rung 1. pub fn phase_increment(&self, f_number: i32) -> i32 { // Spec 5.3: block 0 shifts right once, block 1 not at all, 2 to 7 left. let mut increment = (f_number << self.block) >> 1; // Spec 5.6, 5.7: detune by key code, kept to 17 bits, so that a negative // detune on a small increment wraps to a very large one. let magnitude = self.detune & 3; if magnitude != 0 { let amount = DETUNE[magnitude as usize][self.key_code as usize]; if self.detune & 4 != 0 { increment = (increment - amount) & 0xFFFFFF; } else { increment = (increment + amount) & 0xFFFFFF; } } // Spec 5.8: the multiple; 0 halves. Kept to 20 bits. if self.multiple != 0 { return (increment * self.multiple) & 0xFFFFF; } increment >> 1 } // -- envelope generator (spec 7) --------------------------------------------- /// Spec 7.2.1, 7.2.2 (documented, Yamaha): 2R + Rks; 0 if R is 0; at most 63. /// /// Rks is the key code shifted right by 3, 2, 1, 0 for key scale 0 to 3. pub fn rate(&self, register: i32) -> i32 { if register == 0 { return 0; } let rate = 2 * register + (self.key_code >> (3 - self.key_scale)); rate.min(63) } /// Whether SSG-EG inverts the output now (spec 7.6.2: measured, p8025). pub fn inverted(&self) -> bool { let ssg = self.ssg; ssg & SSG_ENABLE != 0 && self.envelope_phase != RELEASE && ((ssg & SSG_ATTACK) != 0) != (self.ssg_flag != 0) } /// Act on the key if it changed (spec 7.4.3, 7.4.8, 7.4.9; every sample). pub fn set_key(&mut self, key: i32) { if key == self.key_state { return; // spec 7.4.8: a repeated key-on or key-off changes nothing } self.key_state = key; if key != 0 { // Spec 7.4.3: attack from where the envelope stands; the level is not // reset (p5724, p7999). Spec 5.9: the phase counter is cleared (p7967). // Spec 7.6.2: the inversion flag is cleared (p8025). self.envelope_phase = ATTACK; self.phase = 0; self.ssg_flag = 0; // Spec 7.4.4 (measured, p7967): rates 62 and 63 go to 0 at once. if self.rate(self.attack_rate) >= 62 { self.attenuation = 0; } } else { // Spec 7.6.5, PROVISIONAL, emulator tier (unknown U23): release goes // on from the level that was being heard. if self.inverted() { self.attenuation = (SSG_THRESHOLD - self.attenuation) & 0x3FF; } self.envelope_phase = RELEASE; } } /// The SSG-EG work done every sample, before any envelope update (spec 7.6.3). /// /// Measured by Nemesis and stated in prose (p7967, p8025, p8032, p8037), except /// the held-silent case, which follows from the manual's eight shapes. pub fn ssg_step(&mut self) { let ssg = self.ssg; if ssg & SSG_ENABLE == 0 || self.attenuation < SSG_THRESHOLD { return; } if ssg & SSG_ALTERNATE != 0 && (ssg & SSG_HOLD == 0 || self.ssg_flag == 0) { self.ssg_flag ^= 1; } if ssg & (SSG_ALTERNATE | SSG_HOLD) == 0 { self.phase = 0; } let phase = self.envelope_phase; if phase == ATTACK { return; } if phase != RELEASE && ssg & SSG_HOLD == 0 { // The pattern repeats: attack again, at once if the rate is 62 or 63. self.envelope_phase = ATTACK; if self.rate(self.attack_rate) >= 62 { self.attenuation = 0; } } else if phase == RELEASE || !self.inverted() { // Release reaching $200 goes silent (p8025, p8032). A held pattern that // ends not inverted goes silent (shapes 001 and 111: derived). self.attenuation = MAX_ATTENUATION; } } /// One envelope update, every third sample (spec 7.3, 7.4). pub fn envelope_step(&mut self, counter: i32) { let mut phase = self.envelope_phase; let mut attenuation = self.attenuation; // Spec 7.4.6 (measured, p7967): attack ends at 0; decay ends when the level // reaches or passes the sustain level, without being cut back to it, and // the change is one-way. CHOICE of order: both are looked at before the // step, as ymfm does, so "the sustain phase begins on the next cycle". if phase == ATTACK && attenuation == 0 { self.envelope_phase = DECAY; phase = DECAY; } if phase == DECAY { let level = self.sustain_level; if attenuation >= (if level == 15 { SUSTAIN_LEVEL_15 } else { level << 5 }) { self.envelope_phase = SUSTAIN; phase = SUSTAIN; } } // Spec 7.2.3 (measured, p7967): the rate is worked out at every update. let rate = if phase == ATTACK { self.rate(self.attack_rate) } else if phase == DECAY { self.rate(self.decay_rate) } else if phase == SUSTAIN { self.rate(self.sustain_rate) } else { // Spec 7.2.1: the 4-bit release rate doubled plus one, never 0 (p5724). self.rate(2 * self.release_rate + 1) }; // Spec 7.3.2: the shared counter's low bits gate the update and the three // bits above them choose one of eight increments. let shift = ENVELOPE_SHIFT[rate as usize]; if counter & ((1 << shift) - 1) != 0 { return; } let increment = ENVELOPE_INCREMENTS[rate as usize][((counter >> shift) & 7) as usize]; if phase == ATTACK { // Spec 7.4.5 (measured, p7967): at 62 or 63 a running attack stalls. // Spec 7.4.2, PROVISIONAL, emulator tier (unknown U22): the curve. if rate < 62 { self.attenuation = attenuation + ((!attenuation * increment) >> 4); } } else if self.ssg & SSG_ENABLE != 0 { // Spec 7.6.1: four times the step (measured), only below $200 (derived). if attenuation < SSG_THRESHOLD { attenuation += 4 * increment; self.attenuation = if attenuation < 0x400 { attenuation } else { MAX_ATTENUATION }; } } else { // Spec 7.4.1 (measured): add, limited. attenuation += increment; self.attenuation = if attenuation < 0x400 { attenuation } else { MAX_ATTENUATION }; } } /// The attenuation handed to the operator unit this sample (spec 7.1.2). /// /// Measured (p5716, p7967): SSG-EG's inversion on a copy first, then the total /// level, then tremolo, limited to 10 bits. pub fn level(&self, tremolo: i32) -> i32 { let mut level = self.attenuation; if self.ssg & SSG_ENABLE != 0 && self.inverted() { level = (SSG_THRESHOLD - level) & 0x3FF; // spec 7.6.2: $001 -> $1FF } level += self.total_level << 3; if self.tremolo != 0 { level += tremolo; } if level < 0x400 { level } else { MAX_ATTENUATION } } // -- one sample (spec 5, 6) -------------------------------------------------- /// Advance the phase and return the signed 14-bit output (spec 6). /// /// `modulation` is the 10-bit phase offset from other operators or from /// feedback (spec 9.3, 9.4). The output is worked from the advanced phase: /// with the counter frozen at 0 by test bit $21:3 "the phase equals the /// increment" (spec 17). pub fn clock(&mut self, increment: i32, modulation: i32, tremolo: i32) -> i32 { self.phase = (self.phase + increment) & 0xFFFFF; let phase = self.phase; // Spec 6.2: ten bits; bit 8 mirrors the quarter wave, bit 9 negates. let angle = (phase >> 10) + modulation; let mut index = angle & 0xFF; if angle & 0x100 != 0 { index ^= 0xFF; } // Spec 6.4: the envelope's 4.6 attenuation becomes 4.8 and is added. let total = LOG_SINE[index as usize] + (self.level(tremolo) << 2); // Spec 6.5: the fraction indexes the exponent ROM; the whole part shifts. let value = (EXPONENT[(total & 0xFF) as usize] << 2) >> (total >> 8); if angle & 0x200 != 0 { -value } else { value } } }