fm-vector 0.1.0

A notation program's PDF read from its vectors: every notehead, stem, beam and barline where the engraver put it, read into .fmn and compiled to MusicXML, with the words from the PDF's text. No model, no server: it runs in the browser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
//! A reading checked against its own page, with no answer key (docs/quality.md, "The audit").
//!
//! The measure of notes says nothing of the marks that are not notes, and a PDF from the library
//! has no key to score against. Two things can still be told from the PDF and its reading alone:
//!
//! - **What is printed is what is written.** Each pedal sign, dynamic, fermata, articulation,
//!   ornament, breath and ottava sign is a glyph of the music font: they are counted where they
//!   stand, a system at a time, and so are the marks the `.fmn` writes in that system's bars.
//!   Three printed and five written is a mark written twice, three and one a mark lost.
//! - **Readings that cannot be right.** A pedal written on two staves where one is printed, or on
//!   a voice's staff; a pedal let up that was never down; the same dynamic in one bar on both
//!   staves of a piano where one is printed; a slur or hairpin closed that was never opened, or
//!   never closed; a pedal, dynamic or hairpin on a staff that has no note in that bar.
//!
//! Each finding has a weight, and a bar's, a system's and the PDF's suspicion are the sums: a
//! person looks at the worst systems first (`tools/proof`).

use std::collections::{BTreeMap, BTreeSet};

use crate::page::{Glyph, Page};
use crate::read::{Reading, Refusal};
use crate::review::BarPlace;
use crate::smufl;

/// The kinds counted, printed and written.
pub const KINDS: [&str; 11] = [
    "pedal down",
    "pedal up",
    "dynamic",
    "fermata",
    "staccato",
    "accent",
    "tenuto",
    "marcato",
    "ornament",
    "breath",
    "ottava",
];

/// A bar's findings.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BarAudit {
    /// The bar's label, as in the `.fmn`.
    pub bar: String,
    /// `[x0, y0, x1, y1]` in page points from the top left.
    pub frame: [f64; 4],
    pub score: f64,
    pub reasons: Vec<String>,
}

/// A system's findings: its bars', and the counts that do not agree over the whole system.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SystemAudit {
    /// From 0.
    pub system: usize,
    /// From 0.
    pub page: usize,
    /// `[x0, y0, x1, y1]`: its bars' frames, joined.
    pub frame: [f64; 4],
    pub bars: Vec<BarAudit>,
    /// Its bars' scores and its own reasons' weights.
    pub score: f64,
    pub reasons: Vec<String>,
    /// Per kind (as [`KINDS`]): the marks printed in it, and written in its bars.
    pub printed: [usize; 11],
    pub written: [usize; 11],
    /// Whether the counts were compared (not where a staff's bar of it was left unread).
    pub counted: bool,
}

/// A PDF's reading and what is suspect in it.
#[derive(Clone, Debug)]
pub struct Audit {
    pub reading: Reading,
    pub systems: Vec<SystemAudit>,
    /// The systems' scores, summed.
    pub score: f64,
    /// Each kind of finding and how many bars or systems have it.
    pub findings: BTreeMap<String, usize>,
    /// The pages' sizes, in points.
    pub pages: Vec<[f64; 2]>,
}

/// Read a PDF and audit the reading.
pub fn audit_pdf(bytes: &[u8]) -> Result<Audit, Refusal> {
    let pages = crate::page::read_pages(bytes).map_err(|why| Refusal { system: None, why })?;
    let review = crate::review::read_pdf_review(bytes)?;
    Ok(audit(
        &pages,
        review.reading,
        &review.bars,
        review.pages.clone(),
    ))
}

/// A mark printed: its kind (an index into [`KINDS`]) and where it stands.
struct Printed {
    kind: usize,
    page: usize,
    x: f64,
    y: f64,
}

fn kind_of_glyph(code: u32) -> Option<usize> {
    let k = |name: &str| KINDS.iter().position(|&n| n == name);
    match code {
        0xE650 | 0xE651 => k("pedal down"),
        0xE655 => k("pedal up"),
        0xE510..=0xE516 | 0xE51C | 0xE51D => k("ottava"),
        0xE4CE | 0xE4CF => k("breath"),
        0xE566 | 0xE567 | 0xE568 | 0xE56C | 0xE56D => k("ornament"),
        _ if smufl::fermata(code).is_some() => k("fermata"),
        _ => match smufl::articulation(code) {
            Some("-.") => k("staccato"),
            Some("->") => k("accent"),
            Some("-_") => k("tenuto"),
            Some("-^") => k("marcato"),
            _ => None,
        },
    }
}

