restructure
Check and Windows preview / check (patina) (push) Successful in 2m20s
Check and Windows preview / check (rivet) (push) Successful in 1m38s
Check and Windows preview / previews (push) Successful in 1m6s
Check and Windows preview / windows (push) Successful in 1m50s
Independent plugin release / publish (push) Successful in 8s
Independent plugin release / plan (push) Successful in 7s
Independent plugin release / build (push) Successful in 2m21s
Check and Windows preview / check (patina) (push) Successful in 2m20s
Check and Windows preview / check (rivet) (push) Successful in 1m38s
Check and Windows preview / previews (push) Successful in 1m6s
Check and Windows preview / windows (push) Successful in 1m50s
Independent plugin release / publish (push) Successful in 8s
Independent plugin release / plan (push) Successful in 7s
Independent plugin release / build (push) Successful in 2m21s
This commit is contained in:
1 parent
3c5b05fdec
commit
15853e61ac
87 files changed
+2065
-1198
No files matched your search
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"rivet": {
|
||||
"name": "Rivet",
|
||||
"description": "Join motifs into connected musical phrases",
|
||||
"manifest": "plugins/rivet/plugin/Cargo.toml",
|
||||
"library": "rivet",
|
||||
"documentation": "docs/rivet",
|
||||
"standalone": "rivet",
|
||||
"clap_id": "io.storyboard.motif",
|
||||
"packages": [
|
||||
"rivet-core",
|
||||
"rivet-midi",
|
||||
"rivet-app",
|
||||
"rivet-preview"
|
||||
]
|
||||
},
|
||||
"patina": {
|
||||
"name": "Patina",
|
||||
"description": "Smooth harsh resonances while retaining character",
|
||||
"manifest": "plugins/patina/plugin/Cargo.toml",
|
||||
"library": "patina",
|
||||
"documentation": "docs/patina",
|
||||
"clap_id": "io.storyboard.resonance-compressor",
|
||||
"licenses": {
|
||||
"plugins/patina/ui/assets/OFL.txt": "licenses/Roboto-OFL.txt"
|
||||
},
|
||||
"packages": [
|
||||
"patina-core",
|
||||
"patina-ui",
|
||||
"patina-render"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fn main() {
|
||||
nih_plug::prelude::nih_export_standalone::<motif_storyboard::MotifStoryboard>();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "patina-core"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
[dependencies]
|
||||
rustfft = "6.4"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,404 @@
|
||||
//! Independently designed spectral attenuation. No host or GUI dependencies.
|
||||
mod settings;
|
||||
use rustfft::{num_complex::Complex32, Fft, FftPlanner};
|
||||
pub use settings::{focus_offset, knee, Focus, Settings};
|
||||
use std::{f32::consts::PI, sync::Arc};
|
||||
|
||||
pub const GRID: usize = 512;
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AnalyzerFrame {
|
||||
pub input: [f32; GRID],
|
||||
pub reduction: [f32; GRID],
|
||||
pub focus: [f32; GRID],
|
||||
pub input_peak: f32,
|
||||
pub output_peak: f32,
|
||||
pub guard: f32,
|
||||
pub sample_rate: f32,
|
||||
pub latency: u32,
|
||||
pub channels: usize,
|
||||
}
|
||||
impl Default for AnalyzerFrame {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
input: [-120.; GRID],
|
||||
reduction: [0.; GRID],
|
||||
focus: [0.; GRID],
|
||||
input_peak: 0.,
|
||||
output_peak: 0.,
|
||||
guard: 0.,
|
||||
sample_rate: 48000.,
|
||||
latency: 4096,
|
||||
channels: 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn frequency(index: usize) -> f32 {
|
||||
20. * 1000f32.powf(index as f32 / (GRID - 1) as f32)
|
||||
}
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct Monitor {
|
||||
pub delta: bool,
|
||||
}
|
||||
|
||||
pub struct Engine {
|
||||
rate: f32,
|
||||
channels: usize,
|
||||
n: usize,
|
||||
hop: usize,
|
||||
pos: usize,
|
||||
hop_pos: usize,
|
||||
input: [Vec<f32>; 2],
|
||||
output: [Vec<f32>; 2],
|
||||
spectra: [Vec<Complex32>; 2],
|
||||
window: Vec<f32>,
|
||||
scratch: Vec<Complex32>,
|
||||
forward: Arc<dyn Fft<f32>>,
|
||||
inverse: Arc<dyn Fft<f32>>,
|
||||
levels: [[f32; GRID]; 2],
|
||||
target: [f32; GRID],
|
||||
reduction: [f32; GRID],
|
||||
curve: [f32; GRID],
|
||||
mask: [f32; GRID],
|
||||
map: [(usize, f32); GRID],
|
||||
bin_map: Vec<(usize, f32)>,
|
||||
kernel: [f32; 65],
|
||||
radius: usize,
|
||||
settings: Settings,
|
||||
frame: AnalyzerFrame,
|
||||
fresh: bool,
|
||||
fast: f32,
|
||||
slow: f32,
|
||||
protect: f32,
|
||||
sample_power: f32,
|
||||
mix: f32,
|
||||
gain: f32,
|
||||
bypass: f32,
|
||||
delta: f32,
|
||||
mix_initialized: bool,
|
||||
power_scale: f32,
|
||||
in_peak: f32,
|
||||
out_peak: f32,
|
||||
}
|
||||
impl Engine {
|
||||
pub fn new(rate: f32, channels: usize) -> Result<Self, &'static str> {
|
||||
if ![44100., 48000., 88200., 96000., 176400., 192000.].contains(&rate)
|
||||
|| !(1..=2).contains(&channels)
|
||||
{
|
||||
return Err("Supported rates: 44.1/48/88.2/96/176.4/192 kHz; mono or stereo");
|
||||
}
|
||||
let scale = if rate > 96000. {
|
||||
4
|
||||
} else if rate > 48000. {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let n = 4096 * scale;
|
||||
let hop = n / 8;
|
||||
let mut planner = FftPlanner::new();
|
||||
let forward = planner.plan_fft_forward(n);
|
||||
let inverse = planner.plan_fft_inverse(n);
|
||||
let scratch_len = forward
|
||||
.get_inplace_scratch_len()
|
||||
.max(inverse.get_inplace_scratch_len());
|
||||
let window: Vec<_> = (0..n)
|
||||
.map(|i| {
|
||||
(0.5 - 0.5 * (2. * PI * i as f32 / n as f32).cos())
|
||||
.max(0.)
|
||||
.sqrt()
|
||||
})
|
||||
.collect();
|
||||
let power_scale = 2. / window.iter().sum::<f32>().powi(2);
|
||||
let nyquist = rate * 0.5;
|
||||
let map = std::array::from_fn(|i| {
|
||||
let bin = (frequency(i).min(nyquist) * n as f32 / rate).min((n / 2 - 1) as f32);
|
||||
(bin.floor() as usize, bin.fract())
|
||||
});
|
||||
let bin_map = (0..=n / 2)
|
||||
.map(|k| {
|
||||
let grid = ((k as f32 * rate / n as f32).max(20.) / 20.).log2() / 1000f32.log2()
|
||||
* (GRID - 1) as f32;
|
||||
let grid = grid.clamp(0., (GRID - 1) as f32);
|
||||
(
|
||||
(grid.floor() as usize).min(GRID - 2),
|
||||
if grid >= (GRID - 1) as f32 {
|
||||
1.
|
||||
} else {
|
||||
grid.fract()
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut engine = Self {
|
||||
rate,
|
||||
channels,
|
||||
n,
|
||||
hop,
|
||||
pos: 0,
|
||||
hop_pos: 0,
|
||||
input: std::array::from_fn(|_| vec![0.; n]),
|
||||
output: std::array::from_fn(|_| vec![0.; n]),
|
||||
spectra: std::array::from_fn(|_| vec![Complex32::default(); n]),
|
||||
window,
|
||||
scratch: vec![Complex32::default(); scratch_len],
|
||||
forward,
|
||||
inverse,
|
||||
levels: [[-120.; GRID]; 2],
|
||||
target: [0.; GRID],
|
||||
reduction: [0.; GRID],
|
||||
curve: [0.; GRID],
|
||||
mask: [0.; GRID],
|
||||
map,
|
||||
bin_map,
|
||||
kernel: [0.; 65],
|
||||
radius: 0,
|
||||
settings: Settings::default(),
|
||||
frame: AnalyzerFrame::default(),
|
||||
fresh: false,
|
||||
fast: 0.,
|
||||
slow: 0.,
|
||||
protect: 0.,
|
||||
sample_power: 0.,
|
||||
mix: 1.,
|
||||
gain: 1.,
|
||||
bypass: 0.,
|
||||
delta: 0.,
|
||||
mix_initialized: false,
|
||||
power_scale,
|
||||
in_peak: 0.,
|
||||
out_peak: 0.,
|
||||
};
|
||||
engine.rebuild();
|
||||
Ok(engine)
|
||||
}
|
||||
pub fn latency_samples(&self) -> u32 {
|
||||
self.n as u32
|
||||
}
|
||||
pub fn channels(&self) -> usize {
|
||||
self.channels
|
||||
}
|
||||
pub fn settings(&self) -> Settings {
|
||||
self.settings
|
||||
}
|
||||
pub fn set_settings(&mut self, settings: Settings) -> Result<(), &'static str> {
|
||||
settings.validate()?;
|
||||
if settings != self.settings {
|
||||
let rebuild = settings.focus != self.settings.focus
|
||||
|| settings.low != self.settings.low
|
||||
|| settings.high != self.settings.high
|
||||
|| settings.cut_width != self.settings.cut_width;
|
||||
self.settings = settings;
|
||||
if rebuild {
|
||||
self.rebuild();
|
||||
}
|
||||
}
|
||||
if !self.mix_initialized {
|
||||
self.mix = settings.mix / 100.;
|
||||
self.gain = 10f32.powf(settings.output / 20.);
|
||||
self.bypass = f32::from(settings.bypass);
|
||||
self.mix_initialized = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn rebuild(&mut self) {
|
||||
let step = 1000f32.log2() / (GRID - 1) as f32;
|
||||
self.radius = ((self.settings.cut_width / step * 1.3).ceil() as usize).clamp(1, 64);
|
||||
let sigma = self.settings.cut_width / step / 2.355;
|
||||
for j in 0..=self.radius {
|
||||
self.kernel[j] = (-0.5 * (j as f32 / sigma).powi(2)).exp();
|
||||
}
|
||||
for i in 0..GRID {
|
||||
let f = frequency(i);
|
||||
self.curve[i] = focus_offset(f, &self.settings.focus);
|
||||
let low = (f / self.settings.low).log2() / 0.15;
|
||||
let high = (self.settings.high.min(self.rate * 0.49) / f).log2() / 0.15;
|
||||
let edge = low.min(high).clamp(0., 1.);
|
||||
self.mask[i] = edge * edge * (3. - 2. * edge);
|
||||
}
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
for channel in &mut self.input {
|
||||
channel.fill(0.);
|
||||
}
|
||||
for channel in &mut self.output {
|
||||
channel.fill(0.);
|
||||
}
|
||||
self.reduction.fill(0.);
|
||||
self.pos = 0;
|
||||
self.hop_pos = 0;
|
||||
self.fast = 0.;
|
||||
self.slow = 0.;
|
||||
self.protect = 0.;
|
||||
self.sample_power = 0.;
|
||||
self.in_peak = 0.;
|
||||
self.out_peak = 0.;
|
||||
self.fresh = false;
|
||||
self.frame = AnalyzerFrame {
|
||||
sample_rate: self.rate,
|
||||
latency: self.n as u32,
|
||||
..Default::default()
|
||||
};
|
||||
self.mix_initialized = false;
|
||||
self.delta = 0.;
|
||||
}
|
||||
pub fn take_analyzer(&mut self) -> Option<AnalyzerFrame> {
|
||||
if self.fresh {
|
||||
self.fresh = false;
|
||||
Some(self.frame)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
/// Sample scheduling is independent of the caller's block partition.
|
||||
pub fn process_sample(&mut self, sample: [f32; 2], monitor: Monitor) -> [f32; 2] {
|
||||
let mut result = [0.; 2];
|
||||
let mut energy = 0f32;
|
||||
let smooth = 1. - (-1. / (self.rate * 0.01)).exp();
|
||||
self.mix += (self.settings.mix / 100. - self.mix) * smooth;
|
||||
self.gain += (10f32.powf(self.settings.output / 20.) - self.gain) * smooth;
|
||||
self.bypass += (f32::from(self.settings.bypass) - self.bypass) * smooth;
|
||||
self.delta += (f32::from(monitor.delta) - self.delta) * smooth;
|
||||
for c in 0..self.channels {
|
||||
let x = if sample[c].is_finite() {
|
||||
sample[c].clamp(-64., 64.)
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
let dry = self.input[c][self.pos];
|
||||
let wet = self.output[c][self.pos];
|
||||
self.output[c][self.pos] = 0.;
|
||||
let x = if x.abs() < 1e-20 { 0. } else { x };
|
||||
self.input[c][self.pos] = x;
|
||||
let mixed = (dry + (wet - dry) * self.mix) * self.gain;
|
||||
let normal = mixed + (dry - mixed) * self.bypass;
|
||||
let audible = normal + ((dry - wet) - normal) * self.delta;
|
||||
result[c] = if audible.is_finite() { audible } else { 0. };
|
||||
self.in_peak = self.in_peak.max(x.abs());
|
||||
self.out_peak = self.out_peak.max(result[c].abs());
|
||||
energy = energy.max(x * x);
|
||||
}
|
||||
self.fast += (energy - self.fast) * (1. - (-1. / (self.rate * 0.001)).exp());
|
||||
self.slow += (energy - self.slow) * (1. - (-1. / (self.rate * 0.05)).exp());
|
||||
let onset =
|
||||
((10. * ((self.fast + 1e-20) / (self.slow + 1e-20)).log10() - 3.) / 9.).clamp(0., 1.);
|
||||
self.protect = onset.max(self.protect * (-1. / (self.rate * 0.03)).exp());
|
||||
self.sample_power += energy;
|
||||
self.pos = (self.pos + 1) % self.n;
|
||||
self.hop_pos += 1;
|
||||
if self.hop_pos == self.hop {
|
||||
self.hop_pos = 0;
|
||||
self.process_window();
|
||||
}
|
||||
result
|
||||
}
|
||||
fn process_window(&mut self) {
|
||||
for c in 0..self.channels {
|
||||
for i in 0..self.n {
|
||||
self.spectra[c][i] =
|
||||
Complex32::new(self.input[c][(self.pos + i) % self.n] * self.window[i], 0.);
|
||||
}
|
||||
self.forward
|
||||
.process_with_scratch(&mut self.spectra[c], &mut self.scratch);
|
||||
for i in 0..GRID {
|
||||
let (k, w) = self.map[i];
|
||||
let power = self.spectra[c][k].norm_sqr() * (1. - w)
|
||||
+ self.spectra[c][k + 1].norm_sqr() * w;
|
||||
self.levels[c][i] = 10. * (power * self.power_scale).max(1e-20).log10();
|
||||
}
|
||||
}
|
||||
let awake = self.sample_power / self.hop as f32 > 1e-9;
|
||||
self.sample_power = 0.;
|
||||
let step = 1000f32.log2() / (GRID - 1) as f32;
|
||||
let radius = (self.settings.neighborhood / step * 0.5).round() as usize;
|
||||
self.target.fill(0.);
|
||||
for c in 0..self.channels {
|
||||
let mut prefix = [0.; GRID + 1];
|
||||
for i in 0..GRID {
|
||||
prefix[i + 1] = prefix[i] + self.levels[c][i];
|
||||
}
|
||||
for i in 0..GRID {
|
||||
let low = i.saturating_sub(radius);
|
||||
let high = (i + radius + 1).min(GRID);
|
||||
let e0 = i.saturating_sub(1).max(low);
|
||||
let e1 = (i + 2).min(high);
|
||||
let count = (high - low) - (e1 - e0);
|
||||
let baseline =
|
||||
(prefix[high] - prefix[low] - (prefix[e1] - prefix[e0])) / count.max(1) as f32;
|
||||
let excess =
|
||||
self.levels[c][i] - baseline + self.curve[i] - self.settings.sensitivity;
|
||||
let target = if awake {
|
||||
knee(excess, self.settings.knee) * self.settings.amount * 0.02
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
self.target[i] = self.target[i].max(target.min(self.settings.max_cut));
|
||||
}
|
||||
}
|
||||
let attack = (-(self.hop as f32) / (self.rate * self.settings.attack * 0.001)).exp();
|
||||
let release = (-(self.hop as f32) / (self.rate * self.settings.release * 0.001)).exp();
|
||||
for i in 0..GRID {
|
||||
let low = i.saturating_sub(self.radius);
|
||||
let high = (i + self.radius + 1).min(GRID);
|
||||
let mut sum = 0.;
|
||||
let mut weight = 0.;
|
||||
for j in low..high {
|
||||
let w = self.kernel[i.abs_diff(j)];
|
||||
sum += self.target[j] * w;
|
||||
weight += w;
|
||||
}
|
||||
let target = sum / weight;
|
||||
let alpha = if target > self.reduction[i] {
|
||||
attack
|
||||
} else {
|
||||
release
|
||||
};
|
||||
self.reduction[i] = alpha * self.reduction[i] + (1. - alpha) * target;
|
||||
if self.reduction[i] < 1e-12 {
|
||||
self.reduction[i] = 0.;
|
||||
}
|
||||
self.frame.reduction[i] = (self.reduction[i]
|
||||
* self.mask[i]
|
||||
* (1. - self.protect * self.settings.transient_guard / 100.))
|
||||
.clamp(0., self.settings.max_cut);
|
||||
self.frame.focus[i] = self.curve[i];
|
||||
self.frame.input[i] = self.levels[0][i].max(if self.channels == 2 {
|
||||
self.levels[1][i]
|
||||
} else {
|
||||
-200.
|
||||
});
|
||||
}
|
||||
for c in 0..self.channels {
|
||||
for k in 0..=self.n / 2 {
|
||||
let (i, w) = self.bin_map[k];
|
||||
let d = self.frame.reduction[i] * (1. - w) + self.frame.reduction[i + 1] * w;
|
||||
let f = k as f32 * self.rate / self.n as f32;
|
||||
let d = if f >= self.settings.low && f <= self.settings.high.min(self.rate * 0.49) {
|
||||
d
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
let g = 10f32.powf(-d / 20.);
|
||||
self.spectra[c][k] *= g;
|
||||
if k > 0 && k < self.n / 2 {
|
||||
self.spectra[c][self.n - k] *= g;
|
||||
}
|
||||
}
|
||||
self.inverse
|
||||
.process_with_scratch(&mut self.spectra[c], &mut self.scratch);
|
||||
// Eight overlaps of a periodic Hann sum to four.
|
||||
for i in 0..self.n {
|
||||
self.output[c][(self.pos + i) % self.n] +=
|
||||
self.spectra[c][i].re * self.window[i] / (self.n as f32 * 4.);
|
||||
}
|
||||
}
|
||||
self.frame.input_peak = self.in_peak;
|
||||
self.frame.output_peak = self.out_peak;
|
||||
self.frame.guard = self.protect;
|
||||
self.frame.sample_rate = self.rate;
|
||||
self.frame.latency = self.n as u32;
|
||||
self.frame.channels = self.channels;
|
||||
self.in_peak = 0.;
|
||||
self.out_peak = 0.;
|
||||
self.fresh = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Stable, host-independent controls. Frequencies are Hz, times milliseconds.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Focus {
|
||||
pub enabled: bool,
|
||||
pub frequency: f32,
|
||||
pub width: f32,
|
||||
pub sensitivity: f32,
|
||||
}
|
||||
impl Default for Focus {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
frequency: 2000.,
|
||||
width: 0.5,
|
||||
sensitivity: 0.,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Settings {
|
||||
pub amount: f32,
|
||||
pub sensitivity: f32,
|
||||
pub max_cut: f32,
|
||||
pub neighborhood: f32,
|
||||
pub cut_width: f32,
|
||||
pub knee: f32,
|
||||
pub attack: f32,
|
||||
pub release: f32,
|
||||
pub transient_guard: f32,
|
||||
pub low: f32,
|
||||
pub high: f32,
|
||||
pub mix: f32,
|
||||
pub output: f32,
|
||||
pub bypass: bool,
|
||||
pub focus: [Focus; 4],
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
amount: 35.,
|
||||
sensitivity: 6.,
|
||||
max_cut: 3.,
|
||||
neighborhood: 1.,
|
||||
cut_width: 0.08,
|
||||
knee: 3.,
|
||||
attack: 15.,
|
||||
release: 120.,
|
||||
transient_guard: 50.,
|
||||
low: 120.,
|
||||
high: 12000.,
|
||||
mix: 100.,
|
||||
output: 0.,
|
||||
bypass: false,
|
||||
focus: [Focus::default(); 4],
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Settings {
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
for (v, low, high) in [
|
||||
(self.amount, 0., 100.),
|
||||
(self.sensitivity, 0., 24.),
|
||||
(self.max_cut, 0., 18.),
|
||||
(self.neighborhood, 0.25, 2.),
|
||||
(self.cut_width, 0.03, 0.5),
|
||||
(self.knee, 0., 12.),
|
||||
(self.attack, 1., 200.),
|
||||
(self.release, 10., 1000.),
|
||||
(self.transient_guard, 0., 100.),
|
||||
(self.low, 20., 20000.),
|
||||
(self.high, 20., 20000.),
|
||||
(self.mix, 0., 100.),
|
||||
(self.output, -12., 12.),
|
||||
] {
|
||||
if !v.is_finite() || !(low..=high).contains(&v) {
|
||||
return Err("Invalid resonance control value");
|
||||
}
|
||||
}
|
||||
if self.low >= self.high {
|
||||
return Err("Low frequency must be below high frequency");
|
||||
}
|
||||
for f in self.focus {
|
||||
if !f.frequency.is_finite()
|
||||
|| !(20. ..=20000.).contains(&f.frequency)
|
||||
|| !f.width.is_finite()
|
||||
|| !(0.05..=2.).contains(&f.width)
|
||||
|| !f.sensitivity.is_finite()
|
||||
|| !(-18. ..=18.).contains(&f.sensitivity)
|
||||
{
|
||||
return Err("Invalid focus control");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub const PRESETS: [&'static str; 4] = [
|
||||
"Gentle cleanup",
|
||||
"Bass whistle",
|
||||
"Snare tail",
|
||||
"Bright melodic layer",
|
||||
];
|
||||
pub fn preset(index: usize) -> Self {
|
||||
let mut s = Self::default();
|
||||
match index {
|
||||
1 => {
|
||||
s.low = 700.;
|
||||
s.high = 10000.;
|
||||
s.sensitivity = 5.;
|
||||
s.max_cut = 6.;
|
||||
s.cut_width = 0.05;
|
||||
s.attack = 8.;
|
||||
}
|
||||
2 => {
|
||||
s.low = 250.;
|
||||
s.high = 6000.;
|
||||
s.attack = 25.;
|
||||
s.release = 180.;
|
||||
s.transient_guard = 85.;
|
||||
s.max_cut = 5.;
|
||||
}
|
||||
3 => {
|
||||
s.low = 1800.;
|
||||
s.high = 15000.;
|
||||
s.sensitivity = 4.;
|
||||
s.max_cut = 4.;
|
||||
s.cut_width = 0.14;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
/// Soft knee on excess prominence, measured in dB.
|
||||
pub fn knee(excess: f32, width: f32) -> f32 {
|
||||
if width <= 0. {
|
||||
excess.max(0.)
|
||||
} else if excess <= -width * 0.5 {
|
||||
0.
|
||||
} else if excess >= width * 0.5 {
|
||||
excess
|
||||
} else {
|
||||
(excess + width * 0.5).powi(2) / (2. * width)
|
||||
}
|
||||
}
|
||||
pub fn focus_offset(f: f32, focus: &[Focus; 4]) -> f32 {
|
||||
focus
|
||||
.iter()
|
||||
.filter(|p| p.enabled)
|
||||
.map(|p| {
|
||||
let z = (f / p.frequency).log2() / p.width;
|
||||
p.sensitivity * (-4. * std::f32::consts::LN_2 * z * z).exp()
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
use patina_core::*;
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
fn noise(i: usize) -> f32 {
|
||||
let x = (i as u32).wrapping_mul(747796405).wrapping_add(2891336453);
|
||||
let word = ((x >> ((x >> 28) + 4)) ^ x).wrapping_mul(277803737);
|
||||
(((word >> 22) ^ word) as f32 / u32::MAX as f32 - 0.5) * 0.1
|
||||
}
|
||||
#[test]
|
||||
fn delayed_identity_and_all_mix_positions_at_all_rates() {
|
||||
for rate in [44100., 48000., 88200., 96000., 176400., 192000.] {
|
||||
for mix in [0., 37., 100.] {
|
||||
let mut e = Engine::new(rate, 2).unwrap();
|
||||
e.set_settings(Settings {
|
||||
amount: 0.,
|
||||
mix,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
let n = e.latency_samples() as usize;
|
||||
let mut error = 0f64;
|
||||
let mut power = 0f64;
|
||||
for i in 0..n * 4 {
|
||||
let x = if i < n * 2 { noise(i) } else { 0. };
|
||||
let y = e.process_sample([x, -x], Monitor::default());
|
||||
let expected = if i >= n && i < n * 3 {
|
||||
noise(i - n)
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
error += (y[0] as f64 - expected as f64).powi(2);
|
||||
power += (expected as f64).powi(2);
|
||||
assert!((y[0] + y[1]).abs() < 1e-6);
|
||||
}
|
||||
assert!(
|
||||
10. * (error / power).max(1e-30).log10() < -100.,
|
||||
"rate {rate}, mix {mix}: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn impulse_latency_delta_and_reset() {
|
||||
let mut e = Engine::new(48000., 1).unwrap();
|
||||
e.set_settings(Settings {
|
||||
amount: 0.,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
let latency = e.latency_samples() as usize;
|
||||
for i in 0..latency * 2 {
|
||||
let y = e.process_sample([if i == 0 { 1. } else { 0. }, 0.], Monitor::default())[0];
|
||||
assert!((y - if i == latency { 1. } else { 0. }).abs() < 1e-6);
|
||||
}
|
||||
e.reset();
|
||||
for _ in 0..latency * 2 {
|
||||
assert_eq!(e.process_sample([0., 0.], Monitor { delta: true }), [0.; 2]);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn resonance_is_local_bounded_and_recovers_in_silence() {
|
||||
let mut e = Engine::new(48000., 2).unwrap();
|
||||
e.set_settings(Settings {
|
||||
amount: 100.,
|
||||
sensitivity: 2.,
|
||||
max_cut: 6.,
|
||||
transient_guard: 0.,
|
||||
attack: 1.,
|
||||
release: 20.,
|
||||
low: 500.,
|
||||
high: 9000.,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
let mut frame = AnalyzerFrame::default();
|
||||
for i in 0..48000 {
|
||||
let x = 0.3 * (TAU * 3000. * i as f32 / 48000.).sin() + noise(i);
|
||||
e.process_sample([x, -x], Monitor::default());
|
||||
if let Some(f) = e.take_analyzer() {
|
||||
frame = f;
|
||||
}
|
||||
}
|
||||
let peak = frame.reduction.iter().copied().fold(0f32, f32::max);
|
||||
assert!(peak > 3. && peak <= 6.);
|
||||
for i in 0..GRID {
|
||||
if frequency(i) < 500. || frequency(i) > 9000. {
|
||||
assert_eq!(frame.reduction[i], 0.);
|
||||
}
|
||||
}
|
||||
let ring = (0..GRID)
|
||||
.min_by(|a, b| {
|
||||
(frequency(*a) - 3000.)
|
||||
.abs()
|
||||
.total_cmp(&(frequency(*b) - 3000.).abs())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(frame.reduction[ring] > 3.);
|
||||
for _ in 0..48000 {
|
||||
e.process_sample([0.; 2], Monitor::default());
|
||||
}
|
||||
let f = e.take_analyzer().unwrap();
|
||||
assert!(f.reduction.iter().all(|d| *d < 0.001));
|
||||
}
|
||||
#[test]
|
||||
fn invalid_settings_do_not_mutate_and_numerical_inputs_stay_finite() {
|
||||
let mut e = Engine::new(48000., 1).unwrap();
|
||||
let before = e.settings();
|
||||
assert!(e
|
||||
.set_settings(Settings {
|
||||
attack: f32::NAN,
|
||||
..before
|
||||
})
|
||||
.is_err());
|
||||
assert_eq!(e.settings(), before);
|
||||
assert!(Engine::new(8000., 2).is_err());
|
||||
for _ in 0..10000 {
|
||||
let y = e.process_sample([f32::NAN, f32::INFINITY], Monitor::default());
|
||||
assert!(y.iter().all(|v| v.is_finite()));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn soft_knee_and_presets_are_valid() {
|
||||
for i in 0..4 {
|
||||
Settings::preset(i).validate().unwrap();
|
||||
}
|
||||
assert_eq!(knee(-2., 3.), 0.);
|
||||
assert_eq!(knee(5., 3.), 5.);
|
||||
assert_eq!(knee(-1., 0.), 0.);
|
||||
let p = Focus {
|
||||
enabled: true,
|
||||
frequency: 2000.,
|
||||
width: 1.,
|
||||
sensitivity: -12.,
|
||||
};
|
||||
assert_eq!(focus_offset(2000., &[p; 4]), -48.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_detector_scales_and_manual_protection_reduces_false_positives() {
|
||||
let s = Settings {
|
||||
amount: 80.,
|
||||
sensitivity: 3.,
|
||||
max_cut: 12.,
|
||||
attack: 1.,
|
||||
transient_guard: 0.,
|
||||
..Default::default()
|
||||
};
|
||||
let mut loud = Engine::new(48000., 1).unwrap();
|
||||
loud.set_settings(s).unwrap();
|
||||
let mut quiet = Engine::new(48000., 1).unwrap();
|
||||
quiet.set_settings(s).unwrap();
|
||||
let mut protected = Engine::new(48000., 1).unwrap();
|
||||
let mut p = s;
|
||||
p.focus[0] = Focus {
|
||||
enabled: true,
|
||||
frequency: 3000.,
|
||||
width: 0.5,
|
||||
sensitivity: -18.,
|
||||
};
|
||||
protected.set_settings(p).unwrap();
|
||||
for i in 0..24000 {
|
||||
let x = 0.3 * (TAU * 3000. * i as f32 / 48000.).sin() + noise(i);
|
||||
loud.process_sample([x, 0.], Monitor::default());
|
||||
quiet.process_sample([x * 0.1, 0.], Monitor::default());
|
||||
protected.process_sample([x, 0.], Monitor::default());
|
||||
}
|
||||
let a = loud.take_analyzer().unwrap();
|
||||
let b = quiet.take_analyzer().unwrap();
|
||||
let c = protected.take_analyzer().unwrap();
|
||||
for i in 0..GRID {
|
||||
assert!((a.reduction[i] - b.reduction[i]).abs() < 0.02);
|
||||
}
|
||||
let k = (0..GRID)
|
||||
.min_by(|a, b| {
|
||||
(frequency(*a) - 3000.)
|
||||
.abs()
|
||||
.total_cmp(&(frequency(*b) - 3000.).abs())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(c.reduction[k] < a.reduction[k] - 1.);
|
||||
}
|
||||
#[test]
|
||||
fn settled_delta_and_bypass_have_precise_taps() {
|
||||
let s = Settings {
|
||||
attack: 1.,
|
||||
transient_guard: 0.,
|
||||
..Default::default()
|
||||
};
|
||||
let mut wet = Engine::new(48000., 1).unwrap();
|
||||
wet.set_settings(s).unwrap();
|
||||
let mut delta = Engine::new(48000., 1).unwrap();
|
||||
delta.set_settings(s).unwrap();
|
||||
let mut bypass = Engine::new(48000., 1).unwrap();
|
||||
bypass.set_settings(Settings { bypass: true, ..s }).unwrap();
|
||||
let latency = wet.latency_samples() as usize;
|
||||
for i in 0..24000 {
|
||||
let x = noise(i);
|
||||
let a = wet.process_sample([x, 0.], Monitor::default())[0];
|
||||
let b = delta.process_sample([x, 0.], Monitor { delta: true })[0];
|
||||
let c = bypass.process_sample([x, 0.], Monitor::default())[0];
|
||||
if i > 12000 {
|
||||
let expected = noise(i - latency);
|
||||
assert!((a + b - expected).abs() < 1e-5);
|
||||
assert!((c - expected).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use patina_core::{Engine, Monitor, Settings};
|
||||
use std::{
|
||||
alloc::{GlobalAlloc, Layout, System},
|
||||
cell::Cell,
|
||||
};
|
||||
|
||||
struct CheckedAllocator;
|
||||
thread_local! {
|
||||
static CHECK:Cell<bool>=const {Cell::new(false)};
|
||||
static OPERATIONS:Cell<usize>=const {Cell::new(0)};
|
||||
}
|
||||
fn record() {
|
||||
if CHECK.try_with(Cell::get).unwrap_or(false) {
|
||||
let _ = OPERATIONS.try_with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
}
|
||||
unsafe impl GlobalAlloc for CheckedAllocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
record();
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
|
||||
record();
|
||||
unsafe { System.dealloc(pointer, layout) }
|
||||
}
|
||||
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
|
||||
record();
|
||||
unsafe { System.realloc(pointer, layout, size) }
|
||||
}
|
||||
}
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: CheckedAllocator = CheckedAllocator;
|
||||
|
||||
#[test]
|
||||
fn processing_automation_and_analysis_do_not_allocate_or_free() {
|
||||
let mut engine = Engine::new(48000., 2).unwrap();
|
||||
let mut settings = Settings::preset(1);
|
||||
engine.set_settings(settings).unwrap();
|
||||
CHECK.with(|v| v.set(true));
|
||||
for i in 0..48000 {
|
||||
if i % 512 == 0 {
|
||||
settings.focus[0].enabled = true;
|
||||
settings.focus[0].frequency = 1000. + (i % 10000) as f32;
|
||||
settings.focus[0].sensitivity = 6.;
|
||||
settings.low = 120. + (i % 100) as f32;
|
||||
engine.set_settings(settings).unwrap();
|
||||
}
|
||||
std::hint::black_box(engine.process_sample([0.3, -0.2], Monitor { delta: i > 24000 }));
|
||||
std::hint::black_box(engine.take_analyzer());
|
||||
}
|
||||
engine.reset();
|
||||
CHECK.with(|v| v.set(false));
|
||||
assert_eq!(OPERATIONS.with(Cell::get), 0);
|
||||
}
|
||||
+29
-29
@@ -1410,6 +1410,35 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "patina"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"crossbeam-queue",
|
||||
"nih_plug",
|
||||
"nih_plug_egui",
|
||||
"patina-core",
|
||||
"patina-ui",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "patina-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"rustfft",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "patina-ui"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"patina-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
@@ -1561,35 +1590,6 @@ dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "resonance-compressor"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"crossbeam-queue",
|
||||
"nih_plug",
|
||||
"nih_plug_egui",
|
||||
"resonance-core",
|
||||
"resonance-ui",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "resonance-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"rustfft",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "resonance-ui"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"resonance-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-demangle"
|
||||
version = "0.1.28"
|
||||
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "resonance-compressor"
|
||||
name = "patina"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
@@ -12,8 +12,8 @@ crate-type = ["cdylib", "rlib"]
|
||||
[dependencies]
|
||||
nih_plug = { git = "https://github.com/robbert-vdh/nih-plug.git", rev = "de421011f41a6d10fc8c7a6084e4f4dee0143683", default-features = false }
|
||||
nih_plug_egui = { git = "https://github.com/robbert-vdh/nih-plug.git", rev = "de421011f41a6d10fc8c7a6084e4f4dee0143683" }
|
||||
resonance-core = { path = "../../crates/resonance-core" }
|
||||
resonance-ui = { path = "../../crates/resonance-ui" }
|
||||
patina-core = { path = "../core" }
|
||||
patina-ui = { path = "../ui" }
|
||||
crossbeam-queue = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
@@ -3,8 +3,8 @@ mod params;
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use nih_plug::prelude::*;
|
||||
use nih_plug_egui::{create_egui_editor, egui};
|
||||
use params::{values, ResonanceParams};
|
||||
use resonance_core::{AnalyzerFrame, Engine, Monitor};
|
||||
use params::{values, PatinaParams};
|
||||
use patina_core::{AnalyzerFrame, Engine, Monitor};
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
Arc,
|
||||
@@ -15,17 +15,17 @@ struct Shared {
|
||||
delta: AtomicBool,
|
||||
reset: AtomicU64,
|
||||
}
|
||||
pub struct ResonanceCompressor {
|
||||
params: Arc<ResonanceParams>,
|
||||
pub struct Patina {
|
||||
params: Arc<PatinaParams>,
|
||||
shared: Arc<Shared>,
|
||||
engine: Option<Engine>,
|
||||
publish_count: usize,
|
||||
publish_interval: usize,
|
||||
}
|
||||
impl Default for ResonanceCompressor {
|
||||
impl Default for Patina {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
params: Arc::new(ResonanceParams::default()),
|
||||
params: Arc::new(PatinaParams::default()),
|
||||
shared: Arc::new(Shared {
|
||||
analyzer: ArrayQueue::new(3),
|
||||
delta: AtomicBool::new(false),
|
||||
@@ -37,9 +37,9 @@ impl Default for ResonanceCompressor {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Plugin for ResonanceCompressor {
|
||||
const NAME: &'static str = "Resonance Compressor";
|
||||
const VENDOR: &'static str = "Storyboard";
|
||||
impl Plugin for Patina {
|
||||
const NAME: &'static str = "Patina";
|
||||
const VENDOR: &'static str = "Rivet & Patina";
|
||||
const URL: &'static str = "";
|
||||
const EMAIL: &'static str = "";
|
||||
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
@@ -66,10 +66,10 @@ impl Plugin for ResonanceCompressor {
|
||||
let shared = self.shared.clone();
|
||||
create_egui_editor(
|
||||
params.editor.clone(),
|
||||
resonance_ui::State::default(),
|
||||
patina_ui::State::default(),
|
||||
|ctx, state| {
|
||||
state.delta = false;
|
||||
resonance_ui::style(ctx);
|
||||
patina_ui::style(ctx);
|
||||
},
|
||||
move |ctx, setter, state| {
|
||||
let epoch = shared.reset.load(Ordering::Acquire);
|
||||
@@ -87,7 +87,7 @@ impl Plugin for ResonanceCompressor {
|
||||
nih_plug_egui::resizable_window::ResizableWindow::new("resonance-editor")
|
||||
.min_size(egui::vec2(1040., 700.))
|
||||
.show(ctx, ¶ms.editor, |ui| {
|
||||
resonance_ui::show(ui, &mut edited, state)
|
||||
patina_ui::show(ui, &mut edited, state)
|
||||
});
|
||||
let old = values(&before);
|
||||
let new = values(&edited);
|
||||
@@ -186,7 +186,7 @@ fn state_epoch(ctx: &egui::Context) -> u64 {
|
||||
fn store_epoch(ctx: &egui::Context, e: u64) {
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::new("reset-epoch"), e));
|
||||
}
|
||||
impl ClapPlugin for ResonanceCompressor {
|
||||
impl ClapPlugin for Patina {
|
||||
const CLAP_ID: &'static str = "io.storyboard.resonance-compressor";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> =
|
||||
Some("Dynamic resonance attenuation with explicit tone protection");
|
||||
@@ -199,4 +199,4 @@ impl ClapPlugin for ResonanceCompressor {
|
||||
ClapFeature::Mono,
|
||||
];
|
||||
}
|
||||
nih_export_clap!(ResonanceCompressor);
|
||||
nih_export_clap!(Patina);
|
||||
@@ -1,6 +1,6 @@
|
||||
use nih_plug::prelude::*;
|
||||
use nih_plug_egui::EguiState;
|
||||
use resonance_core::{Focus, Settings};
|
||||
use patina_core::{Focus, Settings};
|
||||
use std::sync::Arc;
|
||||
#[derive(Params)]
|
||||
pub struct FocusParams {
|
||||
@@ -39,7 +39,7 @@ impl Default for FocusParams {
|
||||
}
|
||||
}
|
||||
#[derive(Params)]
|
||||
pub struct ResonanceParams {
|
||||
pub struct PatinaParams {
|
||||
#[persist = "editor"]
|
||||
pub editor: Arc<EguiState>,
|
||||
#[id = "amount"]
|
||||
@@ -73,7 +73,7 @@ pub struct ResonanceParams {
|
||||
#[nested(array, group = "Focus")]
|
||||
pub focus: [FocusParams; 4],
|
||||
}
|
||||
impl Default for ResonanceParams {
|
||||
impl Default for PatinaParams {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
editor: EguiState::from_size(1180, 760),
|
||||
@@ -95,7 +95,7 @@ impl Default for ResonanceParams {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ResonanceParams {
|
||||
impl PatinaParams {
|
||||
pub fn floats(&self) -> [&FloatParam; 29] {
|
||||
[
|
||||
&self.amount,
|
||||
@@ -49,8 +49,8 @@ fn effect_ports_state_latency_and_audio_lifecycle() {
|
||||
// SAFETY: All callbacks, strings, streams, buffers, and the host outlive their
|
||||
// synchronous ABI calls. Activation/processing/destruction follow CLAP order.
|
||||
unsafe {
|
||||
let entry = &resonance_compressor::clap_entry;
|
||||
assert!(entry.init.unwrap()(c"resonance-compressor.clap".as_ptr()));
|
||||
let entry = &patina::clap_entry;
|
||||
assert!(entry.init.unwrap()(c"patina.clap".as_ptr()));
|
||||
let factory = entry.get_factory.unwrap()(CLAP_PLUGIN_FACTORY_ID.as_ptr())
|
||||
as *const clap_plugin_factory;
|
||||
assert!(!factory.is_null());
|
||||
@@ -58,6 +58,7 @@ fn effect_ports_state_latency_and_audio_lifecycle() {
|
||||
assert_eq!(factory.get_plugin_count.unwrap()(factory), 1);
|
||||
let descriptor = factory.get_plugin_descriptor.unwrap()(factory, 0);
|
||||
assert!(!descriptor.is_null());
|
||||
assert_eq!(CStr::from_ptr((*descriptor).name), c"Patina");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.storyboard.resonance-compressor"
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "patina-render"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
[dependencies]
|
||||
patina-core = { path = "../core" }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Bounded offline evaluation: PCM16/24/32 and IEEE float32 RIFF/WAVE input.
|
||||
use patina_core::{Engine, Monitor, Settings};
|
||||
use std::{
|
||||
env, fs,
|
||||
io::{Read, Write},
|
||||
path::Path,
|
||||
time::Instant,
|
||||
};
|
||||
fn main() {
|
||||
if let Err(e) = run() {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<_> = env::args().skip(1).collect();
|
||||
if args.is_empty() || args[0] == "--help" {
|
||||
println!("patina-render <input.wav> <output.wav> [settings.json] [--delta]\npatina-render --demo <output.wav>\npatina-render --benchmark\nOutput is float32 WAV, latency-trimmed with original length. Existing files are refused.");
|
||||
return Ok(());
|
||||
}
|
||||
if args[0] == "--benchmark" {
|
||||
let mut e = Engine::new(48000., 2)?;
|
||||
e.set_settings(Settings::preset(1))?;
|
||||
let frames = 48000 * 5;
|
||||
let start = Instant::now();
|
||||
for i in 0..frames {
|
||||
let x = (i as f32 * 0.173).sin() * 0.3;
|
||||
std::hint::black_box(e.process_sample([x, -x], Monitor::default()));
|
||||
}
|
||||
println!("Stereo 48 kHz / FFT 4096 / hop 512 / 5 seconds: {:.3}s ({:.1}% of one core, run --release for meaningful results)",start.elapsed().as_secs_f64(),start.elapsed().as_secs_f64()/5.*100.);
|
||||
return Ok(());
|
||||
}
|
||||
let (rate, channels, input, output) = if args[0] == "--demo" && args.len() == 2 {
|
||||
let samples = (0..48000 * 3)
|
||||
.map(|i| {
|
||||
let t = i as f32 / 48000.;
|
||||
let envelope = if t % 0.5 < 0.3 { 1. } else { 0.2 };
|
||||
[((t * 440. * std::f32::consts::TAU).sin() * 0.14
|
||||
+ (t * 3000. * std::f32::consts::TAU).sin() * 0.28)
|
||||
* envelope; 2]
|
||||
})
|
||||
.collect();
|
||||
(48000., 2, samples, args[1].clone())
|
||||
} else if args.len() >= 2 {
|
||||
let (r, c, x) = read_wave(Path::new(&args[0]))?;
|
||||
(r, c, x, args[1].clone())
|
||||
} else {
|
||||
return Err("Use --help for usage".into());
|
||||
};
|
||||
let settings = if args.get(2).is_some_and(|s| !s.starts_with("--")) {
|
||||
let bytes = read_limit(Path::new(&args[2]), 64 * 1024)?;
|
||||
serde_json::from_slice::<Settings>(&bytes)?
|
||||
} else {
|
||||
Settings::default()
|
||||
};
|
||||
settings.validate()?;
|
||||
let mut engine = Engine::new(rate, channels)?;
|
||||
engine.set_settings(settings)?;
|
||||
let latency = engine.latency_samples() as usize;
|
||||
let start = Instant::now();
|
||||
let mut rendered = Vec::with_capacity(input.len());
|
||||
let monitor = Monitor {
|
||||
delta: args.iter().any(|a| a == "--delta"),
|
||||
};
|
||||
for i in 0..input.len() + latency {
|
||||
let sample = input.get(i).copied().unwrap_or([0.; 2]);
|
||||
let out = engine.process_sample(sample, monitor);
|
||||
if i >= latency {
|
||||
rendered.push(out);
|
||||
}
|
||||
}
|
||||
write_wave(Path::new(&output), rate as u32, channels, &rendered)?;
|
||||
println!(
|
||||
"Rendered {} frames, {} channel(s), {} Hz in {:.3}s; compensated {} samples → {}",
|
||||
rendered.len(),
|
||||
channels,
|
||||
rate,
|
||||
start.elapsed().as_secs_f64(),
|
||||
latency,
|
||||
output
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn read_limit(path: &Path, limit: usize) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
|
||||
let mut bytes = Vec::new();
|
||||
fs::File::open(path)?
|
||||
.take(limit as u64 + 1)
|
||||
.read_to_end(&mut bytes)?;
|
||||
if bytes.len() > limit {
|
||||
return Err("Input exceeds size limit".into());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
type Wave = (f32, usize, Vec<[f32; 2]>);
|
||||
fn read_wave(path: &Path) -> Result<Wave, Box<dyn std::error::Error>> {
|
||||
let b = read_limit(path, 256 * 1024 * 1024)?;
|
||||
if b.len() < 12 || &b[..4] != b"RIFF" || &b[8..12] != b"WAVE" {
|
||||
return Err("Expected RIFF/WAVE".into());
|
||||
}
|
||||
let u16_at = |p| u16::from_le_bytes([b[p], b[p + 1]]);
|
||||
let u32_at = |p| u32::from_le_bytes([b[p], b[p + 1], b[p + 2], b[p + 3]]);
|
||||
let end = (u32_at(4) as usize)
|
||||
.checked_add(8)
|
||||
.ok_or("Invalid RIFF length")?;
|
||||
if end > b.len() {
|
||||
return Err("Truncated RIFF container".into());
|
||||
}
|
||||
let mut pos = 12;
|
||||
let mut format = None;
|
||||
let mut data = None;
|
||||
while pos + 8 <= end {
|
||||
let len = u32_at(pos + 4) as usize;
|
||||
let start = pos + 8;
|
||||
let stop = start.checked_add(len).ok_or("Invalid chunk length")?;
|
||||
if stop > end {
|
||||
return Err("Truncated WAV chunk".into());
|
||||
}
|
||||
match &b[pos..pos + 4] {
|
||||
b"fmt " if len >= 16 => {
|
||||
format = Some((
|
||||
u16_at(start),
|
||||
u16_at(start + 2) as usize,
|
||||
u32_at(start + 4),
|
||||
u16_at(start + 12) as usize,
|
||||
u16_at(start + 14) as usize,
|
||||
))
|
||||
}
|
||||
b"data" => data = Some((start, stop)),
|
||||
_ => {}
|
||||
}
|
||||
pos = stop + (len % 2);
|
||||
}
|
||||
let (tag, channels, rate, align, bits) = format.ok_or("Missing WAV format")?;
|
||||
let (start, stop) = data.ok_or("Missing WAV data")?;
|
||||
if !(1..=2).contains(&channels) || !matches!((tag, bits), (1, 16) | (1, 24) | (1, 32) | (3, 32))
|
||||
{
|
||||
return Err("Use mono/stereo PCM16/24/32 or float32 WAV".into());
|
||||
}
|
||||
let size = bits / 8;
|
||||
if align != channels * size || (stop - start) % align != 0 {
|
||||
return Err("Invalid WAV block alignment".into());
|
||||
}
|
||||
let mut samples = Vec::with_capacity((stop - start) / align);
|
||||
for p in (start..stop).step_by(align) {
|
||||
let mut frame = [0.; 2];
|
||||
for (c, value) in frame.iter_mut().enumerate().take(channels) {
|
||||
let q = p + c * size;
|
||||
*value = match (tag, bits) {
|
||||
(3, 32) => f32::from_le_bytes(b[q..q + 4].try_into()?),
|
||||
(1, 16) => i16::from_le_bytes(b[q..q + 2].try_into()?) as f32 / 32768.,
|
||||
(1, 24) => {
|
||||
((b[q] as i32 | ((b[q + 1] as i32) << 8) | ((b[q + 2] as i32) << 16)) << 8 >> 8)
|
||||
as f32
|
||||
/ 8388608.
|
||||
}
|
||||
_ => i32::from_le_bytes(b[q..q + 4].try_into()?) as f32 / 2147483648.,
|
||||
};
|
||||
if !value.is_finite() {
|
||||
return Err("Non-finite WAV samples".into());
|
||||
}
|
||||
}
|
||||
samples.push(frame);
|
||||
}
|
||||
Ok((rate as f32, channels, samples))
|
||||
}
|
||||
fn write_wave(
|
||||
path: &Path,
|
||||
rate: u32,
|
||||
channels: usize,
|
||||
samples: &[[f32; 2]],
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let bytes = (samples.len() * channels * 4) as u32;
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)?;
|
||||
f.write_all(b"RIFF")?;
|
||||
f.write_all(&(36 + bytes).to_le_bytes())?;
|
||||
f.write_all(b"WAVEfmt ")?;
|
||||
f.write_all(&16u32.to_le_bytes())?;
|
||||
f.write_all(&3u16.to_le_bytes())?;
|
||||
f.write_all(&(channels as u16).to_le_bytes())?;
|
||||
f.write_all(&rate.to_le_bytes())?;
|
||||
f.write_all(&(rate * channels as u32 * 4).to_le_bytes())?;
|
||||
f.write_all(&(channels as u16 * 4).to_le_bytes())?;
|
||||
f.write_all(&32u16.to_le_bytes())?;
|
||||
f.write_all(b"data")?;
|
||||
f.write_all(&bytes.to_le_bytes())?;
|
||||
for frame in samples {
|
||||
for sample in frame.iter().take(channels) {
|
||||
f.write_all(&sample.to_le_bytes())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "patina-ui"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
[dependencies]
|
||||
egui = "0.31.1"
|
||||
patina-core = { path = "../core" }
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2011 The Roboto Project Authors (https://github.com/googlefonts/roboto-classic)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,906 @@
|
||||
//! Shared native editor, also exercised by the headless renderer.
|
||||
use egui::{self, Color32, FontId, Pos2, Rect, RichText, Sense, Stroke, Vec2};
|
||||
use patina_core::{focus_offset, frequency, AnalyzerFrame, Focus, Settings, GRID};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const BG: Color32 = Color32::from_rgb(23, 20, 31);
|
||||
const PANEL: Color32 = Color32::from_rgb(37, 33, 49);
|
||||
const TEXT: Color32 = Color32::from_rgb(238, 234, 245);
|
||||
const MUTED: Color32 = Color32::from_rgb(161, 151, 179);
|
||||
const CYAN: Color32 = Color32::from_rgb(102, 215, 230);
|
||||
const CORAL: Color32 = Color32::from_rgb(255, 136, 125);
|
||||
const VIOLET: Color32 = Color32::from_rgb(174, 154, 247);
|
||||
pub fn style(ctx: &egui::Context) {
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
fonts.font_data.insert(
|
||||
"regular".into(),
|
||||
egui::FontData::from_static(include_bytes!("../assets/RobotoCondensed-Regular.ttf")).into(),
|
||||
);
|
||||
fonts.font_data.insert(
|
||||
"medium".into(),
|
||||
egui::FontData::from_static(include_bytes!("../assets/RobotoCondensed-Medium.ttf")).into(),
|
||||
);
|
||||
fonts
|
||||
.families
|
||||
.get_mut(&egui::FontFamily::Proportional)
|
||||
.unwrap()
|
||||
.insert(0, "regular".into());
|
||||
fonts.families.insert(
|
||||
egui::FontFamily::Name("medium".into()),
|
||||
vec![
|
||||
"medium".into(),
|
||||
"Ubuntu-Light".into(),
|
||||
"NotoEmoji-Regular".into(),
|
||||
"emoji-icon-font".into(),
|
||||
],
|
||||
);
|
||||
ctx.set_fonts(fonts);
|
||||
let mut s = (*ctx.style()).clone();
|
||||
s.visuals = egui::Visuals::dark();
|
||||
s.visuals.panel_fill = BG;
|
||||
s.visuals.window_fill = PANEL;
|
||||
s.visuals.override_text_color = Some(TEXT);
|
||||
s.visuals.selection.bg_fill = Color32::from_rgb(80, 64, 112);
|
||||
s.visuals.widgets.inactive.bg_fill = PANEL;
|
||||
s.visuals.widgets.hovered.bg_fill = Color32::from_rgb(62, 50, 80);
|
||||
s.visuals.widgets.active.bg_fill = Color32::from_rgb(81, 58, 102);
|
||||
s.spacing.item_spacing = Vec2::new(10., 8.);
|
||||
s.spacing.button_padding = Vec2::new(12., 6.);
|
||||
s.text_styles
|
||||
.insert(egui::TextStyle::Body, FontId::proportional(16.));
|
||||
s.text_styles
|
||||
.insert(egui::TextStyle::Button, FontId::proportional(16.));
|
||||
ctx.set_style(s);
|
||||
}
|
||||
pub struct State {
|
||||
pub delta: bool,
|
||||
pub selected: Option<usize>,
|
||||
pub preset: usize,
|
||||
pub snapshots: [Settings; 2],
|
||||
pub active: usize,
|
||||
pub analyzer: AnalyzerFrame,
|
||||
pub gesture_active: bool,
|
||||
pub gestures: [bool; 30],
|
||||
last_audio: Instant,
|
||||
pub help: String,
|
||||
drag: Option<usize>,
|
||||
}
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
delta: false,
|
||||
selected: None,
|
||||
preset: 0,
|
||||
snapshots: [Settings::default(); 2],
|
||||
active: 0,
|
||||
analyzer: AnalyzerFrame::default(),
|
||||
gesture_active: false,
|
||||
gestures: [false; 30],
|
||||
last_audio: Instant::now(),
|
||||
help: "Focus a troublesome region, then compare in the full mix.".into(),
|
||||
drag: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl State {
|
||||
pub fn accept_frame(&mut self, frame: AnalyzerFrame) {
|
||||
// Display-only smoothing; it never feeds the detector.
|
||||
for i in 0..GRID {
|
||||
self.analyzer.input[i] += 0.45 * (frame.input[i] - self.analyzer.input[i]);
|
||||
self.analyzer.reduction[i] += 0.5 * (frame.reduction[i] - self.analyzer.reduction[i]);
|
||||
}
|
||||
self.analyzer.focus = frame.focus;
|
||||
self.analyzer.input_peak = frame.input_peak;
|
||||
self.analyzer.output_peak = frame.output_peak;
|
||||
self.analyzer.guard = frame.guard;
|
||||
self.analyzer.sample_rate = frame.sample_rate;
|
||||
self.analyzer.latency = frame.latency;
|
||||
self.analyzer.channels = frame.channels;
|
||||
if frame.input_peak > 1e-6
|
||||
|| frame.output_peak > 1e-6
|
||||
|| frame.reduction.iter().any(|v| *v > 0.001)
|
||||
{
|
||||
self.last_audio = Instant::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
fn db(x: f32) -> f32 {
|
||||
20. * x.max(1e-6).log10()
|
||||
}
|
||||
fn note(ui: &mut egui::Ui, text: &str) {
|
||||
ui.label(RichText::new(text).color(MUTED));
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)] // Explicit widget metadata keeps the control table readable.
|
||||
fn control(
|
||||
ui: &mut egui::Ui,
|
||||
name: &str,
|
||||
value: &mut f32,
|
||||
range: std::ops::RangeInclusive<f32>,
|
||||
unit: &str,
|
||||
log: bool,
|
||||
help: &str,
|
||||
state: &mut State,
|
||||
) {
|
||||
ui.vertical(|ui| {
|
||||
ui.label(RichText::new(name).color(TEXT));
|
||||
let previous = *value;
|
||||
let response = ui.add(
|
||||
egui::Slider::new(value, range)
|
||||
.logarithmic(log)
|
||||
.suffix(unit)
|
||||
.clamping(egui::SliderClamping::Always)
|
||||
.smart_aim(false),
|
||||
);
|
||||
if response.dragged() && ui.input(|i| i.modifiers.shift) {
|
||||
*value = previous + (*value - previous) * 0.1;
|
||||
}
|
||||
if response.double_clicked() {
|
||||
let defaults = Settings::default();
|
||||
*value = match name {
|
||||
"Amount" => defaults.amount,
|
||||
"Sensitivity" => defaults.sensitivity,
|
||||
"Max cut" => defaults.max_cut,
|
||||
"Transient guard" => defaults.transient_guard,
|
||||
"Attack" => defaults.attack,
|
||||
"Release" => defaults.release,
|
||||
"Neighborhood" => defaults.neighborhood,
|
||||
"Cut width" => defaults.cut_width,
|
||||
"Knee" => defaults.knee,
|
||||
"Low frequency" => defaults.low,
|
||||
"High frequency" => defaults.high,
|
||||
"Mix" => defaults.mix,
|
||||
_ => *value,
|
||||
};
|
||||
}
|
||||
if response.hovered() || response.has_focus() {
|
||||
state.help = help.into();
|
||||
}
|
||||
});
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn rotary(
|
||||
ui: &mut egui::Ui,
|
||||
name: &str,
|
||||
value: &mut f32,
|
||||
range: std::ops::RangeInclusive<f32>,
|
||||
default: f32,
|
||||
unit: &str,
|
||||
size: f32,
|
||||
color: Color32,
|
||||
) {
|
||||
let low = *range.start();
|
||||
let high = *range.end();
|
||||
let (rect, response) = ui.allocate_exact_size(Vec2::splat(size), Sense::click_and_drag());
|
||||
if response.drag_started() {
|
||||
response.request_focus();
|
||||
}
|
||||
if response.dragged() {
|
||||
let delta = ui.input(|i| i.pointer.delta().y);
|
||||
let fine = if ui.input(|i| i.modifiers.shift) {
|
||||
0.1
|
||||
} else {
|
||||
1.
|
||||
};
|
||||
*value = (*value - delta * (high - low) / 180. * fine).clamp(low, high);
|
||||
}
|
||||
if response.double_clicked() {
|
||||
*value = default;
|
||||
}
|
||||
if response.has_focus() {
|
||||
let step = if ui.input(|i| i.modifiers.shift) {
|
||||
0.1
|
||||
} else {
|
||||
1.
|
||||
};
|
||||
if ui.input(|i| i.key_pressed(egui::Key::ArrowUp) || i.key_pressed(egui::Key::ArrowRight)) {
|
||||
*value = (*value + step).min(high);
|
||||
}
|
||||
if ui.input(|i| i.key_pressed(egui::Key::ArrowDown) || i.key_pressed(egui::Key::ArrowLeft))
|
||||
{
|
||||
*value = (*value - step).max(low);
|
||||
}
|
||||
}
|
||||
let center = rect.center();
|
||||
let radius = size * 0.45;
|
||||
let p = ui.painter();
|
||||
p.circle_filled(
|
||||
center + Vec2::new(0., 3.),
|
||||
radius,
|
||||
Color32::from_black_alpha(90),
|
||||
);
|
||||
p.circle_filled(center, radius, Color32::from_rgb(20, 18, 29));
|
||||
p.circle_stroke(
|
||||
center,
|
||||
radius,
|
||||
Stroke::new(1.0_f32, Color32::from_rgb(74, 65, 90)),
|
||||
);
|
||||
p.circle_filled(center, radius - 6., Color32::from_rgb(43, 37, 56));
|
||||
p.circle_stroke(
|
||||
center,
|
||||
radius - 7.,
|
||||
Stroke::new(1.0_f32, Color32::from_rgb(60, 51, 77)),
|
||||
);
|
||||
let start = std::f32::consts::PI * 0.75;
|
||||
let span = std::f32::consts::PI * 1.5;
|
||||
let normalized = (*value - low) / (high - low);
|
||||
for (fraction, stroke) in [
|
||||
(1., Stroke::new(3.0_f32, Color32::from_rgb(59, 49, 76))),
|
||||
(normalized, Stroke::new(3.0_f32, color)),
|
||||
] {
|
||||
let points: Vec<_> = (0..=64)
|
||||
.map(|i| {
|
||||
let a = start + span * fraction * i as f32 / 64.;
|
||||
center + Vec2::angled(a) * (radius - 3.)
|
||||
})
|
||||
.collect();
|
||||
p.add(egui::Shape::line(points, stroke));
|
||||
}
|
||||
let angle = start + span * normalized;
|
||||
p.line_segment(
|
||||
[
|
||||
center + Vec2::angled(angle) * (radius - 14.),
|
||||
center + Vec2::angled(angle) * (radius - 8.),
|
||||
],
|
||||
Stroke::new(2.0_f32, color),
|
||||
);
|
||||
p.text(
|
||||
center,
|
||||
egui::Align2::CENTER_CENTER,
|
||||
format!("{:.0}{}", *value, unit),
|
||||
FontId::proportional(if size > 100. { 25. } else { 18. }),
|
||||
color,
|
||||
);
|
||||
if response.has_focus() {
|
||||
p.circle_stroke(center, radius + 2., Stroke::new(1.0_f32, TEXT));
|
||||
}
|
||||
ui.label(
|
||||
RichText::new(name)
|
||||
.size(if size > 100. { 20. } else { 17. })
|
||||
.color(TEXT),
|
||||
);
|
||||
ui.add(
|
||||
egui::DragValue::new(value)
|
||||
.range(range)
|
||||
.speed(0.1)
|
||||
.suffix(unit),
|
||||
);
|
||||
}
|
||||
pub fn show(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
|
||||
ui.spacing_mut().slider_width = ((ui.available_width() - 100.) / 4. - 85.).max(95.);
|
||||
let before = *settings;
|
||||
ui.horizontal(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.label(
|
||||
RichText::new("Patina")
|
||||
.font(FontId::new(30., egui::FontFamily::Name("medium".into()))),
|
||||
);
|
||||
note(ui, "Keep the character. Control the ring.");
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.checkbox(&mut settings.bypass, "Bypass");
|
||||
if ui
|
||||
.selectable_label(
|
||||
state.delta,
|
||||
RichText::new("Delta").color(if state.delta { CORAL } else { TEXT }),
|
||||
)
|
||||
.on_hover_text("Hear delayed dry minus wet, before output trim.")
|
||||
.clicked()
|
||||
{
|
||||
state.delta = !state.delta;
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button("Copy A to B").clicked() {
|
||||
state.snapshots[state.active] = *settings;
|
||||
state.snapshots[1] = state.snapshots[0];
|
||||
if state.active == 1 {
|
||||
*settings = state.snapshots[1];
|
||||
}
|
||||
}
|
||||
for i in (0..2).rev() {
|
||||
if ui
|
||||
.selectable_label(state.active == i, if i == 0 { "A" } else { "B" })
|
||||
.clicked()
|
||||
&& state.active != i
|
||||
{
|
||||
state.snapshots[state.active] = *settings;
|
||||
*settings = state.snapshots[i];
|
||||
state.active = i;
|
||||
}
|
||||
}
|
||||
egui::ComboBox::from_id_salt("resonance-preset")
|
||||
.selected_text(
|
||||
(0..4)
|
||||
.find(|i| *settings == Settings::preset(*i))
|
||||
.map_or("Custom settings", |i| Settings::PRESETS[i]),
|
||||
)
|
||||
.width(155.)
|
||||
.show_ui(ui, |ui| {
|
||||
for (i, name) in Settings::PRESETS.iter().enumerate() {
|
||||
if ui.selectable_value(&mut state.preset, i, *name).clicked() {
|
||||
*settings = Settings::preset(i);
|
||||
state.delta = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(8.);
|
||||
ui.horizontal(|ui| {
|
||||
let input = db(state.analyzer.input_peak);
|
||||
let output = db(state.analyzer.output_peak);
|
||||
ui.label(RichText::new(format!("Input {input:>5.1} dBFS")).color(CYAN));
|
||||
ui.label(
|
||||
RichText::new(format!("Output {output:>5.1} dBFS")).color(if output >= 0. {
|
||||
CORAL
|
||||
} else {
|
||||
TEXT
|
||||
}),
|
||||
);
|
||||
let max = state
|
||||
.analyzer
|
||||
.reduction
|
||||
.iter()
|
||||
.copied()
|
||||
.fold(0f32, f32::max);
|
||||
ui.label(RichText::new(format!("Reduction {max:.1} dB")).color(CORAL));
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
"Transient guard {:.0}%",
|
||||
state.analyzer.guard * 100.
|
||||
))
|
||||
.color(MUTED),
|
||||
);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
note(
|
||||
ui,
|
||||
&format!(
|
||||
"{:.1} ms latency • {}",
|
||||
state.analyzer.latency as f32 / state.analyzer.sample_rate * 1000.,
|
||||
if state.analyzer.channels == 1 {
|
||||
"Mono"
|
||||
} else {
|
||||
"Stereo linked"
|
||||
}
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
ui.add_space(6.);
|
||||
let body_height = (ui.available_height() - 35.).max(500.);
|
||||
ui.horizontal_top(|ui| {
|
||||
egui::Frame::new()
|
||||
.fill(PANEL)
|
||||
.corner_radius(8.)
|
||||
.inner_margin(14.)
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(156.);
|
||||
ui.set_min_height(body_height - 28.);
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(4.);
|
||||
rotary(
|
||||
ui,
|
||||
"Amount",
|
||||
&mut settings.amount,
|
||||
0. ..=100.,
|
||||
35.,
|
||||
" %",
|
||||
126.,
|
||||
CYAN,
|
||||
);
|
||||
ui.add_space(8.);
|
||||
ui.separator();
|
||||
ui.add_space(12.);
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.set_width(72.);
|
||||
rotary(
|
||||
ui,
|
||||
"Mix",
|
||||
&mut settings.mix,
|
||||
0. ..=100.,
|
||||
100.,
|
||||
" %",
|
||||
64.,
|
||||
VIOLET,
|
||||
);
|
||||
});
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.set_width(72.);
|
||||
rotary(
|
||||
ui,
|
||||
"Output",
|
||||
&mut settings.output,
|
||||
-12. ..=12.,
|
||||
0.,
|
||||
" dB",
|
||||
64.,
|
||||
CORAL,
|
||||
);
|
||||
});
|
||||
});
|
||||
ui.add_space(10.);
|
||||
note(ui, "Peak reduction");
|
||||
let max = state
|
||||
.analyzer
|
||||
.reduction
|
||||
.iter()
|
||||
.copied()
|
||||
.fold(0f32, f32::max);
|
||||
ui.label(RichText::new(format!("{max:.1} dB")).size(25.).color(CORAL));
|
||||
ui.add_space(12.);
|
||||
ui.label(
|
||||
RichText::new("Drag to adjust. Shift for fine steps. Double-click resets.")
|
||||
.size(13.)
|
||||
.color(MUTED),
|
||||
);
|
||||
});
|
||||
});
|
||||
ui.add_space(4.);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.spacing_mut().slider_width = ((ui.available_width() - 48.) / 4. - 103.).max(72.);
|
||||
spectrum(ui, settings, state);
|
||||
ui.add_space(4.);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(RichText::new("Focus / protect").color(VIOLET));
|
||||
for i in 0..4 {
|
||||
let f = settings.focus[i];
|
||||
if ui
|
||||
.selectable_label(
|
||||
state.selected == Some(i),
|
||||
format!("{} {}", i + 1, if f.enabled { "●" } else { "○" }),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
state.selected = Some(i);
|
||||
}
|
||||
}
|
||||
if let Some(i) = state.selected {
|
||||
let f = &mut settings.focus[i];
|
||||
ui.checkbox(&mut f.enabled, "Enabled");
|
||||
ui.label("Hz");
|
||||
ui.add(
|
||||
egui::DragValue::new(&mut f.frequency)
|
||||
.range(20. ..=20000.)
|
||||
.speed(5.),
|
||||
);
|
||||
ui.label("Sensitivity");
|
||||
ui.add(
|
||||
egui::DragValue::new(&mut f.sensitivity)
|
||||
.range(-18. ..=18.)
|
||||
.speed(0.1)
|
||||
.suffix(" dB"),
|
||||
);
|
||||
ui.label("Width");
|
||||
ui.add(
|
||||
egui::DragValue::new(&mut f.width)
|
||||
.range(0.05..=2.)
|
||||
.speed(0.01)
|
||||
.suffix(" oct"),
|
||||
);
|
||||
if ui.small_button("Reset").clicked() {
|
||||
f.sensitivity = 0.;
|
||||
}
|
||||
if ui.small_button("Remove").clicked() {
|
||||
*f = Focus::default();
|
||||
state.selected = None;
|
||||
}
|
||||
} else {
|
||||
note(
|
||||
ui,
|
||||
"Double-click the spectrum to place a point. Drag to tame or protect.",
|
||||
);
|
||||
}
|
||||
});
|
||||
ui.add_space(6.);
|
||||
ui.separator();
|
||||
ui.add_space(4.);
|
||||
egui::Grid::new("engine-controls")
|
||||
.num_columns(4)
|
||||
.spacing([16., 12.])
|
||||
.min_col_width((ui.available_width() - 48.) / 4.)
|
||||
.show(ui, |ui| {
|
||||
control(
|
||||
ui,
|
||||
"Sensitivity",
|
||||
&mut settings.sensitivity,
|
||||
0. ..=24.,
|
||||
" dB",
|
||||
false,
|
||||
"Lower catches more peaks. Measured relative to the local spectral reference.",
|
||||
state,
|
||||
);
|
||||
control(
|
||||
ui,
|
||||
"Max cut",
|
||||
&mut settings.max_cut,
|
||||
0. ..=18.,
|
||||
" dB",
|
||||
false,
|
||||
"Upper bound on spectral attenuation. This is not a limiter.",
|
||||
state,
|
||||
);
|
||||
control(
|
||||
ui,
|
||||
"Transient guard",
|
||||
&mut settings.transient_guard,
|
||||
0. ..=100.,
|
||||
" %",
|
||||
false,
|
||||
"Relaxes reduction during attacks. Turn down to catch short resonances.",
|
||||
state,
|
||||
);
|
||||
control(
|
||||
ui,
|
||||
"Knee",
|
||||
&mut settings.knee,
|
||||
0. ..=12.,
|
||||
" dB",
|
||||
false,
|
||||
"Softness of the transition into prominence reduction.",
|
||||
state,
|
||||
);
|
||||
ui.end_row();
|
||||
control(
|
||||
ui,
|
||||
"Attack",
|
||||
&mut settings.attack,
|
||||
1. ..=200.,
|
||||
" ms",
|
||||
true,
|
||||
"Attenuation rise time, in addition to window and detection delay.",
|
||||
state,
|
||||
);
|
||||
control(
|
||||
ui,
|
||||
"Release",
|
||||
&mut settings.release,
|
||||
10. ..=1000.,
|
||||
" ms",
|
||||
true,
|
||||
"Recovery time after a resonance subsides.",
|
||||
state,
|
||||
);
|
||||
control(
|
||||
ui,
|
||||
"Neighborhood",
|
||||
&mut settings.neighborhood,
|
||||
0.25..=2.,
|
||||
" oct",
|
||||
false,
|
||||
"Width of the surrounding spectral reference. Wider includes more context.",
|
||||
state,
|
||||
);
|
||||
control(
|
||||
ui,
|
||||
"Cut width",
|
||||
&mut settings.cut_width,
|
||||
0.03..=0.5,
|
||||
" oct",
|
||||
false,
|
||||
"Frequency smoothing width of the attenuation surface.",
|
||||
state,
|
||||
);
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(6.);
|
||||
egui::Grid::new("range-controls")
|
||||
.num_columns(2)
|
||||
.spacing([22., 8.])
|
||||
.show(ui, |ui| {
|
||||
control(
|
||||
ui,
|
||||
"Low frequency",
|
||||
&mut settings.low,
|
||||
20. ..=19999.,
|
||||
" Hz",
|
||||
true,
|
||||
"Lower processing boundary. Protect the source's body.",
|
||||
state,
|
||||
);
|
||||
control(
|
||||
ui,
|
||||
"High frequency",
|
||||
&mut settings.high,
|
||||
21. ..=20000.,
|
||||
" Hz",
|
||||
true,
|
||||
"Upper processing boundary, also limited by Nyquist.",
|
||||
state,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
note(ui, &state.help);
|
||||
if settings.low >= settings.high {
|
||||
if settings.low != before.low {
|
||||
settings.low = (settings.high - 1.).max(20.);
|
||||
} else {
|
||||
settings.high = (settings.low + 1.).min(20000.);
|
||||
}
|
||||
}
|
||||
state.gesture_active = ui.input(|i| i.pointer.any_down());
|
||||
if state.last_audio.elapsed() < Duration::from_millis(300) {
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(33));
|
||||
}
|
||||
}
|
||||
fn spectrum(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
|
||||
let height = (ui.available_height() - 360.).clamp(180., 480.);
|
||||
let (outer, response) = ui.allocate_exact_size(
|
||||
Vec2::new(ui.available_width(), height),
|
||||
Sense::click_and_drag(),
|
||||
);
|
||||
let p = ui.painter();
|
||||
p.rect_filled(outer, 6., Color32::from_rgb(15, 13, 22));
|
||||
let r = Rect::from_min_max(
|
||||
outer.min + Vec2::new(46., 26.),
|
||||
outer.max - Vec2::new(42., 26.),
|
||||
);
|
||||
let x = |f: f32| r.left() + ((f.max(20.) / 20.).ln() / 1000f32.ln()).clamp(0., 1.) * r.width();
|
||||
let y = |d: f32| r.bottom() - (d + 100.).clamp(0., 100.) / 100. * r.height();
|
||||
let red_y = |d: f32| r.top() + d / 18. * r.height() * 0.75;
|
||||
for (xx, level, color) in [
|
||||
(outer.left() + 5., state.analyzer.input_peak, CYAN),
|
||||
(
|
||||
outer.right() - 9.,
|
||||
state.analyzer.output_peak,
|
||||
if state.analyzer.output_peak >= 1. {
|
||||
CORAL
|
||||
} else {
|
||||
VIOLET
|
||||
},
|
||||
),
|
||||
] {
|
||||
let rail = Rect::from_min_max(Pos2::new(xx, r.top()), Pos2::new(xx + 4., r.bottom()));
|
||||
p.rect_filled(rail, 2., Color32::from_rgb(38, 33, 48));
|
||||
let height = ((db(level) + 72.) / 72.).clamp(0., 1.) * rail.height();
|
||||
p.rect_filled(
|
||||
Rect::from_min_max(Pos2::new(xx, rail.bottom() - height), rail.max),
|
||||
2.,
|
||||
color.gamma_multiply(0.65),
|
||||
);
|
||||
}
|
||||
let color_grid = Color32::from_rgb(58, 51, 70);
|
||||
for f in [
|
||||
20., 50., 100., 200., 500., 1000., 2000., 5000., 10000., 20000.,
|
||||
] {
|
||||
let xx = x(f);
|
||||
p.line_segment(
|
||||
[Pos2::new(xx, r.top()), Pos2::new(xx, r.bottom())],
|
||||
Stroke::new(1.0_f32, color_grid),
|
||||
);
|
||||
let label = if f >= 1000. {
|
||||
format!("{}k", f / 1000.)
|
||||
} else {
|
||||
format!("{f:.0}")
|
||||
};
|
||||
p.text(
|
||||
Pos2::new(xx, r.bottom() + 7.),
|
||||
egui::Align2::CENTER_TOP,
|
||||
label,
|
||||
FontId::proportional(12.),
|
||||
MUTED,
|
||||
);
|
||||
}
|
||||
for d in [-96., -72., -48., -24., 0.] {
|
||||
p.line_segment(
|
||||
[Pos2::new(r.left(), y(d)), Pos2::new(r.right(), y(d))],
|
||||
Stroke::new(1.0_f32, color_grid),
|
||||
);
|
||||
p.text(
|
||||
Pos2::new(r.left() - 7., y(d)),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
format!("{d:.0}"),
|
||||
FontId::proportional(12.),
|
||||
MUTED,
|
||||
);
|
||||
}
|
||||
for d in [0., 6., 12., 18.] {
|
||||
p.text(
|
||||
Pos2::new(r.right() + 7., red_y(d)),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
format!("−{d:.0}"),
|
||||
FontId::proportional(12.),
|
||||
CORAL,
|
||||
);
|
||||
}
|
||||
p.text(
|
||||
r.left_top() - Vec2::new(30., 19.),
|
||||
egui::Align2::LEFT_TOP,
|
||||
"dBFS / bin",
|
||||
FontId::proportional(12.),
|
||||
MUTED,
|
||||
);
|
||||
p.text(
|
||||
r.right_top() + Vec2::new(30., -19.),
|
||||
egui::Align2::RIGHT_TOP,
|
||||
"Cut dB",
|
||||
FontId::proportional(12.),
|
||||
CORAL,
|
||||
);
|
||||
p.rect_filled(
|
||||
Rect::from_min_max(r.min, Pos2::new(x(settings.low), r.bottom())),
|
||||
0.,
|
||||
Color32::from_black_alpha(90),
|
||||
);
|
||||
p.rect_filled(
|
||||
Rect::from_min_max(Pos2::new(x(settings.high), r.top()), r.max),
|
||||
0.,
|
||||
Color32::from_black_alpha(90),
|
||||
);
|
||||
let signal: Vec<_> = (0..GRID)
|
||||
.map(|i| Pos2::new(x(frequency(i)), y(state.analyzer.input[i])))
|
||||
.collect();
|
||||
let mut source_fill = egui::Mesh::default();
|
||||
for (i, point) in signal.iter().enumerate() {
|
||||
source_fill.colored_vertex(
|
||||
Pos2::new(point.x, r.bottom()),
|
||||
Color32::from_rgba_unmultiplied(102, 215, 230, 7),
|
||||
);
|
||||
source_fill.colored_vertex(*point, Color32::from_rgba_unmultiplied(102, 215, 230, 60));
|
||||
if i > 0 {
|
||||
let j = (i * 2) as u32;
|
||||
source_fill.add_triangle(j - 2, j - 1, j);
|
||||
source_fill.add_triangle(j - 1, j, j + 1);
|
||||
}
|
||||
}
|
||||
p.add(egui::Shape::mesh(source_fill));
|
||||
p.add(egui::Shape::line(signal, Stroke::new(1.5_f32, CYAN)));
|
||||
let mut fill = Vec::with_capacity(GRID + 2);
|
||||
fill.push(r.left_top());
|
||||
for i in 0..GRID {
|
||||
fill.push(Pos2::new(
|
||||
x(frequency(i)),
|
||||
red_y(state.analyzer.reduction[i]),
|
||||
));
|
||||
}
|
||||
fill.push(r.right_top());
|
||||
// A triangle strip makes non-convex reduction envelopes render accurately.
|
||||
let mut mesh = egui::Mesh::default();
|
||||
for i in 0..GRID {
|
||||
let xx = x(frequency(i));
|
||||
let yy = red_y(state.analyzer.reduction[i]);
|
||||
mesh.colored_vertex(
|
||||
Pos2::new(xx, r.top()),
|
||||
Color32::from_rgba_unmultiplied(255, 136, 125, 8),
|
||||
);
|
||||
mesh.colored_vertex(
|
||||
Pos2::new(xx, yy),
|
||||
Color32::from_rgba_unmultiplied(255, 136, 125, 90),
|
||||
);
|
||||
if i > 0 {
|
||||
let j = (i * 2) as u32;
|
||||
mesh.add_triangle(j - 2, j - 1, j);
|
||||
mesh.add_triangle(j - 1, j, j + 1);
|
||||
}
|
||||
}
|
||||
p.add(egui::Shape::mesh(mesh));
|
||||
p.add(egui::Shape::line(
|
||||
fill[1..=GRID].to_vec(),
|
||||
Stroke::new(1.6_f32, CORAL),
|
||||
));
|
||||
let center = r.center().y;
|
||||
let focus_y = |offset: f32| center - offset / 36. * r.height() * 0.65;
|
||||
let points: Vec<_> = (0..GRID)
|
||||
.map(|i| {
|
||||
Pos2::new(
|
||||
x(frequency(i)),
|
||||
focus_y(focus_offset(frequency(i), &settings.focus)),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
p.line_segment(
|
||||
[Pos2::new(r.left(), center), Pos2::new(r.right(), center)],
|
||||
Stroke::new(0.7_f32, VIOLET.gamma_multiply(0.35)),
|
||||
);
|
||||
p.add(egui::Shape::line(points, Stroke::new(1.3_f32, VIOLET)));
|
||||
for (i, f) in settings.focus.iter().enumerate().filter(|(_, f)| f.enabled) {
|
||||
let pos = Pos2::new(x(f.frequency), focus_y(f.sensitivity));
|
||||
p.circle_filled(pos, if state.selected == Some(i) { 7. } else { 5. }, VIOLET);
|
||||
p.text(
|
||||
pos - Vec2::new(0., 12.),
|
||||
egui::Align2::CENTER_BOTTOM,
|
||||
format!("{}", i + 1),
|
||||
FontId::proportional(12.),
|
||||
TEXT,
|
||||
);
|
||||
}
|
||||
if state.analyzer.input_peak < 1e-6 {
|
||||
p.text(
|
||||
r.center() + Vec2::new(0., 42.),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
"Play audio to inspect its resonances",
|
||||
FontId::proportional(18.),
|
||||
MUTED,
|
||||
);
|
||||
}
|
||||
if let Some(pos) = response.hover_pos() {
|
||||
if r.contains(pos) {
|
||||
let f = 20. * 1000f32.powf((pos.x - r.left()) / r.width());
|
||||
p.line_segment(
|
||||
[Pos2::new(pos.x, r.top()), Pos2::new(pos.x, r.bottom())],
|
||||
Stroke::new(0.7_f32, TEXT.gamma_multiply(0.3)),
|
||||
);
|
||||
response.clone().on_hover_text(format!("{f:.0} Hz • Double-click to add focus; drag a node to tame/protect; wheel sets width"));
|
||||
if response.double_clicked() {
|
||||
if let Some(i) = settings.focus.iter().position(|p| !p.enabled) {
|
||||
settings.focus[i] = Focus {
|
||||
enabled: true,
|
||||
frequency: f,
|
||||
sensitivity: 0.,
|
||||
..Default::default()
|
||||
};
|
||||
state.selected = Some(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if response.drag_started() {
|
||||
if let Some(pos) = response.interact_pointer_pos() {
|
||||
state.drag = settings
|
||||
.focus
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| f.enabled)
|
||||
.find(|(_, f)| {
|
||||
Pos2::new(x(f.frequency), focus_y(f.sensitivity)).distance(pos) < 18.
|
||||
})
|
||||
.map(|(i, _)| i);
|
||||
if state.drag.is_some() {
|
||||
state.selected = state.drag;
|
||||
} else if (pos.x - x(settings.low)).abs() < 12. {
|
||||
state.drag = Some(4);
|
||||
} else if (pos.x - x(settings.high)).abs() < 12. {
|
||||
state.drag = Some(5);
|
||||
}
|
||||
}
|
||||
}
|
||||
if response.dragged() {
|
||||
if let (Some(i), Some(pos)) = (state.drag, response.interact_pointer_pos()) {
|
||||
let fine = ui.input(|i| i.modifiers.shift);
|
||||
let f = (20. * 1000f32.powf((pos.x - r.left()) / r.width())).clamp(20., 20000.);
|
||||
if i < 4 {
|
||||
let node = &mut settings.focus[i];
|
||||
let next = ((center - pos.y) / (r.height() * 0.65) * 36.).clamp(-18., 18.);
|
||||
if fine {
|
||||
node.frequency += (f - node.frequency) * 0.1;
|
||||
node.sensitivity += (next - node.sensitivity) * 0.1;
|
||||
} else {
|
||||
node.frequency = f;
|
||||
node.sensitivity = next;
|
||||
}
|
||||
} else if i == 4 {
|
||||
settings.low = f.min(settings.high - 1.);
|
||||
} else {
|
||||
settings.high = f.max(settings.low + 1.);
|
||||
}
|
||||
}
|
||||
}
|
||||
if response.drag_stopped() {
|
||||
state.drag = None;
|
||||
}
|
||||
if response.hovered() {
|
||||
if let Some(i) = state.selected {
|
||||
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
|
||||
if scroll != 0. {
|
||||
settings.focus[i].width =
|
||||
(settings.focus[i].width + scroll * 0.002).clamp(0.05, 2.);
|
||||
}
|
||||
}
|
||||
}
|
||||
for f in [settings.low, settings.high] {
|
||||
p.line_segment(
|
||||
[Pos2::new(x(f), r.top()), Pos2::new(x(f), r.bottom())],
|
||||
Stroke::new(2.0_f32, MUTED),
|
||||
);
|
||||
let handle = Rect::from_center_size(Pos2::new(x(f), r.center().y), Vec2::new(12., 30.));
|
||||
p.rect_filled(handle, 6., Color32::from_rgb(65, 77, 96));
|
||||
p.rect_stroke(
|
||||
handle,
|
||||
6.,
|
||||
Stroke::new(1.0_f32, CYAN.gamma_multiply(0.65)),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "rivet-app"
|
||||
version = "0.3.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
rivet-core.workspace = true
|
||||
rivet-midi.workspace = true
|
||||
crossbeam-queue = "0.3"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_UI_Controls_Dialogs", "Win32_Foundation"] }
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Dialogs execute only on the file worker. A path field remains available in the editor.
|
||||
use rivet_core::{Error, Result};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn choose(save: bool, session: bool) -> Result<Option<PathBuf>> {
|
||||
use std::{ffi::OsString, os::windows::ffi::OsStringExt};
|
||||
use windows_sys::Win32::UI::Controls::Dialogs::*;
|
||||
let mut buffer = [0u16; 32768];
|
||||
let filter: Vec<u16> = if session {
|
||||
"Storyboard session\0*.json\0\0"
|
||||
} else {
|
||||
"MIDI file\0*.mid;*.midi\0\0"
|
||||
}
|
||||
.encode_utf16()
|
||||
.collect();
|
||||
let extension: Vec<u16> = if session { "json\0" } else { "mid\0" }
|
||||
.encode_utf16()
|
||||
.collect();
|
||||
let mut options: OPENFILENAMEW = unsafe { std::mem::zeroed() };
|
||||
options.lStructSize = std::mem::size_of::<OPENFILENAMEW>() as u32;
|
||||
options.lpstrFile = buffer.as_mut_ptr();
|
||||
options.nMaxFile = buffer.len() as u32;
|
||||
options.lpstrFilter = filter.as_ptr();
|
||||
options.lpstrDefExt = extension.as_ptr();
|
||||
options.Flags = OFN_EXPLORER
|
||||
| OFN_NOCHANGEDIR
|
||||
| OFN_PATHMUSTEXIST
|
||||
| if save { 0 } else { OFN_FILEMUSTEXIST };
|
||||
// SAFETY: Every pointer references live UTF-16 storage for the duration of the modal call.
|
||||
let success = unsafe {
|
||||
if save {
|
||||
GetSaveFileNameW(&mut options)
|
||||
} else {
|
||||
GetOpenFileNameW(&mut options)
|
||||
}
|
||||
};
|
||||
if success == 0 {
|
||||
let code = unsafe { CommDlgExtendedError() };
|
||||
return if code == 0 {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(Error(format!(
|
||||
"File dialog failed ({code}). Enter a path instead."
|
||||
)))
|
||||
};
|
||||
}
|
||||
let len = buffer.iter().position(|&c| c == 0).unwrap_or(buffer.len());
|
||||
Ok(Some(PathBuf::from(OsString::from_wide(&buffer[..len]))))
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn choose(save: bool, session: bool) -> Result<Option<PathBuf>> {
|
||||
let mut cmd = std::process::Command::new("zenity");
|
||||
cmd.arg("--file-selection").arg(if session {
|
||||
"--file-filter=Session | *.json"
|
||||
} else {
|
||||
"--file-filter=MIDI | *.mid *.midi"
|
||||
});
|
||||
if save {
|
||||
cmd.arg("--save");
|
||||
}
|
||||
let output = cmd.output().map_err(|_| {
|
||||
Error("File dialog unavailable. Enter a path in the editor instead.".into())
|
||||
})?;
|
||||
if !output.status.success() {
|
||||
return Ok(None);
|
||||
}
|
||||
let path = String::from_utf8(output.stdout)
|
||||
.map_err(|_| Error("File path is not UTF-8. Enter it manually.".into()))?;
|
||||
Ok(Some(PathBuf::from(path.trim_end_matches('\n'))))
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
//! Shared application state and bounded control messages. The audio callback never locks a session.
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use rivet_core::{
|
||||
Audition, Candidate, Error, EventBatch, MessageKind, MidiMessage, Performance, PerformanceClip,
|
||||
PerformancePlayer, Result, Session, SECTION,
|
||||
};
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
sync::{
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
Arc, Mutex, RwLock,
|
||||
},
|
||||
};
|
||||
pub mod dialog;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PlayRequest {
|
||||
pub epoch: u64,
|
||||
pub clip: PerformanceClip,
|
||||
pub quantized: bool,
|
||||
}
|
||||
|
||||
pub struct Shared {
|
||||
pub session: RwLock<Session>,
|
||||
pub epoch: AtomicU64,
|
||||
pub revision: AtomicU64,
|
||||
pub tempo: AtomicU64,
|
||||
pub audition_tempo: AtomicU64,
|
||||
pub follow_host: AtomicBool,
|
||||
pub midi: AtomicBool,
|
||||
pub looping: AtomicBool,
|
||||
pub queued: AtomicBool,
|
||||
pub playing: AtomicBool,
|
||||
pub playhead: AtomicU64,
|
||||
pub commands: ArrayQueue<PlayRequest>,
|
||||
pub busy: AtomicBool,
|
||||
results: Mutex<Vec<Completion>>,
|
||||
}
|
||||
pub enum Output {
|
||||
Imported(rivet_midi::MidiFile),
|
||||
Generated(Vec<Candidate>),
|
||||
Exported(PathBuf),
|
||||
Saved(PathBuf),
|
||||
Loaded(Box<Session>),
|
||||
LibraryLoaded(Vec<rivet_core::Gesture>),
|
||||
Canceled,
|
||||
}
|
||||
pub struct Completion {
|
||||
pub revision: u64,
|
||||
pub result: Result<Output>,
|
||||
}
|
||||
impl Default for Shared {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
session: RwLock::new(Session::default()),
|
||||
epoch: AtomicU64::new(0),
|
||||
revision: AtomicU64::new(0),
|
||||
tempo: AtomicU64::new(140f64.to_bits()),
|
||||
audition_tempo: AtomicU64::new(f64::NAN.to_bits()),
|
||||
follow_host: AtomicBool::new(false),
|
||||
midi: AtomicBool::new(false),
|
||||
looping: AtomicBool::new(true),
|
||||
queued: AtomicBool::new(false),
|
||||
playing: AtomicBool::new(false),
|
||||
playhead: AtomicU64::new(0),
|
||||
commands: ArrayQueue::new(2),
|
||||
busy: AtomicBool::new(false),
|
||||
results: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Shared {
|
||||
pub fn snapshot(&self) -> (u64, Session) {
|
||||
let state = self.session.read().unwrap_or_else(|p| p.into_inner());
|
||||
(self.revision.load(Ordering::Acquire), state.clone())
|
||||
}
|
||||
pub fn stop(&self) {
|
||||
self.epoch.fetch_add(1, Ordering::AcqRel);
|
||||
self.playing.store(false, Ordering::Release);
|
||||
self.queued.store(false, Ordering::Release);
|
||||
}
|
||||
fn publish(&self, s: &Session) {
|
||||
self.tempo.store(s.tempo.to_bits(), Ordering::Release);
|
||||
self.follow_host.store(s.follow_host, Ordering::Release);
|
||||
self.midi
|
||||
.store(s.audition == Audition::Midi, Ordering::Release);
|
||||
self.looping.store(s.looping, Ordering::Release);
|
||||
self.revision.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
pub fn replace(&self, mut session: Session) -> Result<()> {
|
||||
session.migrate()?;
|
||||
session.validate()?;
|
||||
self.stop();
|
||||
let mut current = self.session.write().unwrap_or_else(|p| p.into_inner());
|
||||
*current = session;
|
||||
self.publish(¤t);
|
||||
Ok(())
|
||||
}
|
||||
pub fn edit(&self, revision: u64, mut session: Session) -> Result<()> {
|
||||
session.migrate()?;
|
||||
session.validate()?;
|
||||
let mut current = self.session.write().unwrap_or_else(|p| p.into_inner());
|
||||
if self.revision.load(Ordering::Acquire) != revision {
|
||||
return Err(Error(
|
||||
"Session changed while this operation was running. Try again.".into(),
|
||||
));
|
||||
}
|
||||
if current.source != session.source
|
||||
|| current.settings != session.settings
|
||||
|| current.harmony != session.harmony
|
||||
|| current.candidates != session.candidates
|
||||
|| current.performance != session.performance
|
||||
|| current.audition != session.audition
|
||||
{
|
||||
self.stop();
|
||||
}
|
||||
*current = session;
|
||||
self.publish(¤t);
|
||||
Ok(())
|
||||
}
|
||||
fn compile_clip(&self, phrase: &rivet_core::Phrase) -> Result<PerformanceClip> {
|
||||
let state = self.session.read().unwrap_or_else(|p| p.into_inner());
|
||||
let observed = f64::from_bits(self.audition_tempo.load(Ordering::Acquire));
|
||||
let tempo = if state.follow_host && observed.is_finite() {
|
||||
observed
|
||||
} else {
|
||||
state.tempo
|
||||
};
|
||||
let settings = state.performance.clone();
|
||||
let compensate = state.audition == Audition::Midi;
|
||||
drop(state);
|
||||
Performance::compile(phrase, &settings, tempo, compensate)?.clip()
|
||||
}
|
||||
pub fn preview(&self, phrase: &rivet_core::Phrase) -> Result<()> {
|
||||
let epoch = self.epoch.load(Ordering::Acquire);
|
||||
let clip = self.compile_clip(phrase)?;
|
||||
let next = epoch.wrapping_add(1);
|
||||
self.epoch
|
||||
.compare_exchange(epoch, next, Ordering::AcqRel, Ordering::Acquire)
|
||||
.map_err(|_| Error("Session changed while preparing audition. Try again.".into()))?;
|
||||
self.playing.store(false, Ordering::Release);
|
||||
self.queued.store(false, Ordering::Release);
|
||||
self.commands.force_push(PlayRequest {
|
||||
epoch: next,
|
||||
clip,
|
||||
quantized: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
pub fn audition(&self, phrase: &rivet_core::Phrase) -> Result<()> {
|
||||
if !self.playing.load(Ordering::Acquire) {
|
||||
return self.preview(phrase);
|
||||
}
|
||||
let epoch = self.epoch.load(Ordering::Acquire);
|
||||
let clip = self.compile_clip(phrase)?;
|
||||
if self.epoch.load(Ordering::Acquire) != epoch {
|
||||
return Err(Error(
|
||||
"Session changed while preparing audition. Try again.".into(),
|
||||
));
|
||||
}
|
||||
self.queued.store(true, Ordering::Release);
|
||||
self.commands.force_push(PlayRequest {
|
||||
epoch,
|
||||
clip,
|
||||
quantized: true,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
/// All jobs run off the audio/UI thread; one outstanding job per instance bounds resource use.
|
||||
pub fn work(
|
||||
self: &Arc<Self>,
|
||||
revision: u64,
|
||||
job: impl FnOnce() -> Result<Output> + Send + 'static,
|
||||
) -> Result<()> {
|
||||
self.busy
|
||||
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||
.map_err(|_| Error("Wait for the current operation to finish.".into()))?;
|
||||
let shared = self.clone();
|
||||
let result = std::thread::Builder::new()
|
||||
.name("motif-worker".into())
|
||||
.spawn(move || {
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job))
|
||||
.unwrap_or_else(|_| Err(Error("The operation failed unexpectedly.".into())));
|
||||
shared
|
||||
.results
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.push(Completion { revision, result });
|
||||
// Busy is cleared when the GUI consumes the result, so completions cannot accumulate.
|
||||
});
|
||||
if let Err(e) = result {
|
||||
self.busy.store(false, Ordering::Release);
|
||||
return Err(Error(e.to_string()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn take_completion(&self) -> Option<Completion> {
|
||||
let result = self.results.lock().unwrap_or_else(|p| p.into_inner()).pop();
|
||||
if result.is_some() {
|
||||
self.busy.store(false, Ordering::Release);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_limited(path: &Path, limit: usize) -> Result<Vec<u8>> {
|
||||
let file =
|
||||
File::open(path).map_err(|e| Error(format!("Cannot open {}: {e}", path.display())))?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(limit as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| Error(e.to_string()))?;
|
||||
if bytes.len() > limit {
|
||||
return Err(Error(format!(
|
||||
"File exceeds the {} MiB limit.",
|
||||
limit / 1024 / 1024
|
||||
)));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
/// Never silently overwrite a user's existing MIDI/session file.
|
||||
pub fn write_new(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
let mut file = File::options()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
.map_err(|e| {
|
||||
Error(format!(
|
||||
"Cannot create {}: {e}. Choose a new filename if it already exists.",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
file.write_all(bytes)
|
||||
.and_then(|_| file.sync_all())
|
||||
.map_err(|e| Error(e.to_string()))
|
||||
}
|
||||
|
||||
/// Fixed-size scheduling and MIDI state; no session locks or heap work on this path.
|
||||
#[derive(Default)]
|
||||
pub struct AudioEngine {
|
||||
pub player: PerformancePlayer,
|
||||
epoch: u64,
|
||||
pending: Option<(f64, PerformanceClip)>,
|
||||
active: [Option<u8>; 16],
|
||||
controls: [Option<(u8, u8)>; 16],
|
||||
clear: bool,
|
||||
was_midi: bool,
|
||||
}
|
||||
pub struct AudioFrame {
|
||||
pub sample: f32,
|
||||
pub events: EventBatch,
|
||||
/// Channel-one summaries retained for simple monophonic callers.
|
||||
pub off: Option<u8>,
|
||||
pub on: Option<(u8, u8)>,
|
||||
}
|
||||
impl AudioEngine {
|
||||
pub fn stop(&mut self) {
|
||||
self.player.stop();
|
||||
self.pending = None;
|
||||
self.clear = true;
|
||||
}
|
||||
pub fn begin_block(&mut self, shared: &Shared) {
|
||||
let epoch = shared.epoch.load(Ordering::Acquire);
|
||||
if self.epoch != epoch {
|
||||
self.stop();
|
||||
self.epoch = epoch;
|
||||
}
|
||||
self.player
|
||||
.set_looping(shared.looping.load(Ordering::Acquire));
|
||||
for _ in 0..2 {
|
||||
let Some(request) = shared.commands.pop() else {
|
||||
break;
|
||||
};
|
||||
if request.epoch != epoch {
|
||||
continue;
|
||||
}
|
||||
if request.quantized && self.player.is_playing() {
|
||||
let now = self.player.absolute_tick();
|
||||
let lead = request.clip.lead_in as f64;
|
||||
let boundary = ((now + lead) / SECTION as f64)
|
||||
.floor()
|
||||
.mul_add(SECTION as f64, SECTION as f64);
|
||||
self.pending = Some((boundary - lead, request.clip));
|
||||
} else {
|
||||
self.player.play(request.clip);
|
||||
self.pending = None;
|
||||
self.clear = true;
|
||||
shared.queued.store(false, Ordering::Release);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn release(&mut self, batch: &mut EventBatch) {
|
||||
for channel in 0..16 {
|
||||
if let Some(key) = self.active[channel].take() {
|
||||
batch.push(MidiMessage {
|
||||
kind: MessageKind::Off,
|
||||
channel: channel as u8,
|
||||
key,
|
||||
value: 0,
|
||||
rest: 0,
|
||||
});
|
||||
}
|
||||
if let Some((key, rest)) = self.controls[channel].take() {
|
||||
batch.push(MidiMessage {
|
||||
kind: MessageKind::Control,
|
||||
channel: channel as u8,
|
||||
key,
|
||||
value: rest,
|
||||
rest,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
fn forward(&mut self, message: MidiMessage, batch: &mut EventBatch) {
|
||||
let channel = message.channel as usize;
|
||||
match message.kind {
|
||||
MessageKind::On => self.active[channel] = Some(message.key),
|
||||
MessageKind::Off => {
|
||||
if self.active[channel] == Some(message.key) {
|
||||
self.active[channel] = None;
|
||||
}
|
||||
}
|
||||
MessageKind::Control => self.controls[channel] = Some((message.key, message.rest)),
|
||||
}
|
||||
batch.push(message);
|
||||
}
|
||||
pub fn sample(&mut self, bpm: f64) -> f32 {
|
||||
self.frame(bpm, false).sample
|
||||
}
|
||||
pub fn frame(&mut self, bpm: f64, midi: bool) -> AudioFrame {
|
||||
if self.pending.as_ref().is_some_and(|(boundary, _)| {
|
||||
self.player.absolute_tick() >= *boundary || !self.player.is_playing()
|
||||
}) {
|
||||
let (_, clip) = self.pending.take().unwrap();
|
||||
self.player.play(clip);
|
||||
self.clear = true;
|
||||
}
|
||||
let mut events = EventBatch::default();
|
||||
if self.clear || (!midi && self.was_midi) {
|
||||
self.release(&mut events);
|
||||
self.clear = false;
|
||||
}
|
||||
let (sample, raw) = self.player.next_frame(bpm);
|
||||
if midi {
|
||||
if !self.was_midi {
|
||||
let current = self.player.current_messages();
|
||||
for message in current.events[..current.len].iter().flatten().copied() {
|
||||
self.forward(message, &mut events);
|
||||
}
|
||||
} else {
|
||||
for message in raw.events[..raw.len].iter().flatten().copied() {
|
||||
self.forward(message, &mut events);
|
||||
}
|
||||
}
|
||||
if !self.player.is_playing() {
|
||||
self.release(&mut events);
|
||||
}
|
||||
}
|
||||
self.was_midi = midi;
|
||||
let off = events
|
||||
.events
|
||||
.iter()
|
||||
.flatten()
|
||||
.find(|m| m.channel == 0 && m.kind == MessageKind::Off)
|
||||
.map(|m| m.key);
|
||||
let on = events
|
||||
.events
|
||||
.iter()
|
||||
.flatten()
|
||||
.find(|m| m.channel == 0 && m.kind == MessageKind::On)
|
||||
.map(|m| (m.key, m.value));
|
||||
AudioFrame {
|
||||
sample,
|
||||
events,
|
||||
off,
|
||||
on,
|
||||
}
|
||||
}
|
||||
pub fn end_block(&self, shared: &Shared) {
|
||||
shared.queued.store(
|
||||
self.pending.is_some() || !shared.commands.is_empty(),
|
||||
Ordering::Release,
|
||||
);
|
||||
shared
|
||||
.playing
|
||||
.store(self.player.is_playing(), Ordering::Release);
|
||||
shared
|
||||
.playhead
|
||||
.store(self.player.tick().to_bits(), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stop_cancels_pending_and_active_preview() {
|
||||
let shared = Shared::default();
|
||||
let motif = rivet_core::demo_motif();
|
||||
let mut audio = AudioEngine::default();
|
||||
shared.preview(&motif).unwrap();
|
||||
shared.stop();
|
||||
audio.begin_block(&shared);
|
||||
assert!(!audio.player.is_playing());
|
||||
shared.preview(&motif).unwrap();
|
||||
audio.begin_block(&shared);
|
||||
assert!(audio.player.is_playing());
|
||||
shared.replace(Session::default()).unwrap();
|
||||
audio.begin_block(&shared);
|
||||
assert!(!audio.player.is_playing());
|
||||
}
|
||||
#[test]
|
||||
fn stale_edits_do_not_replace_new_session() {
|
||||
let s = Shared::default();
|
||||
let (revision, old) = s.snapshot();
|
||||
let mut new = old.clone();
|
||||
new.tempo = 160.;
|
||||
s.replace(new).unwrap();
|
||||
assert!(s.edit(revision, old).is_err());
|
||||
assert_eq!(s.snapshot().1.tempo, 160.);
|
||||
}
|
||||
#[test]
|
||||
fn bounded_preview_queue_keeps_latest_request() {
|
||||
let s = Shared::default();
|
||||
for _ in 0..8 {
|
||||
s.preview(&rivet_core::demo_motif()).unwrap();
|
||||
}
|
||||
assert_eq!(s.commands.len(), 2);
|
||||
let mut a = AudioEngine::default();
|
||||
a.begin_block(&s);
|
||||
assert!(a.player.is_playing());
|
||||
}
|
||||
#[test]
|
||||
fn replacing_session_publishes_audio_controls() {
|
||||
let s = Shared::default();
|
||||
s.replace(Session {
|
||||
tempo: 172.,
|
||||
follow_host: true,
|
||||
..Session::default()
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(f64::from_bits(s.tempo.load(Ordering::Acquire)), 172.);
|
||||
assert!(s.follow_host.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_completion_keeps_the_revision_of_its_input() {
|
||||
let shared = Arc::new(Shared::default());
|
||||
let revision = shared.revision.load(Ordering::Acquire);
|
||||
let (release, wait) = std::sync::mpsc::channel();
|
||||
shared
|
||||
.work(revision, move || {
|
||||
wait.recv().unwrap();
|
||||
Ok(Output::Canceled)
|
||||
})
|
||||
.unwrap();
|
||||
shared.replace(Session::default()).unwrap();
|
||||
release.send(()).unwrap();
|
||||
let completion = (0..1000)
|
||||
.find_map(|_| {
|
||||
let completion = shared.take_completion();
|
||||
if completion.is_none() {
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
completion
|
||||
})
|
||||
.expect("worker should complete");
|
||||
assert_eq!(completion.revision, revision);
|
||||
assert_ne!(completion.revision, shared.revision.load(Ordering::Acquire));
|
||||
assert!(!shared.busy.load(Ordering::Acquire));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
use rivet_app::{AudioEngine, Shared};
|
||||
use rivet_core::{Note, Phrase, PPQ, SECTION};
|
||||
|
||||
fn clip(pitch: u8, length: u32) -> Phrase {
|
||||
Phrase {
|
||||
length,
|
||||
notes: vec![Note {
|
||||
start: 0,
|
||||
duration: length,
|
||||
pitch,
|
||||
velocity: 90,
|
||||
..Default::default()
|
||||
}],
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn looping_and_mode_changes_release_and_retrigger_notes() {
|
||||
let shared = Shared::default();
|
||||
let mut a = AudioEngine::default();
|
||||
a.player.set_sample_rate(8000.).unwrap();
|
||||
shared.preview(&clip(60, PPQ)).unwrap();
|
||||
a.begin_block(&shared);
|
||||
let first = a.frame(120., true);
|
||||
assert_eq!(first.on, Some((60, 90)));
|
||||
assert_eq!(first.off, None);
|
||||
let mut repeated = false;
|
||||
for _ in 0..4001 {
|
||||
let frame = a.frame(120., true);
|
||||
if frame.off.is_some() {
|
||||
assert_eq!(frame.off, Some(60));
|
||||
assert_eq!(frame.on, Some((60, 90)));
|
||||
repeated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(repeated);
|
||||
let muted = a.frame(120., false);
|
||||
assert_eq!(muted.off, Some(60));
|
||||
assert_eq!(muted.on, None);
|
||||
assert_eq!(a.frame(120., true).on, Some((60, 90)));
|
||||
shared.stop();
|
||||
a.begin_block(&shared);
|
||||
let stopped = a.frame(120., true);
|
||||
assert_eq!(stopped.off, Some(60));
|
||||
assert_eq!(stopped.on, None);
|
||||
}
|
||||
#[test]
|
||||
fn adjacent_same_pitch_notes_have_separate_sample_accurate_attacks() {
|
||||
let shared = Shared::default();
|
||||
shared
|
||||
.looping
|
||||
.store(false, std::sync::atomic::Ordering::Release);
|
||||
let mut a = AudioEngine::default();
|
||||
a.player.set_sample_rate(8000.).unwrap();
|
||||
let p = Phrase {
|
||||
length: PPQ,
|
||||
notes: vec![
|
||||
Note {
|
||||
start: 0,
|
||||
duration: PPQ / 2,
|
||||
pitch: 60,
|
||||
velocity: 90,
|
||||
..Default::default()
|
||||
},
|
||||
Note {
|
||||
start: PPQ / 2,
|
||||
duration: PPQ / 2,
|
||||
pitch: 60,
|
||||
velocity: 70,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
};
|
||||
shared.preview(&p).unwrap();
|
||||
a.begin_block(&shared);
|
||||
let mut events = Vec::new();
|
||||
for frame in 0i32..4003 {
|
||||
let e = a.frame(120., true);
|
||||
if e.off.is_some() || e.on.is_some() {
|
||||
events.push((frame, e.off, e.on));
|
||||
}
|
||||
}
|
||||
assert_eq!(events.len(), 3);
|
||||
assert_eq!(events[0], (0, None, Some((60, 90))));
|
||||
assert!((events[1].0 - 2000).abs() <= 1);
|
||||
assert_eq!(events[1].1, Some(60));
|
||||
assert_eq!(events[1].2, Some((60, 70)));
|
||||
assert!((events[2].0 - 4000).abs() <= 1);
|
||||
assert_eq!(events[2].1, Some(60));
|
||||
assert_eq!(events[2].2, None);
|
||||
}
|
||||
#[test]
|
||||
fn queued_audition_switches_at_section_boundary_and_stop_cancels_it() {
|
||||
let shared = Shared::default();
|
||||
let mut a = AudioEngine::default();
|
||||
a.player.set_sample_rate(8000.).unwrap();
|
||||
shared.preview(&clip(60, 2 * SECTION)).unwrap();
|
||||
a.begin_block(&shared);
|
||||
for _ in 0..100 {
|
||||
a.frame(120., true);
|
||||
}
|
||||
a.end_block(&shared);
|
||||
shared.audition(&clip(67, 2 * SECTION)).unwrap();
|
||||
a.begin_block(&shared);
|
||||
let mut switched = None;
|
||||
for index in 100i32..32003 {
|
||||
let f = a.frame(120., true);
|
||||
if f.on == Some((67, 90)) {
|
||||
assert_eq!(f.off, Some(60));
|
||||
switched = Some(index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!((switched.unwrap() - 32000).abs() <= 1);
|
||||
a.end_block(&shared);
|
||||
shared.audition(&clip(72, SECTION)).unwrap();
|
||||
a.begin_block(&shared);
|
||||
shared.stop();
|
||||
a.begin_block(&shared);
|
||||
let f = a.frame(120., true);
|
||||
assert_eq!(f.off, Some(67));
|
||||
assert_eq!(f.on, None);
|
||||
assert!(!a.player.is_playing());
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use rivet_app::{AudioEngine, Shared};
|
||||
use std::{
|
||||
alloc::{GlobalAlloc, Layout, System},
|
||||
cell::Cell,
|
||||
};
|
||||
|
||||
struct CheckedAllocator;
|
||||
thread_local! {
|
||||
static CHECK:Cell<bool>=const {Cell::new(false)};
|
||||
static OPERATIONS:Cell<usize>=const {Cell::new(0)};
|
||||
}
|
||||
fn record() {
|
||||
if CHECK.try_with(Cell::get).unwrap_or(false) {
|
||||
let _ = OPERATIONS.try_with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
}
|
||||
unsafe impl GlobalAlloc for CheckedAllocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
record();
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
|
||||
record();
|
||||
unsafe { System.dealloc(pointer, layout) }
|
||||
}
|
||||
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
|
||||
record();
|
||||
unsafe { System.realloc(pointer, layout, size) }
|
||||
}
|
||||
}
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: CheckedAllocator = CheckedAllocator;
|
||||
|
||||
#[test]
|
||||
fn playback_control_and_rendering_do_not_allocate_or_free() {
|
||||
let shared = Shared::default();
|
||||
let mut settings = rivet_core::PerformanceSettings {
|
||||
mode: rivet_core::RoleMode::Alternating,
|
||||
..Default::default()
|
||||
};
|
||||
for (i, voice) in settings.voices.iter_mut().enumerate() {
|
||||
voice.attack_ms = 100;
|
||||
voice.release_ms = 20;
|
||||
voice.controller.enabled = true;
|
||||
voice.controller.cc = 20 + i as u8;
|
||||
}
|
||||
shared
|
||||
.replace(rivet_core::Session {
|
||||
performance: settings,
|
||||
audition: rivet_core::Audition::Midi,
|
||||
tempo: 300.,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
let mut audio = AudioEngine::default();
|
||||
let motif = rivet_core::demo_motif();
|
||||
audio.player.set_sample_rate(8000.).unwrap();
|
||||
shared.preview(&motif).unwrap();
|
||||
CHECK.with(|flag| flag.set(true));
|
||||
for _ in 0..4 {
|
||||
audio.begin_block(&shared);
|
||||
for _ in 0..10000 {
|
||||
std::hint::black_box(audio.frame(300., true));
|
||||
}
|
||||
audio.end_block(&shared);
|
||||
}
|
||||
CHECK.with(|flag| flag.set(false));
|
||||
shared.audition(&motif).unwrap();
|
||||
CHECK.with(|flag| flag.set(true));
|
||||
audio.begin_block(&shared);
|
||||
for _ in 0..30000 {
|
||||
std::hint::black_box(audio.frame(300., true));
|
||||
}
|
||||
audio.end_block(&shared);
|
||||
CHECK.with(|flag| flag.set(false));
|
||||
shared.stop();
|
||||
CHECK.with(|flag| flag.set(true));
|
||||
audio.begin_block(&shared);
|
||||
std::hint::black_box(audio.frame(300., true));
|
||||
audio.end_block(&shared);
|
||||
CHECK.with(|flag| flag.set(false));
|
||||
assert_eq!(OPERATIONS.with(Cell::get), 0);
|
||||
assert!(!audio.player.is_playing());
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
use rivet_app::{AudioEngine, Shared};
|
||||
use rivet_core::*;
|
||||
fn fixture() -> (Shared, AudioEngine, Phrase) {
|
||||
let mut settings = PerformanceSettings {
|
||||
mode: RoleMode::Alternating,
|
||||
..Default::default()
|
||||
};
|
||||
for (i, v) in settings.voices.iter_mut().enumerate() {
|
||||
v.controller.enabled = true;
|
||||
v.controller.cc = 20 + i as u8;
|
||||
v.controller.rest = 5 + i as u8;
|
||||
}
|
||||
let shared = Shared::default();
|
||||
shared
|
||||
.replace(Session {
|
||||
performance: settings,
|
||||
audition: Audition::Midi,
|
||||
tempo: 120.,
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap();
|
||||
let mut audio = AudioEngine::default();
|
||||
audio.player.set_sample_rate(8000.).unwrap();
|
||||
let phrase = Phrase {
|
||||
length: PPQ,
|
||||
notes: vec![
|
||||
Note {
|
||||
start: 0,
|
||||
duration: PPQ / 2,
|
||||
pitch: 60,
|
||||
velocity: 90,
|
||||
..Default::default()
|
||||
},
|
||||
Note {
|
||||
start: PPQ / 2,
|
||||
duration: PPQ / 2,
|
||||
pitch: 67,
|
||||
velocity: 80,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
};
|
||||
(shared, audio, phrase)
|
||||
}
|
||||
#[test]
|
||||
fn stop_and_profile_replacement_release_old_mappings() {
|
||||
let (shared, mut audio, phrase) = fixture();
|
||||
shared.preview(&phrase).unwrap();
|
||||
audio.begin_block(&shared);
|
||||
let first = audio.frame(120., true);
|
||||
assert!(first
|
||||
.events
|
||||
.events
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|e| e.kind == MessageKind::On && e.channel == 0));
|
||||
for _ in 0..2100 {
|
||||
audio.frame(120., true);
|
||||
}
|
||||
let (revision, mut state) = shared.snapshot();
|
||||
state.performance.voices[0].controller.cc = 30;
|
||||
shared.edit(revision, state).unwrap();
|
||||
audio.begin_block(&shared);
|
||||
let released = audio.frame(120., true);
|
||||
for (channel, key, value) in [(0, 20, 5), (1, 21, 6)] {
|
||||
assert!(released
|
||||
.events
|
||||
.events
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|e| e.kind == MessageKind::Control
|
||||
&& e.channel == channel
|
||||
&& e.key == key
|
||||
&& e.value == value));
|
||||
}
|
||||
assert!(released
|
||||
.events
|
||||
.events
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|e| e.kind == MessageKind::Off && e.channel == 1 && e.key == 67));
|
||||
assert!(!released
|
||||
.events
|
||||
.events
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|e| e.kind == MessageKind::On));
|
||||
}
|
||||
#[test]
|
||||
fn muting_midi_resets_both_controllers_and_reenabling_restores_current_state() {
|
||||
let (shared, mut audio, phrase) = fixture();
|
||||
shared.preview(&phrase).unwrap();
|
||||
audio.begin_block(&shared);
|
||||
audio.frame(120., true);
|
||||
let off = audio.frame(120., false);
|
||||
assert_eq!(
|
||||
off.events
|
||||
.events
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|e| e.kind == MessageKind::Control)
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
assert_eq!(off.off, Some(60));
|
||||
let on = audio.frame(120., true);
|
||||
assert_eq!(on.on, Some((60, 90)));
|
||||
assert_eq!(
|
||||
on.events
|
||||
.events
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|e| e.kind == MessageKind::Control)
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "rivet-core"
|
||||
version = "0.3.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
@@ -0,0 +1,407 @@
|
||||
use crate::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
pub const MAX_GESTURES: usize = 16;
|
||||
pub const MAX_BRANCHES: usize = 16;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Gesture {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub phrase: Phrase,
|
||||
pub performance: PerformanceSettings,
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct IdeaSnapshot {
|
||||
pub source: Option<Phrase>,
|
||||
pub settings: Settings,
|
||||
pub harmony: Harmony,
|
||||
pub phrase: Option<Phrase>,
|
||||
pub pins: Vec<PinnedSection>,
|
||||
pub performance: PerformanceSettings,
|
||||
}
|
||||
impl IdeaSnapshot {
|
||||
fn validate(&self) -> Result<()> {
|
||||
self.settings.validate()?;
|
||||
self.harmony.validate()?;
|
||||
self.performance.validate()?;
|
||||
if let Some(p) = &self.source {
|
||||
p.validate_source()?;
|
||||
}
|
||||
if let Some(p) = &self.phrase {
|
||||
p.validate(MAX_PLAYBACK_NOTES)?;
|
||||
}
|
||||
let mut seen = 0u8;
|
||||
for pin in &self.pins {
|
||||
if pin.index >= self.settings.bars as usize / 2
|
||||
|| pin.phrase.length != SECTION
|
||||
|| seen & (1 << pin.index) != 0
|
||||
{
|
||||
return Err(err("Invalid branch pins."));
|
||||
}
|
||||
seen |= 1 << pin.index;
|
||||
if !pin.phrase.notes.is_empty() {
|
||||
pin.phrase.validate(MAX_PLAYBACK_NOTES)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Branch {
|
||||
pub id: u64,
|
||||
pub parent: Option<u64>,
|
||||
pub name: String,
|
||||
pub idea: IdeaSnapshot,
|
||||
}
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct LibraryFile {
|
||||
version: u32,
|
||||
gestures: Vec<Gesture>,
|
||||
}
|
||||
pub fn read_gesture_library(bytes: &[u8]) -> Result<Vec<Gesture>> {
|
||||
if bytes.len() > 2 * 1024 * 1024 {
|
||||
return Err(err("Gesture library exceeds 2 MiB."));
|
||||
}
|
||||
let file: LibraryFile = serde_json::from_slice(bytes).map_err(|e| Error(e.to_string()))?;
|
||||
if file.version != 1 || file.gestures.len() > MAX_GESTURES {
|
||||
return Err(err("Unsupported or oversized gesture library."));
|
||||
}
|
||||
for g in &file.gestures {
|
||||
if !name_valid(&g.name) {
|
||||
return Err(err("Invalid gesture name."));
|
||||
}
|
||||
g.phrase.validate_source()?;
|
||||
g.performance.validate()?;
|
||||
}
|
||||
Ok(file.gestures)
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CreativeMove {
|
||||
Thin,
|
||||
Delay,
|
||||
Lengthen,
|
||||
Transpose(i8),
|
||||
}
|
||||
impl CreativeMove {
|
||||
pub fn name(self) -> String {
|
||||
match self {
|
||||
Self::Thin => "Remove connecting events".into(),
|
||||
Self::Delay => "Delay the gesture".into(),
|
||||
Self::Lengthen => "Lengthen arrivals".into(),
|
||||
Self::Transpose(n) => format!("Transpose {n:+} semitones"),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn name_valid(name: &str) -> bool {
|
||||
!name.trim().is_empty() && name.chars().count() <= 64
|
||||
}
|
||||
impl Session {
|
||||
pub fn export_gesture_library(&self) -> Result<Vec<u8>> {
|
||||
self.validate_creative()?;
|
||||
serde_json::to_vec(&LibraryFile {
|
||||
version: 1,
|
||||
gestures: self.gestures.clone(),
|
||||
})
|
||||
.map_err(|e| Error(e.to_string()))
|
||||
}
|
||||
pub fn import_gesture_library(&mut self, gestures: Vec<Gesture>) -> Result<usize> {
|
||||
if self.gestures.len() + gestures.len() > MAX_GESTURES {
|
||||
return Err(err("The combined gesture library would exceed 16 entries."));
|
||||
}
|
||||
let mut next = self.clone();
|
||||
let count = gestures.len();
|
||||
for mut g in gestures {
|
||||
g.id = next.allocate_id()?;
|
||||
next.gestures.push(g);
|
||||
}
|
||||
next.validate()?;
|
||||
*self = next;
|
||||
Ok(count)
|
||||
}
|
||||
fn allocate_id(&mut self) -> Result<u64> {
|
||||
let highest = self
|
||||
.gestures
|
||||
.iter()
|
||||
.map(|g| g.id)
|
||||
.chain(self.branches.iter().map(|b| b.id))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
let id = self.next_id.max(highest.saturating_add(1));
|
||||
self.next_id = id
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| err("Idea identifier limit reached."))?;
|
||||
Ok(id)
|
||||
}
|
||||
pub(crate) fn validate_creative(&self) -> Result<()> {
|
||||
if self.gestures.len() > MAX_GESTURES || self.branches.len() > MAX_BRANCHES {
|
||||
return Err(err(
|
||||
"At most 16 gestures and 16 branches can be stored per session.",
|
||||
));
|
||||
}
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
for g in &self.gestures {
|
||||
if g.id == 0 || !ids.insert(g.id) || !name_valid(&g.name) {
|
||||
return Err(err("Invalid gesture name or identifier."));
|
||||
}
|
||||
g.phrase.validate_source()?;
|
||||
g.performance.validate()?;
|
||||
}
|
||||
for b in &self.branches {
|
||||
if b.id == 0 || !ids.insert(b.id) || !name_valid(&b.name) {
|
||||
return Err(err("Invalid branch name or identifier."));
|
||||
}
|
||||
if b.parent.is_some_and(|parent| {
|
||||
parent >= b.id || !self.branches.iter().any(|p| p.id == parent)
|
||||
}) {
|
||||
return Err(err("Invalid branch ancestry."));
|
||||
}
|
||||
b.idea.validate()?;
|
||||
}
|
||||
if self
|
||||
.active_branch
|
||||
.is_some_and(|id| !self.branches.iter().any(|b| b.id == id))
|
||||
{
|
||||
return Err(err("Active branch does not exist."));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn save_gesture(&mut self, name: &str, section: Option<usize>) -> Result<u64> {
|
||||
self.performance.validate()?;
|
||||
if !name_valid(name) {
|
||||
return Err(err("Name the gesture using 1–64 characters."));
|
||||
}
|
||||
if self.gestures.len() >= MAX_GESTURES {
|
||||
return Err(err(
|
||||
"Gesture library is full. Remove an unused gesture or save another session.",
|
||||
));
|
||||
}
|
||||
let phrase = if let Some(index) = section {
|
||||
let p = self.composed_phrase()?;
|
||||
let start = index as u32 * SECTION;
|
||||
let end = start + SECTION;
|
||||
if index >= self.settings.bars as usize / 2
|
||||
|| p.notes.iter().any(|n| {
|
||||
(n.start < start && n.end() > start) || (n.start < end && n.end() > end)
|
||||
})
|
||||
{
|
||||
return Err(err("Choose a two-bar section without crossing notes."));
|
||||
}
|
||||
Phrase {
|
||||
length: SECTION,
|
||||
notes: p
|
||||
.notes
|
||||
.iter()
|
||||
.filter(|n| n.start >= start && n.start < end)
|
||||
.map(|n| Note {
|
||||
start: n.start - start,
|
||||
..*n
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
} else {
|
||||
self.source
|
||||
.clone()
|
||||
.ok_or_else(|| err("Import a motif first."))?
|
||||
};
|
||||
phrase.validate_source()?;
|
||||
let id = self.allocate_id()?;
|
||||
self.gestures.push(Gesture {
|
||||
id,
|
||||
name: name.trim().into(),
|
||||
phrase,
|
||||
performance: self.performance.clone(),
|
||||
});
|
||||
Ok(id)
|
||||
}
|
||||
pub fn recall_gesture(&mut self, id: u64) -> Result<()> {
|
||||
let gesture = self
|
||||
.gestures
|
||||
.iter()
|
||||
.find(|g| g.id == id)
|
||||
.cloned()
|
||||
.ok_or_else(|| err("Gesture does not exist."))?;
|
||||
self.source = Some(gesture.phrase);
|
||||
self.performance = gesture.performance;
|
||||
self.pins.clear();
|
||||
self.candidates.clear();
|
||||
self.selected = 0;
|
||||
self.active_branch = None;
|
||||
Ok(())
|
||||
}
|
||||
pub fn save_branch(&mut self, name: &str) -> Result<u64> {
|
||||
if !name_valid(name) {
|
||||
return Err(err("Name the branch using 1–64 characters."));
|
||||
}
|
||||
if self.branches.len() >= MAX_BRANCHES {
|
||||
return Err(err(
|
||||
"Branch history is full. Remove an unused leaf branch or save another session.",
|
||||
));
|
||||
}
|
||||
let idea = IdeaSnapshot {
|
||||
source: self.source.clone(),
|
||||
settings: self.settings.clone(),
|
||||
harmony: self.harmony.clone(),
|
||||
phrase: if self.candidates.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(self.composed_phrase()?)
|
||||
},
|
||||
pins: self.pins.clone(),
|
||||
performance: self.performance.clone(),
|
||||
};
|
||||
idea.validate()?;
|
||||
let id = self.allocate_id()?;
|
||||
self.branches.push(Branch {
|
||||
id,
|
||||
parent: self.active_branch,
|
||||
name: name.trim().into(),
|
||||
idea,
|
||||
});
|
||||
self.active_branch = Some(id);
|
||||
Ok(id)
|
||||
}
|
||||
pub fn restore_branch(&mut self, id: u64) -> Result<()> {
|
||||
let b = self
|
||||
.branches
|
||||
.iter()
|
||||
.find(|b| b.id == id)
|
||||
.cloned()
|
||||
.ok_or_else(|| err("Branch does not exist."))?;
|
||||
b.idea.validate()?;
|
||||
self.source = b.idea.source;
|
||||
self.settings = b.idea.settings;
|
||||
self.harmony = b.idea.harmony;
|
||||
self.pins = b.idea.pins;
|
||||
self.performance = b.idea.performance;
|
||||
self.candidates = b
|
||||
.idea
|
||||
.phrase
|
||||
.into_iter()
|
||||
.map(|phrase| Candidate {
|
||||
strategy: Strategy::SavedIdea,
|
||||
explanation: format!("Restored branch: {}", b.name),
|
||||
phrase,
|
||||
})
|
||||
.collect();
|
||||
self.selected = 0;
|
||||
self.active_branch = Some(id);
|
||||
Ok(())
|
||||
}
|
||||
pub fn remove_branch(&mut self, id: u64) -> Result<()> {
|
||||
if self.branches.iter().any(|b| b.parent == Some(id)) {
|
||||
return Err(err("Remove child branches first."));
|
||||
}
|
||||
let index = self
|
||||
.branches
|
||||
.iter()
|
||||
.position(|b| b.id == id)
|
||||
.ok_or_else(|| err("Branch does not exist."))?;
|
||||
if self.active_branch == Some(id) {
|
||||
self.active_branch = self.branches[index].parent;
|
||||
}
|
||||
self.branches.remove(index);
|
||||
Ok(())
|
||||
}
|
||||
/// Moves operate on heard selections, respect pinned material/locks, and preserve their parent.
|
||||
pub fn apply_move(&mut self, operation: CreativeMove, section: Option<usize>) -> Result<()> {
|
||||
if section.is_some_and(|i| i >= self.settings.bars as usize / 2) {
|
||||
return Err(err("Section is outside the phrase."));
|
||||
}
|
||||
if self.settings.preserve_rhythm && !matches!(operation, CreativeMove::Transpose(_)) {
|
||||
return Err(err(
|
||||
"Release Keep groove before changing rhythm or articulation.",
|
||||
));
|
||||
}
|
||||
let old = self.composed_phrase()?;
|
||||
let mut phrase = old.clone();
|
||||
let in_selection = |n: &Note| {
|
||||
section.is_none_or(|i| n.start / SECTION == i as u32)
|
||||
&& !self
|
||||
.pins
|
||||
.iter()
|
||||
.any(|p| n.start / SECTION == p.index as u32)
|
||||
};
|
||||
match operation {
|
||||
CreativeMove::Thin => {
|
||||
let mut index = 0;
|
||||
phrase.notes.retain(|n| {
|
||||
if !in_selection(n) {
|
||||
return true;
|
||||
}
|
||||
let keep = index % 2 == 0 || n.is_anchor();
|
||||
index += 1;
|
||||
keep
|
||||
});
|
||||
}
|
||||
CreativeMove::Transpose(steps) => {
|
||||
for n in phrase
|
||||
.notes
|
||||
.iter_mut()
|
||||
.filter(|n| in_selection(n) && !n.keeps_pitch())
|
||||
{
|
||||
let pitch = n.pitch as i16 + steps as i16;
|
||||
if pitch < self.settings.low as i16 || pitch > self.settings.high as i16 {
|
||||
return Err(err("The transposition exceeds the chosen register. Widen it or choose a smaller move."));
|
||||
}
|
||||
n.pitch = pitch as u8;
|
||||
}
|
||||
}
|
||||
CreativeMove::Delay => {
|
||||
for n in phrase
|
||||
.notes
|
||||
.iter_mut()
|
||||
.filter(|n| in_selection(n) && !n.keeps_rhythm())
|
||||
{
|
||||
let boundary = ((n.start / SECTION) + 1) * SECTION;
|
||||
if n.end() + PPQ / 4 > boundary.min(phrase.length) {
|
||||
return Err(err(
|
||||
"The delayed gesture would cross the selected section boundary.",
|
||||
));
|
||||
}
|
||||
n.start += PPQ / 4;
|
||||
}
|
||||
phrase.notes.sort_by_key(|n| n.start);
|
||||
phrase.validate(MAX_PLAYBACK_NOTES).map_err(|_| {
|
||||
err("The delayed gesture would overlap protected or unselected material.")
|
||||
})?;
|
||||
}
|
||||
CreativeMove::Lengthen => {
|
||||
for i in 0..phrase.notes.len() {
|
||||
let boundary = ((phrase.notes[i].start / SECTION) + 1) * SECTION;
|
||||
let next = phrase
|
||||
.notes
|
||||
.get(i + 1)
|
||||
.map_or(phrase.length, |n| n.start)
|
||||
.min(boundary);
|
||||
let n = &mut phrase.notes[i];
|
||||
if !in_selection(n) || n.keeps_rhythm() {
|
||||
continue;
|
||||
}
|
||||
n.duration = (n.duration + n.duration / 2).min(next - n.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
phrase.validate(MAX_PLAYBACK_NOTES)?;
|
||||
if phrase == old {
|
||||
return Err(err(
|
||||
"The chosen move is blocked by locks, pins, or available space.",
|
||||
));
|
||||
}
|
||||
let mut next = self.clone();
|
||||
if next.active_branch.is_none() {
|
||||
next.save_branch("Starting idea")?;
|
||||
}
|
||||
let label = operation.name();
|
||||
next.candidates = vec![Candidate {
|
||||
strategy: Strategy::SavedIdea,
|
||||
explanation: label.clone(),
|
||||
phrase,
|
||||
}];
|
||||
next.selected = 0;
|
||||
next.save_branch(&label)?;
|
||||
next.validate()?;
|
||||
*self = next;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
use crate::{err, Note, Result, Scale, BAR, MAX_PLAYBACK_NOTES};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum ChordQuality {
|
||||
Major,
|
||||
Minor,
|
||||
Major7,
|
||||
Minor7,
|
||||
Sus2,
|
||||
Sus4,
|
||||
}
|
||||
impl ChordQuality {
|
||||
pub const ALL: [Self; 6] = [
|
||||
Self::Major,
|
||||
Self::Minor,
|
||||
Self::Major7,
|
||||
Self::Minor7,
|
||||
Self::Sus2,
|
||||
Self::Sus4,
|
||||
];
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Major => "Major",
|
||||
Self::Minor => "Minor",
|
||||
Self::Major7 => "Major 7",
|
||||
Self::Minor7 => "Minor 7",
|
||||
Self::Sus2 => "Sus 2",
|
||||
Self::Sus4 => "Sus 4",
|
||||
}
|
||||
}
|
||||
pub fn mask(self, root: u8) -> u16 {
|
||||
let intervals: &[u8] = match self {
|
||||
Self::Major => &[0, 4, 7],
|
||||
Self::Minor => &[0, 3, 7],
|
||||
Self::Major7 => &[0, 4, 7, 11],
|
||||
Self::Minor7 => &[0, 3, 7, 10],
|
||||
Self::Sus2 => &[0, 2, 7],
|
||||
Self::Sus4 => &[0, 5, 7],
|
||||
};
|
||||
intervals
|
||||
.iter()
|
||||
.fold(0, |mask, i| mask | 1 << ((root + i) % 12))
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct HarmonySpan {
|
||||
pub start: u32,
|
||||
pub duration: u32,
|
||||
pub tones: u16,
|
||||
pub bass: u8,
|
||||
}
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct Harmony {
|
||||
pub length: u32,
|
||||
pub spans: Vec<HarmonySpan>,
|
||||
}
|
||||
impl Harmony {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.spans.is_empty() {
|
||||
return if self.length == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(err("Empty harmony must have zero length."))
|
||||
};
|
||||
}
|
||||
if self.length == 0 || self.length > 8 * BAR || self.spans.len() > 256 {
|
||||
return Err(err("Harmony must fit eight bars and at most 256 changes."));
|
||||
}
|
||||
let mut end = 0;
|
||||
for span in &self.spans {
|
||||
if span.duration == 0
|
||||
|| span.start < end
|
||||
|| span.start.saturating_add(span.duration) > self.length
|
||||
|| span.tones == 0
|
||||
|| span.tones > 0xfff
|
||||
|| span.bass > 127
|
||||
{
|
||||
return Err(err("Invalid or overlapping harmonic regions."));
|
||||
}
|
||||
end = span.start + span.duration;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn at(&self, tick: u32) -> Option<&HarmonySpan> {
|
||||
if self.length == 0 {
|
||||
return None;
|
||||
}
|
||||
let tick = tick % self.length;
|
||||
self.spans
|
||||
.iter()
|
||||
.find(|s| tick >= s.start && tick < s.start + s.duration)
|
||||
}
|
||||
pub fn from_midi(notes: &[Note], length: u32) -> Result<Self> {
|
||||
if notes.is_empty() || notes.len() > MAX_PLAYBACK_NOTES || length == 0 || length > 8 * BAR {
|
||||
return Err(err("Import a harmony track of up to eight bars."));
|
||||
}
|
||||
let mut edges = std::collections::BTreeSet::new();
|
||||
for n in notes {
|
||||
if n.pitch > 127 || n.duration == 0 || n.end() > length {
|
||||
return Err(err("Invalid harmony note."));
|
||||
}
|
||||
edges.insert(n.start);
|
||||
edges.insert(n.end());
|
||||
}
|
||||
let edges: Vec<_> = edges.into_iter().collect();
|
||||
let mut spans: Vec<HarmonySpan> = Vec::new();
|
||||
for pair in edges.windows(2) {
|
||||
let active: Vec<_> = notes
|
||||
.iter()
|
||||
.filter(|n| n.start <= pair[0] && n.end() > pair[0])
|
||||
.collect();
|
||||
if active.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let tones = active.iter().fold(0, |mask, n| mask | 1 << (n.pitch % 12));
|
||||
let bass = active.iter().map(|n| n.pitch).min().unwrap();
|
||||
if let Some(last) = spans.last_mut() {
|
||||
if last.start + last.duration == pair[0] && last.tones == tones && last.bass == bass
|
||||
{
|
||||
last.duration += pair[1] - pair[0];
|
||||
continue;
|
||||
}
|
||||
}
|
||||
spans.push(HarmonySpan {
|
||||
start: pair[0],
|
||||
duration: pair[1] - pair[0],
|
||||
tones,
|
||||
bass,
|
||||
});
|
||||
}
|
||||
let context = Self { length, spans };
|
||||
context.validate()?;
|
||||
Ok(context)
|
||||
}
|
||||
pub fn progression(root: u8, scale: Scale) -> Self {
|
||||
let minor = scale != Scale::Major;
|
||||
let chords = if minor {
|
||||
[
|
||||
(0, ChordQuality::Minor),
|
||||
(8, ChordQuality::Major),
|
||||
(3, ChordQuality::Major),
|
||||
(10, ChordQuality::Major),
|
||||
]
|
||||
} else {
|
||||
[
|
||||
(0, ChordQuality::Major),
|
||||
(9, ChordQuality::Minor),
|
||||
(5, ChordQuality::Major),
|
||||
(7, ChordQuality::Major),
|
||||
]
|
||||
};
|
||||
Self {
|
||||
length: 4 * BAR,
|
||||
spans: chords
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, (step, quality))| {
|
||||
let root = (root + step) % 12;
|
||||
HarmonySpan {
|
||||
start: i as u32 * BAR,
|
||||
duration: BAR,
|
||||
tones: quality.mask(root),
|
||||
bass: 48 + root,
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
//! Musical time and deterministic motif development, independent of the host and UI.
|
||||
mod creative;
|
||||
mod harmony;
|
||||
mod performance;
|
||||
mod playback;
|
||||
mod variation;
|
||||
pub use creative::{
|
||||
read_gesture_library, Branch, CreativeMove, Gesture, IdeaSnapshot, MAX_BRANCHES, MAX_GESTURES,
|
||||
};
|
||||
pub use harmony::{ChordQuality, Harmony, HarmonySpan};
|
||||
pub use performance::*;
|
||||
pub use playback::{PlaybackClip, PreviewPlayer, MAX_PLAYBACK_NOTES};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
pub const PPQ: u32 = 960;
|
||||
pub const BAR: u32 = PPQ * 4;
|
||||
pub const MAX_SOURCE_NOTES: usize = 256;
|
||||
pub const STATE_VERSION: u32 = 3;
|
||||
pub const MAX_STATE_BYTES: usize = 16 * 1024 * 1024;
|
||||
pub const SECTION: u32 = 2 * BAR;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Error(pub String);
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
fn err(s: &str) -> Error {
|
||||
Error(s.into())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct Note {
|
||||
pub start: u32,
|
||||
pub duration: u32,
|
||||
pub pitch: u8,
|
||||
pub velocity: u8,
|
||||
pub locked: bool,
|
||||
#[serde(default)]
|
||||
pub pitch_locked: bool,
|
||||
#[serde(default)]
|
||||
pub rhythm_locked: bool,
|
||||
}
|
||||
impl Note {
|
||||
pub fn end(&self) -> u32 {
|
||||
self.start.saturating_add(self.duration)
|
||||
}
|
||||
pub fn keeps_pitch(&self) -> bool {
|
||||
self.locked || self.pitch_locked
|
||||
}
|
||||
pub fn keeps_rhythm(&self) -> bool {
|
||||
self.locked || self.rhythm_locked
|
||||
}
|
||||
pub fn is_anchor(&self) -> bool {
|
||||
self.locked || self.pitch_locked || self.rhythm_locked
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct Phrase {
|
||||
pub notes: Vec<Note>,
|
||||
pub length: u32,
|
||||
}
|
||||
impl Phrase {
|
||||
pub fn validate(&self, max_notes: usize) -> Result<()> {
|
||||
if self.notes.is_empty() || self.notes.len() > max_notes {
|
||||
return Err(err(
|
||||
"Choose a phrase containing between 1 and the supported maximum number of notes.",
|
||||
));
|
||||
}
|
||||
if self.length == 0 || self.length > 8 * BAR {
|
||||
return Err(err(
|
||||
"Phrase length must be positive and at most eight bars.",
|
||||
));
|
||||
}
|
||||
let mut end = 0;
|
||||
for n in &self.notes {
|
||||
if n.duration == 0
|
||||
|| n.pitch > 127
|
||||
|| n.velocity == 0
|
||||
|| n.velocity > 127
|
||||
|| n.end() > self.length
|
||||
{
|
||||
return Err(err("Notes must have positive duration and velocity, valid MIDI values, and fit inside the phrase."));
|
||||
}
|
||||
if n.start < end {
|
||||
return Err(err(
|
||||
"Overlapping notes are unsupported. Select a monophonic MIDI track.",
|
||||
));
|
||||
}
|
||||
end = n.end();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn validate_source(&self) -> Result<()> {
|
||||
self.validate(MAX_SOURCE_NOTES)?;
|
||||
if self.length > 2 * BAR {
|
||||
return Err(err("Select a motif of at most two bars in 4/4."));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum Scale {
|
||||
Minor,
|
||||
Major,
|
||||
Dorian,
|
||||
Pentatonic,
|
||||
}
|
||||
impl Scale {
|
||||
pub const ALL: [Self; 4] = [Self::Minor, Self::Major, Self::Dorian, Self::Pentatonic];
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Minor => "Natural minor",
|
||||
Self::Major => "Major",
|
||||
Self::Dorian => "Dorian",
|
||||
Self::Pentatonic => "Minor pentatonic",
|
||||
}
|
||||
}
|
||||
pub fn intervals(self) -> &'static [u8] {
|
||||
match self {
|
||||
Self::Minor => &[0, 2, 3, 5, 7, 8, 10],
|
||||
Self::Major => &[0, 2, 4, 5, 7, 9, 11],
|
||||
Self::Dorian => &[0, 2, 3, 5, 7, 9, 10],
|
||||
Self::Pentatonic => &[0, 3, 5, 7, 10],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(default)]
|
||||
pub struct Settings {
|
||||
pub bars: u8,
|
||||
pub root: u8,
|
||||
pub scale: Scale,
|
||||
pub variation: u8,
|
||||
pub preserve_rhythm: bool,
|
||||
pub preserve_contour: bool,
|
||||
pub task: Task,
|
||||
pub ending: Ending,
|
||||
pub low: u8,
|
||||
pub high: u8,
|
||||
pub seed: u64,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
bars: 8,
|
||||
root: 0,
|
||||
scale: Scale::Minor,
|
||||
variation: 55,
|
||||
preserve_rhythm: false,
|
||||
preserve_contour: true,
|
||||
task: Task::Develop,
|
||||
ending: Ending::Resolve,
|
||||
low: 48,
|
||||
high: 84,
|
||||
seed: 42,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum Task {
|
||||
#[default]
|
||||
Develop,
|
||||
Answer,
|
||||
MakeSpace,
|
||||
Return,
|
||||
}
|
||||
impl Task {
|
||||
pub const ALL: [Self; 4] = [Self::Develop, Self::Answer, Self::MakeSpace, Self::Return];
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Develop => "Develop the motif",
|
||||
Self::Answer => "Write an answer",
|
||||
Self::MakeSpace => "Make room",
|
||||
Self::Return => "Find a return",
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum Ending {
|
||||
#[default]
|
||||
Resolve,
|
||||
Open,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum Audition {
|
||||
#[default]
|
||||
Internal,
|
||||
Midi,
|
||||
}
|
||||
impl Settings {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if ![4, 8].contains(&self.bars)
|
||||
|| self.root > 11
|
||||
|| self.variation > 100
|
||||
|| self.low > self.high
|
||||
|| self.high > 127
|
||||
{
|
||||
return Err(err("Use four or eight bars, a valid key, variation 0–100, and an ordered MIDI register."));
|
||||
}
|
||||
if !(self.low..=self.high).any(|p| self.contains(p)) {
|
||||
return Err(err(
|
||||
"The register must contain at least one note in the selected scale.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn contains(&self, p: u8) -> bool {
|
||||
self.scale
|
||||
.intervals()
|
||||
.contains(&((p + 12 - self.root) % 12))
|
||||
}
|
||||
fn degree(&self, p: u8, steps: i16) -> u8 {
|
||||
let choices: Vec<_> = (self.low..=self.high)
|
||||
.filter(|&n| self.contains(n))
|
||||
.collect();
|
||||
let index = choices
|
||||
.iter()
|
||||
.enumerate()
|
||||
.min_by_key(|(_, n)| (**n as i16 - p as i16).abs())
|
||||
.map(|(i, _)| i)
|
||||
.unwrap_or(0) as i16;
|
||||
choices[(index + steps).clamp(0, choices.len() as i16 - 1) as usize]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum Strategy {
|
||||
ChangedEnding,
|
||||
LaterPeak,
|
||||
DelayedResolution,
|
||||
NewRhythm,
|
||||
FragmentAnswer,
|
||||
NegativeSpace,
|
||||
CallResponse,
|
||||
HarmonicReturn,
|
||||
SavedIdea,
|
||||
}
|
||||
impl Strategy {
|
||||
pub const ALL: [Self; 8] = [
|
||||
Self::NewRhythm,
|
||||
Self::FragmentAnswer,
|
||||
Self::NegativeSpace,
|
||||
Self::CallResponse,
|
||||
Self::HarmonicReturn,
|
||||
Self::ChangedEnding,
|
||||
Self::LaterPeak,
|
||||
Self::DelayedResolution,
|
||||
];
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::ChangedEnding => "Changed ending",
|
||||
Self::LaterPeak => "Later peak",
|
||||
Self::DelayedResolution => "Delayed resolution",
|
||||
Self::NewRhythm => "Displaced groove",
|
||||
Self::FragmentAnswer => "Fragment and answer",
|
||||
Self::NegativeSpace => "Room to breathe",
|
||||
Self::CallResponse => "Short question, long answer",
|
||||
Self::HarmonicReturn => "Familiar return",
|
||||
Self::SavedIdea => "Working gesture",
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Candidate {
|
||||
pub strategy: Strategy,
|
||||
pub explanation: String,
|
||||
pub phrase: Phrase,
|
||||
}
|
||||
|
||||
/// Generate context-free proposals. Use `generate_with_harmony` when harmony is available.
|
||||
pub fn generate(source: &Phrase, settings: &Settings) -> Result<Vec<Candidate>> {
|
||||
generate_with_harmony(source, settings, &Harmony::default())
|
||||
}
|
||||
pub fn generate_with_harmony(
|
||||
source: &Phrase,
|
||||
settings: &Settings,
|
||||
harmony: &Harmony,
|
||||
) -> Result<Vec<Candidate>> {
|
||||
variation::generate(source, settings, harmony)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct PinnedSection {
|
||||
pub index: usize,
|
||||
pub phrase: Phrase,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Session {
|
||||
pub version: u32,
|
||||
pub source: Option<Phrase>,
|
||||
pub settings: Settings,
|
||||
pub candidates: Vec<Candidate>,
|
||||
pub selected: usize,
|
||||
pub accepted: Option<Phrase>,
|
||||
pub previous_accepted: Option<Phrase>,
|
||||
pub tempo: f64,
|
||||
pub follow_host: bool,
|
||||
#[serde(default)]
|
||||
pub harmony: Harmony,
|
||||
#[serde(default)]
|
||||
pub pins: Vec<PinnedSection>,
|
||||
#[serde(default)]
|
||||
pub audition: Audition,
|
||||
#[serde(default)]
|
||||
pub looping: bool,
|
||||
#[serde(default)]
|
||||
pub performance: PerformanceSettings,
|
||||
#[serde(default)]
|
||||
pub gestures: Vec<Gesture>,
|
||||
#[serde(default)]
|
||||
pub branches: Vec<Branch>,
|
||||
#[serde(default)]
|
||||
pub active_branch: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub next_id: u64,
|
||||
}
|
||||
impl Default for Session {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: STATE_VERSION,
|
||||
source: None,
|
||||
settings: Settings::default(),
|
||||
candidates: Vec::new(),
|
||||
selected: 0,
|
||||
accepted: None,
|
||||
previous_accepted: None,
|
||||
tempo: 140.0,
|
||||
follow_host: false,
|
||||
harmony: Harmony::default(),
|
||||
pins: Vec::new(),
|
||||
audition: Audition::Internal,
|
||||
looping: true,
|
||||
performance: PerformanceSettings::default(),
|
||||
gestures: Vec::new(),
|
||||
branches: Vec::new(),
|
||||
active_branch: None,
|
||||
next_id: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Session {
|
||||
pub fn migrate(&mut self) -> Result<()> {
|
||||
match self.version {
|
||||
1 | 2 => self.version = STATE_VERSION,
|
||||
STATE_VERSION => {}
|
||||
_ => return Err(err("Unsupported session version.")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn validate_pins(&self) -> Result<()> {
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for pin in &self.pins {
|
||||
if pin.index >= self.settings.bars as usize / 2
|
||||
|| !seen.insert(pin.index)
|
||||
|| pin.phrase.length != SECTION
|
||||
{
|
||||
return Err(err("Invalid pinned section."));
|
||||
}
|
||||
if !pin.phrase.notes.is_empty() {
|
||||
pin.phrase.validate(MAX_PLAYBACK_NOTES)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn pin_selected(&mut self, index: usize) -> Result<()> {
|
||||
if index >= self.settings.bars as usize / 2 {
|
||||
return Err(err("Section is outside the phrase."));
|
||||
}
|
||||
let source = self
|
||||
.selected_phrase()
|
||||
.ok_or_else(|| err("Generate a candidate first."))?;
|
||||
let start = index as u32 * SECTION;
|
||||
let end = start + SECTION;
|
||||
if source
|
||||
.notes
|
||||
.iter()
|
||||
.any(|n| (n.start < start && n.end() > start) || (n.start < end && n.end() > end))
|
||||
{
|
||||
return Err(err(
|
||||
"A note crosses this section boundary. Edit the seam before pinning.",
|
||||
));
|
||||
}
|
||||
let phrase = Phrase {
|
||||
length: SECTION,
|
||||
notes: source
|
||||
.notes
|
||||
.iter()
|
||||
.filter(|n| n.start >= start && n.start < end)
|
||||
.map(|n| Note {
|
||||
start: n.start - start,
|
||||
..*n
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
self.pins.retain(|pin| pin.index != index);
|
||||
self.pins.push(PinnedSection { index, phrase });
|
||||
self.pins.sort_by_key(|p| p.index);
|
||||
Ok(())
|
||||
}
|
||||
pub fn composed_phrase(&self) -> Result<Phrase> {
|
||||
self.validate_pins()?;
|
||||
let mut phrase = self
|
||||
.selected_phrase()
|
||||
.cloned()
|
||||
.ok_or_else(|| err("Generate a candidate first."))?;
|
||||
for pin in &self.pins {
|
||||
let start = pin.index as u32 * SECTION;
|
||||
let end = start + SECTION;
|
||||
if phrase
|
||||
.notes
|
||||
.iter()
|
||||
.any(|n| (n.start < start && n.end() > start) || (n.start < end && n.end() > end))
|
||||
{
|
||||
return Err(err("A candidate note crosses a pinned section boundary."));
|
||||
}
|
||||
phrase.notes.retain(|n| n.start < start || n.start >= end);
|
||||
phrase.notes.extend(pin.phrase.notes.iter().map(|n| Note {
|
||||
start: n.start + start,
|
||||
..*n
|
||||
}));
|
||||
}
|
||||
phrase.notes.sort_by_key(|n| n.start);
|
||||
phrase.validate(MAX_PLAYBACK_NOTES)?;
|
||||
Ok(phrase)
|
||||
}
|
||||
pub fn accept_composed(&mut self) -> Result<()> {
|
||||
let phrase = self.composed_phrase()?;
|
||||
self.previous_accepted = self.accepted.replace(phrase);
|
||||
Ok(())
|
||||
}
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.version != STATE_VERSION {
|
||||
return Err(err("Unsupported session version."));
|
||||
}
|
||||
self.settings.validate()?;
|
||||
self.performance.validate()?;
|
||||
self.validate_creative()?;
|
||||
self.harmony.validate()?;
|
||||
self.validate_pins()?;
|
||||
if !self.tempo.is_finite() || !(30.0..=300.0).contains(&self.tempo) {
|
||||
return Err(err("Tempo must be between 30 and 300 BPM."));
|
||||
}
|
||||
if let Some(p) = &self.source {
|
||||
p.validate_source()?;
|
||||
}
|
||||
if self.candidates.len() > 3
|
||||
|| (!self.candidates.is_empty() && self.selected >= self.candidates.len())
|
||||
{
|
||||
return Err(err("Invalid candidate selection."));
|
||||
}
|
||||
for p in self
|
||||
.candidates
|
||||
.iter()
|
||||
.map(|c| &c.phrase)
|
||||
.chain(self.accepted.iter())
|
||||
.chain(self.previous_accepted.iter())
|
||||
{
|
||||
p.validate(MAX_PLAYBACK_NOTES)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn from_json(bytes: &[u8]) -> Result<Self> {
|
||||
if bytes.len() > MAX_STATE_BYTES {
|
||||
return Err(err("Session exceeds the 16 MiB limit."));
|
||||
}
|
||||
let mut session: Self = serde_json::from_slice(bytes).map_err(|e| Error(e.to_string()))?;
|
||||
session.migrate()?;
|
||||
session.validate()?;
|
||||
Ok(session)
|
||||
}
|
||||
pub fn to_json(&self) -> Result<Vec<u8>> {
|
||||
self.validate()?;
|
||||
let bytes = serde_json::to_vec(self).map_err(|e| Error(e.to_string()))?;
|
||||
if bytes.len() > MAX_STATE_BYTES {
|
||||
return Err(err("Session exceeds the 16 MiB limit."));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
pub fn regenerate(&mut self) -> Result<()> {
|
||||
let source = self
|
||||
.source
|
||||
.as_ref()
|
||||
.ok_or_else(|| err("Import a MIDI motif first."))?;
|
||||
self.candidates = generate_with_harmony(source, &self.settings, &self.harmony)?;
|
||||
self.selected = 0;
|
||||
Ok(())
|
||||
}
|
||||
pub fn selected_phrase(&self) -> Option<&Phrase> {
|
||||
self.candidates.get(self.selected).map(|c| &c.phrase)
|
||||
}
|
||||
pub fn accept(&mut self) {
|
||||
if let Some(p) = self.selected_phrase().cloned() {
|
||||
self.previous_accepted = self.accepted.replace(p);
|
||||
}
|
||||
}
|
||||
pub fn undo_accept(&mut self) {
|
||||
std::mem::swap(&mut self.accepted, &mut self.previous_accepted);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn demo_motif() -> Phrase {
|
||||
Phrase {
|
||||
length: 2 * BAR,
|
||||
notes: [
|
||||
(0, 60),
|
||||
(720, 67),
|
||||
(1440, 63),
|
||||
(2880, 62),
|
||||
(4320, 67),
|
||||
(5760, 65),
|
||||
(6720, 63),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(start, pitch)| Note {
|
||||
start,
|
||||
pitch,
|
||||
duration: 480,
|
||||
velocity: 90,
|
||||
locked: false,
|
||||
..Note::default()
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn reproducible_distinct_and_bounded() {
|
||||
let source = demo_motif();
|
||||
let s = Settings::default();
|
||||
let a = generate(&source, &s).unwrap();
|
||||
assert_eq!(a, generate(&source, &s).unwrap());
|
||||
assert_ne!(a[0].phrase, a[1].phrase);
|
||||
assert_ne!(a[1].phrase, a[2].phrase);
|
||||
for c in a {
|
||||
c.phrase.validate(MAX_PLAYBACK_NOTES).unwrap();
|
||||
assert_eq!(c.phrase.length, 8 * BAR);
|
||||
assert_eq!(
|
||||
&c.phrase.notes[..source.notes.len()],
|
||||
source.notes.as_slice()
|
||||
);
|
||||
for n in c.phrase.notes.iter().filter(|n| n.start >= source.length) {
|
||||
assert!((s.low..=s.high).contains(&n.pitch));
|
||||
assert!(s.contains(n.pitch));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn locks_preserve_all_attributes_even_outside_scale_and_register() {
|
||||
let mut source = demo_motif();
|
||||
source.notes[2].locked = true;
|
||||
source.notes[2].pitch = 99;
|
||||
for c in generate(
|
||||
&source,
|
||||
&Settings {
|
||||
preserve_rhythm: false,
|
||||
..Settings::default()
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
{
|
||||
for rep in 0..4 {
|
||||
let mut expected = source.notes[2];
|
||||
expected.start += rep * source.length;
|
||||
assert!(c.phrase.notes.contains(&expected));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn all_keys_register_edges_and_seeds() {
|
||||
for root in 0..12 {
|
||||
for scale in Scale::ALL {
|
||||
for seed in 0..12 {
|
||||
for bars in [4, 8] {
|
||||
let s = Settings {
|
||||
root,
|
||||
scale,
|
||||
seed,
|
||||
bars,
|
||||
low: 60,
|
||||
high: 72,
|
||||
preserve_rhythm: false,
|
||||
..Settings::default()
|
||||
};
|
||||
for c in generate(&demo_motif(), &s).unwrap() {
|
||||
c.phrase.validate(MAX_PLAYBACK_NOTES).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn session_round_trip_and_accept_history() {
|
||||
let mut s = Session {
|
||||
source: Some(demo_motif()),
|
||||
..Session::default()
|
||||
};
|
||||
s.regenerate().unwrap();
|
||||
s.accept();
|
||||
let first = s.accepted.clone();
|
||||
s.selected = 1;
|
||||
s.accept();
|
||||
s.undo_accept();
|
||||
assert_eq!(s.accepted, first);
|
||||
s.settings.seed += 1;
|
||||
s.regenerate().unwrap();
|
||||
assert_eq!(s.accepted, first);
|
||||
assert_eq!(Session::from_json(&s.to_json().unwrap()).unwrap(), s);
|
||||
s.version = 99;
|
||||
assert!(s.to_json().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn invalid_inputs_and_non_divisible_lengths() {
|
||||
let mut source = demo_motif();
|
||||
source.notes[1].start = 1;
|
||||
assert!(generate(&source, &Settings::default()).is_err());
|
||||
let source = Phrase {
|
||||
notes: vec![Note {
|
||||
start: 0,
|
||||
duration: 300,
|
||||
pitch: 60,
|
||||
velocity: 80,
|
||||
locked: true,
|
||||
..Note::default()
|
||||
}],
|
||||
length: 1000,
|
||||
};
|
||||
for c in generate(&source, &Settings::default()).unwrap() {
|
||||
c.phrase.validate(MAX_PLAYBACK_NOTES).unwrap();
|
||||
}
|
||||
assert!(generate(
|
||||
&source,
|
||||
&Settings {
|
||||
low: 61,
|
||||
high: 61,
|
||||
root: 0,
|
||||
scale: Scale::Major,
|
||||
..Settings::default()
|
||||
}
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
//! Explicit sound roles and controller gestures, compiled away from the audio thread.
|
||||
use crate::{err, Note, Phrase, Result, BAR, MAX_PLAYBACK_NOTES, PPQ, SECTION};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
pub const MAX_PERFORMANCE_EVENTS: usize = 5120;
|
||||
pub const MAX_FRAME_EVENTS: usize = 64;
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum RoleMode {
|
||||
#[default]
|
||||
Solo,
|
||||
Alternating,
|
||||
CallResponse,
|
||||
Interlock,
|
||||
}
|
||||
impl RoleMode {
|
||||
pub const ALL: [Self; 4] = [
|
||||
Self::Solo,
|
||||
Self::Alternating,
|
||||
Self::CallResponse,
|
||||
Self::Interlock,
|
||||
];
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Solo => "One voice",
|
||||
Self::Alternating => "Alternate events",
|
||||
Self::CallResponse => "Question and answer",
|
||||
Self::Interlock => "Strong beats and replies",
|
||||
}
|
||||
}
|
||||
pub fn role(self, index: usize, n: &Note) -> usize {
|
||||
match self {
|
||||
Self::Solo => 0,
|
||||
Self::Alternating => index % 2,
|
||||
Self::CallResponse => usize::from(n.start % SECTION >= BAR),
|
||||
Self::Interlock => usize::from(!n.start.is_multiple_of(PPQ)),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct CurvePoint {
|
||||
pub position: u16,
|
||||
pub value: u8,
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct ControllerCurve {
|
||||
pub enabled: bool,
|
||||
pub cc: u8,
|
||||
pub rest: u8,
|
||||
pub points: Vec<CurvePoint>,
|
||||
}
|
||||
impl Default for ControllerCurve {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
cc: 1,
|
||||
rest: 0,
|
||||
points: vec![
|
||||
CurvePoint {
|
||||
position: 0,
|
||||
value: 0,
|
||||
},
|
||||
CurvePoint {
|
||||
position: 1000,
|
||||
value: 127,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ControllerCurve {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.cc == 0 || self.cc >= 120 || [32, 64, 66, 69].contains(&self.cc) || self.rest > 127
|
||||
{
|
||||
return Err(err("Choose a continuous controller in 1–119 (excluding bank/hold pedals) and a valid rest value."));
|
||||
}
|
||||
if !(2..=16).contains(&self.points.len())
|
||||
|| self.points.first().unwrap().position != 0
|
||||
|| self.points.last().unwrap().position != 1000
|
||||
|| self.points.iter().any(|p| p.value > 127)
|
||||
|| self
|
||||
.points
|
||||
.windows(2)
|
||||
.any(|p| p[0].position >= p[1].position)
|
||||
{
|
||||
return Err(err("A controller curve needs 2–16 ordered points from 0 to 1000, with MIDI values 0–127."));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn value_at(&self, position: u16) -> u8 {
|
||||
for pair in self.points.windows(2) {
|
||||
if position <= pair[1].position {
|
||||
let p = position.saturating_sub(pair[0].position) as f64
|
||||
/ (pair[1].position - pair[0].position) as f64;
|
||||
return (pair[0].value as f64 + (pair[1].value as f64 - pair[0].value as f64) * p)
|
||||
.round()
|
||||
.clamp(0., 127.) as u8;
|
||||
}
|
||||
}
|
||||
self.points.last().map_or(0, |p| p.value)
|
||||
}
|
||||
pub fn shape(&mut self, preset: usize) {
|
||||
self.points = match preset {
|
||||
1 => vec![(0, 127), (1000, 0)],
|
||||
2 => vec![(0, 0), (500, 127), (1000, 0)],
|
||||
3 => vec![
|
||||
(0, 0),
|
||||
(125, 127),
|
||||
(250, 0),
|
||||
(375, 127),
|
||||
(500, 0),
|
||||
(625, 127),
|
||||
(750, 0),
|
||||
(875, 127),
|
||||
(1000, 0),
|
||||
],
|
||||
_ => vec![(0, 0), (1000, 127)],
|
||||
}
|
||||
.into_iter()
|
||||
.map(|(position, value)| CurvePoint { position, value })
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VoiceProfile {
|
||||
pub name: String,
|
||||
pub channel: u8,
|
||||
pub transpose: i8,
|
||||
pub gate: u16,
|
||||
pub velocity: u16,
|
||||
pub attack_ms: u16,
|
||||
pub release_ms: u16,
|
||||
pub controller: ControllerCurve,
|
||||
}
|
||||
impl Default for VoiceProfile {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: "Primary".into(),
|
||||
channel: 0,
|
||||
transpose: 0,
|
||||
gate: 100,
|
||||
velocity: 100,
|
||||
attack_ms: 0,
|
||||
release_ms: 0,
|
||||
controller: ControllerCurve::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct PerformanceSettings {
|
||||
pub mode: RoleMode,
|
||||
pub voices: [VoiceProfile; 2],
|
||||
pub compensated_export: bool,
|
||||
}
|
||||
impl Default for PerformanceSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mode: RoleMode::Solo,
|
||||
voices: [
|
||||
VoiceProfile::default(),
|
||||
VoiceProfile {
|
||||
name: "Answer".into(),
|
||||
channel: 1,
|
||||
..VoiceProfile::default()
|
||||
},
|
||||
],
|
||||
compensated_export: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl PerformanceSettings {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.mode != RoleMode::Solo && self.voices[0].channel == self.voices[1].channel {
|
||||
return Err(err("Use separate MIDI channels for the two sound roles."));
|
||||
}
|
||||
for v in &self.voices {
|
||||
if v.name.chars().count() > 48
|
||||
|| v.channel > 15
|
||||
|| !(-24..=24).contains(&v.transpose)
|
||||
|| !(10..=200).contains(&v.gate)
|
||||
|| !(1..=200).contains(&v.velocity)
|
||||
|| v.attack_ms > 500
|
||||
|| v.release_ms > 2000
|
||||
{
|
||||
return Err(err("Invalid patch profile: check channel, register offset, gate, velocity, and timing limits."));
|
||||
}
|
||||
v.controller.validate()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum MessageKind {
|
||||
#[default]
|
||||
Off,
|
||||
Control,
|
||||
On,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct MidiMessage {
|
||||
pub kind: MessageKind,
|
||||
pub channel: u8,
|
||||
pub key: u8,
|
||||
pub value: u8,
|
||||
pub rest: u8,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct TimedMessage {
|
||||
pub tick: i32,
|
||||
pub role: u8,
|
||||
pub message: MidiMessage,
|
||||
pub next_cycle: bool,
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Performance {
|
||||
pub length: u32,
|
||||
pub lead_in: u32,
|
||||
pub events: Vec<TimedMessage>,
|
||||
}
|
||||
impl Performance {
|
||||
pub fn compile(
|
||||
phrase: &Phrase,
|
||||
settings: &PerformanceSettings,
|
||||
bpm: f64,
|
||||
compensate: bool,
|
||||
) -> Result<Self> {
|
||||
phrase.validate(MAX_PLAYBACK_NOTES)?;
|
||||
settings.validate()?;
|
||||
if !bpm.is_finite() || !(30.0..=300.0).contains(&bpm) {
|
||||
return Err(err("Tempo must be 30–300 BPM."));
|
||||
}
|
||||
let to_ticks = |ms: u16| (ms as f64 * bpm * PPQ as f64 / 60000.).round() as i32;
|
||||
let mut events = Vec::new();
|
||||
let mut lead_in = 0;
|
||||
for role in 0..2 {
|
||||
if role == 1 && settings.mode == RoleMode::Solo {
|
||||
continue;
|
||||
}
|
||||
let profile = &settings.voices[role];
|
||||
let attack = if compensate {
|
||||
to_ticks(profile.attack_ms)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let release = if compensate {
|
||||
to_ticks(profile.release_ms)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let routed: Vec<_> = phrase
|
||||
.notes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, n)| settings.mode.role(*i, n) == role)
|
||||
.map(|(_, n)| n)
|
||||
.collect();
|
||||
if routed.is_empty() && !profile.controller.enabled {
|
||||
continue;
|
||||
}
|
||||
lead_in = lead_in.max(attack as u32);
|
||||
for (index, n) in routed.iter().enumerate() {
|
||||
let pitch = if n.keeps_pitch() {
|
||||
n.pitch as i16
|
||||
} else {
|
||||
n.pitch as i16 + profile.transpose as i16
|
||||
};
|
||||
if !(0..=127).contains(&pitch) {
|
||||
return Err(err(
|
||||
"A sound-role register offset exceeds MIDI pitch limits.",
|
||||
));
|
||||
}
|
||||
let on = n.start as i32 - attack;
|
||||
let duration = if n.keeps_rhythm() {
|
||||
n.duration
|
||||
} else {
|
||||
(n.duration as u64 * profile.gate as u64 / 100).max(1) as u32
|
||||
};
|
||||
let wrap = routed.first().map_or(phrase.length as i32, |first| {
|
||||
phrase.length as i32 + (first.start as i32 - attack).min(0)
|
||||
});
|
||||
let next = routed
|
||||
.get(index + 1)
|
||||
.map_or(wrap, |n| n.start as i32 - attack);
|
||||
let off = (n.start as i32 + duration as i32 - release)
|
||||
.min(next)
|
||||
.min(phrase.length as i32)
|
||||
.max(on + 1);
|
||||
let velocity = if n.locked {
|
||||
n.velocity
|
||||
} else {
|
||||
(n.velocity as u32 * profile.velocity as u32 / 100).clamp(1, 127) as u8
|
||||
};
|
||||
events.push(TimedMessage {
|
||||
tick: on,
|
||||
role: role as u8,
|
||||
message: MidiMessage {
|
||||
kind: MessageKind::On,
|
||||
channel: profile.channel,
|
||||
key: pitch as u8,
|
||||
value: velocity,
|
||||
rest: 0,
|
||||
},
|
||||
next_cycle: false,
|
||||
});
|
||||
events.push(TimedMessage {
|
||||
tick: off,
|
||||
role: role as u8,
|
||||
message: MidiMessage {
|
||||
kind: MessageKind::Off,
|
||||
channel: profile.channel,
|
||||
key: pitch as u8,
|
||||
value: 0,
|
||||
rest: 0,
|
||||
},
|
||||
next_cycle: false,
|
||||
});
|
||||
}
|
||||
if profile.controller.enabled {
|
||||
let curve = &profile.controller;
|
||||
let mut points = std::collections::BTreeMap::new();
|
||||
for tick in (0..=phrase.length).step_by((PPQ / 8) as usize) {
|
||||
points.insert(
|
||||
tick as i32,
|
||||
curve.value_at((tick as u64 * 1000 / phrase.length as u64) as u16),
|
||||
);
|
||||
}
|
||||
for p in &curve.points {
|
||||
points.insert(
|
||||
(p.position as u64 * phrase.length as u64 / 1000) as i32,
|
||||
p.value,
|
||||
);
|
||||
}
|
||||
if attack > 0 {
|
||||
points.insert(-attack, curve.value_at(0));
|
||||
}
|
||||
for (tick, value) in points {
|
||||
events.push(TimedMessage {
|
||||
tick,
|
||||
role: role as u8,
|
||||
message: MidiMessage {
|
||||
kind: MessageKind::Control,
|
||||
channel: profile.channel,
|
||||
key: curve.cc,
|
||||
value,
|
||||
rest: curve.rest,
|
||||
},
|
||||
next_cycle: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Negative early triggers are played once during warm-up, and before each subsequent wrap.
|
||||
let wrapped: Vec<_> = events
|
||||
.iter()
|
||||
.filter(|e| e.tick < 0)
|
||||
.map(|e| TimedMessage {
|
||||
tick: e.tick + phrase.length as i32,
|
||||
next_cycle: true,
|
||||
..*e
|
||||
})
|
||||
.collect();
|
||||
// Very short synthetic clips cannot represent their own warm-up as one loop.
|
||||
if lead_in >= phrase.length {
|
||||
return Err(err("Attack compensation exceeds this phrase's length. Reduce it or use a longer phrase."));
|
||||
}
|
||||
events.extend(wrapped);
|
||||
events.sort_by_key(|e| (e.tick, e.message.kind, e.message.channel, e.message.key));
|
||||
if events.len() > MAX_PERFORMANCE_EVENTS {
|
||||
return Err(err("Performance exceeds the bounded event limit. Simplify the phrase or controller curve."));
|
||||
}
|
||||
Ok(Self {
|
||||
length: phrase.length,
|
||||
lead_in,
|
||||
events,
|
||||
})
|
||||
}
|
||||
pub fn clip(&self) -> Result<PerformanceClip> {
|
||||
if self.events.len() > MAX_PERFORMANCE_EVENTS
|
||||
|| self.length == 0
|
||||
|| self.length > 8 * BAR
|
||||
|| self.lead_in >= self.length
|
||||
{
|
||||
return Err(err("Invalid performance clip."));
|
||||
}
|
||||
let mut per_tick = std::collections::BTreeMap::new();
|
||||
for event in &self.events {
|
||||
if event.role > 1
|
||||
|| event.message.channel > 15
|
||||
|| event.message.key > 127
|
||||
|| event.message.value > 127
|
||||
|| event.message.rest > 127
|
||||
|| event.message.kind == MessageKind::On && event.message.value == 0
|
||||
|| event.tick < -(self.lead_in as i32)
|
||||
|| event.tick > self.length as i32
|
||||
|| event.next_cycle && event.tick < 0
|
||||
{
|
||||
return Err(err("Invalid scheduled MIDI event."));
|
||||
}
|
||||
*per_tick.entry(event.tick).or_insert(0) += 1;
|
||||
}
|
||||
if per_tick.values().any(|&count| count > 16)
|
||||
|| self.events.windows(2).any(|p| p[0].tick > p[1].tick)
|
||||
{
|
||||
return Err(err("Unsorted or excessively dense performance events."));
|
||||
}
|
||||
let mut clip = PerformanceClip {
|
||||
events: [TimedMessage::default(); MAX_PERFORMANCE_EVENTS],
|
||||
count: self.events.len(),
|
||||
length: self.length,
|
||||
lead_in: self.lead_in,
|
||||
};
|
||||
clip.events[..clip.count].copy_from_slice(&self.events);
|
||||
Ok(clip)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PerformanceClip {
|
||||
events: [TimedMessage; MAX_PERFORMANCE_EVENTS],
|
||||
count: usize,
|
||||
pub length: u32,
|
||||
pub lead_in: u32,
|
||||
}
|
||||
pub struct EventBatch {
|
||||
pub events: [Option<MidiMessage>; MAX_FRAME_EVENTS],
|
||||
pub len: usize,
|
||||
}
|
||||
impl Default for EventBatch {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
events: [None; MAX_FRAME_EVENTS],
|
||||
len: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl EventBatch {
|
||||
pub fn push(&mut self, message: MidiMessage) {
|
||||
assert!(self.len < MAX_FRAME_EVENTS, "bounded MIDI batch overflow");
|
||||
self.events[self.len] = Some(message);
|
||||
self.len += 1;
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Voice {
|
||||
held: Option<(u8, u8)>,
|
||||
frequency: f64,
|
||||
phase: f64,
|
||||
gain: f64,
|
||||
level: f64,
|
||||
}
|
||||
impl Voice {
|
||||
fn sample(&mut self, rate: f64, role: usize) -> f32 {
|
||||
let target = if self.held.is_some() { 1. } else { 0. };
|
||||
let speed = if target > self.gain {
|
||||
1. / (0.005 * rate)
|
||||
} else {
|
||||
1. / (0.012 * rate)
|
||||
};
|
||||
self.gain = if target > self.gain {
|
||||
(self.gain + speed).min(target)
|
||||
} else {
|
||||
(self.gain - speed).max(target)
|
||||
};
|
||||
let sine = self.phase.sin();
|
||||
let triangle = 2. / std::f64::consts::PI * sine.asin();
|
||||
let wave = if role == 0 {
|
||||
sine * 0.8 + triangle * 0.2
|
||||
} else {
|
||||
triangle * 0.65 + (self.phase * 2.).sin() * 0.35
|
||||
};
|
||||
self.phase = (self.phase + TAU * self.frequency / rate) % TAU;
|
||||
(wave * self.gain * 0.1 * self.level) as f32
|
||||
}
|
||||
}
|
||||
pub struct PerformancePlayer {
|
||||
clip: PerformanceClip,
|
||||
tick: f64,
|
||||
index: usize,
|
||||
cycle: u64,
|
||||
playing: bool,
|
||||
looping: bool,
|
||||
sample_rate: f64,
|
||||
voices: [Voice; 2],
|
||||
controls: [Option<MidiMessage>; 2],
|
||||
}
|
||||
impl Default for PerformancePlayer {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
clip: PerformanceClip {
|
||||
events: [TimedMessage::default(); MAX_PERFORMANCE_EVENTS],
|
||||
count: 0,
|
||||
length: 0,
|
||||
lead_in: 0,
|
||||
},
|
||||
tick: 0.,
|
||||
index: 0,
|
||||
cycle: 0,
|
||||
playing: false,
|
||||
looping: false,
|
||||
sample_rate: 44100.,
|
||||
voices: [Voice::default(); 2],
|
||||
controls: [None; 2],
|
||||
}
|
||||
}
|
||||
}
|
||||
impl PerformancePlayer {
|
||||
pub fn set_sample_rate(&mut self, rate: f64) -> Result<()> {
|
||||
if !rate.is_finite() || !(8000.0..=384000.0).contains(&rate) {
|
||||
return Err(err("Unsupported sample rate."));
|
||||
}
|
||||
self.sample_rate = rate;
|
||||
self.stop();
|
||||
Ok(())
|
||||
}
|
||||
pub fn set_looping(&mut self, value: bool) {
|
||||
self.looping = value;
|
||||
}
|
||||
pub fn is_playing(&self) -> bool {
|
||||
self.playing
|
||||
}
|
||||
pub fn length(&self) -> u32 {
|
||||
self.clip.length
|
||||
}
|
||||
pub fn tick(&self) -> f64 {
|
||||
self.tick
|
||||
}
|
||||
pub fn absolute_tick(&self) -> f64 {
|
||||
self.cycle as f64 * self.clip.length as f64 + self.tick
|
||||
}
|
||||
pub fn play(&mut self, clip: PerformanceClip) {
|
||||
self.stop();
|
||||
self.clip = clip;
|
||||
self.tick = -(clip.lead_in as f64);
|
||||
self.playing = true;
|
||||
}
|
||||
pub fn stop(&mut self) {
|
||||
self.playing = false;
|
||||
self.tick = 0.;
|
||||
self.index = 0;
|
||||
self.cycle = 0;
|
||||
self.voices = [Voice::default(); 2];
|
||||
self.controls = [None; 2];
|
||||
}
|
||||
fn dispatch_until(&mut self, tick: f64, batch: &mut EventBatch) {
|
||||
while self.index < self.clip.count && self.clip.events[self.index].tick as f64 <= tick {
|
||||
let event = self.clip.events[self.index];
|
||||
self.index += 1;
|
||||
if event.next_cycle && !self.looping {
|
||||
continue;
|
||||
}
|
||||
let voice = &mut self.voices[event.role as usize];
|
||||
match event.message.kind {
|
||||
MessageKind::On => {
|
||||
voice.held = Some((event.message.key, event.message.value));
|
||||
voice.level = event.message.value as f64 / 127.;
|
||||
voice.frequency = 440. * 2.0_f64.powf((event.message.key as f64 - 69.) / 12.);
|
||||
voice.phase = 0.;
|
||||
}
|
||||
MessageKind::Off => {
|
||||
if voice.held.is_some_and(|n| n.0 == event.message.key) {
|
||||
voice.held = None;
|
||||
}
|
||||
}
|
||||
MessageKind::Control => self.controls[event.role as usize] = Some(event.message),
|
||||
}
|
||||
batch.push(event.message);
|
||||
}
|
||||
}
|
||||
pub fn current_messages(&self) -> EventBatch {
|
||||
let mut batch = EventBatch::default();
|
||||
for role in 0..2 {
|
||||
if let Some(message) = self.controls[role] {
|
||||
batch.push(message);
|
||||
}
|
||||
if let Some((key, value)) = self.voices[role].held {
|
||||
let channel = self.clip.events[..self.clip.count]
|
||||
.iter()
|
||||
.find(|e| e.role as usize == role && e.message.kind == MessageKind::On)
|
||||
.map_or(role as u8, |e| e.message.channel);
|
||||
batch.push(MidiMessage {
|
||||
kind: MessageKind::On,
|
||||
channel,
|
||||
key,
|
||||
value,
|
||||
rest: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
batch
|
||||
}
|
||||
pub fn next_frame(&mut self, bpm: f64) -> (f32, EventBatch) {
|
||||
let mut batch = EventBatch::default();
|
||||
if !self.playing {
|
||||
return (0., batch);
|
||||
}
|
||||
if self.tick >= self.clip.length as f64 {
|
||||
self.dispatch_until(self.clip.length as f64, &mut batch);
|
||||
if self.looping {
|
||||
self.tick -= self.clip.length as f64;
|
||||
self.cycle = self.cycle.wrapping_add(1);
|
||||
self.index = self.clip.events[..self.clip.count].partition_point(|e| e.tick < 0);
|
||||
} else {
|
||||
self.playing = false;
|
||||
return (0., batch);
|
||||
}
|
||||
}
|
||||
self.dispatch_until(self.tick, &mut batch);
|
||||
let sample = self
|
||||
.voices
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
.map(|(role, v)| v.sample(self.sample_rate, role))
|
||||
.sum();
|
||||
self.tick += (if bpm.is_finite() {
|
||||
bpm.clamp(30., 300.)
|
||||
} else {
|
||||
140.
|
||||
}) * PPQ as f64
|
||||
/ (60. * self.sample_rate);
|
||||
(sample, batch)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
use crate::{Error, Note, Phrase, Result, PPQ};
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
pub const MAX_PLAYBACK_NOTES: usize = 2048;
|
||||
|
||||
/// Fixed-size, trivially dropped data: safe to move through a bounded RT queue.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PlaybackClip {
|
||||
notes: [Note; MAX_PLAYBACK_NOTES],
|
||||
count: usize,
|
||||
length: u32,
|
||||
}
|
||||
impl PlaybackClip {
|
||||
pub fn new(phrase: &Phrase) -> Result<Self> {
|
||||
phrase.validate(MAX_PLAYBACK_NOTES)?;
|
||||
let mut clip = Self {
|
||||
notes: [Note::default(); MAX_PLAYBACK_NOTES],
|
||||
count: phrase.notes.len(),
|
||||
length: phrase.length,
|
||||
};
|
||||
clip.notes[..clip.count].copy_from_slice(&phrase.notes);
|
||||
Ok(clip)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PreviewPlayer {
|
||||
clip: PlaybackClip,
|
||||
playing: bool,
|
||||
tick: f64,
|
||||
index: usize,
|
||||
phase: f64,
|
||||
sample_rate: f64,
|
||||
looping: bool,
|
||||
cycle: u64,
|
||||
}
|
||||
impl Default for PreviewPlayer {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
clip: PlaybackClip {
|
||||
notes: [Note::default(); MAX_PLAYBACK_NOTES],
|
||||
count: 0,
|
||||
length: 0,
|
||||
},
|
||||
playing: false,
|
||||
tick: 0.,
|
||||
index: 0,
|
||||
phase: 0.,
|
||||
sample_rate: 44100.,
|
||||
looping: false,
|
||||
cycle: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl PreviewPlayer {
|
||||
pub fn set_sample_rate(&mut self, sample_rate: f64) -> Result<()> {
|
||||
if !sample_rate.is_finite() || !(8000.0..=384000.0).contains(&sample_rate) {
|
||||
return Err(Error("Unsupported sample rate.".into()));
|
||||
}
|
||||
self.sample_rate = sample_rate;
|
||||
self.stop();
|
||||
Ok(())
|
||||
}
|
||||
pub fn play(&mut self, clip: PlaybackClip) {
|
||||
self.stop();
|
||||
self.clip = clip;
|
||||
self.playing = true;
|
||||
}
|
||||
pub fn stop(&mut self) {
|
||||
self.playing = false;
|
||||
self.tick = 0.;
|
||||
self.index = 0;
|
||||
self.phase = 0.;
|
||||
self.cycle = 0;
|
||||
}
|
||||
pub fn is_playing(&self) -> bool {
|
||||
self.playing
|
||||
}
|
||||
pub fn tick(&self) -> f64 {
|
||||
self.tick
|
||||
}
|
||||
pub fn set_looping(&mut self, looping: bool) {
|
||||
self.looping = looping;
|
||||
}
|
||||
pub fn cycle(&self) -> u64 {
|
||||
self.cycle
|
||||
}
|
||||
pub fn prepare_sample(&mut self) {
|
||||
if self.playing && self.tick >= self.clip.length as f64 {
|
||||
if self.looping {
|
||||
self.cycle = self
|
||||
.cycle
|
||||
.wrapping_add((self.tick / self.clip.length as f64) as u64);
|
||||
self.tick %= self.clip.length as f64;
|
||||
self.index = 0;
|
||||
self.phase = 0.;
|
||||
} else {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn current_note(&self) -> Option<Note> {
|
||||
if !self.playing {
|
||||
return None;
|
||||
}
|
||||
self.clip.notes[self.index..self.clip.count]
|
||||
.iter()
|
||||
.find(|n| self.tick < n.end() as f64)
|
||||
.filter(|n| self.tick >= n.start as f64)
|
||||
.copied()
|
||||
}
|
||||
pub fn length(&self) -> u32 {
|
||||
self.clip.length
|
||||
}
|
||||
pub fn next_sample(&mut self, bpm: f64) -> f32 {
|
||||
self.prepare_sample();
|
||||
if !self.playing {
|
||||
return 0.;
|
||||
}
|
||||
let bpm = if bpm.is_finite() {
|
||||
bpm.clamp(30., 300.)
|
||||
} else {
|
||||
140.
|
||||
};
|
||||
while self.index < self.clip.count && self.tick >= self.clip.notes[self.index].end() as f64
|
||||
{
|
||||
self.index += 1;
|
||||
self.phase = 0.;
|
||||
}
|
||||
let mut value = 0.;
|
||||
if let Some(n) = self.clip.notes[..self.clip.count].get(self.index) {
|
||||
if self.tick >= n.start as f64 {
|
||||
let age = (self.tick - n.start as f64) * 60. / (bpm * PPQ as f64);
|
||||
let remaining = (n.end() as f64 - self.tick) * 60. / (bpm * PPQ as f64);
|
||||
let env = (age / 0.005).min(remaining / 0.012).clamp(0., 1.);
|
||||
let sine = self.phase.sin();
|
||||
let triangle = 2. / std::f64::consts::PI * sine.asin();
|
||||
value = ((sine * 0.8 + triangle * 0.2) * env * (n.velocity as f64 / 127.) * 0.15)
|
||||
as f32;
|
||||
let frequency = 440. * 2.0_f64.powf((n.pitch as f64 - 69.) / 12.);
|
||||
self.phase = (self.phase + TAU * frequency / self.sample_rate) % TAU;
|
||||
}
|
||||
}
|
||||
self.tick += bpm * PPQ as f64 / (60. * self.sample_rate);
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::demo_motif;
|
||||
fn render(rate: f64, block: usize) -> Vec<f32> {
|
||||
let mut p = PreviewPlayer::default();
|
||||
p.set_sample_rate(rate).unwrap();
|
||||
p.play(PlaybackClip::new(&demo_motif()).unwrap());
|
||||
let total = (rate * 4.0) as usize;
|
||||
let mut out = Vec::new();
|
||||
while out.len() < total {
|
||||
for _ in 0..block.min(total - out.len()) {
|
||||
out.push(p.next_sample(140.));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
#[test]
|
||||
fn independent_of_block_size() {
|
||||
for rate in [44100., 48000., 96000.] {
|
||||
assert_eq!(render(rate, 1), render(rate, 511));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn silent_until_started_and_stops_on_replace() {
|
||||
let mut p = PreviewPlayer::default();
|
||||
assert_eq!(p.next_sample(140.), 0.);
|
||||
let c = PlaybackClip::new(&demo_motif()).unwrap();
|
||||
p.play(c);
|
||||
for _ in 0..1000 {
|
||||
p.next_sample(140.);
|
||||
}
|
||||
p.play(c);
|
||||
assert_eq!(p.tick(), 0.);
|
||||
p.stop();
|
||||
assert_eq!(p.next_sample(140.), 0.);
|
||||
p.play(c);
|
||||
p.set_sample_rate(48000.).unwrap();
|
||||
assert!(!p.is_playing());
|
||||
}
|
||||
#[test]
|
||||
fn duration_and_finite_output() {
|
||||
let mut p = PreviewPlayer::default();
|
||||
p.set_sample_rate(8000.).unwrap();
|
||||
p.play(PlaybackClip::new(&demo_motif()).unwrap());
|
||||
let mut count: i32 = 0;
|
||||
while p.is_playing() {
|
||||
let s = p.next_sample(120.);
|
||||
assert!(s.is_finite() && s.abs() <= 0.15);
|
||||
count += 1;
|
||||
assert!(count < 40000);
|
||||
}
|
||||
assert!((count - 32000).abs() <= 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
//! Phrase-level proposals. Randomness chooses compositional alternatives, not independent pitches.
|
||||
use crate::{
|
||||
Candidate, Ending, Harmony, Note, Phrase, Result, Settings, Strategy, Task, BAR,
|
||||
MAX_PLAYBACK_NOTES, PPQ, SECTION,
|
||||
};
|
||||
|
||||
const FAMILIES: [Strategy; 8] = Strategy::ALL;
|
||||
struct Random(u64);
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9e3779b97f4a7c15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
}
|
||||
fn same_music(a: &Phrase, b: &Phrase) -> bool {
|
||||
a.length == b.length
|
||||
&& a.notes.len() == b.notes.len()
|
||||
&& a.notes
|
||||
.iter()
|
||||
.zip(&b.notes)
|
||||
.all(|(a, b)| (a.start, a.duration, a.pitch) == (b.start, b.duration, b.pitch))
|
||||
}
|
||||
/// Distance deliberately values timing/density differences above small pitch substitutions.
|
||||
pub fn distance(a: &Phrase, b: &Phrase) -> u32 {
|
||||
let a: std::collections::BTreeMap<_, _> = a.notes.iter().map(|n| (n.start, n)).collect();
|
||||
let b: std::collections::BTreeMap<_, _> = b.notes.iter().map(|n| (n.start, n)).collect();
|
||||
let mut total = 0;
|
||||
for (start, n) in &a {
|
||||
total += if let Some(other) = b.get(start) {
|
||||
(n.pitch.abs_diff(other.pitch) as u32).min(12) * 3
|
||||
+ (n.duration.abs_diff(other.duration) / 60).min(24)
|
||||
} else {
|
||||
100
|
||||
};
|
||||
}
|
||||
total += b.keys().filter(|start| !a.contains_key(start)).count() as u32 * 100;
|
||||
total * 10 / (a.len().max(b.len()).max(1) as u32)
|
||||
}
|
||||
fn fit(task: Task, family: Strategy) -> u32 {
|
||||
let preferred = match task {
|
||||
Task::Develop => [
|
||||
Strategy::NewRhythm,
|
||||
Strategy::FragmentAnswer,
|
||||
Strategy::LaterPeak,
|
||||
],
|
||||
Task::Answer => [
|
||||
Strategy::CallResponse,
|
||||
Strategy::ChangedEnding,
|
||||
Strategy::DelayedResolution,
|
||||
],
|
||||
Task::MakeSpace => [
|
||||
Strategy::NegativeSpace,
|
||||
Strategy::FragmentAnswer,
|
||||
Strategy::CallResponse,
|
||||
],
|
||||
Task::Return => [
|
||||
Strategy::HarmonicReturn,
|
||||
Strategy::LaterPeak,
|
||||
Strategy::ChangedEnding,
|
||||
],
|
||||
};
|
||||
if family == preferred[0] {
|
||||
300
|
||||
} else if preferred.contains(&family) {
|
||||
240
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
pub fn generate(source: &Phrase, s: &Settings, harmony: &Harmony) -> Result<Vec<Candidate>> {
|
||||
source.validate_source()?;
|
||||
s.validate()?;
|
||||
harmony.validate()?;
|
||||
if source.notes.len() as u64 * (s.bars as u64 * BAR as u64).div_ceil(source.length as u64)
|
||||
> MAX_PLAYBACK_NOTES as u64
|
||||
{
|
||||
return Err(crate::Error("This motif is too dense to develop within the 2048-note limit. Shorten or simplify it.".into()));
|
||||
}
|
||||
let mut pool: Vec<Candidate> = Vec::new();
|
||||
for (family_index, family) in FAMILIES.into_iter().enumerate() {
|
||||
for variant in 0..3 {
|
||||
let mut rng = Random(
|
||||
s.seed
|
||||
.wrapping_add(family_index as u64 * 7919 + variant * 104729),
|
||||
);
|
||||
let phrase = develop(source, s, harmony, family, &mut rng);
|
||||
if phrase.notes.len() > MAX_PLAYBACK_NOTES {
|
||||
continue;
|
||||
}
|
||||
phrase.validate(MAX_PLAYBACK_NOTES)?;
|
||||
let description = match family {
|
||||
Strategy::SavedIdea => "Saved working gesture.",
|
||||
Strategy::NewRhythm => {
|
||||
"Recognizable contour; displaced entries and repeated pickups."
|
||||
}
|
||||
Strategy::FragmentAnswer => "A short fragment leaves space before a fuller return.",
|
||||
Strategy::NegativeSpace => {
|
||||
"Connecting notes fall away; the signature anchors remain."
|
||||
}
|
||||
Strategy::CallResponse => "A shorter question is answered with longer arrivals.",
|
||||
Strategy::HarmonicReturn => {
|
||||
"The opening gesture returns after a contrasting middle."
|
||||
}
|
||||
Strategy::LaterPeak => {
|
||||
"Register opens in the middle and returns before the ending."
|
||||
}
|
||||
Strategy::ChangedEnding => {
|
||||
"The groove stays recognizable while answer endings change."
|
||||
}
|
||||
Strategy::DelayedResolution => {
|
||||
"Earlier answers stay open; the last arrival follows your ending choice."
|
||||
}
|
||||
};
|
||||
let note = if harmony.spans.is_empty() {
|
||||
" Scale guides pitches; no chord context supplied."
|
||||
} else {
|
||||
" Strong notes and arrivals follow the supplied harmony where locks and contour allow."
|
||||
};
|
||||
let constraints = if s.preserve_rhythm {
|
||||
" Groove is fixed."
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let candidate = Candidate {
|
||||
strategy: family,
|
||||
explanation: format!("{description}{note}{constraints}"),
|
||||
phrase,
|
||||
};
|
||||
if let Some(index) = pool
|
||||
.iter()
|
||||
.position(|c| same_music(&c.phrase, &candidate.phrase))
|
||||
{
|
||||
if fit(s.task, family) > fit(s.task, pool[index].strategy) {
|
||||
pool[index] = candidate;
|
||||
}
|
||||
} else {
|
||||
pool.push(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut selected: Vec<Candidate> = Vec::new();
|
||||
while selected.len() < 3 && !pool.is_empty() {
|
||||
let index = pool
|
||||
.iter()
|
||||
.enumerate()
|
||||
.max_by_key(|(i, c)| {
|
||||
let diversity = selected
|
||||
.iter()
|
||||
.map(|chosen| distance(&c.phrase, &chosen.phrase))
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
let new_family = if selected.iter().all(|chosen| chosen.strategy != c.strategy) {
|
||||
120
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(
|
||||
fit(s.task, c.strategy) > 0,
|
||||
new_family > 0,
|
||||
fit(s.task, c.strategy) + diversity,
|
||||
usize::MAX - *i,
|
||||
)
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.unwrap();
|
||||
selected.push(pool.remove(index));
|
||||
}
|
||||
Ok(selected)
|
||||
}
|
||||
|
||||
fn develop(
|
||||
source: &Phrase,
|
||||
s: &Settings,
|
||||
harmony: &Harmony,
|
||||
family: Strategy,
|
||||
rng: &mut Random,
|
||||
) -> Phrase {
|
||||
let sections = s.bars as u32 / 2;
|
||||
let mut result = Vec::new();
|
||||
for section in 0..sections {
|
||||
let offset = section * SECTION;
|
||||
let mut notes = Vec::new();
|
||||
for repeat in 0..SECTION.div_ceil(source.length) {
|
||||
for original in &source.notes {
|
||||
let n = Note {
|
||||
start: original.start + repeat * source.length,
|
||||
..*original
|
||||
};
|
||||
if n.end() <= SECTION {
|
||||
notes.push(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
if section == 0 {
|
||||
result.extend(notes.into_iter().map(|n| Note {
|
||||
start: n.start + offset,
|
||||
..n
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
let returning = section + 1 == sections;
|
||||
let departure = sections == 4 && section == 2;
|
||||
let pattern = (rng.next() % 3) as usize;
|
||||
let original_count = notes.len();
|
||||
if !s.preserve_rhythm {
|
||||
let mut i = 0;
|
||||
notes.retain(|n| {
|
||||
let index = i;
|
||||
i += 1;
|
||||
if n.is_anchor() {
|
||||
return true;
|
||||
}
|
||||
match family {
|
||||
Strategy::NegativeSpace => {
|
||||
index == 0
|
||||
|| index + 1 == original_count
|
||||
|| (index + pattern).is_multiple_of(3)
|
||||
}
|
||||
Strategy::FragmentAnswer if !returning => index < original_count.div_ceil(2),
|
||||
Strategy::CallResponse if !returning => n.start < BAR,
|
||||
_ => true,
|
||||
}
|
||||
});
|
||||
}
|
||||
for (i, n) in notes.iter_mut().enumerate() {
|
||||
if !n.keeps_pitch() {
|
||||
let steps = match family {
|
||||
Strategy::LaterPeak if departure => 3 + s.variation as i16 / 25,
|
||||
Strategy::LaterPeak if sections == 2 && i < original_count / 2 => 2,
|
||||
Strategy::HarmonicReturn if departure => 2,
|
||||
Strategy::ChangedEnding if i >= original_count / 2 => -1 - pattern as i16,
|
||||
Strategy::DelayedResolution if !returning => 1,
|
||||
_ => 0,
|
||||
};
|
||||
n.pitch = s.degree(n.pitch, steps);
|
||||
}
|
||||
if !n.locked {
|
||||
let accent = if n.start.is_multiple_of(PPQ) { 5 } else { -5 };
|
||||
let arc = if departure {
|
||||
6
|
||||
} else if returning {
|
||||
-3
|
||||
} else {
|
||||
0
|
||||
};
|
||||
n.velocity = (n.velocity as i16 + accent + arc).clamp(1, 127) as u8;
|
||||
}
|
||||
}
|
||||
if !s.preserve_rhythm {
|
||||
for i in 0..notes.len() {
|
||||
if notes[i].keeps_rhythm() {
|
||||
continue;
|
||||
}
|
||||
let previous = if i == 0 { 0 } else { notes[i - 1].end() };
|
||||
let next = notes.get(i + 1).map_or(SECTION, |n| n.start);
|
||||
let n = &mut notes[i];
|
||||
let shift = PPQ / 4 + (s.variation as u32 * PPQ / 400);
|
||||
if matches!(
|
||||
family,
|
||||
Strategy::NewRhythm | Strategy::FragmentAnswer | Strategy::CallResponse
|
||||
) {
|
||||
let wanted = if (i + pattern).is_multiple_of(2) {
|
||||
n.start.saturating_add(shift)
|
||||
} else {
|
||||
n.start.saturating_sub(shift)
|
||||
};
|
||||
n.start = wanted.clamp(previous, next.saturating_sub(1).max(previous));
|
||||
}
|
||||
let desired = match family {
|
||||
Strategy::NegativeSpace | Strategy::FragmentAnswer => n.duration.min(PPQ / 2),
|
||||
Strategy::CallResponse if returning => n.duration.saturating_add(PPQ / 2),
|
||||
Strategy::NewRhythm if (i + pattern) % 2 == 1 => n.duration / 2,
|
||||
_ => n.duration,
|
||||
};
|
||||
n.duration = desired.max(1).min(next - n.start);
|
||||
}
|
||||
if family == Strategy::NewRhythm {
|
||||
let mut extra = Vec::new();
|
||||
for (i, n) in notes.iter().enumerate() {
|
||||
let next = notes.get(i + 1).map_or(SECTION, |n| n.start);
|
||||
if !n.is_anchor() && next.saturating_sub(n.end()) >= PPQ && i % 2 == pattern % 2
|
||||
{
|
||||
extra.push(Note {
|
||||
start: n.end() + PPQ / 4,
|
||||
duration: PPQ / 4,
|
||||
pitch: n.pitch,
|
||||
velocity: n.velocity.saturating_sub(12).max(1),
|
||||
..Note::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
notes.extend(extra);
|
||||
notes.sort_by_key(|n| n.start);
|
||||
}
|
||||
}
|
||||
// Reference relationships constrain harmonic adjustments, preserving the chosen contour.
|
||||
let reference: Vec<_> = notes.iter().map(|n| n.pitch).collect();
|
||||
for i in 0..notes.len() {
|
||||
if notes[i].keeps_pitch() {
|
||||
continue;
|
||||
}
|
||||
let last = i + 1 == notes.len();
|
||||
let global = notes[i].start + offset;
|
||||
let strong = global.is_multiple_of(PPQ);
|
||||
let wants_open = last
|
||||
&& (family == Strategy::DelayedResolution && !returning
|
||||
|| returning && s.ending == Ending::Open);
|
||||
let wants_closed = last && returning && s.ending == Ending::Resolve;
|
||||
let region = harmony.at(global);
|
||||
let mask = region.map(|h| h.tones);
|
||||
if !strong && !last {
|
||||
continue;
|
||||
}
|
||||
let allowed = |pitch: u8| {
|
||||
if !s.preserve_contour {
|
||||
return true;
|
||||
}
|
||||
let previous = i.checked_sub(1).map(|p| (reference[p], notes[p].pitch));
|
||||
let next = reference.get(i + 1).copied();
|
||||
previous.is_none_or(|(old, new)| match reference[i].cmp(&old) {
|
||||
std::cmp::Ordering::Greater => pitch >= new,
|
||||
std::cmp::Ordering::Less => pitch <= new,
|
||||
std::cmp::Ordering::Equal => pitch == new,
|
||||
}) && next.is_none_or(|next| match reference[i].cmp(&next) {
|
||||
std::cmp::Ordering::Greater => pitch >= next,
|
||||
std::cmp::Ordering::Less => pitch <= next,
|
||||
std::cmp::Ordering::Equal => pitch == next,
|
||||
})
|
||||
};
|
||||
let target = if wants_closed && family == Strategy::HarmonicReturn {
|
||||
source.notes.last().unwrap().pitch
|
||||
} else {
|
||||
notes[i].pitch
|
||||
};
|
||||
let chosen = (s.low..=s.high)
|
||||
.filter(|&pitch| {
|
||||
if !allowed(pitch) {
|
||||
return false;
|
||||
}
|
||||
match mask {
|
||||
Some(mask) if wants_open => {
|
||||
s.contains(pitch) && mask & (1 << (pitch % 12)) == 0
|
||||
}
|
||||
Some(mask) => mask & (1 << (pitch % 12)) != 0,
|
||||
None if wants_open => s.contains(pitch) && pitch % 12 != s.root,
|
||||
None if wants_closed => pitch % 12 == s.root,
|
||||
None => false,
|
||||
}
|
||||
})
|
||||
.min_by_key(|&pitch| pitch.abs_diff(target));
|
||||
if let Some(pitch) = chosen {
|
||||
notes[i].pitch = pitch;
|
||||
}
|
||||
}
|
||||
result.extend(notes.into_iter().map(|n| Note {
|
||||
start: n.start + offset,
|
||||
..n
|
||||
}));
|
||||
}
|
||||
Phrase {
|
||||
notes: result,
|
||||
length: s.bars as u32 * BAR,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn later_peak_returns_before_the_final_note() {
|
||||
let source = crate::demo_motif();
|
||||
let settings = Settings {
|
||||
preserve_rhythm: true,
|
||||
..Settings::default()
|
||||
};
|
||||
let phrase = develop(
|
||||
&source,
|
||||
&settings,
|
||||
&Harmony::default(),
|
||||
Strategy::LaterPeak,
|
||||
&mut Random(42),
|
||||
);
|
||||
let peak = phrase
|
||||
.notes
|
||||
.iter()
|
||||
.filter(|n| n.start >= 4 * BAR && n.start < 6 * BAR)
|
||||
.map(|n| n.pitch)
|
||||
.max()
|
||||
.unwrap();
|
||||
let returned = phrase
|
||||
.notes
|
||||
.iter()
|
||||
.filter(|n| n.start >= 6 * BAR)
|
||||
.map(|n| n.pitch)
|
||||
.max()
|
||||
.unwrap();
|
||||
assert!(peak > returned);
|
||||
}
|
||||
#[test]
|
||||
fn preserved_contour_has_no_direction_reversals_with_a_fixed_groove() {
|
||||
let source = crate::demo_motif();
|
||||
let settings = Settings {
|
||||
preserve_rhythm: true,
|
||||
preserve_contour: true,
|
||||
..Settings::default()
|
||||
};
|
||||
for family in FAMILIES {
|
||||
let phrase = develop(
|
||||
&source,
|
||||
&settings,
|
||||
&Harmony::default(),
|
||||
family,
|
||||
&mut Random(42),
|
||||
);
|
||||
for section in phrase.notes.chunks_exact(source.notes.len()) {
|
||||
for (original, new) in source.notes.windows(2).zip(section.windows(2)) {
|
||||
let a = original[1].pitch as i16 - original[0].pitch as i16;
|
||||
let b = new[1].pitch as i16 - new[0].pitch as i16;
|
||||
assert!(a * b >= 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
use rivet_core::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session {
|
||||
source: Some(demo_motif()),
|
||||
..Default::default()
|
||||
};
|
||||
s.regenerate().unwrap();
|
||||
s
|
||||
}
|
||||
#[test]
|
||||
fn moves_fork_and_restore_context_without_losing_siblings() {
|
||||
let mut s = session();
|
||||
s.pin_selected(0).unwrap();
|
||||
let root = s.save_branch("Original").unwrap();
|
||||
let original = s.composed_phrase().unwrap();
|
||||
s.apply_move(CreativeMove::Thin, Some(1)).unwrap();
|
||||
let thin = s.active_branch.unwrap();
|
||||
let thinned = s.composed_phrase().unwrap();
|
||||
assert_ne!(thinned, original);
|
||||
assert_eq!(
|
||||
&thinned.notes[..demo_motif().notes.len()],
|
||||
demo_motif().notes.as_slice()
|
||||
);
|
||||
s.restore_branch(root).unwrap();
|
||||
assert_eq!(s.composed_phrase().unwrap(), original);
|
||||
assert_eq!(s.pins.len(), 1);
|
||||
s.apply_move(CreativeMove::Lengthen, Some(2)).unwrap();
|
||||
let long = s.active_branch.unwrap();
|
||||
assert_ne!(thin, long);
|
||||
assert_eq!(s.branches.len(), 3);
|
||||
assert_eq!(
|
||||
s.branches.iter().find(|b| b.id == thin).unwrap().parent,
|
||||
Some(root)
|
||||
);
|
||||
assert_eq!(
|
||||
s.branches.iter().find(|b| b.id == long).unwrap().parent,
|
||||
Some(root)
|
||||
);
|
||||
s.restore_branch(thin).unwrap();
|
||||
assert_eq!(s.composed_phrase().unwrap(), thinned);
|
||||
assert!(s.remove_branch(root).is_err());
|
||||
assert_eq!(Session::from_json(&s.to_json().unwrap()).unwrap(), s);
|
||||
}
|
||||
#[test]
|
||||
fn gesture_recall_and_cross_project_library_preserve_performance() {
|
||||
let mut s = session();
|
||||
s.performance.mode = RoleMode::CallResponse;
|
||||
s.performance.voices[1].controller.enabled = true;
|
||||
s.performance.voices[1].controller.cc = 20;
|
||||
s.performance.voices[1].controller.shape(2);
|
||||
let id = s.save_gesture("Floating answer", Some(1)).unwrap();
|
||||
let saved = s.gestures[0].clone();
|
||||
let bytes = s.export_gesture_library().unwrap();
|
||||
let mut other = Session {
|
||||
source: Some(demo_motif()),
|
||||
harmony: Harmony::progression(2, Scale::Major),
|
||||
..Default::default()
|
||||
};
|
||||
other.save_gesture("Existing", None).unwrap();
|
||||
let context = other.harmony.clone();
|
||||
other
|
||||
.import_gesture_library(read_gesture_library(&bytes).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(other.gestures.len(), 2);
|
||||
assert_ne!(other.gestures[0].id, other.gestures[1].id);
|
||||
let imported = other.gestures[1].id;
|
||||
other.recall_gesture(imported).unwrap();
|
||||
assert_eq!(other.source, Some(saved.phrase));
|
||||
assert_eq!(other.performance, saved.performance);
|
||||
assert_eq!(other.harmony, context);
|
||||
assert!(other.candidates.is_empty());
|
||||
assert!(other.pins.is_empty());
|
||||
assert!(s.gestures.iter().any(|g| g.id == id));
|
||||
}
|
||||
#[test]
|
||||
fn blocked_moves_and_full_histories_are_atomic() {
|
||||
let mut s = session();
|
||||
s.settings.preserve_rhythm = true;
|
||||
let before = s.clone();
|
||||
assert!(s.apply_move(CreativeMove::Thin, None).is_err());
|
||||
assert_eq!(s, before);
|
||||
s.settings.preserve_rhythm = false;
|
||||
for i in 0..MAX_BRANCHES {
|
||||
s.save_branch(&format!("Idea {i}")).unwrap();
|
||||
}
|
||||
let before = s.clone();
|
||||
assert!(s.apply_move(CreativeMove::Thin, Some(1)).is_err());
|
||||
assert_eq!(s, before);
|
||||
let leaf = s.active_branch.unwrap();
|
||||
s.remove_branch(leaf).unwrap();
|
||||
assert_eq!(s.branches.len(), MAX_BRANCHES - 1);
|
||||
}
|
||||
#[test]
|
||||
fn malformed_ancestry_libraries_and_version_two_state_are_handled() {
|
||||
let mut s = session();
|
||||
let id = s.save_branch("Root").unwrap();
|
||||
s.branches[0].parent = Some(id);
|
||||
assert!(s.validate().is_err());
|
||||
assert!(read_gesture_library(br#"{"version":99,"gestures":[]}"#).is_err());
|
||||
let old = session();
|
||||
let mut value = serde_json::to_value(&old).unwrap();
|
||||
value["version"] = 2.into();
|
||||
for key in [
|
||||
"performance",
|
||||
"gestures",
|
||||
"branches",
|
||||
"active_branch",
|
||||
"next_id",
|
||||
] {
|
||||
value.as_object_mut().unwrap().remove(key);
|
||||
}
|
||||
let restored = Session::from_json(&serde_json::to_vec(&value).unwrap()).unwrap();
|
||||
assert_eq!(restored.version, 3);
|
||||
assert_eq!(restored.source, old.source);
|
||||
assert_eq!(restored.performance, PerformanceSettings::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delay_moves_adjacent_notes_together_and_rejects_protected_collisions() {
|
||||
let mut s = session();
|
||||
let make_note = |start| Note {
|
||||
start,
|
||||
duration: PPQ,
|
||||
pitch: 60,
|
||||
velocity: 90,
|
||||
..Default::default()
|
||||
};
|
||||
s.candidates[s.selected].phrase.notes = vec![make_note(SECTION), make_note(SECTION + PPQ)];
|
||||
s.apply_move(CreativeMove::Delay, Some(1)).unwrap();
|
||||
let moved = s.composed_phrase().unwrap();
|
||||
assert_eq!(moved.notes[0].start, SECTION + PPQ / 4);
|
||||
assert_eq!(moved.notes[1].start, SECTION + PPQ + PPQ / 4);
|
||||
s.candidates[0].phrase.notes[1].rhythm_locked = true;
|
||||
let before = s.clone();
|
||||
assert!(s.apply_move(CreativeMove::Delay, Some(1)).is_err());
|
||||
assert_eq!(s, before);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
use rivet_core::*;
|
||||
|
||||
fn rhythm(p: &Phrase) -> Vec<(u32, u32)> {
|
||||
p.notes.iter().map(|n| (n.start, n.duration)).collect()
|
||||
}
|
||||
#[test]
|
||||
fn alternatives_change_density_and_rhythm_instead_of_only_pitch() {
|
||||
let source = demo_motif();
|
||||
let s = Settings::default();
|
||||
let candidates = generate(&source, &s).unwrap();
|
||||
assert_eq!(candidates.len(), 3);
|
||||
assert!(candidates
|
||||
.iter()
|
||||
.any(|c| c.phrase.notes.len() != source.notes.len() * 4));
|
||||
assert!(candidates
|
||||
.windows(2)
|
||||
.any(|pair| rhythm(&pair[0].phrase) != rhythm(&pair[1].phrase)));
|
||||
for c in &candidates {
|
||||
assert_eq!(
|
||||
&c.phrase.notes[..source.notes.len()],
|
||||
source.notes.as_slice()
|
||||
);
|
||||
}
|
||||
assert_eq!(candidates, generate(&source, &s).unwrap());
|
||||
let mut signatures = std::collections::BTreeSet::new();
|
||||
for seed in 0..12 {
|
||||
for c in generate(&source, &Settings { seed, ..s.clone() }).unwrap() {
|
||||
signatures.insert(rhythm(&c.phrase));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
signatures.len() > 3,
|
||||
"seeds should explore multiple rhythmic decisions"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn fixed_groove_and_separate_note_locks_take_priority() {
|
||||
let mut source = demo_motif();
|
||||
source.notes[1].pitch_locked = true;
|
||||
source.notes[1].pitch = 99;
|
||||
source.notes[3].rhythm_locked = true;
|
||||
for c in generate(&source, &Settings::default()).unwrap() {
|
||||
let pitch: Vec<_> = c.phrase.notes.iter().filter(|n| n.pitch_locked).collect();
|
||||
assert_eq!(pitch.len(), 4);
|
||||
assert!(pitch.iter().all(|n| n.pitch == 99));
|
||||
for rep in 0..4 {
|
||||
assert!(c.phrase.notes.iter().any(|n| n.rhythm_locked
|
||||
&& n.start == source.notes[3].start + rep * source.length
|
||||
&& n.duration == source.notes[3].duration));
|
||||
}
|
||||
}
|
||||
let source = demo_motif();
|
||||
let repeated: Vec<_> = (0..4)
|
||||
.flat_map(|rep| {
|
||||
source
|
||||
.notes
|
||||
.iter()
|
||||
.map(move |n| (n.start + rep * SECTION, n.duration))
|
||||
})
|
||||
.collect();
|
||||
for c in generate(
|
||||
&source,
|
||||
&Settings {
|
||||
preserve_rhythm: true,
|
||||
..Settings::default()
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
{
|
||||
assert_eq!(rhythm(&c.phrase), repeated);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn impossible_diversity_returns_one_honest_proposal() {
|
||||
let mut source = demo_motif();
|
||||
for n in &mut source.notes {
|
||||
n.locked = true;
|
||||
}
|
||||
let candidates = generate(&source, &Settings::default()).unwrap();
|
||||
assert_eq!(candidates.len(), 1);
|
||||
assert_eq!(candidates[0].phrase.notes.len(), source.notes.len() * 4);
|
||||
}
|
||||
#[test]
|
||||
fn harmony_drives_strong_notes_and_distinct_open_or_closed_arrivals() {
|
||||
let harmony = Harmony {
|
||||
length: BAR,
|
||||
spans: vec![HarmonySpan {
|
||||
start: 0,
|
||||
duration: BAR,
|
||||
tones: ChordQuality::Major.mask(0),
|
||||
bass: 48,
|
||||
}],
|
||||
};
|
||||
for ending in [Ending::Open, Ending::Resolve] {
|
||||
let s = Settings {
|
||||
preserve_contour: false,
|
||||
ending,
|
||||
..Settings::default()
|
||||
};
|
||||
for c in generate_with_harmony(&demo_motif(), &s, &harmony).unwrap() {
|
||||
let last = c.phrase.notes.last().unwrap();
|
||||
let chord = ChordQuality::Major.mask(0) & (1 << (last.pitch % 12)) != 0;
|
||||
assert_eq!(chord, ending == Ending::Resolve);
|
||||
for n in c.phrase.notes.iter().filter(|n| {
|
||||
n.start >= SECTION && n.start.is_multiple_of(PPQ) && n.start != last.start
|
||||
}) {
|
||||
assert_ne!(
|
||||
harmony.at(n.start).unwrap().tones & (1 << (n.pitch % 12)),
|
||||
0
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn imported_harmony_preserves_voicings_and_gaps_without_guessing_roots() {
|
||||
let notes = vec![
|
||||
Note {
|
||||
start: 0,
|
||||
duration: BAR,
|
||||
pitch: 64,
|
||||
velocity: 90,
|
||||
..Default::default()
|
||||
},
|
||||
Note {
|
||||
start: 0,
|
||||
duration: BAR,
|
||||
pitch: 67,
|
||||
velocity: 90,
|
||||
..Default::default()
|
||||
},
|
||||
Note {
|
||||
start: 0,
|
||||
duration: BAR,
|
||||
pitch: 72,
|
||||
velocity: 90,
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
let h = Harmony::from_midi(¬es, 2 * BAR).unwrap();
|
||||
assert_eq!(h.spans.len(), 1);
|
||||
assert_eq!(h.spans[0].bass, 64);
|
||||
assert_eq!(h.spans[0].tones, ChordQuality::Major.mask(0));
|
||||
assert!(h.at(BAR + 1).is_none());
|
||||
assert_eq!(h.at(2 * BAR).unwrap().bass, 64);
|
||||
}
|
||||
#[test]
|
||||
fn pins_combine_candidates_and_survive_regeneration_exactly() {
|
||||
let mut s = Session {
|
||||
source: Some(demo_motif()),
|
||||
..Default::default()
|
||||
};
|
||||
s.regenerate().unwrap();
|
||||
s.pin_selected(1).unwrap();
|
||||
let saved = s.pins[0].clone();
|
||||
s.selected = 1;
|
||||
let expected: Vec<_> = saved
|
||||
.phrase
|
||||
.notes
|
||||
.iter()
|
||||
.map(|n| Note {
|
||||
start: n.start + SECTION,
|
||||
..*n
|
||||
})
|
||||
.collect();
|
||||
let combined = s.composed_phrase().unwrap();
|
||||
assert_eq!(
|
||||
combined
|
||||
.notes
|
||||
.iter()
|
||||
.filter(|n| n.start >= SECTION && n.start < 2 * SECTION)
|
||||
.copied()
|
||||
.collect::<Vec<_>>(),
|
||||
expected
|
||||
);
|
||||
s.settings.seed += 7;
|
||||
s.regenerate().unwrap();
|
||||
assert_eq!(s.pins[0], saved);
|
||||
s.accept_composed().unwrap();
|
||||
assert_eq!(s.accepted, Some(s.composed_phrase().unwrap()));
|
||||
assert_eq!(Session::from_json(&s.to_json().unwrap()).unwrap(), s);
|
||||
}
|
||||
#[test]
|
||||
fn version_one_sessions_migrate_without_losing_existing_notes() {
|
||||
let s = Session {
|
||||
source: Some(demo_motif()),
|
||||
..Default::default()
|
||||
};
|
||||
let mut value = serde_json::to_value(&s).unwrap();
|
||||
value["version"] = 1.into();
|
||||
let object = value.as_object_mut().unwrap();
|
||||
for key in ["harmony", "pins", "audition", "looping"] {
|
||||
object.remove(key);
|
||||
}
|
||||
let settings = object.get_mut("settings").unwrap().as_object_mut().unwrap();
|
||||
for key in ["preserve_contour", "task", "ending"] {
|
||||
settings.remove(key);
|
||||
}
|
||||
for n in object.get_mut("source").unwrap()["notes"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
{
|
||||
n.as_object_mut().unwrap().remove("pitch_locked");
|
||||
n.as_object_mut().unwrap().remove("rhythm_locked");
|
||||
}
|
||||
let migrated = Session::from_json(&serde_json::to_vec(&value).unwrap()).unwrap();
|
||||
assert_eq!(migrated.version, STATE_VERSION);
|
||||
assert_eq!(migrated.source, s.source);
|
||||
assert!(!migrated.looping);
|
||||
assert!(migrated.harmony.spans.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn invalid_pins_and_unsafe_legacy_seams_are_rejected() {
|
||||
let mut s = Session {
|
||||
source: Some(demo_motif()),
|
||||
..Default::default()
|
||||
};
|
||||
s.regenerate().unwrap();
|
||||
s.candidates[0].phrase.notes = vec![Note {
|
||||
start: SECTION - 100,
|
||||
duration: 200,
|
||||
pitch: 60,
|
||||
velocity: 80,
|
||||
..Default::default()
|
||||
}];
|
||||
assert!(s.pin_selected(1).is_err());
|
||||
assert!(s.pin_selected(9).is_err());
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
use rivet_core::*;
|
||||
fn held() -> Phrase {
|
||||
Phrase {
|
||||
length: PPQ,
|
||||
notes: vec![
|
||||
Note {
|
||||
start: 0,
|
||||
duration: PPQ / 2,
|
||||
pitch: 60,
|
||||
velocity: 90,
|
||||
..Default::default()
|
||||
},
|
||||
Note {
|
||||
start: PPQ / 2,
|
||||
duration: PPQ / 2,
|
||||
pitch: 60,
|
||||
velocity: 70,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn role_handoffs_preserve_event_identity_and_respect_locks() {
|
||||
let mut source = demo_motif();
|
||||
source.notes[1].pitch_locked = true;
|
||||
source.notes[0].locked = true;
|
||||
for mode in RoleMode::ALL {
|
||||
let mut s = PerformanceSettings {
|
||||
mode,
|
||||
..Default::default()
|
||||
};
|
||||
s.voices[0].transpose = -12;
|
||||
s.voices[1].transpose = 12;
|
||||
s.voices[0].velocity = 50;
|
||||
s.voices[1].velocity = 50;
|
||||
let p = Performance::compile(&source, &s, 140., false).unwrap();
|
||||
let on: Vec<_> = p
|
||||
.events
|
||||
.iter()
|
||||
.filter(|e| e.message.kind == MessageKind::On && !e.next_cycle)
|
||||
.collect();
|
||||
assert_eq!(on.len(), source.notes.len());
|
||||
for (i, n) in source.notes.iter().enumerate() {
|
||||
let role = mode.role(i, n);
|
||||
let actual = on.iter().find(|e| e.tick == n.start as i32).unwrap();
|
||||
assert_eq!(actual.message.channel, s.voices[role].channel);
|
||||
assert_eq!(
|
||||
actual.message.key,
|
||||
if n.keeps_pitch() {
|
||||
n.pitch
|
||||
} else {
|
||||
(n.pitch as i16 + s.voices[role].transpose as i16) as u8
|
||||
}
|
||||
);
|
||||
}
|
||||
assert_eq!(on[0].message.value, 90);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn controller_interpolation_and_validation_are_explicit() {
|
||||
let mut curve = ControllerCurve::default();
|
||||
assert_eq!(curve.value_at(500), 64);
|
||||
curve.shape(2);
|
||||
assert_eq!(curve.value_at(500), 127);
|
||||
assert_eq!(curve.value_at(1000), 0);
|
||||
curve.cc = 64;
|
||||
assert!(curve.validate().is_err());
|
||||
let mut s = PerformanceSettings::default();
|
||||
s.voices[0].controller.enabled = true;
|
||||
s.voices[0].controller.cc = 20;
|
||||
let p = Performance::compile(&held(), &s, 120., false).unwrap();
|
||||
assert!(p
|
||||
.events
|
||||
.iter()
|
||||
.any(|e| e.message.kind == MessageKind::Control
|
||||
&& e.message.key == 20
|
||||
&& e.message.value == 127));
|
||||
s.voices[0].controller.points[1].position = 0;
|
||||
assert!(s.validate().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn attack_compensation_warms_up_once_and_wraps_without_cutting_the_next_note() {
|
||||
let mut s = PerformanceSettings::default();
|
||||
s.voices[0].attack_ms = 100;
|
||||
let performance = Performance::compile(&held(), &s, 120., true).unwrap();
|
||||
assert_eq!(performance.lead_in, 192);
|
||||
assert!(performance
|
||||
.events
|
||||
.iter()
|
||||
.any(|e| e.tick == -192 && e.message.kind == MessageKind::On && !e.next_cycle));
|
||||
let mut player = PerformancePlayer::default();
|
||||
player.set_sample_rate(8000.).unwrap();
|
||||
player.set_looping(true);
|
||||
player.play(performance.clip().unwrap());
|
||||
let mut ons = Vec::new();
|
||||
for frame in 0..4802 {
|
||||
let (_, events) = player.next_frame(120.);
|
||||
for e in events.events[..events.len].iter().flatten() {
|
||||
if e.kind == MessageKind::On {
|
||||
ons.push(frame);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(ons.len(), 3);
|
||||
assert_eq!(ons[0], 0);
|
||||
assert!((ons[2] as i32 - 4000).abs() <= 1);
|
||||
assert!(player
|
||||
.current_messages()
|
||||
.events
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|e| e.kind == MessageKind::On && e.key == 60));
|
||||
player.set_looping(false);
|
||||
player.play(performance.clip().unwrap());
|
||||
let mut count = 0;
|
||||
while player.is_playing() {
|
||||
let (_, events) = player.next_frame(120.);
|
||||
count += events
|
||||
.events
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|e| e.kind == MessageKind::On)
|
||||
.count();
|
||||
}
|
||||
assert_eq!(count, 2);
|
||||
}
|
||||
#[test]
|
||||
fn public_clip_validation_rejects_bad_roles_and_dense_events() {
|
||||
let mut p =
|
||||
Performance::compile(&held(), &PerformanceSettings::default(), 120., false).unwrap();
|
||||
p.events[0].role = 9;
|
||||
assert!(p.clip().is_err());
|
||||
let event = TimedMessage {
|
||||
tick: 0,
|
||||
role: 0,
|
||||
message: MidiMessage {
|
||||
kind: MessageKind::On,
|
||||
channel: 0,
|
||||
key: 60,
|
||||
value: 90,
|
||||
rest: 0,
|
||||
},
|
||||
next_cycle: false,
|
||||
};
|
||||
let p = Performance {
|
||||
length: PPQ,
|
||||
lead_in: 0,
|
||||
events: vec![event; 17],
|
||||
};
|
||||
assert!(p.clip().is_err());
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "rivet-midi"
|
||||
version = "0.3.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
rivet-core.workspace = true
|
||||
@@ -0,0 +1,546 @@
|
||||
//! Strict Standard MIDI File import/export. Unsupported data is reported, never flattened.
|
||||
use rivet_core::{
|
||||
Error, MessageKind, Note, Performance, PerformanceSettings, Phrase, Result, BAR,
|
||||
MAX_PLAYBACK_NOTES, PPQ,
|
||||
};
|
||||
|
||||
pub const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
|
||||
#[derive(Debug)]
|
||||
pub struct MidiTrack {
|
||||
pub name: String,
|
||||
pub phrase: Phrase,
|
||||
pub warnings: Vec<String>,
|
||||
pub channels: Vec<u8>,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct MidiFile {
|
||||
pub tracks: Vec<MidiTrack>,
|
||||
pub tempo: Option<f64>,
|
||||
}
|
||||
fn error(s: &str) -> Error {
|
||||
Error(s.into())
|
||||
}
|
||||
|
||||
struct Reader<'a> {
|
||||
bytes: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
impl<'a> Reader<'a> {
|
||||
fn take(&mut self, len: usize) -> Result<&'a [u8]> {
|
||||
let end = self
|
||||
.pos
|
||||
.checked_add(len)
|
||||
.ok_or_else(|| error("MIDI length overflow."))?;
|
||||
let out = self
|
||||
.bytes
|
||||
.get(self.pos..end)
|
||||
.ok_or_else(|| error("Truncated MIDI file."))?;
|
||||
self.pos = end;
|
||||
Ok(out)
|
||||
}
|
||||
fn byte(&mut self) -> Result<u8> {
|
||||
Ok(self.take(1)?[0])
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16> {
|
||||
let b = self.take(2)?;
|
||||
Ok(u16::from_be_bytes([b[0], b[1]]))
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32> {
|
||||
let b = self.take(4)?;
|
||||
Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
fn vlq(&mut self) -> Result<u32> {
|
||||
let mut v = 0;
|
||||
for _ in 0..4 {
|
||||
let b = self.byte()?;
|
||||
v = (v << 7) | (b & 127) as u32;
|
||||
if b & 128 == 0 {
|
||||
return Ok(v);
|
||||
}
|
||||
}
|
||||
Err(error("Invalid MIDI variable-length integer."))
|
||||
}
|
||||
fn data(&mut self) -> Result<u8> {
|
||||
let b = self.byte()?;
|
||||
if b > 127 {
|
||||
Err(error("Invalid MIDI data byte."))
|
||||
} else {
|
||||
Ok(b)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn ticks(value: u32, division: u16) -> Result<u32> {
|
||||
let numerator = value as u64 * PPQ as u64;
|
||||
if !numerator.is_multiple_of(division as u64) {
|
||||
return Err(error("This MIDI timing cannot be represented exactly at 960 PPQ. Re-export at 96, 480, or 960 PPQ."));
|
||||
}
|
||||
u32::try_from(numerator / division as u64).map_err(|_| error("MIDI timeline is too long."))
|
||||
}
|
||||
|
||||
pub fn read(bytes: &[u8]) -> Result<MidiFile> {
|
||||
if bytes.len() > MAX_FILE_BYTES {
|
||||
return Err(error("MIDI file exceeds 4 MiB."));
|
||||
}
|
||||
let mut r = Reader { bytes, pos: 0 };
|
||||
if r.take(4)? != b"MThd" {
|
||||
return Err(error("Select a standard .mid MIDI file."));
|
||||
}
|
||||
let header_len = r.u32()? as usize;
|
||||
if header_len < 6 {
|
||||
return Err(error("Invalid MIDI header."));
|
||||
}
|
||||
let format = r.u16()?;
|
||||
let count = r.u16()?;
|
||||
let division = r.u16()?;
|
||||
if format > 1 {
|
||||
return Err(error(
|
||||
"Asynchronous format-2 MIDI is unsupported. Export format 0 or 1.",
|
||||
));
|
||||
}
|
||||
if count == 0 || count > 128 || (format == 0 && count != 1) {
|
||||
return Err(error("Invalid MIDI track count (maximum 128)."));
|
||||
}
|
||||
if division == 0 || division & 0x8000 != 0 {
|
||||
return Err(error(
|
||||
"SMPTE timing is unsupported. Export beat-based MIDI.",
|
||||
));
|
||||
}
|
||||
r.take(header_len - 6)?;
|
||||
let mut tracks = Vec::new();
|
||||
let mut tempo = None;
|
||||
for track_index in 0..count {
|
||||
if r.take(4)? != b"MTrk" {
|
||||
return Err(error("Missing MIDI track chunk."));
|
||||
}
|
||||
let len = r.u32()? as usize;
|
||||
let data = r.take(len)?;
|
||||
let mut t = Reader {
|
||||
bytes: data,
|
||||
pos: 0,
|
||||
};
|
||||
let mut clock = 0u32;
|
||||
let mut running = 0u8;
|
||||
let mut active = [[None; 128]; 16];
|
||||
let mut notes = Vec::new();
|
||||
let mut name = format!("Track {}", track_index + 1);
|
||||
let mut ignored = false;
|
||||
let mut channels = 0u16;
|
||||
let mut ended = false;
|
||||
let mut events = 0;
|
||||
while t.pos < data.len() {
|
||||
events += 1;
|
||||
if events > 100_000 {
|
||||
return Err(error("MIDI track exceeds 100,000 events."));
|
||||
}
|
||||
clock = clock
|
||||
.checked_add(t.vlq()?)
|
||||
.ok_or_else(|| error("MIDI timeline overflow."))?;
|
||||
let first = t.byte()?;
|
||||
let status = if first < 128 {
|
||||
if running == 0 {
|
||||
return Err(error("Invalid MIDI running status."));
|
||||
}
|
||||
t.pos -= 1;
|
||||
running
|
||||
} else {
|
||||
first
|
||||
};
|
||||
match status {
|
||||
0xff => {
|
||||
running = 0;
|
||||
let kind = t.byte()?;
|
||||
let len = t.vlq()? as usize;
|
||||
let body = t.take(len)?;
|
||||
match kind {
|
||||
0x03 => name = String::from_utf8_lossy(body).chars().take(120).collect(),
|
||||
0x2f => {
|
||||
if !body.is_empty() {
|
||||
return Err(error("Invalid end-of-track event."));
|
||||
}
|
||||
ended = true;
|
||||
break;
|
||||
}
|
||||
0x51 => {
|
||||
if body.len() != 3 {
|
||||
return Err(error("Invalid tempo event."));
|
||||
}
|
||||
let us =
|
||||
((body[0] as u32) << 16) | ((body[1] as u32) << 8) | body[2] as u32;
|
||||
if us == 0 {
|
||||
return Err(error("Invalid zero MIDI tempo."));
|
||||
}
|
||||
if tempo.is_none() {
|
||||
tempo = Some(60_000_000. / us as f64);
|
||||
} else {
|
||||
ignored = true;
|
||||
}
|
||||
}
|
||||
0x58 => {
|
||||
if body.len() != 4 {
|
||||
return Err(error("Invalid time signature."));
|
||||
}
|
||||
if body[0] != 4 || body[1] != 2 {
|
||||
return Err(error(
|
||||
"Only 4/4 motifs are supported in this version.",
|
||||
));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
0xf0 | 0xf7 => {
|
||||
running = 0;
|
||||
let len = t.vlq()? as usize;
|
||||
t.take(len)?;
|
||||
ignored = true;
|
||||
}
|
||||
0x80..=0xef => {
|
||||
running = status;
|
||||
let a = t.data()?;
|
||||
let b = if status & 0xf0 == 0xc0 || status & 0xf0 == 0xd0 {
|
||||
0
|
||||
} else {
|
||||
t.data()?
|
||||
};
|
||||
let ch = (status & 15) as usize;
|
||||
match (status & 0xf0, b) {
|
||||
(0x90, 1..=127) => {
|
||||
channels |= 1 << ch;
|
||||
if active[ch][a as usize].is_some() {
|
||||
return Err(error(
|
||||
"Repeated note-on before note-off is unsupported.",
|
||||
));
|
||||
}
|
||||
active[ch][a as usize] = Some((clock, b));
|
||||
}
|
||||
(0x80, _) | (0x90, 0) => {
|
||||
let (start, velocity) =
|
||||
active[ch][a as usize].take().ok_or_else(|| {
|
||||
error("MIDI contains a note-off without a note-on.")
|
||||
})?;
|
||||
let start = ticks(start, division)?;
|
||||
let end = ticks(clock, division)?;
|
||||
if end <= start {
|
||||
return Err(error("MIDI contains a zero-length note."));
|
||||
}
|
||||
if notes.len() >= MAX_PLAYBACK_NOTES {
|
||||
return Err(error("MIDI track has too many notes."));
|
||||
}
|
||||
notes.push(Note {
|
||||
start,
|
||||
duration: end - start,
|
||||
pitch: a,
|
||||
velocity,
|
||||
locked: false,
|
||||
..Note::default()
|
||||
});
|
||||
}
|
||||
_ => ignored = true,
|
||||
}
|
||||
}
|
||||
_ => return Err(error("Unsupported MIDI event status.")),
|
||||
}
|
||||
}
|
||||
if !ended {
|
||||
return Err(error("MIDI track is missing its end-of-track event."));
|
||||
}
|
||||
if active.iter().flatten().any(Option::is_some) {
|
||||
return Err(error("MIDI contains notes without note-offs."));
|
||||
}
|
||||
if !notes.is_empty() {
|
||||
notes.sort_by_key(|n| (n.start, n.pitch));
|
||||
let end = ticks(clock, division)?.max(notes.iter().map(Note::end).max().unwrap_or(0));
|
||||
let length = end
|
||||
.checked_add(BAR - 1)
|
||||
.ok_or_else(|| error("MIDI timeline overflow."))?
|
||||
/ BAR
|
||||
* BAR;
|
||||
let warnings = if ignored {
|
||||
vec!["Controllers, pitch bend, program changes, SysEx, or later tempo events are not imported. Preview uses a single tempo.".into()]
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
tracks.push(MidiTrack {
|
||||
name,
|
||||
phrase: Phrase { notes, length },
|
||||
warnings,
|
||||
channels: (0..16).filter(|c| channels & (1 << c) != 0).collect(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if tracks.is_empty() {
|
||||
return Err(error("This MIDI file has no note tracks."));
|
||||
}
|
||||
Ok(MidiFile { tracks, tempo })
|
||||
}
|
||||
|
||||
fn vlq(mut value: u32, out: &mut Vec<u8>) {
|
||||
let mut b = [0u8; 5];
|
||||
let mut i = 4;
|
||||
b[i] = (value & 127) as u8;
|
||||
value >>= 7;
|
||||
while value > 0 {
|
||||
i -= 1;
|
||||
b[i] = ((value & 127) as u8) | 128;
|
||||
value >>= 7;
|
||||
}
|
||||
out.extend_from_slice(&b[i..]);
|
||||
}
|
||||
|
||||
pub fn write(phrase: &Phrase, bpm: f64) -> Result<Vec<u8>> {
|
||||
phrase.validate(MAX_PLAYBACK_NOTES)?;
|
||||
if !bpm.is_finite() || !(30.0..=300.0).contains(&bpm) {
|
||||
return Err(error("Tempo must be 30–300 BPM."));
|
||||
}
|
||||
let us = (60_000_000. / bpm).round() as u32;
|
||||
let mut track = vec![
|
||||
0,
|
||||
0xff,
|
||||
0x51,
|
||||
3,
|
||||
(us >> 16) as u8,
|
||||
(us >> 8) as u8,
|
||||
us as u8,
|
||||
0,
|
||||
0xff,
|
||||
0x58,
|
||||
4,
|
||||
4,
|
||||
2,
|
||||
24,
|
||||
8,
|
||||
];
|
||||
let mut events = Vec::new();
|
||||
for n in &phrase.notes {
|
||||
events.push((n.start, 1, n.pitch, n.velocity));
|
||||
events.push((n.end(), 0, n.pitch, 0));
|
||||
}
|
||||
events.sort_unstable();
|
||||
let mut previous = 0;
|
||||
for (time, on, pitch, velocity) in events {
|
||||
vlq(time - previous, &mut track);
|
||||
track.extend_from_slice(&[if on == 1 { 0x90 } else { 0x80 }, pitch, velocity]);
|
||||
previous = time;
|
||||
}
|
||||
vlq(phrase.length - previous, &mut track);
|
||||
track.extend_from_slice(&[0xff, 0x2f, 0]);
|
||||
let mut out = b"MThd\0\0\0\x06\0\0\0\x01".to_vec();
|
||||
out.extend_from_slice(&(PPQ as u16).to_be_bytes());
|
||||
out.extend_from_slice(b"MTrk");
|
||||
out.extend_from_slice(&(track.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(&track);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Two explicit sound roles, named tracks, channel routing, and mapped expression.
|
||||
/// Compensated export adds a full bar before the intended musical start.
|
||||
pub fn write_performance(
|
||||
phrase: &Phrase,
|
||||
settings: &PerformanceSettings,
|
||||
bpm: f64,
|
||||
) -> Result<Vec<u8>> {
|
||||
let p = Performance::compile(phrase, settings, bpm, settings.compensated_export)?;
|
||||
let shift = if settings.compensated_export && p.lead_in > 0 {
|
||||
BAR
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let us = (60_000_000. / bpm).round() as u32;
|
||||
let mut conductor = vec![
|
||||
0,
|
||||
0xff,
|
||||
0x51,
|
||||
3,
|
||||
(us >> 16) as u8,
|
||||
(us >> 8) as u8,
|
||||
us as u8,
|
||||
0,
|
||||
0xff,
|
||||
0x58,
|
||||
4,
|
||||
4,
|
||||
2,
|
||||
24,
|
||||
8,
|
||||
];
|
||||
vlq(phrase.length + shift, &mut conductor);
|
||||
conductor.extend_from_slice(&[0xff, 0x2f, 0]);
|
||||
let mut tracks = vec![conductor];
|
||||
for role in 0..2 {
|
||||
let events: Vec<_> = p
|
||||
.events
|
||||
.iter()
|
||||
.filter(|e| e.role as usize == role && !e.next_cycle)
|
||||
.collect();
|
||||
if events.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut track = vec![0, 0xff, 3];
|
||||
let name = format!(
|
||||
"{} (channel {})",
|
||||
settings.voices[role].name,
|
||||
settings.voices[role].channel + 1
|
||||
);
|
||||
vlq(name.len() as u32, &mut track);
|
||||
track.extend_from_slice(name.as_bytes());
|
||||
let mut previous = 0;
|
||||
for e in events {
|
||||
let tick = (e.tick + shift as i32) as u32;
|
||||
vlq(tick - previous, &mut track);
|
||||
let kind = match e.message.kind {
|
||||
MessageKind::Off => 0x80,
|
||||
MessageKind::On => 0x90,
|
||||
MessageKind::Control => 0xb0,
|
||||
};
|
||||
track.extend_from_slice(&[kind | e.message.channel, e.message.key, e.message.value]);
|
||||
previous = tick;
|
||||
}
|
||||
let end = phrase.length + shift;
|
||||
if settings.voices[role].controller.enabled {
|
||||
vlq(end - previous, &mut track);
|
||||
track.extend_from_slice(&[
|
||||
0xb0 | settings.voices[role].channel,
|
||||
settings.voices[role].controller.cc,
|
||||
settings.voices[role].controller.rest,
|
||||
]);
|
||||
previous = end;
|
||||
}
|
||||
vlq(end - previous, &mut track);
|
||||
track.extend_from_slice(&[0xff, 0x2f, 0]);
|
||||
tracks.push(track);
|
||||
}
|
||||
let mut out = b"MThd\0\0\0\x06\0\x01".to_vec();
|
||||
out.extend_from_slice(&(tracks.len() as u16).to_be_bytes());
|
||||
out.extend_from_slice(&(PPQ as u16).to_be_bytes());
|
||||
for track in tracks {
|
||||
out.extend_from_slice(b"MTrk");
|
||||
out.extend_from_slice(&(track.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(&track);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn file(track: &[u8]) -> Vec<u8> {
|
||||
let mut b = b"MThd\0\0\0\x06\0\0\0\x01\x03\xc0MTrk".to_vec();
|
||||
b.extend_from_slice(&(track.len() as u32).to_be_bytes());
|
||||
b.extend_from_slice(track);
|
||||
b
|
||||
}
|
||||
#[test]
|
||||
fn round_trip_source_and_generated_phrase() {
|
||||
let source = rivet_core::demo_motif();
|
||||
let bytes = write(&source, 140.).unwrap();
|
||||
let parsed = read(&bytes).unwrap();
|
||||
assert_eq!(parsed.tracks[0].phrase, source);
|
||||
assert!((parsed.tempo.unwrap() - 140.).abs() < 0.001);
|
||||
for c in rivet_core::generate(&source, &rivet_core::Settings::default()).unwrap() {
|
||||
assert_eq!(
|
||||
read(&write(&c.phrase, 140.).unwrap()).unwrap().tracks[0].phrase,
|
||||
c.phrase
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn running_status_and_zero_velocity_off() {
|
||||
let parsed = read(&file(&[
|
||||
0, 0x90, 60, 90, 0x83, 0x60, 60, 0, 0, 0xff, 0x2f, 0,
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(parsed.tracks[0].phrase.notes[0].duration, 480);
|
||||
}
|
||||
#[test]
|
||||
fn malformed_and_unsupported_files() {
|
||||
let good = write(&rivet_core::demo_motif(), 140.).unwrap();
|
||||
for n in 0..good.len() {
|
||||
assert!(read(&good[..n]).is_err());
|
||||
}
|
||||
let mut smpte = good.clone();
|
||||
smpte[12] = 0x80;
|
||||
assert!(read(&smpte).unwrap_err().0.contains("SMPTE"));
|
||||
assert!(read(&file(&[0, 0x90, 60, 80, 0, 0xff, 0x2f, 0])).is_err());
|
||||
assert!(
|
||||
read(&file(&[0, 0xff, 0x58, 4, 3, 2, 24, 8, 0, 0xff, 0x2f, 0]))
|
||||
.unwrap_err()
|
||||
.0
|
||||
.contains("4/4")
|
||||
);
|
||||
assert!(read(&file(&[0x81, 0x81, 0x81, 0x81, 0, 0xff, 0x2f, 0])).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn overlap_is_available_for_selection_but_rejected_as_motif() {
|
||||
let p = read(&file(&[
|
||||
0, 0x90, 60, 90, 0, 0x90, 67, 80, 10, 0x80, 60, 0, 0, 0x80, 67, 0, 0, 0xff, 0x2f, 0,
|
||||
]))
|
||||
.unwrap();
|
||||
assert!(p.tracks[0]
|
||||
.phrase
|
||||
.validate_source()
|
||||
.unwrap_err()
|
||||
.0
|
||||
.contains("Overlapping"));
|
||||
}
|
||||
#[test]
|
||||
fn separate_tracks_and_timing_resolution() {
|
||||
let a = write(&rivet_core::demo_motif(), 140.).unwrap();
|
||||
let mut two = a[..14].to_vec();
|
||||
two[9] = 1;
|
||||
two[11] = 2;
|
||||
two.extend_from_slice(&a[14..]);
|
||||
two.extend_from_slice(&a[14..]);
|
||||
assert_eq!(read(&two).unwrap().tracks.len(), 2);
|
||||
let mut b = file(&[1, 0x90, 60, 80, 1, 0x80, 60, 0, 0, 0xff, 0x2f, 0]);
|
||||
b[12..14].copy_from_slice(&1000u16.to_be_bytes());
|
||||
assert!(read(&b).unwrap_err().0.contains("exactly"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn performance_export_has_named_channel_tracks_and_controller_resets() {
|
||||
let mut settings = PerformanceSettings {
|
||||
mode: rivet_core::RoleMode::Alternating,
|
||||
..Default::default()
|
||||
};
|
||||
for (role, v) in settings.voices.iter_mut().enumerate() {
|
||||
v.controller.enabled = true;
|
||||
v.controller.cc = 20 + role as u8;
|
||||
v.controller.rest = 5 + role as u8;
|
||||
}
|
||||
let source = rivet_core::demo_motif();
|
||||
let bytes = write_performance(&source, &settings, 120.).unwrap();
|
||||
let file = read(&bytes).unwrap();
|
||||
assert_eq!(file.tracks.len(), 2);
|
||||
assert_eq!(file.tracks[0].channels, vec![0]);
|
||||
assert_eq!(file.tracks[1].channels, vec![1]);
|
||||
assert!(file.tracks[0].name.contains("Primary"));
|
||||
assert!(file.tracks[1].name.contains("Answer"));
|
||||
assert_eq!(
|
||||
file.tracks
|
||||
.iter()
|
||||
.map(|t| t.phrase.notes.len())
|
||||
.sum::<usize>(),
|
||||
source.notes.len()
|
||||
);
|
||||
assert!(file.tracks.iter().all(|t| !t.warnings.is_empty()));
|
||||
assert!(bytes
|
||||
.windows(7)
|
||||
.any(|p| p == [0xb0, 20, 5, 0, 0xff, 0x2f, 0]));
|
||||
assert!(bytes
|
||||
.windows(7)
|
||||
.any(|p| p == [0xb1, 21, 6, 0, 0xff, 0x2f, 0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compensated_export_adds_lead_in_while_default_export_keeps_the_grid() {
|
||||
let source = rivet_core::demo_motif();
|
||||
let mut settings = PerformanceSettings::default();
|
||||
settings.voices[0].attack_ms = 100;
|
||||
let direct = read(&write_performance(&source, &settings, 120.).unwrap()).unwrap();
|
||||
assert_eq!(direct.tracks[0].phrase.notes[0].start, 0);
|
||||
settings.compensated_export = true;
|
||||
let compensated = read(&write_performance(&source, &settings, 120.).unwrap()).unwrap();
|
||||
assert_eq!(compensated.tracks[0].phrase.notes[0].start, BAR - 192);
|
||||
assert_eq!(compensated.tracks[0].phrase.length, source.length + BAR);
|
||||
}
|
||||
}
|
||||
@@ -1350,19 +1350,6 @@ dependencies = [
|
||||
"adler2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "motif-storyboard"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"nih_plug",
|
||||
"nih_plug_egui",
|
||||
"serde_json",
|
||||
"story-app",
|
||||
"story-core",
|
||||
"story-midi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ndk"
|
||||
version = "0.8.0"
|
||||
@@ -2065,6 +2052,44 @@ version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "rivet"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"nih_plug",
|
||||
"nih_plug_egui",
|
||||
"rivet-app",
|
||||
"rivet-core",
|
||||
"rivet-midi",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rivet-app"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"crossbeam-queue",
|
||||
"rivet-core",
|
||||
"rivet-midi",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rivet-core"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rivet-midi"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"rivet-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rtrb"
|
||||
version = "0.2.3"
|
||||
@@ -2249,31 +2274,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "story-app"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"crossbeam-queue",
|
||||
"story-core",
|
||||
"story-midi",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "story-core"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "story-midi"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"story-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "motif-storyboard"
|
||||
name = "rivet"
|
||||
version = "0.3.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
@@ -11,7 +11,7 @@ license = "ISC"
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[[bin]]
|
||||
name = "motif-storyboard"
|
||||
name = "rivet"
|
||||
path = "src/main.rs"
|
||||
required-features = ["standalone"]
|
||||
|
||||
@@ -21,9 +21,9 @@ standalone = ["nih_plug/standalone"]
|
||||
[dependencies]
|
||||
nih_plug = { git = "https://github.com/robbert-vdh/nih-plug.git", rev = "de421011f41a6d10fc8c7a6084e4f4dee0143683", default-features = false }
|
||||
nih_plug_egui = { git = "https://github.com/robbert-vdh/nih-plug.git", rev = "de421011f41a6d10fc8c7a6084e4f4dee0143683" }
|
||||
story-core = { path = "../../crates/story-core" }
|
||||
story-midi = { path = "../../crates/story-midi" }
|
||||
story-app = { path = "../../crates/story-app" }
|
||||
rivet-core = { path = "../core" }
|
||||
rivet-midi = { path = "../midi" }
|
||||
rivet-app = { path = "../app" }
|
||||
|
||||
[dev-dependencies]
|
||||
clap-sys = { git = "https://github.com/micahrj/clap-sys.git", rev = "25d7f53fdb6363ad63fbd80049cb7a42a97ac156" }
|
||||
+8
-8
@@ -1,7 +1,7 @@
|
||||
use super::{egui, report, start, EditorState, LOCK, MUTED, NOTE};
|
||||
use rivet_app::{Output, Shared};
|
||||
use rivet_core::{CreativeMove, PerformanceSettings, Result, RoleMode, Session};
|
||||
use std::sync::Arc;
|
||||
use story_app::{Output, Shared};
|
||||
use story_core::{CreativeMove, PerformanceSettings, Result, RoleMode, Session};
|
||||
|
||||
pub struct CreativeUi {
|
||||
gesture_name: String,
|
||||
@@ -77,16 +77,16 @@ pub fn ideas(
|
||||
let saved = session.export_gesture_library();
|
||||
start(shared, state, move || {
|
||||
let bytes = saved?;
|
||||
let Some(mut path) = story_app::dialog::choose(true, true)? else { return Ok(Output::Canceled); };
|
||||
let Some(mut path) = rivet_app::dialog::choose(true, true)? else { return Ok(Output::Canceled); };
|
||||
if path.extension().is_none() { path.set_extension("json"); }
|
||||
story_app::write_new(&path, &bytes)?; Ok(Output::Saved(path))
|
||||
rivet_app::write_new(&path, &bytes)?; Ok(Output::Saved(path))
|
||||
});
|
||||
}
|
||||
if ui.button("Import gestures…").clicked() {
|
||||
start(shared, state, move || {
|
||||
let Some(path) = story_app::dialog::choose(false, true)? else { return Ok(Output::Canceled); };
|
||||
let bytes = story_app::read_limited(&path, 2 * 1024 * 1024)?;
|
||||
Ok(Output::LibraryLoaded(story_core::read_gesture_library(&bytes)?))
|
||||
let Some(path) = rivet_app::dialog::choose(false, true)? else { return Ok(Output::Canceled); };
|
||||
let bytes = rivet_app::read_limited(&path, 2 * 1024 * 1024)?;
|
||||
Ok(Output::LibraryLoaded(rivet_core::read_gesture_library(&bytes)?))
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -204,7 +204,7 @@ pub fn performance(ui: &mut egui::Ui, settings: &mut PerformanceSettings) {
|
||||
if ui.add_enabled(curve.points.len()<16, egui::Button::new("Add point in largest gap")).clicked() {
|
||||
if let Some((index,pair)) = curve.points.windows(2).enumerate().max_by_key(|(_,p)|p[1].position-p[0].position) {
|
||||
let position = (pair[0].position+pair[1].position)/2;
|
||||
if position > pair[0].position { let value = curve.value_at(position); curve.points.insert(index+1,story_core::CurvePoint {position,value}); }
|
||||
if position > pair[0].position { let value = curve.value_at(position); curve.points.insert(index+1,rivet_core::CurvePoint {position,value}); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
//! Shared egui view. Also compiled by the offline visual QA harness against cached egui.
|
||||
use crate::egui::{self, Align2, Color32, FontId, Pos2, Rect, RichText, Sense, Stroke, Vec2};
|
||||
use rivet_app::{Output, Shared};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{atomic::Ordering, Arc},
|
||||
time::Duration,
|
||||
};
|
||||
use story_app::{Output, Shared};
|
||||
#[path = "creative_editor.rs"]
|
||||
mod creative_editor;
|
||||
use story_core::{
|
||||
use rivet_core::{
|
||||
Audition, ChordQuality, Ending, Error, Harmony, Phrase, Result, Scale, Session, Task, BAR,
|
||||
};
|
||||
const INK: Color32 = Color32::from_rgb(225, 231, 243);
|
||||
@@ -25,7 +25,7 @@ pub struct EditorState {
|
||||
error: bool,
|
||||
import_path: String,
|
||||
export_path: String,
|
||||
pending: Option<story_midi::MidiFile>,
|
||||
pending: Option<rivet_midi::MidiFile>,
|
||||
track: usize,
|
||||
preview_lane: Option<usize>,
|
||||
pending_lane: Option<usize>,
|
||||
@@ -109,13 +109,13 @@ fn import(shared: &Arc<Shared>, state: &mut EditorState, path: Option<PathBuf>,
|
||||
start(shared, state, move || {
|
||||
let path = match path {
|
||||
Some(p) => Some(p),
|
||||
None => story_app::dialog::choose(false, false)?,
|
||||
None => rivet_app::dialog::choose(false, false)?,
|
||||
};
|
||||
let Some(path) = path else {
|
||||
return Ok(Output::Canceled);
|
||||
};
|
||||
let bytes = story_app::read_limited(&path, story_midi::MAX_FILE_BYTES)?;
|
||||
Ok(Output::Imported(story_midi::read(&bytes)?))
|
||||
let bytes = rivet_app::read_limited(&path, rivet_midi::MAX_FILE_BYTES)?;
|
||||
Ok(Output::Imported(rivet_midi::read(&bytes)?))
|
||||
});
|
||||
}
|
||||
fn export(
|
||||
@@ -138,7 +138,7 @@ fn export(
|
||||
start(shared, state, move || {
|
||||
let path = match path {
|
||||
Some(p) => Some(p),
|
||||
None => story_app::dialog::choose(true, false)?,
|
||||
None => rivet_app::dialog::choose(true, false)?,
|
||||
};
|
||||
let Some(mut path) = path else {
|
||||
return Ok(Output::Canceled);
|
||||
@@ -146,9 +146,9 @@ fn export(
|
||||
if path.extension().is_none() {
|
||||
path.set_extension("mid");
|
||||
}
|
||||
story_app::write_new(
|
||||
rivet_app::write_new(
|
||||
&path,
|
||||
&story_midi::write_performance(&phrase, &performance, tempo)?,
|
||||
&rivet_midi::write_performance(&phrase, &performance, tempo)?,
|
||||
)?;
|
||||
Ok(Output::Exported(path))
|
||||
});
|
||||
@@ -349,13 +349,13 @@ pub fn show(ui: &mut egui::Ui, shared: &Arc<Shared>, state: &mut EditorState) {
|
||||
});
|
||||
egui::ScrollArea::vertical().show(ui,|ui|{
|
||||
ui.horizontal(|ui|{
|
||||
ui.label(RichText::new("Motif Storyboard").size(28.).strong());
|
||||
ui.label(RichText::new("Rivet").size(28.).strong());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center),|ui|{
|
||||
if ui.add_enabled(!busy,egui::Button::new("Import motif…")).clicked(){
|
||||
import(shared,state,None,false);
|
||||
}
|
||||
if ui.add_enabled(!busy,egui::Button::new("Load demo")).clicked(){
|
||||
session.source=Some(story_core::demo_motif());
|
||||
session.source=Some(rivet_core::demo_motif());
|
||||
session.pins.clear();
|
||||
state.status="Choose what to preserve, then explore a musical task.".into();
|
||||
state.error=false;
|
||||
@@ -548,22 +548,22 @@ pub fn show(ui: &mut egui::Ui, shared: &Arc<Shared>, state: &mut EditorState) {
|
||||
if ui.add_enabled(!busy,egui::Button::new("Save session…")).clicked(){
|
||||
let saved=session.clone();
|
||||
start(shared,state,move||{
|
||||
let Some(mut path)=story_app::dialog::choose(true,true)? else{
|
||||
let Some(mut path)=rivet_app::dialog::choose(true,true)? else{
|
||||
return Ok(Output::Canceled);
|
||||
};
|
||||
if path.extension().is_none(){
|
||||
path.set_extension("json");
|
||||
}
|
||||
story_app::write_new(&path,&saved.to_json()?)?;
|
||||
rivet_app::write_new(&path,&saved.to_json()?)?;
|
||||
Ok(Output::Saved(path))
|
||||
});
|
||||
}
|
||||
if ui.add_enabled(!busy,egui::Button::new("Load session…")).clicked(){
|
||||
start(shared,state,move||{
|
||||
let Some(path)=story_app::dialog::choose(false,true)? else{
|
||||
let Some(path)=rivet_app::dialog::choose(false,true)? else{
|
||||
return Ok(Output::Canceled);
|
||||
};
|
||||
Ok(Output::Loaded(Box::new(Session::from_json(&story_app::read_limited(&path,story_core::MAX_STATE_BYTES)?)?)))
|
||||
Ok(Output::Loaded(Box::new(Session::from_json(&rivet_app::read_limited(&path,rivet_core::MAX_STATE_BYTES)?)?)))
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -620,7 +620,7 @@ pub fn show(ui: &mut egui::Ui, shared: &Arc<Shared>, state: &mut EditorState) {
|
||||
let settings = session.settings.clone();
|
||||
let harmony = session.harmony.clone();
|
||||
start_at(shared, state, generation_revision, move || {
|
||||
Ok(Output::Generated(story_core::generate_with_harmony(
|
||||
Ok(Output::Generated(rivet_core::generate_with_harmony(
|
||||
&source, &settings, &harmony,
|
||||
)?))
|
||||
});
|
||||
@@ -712,7 +712,7 @@ fn harmony_editor(
|
||||
#[derive(Clone, Copy)]
|
||||
struct RollStyle {
|
||||
register: (u8, u8),
|
||||
roles: story_core::RoleMode,
|
||||
roles: rivet_core::RoleMode,
|
||||
}
|
||||
fn roll(
|
||||
ui: &mut egui::Ui,
|
||||
@@ -1,9 +1,9 @@
|
||||
use nih_plug::{params::persist::PersistentField, prelude::*};
|
||||
pub use nih_plug_egui::egui;
|
||||
use nih_plug_egui::{create_egui_editor, EguiState};
|
||||
use rivet_app::{AudioEngine, Shared};
|
||||
use rivet_core::Session;
|
||||
use std::sync::{atomic::Ordering, Arc};
|
||||
use story_app::{AudioEngine, Shared};
|
||||
use story_core::Session;
|
||||
mod editor;
|
||||
|
||||
pub struct SessionField(Arc<Shared>);
|
||||
@@ -24,7 +24,7 @@ impl<'a> PersistentField<'a, Session> for SessionField {
|
||||
}
|
||||
|
||||
#[derive(Params)]
|
||||
struct StoryParams {
|
||||
struct RivetParams {
|
||||
#[persist = "editor"]
|
||||
editor: Arc<EguiState>,
|
||||
#[persist = "story-session-v1"]
|
||||
@@ -34,17 +34,17 @@ struct StoryParams {
|
||||
revision: IntParam,
|
||||
}
|
||||
|
||||
pub struct MotifStoryboard {
|
||||
params: Arc<StoryParams>,
|
||||
pub struct Rivet {
|
||||
params: Arc<RivetParams>,
|
||||
shared: Arc<Shared>,
|
||||
audio: AudioEngine,
|
||||
host_was_playing: bool,
|
||||
}
|
||||
impl Default for MotifStoryboard {
|
||||
impl Default for Rivet {
|
||||
fn default() -> Self {
|
||||
let shared = Arc::new(Shared::default());
|
||||
Self {
|
||||
params: Arc::new(StoryParams {
|
||||
params: Arc::new(RivetParams {
|
||||
editor: EguiState::from_size(1100, 850),
|
||||
session: SessionField(shared.clone()),
|
||||
revision: IntParam::new(
|
||||
@@ -64,9 +64,9 @@ impl Default for MotifStoryboard {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Plugin for MotifStoryboard {
|
||||
const NAME: &'static str = "Motif Storyboard";
|
||||
const VENDOR: &'static str = "Storyboard";
|
||||
impl Plugin for Rivet {
|
||||
const NAME: &'static str = "Rivet";
|
||||
const VENDOR: &'static str = "Rivet & Patina";
|
||||
const URL: &'static str = "";
|
||||
const EMAIL: &'static str = "";
|
||||
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
@@ -144,21 +144,21 @@ impl Plugin for MotifStoryboard {
|
||||
let frame = self.audio.frame(bpm, midi);
|
||||
for message in frame.events.events[..frame.events.len].iter().flatten() {
|
||||
match message.kind {
|
||||
story_core::MessageKind::Off => context.send_event(NoteEvent::NoteOff {
|
||||
rivet_core::MessageKind::Off => context.send_event(NoteEvent::NoteOff {
|
||||
timing: index as u32,
|
||||
voice_id: None,
|
||||
channel: message.channel,
|
||||
note: message.key,
|
||||
velocity: 0.,
|
||||
}),
|
||||
story_core::MessageKind::On => context.send_event(NoteEvent::NoteOn {
|
||||
rivet_core::MessageKind::On => context.send_event(NoteEvent::NoteOn {
|
||||
timing: index as u32,
|
||||
voice_id: None,
|
||||
channel: message.channel,
|
||||
note: message.key,
|
||||
velocity: message.value as f32 / 127.,
|
||||
}),
|
||||
story_core::MessageKind::Control => context.send_event(NoteEvent::MidiCC {
|
||||
rivet_core::MessageKind::Control => context.send_event(NoteEvent::MidiCC {
|
||||
timing: index as u32,
|
||||
channel: message.channel,
|
||||
cc: message.key,
|
||||
@@ -176,7 +176,7 @@ impl Plugin for MotifStoryboard {
|
||||
ProcessStatus::KeepAlive
|
||||
}
|
||||
}
|
||||
impl ClapPlugin for MotifStoryboard {
|
||||
impl ClapPlugin for Rivet {
|
||||
const CLAP_ID: &'static str = "io.storyboard.motif";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> =
|
||||
Some("Develop a MIDI motif into a connected phrase");
|
||||
@@ -189,4 +189,4 @@ impl ClapPlugin for MotifStoryboard {
|
||||
ClapFeature::Utility,
|
||||
];
|
||||
}
|
||||
nih_export_clap!(MotifStoryboard);
|
||||
nih_export_clap!(Rivet);
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
nih_plug::prelude::nih_export_standalone::<rivet::Rivet>();
|
||||
}
|
||||
@@ -49,8 +49,8 @@ fn exported_factory_state_and_silent_audio_lifecycle() {
|
||||
// SAFETY: All callbacks, strings, streams, buffers, and the host outlive their
|
||||
// synchronous ABI calls. Activation/processing/destruction follow CLAP order.
|
||||
unsafe {
|
||||
let entry = &motif_storyboard::clap_entry;
|
||||
assert!(entry.init.unwrap()(c"motif-storyboard.clap".as_ptr()));
|
||||
let entry = &rivet::clap_entry;
|
||||
assert!(entry.init.unwrap()(c"rivet.clap".as_ptr()));
|
||||
let factory = entry.get_factory.unwrap()(CLAP_PLUGIN_FACTORY_ID.as_ptr())
|
||||
as *const clap_plugin_factory;
|
||||
assert!(!factory.is_null());
|
||||
@@ -58,6 +58,7 @@ fn exported_factory_state_and_silent_audio_lifecycle() {
|
||||
assert_eq!(factory.get_plugin_count.unwrap()(factory), 1);
|
||||
let descriptor = factory.get_plugin_descriptor.unwrap()(factory, 0);
|
||||
assert!(!descriptor.is_null());
|
||||
assert_eq!(CStr::from_ptr((*descriptor).name), c"Rivet");
|
||||
assert_eq!(CStr::from_ptr((*descriptor).id), c"io.storyboard.motif");
|
||||
assert!(factory.get_plugin_descriptor.unwrap()(factory, 1).is_null());
|
||||
let host = clap_host {
|
||||
@@ -96,27 +97,27 @@ fn exported_factory_state_and_silent_audio_lifecycle() {
|
||||
};
|
||||
let mut envelope: nih_plug::prelude::PluginState =
|
||||
serde_json::from_slice(&save()[8..]).unwrap();
|
||||
let mut session = story_core::Session {
|
||||
source: Some(story_core::demo_motif()),
|
||||
let mut session = rivet_core::Session {
|
||||
source: Some(rivet_core::demo_motif()),
|
||||
tempo: 150.,
|
||||
..Default::default()
|
||||
};
|
||||
session.source.as_mut().unwrap().notes[1].locked = true;
|
||||
session.harmony = story_core::Harmony::progression(0, story_core::Scale::Minor);
|
||||
session.audition = story_core::Audition::Midi;
|
||||
session.harmony = rivet_core::Harmony::progression(0, rivet_core::Scale::Minor);
|
||||
session.audition = rivet_core::Audition::Midi;
|
||||
session.regenerate().unwrap();
|
||||
session.pin_selected(1).unwrap();
|
||||
session.accept();
|
||||
session.selected = 2;
|
||||
session.accept();
|
||||
session.performance.mode = story_core::RoleMode::CallResponse;
|
||||
session.performance.mode = rivet_core::RoleMode::CallResponse;
|
||||
session.performance.voices[1].controller.enabled = true;
|
||||
session.performance.voices[1].controller.cc = 20;
|
||||
session.performance.voices[1].attack_ms = 75;
|
||||
session.save_gesture("Airy question", None).unwrap();
|
||||
session.save_branch("Original call").unwrap();
|
||||
session
|
||||
.apply_move(story_core::CreativeMove::Thin, Some(0))
|
||||
.apply_move(rivet_core::CreativeMove::Thin, Some(0))
|
||||
.unwrap();
|
||||
envelope.fields.insert(
|
||||
"story-session-v1".into(),
|
||||
@@ -134,7 +135,7 @@ fn exported_factory_state_and_silent_audio_lifecycle() {
|
||||
let restored: nih_plug::prelude::PluginState =
|
||||
serde_json::from_slice(&save()[8..]).unwrap();
|
||||
assert_eq!(
|
||||
story_core::Session::from_json(restored.fields["story-session-v1"].as_bytes()).unwrap(),
|
||||
rivet_core::Session::from_json(restored.fields["story-session-v1"].as_bytes()).unwrap(),
|
||||
session
|
||||
);
|
||||
for rate in [44100., 48000., 96000.] {
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "rivet-preview"
|
||||
version = "0.3.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
rivet-core.workspace = true
|
||||
rivet-midi.workspace = true
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Headless end-to-end development harness; uses exactly the plugin's composition and voice.
|
||||
use rivet_core::{demo_motif, Harmony, Performance, PerformancePlayer, Session};
|
||||
use std::{env, fs, io::Write, path::PathBuf};
|
||||
|
||||
fn main() {
|
||||
if let Err(e) = run() {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<_> = env::args().skip(1).collect();
|
||||
if args.is_empty() || args[0] == "--help" {
|
||||
println!("Rivet preview\n rivet-preview demo <output-directory>\n rivet-preview develop <input.mid> <track-index> <output-directory> [harmony.mid harmony-track-index]\n rivet-preview session <session.json> <output-directory>\nWrites source.mid, up to three distinct candidates, session.json, and selected.wav. Track indices start at 0.");
|
||||
return Ok(());
|
||||
}
|
||||
let mut session = Session::default();
|
||||
let output = match args[0].as_str() {
|
||||
"demo" if args.len() == 2 => {
|
||||
session.source = Some(demo_motif());
|
||||
PathBuf::from(&args[1])
|
||||
}
|
||||
"session" if args.len() == 3 => {
|
||||
session = Session::from_json(&fs::read(&args[1])?)?;
|
||||
PathBuf::from(&args[2])
|
||||
}
|
||||
"develop" if args.len() == 4 || args.len() == 6 => {
|
||||
let bytes = fs::read(&args[1])?;
|
||||
let file = rivet_midi::read(&bytes)?;
|
||||
let index: usize = args[2].parse()?;
|
||||
let track = file.tracks.get(index).ok_or("Track index out of range")?;
|
||||
track.phrase.validate_source()?;
|
||||
for w in &track.warnings {
|
||||
eprintln!("{w}");
|
||||
}
|
||||
session.source = Some(track.phrase.clone());
|
||||
PathBuf::from(&args[3])
|
||||
}
|
||||
_ => return Err("Use --help for usage.".into()),
|
||||
};
|
||||
if args.len() == 6 {
|
||||
let file = rivet_midi::read(&fs::read(&args[4])?)?;
|
||||
let index: usize = args[5].parse()?;
|
||||
let track = file
|
||||
.tracks
|
||||
.get(index)
|
||||
.ok_or("Harmony track index out of range")?;
|
||||
session.harmony = Harmony::from_midi(&track.phrase.notes, track.phrase.length)?;
|
||||
}
|
||||
if args[0] != "session" {
|
||||
session.regenerate()?;
|
||||
session.accept();
|
||||
}
|
||||
let selected = session.composed_phrase()?;
|
||||
fs::create_dir_all(&output)?;
|
||||
if let Some(source) = &session.source {
|
||||
fs::write(
|
||||
output.join("source.mid"),
|
||||
rivet_midi::write(source, session.tempo)?,
|
||||
)?;
|
||||
}
|
||||
for (i, c) in session.candidates.iter().enumerate() {
|
||||
fs::write(
|
||||
output.join(format!("candidate-{}.mid", i + 1)),
|
||||
rivet_midi::write_performance(&c.phrase, &session.performance, session.tempo)?,
|
||||
)?;
|
||||
println!("{}: {}", c.strategy.name(), c.explanation);
|
||||
}
|
||||
fs::write(output.join("session.json"), session.to_json()?)?;
|
||||
fs::write(
|
||||
output.join("selected.mid"),
|
||||
rivet_midi::write_performance(&selected, &session.performance, session.tempo)?,
|
||||
)?;
|
||||
let mut player = PerformancePlayer::default();
|
||||
player.set_sample_rate(44100.)?;
|
||||
player
|
||||
.play(Performance::compile(&selected, &session.performance, session.tempo, false)?.clip()?);
|
||||
let mut samples = Vec::new();
|
||||
while player.is_playing() {
|
||||
samples.push((player.next_frame(session.tempo).0 * i16::MAX as f32) as i16);
|
||||
}
|
||||
let len = (samples.len() * 2) as u32;
|
||||
let mut wav = fs::File::create(output.join("selected.wav"))?;
|
||||
wav.write_all(b"RIFF")?;
|
||||
wav.write_all(&(36 + len).to_le_bytes())?;
|
||||
wav.write_all(b"WAVEfmt ")?;
|
||||
wav.write_all(&16u32.to_le_bytes())?;
|
||||
wav.write_all(&1u16.to_le_bytes())?;
|
||||
wav.write_all(&1u16.to_le_bytes())?;
|
||||
wav.write_all(&44100u32.to_le_bytes())?;
|
||||
wav.write_all(&88200u32.to_le_bytes())?;
|
||||
wav.write_all(&2u16.to_le_bytes())?;
|
||||
wav.write_all(&16u16.to_le_bytes())?;
|
||||
wav.write_all(b"data")?;
|
||||
wav.write_all(&len.to_le_bytes())?;
|
||||
for s in samples {
|
||||
wav.write_all(&s.to_le_bytes())?;
|
||||
}
|
||||
println!("Saved {}", output.display());
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user