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,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user