/// The marks printed on the pages. A dynamic's letters set side by side are one mark, and so
/// are an ottava's `8` and its `va`.
fn printed_marks(pages: &[Page]) -> Vec<Printed> {
    let dynamic = KINDS.iter().position(|&n| n == "dynamic").unwrap_or(0);
    let ottava = KINDS.iter().position(|&n| n == "ottava").unwrap_or(0);
    let mut out = Vec::new();
    for (pi, pg) in pages.iter().enumerate() {
        // (`(Ped.)` in the pedal's parentheses is the pedal still down, shown again at a
        // system's start: no mark of its own)
        // (nor is a pedal's sign at the size of words, set in a line of them)
        let again = |g: &Glyph| {
            let pedal = matches!(g.code, 0xE650 | 0xE651 | 0xE655 | 0xE656);
            (pedal && g.size <= 0.6 * pg.size)
                || (matches!(g.code, 0xE650 | 0xE651)
                    && pg.glyphs.iter().any(|p| {
                        p.code == 0xE676
                            && (p.y - g.y).abs() < 0.1 * g.size.max(4.0)
                            && (g.x0 - p.x1).abs() < 0.25 * g.size.max(4.0)
                    }))
        };
        let mut run: Vec<(&Glyph, usize)> = (pg.glyphs.iter())
            .filter(|g| !again(g))
            .filter_map(|g| {
                if smufl::dynamic_text(g.code).is_some() {
                    Some((g, dynamic))
                } else {
                    kind_of_glyph(g.code).map(|k| (g, k))
                }
            })
            .collect();
        run.sort_by(|a, b| (a.1, a.0.x0).partial_cmp(&(b.1, b.0.x0)).unwrap());
        let mut last: Option<(&Glyph, usize)> = None;
        for (g, k) in run {
            let joined = (k == dynamic || k == ottava)
                && last.is_some_and(|(p, pk)| {
                    pk == k
                        && g.x0 - p.x1 < 0.35 * g.size.max(4.0)
                        && (g.y - p.y).abs() < 0.3 * g.size.max(4.0)
                });
            if !joined {
                out.push(Printed {
                    kind: k,
                    page: pi,
                    x: g.x0,
                    y: g.y,
                });
            }
            last = Some((g, k));
        }
    }
    out
}

/// A staff's bar as written: its marks counted, and what its lines hold.
#[derive(Clone, Debug, Default)]
struct Written {
    counts: [usize; 11],
    /// The dynamics, as written (`p`, `mf`).
    dynamics: Vec<String>,
    notes: usize,
    /// In order: the pedal's marks, the hairpins' and the slurs' opens and closes.
    events: Vec<Event>,
}

#[derive(Clone, Debug, PartialEq)]
enum Event {
    PedalDown,
    PedalChange,
    PedalUp,
    HairpinOpen(u8),
    HairpinClose(u8),
    SlurOpen,
    SlurClose,
}

/// The tokens of a line of music: split at spaces, but not inside a chord's `<...>` or a
/// quoted text.
fn tokens(line: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let (mut start, mut quote, mut chord) = (None, false, false);
    let b = line.as_bytes();
    for (i, &c) in b.iter().enumerate() {
        if start.is_none() && !c.is_ascii_whitespace() {
            start = Some(i);
            chord = c == b'<';
        }
        match c {
            b'"' => quote = !quote,
            b'>' if chord && !quote => chord = false,
            _ => {}
        }
        if c.is_ascii_whitespace() && !quote && !chord {
            if let Some(s) = start.take() {
                out.push(&line[s..i]);
            }
        }
    }
    if let Some(s) = start {
        out.push(&line[s..]);
    }
    out
}

fn kind(name: &str) -> usize {
    KINDS.iter().position(|&n| n == name).unwrap_or(0)
}

