Skip to main content

sva_core/
answer.rs

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