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, Given, MAX_PINNED_FRAME, READINGS, Reading, Representation,
10 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 mut given = self.given;
198 for (arg, time) in &self.times {
199 let secs = match (time.unit, seconds_per_bar) {
200 (SpanUnit::Seconds, _) => time.amount,
201 (SpanUnit::Bars, Some(per)) => time.amount * per,
202 (SpanUnit::Bars, None) => {
203 return Err(CliError::BadTempo(format!(
204 "`{}({}={})` is written in bars, and this reading has no tempo to \
205 count them in: a render reads it off `variables/bpm` and \
206 `variables/meter`, and a file holds none; write seconds",
207 self.name,
208 arg.key(),
209 time.written
210 )));
211 }
212 };
213 if *arg == Arg::Frame && (secs * f64::from(rate)).round() < 1.0 {
214 return Err(CliError::usage(
215 "query.bad_value",
216 format!(
217 "`{}(frame={})` is {secs}s, under half a sample at {rate} Hz, and a \
218 frame steps by whole samples, rounded; ask at least {}s, half a sample",
219 self.name,
220 time.written,
221 0.5 / f64::from(rate)
222 ),
223 ));
224 }
225 let most = MOST_SAMPLES / f64::from(rate);
226 if secs > most {
227 return Err(CliError::usage(
228 "query.bad_value",
229 format!(
230 "`{}({}={})` is {secs}s, past the 2^53 samples a count holds exactly at \
231 {rate} Hz; ask at most {most}s",
232 self.name,
233 arg.key(),
234 time.written
235 ),
236 ));
237 }
238 match arg {
239 Arg::Frame => given.frame = Some(secs),
240 Arg::Window => given.window = Some(secs),
241 Arg::Cell => given.cell_secs = secs,
242 Arg::Smooth => given.smooth_secs = secs,
243 _ => unreachable!("only a time argument is held as a time"),
244 }
245 }
246 let representation = self.reading().representation(&given);
247 pinned(representation, rate)?;
248 Ok(representation)
249 }
250
251 pub fn path(&self) -> Option<&Path> {
252 match &self.dest {
253 Some(Destination::File(path)) => Some(path),
254 Some(Destination::Alsa { .. }) | None => None,
255 }
256 }
257}
258
259pub fn asked(call: &Call) -> Result<Asked, CliError> {
261 let name = call.name.as_str();
262 if let Some(write) = retired(name) {
263 return Err(CliError::usage(
264 "query.retired",
265 format!("`{name}` left the language; write `{write}`"),
266 ));
267 }
268 let Some(row) = READINGS.iter().find(|row| row.name == name) else {
269 let names: Vec<&str> = READINGS.iter().map(|row| row.name).collect();
270 return Err(CliError::usage(
271 "query.unknown_representation",
272 format!(
273 "unknown representation `{name}`; the representations are {}",
274 names.join(", ")
275 ),
276 ));
277 };
278 let (mut given, mut node, mut brief, mut skim) = (Given::default(), None, false, false);
279 let (mut buffer, mut times) = (None, Vec::new());
280 for (key, raw) in &call.args {
281 let Some(arg) = row.takes.iter().find(|arg| arg.key() == key) else {
282 let keys: Vec<&str> = row.takes.iter().map(|arg| arg.key()).collect();
283 return Err(CliError::usage(
284 "query.unknown_argument",
285 match keys[..] {
286 [] => format!("`{name}` takes no arguments, not `{key}`"),
287 _ => format!("`{name}` takes {}, not `{key}`", keys.join(", ")),
288 },
289 ));
290 };
291 match arg {
292 Arg::Peaks => given.peaks = count(raw, key)?,
293 Arg::Depth => given.depth = count(raw, key)?,
294 Arg::Frame | Arg::Window | Arg::Cell | Arg::Smooth => {
295 times.push((*arg, time(raw, key)?));
296 }
297 Arg::Oversample => given.oversample = factor(raw)?,
298 Arg::Brief => brief = switch(raw, key)?,
299 Arg::Skim => skim = switch(raw, key)?,
300 Arg::Node => node = Some(self::node(raw)?),
301 Arg::Buffer => buffer = Some(microseconds(raw, key)?),
302 Arg::Floor => given.floor_db = decibels(raw, key)?,
303 Arg::Norm => given.norm = norm(raw)?,
304 Arg::Pairs => given.max_pairs = count(raw, key)?,
305 Arg::Curve => given.curve = switch(raw, key)?,
306 Arg::Bpm => given.bpm = Some(tempo(raw, key)?),
307 }
308 }
309 if row.takes.contains(&Arg::Node) && node.is_none() {
310 return Err(CliError::usage(
311 "query.missing_argument",
312 format!("`{name}` reads one instance's {name}; name it, as `{name}(node=@voice)`"),
313 ));
314 }
315 Ok(Asked {
316 name: call.name.clone(),
317 given,
318 times,
319 dest: destination(name, call.dest.as_deref(), buffer)?,
320 node,
321 brief,
322 skim,
323 })
324}
325
326fn destination(
328 name: &str,
329 dest: Option<&Path>,
330 buffer: Option<f64>,
331) -> Result<Option<Destination>, CliError> {
332 let device = dest.and_then(|d| d.to_str()?.strip_prefix("alsa:"));
333 match (dest, device, buffer) {
334 (_, Some(""), _) => Err(CliError::usage(
335 "destination.no_device",
336 format!(
337 "`{name}=alsa:` names no device; write an ALSA device after it, as \
338 `alsa:default` or `alsa:hw:1`"
339 ),
340 )),
341 (_, Some(device), _) => Ok(Some(Destination::Alsa {
342 device: device.to_string(),
343 buffer_secs: buffer.unwrap_or(DEFAULT_BUFFER_SECS),
344 })),
345 (_, None, Some(_)) => Err(CliError::usage(
346 "query.buffer_without_device",
347 format!(
348 "`buffer` sizes a live device's buffer, and `{name}` names none; write \
349 `{name}(buffer=...)=alsa:<device>`, or drop `buffer`"
350 ),
351 )),
352 (dest, None, None) => Ok(dest.map(|d| Destination::File(d.to_path_buf()))),
353 }
354}
355
356fn split_outside(raw: &str, sep: char) -> Result<Vec<&str>, CliError> {
358 let (mut depth, mut from, mut out) = (0i32, 0, Vec::new());
359 for (at, c) in raw.char_indices() {
360 match c {
361 '(' => depth += 1,
362 ')' => depth -= 1,
363 c if c == sep && depth == 0 => {
364 out.push(&raw[from..at]);
365 from = at + c.len_utf8();
366 }
367 _ => {}
368 }
369 if depth < 0 {
370 return Err(unwritten(raw, "a `)` closes nothing"));
371 }
372 }
373 out.push(&raw[from..]);
374 Ok(out)
375}
376
377fn closing(text: &str) -> Option<usize> {
379 let mut depth = 0i32;
380 for (at, c) in text.char_indices() {
381 match c {
382 '(' => depth += 1,
383 ')' => {
384 depth -= 1;
385 if depth == 0 {
386 return Some(at);
387 }
388 }
389 _ => {}
390 }
391 }
392 None
393}
394
395fn unwritten(text: &str, why: &str) -> CliError {
396 CliError::usage(
397 "query.malformed",
398 format!(
399 "`{text}` is no reading: {why}. write a call, as `spectrum(peaks=8, frame=50ms)`, \
400 `=path` after it to write it to a file"
401 ),
402 )
403}
404
405pub fn wav_path(raw: &str) -> Result<PathBuf, CliError> {
406 match is_wav(Path::new(raw)) {
407 true => Ok(PathBuf::from(raw)),
408 false => Err(CliError::usage(
409 "analyze.not_wav",
410 format!("`{raw}` is no `.wav` file; mp3 and every other format are out of scope"),
411 )),
412 }
413}
414
415fn count(raw: &str, key: &str) -> Result<usize, CliError> {
416 raw.parse::<usize>().map_err(|_| {
417 CliError::usage(
418 "query.bad_value",
419 format!("`{key}` needs a whole count, got `{raw}`"),
420 )
421 })
422}
423
424fn factor(raw: &str) -> Result<u32, CliError> {
425 match raw.parse::<u32>() {
426 Ok(k) if (2..=16).contains(&k) && k.is_power_of_two() => Ok(k),
427 _ => Err(CliError::usage(
428 "query.bad_value",
429 format!("`oversample` needs a power of two from 2 to 16, got `{raw}`"),
430 )),
431 }
432}
433
434fn time(raw: &str, key: &str) -> Result<Time, CliError> {
437 let bad = |why: String| {
438 CliError::usage(
439 "query.bad_value",
440 format!(
441 "`{key}` needs a positive time, in seconds as `50ms` or `0.05`, or in bars as \
442 `1b/8`: {why}"
443 ),
444 )
445 };
446 let folding = Folding::<f64> {
447 field: Field::Time,
448 mark: &|_| None,
449 degree: &|_| Err("a reading's time counts no degrees".to_string()),
450 own: None,
451 };
452 let value = evaluate(raw, &folding).map_err(|refused| match refused {
453 Refused::At(_, why) => bad(why),
454 Refused::Mark(name, _) => bad(format!(
455 "`mark({name})` is a score's, and a reading has none"
456 )),
457 })?;
458 let unit = match value.kind {
459 Kind::Bars => SpanUnit::Bars,
460 Kind::Seconds | Kind::Number => SpanUnit::Seconds,
461 other => return Err(bad(format!("`{raw}` is a {}", other.name()))),
462 };
463 match value.amount > 0.0 && value.amount.is_finite() {
464 true => Ok(Time {
465 amount: value.amount,
466 unit,
467 written: raw.to_string(),
468 }),
469 false => Err(bad(format!("`{raw}` is not over zero"))),
470 }
471}
472
473fn pinned(representation: Representation, rate: u32) -> Result<(), CliError> {
475 let Representation::Spectrum {
476 frame_secs: Some(secs),
477 ..
478 } = representation
479 else {
480 return Ok(());
481 };
482 let sr = f64::from(rate);
483 let frame = pinned_frame(secs, sr);
484 match frame > MAX_PINNED_FRAME {
485 true => Err(CliError::usage(
486 "query.bad_value",
487 format!(
488 "`spectrum(frame={secs})` sizes its transform to {frame} samples at {sr} Hz, \
489 past the {MAX_PINNED_FRAME}-sample bound"
490 ),
491 )),
492 false => Ok(()),
493 }
494}
495
496pub fn seconds(raw: &str, key: &str) -> Result<f64, CliError> {
498 let held = match sva_ast::tokenize(raw).as_deref() {
499 Ok([one]) => match one.kind {
500 sva_ast::TokenKind::Num(v)
501 | sva_ast::TokenKind::Time(v, sva_ast::SpanUnit::Seconds) => Some(v),
502 _ => None,
503 },
504 _ => None,
505 };
506 match held {
507 Some(v) if v > 0.0 && v.is_finite() => Ok(v),
508 _ => Err(CliError::usage(
509 "query.bad_value",
510 format!("`{key}` needs a positive time, as `50ms` or `0.05`, got `{raw}`"),
511 )),
512 }
513}
514
515fn tempo(raw: &str, key: &str) -> Result<f64, CliError> {
517 let held = match sva_ast::tokenize(raw).as_deref() {
518 Ok([one]) => match one.kind {
519 sva_ast::TokenKind::Num(v) => Some(v),
520 _ => None,
521 },
522 _ => None,
523 };
524 match held {
525 Some(v) if v > 0.0 && v.is_finite() => Ok(v),
526 _ => Err(CliError::usage(
527 "query.bad_value",
528 format!("`{key}` needs a positive tempo in beats per minute, as `140`, got `{raw}`"),
529 )),
530 }
531}
532
533fn microseconds(raw: &str, key: &str) -> Result<f64, CliError> {
535 let secs = seconds(raw, key)?;
536 match (1.0..=f64::from(i32::MAX)).contains(&(secs * 1e6).round()) {
537 true => Ok(secs),
538 false => Err(CliError::usage(
539 "query.bad_value",
540 format!(
541 "`{key}` is a whole number of microseconds from 1us to {}s, got `{raw}`",
542 i32::MAX / 1_000_000
543 ),
544 )),
545 }
546}
547
548fn decibels(raw: &str, key: &str) -> Result<f64, CliError> {
550 use sva_ast::{LogUnit::Decibels, TokenKind};
551 let kinds: Option<Vec<TokenKind>> = sva_ast::tokenize(raw)
552 .ok()
553 .map(|tokens| tokens.into_iter().map(|t| t.kind).collect());
554 let held = match kinds.as_deref() {
555 Some([TokenKind::Log(v, Decibels)]) => Some(*v),
556 Some([TokenKind::Minus, TokenKind::Log(v, Decibels)]) => Some(-v),
557 _ => None,
558 };
559 match held {
560 Some(v) if v.is_finite() => Ok(v),
561 _ => Err(CliError::usage(
562 "query.bad_value",
563 format!("`{key}` needs a level in decibels, as `-40db`, got `{raw}`"),
564 )),
565 }
566}
567
568fn norm(raw: &str) -> Result<Norm, CliError> {
569 [Norm::L1, Norm::L2]
570 .into_iter()
571 .find(|n| n.key() == raw)
572 .ok_or_else(|| {
573 CliError::usage(
574 "query.bad_value",
575 format!("`norm` is `l1` or `l2`, got `{raw}`"),
576 )
577 })
578}
579
580fn switch(raw: &str, key: &str) -> Result<bool, CliError> {
581 match raw {
582 "1" => Ok(true),
583 "0" => Ok(false),
584 _ => Err(CliError::usage(
585 "query.bad_value",
586 format!("`{key}` is `1` or `0`, got `{raw}`"),
587 )),
588 }
589}
590
591fn node(raw: &str) -> Result<String, CliError> {
593 match raw.strip_prefix('@') {
594 Some(path) if !path.is_empty() => Ok(path.to_string()),
595 _ => Err(CliError::usage(
596 "query.bad_value",
597 format!("`node` names an instance as a ref, as `@voice`, not `{raw}`"),
598 )),
599 }
600}