/// A line of music's tokens added to its staff's bar.
fn write_line(w: &mut Written, line: &str) {
    for tok in tokens(line) {
        if let Some(body) = tok.strip_prefix('\\') {
            let number = |s: &str| s.parse::<u8>().unwrap_or(1);
            if body == "ped" {
                w.counts[kind("pedal down")] += 1;
                w.events.push(Event::PedalDown);
            } else if body == "ped*" {
                w.counts[kind("pedal up")] += 1;
                w.events.push(Event::PedalUp);
            } else if body == "ped^" {
                w.events.push(Event::PedalChange);
            } else if let Some(n) = body.strip_prefix('<').or(body.strip_prefix('>')) {
                w.events.push(Event::HairpinOpen(number(n)));
            } else if let Some(n) = body.strip_prefix('!') {
                w.events.push(Event::HairpinClose(number(n)));
            } else if ["8va", "8vb", "15ma", "15mb"]
                .iter()
                .any(|o| body == *o || body.strip_suffix(":voice") == Some(o))
            {
                w.counts[kind("ottava")] += 1;
            } else if !body.is_empty() && body.chars().all(|c| "pmfszrn".contains(c)) {
                w.counts[kind("dynamic")] += 1;
                w.dynamics.push(body.to_string());
            }
            continue;
        }
        if tok.starts_with("^\"") || tok.starts_with("_\"") || tok.starts_with('"') {
            continue;
        }
        let first = tok.chars().next().unwrap_or(' ');
        if first == '<' || (('a'..='g').contains(&first) && tok.contains('/')) {
            w.notes += 1;
        }
        // (the marks after the note: past a chord's own `>`)
        let tail = match (first == '<', tok.find('>')) {
            (true, Some(i)) => &tok[i + 1..],
            _ => tok,
        };
        for c in tok.chars() {
            match c {
                '(' => w.events.push(Event::SlurOpen),
                ')' => w.events.push(Event::SlurClose),
                _ => {}
            }
        }
        let mut rest = tail;
        while let Some(i) = rest.find('-') {
            rest = &rest[i + 1..];
            let named = [
                ("fermatabelow", "fermata"),
                ("shortfermata", "fermata"),
                ("longfermata", "fermata"),
                ("fermata", "fermata"),
                ("breath", "breath"),
                ("turn", "ornament"),
                ("tr", "ornament"),
                ("prall", "ornament"),
                ("mordent", "ornament"),
                (".", "staccato"),
                (">", "accent"),
                ("_", "tenuto"),
                ("^", "marcato"),
            ];
            if let Some((_, k)) = named
                .iter()
                .find(|(n, _)| rest.starts_with(n) && !(*n == "tr" && rest.starts_with("trem")))
            {
                w.counts[kind(k)] += 1;
            }
        }
    }
}

/// The `.fmn` as the audit needs it: the parts that are a voice's and a piano's, and per bar
/// (in order) each staff's marks.
struct Fmn {
    voices: BTreeSet<String>,
    pianos: BTreeSet<String>,
    bars: Vec<(String, BTreeMap<String, Written>)>,
}

fn parse_fmn(fmn: &str) -> Fmn {
    let mut out = Fmn {
        voices: BTreeSet::new(),
        pianos: BTreeSet::new(),
        bars: Vec::new(),
    };
    for line in fmn.lines() {
        if let Some(rest) = line.strip_prefix("part ") {
            let id = rest.split_whitespace().next().unwrap_or("").to_string();
            if rest.ends_with(" voice") {
                out.voices.insert(id);
            } else if rest.ends_with(" piano") {
                out.pianos.insert(id);
            }
        } else if let Some(rest) = line.strip_prefix("bar ") {
            let label = rest.split_whitespace().next().unwrap_or("").to_string();
            out.bars.push((label, BTreeMap::new()));
        } else if let (Some((head, music)), Some(bar)) =
            (line.split_once(": "), out.bars.last_mut())
        {
            // (`P.1/2: ...` is the staff P.1's second voice; `V lyrics: ...` is no music)
            if head.contains(' ') || head.is_empty() {
                continue;
            }
            let staff = head.split('/').next().unwrap_or(head).to_string();
            write_line(bar.1.entry(staff).or_default(), music);
        }
    }
    out
}

fn part_of(staff: &str) -> &str {
    staff.split('.').next().unwrap_or(staff)
}

