#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dx7Op {
pub rates: [u8; 4],
pub levels: [u8; 4],
pub output_level: u8,
pub fixed: bool,
pub coarse: u8,
pub fine: u8,
pub detune: u8,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dx7Voice {
pub name: String,
pub algorithm: u8,
pub feedback: u8,
pub transpose: u8,
pub ops: [Dx7Op; 6],
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Dx7Error {
Unrecognized,
BadValue {
voice: usize,
},
}
impl crate::text::Localized for Dx7Error {
fn text_key(&self) -> &'static str {
match self {
Dx7Error::Unrecognized => "err-dx7-unrecognized",
Dx7Error::BadValue { .. } => "err-dx7-bad-value",
}
}
fn text_args(&self, f: &mut dyn FnMut(&'static str, crate::text::TextArg<'_>)) {
if let Dx7Error::BadValue { voice } = self {
f("voice", crate::text::TextArg::Int(*voice as i64 + 1));
}
}
fn catalogs(&self) -> &'static [crate::text::Catalog] {
crate::synth::va::text_table::CATALOGS
}
}
impl core::fmt::Display for Dx7Error {
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 Dx7Error {}
const PACKED: usize = 128;
const SINGLE: usize = 155;
const BANK: usize = 32;
pub fn parse_sysex(bytes: &[u8]) -> Result<Vec<Dx7Voice>, Dx7Error> {
let sysex_ok = |len: usize, sub: u8| {
bytes.len() == len
&& bytes[0] == 0xF0
&& bytes[1] == 0x43
&& bytes[2] & 0xF0 == 0x00
&& bytes[3] == sub
&& bytes[len - 1] == 0xF7
};
if sysex_ok(6 + PACKED * BANK + 2, 0x09) {
return packed_bank(&bytes[6..6 + PACKED * BANK]);
}
if sysex_ok(6 + SINGLE + 2, 0x00) {
return Ok(vec![unpacked(&bytes[6..6 + SINGLE], 0)?]);
}
match bytes.len() {
l if l == PACKED * BANK => packed_bank(bytes),
PACKED => Ok(vec![packed(bytes, 0)?]),
SINGLE => Ok(vec![unpacked(bytes, 0)?]),
_ => Err(Dx7Error::Unrecognized),
}
}
fn packed_bank(data: &[u8]) -> Result<Vec<Dx7Voice>, Dx7Error> {
data.chunks(PACKED)
.enumerate()
.map(|(i, c)| packed(c, i))
.collect()
}
fn name_of(b: &[u8]) -> String {
let s: String = b
.iter()
.map(|&c| {
if (0x20..0x7F).contains(&c) {
c as char
} else {
' '
}
})
.collect();
s.trim().to_string()
}
fn check(voice: usize, values: &[u8], max: u8) -> Result<(), Dx7Error> {
if values.iter().any(|&v| v > max) {
Err(Dx7Error::BadValue { voice })
} else {
Ok(())
}
}
fn packed(b: &[u8], voice: usize) -> Result<Dx7Voice, Dx7Error> {
let mut ops: Vec<Dx7Op> = Vec::with_capacity(6);
for i in 0..6 {
let o = &b[i * 17..i * 17 + 17];
check(voice, &o[0..8], 99)?;
check(voice, &o[14..15], 99)?;
check(voice, &o[16..17], 99)?;
let op = Dx7Op {
rates: [o[0], o[1], o[2], o[3]],
levels: [o[4], o[5], o[6], o[7]],
output_level: o[14],
fixed: o[15] & 1 == 1,
coarse: (o[15] >> 1) & 0x1F,
fine: o[16],
detune: ((o[12] >> 3) & 0x0F).min(14),
};
ops.push(op);
}
ops.reverse(); Ok(Dx7Voice {
name: name_of(&b[118..128]),
algorithm: b[110] & 0x1F,
feedback: b[111] & 0x07,
transpose: b[117].min(48),
ops: ops.try_into().expect("6 operators"),
})
}
fn unpacked(b: &[u8], voice: usize) -> Result<Dx7Voice, Dx7Error> {
let mut ops: Vec<Dx7Op> = Vec::with_capacity(6);
for i in 0..6 {
let o = &b[i * 21..i * 21 + 21];
check(voice, &o[0..8], 99)?;
check(voice, &o[16..17], 99)?;
check(voice, &o[19..20], 99)?;
check(voice, &o[20..21], 14)?;
ops.push(Dx7Op {
rates: [o[0], o[1], o[2], o[3]],
levels: [o[4], o[5], o[6], o[7]],
output_level: o[16],
fixed: o[17] & 1 == 1,
coarse: o[18] & 0x1F,
fine: o[19],
detune: o[20],
});
}
ops.reverse();
Ok(Dx7Voice {
name: name_of(&b[145..155]),
algorithm: b[134] & 0x1F,
feedback: b[135] & 0x07,
transpose: b[144].min(48),
ops: ops.try_into().expect("6 operators"),
})
}
pub fn carriers(algorithm: u8) -> u8 {
crate::synth::va::engine::dx7_carrier_mask(algorithm)
}
fn amp(level: u8) -> f32 {
if level == 0 {
return 0.0;
}
let a = 10f32.powf(-(99.0 - level as f32) * 0.75 / 20.0);
if level < 20 {
a * level as f32 / 20.0
} else {
a
}
}
fn t60(rate: u8) -> f32 {
0.02 * 2f32.powf((99.0 - rate as f32) / 9.0)
}
pub fn macro_name(name: &str) -> String {
let mut s = String::new();
for c in name.chars() {
if c.is_ascii_alphanumeric() {
s.push(c.to_ascii_lowercase());
} else if !s.ends_with('_') && !s.is_empty() {
s.push('_');
}
}
let s = s.trim_end_matches('_').to_string();
if s.is_empty() {
"dx7_voice".to_string()
} else if s.starts_with(|c: char| c.is_ascii_digit()) {
format!("dx7_{s}")
} else {
s
}
}
pub fn to_mml(v: &Dx7Voice, name: &str) -> String {
let mask = carriers(v.algorithm);
let n_carriers = mask.count_ones().max(1);
let mut notes: Vec<String> = Vec::new();
let mut s = format!(
"${name} = @15 %fmx_ops=6 %fmx_algo={} %fmx_fb={}",
32 + v.algorithm as u32,
(v.feedback as u32 * 100 + 3) / 7
);
let mut release = 0.0f32;
for (i, op) in v.ops.iter().enumerate() {
let n = i + 1;
let carrier = mask & (1 << i) != 0;
let ratio = if op.fixed {
let hz = 10f32.powi((op.coarse & 3) as i32) * (1.0 + op.fine as f32 * 0.0088);
notes.push(format!(
"OP{n} は固定周波数({hz:.0} Hz)。比に直したので高さに追従する"
));
hz / 261.63
} else {
let c = if op.coarse == 0 {
0.5
} else {
op.coarse as f32
};
c * (1.0 + op.fine as f32 / 100.0)
};
let ratio_x100 = (ratio * 100.0).round().clamp(0.0, 3200.0) as u32;
if ratio * 100.0 > 3200.0 {
notes.push(format!("OP{n} の比 {ratio:.1} は 32 に丸めた"));
}
let out = amp(op.output_level);
let scale = if carrier { 100.0 } else { 130.0 };
let steady = out * amp(op.levels[2]);
let start = out * amp(op.levels[0]);
if op.levels[0] < op.levels[2] {
notes.push(format!(
"OP{n} は出だしより保持の方が大きい(スウェル)。保持の高さで鳴らす"
));
}
let level = (steady * scale).round().clamp(0.0, 400.0) as u32;
let boost = ((start - steady).max(0.0) * scale)
.round()
.clamp(0.0, 400.0) as u32;
let decay = ((t60(op.rates[1]) / 6.9) * 100.0).round().clamp(1.0, 500.0) as u32;
let det = (100 + (op.detune as i32 - 7) * 3 / 2).clamp(0, 200);
s.push_str(&format!(
" %fmx{n}_ratio={ratio_x100} %fmx{n}_level={level} %fmx{n}_env={boost} %fmx{n}_decay={decay} %fmx{n}_det={det}"
));
if carrier {
release = release.max(t60(op.rates[3]));
}
}
let release_u = (release * 100.0).round().clamp(1.0, 255.0) as u32;
let gain = (100.0 * (n_carriers as f32).sqrt())
.round()
.clamp(100.0, 400.0) as u32;
s.push_str(&format!(" %release={release_u} %gain={gain}"));
let mut out = format!(
"; DX7 の音色 \"{}\"(アルゴリズム {}、帰還 {})。近似の取り込みで、音量は pikopiko tone で測り直す\n",
v.name,
v.algorithm + 1,
v.feedback
);
if matches!(v.algorithm, 3 | 5) {
notes.push(
"アルゴリズム 4・6 の別オペレーターへ戻る帰還は、6 の自己帰還で近似した".to_string(),
);
}
notes.push(
"キースケーリング・ベロシティ感度・ピッチエンベロープ・LFO・トランスポーズは取り込まない"
.to_string(),
);
for n in notes {
out.push_str(&format!("; {n}\n"));
}
out.push_str(&s);
out.push('\n');
out
}