1use std::path::{Path, PathBuf};
4
5use sva_ast::SpanUnit;
6use sva_ast::score::{Field, Kind, Reading as Folding, Refused, evaluate};
7use sva_engine::harmony::voice_leading::Norm;
8use sva_engine::{
9 Arg, DEFAULT_BUFFER_SECS, DEFAULT_FRAME_SECS, Given, Harmonic, MAX_PINNED_FRAME, READINGS,
10 Reading, Representation, pinned_frame,
11};
12
13use crate::cli_error::CliError;
14
15pub const RETIRED: [(&str, &str); 2] = [
16 ("exact-envelope", "envelope, symbolic on a closed form"),
17 ("exact-derivative", "derivative, symbolic on a closed form"),
18];
19
20#[derive(Clone, Debug, PartialEq)]
23pub struct Call {
24 pub name: String,
25 pub args: Vec<(String, String)>,
26 pub dest: Option<PathBuf>,
28}
29
30#[derive(Clone, Debug, PartialEq)]
33pub enum Destination {
34 File(PathBuf),
35 Alsa {
36 device: String,
38 buffer_secs: f64,
40 },
41}
42
43const MOST_SAMPLES: f64 = 9_007_199_254_740_992.0;
46
47#[derive(Clone, Debug, PartialEq)]
50pub struct Asked {
51 pub name: String,
52 given: Given,
53 times: Vec<(Arg, Time)>,
54 pub dest: Option<Destination>,
55 pub node: Option<String>,
57 pub brief: bool,
59 pub skim: bool,
61}
62
63pub fn is_wav(path: &Path) -> bool {
64 path.extension()
65 .is_some_and(|e| e.eq_ignore_ascii_case("wav"))
66}
67
68pub fn retired(name: &str) -> Option<&'static str> {
69 RETIRED
70 .iter()
71 .find(|(gone, _)| *gone == name)
72 .map(|(_, write)| *write)
73}
74
75pub fn calls(text: &str) -> Result<Vec<Call>, CliError> {
78 let mut joined: Vec<String> = Vec::new();
79 for one in split_outside(text, ',')? {
80 match joined.last_mut() {
81 Some(last) if names_a_device(last) && !names_a_reading(one) => {
82 last.push(',');
83 last.push_str(one);
84 }
85 _ => joined.push(one.to_string()),
86 }
87 }
88 joined.iter().map(|one| call(one.trim())).collect()
89}
90
91fn names_a_device(call: &str) -> bool {
92 let close = call.rfind(')').map_or(0, |at| at + 1);
93 call[close..]
94 .split_once('=')
95 .is_some_and(|(_, dest)| dest.trim_start().starts_with("alsa:"))
96}
97
98fn names_a_reading(text: &str) -> bool {
99 let head = text[..text.find(['(', '=']).unwrap_or(text.len())].trim();
100 READINGS.iter().any(|row| row.name == head) || retired(head).is_some()
101}
102
103pub fn call(text: &str) -> Result<Call, CliError> {
105 let head_end = text.find(['(', '=']).unwrap_or(text.len());
106 let name = text[..head_end].trim().to_string();
107 if name.is_empty() {
108 return Err(unwritten(text, "it names no reading"));
109 }
110 let mut rest = &text[head_end..];
111 let mut args = Vec::new();
112 if rest.starts_with('(') {
113 let close = closing(rest).ok_or_else(|| unwritten(text, "its `(` is never closed"))?;
114 let inner = rest[1..close].trim();
115 if !inner.is_empty() {
116 for arg in split_outside(inner, ',')? {
117 let Some((key, value)) = arg.split_once('=') else {
118 return Err(unwritten(
119 text,
120 &format!("`{}` is no named argument; write `key=value`", arg.trim()),
121 ));
122 };
123 args.push((key.trim().to_string(), value.trim().to_string()));
124 }
125 }
126 rest = &rest[close + 1..];
127 }
128 let dest = match rest.trim_start().strip_prefix('=') {
129 Some("") => {
130 return Err(unwritten(
131 text,
132 "`=` names no destination; drop it to read the reading under \
133 `data.representations`",
134 ));
135 }
136 Some(path) => Some(PathBuf::from(path)),
137 None if rest.trim().is_empty() => None,
138 None => {
139 return Err(unwritten(
140 text,
141 &format!("`{}` follows the call", rest.trim()),
142 ));
143 }
144 };
145 Ok(Call { name, args, dest })
146}
147
148pub fn asked_all(calls: &[Call]) -> Result<Vec<Asked>, CliError> {
151 let mut out: Vec<Asked> = Vec::with_capacity(calls.len());
152 for call in calls {
153 let one = asked(call)?;
154 if out.iter().any(|held| held.name == one.name) {
155 return Err(CliError::usage(
156 "query.duplicate",
157 format!(
158 "`{}` is asked more than once; ask each reading once, every argument in \
159 its one call",
160 one.name
161 ),
162 ));
163 }
164 out.push(one);
165 }
166 Ok(out)
167}
168
169#[derive(Clone, Debug, PartialEq)]
171struct Time {
172 amount: f64,
173 unit: SpanUnit,
174 written: String,
175}
176
177impl Asked {
178 fn reading(&self) -> &'static Reading {
179 READINGS
180 .iter()
181 .find(|row| row.name == self.name)
182 .expect("an asked reading names a row")
183 }
184
185 pub fn off_samples(&self, sampled: bool) -> bool {
187 self.reading().reads.off_samples(sampled)
188 }
189
190 pub fn representation(
193 &self,
194 rate: u32,
195 seconds_per_bar: Option<f64>,
196 ) -> Result<Representation, CliError> {
197 let given = self.resolved(rate, seconds_per_bar)?;
198 let representation = self.reading().representation(&given);
199 pinned(representation, rate)?;
200 Ok(representation)
201 }
202
203 pub fn args(
208 &self,
209 rate: u32,
210 seconds_per_bar: Option<f64>,
211 taken: Taken,
212 ) -> Result<Vec<(&'static str, Option<Spelled>)>, CliError> {
213 use Representation as R;
214 let count = |n: usize| Some(Spelled::Number(n.to_string()));
215 let secs = |s: f64| Some(Spelled::Text(spelled_secs(s)));
216 let db = |d: f64| Some(Spelled::Text(format!("{d}db")));
217 let switch = |on: bool| Some(Spelled::Number(u8::from(on).to_string()));
218 let text = |t: &str| Some(Spelled::Text(t.to_string()));
219 let frame = |written: Option<f64>, unwritten: Option<f64>| match taken {
220 Taken::Exact => written.and_then(secs),
221 Taken::Measured { .. } => written.or(unwritten).and_then(secs),
222 };
223 let mut held = match self.representation(rate, seconds_per_bar)? {
224 R::Spectrum {
225 max_peaks,
226 frame_secs,
227 } => {
228 let fitted = match taken {
229 Taken::Measured { fitted_frame } => fitted_frame,
230 Taken::Exact => None,
231 };
232 let fitted = fitted.map(|samples| samples as f64 / f64::from(rate));
233 vec![
234 (Arg::Peaks, count(max_peaks)),
235 (Arg::Frame, frame(frame_secs, fitted)),
236 ]
237 }
238 R::Envelope { frame_secs } => {
239 vec![(Arg::Frame, frame(frame_secs, Some(DEFAULT_FRAME_SECS)))]
240 }
241 R::Ledger { depth } => vec![(Arg::Depth, count(depth))],
242 R::Pitch {
243 max_notes: peaks,
244 frame_secs,
245 }
246 | R::Formants {
247 max_formants: peaks,
248 frame_secs,
249 } => vec![(Arg::Peaks, count(peaks)), (Arg::Frame, secs(frame_secs))],
250 R::Stereo { frame_secs } => vec![(Arg::Frame, secs(frame_secs))],
251 R::Loudness { window_secs } => vec![(Arg::Window, secs(window_secs))],
252 R::Bands => vec![],
253 R::Alias { oversample } => vec![(Arg::Oversample, count(oversample as usize))],
254 R::Harmony {
255 reading,
256 frame_secs,
257 floor_db,
258 } => {
259 let own = match reading {
260 Harmonic::Dissonance { max_pairs } => Some((Arg::Pairs, count(max_pairs))),
261 Harmonic::VoiceLeading { norm } => Some((Arg::Norm, text(norm.key()))),
262 Harmonic::TonalDistance | Harmonic::Inharmonicity => None,
263 };
264 let shared = [(Arg::Frame, secs(frame_secs)), (Arg::Floor, db(floor_db))];
265 shared.into_iter().chain(own).collect()
266 }
267 R::Periodicity {
268 frame_secs,
269 window_secs,
270 curve,
271 } => vec![
272 (Arg::Frame, secs(frame_secs)),
273 (Arg::Window, secs(window_secs)),
274 (Arg::Curve, switch(curve)),
275 ],
276 R::Modulation {
277 frame_secs,
278 window_secs,
279 bpm,
280 } => vec![
281 (Arg::Frame, secs(frame_secs)),
282 (Arg::Window, secs(window_secs)),
283 (Arg::Bpm, bpm.map(|b| Spelled::Number(b.to_string()))),
284 ],
285 R::SelfSimilarity {
286 frame_secs,
287 cell_secs,
288 smooth_secs,
289 window_secs,
290 floor_db,
291 listed,
292 curve,
293 } => vec![
294 (Arg::Frame, secs(frame_secs)),
295 (Arg::Cell, secs(cell_secs)),
296 (Arg::Smooth, secs(smooth_secs)),
297 (Arg::Window, secs(window_secs)),
298 (Arg::Floor, db(floor_db)),
299 (Arg::Peaks, count(listed)),
300 (Arg::Curve, switch(curve)),
301 ],
302 R::Lines
303 | R::Atoms
304 | R::Derivative
305 | R::Samples
306 | R::Crest
307 | R::Onsets
308 | R::Bindings
309 | R::Arguments => Vec::new(),
310 };
311 let buffer = match &self.dest {
312 Some(Destination::Alsa { buffer_secs, .. }) => secs(*buffer_secs),
313 _ => None,
314 };
315 held.extend([
316 (Arg::Brief, switch(self.brief)),
317 (Arg::Skim, switch(self.skim)),
318 (
319 Arg::Node,
320 self.node.as_ref().and_then(|n| text(&format!("@{n}"))),
321 ),
322 (Arg::Buffer, buffer),
323 ]);
324 Ok(self
325 .reading()
326 .takes
327 .iter()
328 .map(|arg| {
329 let (_, value) = held
330 .iter()
331 .find(|(one, _)| one == arg)
332 .expect("a reading holds every argument it takes");
333 (arg.key(), value.clone())
334 })
335 .collect())
336 }
337
338 fn resolved(&self, rate: u32, seconds_per_bar: Option<f64>) -> Result<Given, CliError> {
340 let mut given = self.given;
341 for (arg, time) in &self.times {
342 let secs = match (time.unit, seconds_per_bar) {
343 (SpanUnit::Seconds, _) => time.amount,
344 (SpanUnit::Bars, Some(per)) => time.amount * per,
345 (SpanUnit::Bars, None) => {
346 return Err(CliError::BadTempo(format!(
347 "`{}({}={})` is written in bars, and this reading has no tempo to \
348 count them in: a render reads it off `variables/bpm` and \
349 `variables/meter`, and a file holds none; write seconds",
350 self.name,
351 arg.key(),
352 time.written
353 )));
354 }
355 };
356 if *arg == Arg::Frame && (secs * f64::from(rate)).round() < 1.0 {
357 return Err(CliError::usage(
358 "query.bad_value",
359 format!(
360 "`{}(frame={})` is {secs}s, under half a sample at {rate} Hz, and a \
361 frame steps by whole samples, rounded; ask at least {}s, half a sample",
362 self.name,
363 time.written,
364 0.5 / f64::from(rate)
365 ),
366 ));
367 }
368 let most = MOST_SAMPLES / f64::from(rate);
369 if secs > most {
370 return Err(CliError::usage(
371 "query.bad_value",
372 format!(
373 "`{}({}={})` is {secs}s, past the 2^53 samples a count holds exactly at \
374 {rate} Hz; ask at most {most}s",
375 self.name,
376 arg.key(),
377 time.written
378 ),
379 ));
380 }
381 match arg {
382 Arg::Frame => given.frame = Some(secs),
383 Arg::Window => given.window = Some(secs),
384 Arg::Cell => given.cell_secs = secs,
385 Arg::Smooth => given.smooth_secs = secs,
386 _ => unreachable!("only a time argument is held as a time"),
387 }
388 }
389 Ok(given)
390 }
391
392 pub fn path(&self) -> Option<&Path> {
393 match &self.dest {
394 Some(Destination::File(path)) => Some(path),
395 Some(Destination::Alsa { .. }) | None => None,
396 }
397 }
398}
399
400pub fn asked(call: &Call) -> Result<Asked, CliError> {
402 let name = call.name.as_str();
403 if let Some(write) = retired(name) {
404 return Err(CliError::usage(
405 "query.retired",
406 format!("`{name}` left the language; write `{write}`"),
407 ));
408 }
409 let Some(row) = READINGS.iter().find(|row| row.name == name) else {
410 let names: Vec<&str> = READINGS.iter().map(|row| row.name).collect();
411 return Err(CliError::usage(
412 "query.unknown_representation",
413 format!(
414 "unknown representation `{name}`; the representations are {}",
415 names.join(", ")
416 ),
417 ));
418 };
419 let (mut given, mut node, mut brief, mut skim) = (Given::default(), None, false, false);
420 let (mut buffer, mut times) = (None, Vec::new());
421 for (key, raw) in &call.args {
422 let Some(arg) = row.takes.iter().find(|arg| arg.key() == key) else {
423 let keys: Vec<&str> = row.takes.iter().map(|arg| arg.key()).collect();
424 return Err(CliError::usage(
425 "query.unknown_argument",
426 match keys[..] {
427 [] => format!("`{name}` takes no arguments, not `{key}`"),
428 _ => format!("`{name}` takes {}, not `{key}`", keys.join(", ")),
429 },
430 ));
431 };
432 match arg {
433 Arg::Peaks => given.peaks = count(raw, key)?,
434 Arg::Depth => given.depth = count(raw, key)?,
435 Arg::Frame | Arg::Window | Arg::Cell | Arg::Smooth => {
436 times.push((*arg, time(raw, key)?));
437 }
438 Arg::Oversample => given.oversample = factor(raw)?,
439 Arg::Brief => brief = switch(raw, key)?,
440 Arg::Skim => skim = switch(raw, key)?,
441 Arg::Node => node = Some(self::node(raw)?),
442 Arg::Buffer => buffer = Some(microseconds(raw, key)?),
443 Arg::Floor => given.floor_db = decibels(raw, key)?,
444 Arg::Norm => given.norm = norm(raw)?,
445 Arg::Pairs => given.max_pairs = count(raw, key)?,
446 Arg::Curve => given.curve = switch(raw, key)?,
447 Arg::Bpm => given.bpm = Some(tempo(raw, key)?),
448 }
449 }
450 if row.takes.contains(&Arg::Node) && node.is_none() {
451 return Err(CliError::usage(
452 "query.missing_argument",
453 format!("`{name}` reads one instance's {name}; name it, as `{name}(node=@voice)`"),
454 ));
455 }
456 Ok(Asked {
457 name: call.name.clone(),
458 given,
459 times,
460 dest: destination(name, call.dest.as_deref(), buffer)?,
461 node,
462 brief,
463 skim,
464 })
465}
466
467fn destination(
469 name: &str,
470 dest: Option<&Path>,
471 buffer: Option<f64>,
472) -> Result<Option<Destination>, CliError> {
473 let device = dest.and_then(|d| d.to_str()?.strip_prefix("alsa:"));
474 match (dest, device, buffer) {
475 (_, Some(""), _) => Err(CliError::usage(
476 "destination.no_device",
477 format!(
478 "`{name}=alsa:` names no device; write an ALSA device after it, as \
479 `alsa:default` or `alsa:hw:1`"
480 ),
481 )),
482 (_, Some(device), _) => Ok(Some(Destination::Alsa {
483 device: device.to_string(),
484 buffer_secs: buffer.unwrap_or(DEFAULT_BUFFER_SECS),
485 })),
486 (_, None, Some(_)) => Err(CliError::usage(
487 "query.buffer_without_device",
488 format!(
489 "`buffer` sizes a live device's buffer, and `{name}` names none; write \
490 `{name}(buffer=...)=alsa:<device>`, or drop `buffer`"
491 ),
492 )),
493 (dest, None, None) => Ok(dest.map(|d| Destination::File(d.to_path_buf()))),
494 }
495}
496
497fn split_outside(raw: &str, sep: char) -> Result<Vec<&str>, CliError> {
499 let (mut depth, mut from, mut out) = (0i32, 0, Vec::new());
500 for (at, c) in raw.char_indices() {
501 match c {
502 '(' => depth += 1,
503 ')' => depth -= 1,
504 c if c == sep && depth == 0 => {
505 out.push(&raw[from..at]);
506 from = at + c.len_utf8();
507 }
508 _ => {}
509 }
510 if depth < 0 {
511 return Err(unwritten(raw, "a `)` closes nothing"));
512 }
513 }
514 out.push(&raw[from..]);
515 Ok(out)
516}
517
518fn closing(text: &str) -> Option<usize> {
520 let mut depth = 0i32;
521 for (at, c) in text.char_indices() {
522 match c {
523 '(' => depth += 1,
524 ')' => {
525 depth -= 1;
526 if depth == 0 {
527 return Some(at);
528 }
529 }
530 _ => {}
531 }
532 }
533 None
534}
535
536fn unwritten(text: &str, why: &str) -> CliError {
537 CliError::usage(
538 "query.malformed",
539 format!(
540 "`{text}` is no reading: {why}. write a call, as `spectrum(peaks=8, frame=50ms)`, \
541 `=path` after it to write it to a file"
542 ),
543 )
544}
545
546fn count(raw: &str, key: &str) -> Result<usize, CliError> {
547 raw.parse::<usize>().map_err(|_| {
548 CliError::usage(
549 "query.bad_value",
550 format!("`{key}` needs a whole count, got `{raw}`"),
551 )
552 })
553}
554
555fn factor(raw: &str) -> Result<u32, CliError> {
556 match raw.parse::<u32>() {
557 Ok(k) if (2..=16).contains(&k) && k.is_power_of_two() => Ok(k),
558 _ => Err(CliError::usage(
559 "query.bad_value",
560 format!("`oversample` needs a power of two from 2 to 16, got `{raw}`"),
561 )),
562 }
563}
564
565fn time(raw: &str, key: &str) -> Result<Time, CliError> {
568 let bad = |why: String| {
569 CliError::usage(
570 "query.bad_value",
571 format!(
572 "`{key}` needs a positive time, in seconds as `50ms` or `0.05`, or in bars as \
573 `1b/8`: {why}"
574 ),
575 )
576 };
577 let folding = Folding::<f64> {
578 field: Field::Time,
579 mark: &|_| None,
580 degree: &|_| Err("a reading's time counts no degrees".to_string()),
581 own: None,
582 };
583 let value = evaluate(raw, &folding).map_err(|refused| match refused {
584 Refused::At(_, why) => bad(why),
585 Refused::Mark(name, _) => bad(format!(
586 "`mark({name})` is a score's, and a reading has none"
587 )),
588 })?;
589 let unit = match value.kind {
590 Kind::Bars => SpanUnit::Bars,
591 Kind::Seconds | Kind::Number => SpanUnit::Seconds,
592 other => return Err(bad(format!("`{raw}` is a {}", other.name()))),
593 };
594 match value.amount > 0.0 && value.amount.is_finite() {
595 true => Ok(Time {
596 amount: value.amount,
597 unit,
598 written: raw.to_string(),
599 }),
600 false => Err(bad(format!("`{raw}` is not over zero"))),
601 }
602}
603
604#[derive(Clone, Copy, Debug, PartialEq)]
606pub enum Taken {
607 Exact,
609 Measured { fitted_frame: Option<usize> },
611}
612
613#[derive(Clone, Debug, PartialEq)]
615pub enum Spelled {
616 Number(String),
617 Text(String),
618}
619
620impl Spelled {
621 pub fn text(&self) -> &str {
622 match self {
623 Spelled::Number(t) | Spelled::Text(t) => t,
624 }
625 }
626}
627
628fn spelled_secs(secs: f64) -> String {
631 let ms = secs * 1000.0;
632 match secs < 1.0 && ms / 1000.0 == secs {
633 true => format!("{ms}ms"),
634 false => format!("{secs}s"),
635 }
636}
637
638fn pinned(representation: Representation, rate: u32) -> Result<(), CliError> {
640 let Representation::Spectrum {
641 frame_secs: Some(secs),
642 ..
643 } = representation
644 else {
645 return Ok(());
646 };
647 let sr = f64::from(rate);
648 let frame = pinned_frame(secs, sr);
649 match frame > MAX_PINNED_FRAME {
650 true => Err(CliError::usage(
651 "query.bad_value",
652 format!(
653 "`spectrum(frame={secs})` sizes its transform to {frame} samples at {sr} Hz, \
654 past the {MAX_PINNED_FRAME}-sample bound"
655 ),
656 )),
657 false => Ok(()),
658 }
659}
660
661pub fn seconds(raw: &str, key: &str) -> Result<f64, CliError> {
663 let held = match sva_ast::tokenize(raw).as_deref() {
664 Ok([one]) => match one.kind {
665 sva_ast::TokenKind::Num(v)
666 | sva_ast::TokenKind::Time(v, sva_ast::SpanUnit::Seconds) => Some(v),
667 _ => None,
668 },
669 _ => None,
670 };
671 match held {
672 Some(v) if v > 0.0 && v.is_finite() => Ok(v),
673 _ => Err(CliError::usage(
674 "query.bad_value",
675 format!("`{key}` needs a positive time, as `50ms` or `0.05`, got `{raw}`"),
676 )),
677 }
678}
679
680fn tempo(raw: &str, key: &str) -> Result<f64, CliError> {
682 let held = match sva_ast::tokenize(raw).as_deref() {
683 Ok([one]) => match one.kind {
684 sva_ast::TokenKind::Num(v) => Some(v),
685 _ => None,
686 },
687 _ => None,
688 };
689 match held {
690 Some(v) if v > 0.0 && v.is_finite() => Ok(v),
691 _ => Err(CliError::usage(
692 "query.bad_value",
693 format!("`{key}` needs a positive tempo in beats per minute, as `140`, got `{raw}`"),
694 )),
695 }
696}
697
698fn microseconds(raw: &str, key: &str) -> Result<f64, CliError> {
700 let secs = seconds(raw, key)?;
701 match (1.0..=f64::from(i32::MAX)).contains(&(secs * 1e6).round()) {
702 true => Ok(secs),
703 false => Err(CliError::usage(
704 "query.bad_value",
705 format!(
706 "`{key}` is a whole number of microseconds from 1us to {}s, got `{raw}`",
707 i32::MAX / 1_000_000
708 ),
709 )),
710 }
711}
712
713fn decibels(raw: &str, key: &str) -> Result<f64, CliError> {
715 use sva_ast::{LogUnit::Decibels, TokenKind};
716 let kinds: Option<Vec<TokenKind>> = sva_ast::tokenize(raw)
717 .ok()
718 .map(|tokens| tokens.into_iter().map(|t| t.kind).collect());
719 let held = match kinds.as_deref() {
720 Some([TokenKind::Log(v, Decibels)]) => Some(*v),
721 Some([TokenKind::Minus, TokenKind::Log(v, Decibels)]) => Some(-v),
722 _ => None,
723 };
724 match held {
725 Some(v) if v.is_finite() => Ok(v),
726 _ => Err(CliError::usage(
727 "query.bad_value",
728 format!("`{key}` needs a level in decibels, as `-40db`, got `{raw}`"),
729 )),
730 }
731}
732
733fn norm(raw: &str) -> Result<Norm, CliError> {
734 [Norm::L1, Norm::L2]
735 .into_iter()
736 .find(|n| n.key() == raw)
737 .ok_or_else(|| {
738 CliError::usage(
739 "query.bad_value",
740 format!("`norm` is `l1` or `l2`, got `{raw}`"),
741 )
742 })
743}
744
745fn switch(raw: &str, key: &str) -> Result<bool, CliError> {
746 match raw {
747 "1" => Ok(true),
748 "0" => Ok(false),
749 _ => Err(CliError::usage(
750 "query.bad_value",
751 format!("`{key}` is `1` or `0`, got `{raw}`"),
752 )),
753 }
754}
755
756fn node(raw: &str) -> Result<String, CliError> {
758 match raw.strip_prefix('@') {
759 Some(path) if !path.is_empty() => Ok(path.to_string()),
760 _ => Err(CliError::usage(
761 "query.bad_value",
762 format!("`node` names an instance as a ref, as `@voice`, not `{raw}`"),
763 )),
764 }
765}