/// The audit of a reading: `pages` the PDF's, `places` where each bar of it stands.
pub(crate) fn audit(
    pages: &[Page],
    reading: Reading,
    places: &[BarPlace],
    sizes: Vec<[f64; 2]>,
) -> Audit {
    let fmn = parse_fmn(&reading.fmn);
    let unread: BTreeSet<String> = reading.unread.iter().map(|u| u.bar.to_string()).collect();
    // the systems, each with its bars
    let mut systems: Vec<SystemAudit> = Vec::new();
    for p in places {
        if systems.last().is_none_or(|s| s.system != p.system) {
            systems.push(SystemAudit {
                system: p.system,
                page: p.page,
                frame: p.frame,
                counted: true,
                ..Default::default()
            });
        }
        let s = systems.last_mut().unwrap();
        s.frame = [
            s.frame[0].min(p.frame[0]),
            s.frame[1].min(p.frame[1]),
            s.frame[2].max(p.frame[2]),
            s.frame[3].max(p.frame[3]),
        ];
        s.counted &= !unread.contains(&p.bar);
        s.bars.push(BarAudit {
            bar: p.bar.clone(),
            frame: p.frame,
            ..Default::default()
        });
    }
    let at: BTreeMap<String, (usize, usize)> = (systems.iter().enumerate())
        .flat_map(|(si, s)| {
            (s.bars.iter().enumerate()).map(move |(bi, b)| (b.bar.clone(), (si, bi)))
        })
        .collect();
    let mut found: Vec<(usize, Option<usize>, f64, String)> = Vec::new(); // system, bar, weight, why

    // 1. what is printed, by system and bar
    let mut printed_bar: BTreeMap<(usize, usize), [usize; 11]> = BTreeMap::new();
    let pedal = |k: usize| KINDS[k].starts_with("pedal");
    for m in printed_marks(pages) {
        // the system it stands nearest (in, over or under), on its page; a mark far from every
        // system (a title's, a legend's) is none's. A pedal's sign is the system's it stands
        // under, however far under and however near the next
        let near = (systems.iter().enumerate())
            .filter(|(_, s)| s.page == m.page && s.frame[0] - 40.0 < m.x && m.x < s.frame[2] + 20.0)
            .filter(|(_, s)| !pedal(m.kind) || s.frame[1] < m.y)
            .map(|(i, s)| {
                let d = if m.y < s.frame[1] {
                    s.frame[1] - m.y
                } else {
                    (m.y - s.frame[3]).max(0.0)
                };
                (if pedal(m.kind) { m.y - s.frame[1] } else { d }, d, i)
            })
            .min_by(|a, b| a.0.total_cmp(&b.0));
        let Some((_, d, si)) = near else { continue };
        let s = &mut systems[si];
        if !pedal(m.kind) && d > 0.6 * (s.frame[3] - s.frame[1]).max(60.0) {
            continue;
        }
        s.printed[m.kind] += 1;
        let bi = (s.bars.iter())
            .position(|b| m.x < b.frame[2])
            .unwrap_or(s.bars.len() - 1);
        printed_bar.entry((si, bi)).or_insert([0; 11])[m.kind] += 1;
    }

    // 2. what is written, and the readings that cannot be right
    let mut pedal_down: BTreeMap<String, bool> = BTreeMap::new();
    let mut hairpins: BTreeMap<(String, u8), (usize, usize)> = BTreeMap::new();
    let mut slurs: BTreeMap<String, Vec<(usize, usize)>> = BTreeMap::new();
    let dynamic = kind("dynamic");
    let down = kind("pedal down");
    for (label, staves) in &fmn.bars {
        let Some(&(si, bi)) = at.get(label) else {
            continue;
        };
        let here = printed_bar.get(&(si, bi)).copied().unwrap_or([0; 11]);
        let whole = systems[si].printed;
        let mut written = [0usize; 11];
        for w in staves.values() {
            for (k, n) in w.counts.iter().enumerate() {
                written[k] += n;
                systems[si].written[k] += n;
            }
        }
        // a pedal printed once and written on two staves
        let with_pedal: Vec<&String> = (staves.iter())
            .filter(|(_, w)| w.counts[down] > 0)
            .map(|(s, _)| s)
            .collect();
        if with_pedal.len() > 1 && written[down] > here[down] {
            found.push((
                si,
                Some(bi),
                3.0,
                format!(
                    "pedal on {} staves ({}), {} printed in the bar",
                    with_pedal.len(),
                    with_pedal
                        .iter()
                        .map(|s| s.as_str())
                        .collect::<Vec<_>>()
                        .join(" "),
                    here[down]
                ),
            ));
        }
        for (staff, w) in staves {
            let pedal = w
                .events
                .iter()
                .any(|e| matches!(e, Event::PedalDown | Event::PedalChange | Event::PedalUp));
            if pedal && fmn.voices.contains(part_of(staff)) {
                found.push((
                    si,
                    Some(bi),
                    3.0,
                    format!("pedal on a voice's staff ({staff})"),
                ));
            }
            let opens = (w.events.iter()).any(|e| matches!(e, Event::HairpinOpen(_)));
            if w.notes == 0 && (pedal || opens || !w.dynamics.is_empty()) {
                let what = [
                    (pedal, "pedal"),
                    (!w.dynamics.is_empty(), "dynamic"),
                    (opens, "hairpin"),
                ];
                let what: Vec<&str> = what.iter().filter(|x| x.0).map(|x| x.1).collect();
                found.push((
                    si,
                    Some(bi),
                    if pedal { 2.0 } else { 1.0 },
                    format!(
                        "{} on {staff}, which has no note in the bar",
                        what.join(", ")
                    ),
                ));
            }
            // (a staff's voices are written a line each, so the order of a bar's marks across
            // them is not known: the bar's opens and closes are balanced, not followed)
            let n = |e: &Event| w.events.iter().filter(|x| *x == e).count();
            let (downs, ups, changes) = (
                n(&Event::PedalDown),
                n(&Event::PedalUp),
                n(&Event::PedalChange),
            );
            let was = usize::from(pedal_down.get(staff).copied().unwrap_or(false));
            if ups > was + downs || (changes > 0 && was + downs == 0) {
                found.push((
                    si,
                    Some(bi),
                    2.0,
                    format!("pedal let up on {staff}, which was never down"),
                ));
            }
            let left = (was + downs).saturating_sub(ups);
            if left > 1 {
                found.push((
                    si,
                    Some(bi),
                    1.0,
                    format!("pedal down on {staff}, which was down already"),
                ));
            }
            if downs + ups > 0 {
                pedal_down.insert(staff.clone(), left > 0);
            }
            let numbers: BTreeSet<u8> = (w.events.iter())
                .filter_map(|e| match e {
                    Event::HairpinOpen(k) | Event::HairpinClose(k) => Some(*k),
                    _ => None,
                })
                .collect();
            for k in numbers {
                let key = (staff.clone(), k);
                let (opens, closes) = (n(&Event::HairpinOpen(k)), n(&Event::HairpinClose(k)));
                let was = usize::from(hairpins.contains_key(&key));
                if closes > was + opens {
                    found.push((
                        si,
                        Some(bi),
                        2.0,
                        format!("hairpin closed on {staff} that was never opened"),
                    ));
                }
                let left = (was + opens).saturating_sub(closes);
                if left > 1 {
                    found.push((
                        si,
                        Some(bi),
                        2.0,
                        format!("hairpin opened on {staff} with the one before never closed"),
                    ));
                }
                if left == 0 {
                    hairpins.remove(&key);
                } else if opens > 0 {
                    hairpins.insert(key, (si, bi));
                }
            }
            let open = slurs.entry(staff.clone()).or_default();
            for _ in 0..n(&Event::SlurOpen) {
                open.push((si, bi));
            }
            for _ in 0..n(&Event::SlurClose) {
                // (the oldest open one: a slur closes long before the piece ends)
                if open.is_empty() {
                    found.push((
                        si,
                        Some(bi),
                        2.0,
                        format!("slur closed on {staff} that was never opened"),
                    ));
                } else {
                    open.remove(0);
                }
            }
        }
        // the same dynamic on both staves of a piano, printed once
        let mut by_part: BTreeMap<(&str, &str), Vec<&str>> = BTreeMap::new();
        for (staff, w) in staves {
            let part = part_of(staff);
            if fmn.pianos.contains(part) {
                let seen: BTreeSet<&str> = w.dynamics.iter().map(|d| d.as_str()).collect();
                for d in seen {
                    by_part.entry((part, d)).or_default().push(staff);
                }
            }
        }
        for ((_, d), on) in by_part {
            // (where the page has no dynamic as a glyph, its dynamics are text: not counted)
            if on.len() > 1 && written[dynamic] > here[dynamic] && whole[dynamic] > 0 {
                found.push((
                    si,
                    Some(bi),
                    3.0,
                    format!(
                        "{d} on both staves of a piano ({}), {} dynamic(s) printed in the bar",
                        on.join(" "),
                        here[dynamic]
                    ),
                ));
            }
        }
        // the bar's counts, kept for the system's
        if systems[si].counted {
            for k in 0..KINDS.len() {
                if written[k] != here[k] {
                    systems[si].bars[bi].reasons.push(format!(
                        "\u{1}{k}\u{1}{} printed, {} written",
                        here[k], written[k]
                    ));
                }
            }
        }
    }
    for ((staff, _), (si, bi)) in hairpins {
        found.push((
            si,
            Some(bi),
            2.0,
            format!("hairpin on {staff} never closed"),
        ));
    }
    for (staff, open) in slurs {
        for (si, bi) in open {
            found.push((si, Some(bi), 2.0, format!("slur on {staff} never closed")));
        }
    }

    // 3. the counts: a system's printed marks against its written ones
    let fonts_dynamics = systems.iter().any(|s| s.printed[dynamic] > 0);
    for (si, s) in systems.iter_mut().enumerate() {
        let mut off = [false; 11];
        if s.counted {
            for k in 0..KINDS.len() {
                let (p, w) = (s.printed[k], s.written[k]);
                // (a pedal's line ends in a hook, no glyph, and an ottava's sign is printed
                // again where its line runs on: only a sign not written, only a sign written
                // and not printed is told; dynamics set as text are not glyphs)
                let skip = (KINDS[k] == "pedal up" && w >= p)
                    || (KINDS[k] == "ottava" && w <= p)
                    || (k == dynamic && !fonts_dynamics);
                if p != w && !skip {
                    off[k] = true;
                    found.push((
                        si,
                        None,
                        (p.abs_diff(w) as f64).min(4.0),
                        format!("{}: {p} printed, {w} written", KINDS[k]),
                    ));
                }
            }
        }
        // a bar's own count is told only where its system's is off (a mark at a barline may be
        // counted in the bar beside it)
        for b in &mut s.bars {
            let notes = std::mem::take(&mut b.reasons);
            for n in notes {
                let mut it = n.split('\u{1}');
                let (_, k, text) = (it.next(), it.next(), it.next());
                let k: usize = k.and_then(|k| k.parse().ok()).unwrap_or(0);
                if off[k] {
                    b.reasons
                        .push(format!("{}: {}", KINDS[k], text.unwrap_or("")));
                    b.score += 0.5;
                }
            }
        }
    }

    let mut findings: BTreeMap<String, usize> = BTreeMap::new();
    for (si, bi, weight, why) in found {
        let class = class_of(&why);
        *findings.entry(class).or_default() += 1;
        match bi {
            Some(bi) => {
                let b = &mut systems[si].bars[bi];
                b.score += weight;
                b.reasons.push(why);
            }
            None => {
                systems[si].score += weight;
                systems[si].reasons.push(why);
            }
        }
    }
    for s in &mut systems {
        s.score += s.bars.iter().map(|b| b.score).sum::<f64>();
    }
    Audit {
        score: systems.iter().map(|s| s.score).sum(),
        reading,
        systems,
        findings,
        pages: sizes,
    }
}

