1use std::path::Path;
4
5use sva_engine::{
6 Alias, AliasBand, Answer, Arguments, BandCrest, BandTrack, Bands, Binding, Boot, BootPhase,
7 Buffer, CacheStats, Counters, Crest, CuttingBelowSilenceThreshold, Detail, EngineStats,
8 EnvelopeFrame, FormantFrame, Kind, Label, LedgerEntry, Loudness, LoudnessFrame, Onsets,
9 Outcome, Output, PayloadKind, Phase, Source, SpectralSum, Spectrum, StereoFrame, StereoImage,
10 Work, Worked,
11};
12
13use sva_engine::harmony::Framing;
14use sva_engine::harmony::chords::{self, Chord};
15use sva_engine::harmony::dissonance::{self, Dissonance, Extreme};
16use sva_engine::harmony::inharmonicity::{self, Inharmonicity, Series, Weighted};
17use sva_engine::harmony::tonnetz::{self, Quality, TonalDistance, Triad};
18use sva_engine::harmony::voice_leading::{self, VoiceLeading};
19use sva_engine::modulation::{self, Modulation};
20use sva_engine::periodicity::{self, Periodicity, Track, Window};
21use sva_engine::pitch as pitch_names;
22use sva_engine::self_similarity::{self, SelfSimilarity};
23use sva_engine::sliding::Stats;
24
25use crate::cli_error::CliError;
26use crate::json::{NONE, capped, escape, latest, list, num};
27use crate::query::{Asked, Spelled, Taken};
28
29pub const SAMPLE_LIMIT: usize = 4096;
31
32fn maybe(v: Option<f64>) -> String {
33 v.map(num).unwrap_or_else(|| NONE.to_string())
34}
35
36fn counted(v: Option<usize>) -> String {
37 v.map_or_else(|| NONE.to_string(), |c| c.to_string())
38}
39
40fn ledger_json(entries: &[LedgerEntry], skim: bool) -> String {
41 list(entries, |e| {
42 let clipped = e
43 .clipped
44 .map_or_else(|| NONE.to_string(), |c| c.to_string());
45 let channel = counted(e.channel);
46 if skim {
47 return format!(
48 "\n {{ \"node\": \"{}\", \"channel\": {channel}, \"rms\": {}, \"peak\": {}, \"clipped\": {clipped} }}",
49 escape(&e.node),
50 num(e.rms),
51 num(e.peak)
52 );
53 }
54 format!(
55 "\n {{ \"node\": \"{}\", \"channel\": {channel}, \"depth\": {}, \"unit\": \"{}\", \
56 \"control\": {}, \"rms\": {}, \"peak\": {}, \"min\": {}, \"max\": {}, \
57 \"share\": {}, \"clipped\": {clipped} }}",
58 escape(&e.node),
59 e.depth,
60 e.kind.unit().name(),
61 !e.kind.is_audio(),
62 num(e.rms),
63 num(e.peak),
64 num(e.min),
65 num(e.max),
66 maybe(e.share)
67 )
68 })
69}
70
71fn spectrum_json(s: &Spectrum) -> String {
72 format!(
73 "{{ \"frame_size\": {}, \"frames\": {}, \"resolution_hz\": {}, \"rms\": {}, \
74 \"centroid_hz\": {}, \"rolloff85_hz\": {}, \"peaks\": {}, \"bands\": {} }}",
75 s.frame_size,
76 s.frames,
77 num(s.resolution_hz),
78 num(s.rms),
79 num(s.centroid_hz),
80 num(s.rolloff85_hz),
81 list(&s.peaks, |p| format!(
82 "{{ \"hz\": {}, \"db\": {} }}",
83 num(p.hz),
84 num(p.db)
85 )),
86 list(&s.bands, |b| format!(
87 "\n {{ \"lo_hz\": {}, \"hi_hz\": {}, \"db\": {} }}",
88 num(b.lo_hz),
89 num(b.hi_hz),
90 num(b.db)
91 ))
92 )
93}
94
95fn stereo_json(image: &StereoImage) -> String {
96 let frame = |f: &StereoFrame| {
97 format!(
98 "\n {{ \"t\": {}, \"correlation\": {}, \"mid_rms\": {}, \"side_rms\": {}, \
99 \"width\": {}, \"balance_db\": {}, \"mono_db\": {} }}",
100 num(f.t_secs),
101 num(f.correlation),
102 num(f.mid_rms),
103 num(f.side_rms),
104 num(f.width),
105 num(f.balance_db),
106 num(f.mono_db)
107 )
108 };
109 format!(
110 "{{ \"channels\": {}, \"overall\": {}, \"frames\": {} }}",
111 image.channels,
112 frame(&image.overall),
113 list(&image.frames, frame)
114 )
115}
116
117fn formants_json(f: &FormantFrame) -> String {
118 format!(
119 "\n {{ \"t\": {}, \"order\": {}, \"energy\": {}, \"residual\": {}, \"formants\": {} }}",
120 num(f.t_secs),
121 f.order,
122 num(f.energy),
123 num(f.residual),
124 list(&f.formants, |v| format!(
125 "{{ \"hz\": {}, \"bandwidth_hz\": {}, \"db\": {} }}",
126 num(v.hz),
127 num(v.bandwidth_hz),
128 num(v.db)
129 ))
130 )
131}
132
133fn band_json(b: &BandTrack, start_secs: f64, rate_hz: f64, limit: Option<usize>) -> String {
134 let shown = limit.map_or(b.rms.len(), |cap| b.rms.len().min(cap));
135 format!(
136 "\n {{ \"centre_hz\": {}, \"cam\": {}, \"erb_hz\": {}, \"q\": {}, \"peak\": {}, \
137 \"time_to_peak_secs\": {}, \"rise_10_90_secs\": {}, \
138 \"floor\": {{ \"peak\": {}, \"time_to_peak_secs\": {}, \"rise_10_90_secs\": {} }}, \
139 \"rms\": {} }}",
140 num(b.centre_hz),
141 num(b.cam),
142 num(b.erb_hz),
143 num(b.q),
144 num(b.peak),
145 maybe(b.time_to_peak_secs),
146 maybe(b.rise_10_90_secs),
147 num(b.floor.peak),
148 num(b.floor.time_to_peak_secs),
149 maybe(b.floor.rise_10_90_secs),
150 capped(
151 &b.rms,
152 shown,
153 |n| start_secs + n as f64 / rate_hz,
154 |v| num(*v),
155 )
156 )
157}
158
159fn bands_json(b: &Bands, limit: Option<usize>) -> String {
160 format!(
161 "{{ \"rate_hz\": {}, \"start_secs\": {}, \"bands\": {} }}",
162 num(b.rate_hz),
163 num(b.start_secs),
164 list(&b.bands, |band| band_json(
165 band,
166 b.start_secs,
167 b.rate_hz,
168 limit
169 ))
170 )
171}
172
173fn loudness_json(l: &Loudness, limit: Option<usize>) -> String {
174 let frames = |fs: &[LoudnessFrame]| {
175 let shown = limit.map_or(fs.len(), |cap| fs.len().min(cap));
176 capped(
177 fs,
178 shown,
179 |n| fs[n].t,
180 |f| format!("\n {{ \"t\": {}, \"lufs\": {} }}", num(f.t), num(f.lufs)),
181 )
182 };
183 format!(
184 "{{ \"integrated_lufs\": {}, \"range_lu\": {}, \"momentary_max_lufs\": {}, \
185 \"short_term_max_lufs\": {}, \"sample_peak\": {}, \"sample_peak_dbfs\": {}, \
186 \"peak_note\": \"{}\", \"momentary_secs\": {}, \"hop_secs\": {}, \"momentary\": {}, \
187 \"short_term\": {} }}",
188 maybe(l.integrated_lufs),
189 maybe(l.range_lu),
190 maybe(l.momentary_max_lufs),
191 maybe(l.short_term_max_lufs),
192 num(l.sample_peak),
193 maybe(l.sample_peak_dbfs),
194 escape(l.peak_note),
195 num(l.momentary_secs),
196 num(l.hop_secs),
197 frames(&l.momentary),
198 frames(&l.short_term)
199 )
200}
201
202fn crest_json(c: &Crest) -> String {
203 let band = |b: &BandCrest| {
204 format!(
205 "\n {{ \"lo_hz\": {}, \"hi_hz\": {}, \"centre_hz\": {}, \"peak\": {}, \
206 \"rms\": {}, \"crest_db\": {}, \"counted\": {} }}",
207 num(b.lo_hz),
208 num(b.hi_hz),
209 num(b.centre_hz),
210 num(b.peak),
211 num(b.rms),
212 num(b.crest_db),
213 b.counted
214 )
215 };
216 format!(
217 "{{ \"broadband_crest_db\": {}, \"spread_db\": {}, \"widest_band_hz\": {}, \
218 \"tightest_band_hz\": {}, \"counted_under_db\": {}, \"bands\": {} }}",
219 num(c.broadband_crest_db),
220 maybe(c.spread_db),
221 maybe(c.widest_band_hz),
222 maybe(c.tightest_band_hz),
223 num(c.counted_under_db),
224 list(&c.bands, band)
225 )
226}
227
228fn onsets_json(o: &Onsets) -> String {
229 format!(
230 "{{ \"onsets\": {}, \"resolution_secs\": {}, \"ioi_histogram\": {} }}",
231 list(&o.onsets, |t| format!(
232 "{{ \"t_secs\": {}, \"strength\": {} }}",
233 num(t.t_secs),
234 num(t.strength)
235 )),
236 num(o.resolution_secs),
237 list(&o.ioi_histogram, |b| format!(
238 "{{ \"lo_secs\": {}, \"hi_secs\": {}, \"count\": {} }}",
239 num(b.lo_secs),
240 num(b.hi_secs),
241 b.count
242 )),
243 )
244}
245
246fn alias_json(a: &Alias) -> String {
247 let band = |b: &AliasBand| {
248 format!(
249 "\n {{ \"lo_hz\": {}, \"hi_hz\": {}, \"signal_db\": {}, \"alias_db\": {}, \
250 \"nmr_db\": {} }}",
251 num(b.lo_hz),
252 num(b.hi_hz),
253 num(b.signal_db),
254 num(b.alias_db),
255 num(b.nmr_db)
256 )
257 };
258 format!(
259 "{{ \"oversample\": {}, \"sample_rate\": {}, \"frame_size\": {}, \"frames\": {}, \
260 \"scored_frames\": {}, \"playback_db_spl\": {}, \"asr_db\": {}, \"nmr_db\": {}, \
261 \"nmr_peak_db\": {}, \"peak_at_secs\": {}, \"audible\": {}, \
262 \"instances\": {}, \"bands\": {} }}",
263 a.oversample,
264 num(a.sample_rate),
265 a.frame_size,
266 a.frames,
267 a.scored_frames,
268 num(a.playback_db_spl),
269 num(a.asr_db),
270 num(a.nmr_db),
271 num(a.nmr_peak_db),
272 num(a.peak_at_secs),
273 a.audible,
274 a.instances,
275 list(&a.bands, band)
276 )
277}
278
279fn framing_json(framing: &Framing, floor_db: f64) -> String {
282 let window = framing.window.map_or(NONE.to_string(), |w| {
283 format!(
284 "{{ \"size\": {}, \"secs\": {}, \"resolution_hz\": {} }}",
285 w.size,
286 num(w.secs),
287 num(w.resolution_hz)
288 )
289 });
290 format!(
291 "\"partials\": \"{}\", \"floor_db\": {}, \"hop_secs\": {}, \"window\": {window}",
292 escape(framing.method()),
293 num(floor_db),
294 num(framing.hop_secs)
295 )
296}
297
298fn extreme_json(e: Option<Extreme>) -> String {
299 e.map_or(NONE.to_string(), |e| {
300 format!(
301 "{{ \"value\": {}, \"t\": {} }}",
302 num(e.value),
303 num(e.t_secs)
304 )
305 })
306}
307
308fn dissonance_json(d: &Dissonance) -> String {
309 format!(
310 "{{ \"model\": \"{}\", \"constants\": {{ \"a\": {}, \"b\": {}, \"d_star\": {}, \
311 \"s1\": {}, \"s2\": {} }}, \"amplitude\": \"product\", {}, \"mean\": {}, \
312 \"max\": {}, \"min\": {}, \"curve\": {} }}",
313 escape(dissonance::MODEL),
314 num(dissonance::A),
315 num(dissonance::B),
316 num(dissonance::D_STAR),
317 num(dissonance::S1),
318 num(dissonance::S2),
319 framing_json(&d.framing, d.floor_db),
320 maybe(d.mean),
321 extreme_json(d.max),
322 extreme_json(d.min),
323 list(&d.frames, |f| format!(
324 "\n {{ \"t\": {}, \"roughness\": {}, \"roughness_bounds\": [{}, {}], \
325 \"partials\": {} }}",
326 num(f.t_secs),
327 num(f.roughness),
328 num(f.roughness_bounds.0),
329 num(f.roughness_bounds.1),
330 f.partials
331 ))
332 )
333}
334
335fn notes_json(notes: &[i64]) -> String {
336 list(notes, |n| format!("\"{}\"", pitch_names::note_name(*n)))
337}
338
339fn chord_fields(c: &Chord) -> String {
340 format!(
341 "\"start_secs\": {}, \"end_secs\": {}, \"notes\": {}, \"unresolved\": {}",
342 num(c.start_secs),
343 num(c.end_secs),
344 notes_json(&c.notes),
345 notes_json(&c.unresolved)
346 )
347}
348
349fn voice_leading_json(v: &VoiceLeading) -> String {
350 format!(
351 "{{ \"model\": \"{}\", \"norm\": \"{}\", \"chords_by\": \"{}\", {}, \
352 \"total\": {}, \"chords\": {}, \"transitions\": {} }}",
353 escape(voice_leading::MODEL),
354 v.norm.key(),
355 escape(chords::METHOD),
356 framing_json(&v.framing, v.floor_db),
357 num(v.total),
358 list(&v.chords, |c| format!("\n {{ {} }}", chord_fields(c))),
359 list(&v.transitions, |t| format!(
360 "\n {{ \"t\": {}, \"from\": {}, \"to\": {}, \"distance\": {}, \
361 \"mapping\": {} }}",
362 num(t.at_secs),
363 notes_json(&t.from),
364 notes_json(&t.to),
365 num(t.distance),
366 list(&t.mapping, |(from, to)| format!(
367 "{{ \"from\": \"{}\", \"to\": \"{}\" }}",
368 pitch_names::note_name(*from),
369 pitch_names::note_name(*to)
370 ))
371 ))
372 )
373}
374
375fn triad_json(t: Option<Triad>) -> String {
376 t.map_or(NONE.to_string(), |t| {
377 format!(
378 "{{ \"root\": \"{}\", \"quality\": \"{}\" }}",
379 pitch_names::class_name(i64::from(t.root)),
380 match t.quality {
381 Quality::Major => "major",
382 Quality::Minor => "minor",
383 }
384 )
385 })
386}
387
388fn tonal_distance_json(d: &TonalDistance) -> String {
389 let tonic = d.tonic.map_or(NONE.to_string(), |(triad, t)| {
390 format!(
391 "{{ \"triad\": {}, \"t\": {} }}",
392 triad_json(Some(triad)),
393 num(t)
394 )
395 });
396 format!(
397 "{{ \"model\": \"{}\", \"chords_by\": \"{}\", {}, \"tonic\": {tonic}, \
398 \"chords\": {}, \"transitions\": {} }}",
399 escape(tonnetz::MODEL),
400 escape(chords::METHOD),
401 framing_json(&d.framing, d.floor_db),
402 list(&d.chords, |c| format!(
403 "\n {{ {}, \"triad\": {}, \"tension\": {} }}",
404 chord_fields(&c.chord),
405 triad_json(c.triad),
406 counted(c.tension)
407 )),
408 list(&d.transitions, |t| format!(
409 "\n {{ \"t\": {}, \"from\": {}, \"to\": {}, \"distance\": {}, \
410 \"path\": {} }}",
411 num(t.at_secs),
412 triad_json(t.from),
413 triad_json(t.to),
414 counted(t.path.as_ref().map(Vec::len)),
415 t.path.as_ref().map_or(NONE.to_string(), |p| format!(
416 "\"{}\"",
417 p.iter().map(|s| s.letter()).collect::<String>()
418 ))
419 ))
420 )
421}
422
423fn weighted_json(w: Option<Weighted>) -> String {
424 w.map_or(NONE.to_string(), |w| {
425 format!(
426 "{{ \"value\": {}, \"bounds\": [{}, {}] }}",
427 num(w.value),
428 num(w.bounds.0),
429 num(w.bounds.1)
430 )
431 })
432}
433
434fn bounds_json(b: Option<(f64, f64)>) -> String {
435 b.map_or(NONE.to_string(), |(lo, hi)| {
436 format!("[{}, {}]", num(lo), num(hi))
437 })
438}
439
440fn series_json(s: &Series) -> String {
441 let fit = s.fit.map_or(NONE.to_string(), |f| {
442 format!(
443 "{{ \"b\": {}, \"b_bounds\": {}, \"f0\": {}, \"f0_bounds\": {} }}",
444 num(f.b),
445 bounds_json(f.b_bounds),
446 num(f.f0_hz),
447 bounds_json(f.f0_bounds)
448 )
449 });
450 format!(
451 "{{ \"f1\": {}, \"cents\": {}, \"fit\": {fit}, \"members\": {} }}",
452 num(s.members[0].partial.hz),
453 weighted_json(s.cents),
454 list(&s.members, |m| format!(
455 "{{ \"n\": {}, \"hz\": {}, \"hz_bounds\": {}, \"amplitude\": {}, \
456 \"amplitude_bounds\": {}, \"cents\": {}, \"cents_bounds\": {} }}",
457 m.n,
458 num(m.partial.hz),
459 bounds_json(Some(m.partial.hz_bounds)),
460 num(m.partial.amplitude),
461 bounds_json(Some(m.partial.amplitude_bounds)),
462 num(m.cents),
463 bounds_json(Some(m.cents_bounds))
464 ))
465 )
466}
467
468fn inharmonicity_json(r: &Inharmonicity) -> String {
469 format!(
470 "{{ \"model\": \"{}\", {}, \"cents_mean\": {}, \"cents_max\": {}, \
471 \"unexplained_mean\": {}, \"curve\": {} }}",
472 escape(inharmonicity::MODEL),
473 framing_json(&r.framing, r.floor_db),
474 maybe(r.cents_mean),
475 extreme_json(r.cents_max),
476 maybe(r.unexplained_mean),
477 list(&r.frames, |f| format!(
478 "\n {{ \"t\": {}, \"cents\": {}, \"unexplained\": {}, \"series\": {} }}",
479 num(f.t_secs),
480 weighted_json(f.cents),
481 weighted_json(f.unexplained),
482 list(&f.series, series_json)
483 ))
484 )
485}
486
487fn spread_json(s: Option<Stats>) -> String {
488 s.map_or(NONE.to_string(), |s| {
489 format!(
490 "{{ \"mean\": {}, \"min\": {}, \"max\": {} }}",
491 num(s.mean),
492 extreme_json(Some(s.min)),
493 extreme_json(Some(s.max))
494 )
495 })
496}
497
498fn periodicity_window_json(w: &Window) -> String {
501 let curve = w.curve.as_ref().map_or(String::new(), |c| {
502 let heights: Vec<String> = c.iter().map(|h| num(*h)).collect();
503 format!(", \"curve\": [{}]", heights.join(", "))
504 });
505 format!(
506 "\n {{ \"t\": {}, \"from\": {}, \"to\": {}, \"drift_bpm\": {}, \"peaks\": {}{curve} }}",
507 num(w.t_secs),
508 num(w.from_secs),
509 num(w.to_secs),
510 maybe(w.drift_bpm),
511 list(&w.peaks, |p| format!(
512 "{{ \"period_secs\": {}, \"period_bounds_secs\": {}, \"bpm\": {}, \
513 \"bpm_bounds\": {}, \"height\": {} }}",
514 num(p.period_secs),
515 bounds_json(p.period_bounds_secs),
516 num(p.bpm),
517 bounds_json(p.bpm_bounds),
518 num(p.height)
519 ))
520 )
521}
522
523fn periodicity_track_json(t: &Track) -> String {
524 let centres: Vec<String> = t.centres_hz.iter().map(|hz| num(*hz)).collect();
525 format!(
526 "\n {{ \"group\": \"{}\", \"centres_hz\": [{}], \"summary\": {{ \
527 \"windows_with_peak\": {}, \"bpm\": {}, \"height\": {}, \"drift_bpm\": {} }}, \
528 \"windows\": {} }}",
529 t.group.key(),
530 centres.join(", "),
531 t.summary.windows_with_peak,
532 spread_json(t.summary.bpm),
533 spread_json(t.summary.height),
534 spread_json(t.summary.drift_bpm),
535 list(&t.windows, periodicity_window_json)
536 )
537}
538
539fn periodicity_json(p: &Periodicity) -> String {
540 format!(
541 "{{ \"model\": \"{}\", \"hop_secs\": {}, \"window_secs\": {}, \"envelope_hz\": {}, \
542 \"lag_step_secs\": {}, \"min_period_secs\": {}, \"max_period_secs\": {}, \
543 \"split_hz\": {}, \"smoothing\": {{ \"hz\": {}, \"poles\": {} }}, \"tracks\": {} }}",
544 escape(periodicity::MODEL),
545 num(p.hop_secs),
546 num(p.window_secs),
547 num(p.envelope_hz),
548 num(p.lag_step_secs),
549 num(p.min_period_secs),
550 num(p.max_period_secs),
551 num(periodicity::SPLIT_HZ),
552 maybe(periodicity::SMOOTHING.hz),
553 periodicity::SMOOTHING.poles,
554 list(&p.tracks, periodicity_track_json)
555 )
556}
557
558fn modulation_peak_json(p: &modulation::Peak, depth_key: &str) -> String {
561 let beats = p.period_beats.map_or(String::new(), |b| {
562 format!(
563 ", \"period_beats\": {}, \"period_beats_bounds\": {}",
564 num(b),
565 bounds_json(p.period_beats_bounds)
566 )
567 });
568 format!(
569 "{{ \"hz\": {}, \"hz_bounds\": {}{beats}, \"{depth_key}\": {}, \
570 \"{depth_key}_bounds\": {} }}",
571 num(p.hz),
572 bounds_json(p.hz_bounds),
573 num(p.depth),
574 bounds_json(p.depth_bounds)
575 )
576}
577
578fn modulation_window_json(w: &modulation::Window) -> String {
579 let centroid = w.centroid.as_ref().map_or(NONE.to_string(), |c| {
580 format!(
581 "{{ \"mean_hz\": {}, \"peaks\": {} }}",
582 num(c.mean_hz),
583 list(&c.peaks, |p| modulation_peak_json(p, "depth_hz"))
584 )
585 });
586 format!(
587 "\n {{ \"t\": {}, \"from\": {}, \"to\": {}, \"level\": {}, \"peaks\": {}, \
588 \"centroid\": {centroid} }}",
589 num(w.t_secs),
590 num(w.from_secs),
591 num(w.to_secs),
592 num(w.level),
593 list(&w.peaks, |p| modulation_peak_json(p, "depth"))
594 )
595}
596
597fn modulation_track_json(t: &modulation::Track) -> String {
598 let centres: Vec<String> = t.centres_hz.iter().map(|hz| num(*hz)).collect();
599 format!(
600 "\n {{ \"group\": \"{}\", \"centres_hz\": [{}], \"summary\": {{ \
601 \"windows_with_peak\": {}, \"hz\": {}, \"depth\": {}, \"centroid_hz\": {}, \
602 \"centroid_depth_hz\": {} }}, \"windows\": {} }}",
603 t.group.key(),
604 centres.join(", "),
605 t.summary.windows_with_peak,
606 spread_json(t.summary.hz),
607 spread_json(t.summary.depth),
608 spread_json(t.summary.centroid_hz),
609 spread_json(t.summary.centroid_depth_hz),
610 list(&t.windows, modulation_window_json)
611 )
612}
613
614fn modulation_json(m: &Modulation) -> String {
615 let splits: Vec<String> = modulation::SPLITS_HZ.iter().map(|hz| num(*hz)).collect();
616 format!(
617 "{{ \"model\": \"{}\", \"hop_secs\": {}, \"window_secs\": {}, \"envelope_hz\": {}, \
618 \"bin_step_hz\": {}, \"resolution_hz\": {}, \"min_hz\": {}, \"max_hz\": {}, \
619 \"bpm\": {}, \"splits_hz\": [{}], \"smoothing\": {{ \"hz\": {}, \"poles\": {} }}, \
620 \"passband_gain_at_max_hz\": {}, \"tracks\": {} }}",
621 escape(modulation::MODEL),
622 num(m.hop_secs),
623 num(m.window_secs),
624 num(m.envelope_hz),
625 num(m.bin_step_hz),
626 num(m.resolution_hz),
627 num(m.min_hz),
628 num(m.max_hz),
629 maybe(m.bpm),
630 splits.join(", "),
631 maybe(modulation::SMOOTHING.hz),
632 modulation::SMOOTHING.poles,
633 num(m.passband_gain_at_max_hz),
634 list(&m.tracks, modulation_track_json)
635 )
636}
637
638fn span_json(span: (f64, f64)) -> String {
639 format!("{{ \"from\": {}, \"to\": {} }}", num(span.0), num(span.1))
640}
641
642fn numbers(values: &[f64]) -> String {
643 let held: Vec<String> = values.iter().map(|v| num(*v)).collect();
644 format!("[{}]", held.join(", "))
645}
646
647fn self_similarity_cell_json(c: &self_similarity::Cell) -> String {
648 format!(
649 "\n {{ \"t\": {}, \"from\": {}, \"to\": {}, \"chroma\": {}, \"levels_db\": {} }}",
650 num(c.t_secs),
651 num(c.from_secs),
652 num(c.to_secs),
653 numbers(&c.chroma),
654 numbers(&c.levels_db)
655 )
656}
657
658fn self_similarity_view_json(v: &self_similarity::Reading, from_secs: f64, step: f64) -> String {
660 let matrix = v.matrix.as_ref().map_or(String::new(), |rows| {
661 let rows: Vec<String> = rows
662 .iter()
663 .map(|r| format!("\n {}", numbers(r)))
664 .collect();
665 format!(", \"matrix\": [{}]", rows.join(","))
666 });
667 format!(
668 "\n {{ \"view\": \"{}\", \"stripes_found\": {}, \"stripes\": {}, \
669 \"novelty\": {{ \"from_secs\": {}, \"step_secs\": {}, \"values\": {} }}, \
670 \"peaks_found\": {}, \"peaks\": {}{matrix} }}",
671 v.view.key(),
672 v.stripes_found,
673 list(&v.stripes, |s| format!(
674 "\n {{ \"shift_semitones\": {}, \"lag_secs\": {}, \"earlier\": {}, \
675 \"later\": {}, \"cells\": {}, \"similarity_mean\": {}, \"similarity_min\": {} }}",
676 s.shift_semitones,
677 num(s.lag_secs),
678 span_json(s.earlier),
679 span_json(s.later),
680 s.cells,
681 num(s.similarity_mean),
682 num(s.similarity_min)
683 )),
684 num(from_secs),
685 num(step),
686 numbers(&v.novelty),
687 v.peaks_found,
688 list(&v.peaks, |p| format!(
689 "{{ \"t\": {}, \"novelty\": {} }}",
690 num(p.t_secs),
691 num(p.novelty)
692 ))
693 )
694}
695
696fn self_similarity_json(s: &SelfSimilarity) -> String {
698 let cells = s.cells.as_ref().map_or(String::new(), |c| {
699 format!(", \"cells\": {}", list(c, self_similarity_cell_json))
700 });
701 format!(
702 "{{ \"model\": \"{}\", \"hop_secs\": {}, \"frame_window_secs\": {}, \
703 \"resolution_hz\": {}, \"cell_secs\": {}, \"frames_per_cell\": {}, \
704 \"cell_count\": {}, \"max_cells\": {}, \"smooth_cells\": {}, \"kernel_cells\": {}, \
705 \"floor_db\": {}, \"listed\": {}, \"min_hz\": {}, \"max_hz\": {}, \
706 \"centres_hz\": {}{cells}, \"views\": {} }}",
707 escape(self_similarity::MODEL),
708 num(s.hop_secs),
709 num(s.frame_window_secs),
710 num(s.resolution_hz),
711 num(s.cell_secs),
712 s.frames_per_cell,
713 s.cell_count,
714 self_similarity::MAX_CELLS,
715 s.smooth_cells,
716 s.kernel_cells,
717 num(s.floor_db),
718 s.listed,
719 num(s.min_hz),
720 num(s.max_hz),
721 numbers(&s.centres_hz),
722 list(&s.views, |v| self_similarity_view_json(
723 v,
724 s.novelty_from_secs,
725 s.cell_secs
726 ))
727 )
728}
729
730fn binding_json(b: &Binding) -> String {
731 format!(
732 "\n {{ \"name\": \"{}\", \"source\": \"{}\" }}",
733 escape(&b.name),
734 escape(&b.source)
735 )
736}
737
738fn arguments_json(a: &Arguments) -> String {
739 let at = |s: sva_ast::ByteSpan| format!("{{ \"start\": {}, \"end\": {} }}", s.start, s.end);
740 let calls = list(&a.calls, |c| {
741 let arguments = list(&c.arguments, |x| {
742 format!(
743 "{{ \"name\": \"{}\", \"value\": {}, \"written\": {} }}",
744 escape(&x.name),
745 num(x.value),
746 x.written
747 )
748 });
749 format!(
750 "\n {{ \"name\": \"{}\", \"at\": {}, \"arguments\": {arguments} }}",
751 escape(&c.name),
752 at(c.at)
753 )
754 });
755 let chosen = list(&a.chosen, |c| {
756 format!(
757 "\n {{ \"name\": \"{}\", \"at\": {}, \"operands\": {}, \"chosen\": {} }}",
758 escape(&c.name),
759 at(c.at),
760 list(&c.operands, |v| num(*v)),
761 c.chosen
762 )
763 });
764 format!(
765 "\n {{ \"node\": \"{}\", \"calls\": {calls}, \"chosen\": {chosen} }}",
766 escape(&a.node)
767 )
768}
769
770fn samples_json(b: &Buffer, limit: Option<usize>) -> String {
772 let component = |c: usize| {
773 let plane = b.plane(c);
774 let shown = limit.map_or(plane.len(), |cap| plane.len().min(cap));
775 format!(
776 "\n {{ \"channel\": {c}, \"values\": {} }}",
777 capped(
778 plane,
779 shown,
780 |n| b.origin_secs() + n as f64 / f64::from(b.rate),
781 |v| num(*v)
782 )
783 )
784 };
785 let components: Vec<usize> = (0..b.width()).collect();
786 format!(
787 "{{ \"rate\": {}, \"origin_secs\": {}, \"width\": {}, \"components\": {} }}",
788 b.rate,
789 num(b.origin_secs()),
790 b.width(),
791 list(&components, |c| component(*c))
792 )
793}
794
795fn symbolic_json(n: &SpectralSum) -> String {
796 format!(
797 "{{ \"var\": \"{}\", \"lanes\": {}, \"terms\": {} }}",
798 match n.var {
799 sva_engine::Var::T => "t",
800 sva_engine::Var::F => "f",
801 },
802 n.lanes.len(),
803 list(&sva_engine::atoms_of(n), atom_json)
804 )
805}
806
807pub fn value_json(output: &Output, limit: Option<usize>, skim: bool) -> String {
810 match output {
811 Output::Lines(lines) => list(lines, line_json),
812 Output::Atoms(atoms) => list(atoms, atom_json),
813 Output::Symbolic(sum) => symbolic_json(sum),
814 Output::Samples(buffer) => samples_json(buffer, limit),
815 Output::Ledger(entries) => ledger_json(entries, skim),
816 Output::Spectrum(s) => spectrum_json(s),
817 Output::Stereo(image) => stereo_json(image),
818 Output::Bands(b) => bands_json(b, limit),
819 Output::Loudness(l) => loudness_json(l, limit),
820 Output::Crest(c) => crest_json(c),
821 Output::Onsets(o) => onsets_json(o),
822 Output::Alias(a) => alias_json(a),
823 Output::Dissonance(d) => dissonance_json(d),
824 Output::VoiceLeading(v) => voice_leading_json(v),
825 Output::TonalDistance(d) => tonal_distance_json(d),
826 Output::Inharmonicity(r) => inharmonicity_json(r),
827 Output::Periodicity(p) => periodicity_json(p),
828 Output::Modulation(m) => modulation_json(m),
829 Output::SelfSimilarity(s) => self_similarity_json(s),
830 Output::Bindings(b) => list(b, binding_json),
831 Output::Arguments(a) => list(a, arguments_json),
832 Output::Envelope(frames) => list(frames, |f: &EnvelopeFrame| {
833 format!(
834 "\n {{ \"t\": {}, \"rms\": {}, \"peak\": {} }}",
835 num(f.t_secs),
836 num(f.rms),
837 num(f.peak)
838 )
839 }),
840 Output::Pitch(frames) => list(frames, |f| {
841 format!(
842 "\n {{ \"t\": {}, \"notes\": {} }}",
843 num(f.t_secs),
844 list(&f.notes, |n| format!(
845 "{{ \"note\": \"{}\", \"hz\": {}, \"cents\": {}, \"db\": {}, \
846 \"harmonic_of\": {} }}",
847 escape(&n.name),
848 num(n.hz),
849 num(n.cents),
850 num(n.db),
851 maybe(n.harmonic_of)
852 ))
853 )
854 }),
855 Output::Formants(frames) => list(frames, formants_json),
856 }
857}
858
859fn atom_json(a: &sva_engine::Atom) -> String {
862 let (at, per, turns) = match a.var {
863 sva_engine::Var::T => ("secs", "sec", "hz"),
864 sva_engine::Var::F => ("hz", "hz", "secs"),
865 };
866 format!(
867 "\n {{ \"channel\": {}, \"sketch\": \"{}\", \"{turns}\": {}, \"re\": {}, \"im\": {}, \
868 \"db\": {}, \"decay_per_{per}\": {}, \"decay_from_{at}\": {}, \"degree\": {}, \
869 \"polynomial_at_{at}\": {}, \"start_{at}\": {}, \"end_{at}\": {} }}",
870 a.channel,
871 escape(&a.sketch),
872 num(a.turns),
873 num(a.amp.re),
874 num(a.amp.im),
875 num(20.0 * a.amp.abs().log10()),
876 num(a.decay),
877 num(a.decay_from),
878 a.degree,
879 num(a.polynomial_at),
880 maybe(a.start),
881 maybe(a.end)
882 )
883}
884
885fn line_json(l: &sva_engine::Line) -> String {
886 format!(
887 "\n {{ \"hz\": {}, \"re\": {}, \"im\": {}, \"db\": {} }}",
888 num(l.hz),
889 num(l.amp.re),
890 num(l.amp.im),
891 num(20.0 * l.amp.abs().log10())
892 )
893}
894
895pub fn answer_json(printed: &Printed, limit: Option<usize>) -> String {
899 let answer = &printed.answer;
900 let args = printed
901 .args
902 .iter()
903 .map(|(key, value)| {
904 let value = match value {
905 None => NONE.to_string(),
906 Some(Spelled::Number(n)) => n.clone(),
907 Some(Spelled::Text(t)) => format!("\"{}\"", escape(t)),
908 };
909 format!("\"{key}\": {value}")
910 })
911 .collect::<Vec<_>>()
912 .join(", ");
913 let args = match args.is_empty() {
914 true => "{}".to_string(),
915 false => format!("{{ {args} }}"),
916 };
917 format!(
918 "{{ \"representation\": \"{}\", \"args\": {args}, \"source\": \"{}\", \"profile\": \"{}\", \
919 \"rate\": {}, \"value\": {}, \"dropped\": {}, \"tail_db\": {} }}",
920 escape(&printed.name),
921 match answer.source {
922 Source::Exact => "exact",
923 Source::Measured => "measured",
924 },
925 escape(answer.profile),
926 answer
927 .rate
928 .map_or_else(|| NONE.to_string(), |r| r.to_string()),
929 value_json(&answer.value, limit, printed.skim),
930 list(&answer.dropped, line_json),
931 maybe(answer.tail_db)
932 )
933}
934
935fn detail_json(detail: &Detail) -> String {
937 match detail {
938 Detail::Lines {
939 summed,
940 dropped,
941 dropped_more,
942 tail_db,
943 ..
944 } => format!(
945 ", \"summed\": {summed}, \"dropped\": {}, \"dropped_more\": {dropped_more}, \
946 \"tail_db\": {}",
947 list(dropped, |d| format!(
948 "{{ \"hz\": {}, \"db\": {} }}",
949 num(d.hz),
950 num(d.db)
951 )),
952 maybe(*tail_db)
953 ),
954 Detail::Cropped { tail_db, .. } => format!(", \"tail_db\": {}", maybe(*tail_db)),
955 Detail::Point {
956 alias_db, tail_db, ..
957 } => format!(
958 ", \"alias_db\": {}, \"tail_db\": {}",
959 maybe(*alias_db),
960 maybe(*tail_db)
961 ),
962 Detail::Roundtrip { edited, .. } => format!(", \"edited\": {edited}"),
963 Detail::Continuous { .. } | Detail::Reading { .. } => String::new(),
964 Detail::Added { parts } => format!(
965 ", \"addends\": {}",
966 list(parts, |part| format!(
967 "{{ \"rule\": \"{}\"{} }}",
968 part.rule().as_str(),
969 detail_json(part)
970 ))
971 ),
972 }
973}
974
975pub fn label_json(label: &Label) -> String {
978 let detail = detail_json(&label.detail);
979 let cutting = label
980 .cutting_below_silence_threshold
981 .as_ref()
982 .map_or(NONE.to_string(), cutting_below_silence_threshold_json);
983 let rest = format!(
984 ", \"moved_s\": {}, \"pruned\": {cutting}, \"resampled\": {}",
985 maybe(label.moved),
986 list(&label.resampled, resampled_json)
987 );
988 format!(
989 "{{ \"source\": \"{}\", \"profile\": \"{}\", \"rate\": {}, \"rule\": \"{}\"{detail}{rest} }}",
990 match label.source {
991 Source::Exact => "exact",
992 Source::Measured => "measured",
993 },
994 escape(label.profile),
995 label.rate,
996 escape(label.rule().as_str())
997 )
998}
999
1000pub fn resampled_json(r: &sva_engine::Resampled) -> String {
1002 format!(
1003 "{{ \"from_hz\": {}, \"to_hz\": {}, \"passband_hz\": {}, \"stopband_hz\": {}, \
1004 \"ripple_db\": {}, \"stopband_db\": {} }}",
1005 r.from_hz,
1006 r.to_hz,
1007 num(r.passband_hz),
1008 num(r.stopband_hz),
1009 num(r.ripple_db),
1010 num(r.stopband_db)
1011 )
1012}
1013
1014pub fn cutting_below_silence_threshold_json(cutting: &CuttingBelowSilenceThreshold) -> String {
1017 let cuts = list(&cutting.treated_as_silent_from_sample, |(node, from)| {
1018 format!("{{ \"node\": \"{}\", \"from\": {from} }}", escape(node))
1019 });
1020 format!(
1021 "{{ \"db\": {}, \"cuts\": {cuts} }}",
1022 num(cutting.silence_threshold_dbfs)
1023 )
1024}
1025
1026pub fn work_json(work: &Work) -> String {
1027 format!(
1028 "{{ \"samples\": {}, \"computed_samples\": {} }}",
1029 work.samples, work.computed_samples
1030 )
1031}
1032
1033pub fn stats_json(stats: &CacheStats) -> String {
1037 stats_with(stats, "")
1038}
1039
1040pub fn stream_stats_json(
1044 stats: &CacheStats,
1045 (dropped, made): (&[&str], usize),
1046 cutting: &CuttingBelowSilenceThreshold,
1047) -> String {
1048 let dropped = latest(dropped, made, |name| format!("\"{}\"", escape(name)));
1049 let pruned = cutting_below_silence_threshold_json(cutting);
1050 stats_with(
1051 stats,
1052 &format!(", \"dropped\": {dropped}, \"pruned\": {pruned}"),
1053 )
1054}
1055
1056fn stats_with(stats: &CacheStats, extra: &str) -> String {
1057 let made = stats.shed + stats.lookups.len();
1058 let lookups = latest(&stats.lookups, made, |l| {
1059 let outcome = match l.outcome {
1060 Outcome::Hit => "hit",
1061 Outcome::ComputedStored => "computed_stored",
1062 Outcome::ComputedNotStored => "computed_not_stored",
1063 Outcome::ComputedReplaced => "computed_replaced",
1064 Outcome::Extended => "extended",
1065 Outcome::Prefix => "prefix",
1066 Outcome::Reused => "reused",
1067 };
1068 format!(
1069 "{{ \"node\": \"{}\", \"key\": \"{}\", \"kind\": \"{}\", \"outcome\": \"{outcome}\" }}",
1070 escape(&l.node),
1071 l.key,
1072 match l.kind {
1073 PayloadKind::Segments => "segments",
1074 PayloadKind::Frames => "frames",
1075 PayloadKind::Run => "run",
1076 }
1077 )
1078 });
1079 format!(
1080 "{{ \"nodes\": {}, \"hits\": {}, \"computed\": {}, \"stored\": {}, \"replaced\": {}, \"extended\": {}, \"reused\": {}, \
1081 \"bytes\": {}, \"max_bytes\": {}, \"entries\": {}, \"evictions\": {}, \
1082 \"tier\": {}, \"lookups\": {lookups}{extra} }}",
1083 stats.nodes(),
1084 stats.hits(),
1085 stats.computed(),
1086 stats.stored(),
1087 stats.replaced(),
1088 stats.extended(),
1089 stats.reused(),
1090 stats.bytes,
1091 stats.max_bytes,
1092 stats.entries,
1093 stats.evictions,
1094 counters_json(&stats.tier)
1095 )
1096}
1097
1098pub fn counters_json(counters: &Counters) -> String {
1100 format!(
1101 "{{ \"disk_lookups\": {}, \"disk_reads\": {}, \"disk_read_bytes\": {}, \
1102 \"promotions\": {}, \"writebacks\": {}, \"hits\": {}, \"evictions\": {}, \
1103 \"probation_evictions\": {}, \"protected_evictions\": {} }}",
1104 counters.disk_lookups,
1105 counters.disk_reads,
1106 counters.disk_read_bytes,
1107 counters.promotions,
1108 counters.writebacks,
1109 counters.hits,
1110 counters.evictions(),
1111 counters.probation_evictions,
1112 counters.protected_evictions
1113 )
1114}
1115
1116fn worked_json(worked: &Worked) -> String {
1117 let lookups = worked.lookups;
1118 format!(
1119 "\"samples\": {}, \"cached_samples\": {}, \"cached_from_store_samples\": {}, \
1120 \"computed_samples\": {}, \"lookups\": {{ \"hit\": {}, \
1121 \"from_memory\": {}, \"from_store\": {}, \"prefix\": {}, \"miss\": {}, \"new\": {}, \
1122 \"reused\": {} }}, \"tier\": {}",
1123 worked.samples,
1124 worked.work.cached_samples,
1125 worked.work.stored_samples,
1126 worked.work.computed_samples,
1127 lookups.hit,
1128 lookups.hit - lookups.from_store,
1129 lookups.from_store,
1130 lookups.prefix,
1131 lookups.miss,
1132 lookups.new,
1133 lookups.reused,
1134 counters_json(&worked.tier)
1135 )
1136}
1137
1138pub fn engine_stats_json(stats: &EngineStats) -> String {
1140 let call = stats.call.as_ref().map_or("null".to_string(), |call| {
1141 let kind = match call.kind {
1142 Kind::Render => "render",
1143 Kind::Stream => "stream",
1144 Kind::Edit => "edit",
1145 Kind::Persist => "persist",
1146 };
1147 let phase = match call.phase {
1148 Phase::Parsing => "parsing",
1149 Phase::Typing => "typing",
1150 Phase::LookingUp => "looking_up",
1151 Phase::Planning => "planning",
1152 Phase::Fetching => "fetching",
1153 Phase::Delivering => "delivering",
1154 Phase::Finishing => "finishing",
1155 Phase::Storing => "storing",
1156 Phase::Done => "done",
1157 Phase::Failed => "failed",
1158 Phase::Abandoned => "abandoned",
1159 };
1160 let count = |n: Option<u64>| n.map_or("null".to_string(), |n| n.to_string());
1161 let (total, planned) = (count(call.total_samples), count(call.planned_samples));
1162 let typing = call.typing.map_or("null".to_string(), |typing| {
1163 format!(
1164 "{{ \"instances\": {}, \"nodes\": {}, \"typed\": {} }}",
1165 typing.instances, typing.nodes, typing.typed
1166 )
1167 });
1168 format!(
1169 "{{ \"id\": {}, \"kind\": \"{kind}\", \"target\": \"{}\", \"phase\": \"{phase}\", \
1170 \"total_samples\": {total}, \"planned_samples\": {planned}, \"typing\": {typing}, \
1171 {} }}",
1172 call.id,
1173 escape(&call.target),
1174 worked_json(&call.counts)
1175 )
1176 });
1177 let boot = stats
1178 .boot
1179 .map_or("null".to_string(), |boot| boot_json(&boot));
1180 let state = match (
1181 stats.boot.is_some_and(|boot| boot.under_way()),
1182 stats.working,
1183 ) {
1184 (true, _) => "booting",
1185 (false, 0) => "idle",
1186 (false, _) => "working",
1187 };
1188 format!(
1189 "{{ \"state\": \"{state}\", \"working\": {}, \"boot\": {boot}, \"call\": {call}, \
1190 \"totals\": {{ {} }} }}",
1191 stats.working,
1192 worked_json(&stats.totals)
1193 )
1194}
1195
1196fn boot_json(boot: &Boot) -> String {
1197 let phase = match boot.phase {
1198 BootPhase::StartingThreads => "starting_threads",
1199 BootPhase::ThreadsStarted => "threads_started",
1200 BootPhase::ThreadsFailed => "threads_failed",
1201 BootPhase::OpeningStore => "opening_store",
1202 BootPhase::ReadingIndex => "reading_index",
1203 BootPhase::IndexRead => "index_read",
1204 BootPhase::StoreFailed => "store_failed",
1205 BootPhase::Opened => "opened",
1206 };
1207 let count = |n: Option<u64>| n.map_or("null".to_string(), |n| n.to_string());
1208 let store = boot.store.map_or("null".to_string(), |store| {
1209 format!(
1210 "{{ \"max_bytes\": {}, \"index_bytes\": {}, \"entries\": {}, \"bytes\": {} }}",
1211 store.max_bytes,
1212 count(store.read.map(|read| read.0)),
1213 count(store.read.map(|read| read.1 as u64)),
1214 count(store.read.map(|read| read.2)),
1215 )
1216 });
1217 format!(
1218 "{{ \"phase\": \"{phase}\", \"threads\": {}, \"store\": {store} }}",
1219 count(boot.threads.map(|n| n as u64))
1220 )
1221}
1222
1223pub struct Printed {
1225 pub name: String,
1226 pub args: Vec<(&'static str, Option<Spelled>)>,
1229 pub answer: Answer,
1230 pub skim: bool,
1232}
1233
1234impl Printed {
1235 pub fn of(
1237 asked: &Asked,
1238 answer: Answer,
1239 rate: u32,
1240 seconds_per_bar: Option<f64>,
1241 ) -> Result<Printed, CliError> {
1242 let taken = match (answer.source, &answer.value) {
1243 (Source::Exact, _) => Taken::Exact,
1244 (Source::Measured, Output::Spectrum(s)) => Taken::Measured {
1245 fitted_frame: Some(s.frame_size),
1246 },
1247 (Source::Measured, _) => Taken::Measured { fitted_frame: None },
1248 };
1249 Ok(Printed {
1250 name: asked.name.clone(),
1251 args: asked.args(rate, seconds_per_bar, taken)?,
1252 answer,
1253 skim: asked.skim,
1254 })
1255 }
1256}
1257
1258pub struct Report<'a> {
1260 pub target: &'a str,
1261 pub rate: u32,
1262 pub bits: Option<i32>,
1264 pub interval: Option<(f64, f64)>,
1266 pub profile: &'a str,
1267 pub label: Option<&'a Label>,
1268 pub written: &'a [(String, &'a Path)],
1269 pub played: Option<&'a Played>,
1271 pub answers: &'a [Printed],
1272 pub limit: Option<usize>,
1273}
1274
1275#[derive(Clone, Debug, PartialEq)]
1277pub struct Played {
1278 pub representation: String,
1279 pub device: String,
1281 pub seconds: f64,
1282 pub rate: u32,
1283 pub channels: usize,
1284 pub format: &'static str,
1286 pub buffer_secs: f64,
1287 pub granted_buffer_secs: Option<f64>,
1289 pub underruns: usize,
1290 pub underruns_seen_by: &'static str,
1292}
1293
1294fn played_json(played: &Played) -> String {
1295 format!(
1296 "{{ \"representation\": \"{}\", \"device\": \"{}\", \"seconds\": {}, \
1297 \"sample_rate\": {}, \"channels\": {}, \"format\": \"{}\", \"buffer\": {{ \
1298 \"asked_secs\": {}, \"granted_secs\": {} }}, \"underruns\": {{ \"count\": {}, \
1299 \"seen_by\": \"{}\" }} }}",
1300 escape(&played.representation),
1301 escape(&played.device),
1302 num(played.seconds),
1303 played.rate,
1304 played.channels,
1305 played.format,
1306 num(played.buffer_secs),
1307 maybe(played.granted_buffer_secs),
1308 played.underruns,
1309 escape(played.underruns_seen_by),
1310 )
1311}
1312
1313pub fn query_data(report: &Report) -> String {
1315 let written = list(report.written, |(name, path)| {
1316 format!(
1317 "{{ \"representation\": \"{}\", \"path\": \"{}\" }}",
1318 escape(name),
1319 escape(&path.display().to_string())
1320 )
1321 });
1322 let label = report
1323 .label
1324 .map(label_json)
1325 .unwrap_or_else(|| NONE.to_string());
1326 let reads = report
1327 .answers
1328 .iter()
1329 .map(|printed| {
1330 format!(
1331 "\"{}\": {}",
1332 escape(&printed.name),
1333 answer_json(printed, report.limit)
1334 )
1335 })
1336 .collect::<Vec<_>>()
1337 .join(",\n ");
1338 let interval = report.interval.map_or(NONE.to_string(), |(start, end)| {
1339 format!(
1340 "{{ \"start_secs\": {}, \"end_secs\": {} }}",
1341 num(start),
1342 num(end)
1343 )
1344 });
1345 let played = report.played.map_or(String::new(), |played| {
1346 format!("\n \"played\": {},", played_json(played))
1347 });
1348 format!(
1349 "{{\n \"target\": \"{}\",\n \"sample_rate\": {},\n \"bits\": {},\n \
1350 \"profile\": \"{}\",\n \"interval\": {interval},\n \"label\": {label},\n \
1351 \"written\": {written},{played}\n \"representations\": {{\n {reads}\n }}\n}}",
1352 escape(report.target),
1353 report.rate,
1354 report.bits.map_or(NONE.to_string(), |b| b.to_string()),
1355 escape(report.profile),
1356 )
1357}