use crate::compiler::song::{ChordKeys, EventKind, Song};
use crate::synth::SynthSpec;
use crate::Span;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NoteSpan {
pub track: u8,
pub key: u8,
pub start: u64,
pub end: u64,
pub tone: u8,
pub span: Span,
}
pub fn notes(song: &Song, spec: Option<&SynthSpec>) -> Vec<NoteSpan> {
let mut open: Vec<Option<(ChordKeys, u64, u8, Span)>> = vec![None; 256];
let mut tone = vec![song.default_tone; 256];
let mut out = Vec::new();
let close =
|out: &mut Vec<NoteSpan>, track: u8, slot: Option<(ChordKeys, u64, u8, Span)>, end: u64| {
if let Some((keys, start, tone, span)) = slot {
if spec.is_some_and(|s| s.is_unpitched(tone)) {
return;
}
for &key in keys.as_slice() {
out.push(NoteSpan {
track,
key,
start,
end,
tone,
span,
});
}
}
};
for e in &song.events {
let t = e.track as usize;
match e.kind {
EventKind::NoteOn { key, .. } => {
close(&mut out, e.track, open[t].take(), e.tick);
open[t] = ChordKeys::new(&[key]).map(|k| (k, e.tick, tone[t], e.span));
}
EventKind::Chord { keys, .. } => {
close(&mut out, e.track, open[t].take(), e.tick);
open[t] = Some((keys, e.tick, tone[t], e.span));
}
EventKind::NoteOff => close(&mut out, e.track, open[t].take(), e.tick),
EventKind::Tone(v) => tone[t] = v,
_ => {}
}
}
for (t, slot) in open.iter_mut().enumerate() {
if let Some((_, start, _, _)) = slot {
let end = song.length_ticks.max(*start);
close(&mut out, t as u8, slot.take(), end);
}
}
out.retain(|n| n.end > n.start);
out.sort_by_key(|n| (n.start, n.track, n.key));
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum Mode {
Major,
Minor,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Key {
pub tonic: u8,
pub mode: Mode,
}
const MAJOR_SCALE: [u8; 7] = [0, 2, 4, 5, 7, 9, 11];
const MINOR_SCALE: [u8; 7] = [0, 2, 3, 5, 7, 8, 10];
const MAJOR_NAMES: [&str; 12] = [
"C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B",
];
const MINOR_NAMES: [&str; 12] = [
"C", "C#", "D", "Eb", "E", "F", "F#", "G", "G#", "A", "Bb", "B",
];
impl Key {
pub fn all() -> impl Iterator<Item = Key> {
(0..12u8).flat_map(|t| {
[Mode::Major, Mode::Minor]
.into_iter()
.map(move |mode| Key { tonic: t, mode })
})
}
pub fn name(&self) -> String {
match self.mode {
Mode::Major => format!("{} major", MAJOR_NAMES[self.tonic as usize % 12]),
Mode::Minor => format!("{} minor", MINOR_NAMES[self.tonic as usize % 12]),
}
}
pub fn scale(&self) -> [u8; 7] {
let s = match self.mode {
Mode::Major => MAJOR_SCALE,
Mode::Minor => MINOR_SCALE,
};
s.map(|i| (self.tonic + i) % 12)
}
pub fn contains(&self, pc: u8) -> bool {
self.scale().contains(&(pc % 12))
}
pub fn parse(s: &str) -> Option<Key> {
let s = s.trim();
let (root, mode) = s.split_once(char::is_whitespace)?;
let mode = match mode.trim().to_ascii_lowercase().as_str() {
"major" => Mode::Major,
"minor" => Mode::Minor,
_ => return None,
};
Some(Key {
tonic: pitch_class(root)?,
mode,
})
}
}
fn pitch_class(s: &str) -> Option<u8> {
let mut chars = s.chars();
let base = match chars.next()?.to_ascii_lowercase() {
'c' => 0i8,
'd' => 2,
'e' => 4,
'f' => 5,
'g' => 7,
'a' => 9,
'b' => 11,
_ => return None,
};
let mut v = base;
for c in chars {
match c {
'#' | '+' => v += 1,
'b' | '-' => v -= 1,
_ => return None,
}
}
Some(v.rem_euclid(12) as u8)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyEstimate {
pub key: Key,
pub confidence: i32,
}
const MAJOR_PROFILE: [i64; 12] = [635, 223, 348, 233, 438, 409, 252, 519, 239, 366, 229, 288];
const MINOR_PROFILE: [i64; 12] = [633, 268, 352, 538, 260, 353, 254, 475, 398, 269, 334, 317];
pub fn pitch_histogram(notes: &[NoteSpan], range: Option<(u64, u64)>) -> [u64; 12] {
let mut h = [0u64; 12];
for n in notes {
let (s, e) = match range {
Some((a, b)) => (n.start.max(a), n.end.min(b)),
None => (n.start, n.end),
};
if e > s {
h[n.key as usize % 12] += e - s;
}
}
h
}
pub fn estimate_key(hist: &[u64; 12]) -> Option<KeyEstimate> {
let max = *hist.iter().max()?;
let div = if max > 1_000_000 {
max / 1_000_000 + 1
} else {
1
};
let x: [i128; 12] = hist.map(|v| (v / div) as i128);
let sx: i128 = x.iter().sum();
let cx: [i128; 12] = x.map(|v| 12 * v - sx);
let varx: i128 = cx.iter().map(|v| v * v).sum();
if varx == 0 {
return None;
}
let mut best: Option<KeyEstimate> = None;
for key in Key::all() {
let p = match key.mode {
Mode::Major => &MAJOR_PROFILE,
Mode::Minor => &MINOR_PROFILE,
};
let sp: i128 = p.iter().map(|&v| v as i128).sum();
let cp: [i128; 12] = p.map(|v| 12 * v as i128 - sp);
let varp: i128 = cp.iter().map(|v| v * v).sum();
let cov: i128 = (0..12)
.map(|i| cx[(i + key.tonic as usize) % 12] * cp[i])
.sum();
let denom = isqrt((varx as u128) * (varp as u128)) as i128;
let confidence = (cov * 1000 / denom.max(1)) as i32;
if best.is_none_or(|b| confidence > b.confidence) {
best = Some(KeyEstimate { key, confidence });
}
}
best
}
fn isqrt(n: u128) -> u128 {
if n < 2 {
return n;
}
let mut x = 1u128 << (n.ilog2() / 2 + 1);
loop {
let y = (x + n / x) / 2;
if y >= x {
return x;
}
x = y;
}
}
pub fn song_key(song: &Song, spec: Option<&SynthSpec>) -> Option<KeyEstimate> {
estimate_key(&pitch_histogram(¬es(song, spec), None))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum ChordQuality {
Major,
Minor,
Diminished,
Augmented,
Sus4,
Dominant7,
Major7,
Minor7,
HalfDiminished7,
Power,
}
impl ChordQuality {
const ALL: [ChordQuality; 10] = [
ChordQuality::Major,
ChordQuality::Minor,
ChordQuality::Dominant7,
ChordQuality::Minor7,
ChordQuality::Major7,
ChordQuality::Power,
ChordQuality::Sus4,
ChordQuality::Diminished,
ChordQuality::HalfDiminished7,
ChordQuality::Augmented,
];
pub fn intervals(self) -> &'static [u8] {
match self {
ChordQuality::Major => &[0, 4, 7],
ChordQuality::Minor => &[0, 3, 7],
ChordQuality::Diminished => &[0, 3, 6],
ChordQuality::Augmented => &[0, 4, 8],
ChordQuality::Sus4 => &[0, 5, 7],
ChordQuality::Dominant7 => &[0, 4, 7, 10],
ChordQuality::Major7 => &[0, 4, 7, 11],
ChordQuality::Minor7 => &[0, 3, 7, 10],
ChordQuality::HalfDiminished7 => &[0, 3, 6, 10],
ChordQuality::Power => &[0, 7],
}
}
pub fn suffix(self) -> &'static str {
match self {
ChordQuality::Major => "",
ChordQuality::Minor => "m",
ChordQuality::Diminished => "dim",
ChordQuality::Augmented => "aug",
ChordQuality::Sus4 => "sus4",
ChordQuality::Dominant7 => "7",
ChordQuality::Major7 => "maj7",
ChordQuality::Minor7 => "m7",
ChordQuality::HalfDiminished7 => "m7-5",
ChordQuality::Power => "5",
}
}
}
const CHORD_ROOTS: [&str; 12] = [
"C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Chord {
pub root: u8,
pub quality: ChordQuality,
pub bass: u8,
}
impl Chord {
pub fn name(&self) -> String {
let mut s = format!(
"{}{}",
CHORD_ROOTS[self.root as usize % 12],
self.quality.suffix()
);
if self.bass != self.root {
s.push('/');
s.push_str(CHORD_ROOTS[self.bass as usize % 12]);
}
s
}
}
pub fn chord_of(keys: &[u8]) -> Option<Chord> {
let bass = keys.iter().min()? % 12;
let mut set = 0u16;
for &k in keys {
set |= 1 << (k % 12);
}
if set.count_ones() < 2 {
return None;
}
let mut best: Option<(i32, bool, i32, Chord)> = None;
for (qi, &q) in ChordQuality::ALL.iter().enumerate() {
for root in 0..12u8 {
if set & (1 << root) == 0 {
continue;
}
let mut tpl = 0u16;
for &i in q.intervals() {
tpl |= 1 << ((root + i) % 12);
}
let matched = (set & tpl).count_ones() as i32;
let missing = (tpl & !set).count_ones() as i32;
let extra = (set & !tpl).count_ones() as i32;
if missing > 1 || matched < 2 {
continue;
}
let score = matched * 3 - missing * 2 - extra * 2;
if score <= 0 {
continue;
}
let cand = (
score,
root == bass,
-(qi as i32 * 12 + root as i32),
Chord {
root,
quality: q,
bass,
},
);
if best.is_none_or(|b| (cand.0, cand.1, cand.2) > (b.0, b.1, b.2)) {
best = Some(cand);
}
}
}
best.map(|b| b.3)
}
pub fn chord_at(notes: &[NoteSpan], tick: u64, audible: impl Fn(u8) -> bool) -> Option<Chord> {
let keys: Vec<u8> = notes
.iter()
.filter(|n| n.start <= tick && tick < n.end && audible(n.track))
.map(|n| n.key)
.collect();
chord_of(&keys)
}
#[cfg(test)]
mod tests {
#[test]
fn isqrt_is_floor_sqrt() {
for n in (0u128..2000).chain([u64::MAX as u128, u128::MAX / 7, 10u128.pow(30)]) {
let r = super::isqrt(n);
assert!(
r * r <= n && (r + 1).checked_mul(r + 1).is_none_or(|v| v > n),
"{n}"
);
}
}
}