1use std::path::Path;
4
5use sva_engine::{
6 Alias, AliasBand, Answer, Arguments, BandCrest, BandTrack, Bands, Binding, Buffer, CacheStats,
7 Cost, Crest, Detail, EnvelopeFrame, FormantFrame, Horizon, Label, LedgerEntry, Loudness,
8 LoudnessFrame, Outcome, Output, PayloadKind, Source, SpectralSum, Spectrum, StereoFrame,
9 StereoImage, Work,
10};
11
12use crate::json::{NONE, capped, escape, list, num};
13
14pub const SAMPLE_LIMIT: usize = 4096;
16
17fn maybe(v: Option<f64>) -> String {
18 v.map(num).unwrap_or_else(|| NONE.to_string())
19}
20
21fn counted(v: Option<usize>) -> String {
22 v.map_or_else(|| NONE.to_string(), |c| c.to_string())
23}
24
25fn ledger_json(entries: &[LedgerEntry], skim: bool) -> String {
26 list(entries, |e| {
27 let clipped = e
28 .clipped
29 .map_or_else(|| NONE.to_string(), |c| c.to_string());
30 let channel = counted(e.channel);
31 if skim {
32 return format!(
33 "\n {{ \"node\": \"{}\", \"channel\": {channel}, \"rms\": {}, \"peak\": {}, \"clipped\": {clipped} }}",
34 escape(&e.node),
35 num(e.rms),
36 num(e.peak)
37 );
38 }
39 format!(
40 "\n {{ \"node\": \"{}\", \"channel\": {channel}, \"depth\": {}, \"unit\": \"{}\", \
41 \"control\": {}, \"rms\": {}, \"peak\": {}, \"min\": {}, \"max\": {}, \
42 \"share\": {}, \"clipped\": {clipped} }}",
43 escape(&e.node),
44 e.depth,
45 e.kind.unit().name(),
46 !e.kind.is_audio(),
47 num(e.rms),
48 num(e.peak),
49 num(e.min),
50 num(e.max),
51 maybe(e.share)
52 )
53 })
54}
55
56fn spectrum_json(s: &Spectrum) -> String {
57 format!(
58 "{{ \"frame_size\": {}, \"frames\": {}, \"resolution_hz\": {}, \"rms\": {}, \
59 \"centroid_hz\": {}, \"rolloff85_hz\": {}, \"peaks\": {}, \"bands\": {} }}",
60 s.frame_size,
61 s.frames,
62 num(s.resolution_hz),
63 num(s.rms),
64 num(s.centroid_hz),
65 num(s.rolloff85_hz),
66 list(&s.peaks, |p| format!(
67 "{{ \"hz\": {}, \"db\": {} }}",
68 num(p.hz),
69 num(p.db)
70 )),
71 list(&s.bands, |b| format!(
72 "\n {{ \"lo_hz\": {}, \"hi_hz\": {}, \"db\": {} }}",
73 num(b.lo_hz),
74 num(b.hi_hz),
75 num(b.db)
76 ))
77 )
78}
79
80fn stereo_json(image: &StereoImage) -> String {
81 let frame = |f: &StereoFrame| {
82 format!(
83 "\n {{ \"t\": {}, \"correlation\": {}, \"mid_rms\": {}, \"side_rms\": {}, \
84 \"width\": {}, \"balance_db\": {}, \"mono_db\": {} }}",
85 num(f.t_secs),
86 num(f.correlation),
87 num(f.mid_rms),
88 num(f.side_rms),
89 num(f.width),
90 num(f.balance_db),
91 num(f.mono_db)
92 )
93 };
94 format!(
95 "{{ \"channels\": {}, \"overall\": {}, \"frames\": {} }}",
96 image.channels,
97 frame(&image.overall),
98 list(&image.frames, frame)
99 )
100}
101
102fn formants_json(f: &FormantFrame) -> String {
103 format!(
104 "\n {{ \"t\": {}, \"order\": {}, \"energy\": {}, \"residual\": {}, \"formants\": {} }}",
105 num(f.t_secs),
106 f.order,
107 num(f.energy),
108 num(f.residual),
109 list(&f.formants, |v| format!(
110 "{{ \"hz\": {}, \"bandwidth_hz\": {}, \"db\": {} }}",
111 num(v.hz),
112 num(v.bandwidth_hz),
113 num(v.db)
114 ))
115 )
116}
117
118fn band_json(b: &BandTrack, start_secs: f64, rate_hz: f64, limit: Option<usize>) -> String {
119 let shown = limit.map_or(b.rms.len(), |cap| b.rms.len().min(cap));
120 format!(
121 "\n {{ \"centre_hz\": {}, \"cam\": {}, \"erb_hz\": {}, \"q\": {}, \"peak\": {}, \
122 \"time_to_peak_secs\": {}, \"rise_10_90_secs\": {}, \
123 \"floor\": {{ \"peak\": {}, \"time_to_peak_secs\": {}, \"rise_10_90_secs\": {} }}, \
124 \"rms\": {} }}",
125 num(b.centre_hz),
126 num(b.cam),
127 num(b.erb_hz),
128 num(b.q),
129 num(b.peak),
130 maybe(b.time_to_peak_secs),
131 maybe(b.rise_10_90_secs),
132 num(b.floor.peak),
133 num(b.floor.time_to_peak_secs),
134 maybe(b.floor.rise_10_90_secs),
135 capped(
136 &b.rms,
137 shown,
138 |n| start_secs + n as f64 / rate_hz,
139 |v| num(*v),
140 )
141 )
142}
143
144fn bands_json(b: &Bands, limit: Option<usize>) -> String {
145 format!(
146 "{{ \"rate_hz\": {}, \"start_secs\": {}, \"bands\": {} }}",
147 num(b.rate_hz),
148 num(b.start_secs),
149 list(&b.bands, |band| band_json(
150 band,
151 b.start_secs,
152 b.rate_hz,
153 limit
154 ))
155 )
156}
157
158fn loudness_json(l: &Loudness, limit: Option<usize>) -> String {
159 let frames = |fs: &[LoudnessFrame]| {
160 let shown = limit.map_or(fs.len(), |cap| fs.len().min(cap));
161 capped(
162 fs,
163 shown,
164 |n| fs[n].t,
165 |f| format!("\n {{ \"t\": {}, \"lufs\": {} }}", num(f.t), num(f.lufs)),
166 )
167 };
168 format!(
169 "{{ \"integrated_lufs\": {}, \"range_lu\": {}, \"momentary_max_lufs\": {}, \
170 \"short_term_max_lufs\": {}, \"sample_peak\": {}, \"sample_peak_dbfs\": {}, \
171 \"peak_note\": \"{}\", \"momentary\": {}, \"short_term\": {} }}",
172 maybe(l.integrated_lufs),
173 maybe(l.range_lu),
174 maybe(l.momentary_max_lufs),
175 maybe(l.short_term_max_lufs),
176 num(l.sample_peak),
177 maybe(l.sample_peak_dbfs),
178 escape(l.peak_note),
179 frames(&l.momentary),
180 frames(&l.short_term)
181 )
182}
183
184fn crest_json(c: &Crest) -> String {
185 let band = |b: &BandCrest| {
186 format!(
187 "\n {{ \"lo_hz\": {}, \"hi_hz\": {}, \"centre_hz\": {}, \"peak\": {}, \
188 \"rms\": {}, \"crest_db\": {}, \"counted\": {} }}",
189 num(b.lo_hz),
190 num(b.hi_hz),
191 num(b.centre_hz),
192 num(b.peak),
193 num(b.rms),
194 num(b.crest_db),
195 b.counted
196 )
197 };
198 format!(
199 "{{ \"broadband_crest_db\": {}, \"spread_db\": {}, \"widest_band_hz\": {}, \
200 \"tightest_band_hz\": {}, \"counted_under_db\": {}, \"bands\": {} }}",
201 num(c.broadband_crest_db),
202 maybe(c.spread_db),
203 maybe(c.widest_band_hz),
204 maybe(c.tightest_band_hz),
205 num(c.counted_under_db),
206 list(&c.bands, band)
207 )
208}
209
210fn alias_json(a: &Alias) -> String {
213 let band = |b: &AliasBand| {
214 format!(
215 "\n {{ \"lo_hz\": {}, \"hi_hz\": {}, \"signal_db\": {}, \"alias_db\": {}, \
216 \"nmr_db\": {} }}",
217 num(b.lo_hz),
218 num(b.hi_hz),
219 num(b.signal_db),
220 num(b.alias_db),
221 num(b.nmr_db)
222 )
223 };
224 format!(
225 "{{ \"oversample\": {}, \"sample_rate\": {}, \"frame_size\": {}, \"frames\": {}, \
226 \"scored_frames\": {}, \"playback_db_spl\": {}, \"asr_db\": {}, \"nmr_db\": {}, \
227 \"nmr_peak_db\": {}, \"peak_at_secs\": {}, \"audible\": {}, \"rate_dependent\": {}, \
228 \"instances\": {}, \"bands\": {} }}",
229 a.oversample,
230 num(a.sample_rate),
231 a.frame_size,
232 a.frames,
233 a.scored_frames,
234 num(a.playback_db_spl),
235 num(a.asr_db),
236 num(a.nmr_db),
237 num(a.nmr_peak_db),
238 num(a.peak_at_secs),
239 a.audible,
240 a.rate_dependent,
241 a.instances,
242 list(&a.bands, band)
243 )
244}
245
246fn binding_json(b: &Binding) -> String {
247 format!(
248 "\n {{ \"name\": \"{}\", \"source\": \"{}\" }}",
249 escape(&b.name),
250 escape(&b.source)
251 )
252}
253
254fn arguments_json(a: &Arguments) -> String {
255 let at = |s: sva_ast::ByteSpan| format!("{{ \"start\": {}, \"end\": {} }}", s.start, s.end);
256 let calls = list(&a.calls, |c| {
257 let arguments = list(&c.arguments, |x| {
258 format!(
259 "{{ \"name\": \"{}\", \"value\": {}, \"written\": {} }}",
260 escape(&x.name),
261 num(x.value),
262 x.written
263 )
264 });
265 format!(
266 "\n {{ \"name\": \"{}\", \"at\": {}, \"arguments\": {arguments} }}",
267 escape(&c.name),
268 at(c.at)
269 )
270 });
271 let chosen = list(&a.chosen, |c| {
272 format!(
273 "\n {{ \"name\": \"{}\", \"at\": {}, \"operands\": {}, \"chosen\": {} }}",
274 escape(&c.name),
275 at(c.at),
276 list(&c.operands, |v| num(*v)),
277 c.chosen
278 )
279 });
280 format!(
281 "\n {{ \"node\": \"{}\", \"calls\": {calls}, \"chosen\": {chosen} }}",
282 escape(&a.node)
283 )
284}
285
286fn samples_json(b: &Buffer, limit: Option<usize>) -> String {
288 let component = |c: usize| {
289 let plane = b.plane(c);
290 let shown = limit.map_or(plane.len(), |cap| plane.len().min(cap));
291 format!(
292 "\n {{ \"channel\": {c}, \"values\": {} }}",
293 capped(
294 plane,
295 shown,
296 |n| b.origin_secs + n as f64 / f64::from(b.rate),
297 |v| num(*v)
298 )
299 )
300 };
301 let components: Vec<usize> = (0..b.width).collect();
302 format!(
303 "{{ \"rate\": {}, \"origin_secs\": {}, \"width\": {}, \"components\": {} }}",
304 b.rate,
305 num(b.origin_secs),
306 b.width,
307 list(&components, |c| component(*c))
308 )
309}
310
311fn symbolic_json(n: &SpectralSum) -> String {
312 let terms: Vec<String> = n.atoms().map(sva_engine::sketch_atom).collect();
313 format!(
314 "{{ \"var\": \"{}\", \"lanes\": {}, \"terms\": {} }}",
315 match n.var {
316 sva_engine::Var::T => "t",
317 sva_engine::Var::F => "f",
318 },
319 n.lanes.len(),
320 crate::json::strings(&terms)
321 )
322}
323
324fn flops_json(tree: &sva_engine::FlopTree) -> String {
326 format!(
327 "{{ \"total\": {}, \"budget\": {}, \"rows\": {} }}",
328 tree.total,
329 tree.budget,
330 list(&tree.rows, |r: &sva_engine::FlopRow| format!(
331 "\n {{ \"depth\": {}, \"node\": \"{}\", \"own\": {}, \"subtree\": {}, \
332 \"percent\": {}, \"route\": \"{}\", \"shared\": {} }}",
333 r.depth,
334 escape(&r.node),
335 r.own,
336 r.subtree,
337 num(r.percent),
338 escape(r.route),
339 r.shared
340 ))
341 )
342}
343
344pub fn value_json(output: &Output, limit: Option<usize>, skim: bool) -> String {
347 match output {
348 Output::Lines(lines) => list(lines, line_json),
349 Output::Atoms(sketches) => crate::json::strings(sketches),
350 Output::Symbolic(sum) => symbolic_json(sum),
351 Output::Samples(buffer) => samples_json(buffer, limit),
352 Output::Ledger(entries) => ledger_json(entries, skim),
353 Output::Spectrum(s) => spectrum_json(s),
354 Output::Stereo(image) => stereo_json(image),
355 Output::Bands(b) => bands_json(b, limit),
356 Output::Loudness(l) => loudness_json(l, limit),
357 Output::Crest(c) => crest_json(c),
358 Output::Alias(a) => alias_json(a),
359 Output::Bindings(b) => list(b, binding_json),
360 Output::Arguments(a) => list(a, arguments_json),
361 Output::Flops(tree) => flops_json(tree),
362 Output::Envelope(frames) => list(frames, |f: &EnvelopeFrame| {
363 format!(
364 "\n {{ \"t\": {}, \"rms\": {}, \"peak\": {} }}",
365 num(f.t_secs),
366 num(f.rms),
367 num(f.peak)
368 )
369 }),
370 Output::Pitch(frames) => list(frames, |f| {
371 format!(
372 "\n {{ \"t\": {}, \"notes\": {} }}",
373 num(f.t_secs),
374 list(&f.notes, |n| format!(
375 "{{ \"note\": \"{}\", \"hz\": {}, \"cents\": {}, \"db\": {}, \
376 \"harmonic_of\": {} }}",
377 escape(&n.name),
378 num(n.hz),
379 num(n.cents),
380 num(n.db),
381 maybe(n.harmonic_of)
382 ))
383 )
384 }),
385 Output::Formants(frames) => list(frames, formants_json),
386 }
387}
388
389fn line_json(l: &sva_engine::Line) -> String {
390 format!(
391 "\n {{ \"hz\": {}, \"re\": {}, \"im\": {}, \"db\": {} }}",
392 num(l.hz),
393 num(l.amp.re),
394 num(l.amp.im),
395 num(20.0 * l.amp.abs().log10())
396 )
397}
398
399pub fn answer_json(answer: &Answer, limit: Option<usize>, skim: bool) -> String {
403 format!(
404 "{{ \"source\": \"{}\", \"profile\": \"{}\", \"rate\": {}, \"value\": {}, \
405 \"dropped\": {}, \"tail_db\": {} }}",
406 match answer.source {
407 Source::Exact => "exact",
408 Source::Measured => "measured",
409 },
410 escape(answer.profile),
411 answer
412 .rate
413 .map_or_else(|| NONE.to_string(), |r| r.to_string()),
414 value_json(&answer.value, limit, skim),
415 list(&answer.dropped, line_json),
416 maybe(answer.tail_db)
417 )
418}
419
420fn detail_json(detail: &Detail) -> String {
422 match detail {
423 Detail::Lines {
424 placed,
425 summed,
426 dropped,
427 dropped_more,
428 terms,
429 tail_db,
430 ..
431 } => format!(
432 ", \"placed\": {placed}, \"summed\": {summed}, \"dropped\": {}, \
433 \"dropped_more\": {dropped_more}, \"terms\": {}, \"tail_db\": {}",
434 list(dropped, |d| format!(
435 "{{ \"hz\": {}, \"db\": {} }}",
436 num(d.hz),
437 num(d.db)
438 )),
439 counted(*terms),
440 maybe(*tail_db)
441 ),
442 Detail::Cropped { tail_db, .. } => format!(", \"tail_db\": {}", maybe(*tail_db)),
443 Detail::Point { alias_db, .. } => format!(", \"alias_db\": {}", maybe(*alias_db)),
444 Detail::Spectrum { wrap_db, .. } => format!(", \"wrap_db\": {}", num(*wrap_db)),
445 Detail::Roundtrip { edited, .. } => format!(", \"edited\": {edited}"),
446 Detail::Continuous { .. } | Detail::Reading { .. } => String::new(),
447 Detail::Added { parts } => format!(
448 ", \"addends\": {}",
449 list(parts, |part| format!(
450 "{{ \"rule\": \"{}\"{} }}",
451 part.rule().as_str(),
452 detail_json(part)
453 ))
454 ),
455 }
456}
457
458pub fn label_json(label: &Label) -> String {
461 let detail = detail_json(&label.detail);
462 let cost = match label.cost {
463 Some(Cost { flops, budget }) => format!(", \"flops\": {flops}, \"flop_budget\": {budget}"),
464 None => format!(", \"flops\": {NONE}, \"flop_budget\": {NONE}"),
465 };
466 format!(
467 "{{ \"source\": \"{}\", \"profile\": \"{}\", \"rate\": {}, \"rule\": \"{}\"{detail}{cost} }}",
468 match label.source {
469 Source::Exact => "exact",
470 Source::Measured => "measured",
471 },
472 escape(label.profile),
473 label.rate,
474 escape(label.rule().as_str())
475 )
476}
477
478pub fn work_json(work: &Work) -> String {
480 let waves = work.waves.map_or(NONE.to_string(), |w| w.to_string());
481 format!(
482 "{{ \"samples\": {}, \"proofs\": {}, \"priced_flops\": {}, \"waves\": {waves} }}",
483 work.samples, work.proofs, work.priced_flops
484 )
485}
486
487pub fn stats_json(stats: &CacheStats) -> String {
490 let lookups = list(&stats.lookups, |l| {
491 let outcome = match l.outcome {
492 Outcome::Hit => "hit",
493 Outcome::ComputedStored => "computed_stored",
494 Outcome::ComputedNotStored => "computed_not_stored",
495 Outcome::ComputedReplaced => "computed_replaced",
496 };
497 format!(
498 "{{ \"node\": \"{}\", \"key\": \"{}\", \"kind\": \"{}\", \"outcome\": \"{outcome}\" }}",
499 escape(&l.node),
500 l.key,
501 match l.kind {
502 PayloadKind::Samples => "samples",
503 PayloadKind::Frames => "frames",
504 PayloadKind::Symbolic => "symbolic",
505 }
506 )
507 });
508 format!(
509 "{{ \"nodes\": {}, \"hits\": {}, \"computed\": {}, \"stored\": {}, \"replaced\": {}, \
510 \"bytes\": {}, \"max_bytes\": {}, \"entries\": {}, \"evictions\": {}, \
511 \"lookups\": {lookups} }}",
512 stats.nodes(),
513 stats.hits(),
514 stats.computed(),
515 stats.stored(),
516 stats.replaced(),
517 stats.bytes,
518 stats.max_bytes,
519 stats.entries,
520 stats.evictions
521 )
522}
523
524pub struct Report<'a> {
526 pub target: &'a str,
527 pub rate: u32,
528 pub horizon: Horizon,
529 pub profile: &'a str,
530 pub label: Option<&'a Label>,
531 pub written: &'a [(String, &'a Path)],
532 pub answers: &'a [(String, Answer)],
533 pub analyses: &'a [(String, String)],
536 pub limit: Option<usize>,
537 pub skim: bool,
538}
539
540pub fn query_data(report: &Report) -> String {
542 let written = list(report.written, |(name, path)| {
543 format!(
544 "{{ \"as\": \"{}\", \"path\": \"{}\" }}",
545 escape(name),
546 escape(&path.display().to_string())
547 )
548 });
549 let label = report
550 .label
551 .map(label_json)
552 .unwrap_or_else(|| NONE.to_string());
553 let reads = report
554 .answers
555 .iter()
556 .map(|(name, answer)| {
557 format!(
558 "\"{}\": {}",
559 escape(name),
560 answer_json(answer, report.limit, report.skim)
561 )
562 })
563 .chain(report.analyses.iter().map(|(name, value)| {
564 format!(
565 "\"{}\": {{ \"source\": \"measured\", \"profile\": \"{}\", \"rate\": {}, \
566 \"value\": {value} }}",
567 escape(name),
568 escape(report.profile),
569 report.rate
570 )
571 }))
572 .collect::<Vec<_>>()
573 .join(",\n ");
574 let tail = match reads.is_empty() {
575 true => String::new(),
576 false => format!(",\n {reads}"),
577 };
578 format!(
579 "{{\n \"target\": \"{}\",\n \"sample_rate\": {},\n \"profile\": \"{}\",\n \
580 \"window\": {{ \"start_secs\": {}, \"end_secs\": {} }},\n \"label\": {label},\n \
581 \"written\": {written}{tail}\n}}",
582 escape(report.target),
583 report.rate,
584 escape(report.profile),
585 num(report.horizon.start_secs),
586 num(report.horizon.end_secs)
587 )
588}