Compare commits

..

15 Commits

Author SHA1 Message Date
Bel LaPointe
251ae7f308 boring 2026-03-13 13:23:21 -06:00
Bel LaPointe
5b9d3a8bb7 tone accepts T,t,f for majorThird, minorThird, perfectFifth lazily 2026-03-13 13:01:05 -06:00
Bel LaPointe
fedd6abbff notes 2026-03-13 12:43:20 -06:00
Bel LaPointe
7f0b55ac13 add chord references 2026-03-13 12:25:37 -06:00
Bel LaPointe
fb44f680e6 accept -i for interactive 2026-03-13 12:06:07 -06:00
Bel LaPointe
c6a6d59f1c SHELL 2026-03-13 11:58:10 -06:00
Bel LaPointe
6c0b918612 ew cant async because rust reaps thread running tinyaudio need holder 2026-03-13 11:41:36 -06:00
Bel LaPointe
f00923b414 if promopt then async 2026-03-13 11:35:03 -06:00
Bel LaPointe
de5717a61a panic if shell desired as not impl 2026-03-13 11:34:10 -06:00
36c047caf7 note 2026-03-12 15:56:36 -06:00
f4f074b8e7 drop debug 2026-03-12 15:56:04 -06:00
a08246b30f revert 2026-03-12 15:55:51 -06:00
eb1a537ce2 1*ANY for counts since 60 was arbitrary between middleC and 6*0 2026-03-12 15:55:37 -06:00
31faeb3c1b parse all strings and strip comments whether file or not 2026-03-12 15:42:30 -06:00
a3bb1cf11b more debug strings 2026-03-12 15:06:58 -06:00
21 changed files with 462 additions and 94 deletions

7
Cargo.lock generated
View File

@@ -242,6 +242,7 @@ dependencies = [
"chrono", "chrono",
"clap", "clap",
"env_logger", "env_logger",
"io-prompt-prototype",
"itertools 0.14.0", "itertools 0.14.0",
"midir", "midir",
"regex", "regex",
@@ -412,6 +413,12 @@ dependencies = [
"hashbrown", "hashbrown",
] ]
[[package]]
name = "io-prompt-prototype"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca9d71ad6b790f2522eeb0a4f207fa7ef21826777d4714c7ff09483bf17b0ab8"
[[package]] [[package]]
name = "is_terminal_polyfill" name = "is_terminal_polyfill"
version = "1.70.2" version = "1.70.2"

View File

@@ -7,6 +7,7 @@ edition = "2024"
chrono = "0.4.44" chrono = "0.4.44"
clap = { version = "4.5.60", features = ["derive"] } clap = { version = "4.5.60", features = ["derive"] }
env_logger = "0.11.9" env_logger = "0.11.9"
io-prompt-prototype = "1.0.0"
itertools = "0.14.0" itertools = "0.14.0"
midir = "0.10.3" midir = "0.10.3"
regex = "1.12.3" regex = "1.12.3"

View File

@@ -5,6 +5,9 @@ pub struct Flags {
#[arg(short, long, default_value_t = false)] #[arg(short, long, default_value_t = false)]
pub debug: bool, pub debug: bool,
#[arg(short, long, default_value_t = false)]
pub interactive: bool,
#[arg(long, default_value_t = 120)] #[arg(long, default_value_t = 120)]
pub bpm: usize, pub bpm: usize,
@@ -14,7 +17,7 @@ pub struct Flags {
#[arg(long, default_value = "super_small_font.sf2")] #[arg(long, default_value = "super_small_font.sf2")]
pub sound_font: String, pub sound_font: String,
#[arg(short, long, default_value = "c 2e+")] #[arg(short, long, default_value = "c 2*e+")]
pub play: Vec<String>, pub play: Vec<String>,
} }

View File