/// A finding's kind, for the tally.
fn class_of(why: &str) -> String {
    let named = [
        ("on a voice's staff", "pedal on a voice's staff"),
        ("staves (", "pedal printed once, written on two staves"),
        (
            "which has no note",
            "mark on a staff with no note in the bar",
        ),
        ("was down already", "pedal down twice"),
        ("never down", "pedal up, never down"),
        ("hairpin closed", "hairpin closed, never opened"),
        ("hairpin", "hairpin never closed"),
        ("slur closed", "slur closed, never opened"),
        ("slur", "slur never closed"),
        (
            "both staves",
            "dynamic printed once, written on both staves",
        ),
    ];
    match why.split_once(": ") {
        Some((k, _)) if KINDS.contains(&k) => format!("count: {k}"),
        _ => (named.iter())
            .find(|(has, _)| why.contains(has))
            .map_or("other", |(_, name)| name)
            .to_string(),
    }
}

fn json_str(s: &str) -> String {
    let mut out = String::from("\"");
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

fn json_list(items: &[String]) -> String {
    let quoted: Vec<String> = items.iter().map(|s| json_str(s)).collect();
    format!("[{}]", quoted.join(","))
}

fn json_frame(f: &[f64; 4]) -> String {
    format!("[{:.1},{:.1},{:.1},{:.1}]", f[0], f[1], f[2], f[3])
}

impl Audit {
    /// The audit as JSON, the reading's `.fmn` and MusicXML left out: the PDF's score, its
    /// bars and systems counted, the findings by kind, the marks printed and written by kind,
    /// and every system (its page, frame, score, reasons, and its bars with theirs).
    pub fn to_json(&self) -> String {
        let bars: usize = self.systems.iter().map(|s| s.bars.len()).sum();
        let findings: Vec<String> = (self.findings.iter())
            .map(|(k, n)| format!("{}:{n}", json_str(k)))
            .collect();
        let counts: Vec<String> = (KINDS.iter().enumerate())
            .map(|(k, name)| {
                format!(
                    "{}:[{},{}]",
                    json_str(name),
                    self.systems.iter().map(|s| s.printed[k]).sum::<usize>(),
                    self.systems.iter().map(|s| s.written[k]).sum::<usize>()
                )
            })
            .collect();
        let systems: Vec<String> = (self.systems.iter())
            .map(|s| {
                let bars: Vec<String> = (s.bars.iter())
                    .map(|b| {
                        format!(
                            "{{\"bar\":{},\"frame\":{},\"score\":{:.1},\"reasons\":{}}}",
                            json_str(&b.bar),
                            json_frame(&b.frame),
                            b.score,
                            json_list(&b.reasons)
                        )
                    })
                    .collect();
                format!(
                    "{{\"system\":{},\"page\":{},\"frame\":{},\"score\":{:.1},\"counted\":{},\"reasons\":{},\"bars\":[{}]}}",
                    s.system,
                    s.page,
                    json_frame(&s.frame),
                    s.score,
                    s.counted,
                    json_list(&s.reasons),
                    bars.join(",")
                )
            })
            .collect();
        let pages: Vec<String> = (self.pages.iter())
            .map(|p| format!("[{:.1},{:.1}]", p[0], p[1]))
            .collect();
        format!(
            "{{\"score\":{:.1},\"systems_n\":{},\"bars_n\":{bars},\"unread\":{},\"findings\":{{{}}},\"counts\":{{{}}},\"pages\":[{}],\"systems\":[\n{}\n]}}",
            self.score,
            self.systems.len(),
            self.reading.unread.len(),
            findings.join(","),
            counts.join(","),
            pages.join(","),
            systems.join(",\n")
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_line_is_split_at_spaces_outside_chords_and_texts() {
        assert_eq!(
            tokens("^\"a tempo\" \\mf <c4 e4>/8-.-> r/4 \\ped e4/4("),
            [
                "^\"a tempo\"",
                "\\mf",
                "<c4 e4>/8-.->",
                "r/4",
                "\\ped",
                "e4/4("
            ]
        );
    }

    #[test]
    fn a_line_s_marks_are_counted() {
        let mut w = Written::default();
        write_line(
            &mut w,
            "\\mf <c4 e4>/8-.-> r/4-fermata \\ped e4/4(-tr \\ped* g4/8-trem2) \\< a4/4-_ \\! \\8va",
        );
        let n = |k: &str| w.counts[kind(k)];
        assert_eq!(
            (n("dynamic"), n("staccato"), n("accent"), n("fermata")),
            (1, 1, 1, 1)
        );
        assert_eq!((n("pedal down"), n("pedal up"), n("ornament")), (1, 1, 1));
        assert_eq!((n("tenuto"), n("ottava"), w.notes), (1, 1, 4));
        assert_eq!(w.dynamics, ["mf"]);
        assert!(w.events.contains(&Event::SlurOpen) && w.events.contains(&Event::SlurClose));
    }

    #[test]
    fn a_voice_s_pedal_and_a_staff_with_no_note_are_told() {
        let fmn = parse_fmn(
            "part V \"Voice\" voice\npart P \"Piano\" piano\n\nbar 1 system\nV: R \\ped \\ped*\nV lyrics: la (la)\nP.1: c4/1\nP.2/2: c3/1\n",
        );
        assert!(fmn.voices.contains("V") && fmn.pianos.contains("P"));
        let bar = &fmn.bars[0].1;
        assert_eq!(
            (bar["V"].notes, bar["V"].counts[kind("pedal down")]),
            (0, 1)
        );
        assert_eq!((bar["P.1"].notes, bar["P.2"].notes), (1, 1));
        assert!(bar["V"].events.iter().all(|e| *e != Event::SlurOpen));
    }
}