use crate::compiler::song::{EventKind, Song, DEFAULT_TEMPO_MILLI};
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TrackInfo {
pub name: String,
pub note_count: usize,
pub lowest_key: Option<u8>,
pub highest_key: Option<u8>,
pub lowest_note: Option<String>,
pub highest_note: Option<String>,
pub tones: Vec<u8>,
pub envelopes: Vec<String>,
pub end_tick: u64,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SongInfo {
pub synth: String,
pub ppq: u32,
pub length_ticks: u64,
pub duration_secs: f64,
pub loop_tick: Option<u64>,
pub loop_secs: Option<f64>,
#[cfg_attr(feature = "serde", serde(serialize_with = "ser_tempos"))]
pub tempos: Vec<f64>,
pub tracks: Vec<TrackInfo>,
pub key: Option<KeyInfo>,
#[cfg_attr(
feature = "serde",
serde(
default,
skip_serializing_if = "crate::compiler::song::SongMeta::is_empty"
)
)]
pub meta: crate::compiler::song::SongMeta,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Vec::is_empty")
)]
pub markers: Vec<MarkerInfo>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "is_common_time")
)]
pub meter: crate::compiler::song::Meter,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Vec::is_empty")
)]
pub shots: Vec<ShotInfo>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShotInfo {
pub name: String,
pub synth: String,
pub secs: f64,
pub duck: bool,
pub count: usize,
}
#[cfg(feature = "serde")]
fn is_common_time(m: &crate::compiler::song::Meter) -> bool {
*m == crate::compiler::song::Meter::default()
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MarkerInfo {
pub name: String,
pub tick: u64,
pub secs: f64,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct KeyInfo {
pub name: String,
pub tonic: String,
pub mode: crate::composer::analysis::Mode,
pub confidence: f64,
}
const PC_NAMES: [&str; 12] = [
"c", "c+", "d", "d+", "e", "f", "f+", "g", "g+", "a", "a+", "b",
];
pub fn key_name(key: u8) -> String {
let oct = key as i32 / 12 - 1;
format!("o{}{}", oct, PC_NAMES[key as usize % 12])
}
pub fn ticks_to_secs(song: &Song, tick: u64) -> f64 {
let mut secs = 0.0;
let mut last = 0u64;
let mut tempo = DEFAULT_TEMPO_MILLI;
for e in &song.events {
if e.tick >= tick {
break;
}
if let EventKind::Tempo(t) = e.kind {
secs += (e.tick - last) as f64 * 60_000.0 / (tempo as f64 * song.ppq as f64);
last = e.tick;
tempo = t;
}
}
secs + (tick - last.min(tick)) as f64 * 60_000.0 / (tempo as f64 * song.ppq as f64)
}
pub fn secs_to_ticks(song: &Song, secs: f64) -> u64 {
if !secs.is_finite() || secs <= 0.0 {
return 0;
}
let mut elapsed = 0.0;
let mut last = 0u64;
let mut tempo = DEFAULT_TEMPO_MILLI;
let per_tick = |t: u32| 60_000.0 / (t as f64 * song.ppq as f64);
for e in &song.events {
if let EventKind::Tempo(t) = e.kind {
let seg = (e.tick - last) as f64 * per_tick(tempo);
if elapsed + seg > secs {
break;
}
elapsed += seg;
last = e.tick;
tempo = t;
}
}
let t = last + ((secs - elapsed) / per_tick(tempo)).floor() as u64;
t.min(song.length_ticks)
}
pub fn describe(song: &Song) -> SongInfo {
describe_with(song, crate::synth::BUILTIN)
}
pub fn describe_with(song: &Song, synths: &[&crate::SynthSpec]) -> SongInfo {
let spec = crate::synth::find(synths, &song.synth.name);
let mut tracks: Vec<TrackInfo> = song
.tracks
.iter()
.map(|n| TrackInfo {
name: n.clone(),
note_count: 0,
lowest_key: None,
highest_key: None,
lowest_note: None,
highest_note: None,
tones: Vec::new(),
envelopes: Vec::new(),
end_tick: 0,
})
.collect();
let n = tracks.len();
let mut sounding = vec![false; n];
let mut tone = vec![song.default_tone; n];
let mut env: Vec<Option<u8>> = vec![None; n];
let mut last_key = vec![0u8; n];
let mut tempos = Vec::new();
if !song
.events
.iter()
.any(|e| e.tick == 0 && matches!(e.kind, EventKind::Tempo(_)))
{
tempos.push(DEFAULT_TEMPO_MILLI);
}
for e in &song.events {
let ti = e.track as usize;
let Some(t) = tracks.get_mut(ti) else {
continue;
};
match e.kind {
EventKind::NoteOn { key, .. } => {
if !sounding[ti] {
t.note_count += 1;
}
sounding[ti] = true;
last_key[ti] = key;
t.lowest_key = Some(t.lowest_key.map_or(key, |k| k.min(key)));
t.highest_key = Some(t.highest_key.map_or(key, |k| k.max(key)));
if !t.tones.contains(&tone[ti]) {
t.tones.push(tone[ti]);
}
if let Some(e) = env[ti].and_then(|i| song.envelopes.get(i as usize)) {
if !t.envelopes.contains(&e.name) {
t.envelopes.push(e.name.clone());
}
}
}
EventKind::Chord { keys, .. } => {
t.note_count += 1;
sounding[ti] = true;
last_key[ti] = keys.as_slice()[0];
for &key in keys.as_slice() {
t.lowest_key = Some(t.lowest_key.map_or(key, |k| k.min(key)));
t.highest_key = Some(t.highest_key.map_or(key, |k| k.max(key)));
}
if !t.tones.contains(&tone[ti]) {
t.tones.push(tone[ti]);
}
if let Some(e) = env[ti].and_then(|i| song.envelopes.get(i as usize)) {
if !t.envelopes.contains(&e.name) {
t.envelopes.push(e.name.clone());
}
}
}
EventKind::NoteOff => {
sounding[ti] = false;
t.end_tick = t.end_tick.max(e.tick);
}
EventKind::Tone(v) => tone[ti] = v,
EventKind::Param { .. }
| EventKind::Vibrato(_)
| EventKind::Detune(_)
| EventKind::Arp(_)
| EventKind::Duty(_)
| EventKind::Wave(_) => {}
EventKind::Portamento { cents, .. } => {
let key = (last_key[ti] as i32 + cents as i32 / 100).clamp(0, 127) as u8;
t.lowest_key = Some(t.lowest_key.map_or(key, |k| k.min(key)));
t.highest_key = Some(t.highest_key.map_or(key, |k| k.max(key)));
}
EventKind::Envelope(i) => env[ti] = Some(i),
EventKind::Tempo(_) | EventKind::Shot { .. } => {}
}
}
let mut run: Option<(crate::Span, u32)> = None;
for e in &song.events {
let EventKind::Tempo(v) = e.kind else {
continue;
};
match run {
Some((sp, _)) if sp == e.span => run = Some((sp, v)),
_ => {
if let Some((_, last)) = run.replace((e.span, v)) {
if !tempos.contains(&last) {
tempos.push(last);
}
}
}
}
}
if let Some((_, last)) = run {
if !tempos.contains(&last) {
tempos.push(last);
}
}
for t in &mut tracks {
t.tones.sort_unstable();
t.lowest_note = t.lowest_key.map(key_name);
t.highest_note = t.highest_key.map(key_name);
}
SongInfo {
synth: song.synth.name.clone(),
ppq: song.ppq,
length_ticks: song.length_ticks,
duration_secs: ticks_to_secs(song, song.length_ticks),
loop_tick: song.loop_tick,
loop_secs: song.loop_tick.map(|t| ticks_to_secs(song, t)),
tempos: tempos.iter().map(|&m| m as f64 / 1000.0).collect(),
tracks,
key: crate::composer::analysis::song_key(song, spec).map(|k| KeyInfo {
name: k.key.name(),
tonic: PC_NAMES[k.key.tonic as usize % 12].to_string(),
mode: k.key.mode,
confidence: k.confidence as f64 / 1000.0,
}),
meta: song.meta.clone(),
markers: song
.markers
.iter()
.map(|m| MarkerInfo {
name: m.name.clone(),
tick: m.tick,
secs: ticks_to_secs(song, m.tick),
})
.collect(),
meter: song.meter,
shots: song
.shots
.iter()
.enumerate()
.map(|(i, s)| ShotInfo {
name: s.name.clone(),
synth: s.song.synth.name.clone(),
secs: ticks_to_secs(&s.song, s.song.length_ticks),
duck: s.duck,
count: song
.events
.iter()
.filter(|e| matches!(e.kind, EventKind::Shot { id, .. } if id as usize == i))
.count(),
})
.collect(),
}
}
#[cfg(feature = "serde")]
fn ser_tempos<S: serde::Serializer>(v: &[f64], s: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeSeq;
let mut seq = s.serialize_seq(Some(v.len()))?;
for &t in v {
if t.fract() == 0.0 && (0.0..=u32::MAX as f64).contains(&t) {
seq.serialize_element(&(t as u32))?;
} else {
seq.serialize_element(&t)?;
}
}
seq.end()
}