@@ -1,57 +1,78 @@
use io_prompt_prototype::prompt;
use itertools::Itertools; use itertools::Itertools;
mod flags; mod flags;
mod play; mod parse;
mod player;
mod seq; mod seq;
mod syn; mod syn;
mod tone; mod tone;
fn main() { fn main() {
let flags = flags::Flags::new(); let mut flags = flags::Flags::new();
if flags.debug { if flags.debug {
eprintln!("{:?}", flags); eprintln!("{:?}", flags);
} }
if flags.interactive {
flags.play = vec![];
}
let once = flags.play.iter().filter(|x| x.len() > 0).count() > 0;
let mut player = player::new(flags.sample_rate.clone(), flags.bpm.clone());
loop {
play_with_flags(&flags, &mut player);
if once {
break;
}
}
}
fn play_with_flags(flags: &flags::Flags, player: &mut player::Player) {
let mut syn_seq = seq::new_syn(syn::Syn::new( let mut syn_seq = seq::new_syn(syn::Syn::new(
flags.debug, flags.debug.clone(),
flags.sound_font, flags.sound_font.clone(),
flags.sample_rate, flags.sample_rate.clone(),
)); ));
let mut i = 0; let mut i = 0;
for p in flags.play.iter() { for p in flags.play.iter() {
for p in play::new(p.clone()) { for p in parse::new(p.clone()) {
syn_seq.append(i as i32, p); syn_seq.append(i as i32, p);
i += 1; i += 1;
} }
} }
play(syn_seq, flags.sample_rate, flags.bpm); let sync = i > 0;
} if !sync {
let mut to_break = false;
fn play(mut s: seq::SynSeq, sample_rate: usize, bpm: usize) { let mut payload = vec![];
let samples_per_beat = sample_rate / bpm * 60; loop {
let params = tinyaudio::prelude::OutputDeviceParameters { let mut s: String = prompt!("> ").parse().expect("failed to readline");
channels_count: 2, s = s.split_whitespace().join(" ");
sample_rate: sample_rate, payload.push(s.clone());
channel_sample_count: samples_per_beat, match s.as_ref() {
}; "" => match to_break {
let beats = s.beats() + 3; false => {
let duration = 60 * beats / bpm; to_break = true;
}
let sample_count = (params.channel_sample_count) as usize; true => {
let mut left: Vec<f32> = vec![0_f32; sample_count]; break;
let mut right: Vec<f32> = vec![0_f32; sample_count]; }
},
let _device = tinyaudio::prelude::run_output_device(params, { _ => {
move |data| { to_break = false;
s.render(&mut left[..], &mut right[..]); // put in a state of rendering the next loop of these notes }
for (i, value) in left.iter().interleave(right.iter()).enumerate() { };
data[i] = *value;
}
} }
})
.unwrap();
// Wait it out for p in parse::new(payload.join("\n")) {
std::thread::sleep(std::time::Duration::from_secs(duration as u64)); syn_seq.append(i as i32, p);
i += 1;
}
}
match sync {
true => player.play(syn_seq),
false => player.play_async(syn_seq),
};
} }

View File

