use std::f64::consts::TAU;
use duet_capture::{PerformanceFrames, ReadNote, Reading};
const SINE_LEVEL: f64 = 0.3;
const FADE_SECS: f64 = 0.01;
pub fn key_cents(reading: &Reading, key: u8) -> f64 {
reading.tuning.a4.value() + 100.0 * (f64::from(key) - 69.0)
}
pub fn hz(cents: f64) -> f64 {
440.0 * ((cents - 6900.0) / 1200.0).exp2()
}
pub fn slide_end(note: &ReadNote, rate: u32) -> u64 {
note.residual
.as_ref()
.and_then(|r| r.scoop)
.map_or(note.held_from, |scoop| {
note.start + (f64::from(scoop.ms) / 1000.0 * f64::from(rate)).round() as u64
})
.min(note.end)
}
pub const BRIDGE_SECS: f64 = 0.2;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Gaps {
Bridged,
Legato,
Gapped,
}
impl Gaps {
fn bridges(self, frames: u64, rate: u32) -> bool {
match self {
Gaps::Legato => true,
Gaps::Gapped => frames == 0,
Gaps::Bridged => (frames as f64) < BRIDGE_SECS * f64::from(rate),
}
}
}
fn phrases(reading: &Reading, rate: u32, gaps: Gaps) -> Vec<(usize, u64, u64)> {
let mut out: Vec<(usize, u64, u64)> = Vec::new();
for (i, note) in reading.notes.iter().enumerate() {
match out.last_mut() {
Some((_, _, end)) if gaps.bridges(note.start.saturating_sub(*end), rate) => {
*end = (*end).max(note.end);
}
_ => out.push((i, note.start, note.end)),
}
}
out
}
fn sine_cents(reading: &Reading, rate: u32, phrases: &[(usize, u64, u64)], at: u64) -> Option<f64> {
let p = phrases
.partition_point(|&(_, start, _)| start <= at)
.checked_sub(1)?;
let (first, _, end) = phrases[p];
if at >= end {
return None;
}
let notes = &reading.notes;
let i = notes.partition_point(|n| n.start <= at).saturating_sub(1);
let note = ¬es[i];
let here = key_cents(reading, note.key);
let slid = slide_end(note, rate);
if i == first || at >= slid || slid <= note.start {
return Some(here);
}
let before = key_cents(reading, notes[i - 1].key);
let along = (at - note.start) as f64 / (slid - note.start) as f64;
Some(before + (here - before) * along)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum Render {
#[default]
Melody,
Steps,
Bends,
}
impl Render {
pub fn suffix(self) -> &'static str {
match self {
Render::Melody => "",
Render::Steps => ".steps",
Render::Bends => ".bends",
}
}
}
pub struct Voice<'a> {
reading: &'a Reading,
frames: &'a PerformanceFrames,
rate: u32,
render: Render,
phrases: Vec<(usize, u64, u64)>,
}
impl<'a> Voice<'a> {
pub fn new(
reading: &'a Reading,
frames: &'a PerformanceFrames,
gaps: Gaps,
render: Render,
) -> Voice<'a> {
let rate = frames.rate;
Voice {
reading,
frames,
rate,
render,
phrases: phrases(reading, rate, gaps),
}
}
fn phrase(&self, at: u64) -> Option<(u64, u64)> {
let p = self
.phrases
.partition_point(|&(_, start, _)| start <= at)
.checked_sub(1)?;
let (_, start, end) = self.phrases[p];
(at < end).then_some((start, end))
}
pub fn cents(&self, at: u64) -> Option<f64> {
let melody = sine_cents(self.reading, self.rate, &self.phrases, at)?;
let notes = &self.reading.notes;
let i = notes.partition_point(|n| n.start <= at).checked_sub(1);
let Some(note) = i.map(|i| ¬es[i]).filter(|n| at < n.end) else {
return Some(melody);
};
match self.render {
Render::Melody => Some(melody),
Render::Steps => Some(
note.residual
.iter()
.flat_map(|r| &r.excursions)
.find(|e| (e.start..e.end).contains(&at))
.map_or(melody, |e| {
key_cents(self.reading, note.key) + f64::from(e.cents)
}),
),
Render::Bends => Some(performance_cents(self.frames, note, at).unwrap_or(melody)),
}
}
}
fn performance_cents(frames: &PerformanceFrames, note: &ReadNote, at: u64) -> Option<f64> {
let hop = u64::from(frames.hop);
let index = |frame: u64| frame.saturating_sub(frames.first_frame).div_ceil(hop) as usize;
let first = index(note.start).min(frames.len());
let last = index(note.end).min(frames.len());
let next = at
.checked_sub(frames.first_frame)
.map_or(0, |since| (since / hop + 1) as usize)
.clamp(first, last);
let voiced = |k: &usize| !frames.cents[*k].is_nan();
let before = (first..next).rev().find(voiced);
let after = (next..last).find(voiced);
let pitch = |k: usize| f64::from(frames.cents[k]);
match (before, after) {
(Some(b), Some(a)) => {
let (tb, ta) = (frames.frame(b) as f64, frames.frame(a) as f64);
let along = ((at as f64 - tb) / (ta - tb)).clamp(0.0, 1.0);
Some(pitch(b) + (pitch(a) - pitch(b)) * along)
}
(Some(k), None) | (None, Some(k)) => Some(pitch(k)),
(None, None) => None,
}
}
pub fn sine(voice: &Voice, from: u64, to: u64) -> Vec<f32> {
let rate = f64::from(voice.rate);
let fade = FADE_SECS * rate;
let mut phase = 0.0_f64;
(from..to)
.map(|at| {
let (Some(cents), Some((start, end))) = (voice.cents(at), voice.phrase(at)) else {
return 0.0;
};
let envelope = ((at - start) as f64 / fade)
.min((end - at) as f64 / fade)
.min(1.0);
let sample = SINE_LEVEL * envelope * phase.sin();
phase = (phase + TAU * hz(cents) / rate) % TAU;
sample as f32
})
.collect()
}
pub fn stereo(rate: u32, left: &[f32], right: &[f32]) -> Vec<u8> {
debug_assert_eq!(left.len(), right.len());
const CHANNELS: u16 = 2;
const BYTES: u16 = 4;
let frames = left.len() as u32;
let data = frames * u32::from(CHANNELS * BYTES);
let mut out = Vec::with_capacity(58 + data as usize);
out.extend(b"RIFF");
out.extend((50 + data).to_le_bytes());
out.extend(b"WAVEfmt ");
out.extend(18u32.to_le_bytes());
out.extend(3u16.to_le_bytes()); out.extend(CHANNELS.to_le_bytes());
out.extend(rate.to_le_bytes());
out.extend((rate * u32::from(CHANNELS * BYTES)).to_le_bytes());
out.extend((CHANNELS * BYTES).to_le_bytes());
out.extend((BYTES * 8).to_le_bytes());
out.extend(0u16.to_le_bytes()); out.extend(b"fact");
out.extend(4u32.to_le_bytes());
out.extend(frames.to_le_bytes());
out.extend(b"data");
out.extend(data.to_le_bytes());
for (l, r) in left.iter().zip(right) {
out.extend(l.to_le_bytes());
out.extend(r.to_le_bytes());
}
out
}