@@ -12,29 +12,56 @@ fn from_string(s: String) -> String {
.read_to_string(&mut content) .read_to_string(&mut content)
.expect(format!("failed to read {}", s).as_ref()); .expect(format!("failed to read {}", s).as_ref());
content content
.split("\n")
.map(|x| x.split_whitespace().collect::<Vec<_>>().join(" "))
.collect::<Vec<_>>()
.join("\n")
} }
Err(_) => s, Err(_) => s,
} }
} }
fn parse(s: String) -> Vec<String> { fn parse(s: String) -> Vec<String> {
let s = s
.split("\n")
.filter(|x: &&str| {
!x // doesnt start with #
.split_whitespace()
.collect::<Vec<_>>()
.join("")
.starts_with("#")
})
.map(|x| {
x.split("#")
.take(1) // drop after #
.collect::<Vec<_>>()
.join("")
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
})
.collect::<Vec<_>>()
.join("\n");
let mut channels = vec![]; let mut channels = vec![];
let lines = s.split("\n").collect::<Vec<_>>(); let lines = s.split("\n").collect::<Vec<_>>();
let mut j = 0; let mut j = 0;
for i in 0..lines.len() { for i in 0..lines.len() {
while channels.len() <= j {
channels.push("".to_string());
}
match lines[i] { match lines[i] {
"" => { j = 0; }, "" => {
_ => channels[{ let tmp = j; j += 1; tmp }] += &(" ".to_string() + lines[i]), j = 0;
}
_ => {
while channels.len() <= j {
channels.push("".to_string());
}
channels[{
let tmp = j;
j += 1;
tmp
}] += &(" ".to_string() + lines[i]);
}
}; };
} }
channels.iter().map(|x| x.split_whitespace().collect::<Vec<_>>().join(" ")).collect() channels
.iter()
.map(|x| x.split_whitespace().collect::<Vec<_>>().join(" "))
.collect()
} }
#[cfg(test)] #[cfg(test)]
@@ -57,7 +84,7 @@ mod test {
fn test_two_channels_one_bar() { fn test_two_channels_one_bar() {
assert_eq!( assert_eq!(
super::new("src/testdata/two_channels_one_bar.txt")[0], super::new("src/testdata/two_channels_one_bar.txt")[0],
"2a 2b 2c".to_string() "2*a 2*b 2*c".to_string()
); );
assert_eq!( assert_eq!(
super::new("src/testdata/two_channels_one_bar.txt")[1], super::new("src/testdata/two_channels_one_bar.txt")[1],
@@ -73,7 +100,20 @@ mod test {
); );
assert_eq!( assert_eq!(
super::new("src/testdata/two_channels_two_bars.txt")[1], super::new("src/testdata/two_channels_two_bars.txt")[1],
"2a 2b 2c 2d 2e 2f".to_string() "2*a 2*b 2*c 2*d 2*e 2*f".to_string()
); );
} }
#[test]
fn drop_comment_lines() {
assert_eq!(
super::new("# hello\n # world\na b c")[0],
"a b c".to_string()
);
}
#[test]
fn drop_comment_trailer() {
assert_eq!(super::new("a b c # hello world")[0], "a b c".to_string());
}
} }

61
src/player.rs Normal file
View File

@@ -0,0 +1,61 @@
use itertools::Itertools;
use crate::seq;
pub struct Player {
bpm: usize,
params: tinyaudio::OutputDeviceParameters,
device: Option<tinyaudio::OutputDevice>,
}
pub fn new(sample_rate: usize, bpm: usize) -> Player {
let samples_per_beat = sample_rate / bpm * 60;
Player {
bpm: bpm,
params: tinyaudio::prelude::OutputDeviceParameters {
channels_count: 2,
sample_rate: sample_rate,
channel_sample_count: samples_per_beat,
},
device: None,
}
}
impl Player {
pub fn play(&mut self, s: seq::SynSeq) {
self.play_with_sync(s, true);
}
pub fn play_async(&mut self, s: seq::SynSeq) {
self.play_with_sync(s, false);
}
fn play_with_sync(&mut self, mut s: seq::SynSeq, sync: bool) {
let sample_count = (self.params.channel_sample_count) as usize;
let mut left: Vec<f32> = vec![0_f32; sample_count];
let mut right: Vec<f32> = vec![0_f32; sample_count];
let beats = s.beats() + 3;
let duration = 60 * beats / self.bpm;
if self.device.is_some() {
self.device.as_mut().expect("lost device").close();
}
self.device = Some(
tinyaudio::prelude::run_output_device(self.params, {
move |data| {
s.render(&mut left[..], &mut right[..]); // put in a state of rendering the next loop of these notes
for (i, value) in left.iter().interleave(right.iter()).enumerate() {
data[i] = *value;
}
}
})
.unwrap(),
);
if sync {
// Wait it out
std::thread::sleep(std::time::Duration::from_secs(duration as u64));
}
}
}

View File

@@ -117,7 +117,7 @@ impl Seq {
} }
fn append_one(&mut self, s: String) { fn append_one(&mut self, s: String) {
let re = regex::Regex::new(r"^(?<count>[0-9]*)(?<tone>.*)$").unwrap(); let re = regex::Regex::new(r"^((?<count>[0-9]+)\*)?(?<tone>.*)$").unwrap();
let captures = re.captures(&s).unwrap(); let captures = re.captures(&s).unwrap();
let n = match captures.name("count") { let n = match captures.name("count") {
@@ -125,7 +125,8 @@ impl Seq {
_ => 1, _ => 1,
} as usize; } as usize;
let tone = tone::new(captures.name("tone").unwrap().as_str()); let tone_s = captures.name("tone").unwrap().as_str();
let tone = tone::new(tone_s);
self.beats.push((n, tone)); self.beats.push((n, tone));
} }
} }
@@ -139,9 +140,9 @@ mod test {
let mut seq = new(); let mut seq = new();
seq.append("c c"); seq.append("c c");
seq.append("4d"); seq.append("4*d");
seq.append("2-"); seq.append("2*-");
seq.append("g 2e"); seq.append("g 2*e");
assert_eq!(seq.beats.len(), 6); assert_eq!(seq.beats.len(), 6);
assert_eq!(seq.len(), 11); assert_eq!(seq.len(), 11);

View File

@@ -74,10 +74,20 @@ impl Syn {
match self { match self {
Syn::Real(syn) => syn.render(a, b), Syn::Real(syn) => syn.render(a, b),
Syn::Text { m, i } => { Syn::Text { m, i } => {
eprintln!("{} | render[{}]({:?})", chrono::prelude::Utc::now(), i, m eprintln!(
.iter() "{} | render[{}]({:?})",
.map(|tuple| (tuple.0, tuple.1.iter().map(|v| tone::new(v.0.to_string()).string()).collect::<Vec<_>>())) chrono::prelude::Utc::now(),
.collect::<Vec<_>>(), i,
m.iter()
.map(|tuple| (
tuple.0,
tuple
.1
.iter()
.map(|v| tone::new(v.0.to_string()).string())
.collect::<Vec<_>>()
))
.collect::<Vec<_>>(),
); );
*i += 1; *i += 1;
} }

View File

@@ -0,0 +1,9 @@
# https://www.musicnotes.com/sheetmusic/chrissy-ricker/battle-against-a-true-hero-easy/MN0235808
# c major
CM4 CM5 CM5 CM1 CM1 CM2 . .
CM3 CM0 CM0 CM4 CM4 . . .
CM4 CM5 CM5 CM1 CM1 CM2 . .

12
src/testdata/chord_progressions.txt vendored Normal file
View File

@@ -0,0 +1,12 @@
# x+0 x+5 x+7 x+0
CM0 CM3 CM4 CM0
.
# x+2 x+7 x+0
CM1 CM4 CM0
.
# x+0 x+7 x+9 x+5
CM0 CM4 CM5 CM3

5
src/testdata/fifth_wheel.txt vendored Normal file
View File

@@ -0,0 +1,5 @@
# fifth wheel = +7 semitones
# f -> c -> g -> d -> a -> e -> b
f c g d a e b
ff cf gf df af ef bf

View File

@@ -0,0 +1,19 @@
CM0 CM3 CM4 CM0
CM0T CM3T CM4T CM0T
CM0f CM3f CM4f CM0f
.
.
.
CM1 CM4 CM0
CM1T CM4T CM0T
CM1f CM4f CM0f
.
.
.
CM0 CM4 CM5 CM3
CM0T CM4T CM5T CM3T
CM0f CM4f CM5f CM3f

27
src/testdata/major_chords.txt vendored Normal file
View File

@@ -0,0 +1,27 @@
# major CHORD = root + major_third + perfect_fifth
# c = c,e,g
f
a
c
c
e
g
g
b
d
d
f+
a
a
c+
e
e
g+
b

18
src/testdata/major_third.txt vendored Normal file
View File

@@ -0,0 +1,18 @@
# major third
# +2 letters (the third letter) with exactly 2 sharps between
# c,e c+,f d,f+
c c+ d
cT c+T dT
# d+,g e,g+ f,a
d+ e f
d+T eT fT
# f+,a+ g,b g+,c
f+ g g+
f+T gT g+T
# a,c+ a+,d b,d+
a a+ b
aT a+T bT

27
src/testdata/minor_chords.txt vendored Normal file
View File

@@ -0,0 +1,27 @@
# minor CHORD = root + minor_third + perfect_fifth
# c = c,e-,g
f
g+
c
c
e-
g
g
a+
d
d
f
a
a
c
e
e
g
b

18
src/testdata/minor_third.txt vendored Normal file
View File

@@ -0,0 +1,18 @@
# minor third
# +2 letters (the third letter) with exactly 1 half step between
# c,e- c+,e d,f
c c+ d
ct c+t dt
# d+,f+ e,g f,g+
d+ e f
d+t et ft
# f+,a g,a+ g+,b
f+ g g+
f+t gt g+t
# a,c a+,c+ b,d
a a+ b
at a+t bt

12
src/testdata/plus_three_sounds_nice.txt vendored Normal file
View File

@@ -0,0 +1,12 @@
#CM0 CM3 CM4 CM0
#CM1 CM4 CM0
#CM0 CM4 CM5 CM3
# 1 4 6 4 # pop101
#GM0 GM3 GM5 GM3
60
63
66
69
72

12
src/testdata/sandbox.txt vendored Normal file
View File

@@ -0,0 +1,12 @@
#CM0 CM3 CM4 CM0
#CM1 CM4 CM0
#CM0 CM4 CM5 CM3
# 1 4 6 4 # pop101
#GM0 GM3 GM5 GM3
60
63
66
69
72

View File

@@ -1,2 +1,2 @@
2a 2b 2c 2*a 2*b 2*c
. a5 . b5 . c5 . a5 . b5 . c5

View File

@@ -1,5 +1,5 @@
a b c a b c
2a 2b 2c 2*a 2*b 2*c
d e f d e f
2d 2e 2f 2*d 2*e 2*f

View File

@@ -8,7 +8,7 @@ pub fn new<S: ToString>(s: S) -> Tone {
impl Tone { impl Tone {
fn new(s: String) -> Tone { fn new(s: String) -> Tone {
let re = regex::Regex::new(r"^(((?<letter>^[a-g])(?<sharpness>[+-]?)|(?<major>[A-G]M[0-6])|(?<minor>[A-G]m[0-6]))(?<octave>[1-5]?)|(?<numeric>[0-9]+)|(?<rest>[^a-gA-G0-9]))$").unwrap(); let re = regex::Regex::new(r"^(((?<letter>^[a-g])(?<sharpness>[+-]?)|(?<major>[A-G]M[0-6])|(?<minor>[A-G]m[0-6]))(?<octave>[1-5]?)((?<major_third>T)|(?<minor_third>t)|(?<fifth>f))?|(?<numeric>[0-9]+)|(?<rest>[^a-gA-G0-9]))$").unwrap();
let captures = re let captures = re
.captures(&s) .captures(&s)
.expect(format!("tone '{}' does not match regex", s).as_ref()); .expect(format!("tone '{}' does not match regex", s).as_ref());
@@ -20,27 +20,31 @@ impl Tone {
let mut result = match captures.name("letter") { let mut result = match captures.name("letter") {
Some(letter) => Tone::char_to_middle_i32(letter.as_str()), Some(letter) => Tone::char_to_middle_i32(letter.as_str()),
None => match captures.name("major") { None => match captures.name("major") {
Some(major) => Tone::char_to_middle_i32(&major.as_str()[..1]) + match &major.as_str()[2..] { Some(major) => {
"0" => 0, Tone::char_to_middle_i32(&major.as_str()[..1])
"1" => 2, + match &major.as_str()[2..] {
"2" => 4, "0" => 0,
"3" => 5, "1" => 2,
"4" => 7, "2" => 4,
"5" => 9, "3" => 5,
_ => 11, "4" => 7,
}, "5" => 9,
_ => 11,
}
}
None => { None => {
let minor = captures.name("minor").unwrap(); let minor = captures.name("minor").unwrap();
Tone::char_to_middle_i32(&minor.as_str()[..1]) + match &minor.as_str()[2..] { Tone::char_to_middle_i32(&minor.as_str()[..1])
"0" => 0, + match &minor.as_str()[2..] {
"1" => 2, "0" => 0,
"2" => 3, "1" => 2,
"3" => 5, "2" => 3,
"4" => 7, "3" => 5,
"5" => 8, "4" => 7,
_ => 10, "5" => 8,
} _ => 10,
}, }
}
}, },
} as i32; } as i32;
@@ -61,6 +65,21 @@ impl Tone {
None => 0, None => 0,
} as i32; } as i32;
result += match captures.name("major_third") {
Some(_) => 4, // TODO not all are good
None => 0,
} as i32;
result += match captures.name("minor_third") {
Some(_) => 3, // TODO not all are good
None => 0,
} as i32;
result += match captures.name("fifth") {
Some(_) => 7,
None => 0,
} as i32;
result result
} }
}, },
@@ -84,21 +103,31 @@ impl Tone {
} }
pub fn string(&self) -> String { pub fn string(&self) -> String {
match self.i32() { let v = self.i32();
57|69 => "a", let modifier = if v > 0 && v < 57 {
58|70 => "a+", "-"
59|71 => "b", } else if v >= 69 {
60|72 => "c", "+"
61|73 => "c+", } else {
62|74 => "d", ""
63|75 => "d+", };
64|76 => "e", modifier.to_string()
65|77 => "f", + match v {
66|78 => "f+", 45 | 57 | 69 => "a",
67|79 => "g", 46 | 58 | 70 => "a+",
68|80 => "g+", 47 | 59 | 71 => "b",
_ => "?", 48 | 60 | 72 => "c",
}.to_string() 49 | 61 | 73 => "c+",
50 | 62 | 74 => "d",
51 | 63 | 75 => "d+",
52 | 64 | 76 => "e",
53 | 65 | 77 => "f",
54 | 66 | 78 => "f+",
55 | 67 | 79 => "g",
56 | 68 | 80 => "g+",
0 => " ",
_ => "?",
}
} }
} }
@@ -130,6 +159,42 @@ mod test {
assert_eq!(super::new("c+4").i32(), 60 + 12 + 1); assert_eq!(super::new("c+4").i32(), 60 + 12 + 1);
} }
#[test]
fn test_tone_new_major_third() {
assert_eq!(super::new("cT").i32(), 60 + 4);
assert_eq!(super::new("c1T").i32(), 60 + 4 - 24);
assert_eq!(super::new("c+T").i32(), 60 + 1 + 4);
assert_eq!(super::new("c+1T").i32(), 60 + 1 + 4 - 24);
assert_eq!(super::new("CM0T").i32(), 60 + 4);
assert_eq!(super::new("CM01T").i32(), 60 + 4 - 24);
}
#[test]
fn test_tone_new_minor_third() {
assert_eq!(super::new("ct").i32(), 60 + 3);
assert_eq!(super::new("c1t").i32(), 60 + 3 - 24);
assert_eq!(super::new("c+t").i32(), 60 + 1 + 3);
assert_eq!(super::new("c+1t").i32(), 60 + 1 + 3 - 24);
assert_eq!(super::new("CM0t").i32(), 60 + 3);
assert_eq!(super::new("CM01t").i32(), 60 + 3 - 24);
}
#[test]
fn test_tone_new_fifth() {
assert_eq!(super::new("cf").i32(), 60 + 7);
assert_eq!(super::new("c1f").i32(), 60 + 7 - 24);
assert_eq!(super::new("c+f").i32(), 60 + 1 + 7);
assert_eq!(super::new("c+1f").i32(), 60 + 1 + 7 - 24);
assert_eq!(super::new("CM0f").i32(), 60 + 7);
assert_eq!(super::new("CM01f").i32(), 60 + 7 - 24);
}
#[test] #[test]
fn test_tone_c_major() { fn test_tone_c_major() {
assert_eq!(super::new("CM0"), super::new("c")); assert_eq!(super::new("CM0"), super::new("c"));