nord-cli 0.5.0

Command-line tool for Clavia / Nord keyboards — inspect, edit, verify, and transfer programs, samples, and settings
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
//! `nord piano` — the verbs that only mean anything for a piano library.
//!
//! A library is a directory of strokes: one recording per root note, bank and
//! velocity layer, each owning a span of encoded audio. `inspect` reports that
//! directory, `decode` turns one stroke back into a WAV, and `edit`, `trim` and
//! `split` are the transforms `nord_format`'s model can express — renaming,
//! retuning and rerouting keys, dropping banks and layers, narrowing the key range,
//! and cutting a library in two. Nothing here re-encodes audio: a stroke that
//! survives a transform moves byte for byte.
//!
//! A library written here loads on the instrument and plays: confirmed on hardware
//! for `trim`, both for a dropped bank and for dropped velocity layers. What `edit`
//! changes — a name, a key's tuning, the root a key plays — and the narrowed key
//! range `trim --range` and `split` leave behind are inferred from specimens; not
//! confirmed on hardware.
//!
//! These verbs take a file. A library is tens of megabytes, so moving one to or
//! from the instrument is `nord piano get` and `nord piano put`.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use clap::{Args, ValueEnum};
use nord_format::formats::npno::{self, codec, Bank, Change, Layers, Library, UNCOVERED};
use nord_format::Entity;

use crate::edit::write_file;
use crate::note;
use crate::ui::Ui;

/// The banks a trim can drop by name. The attack bank is every library's reason to
/// exist and dropping it would leave silence, so it is not offered.
#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum DroppableBank {
    /// The pedal-down resonance set, which the larger libraries add.
    Resonance,
    /// The note-off sample.
    Release,
}

impl From<DroppableBank> for Bank {
    fn from(bank: DroppableBank) -> Bank {
        match bank {
            DroppableBank::Resonance => Bank::Resonance,
            DroppableBank::Release => Bank::Release,
        }
    }
}

#[derive(Args)]
pub struct InspectArgs {
    /// The piano libraries to report on.
    #[arg(required = true, value_name = "FILE")]
    pub files: Vec<PathBuf>,

    /// List every stroke rather than one line per root.
    #[arg(long)]
    pub strokes: bool,

    /// List every covered key with the root it plays and its fine tune.
    #[arg(long)]
    pub keys: bool,
}

#[derive(Args)]
pub struct DecodeArgs {
    /// The piano library to read.
    #[arg(value_name = "FILE")]
    pub file: PathBuf,

    /// The stroke by its index in the directory. The alternative to `--key`.
    #[arg(long, value_name = "N", conflicts_with = "key")]
    pub stroke: Option<usize>,

    /// A key the library covers: a name (`C4`, `F#3`) or 0-127. Narrow the strokes
    /// it selects with `--layer` and `--bank`.
    #[arg(long, value_name = "KEY")]
    pub key: Option<String>,

    /// Velocity layer, 0 being the loudest recording of the root.
    #[arg(long, value_name = "N", requires = "key")]
    pub layer: Option<u8>,

    #[arg(long, value_enum, requires = "key")]
    pub bank: Option<BankName>,

    /// Where to write the WAV. Frames come out at the rate the instrument plays
    /// them, with no gain applied.
    #[arg(short, long, value_name = "WAV")]
    pub out: PathBuf,
}

#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum BankName {
    Attack,
    Resonance,
    Release,
}

impl From<BankName> for Bank {
    fn from(bank: BankName) -> Bank {
        match bank {
            BankName::Attack => Bank::Attack,
            BankName::Resonance => Bank::Resonance,
            BankName::Release => Bank::Release,
        }
    }
}

#[derive(Args)]
pub struct EditArgs {
    /// The piano library to edit.
    #[arg(value_name = "FILE")]
    pub file: PathBuf,

    /// Rename the library. The name shares a fixed-width field with the variant and
    /// is split from it on a `#`, so a name holding one is refused.
    #[arg(long)]
    pub name: Option<String>,

    /// Replace the variant — the text after the `#`, where the vendor records the
    /// voicing and the library's size. It cannot itself hold a `#`.
    #[arg(long)]
    pub variant: Option<String>,

    /// Replace the voicing, a field of its own that only the newer stream carries.
    #[arg(long)]
    pub voicing: Option<String>,

    /// `KEY=UNITS`, repeatable: retune one key. A bare number is fine-tune units;
    /// a number suffixed with `c` is cents, rounded to the nearest unit.
    #[arg(long = "tune", value_name = "KEY=UNITS")]
    pub tune: Vec<String>,

    /// `KEY=ROOT`, repeatable: play KEY with ROOT's strokes. `KEY=-` uncovers the
    /// key. Both sides take a note name or a number.
    #[arg(long = "map", value_name = "KEY=ROOT")]
    pub map: Vec<String>,

    /// Write the edit here instead of over the input file.
    #[arg(short, long, value_name = "FILE")]
    pub out: Option<PathBuf>,

    /// Confirm the write. Editing a file in place needs it.
    #[arg(long)]
    pub yes: bool,
}

#[derive(Args)]
pub struct TrimArgs {
    /// The piano library to trim.
    #[arg(value_name = "FILE")]
    pub file: PathBuf,

    /// Drop every stroke of one bank. Dropping the resonance set is what turns a
    /// large library into a small one.
    #[arg(long, value_enum, value_name = "BANK")]
    pub drop_bank: Vec<DroppableBank>,

    /// `N` keeps the N loudest layers of each root and bank; `=0,3,7` keeps exactly
    /// those layer values. Surviving layers keep the numbers they had.
    #[arg(long, value_name = "N|=LIST")]
    pub layers: Option<String>,

    /// `LO..HI`, inclusive: uncover every key outside it and drop the roots nothing
    /// plays any more. Both ends take a note name or a number.
    #[arg(long, value_name = "LO..HI")]
    pub range: Option<String>,

    /// Where to write the trimmed library.
    #[arg(short, long, value_name = "FILE")]
    pub out: PathBuf,
}

#[derive(Args)]
pub struct VerifyArgs {
    /// The piano libraries to check.
    #[arg(required = true, value_name = "FILE")]
    pub files: Vec<PathBuf>,

    /// Also decode every stroke, checking each block against the one before it.
    #[arg(long)]
    pub deep: bool,
}

#[derive(Args)]
pub struct SplitArgs {
    /// The piano library to split.
    #[arg(value_name = "FILE")]
    pub file: PathBuf,

    /// The first key of the upper half: a note name or 0-127.
    #[arg(long, value_name = "KEY")]
    pub at: String,

    /// Directory for the two halves, named after the input.
    #[arg(short, long, value_name = "DIR")]
    pub out: PathBuf,
}

/// Read a file and parse it as a piano library, naming the format it turned out to
/// be when it is not one.
fn read(path: &Path) -> Result<(Vec<u8>, npno::Piano), String> {
    let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
    let entity = nord_format::from_stream(&mut std::io::Cursor::new(&bytes))
        .map_err(|e| format!("{}: {e}", path.display()))?;
    match entity {
        Entity::Piano(piano) => Ok((bytes, piano)),
        other => Err(format!(
            "{}: this is a {}, not a piano library (.npno)",
            path.display(),
            entity_kind(&other)
        )),
    }
}

fn entity_kind(entity: &Entity) -> &'static str {
    match entity {
        Entity::Sample(_) => "sample instrument",
        Entity::SampleProject(_) => "Sample Editor project",
        Entity::Program(_) => "program",
        Entity::Live(_) => "live slot",
        Entity::Settings(_) => "settings file",
        _ => "file of another format",
    }
}

/// A trim or a split writes a new library; overwriting the one it reads would
/// leave nothing to compare against, and no flag says that was meant.
fn refuse_in_place(input: &Path, output: &Path) -> Result<(), String> {
    let same = |a: &Path, b: &Path| match (a.canonicalize(), b.canonicalize()) {
        (Ok(a), Ok(b)) => a == b,
        _ => a == b,
    };
    if same(input, output) {
        return Err(format!(
            "{} is the input; give -o another path",
            output.display()
        ));
    }
    Ok(())
}

fn to_bytes(library: &Library<'_>, path: &Path) -> Result<Vec<u8>, String> {
    library
        .to_piano()
        .and_then(|piano| nord_format::to_bytes(&Entity::Piano(piano)))
        .map_err(|e| format!("{}: {e}", path.display()))
}

/// `KEY=VALUE`, with the key as a note.
fn split_pair<'a>(spec: &'a str, flag: &str) -> Result<(u8, &'a str), String> {
    let (key, value) = spec
        .split_once('=')
        .ok_or_else(|| format!("--{flag} takes KEY=VALUE, got {spec:?}"))?;
    Ok((note::parse(key)?, value.trim()))
}

pub fn inspect(ui: &Ui, args: InspectArgs) -> Result<(), String> {
    let mut failed = 0usize;
    for (i, path) in args.files.iter().enumerate() {
        if i > 0 {
            ui.out("");
        }
        ui.out(ui.bold(path.display()));
        match inspect_one(ui, path, &args) {
            Ok(()) => {}
            Err(e) => {
                failed += 1;
                ui.note(format!("  {} {e}", ui.danger("error")));
            }
        }
    }
    match failed {
        0 => Ok(()),
        n => Err(format!("{n} of {} file(s) did not read", args.files.len())),
    }
}

fn inspect_one(ui: &Ui, path: &Path, args: &InspectArgs) -> Result<(), String> {
    let (bytes, piano) = read(path)?;
    let library = piano.library().map_err(|e| e.to_string())?;
    let (name, variant) = library.name();

    let covered = covered_keys(&library);
    let coverage = match (covered.first(), covered.last()) {
        (Some(&lo), Some(&hi)) => format!(
            "{}..{} ({} keys)",
            note::name(lo),
            note::name(hi),
            covered.len()
        ),
        _ => "none".to_string(),
    };
    let title = if variant.is_empty() {
        name
    } else {
        format!("{name} ({variant})")
    };
    ui.out(format!(
        "  {title}  stream {:#06x}  {} channel(s)  {} bytes",
        library.stream_version(),
        library.channels(),
        bytes.len(),
    ));
    if let (Some(long), Some(voicing)) = (library.long_name(), library.voicing()) {
        ui.out(ui.dim(format!("  long name {long:?}, voicing {voicing:?}")));
    }
    ui.out(format!(
        "  {} stroke(s) over {} root(s); keys {coverage}",
        library.strokes().len(),
        library.roots().len(),
    ));

    let mut by_bank: BTreeMap<u8, usize> = BTreeMap::new();
    for stroke in library.strokes() {
        *by_bank.entry(stroke.bank_code()).or_default() += 1;
    }
    let banks: Vec<String> = by_bank
        .iter()
        .map(|(&code, n)| format!("{} {n}", bank_label(code)))
        .collect();
    ui.out(format!("  banks: {}", banks.join(", ")));

    if args.strokes {
        ui.out(ui.dim(format!(
            "  {:>5} {:>6} {:>9} {:>5} {:>9} {:>8}  keys",
            "index", "root", "bank", "layer", "frames", "seconds"
        )));
        for (index, stroke) in library.strokes().iter().enumerate() {
            ui.out(format!(
                "  {index:>5} {:>6} {:>9} {:>5} {:>9} {:>8.3}  {}",
                note::name(stroke.root),
                bank_label(stroke.bank_code()),
                stroke.layer(),
                stroke.frames(),
                f64::from(stroke.frames()) / f64::from(codec::RATE),
                key_span(&library.keys_for(stroke.root)),
            ));
        }
        return Ok(());
    }

    ui.out(ui.dim(format!(
        "  {:>6} {:>7} {:>7}  layers per bank",
        "root", "strokes", "keys"
    )));
    for root in library.roots() {
        let mine: Vec<_> = library
            .strokes()
            .iter()
            .filter(|s| s.root == root)
            .collect();
        let mut layers: BTreeMap<u8, Vec<u8>> = BTreeMap::new();
        for stroke in &mine {
            layers
                .entry(stroke.bank_code())
                .or_default()
                .push(stroke.layer());
        }
        let detail: Vec<String> = layers
            .iter()
            .map(|(&code, values)| {
                format!(
                    "{} {}",
                    bank_label(code),
                    match (values.first(), values.last()) {
                        (Some(lo), Some(hi)) if lo != hi =>
                            format!("{lo}..{hi} ({})", values.len()),
                        (Some(lo), _) => format!("{lo}"),
                        _ => "none".into(),
                    }
                )
            })
            .collect();
        let keys = library.keys_for(root);
        ui.out(format!(
            "  {:>6} {:>7} {:>7}  {}",
            note::name(root),
            mine.len(),
            keys.len(),
            detail.join(", "),
        ));
    }
    let tuned: Vec<i8> = covered
        .iter()
        .map(|&k| library.fine_tune(k))
        .collect::<Result<Vec<i8>, _>>()
        .map_err(|e| e.to_string())?
        .into_iter()
        .filter(|&units| units != 0)
        .collect();
    match (tuned.iter().min(), tuned.iter().max()) {
        (Some(&lo), Some(&hi)) => ui.out(format!(
            "  fine tune: {} of {} key(s), {lo:+} to {hi:+} units ({:+.1} to {:+.1} c)",
            tuned.len(),
            covered.len(),
            f32::from(lo) * npno::FINE_TUNE_CENTS_PER_UNIT,
            f32::from(hi) * npno::FINE_TUNE_CENTS_PER_UNIT,
        )),
        _ => ui.out("  fine tune: none"),
    }

    if args.keys {
        ui.out(ui.dim(format!(
            "  {:>6} {:>6} {:>7}  {}",
            "key", "root", "tune", "cents"
        )));
        for key in covered {
            let units = library.fine_tune(key).map_err(|e| e.to_string())?;
            let root = library
                .key_root(key)
                .map_err(|e| e.to_string())?
                .expect("a covered key names a root");
            ui.out(format!(
                "  {:>6} {:>6} {:>7} {:>+7.1}",
                note::name(key),
                note::name(root),
                format!("{units:+}"),
                f32::from(units) * npno::FINE_TUNE_CENTS_PER_UNIT,
            ));
        }
    }
    Ok(())
}

/// The keys the map routes somewhere, ascending.
fn covered_keys(library: &Library<'_>) -> Vec<u8> {
    library
        .key_map()
        .iter()
        .enumerate()
        .filter(|&(_, &root)| root != UNCOVERED)
        .map(|(key, _)| key as u8)
        .collect()
}

fn bank_label(code: u8) -> String {
    match Bank::from_code(code) {
        Some(bank) => bank.name().to_owned(),
        None => format!("bank{code}"),
    }
}

fn key_span(keys: &[u8]) -> String {
    match (keys.first(), keys.last()) {
        (Some(lo), Some(hi)) if lo != hi => format!("{}..{}", note::name(*lo), note::name(*hi)),
        (Some(lo), _) => note::name(*lo),
        _ => "-".into(),
    }
}

pub fn decode(ui: &Ui, args: DecodeArgs) -> Result<(), String> {
    let (_, piano) = read(&args.file)?;
    let library = piano.library().map_err(|e| e.to_string())?;

    let chosen = match (args.stroke, &args.key) {
        (Some(index), _) => {
            let stroke = library.strokes().get(index).ok_or_else(|| {
                format!(
                    "stroke {index} is outside 0..{}",
                    library.strokes().len().saturating_sub(1)
                )
            })?;
            (index, stroke)
        }
        (None, Some(spec)) => {
            let key = note::parse(spec)?;
            let root = library
                .key_root(key)
                .map_err(|e| format!("--key {spec}: {e}"))?
                .ok_or_else(|| format!("{} is not a key this library covers", note::name(key)))?;
            let matching: Vec<(usize, _)> = library
                .strokes()
                .iter()
                .enumerate()
                .filter(|(_, s)| s.root == root)
                .filter(|(_, s)| args.layer.is_none_or(|l| s.layer() == l))
                .filter(|(_, s)| {
                    args.bank
                        .is_none_or(|b| s.bank_code() == Bank::from(b).code())
                })
                .collect();
            match matching.len() {
                0 => {
                    return Err(format!(
                        "no stroke plays {} with that bank and layer",
                        note::name(key)
                    ))
                }
                1 => matching[0],
                _ => {
                    let listing: Vec<String> = matching
                        .iter()
                        .map(|(i, s)| {
                            format!("{i}: {} layer {}", bank_label(s.bank_code()), s.layer())
                        })
                        .collect();
                    return Err(format!(
                        "{} selects {} strokes; narrow it with --bank/--layer, or name one \
                         with --stroke:\n  {}",
                        note::name(key),
                        matching.len(),
                        listing.join("\n  ")
                    ));
                }
            }
        }
        (None, None) => return Err("give --stroke N or --key KEY".into()),
    };

    let (index, stroke) = chosen;
    let audio = codec::decode(stroke, library.channels()).map_err(|e| e.to_string())?;
    let wav = nord_format::wav::pcm16(&audio.interleaved(), codec::RATE, library.channels())
        .map_err(|e| e.to_string())?;
    if let Some(parent) = args.out.parent().filter(|p| !p.as_os_str().is_empty()) {
        std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
    }
    write_file(ui, &args.out, &wav)?;

    let peak = audio
        .channels
        .iter()
        .flatten()
        .map(|s| i32::from(*s).abs())
        .max()
        .unwrap_or(0);
    ui.out(format!(
        "  stroke {index}  root {}  {}  layer {}  keys {}",
        note::name(stroke.root),
        bank_label(stroke.bank_code()),
        stroke.layer(),
        key_span(&library.keys_for(stroke.root)),
    ));
    ui.out(format!(
        "  {} frames, {:.3} s, {} channel(s) at {} Hz; peak {peak}, no gain applied",
        audio.frames(),
        audio.seconds(),
        library.channels(),
        codec::RATE,
    ));
    ui.out(ui.dim(format!(
        "  {} repeated sample(s) checked against the block before, {} block(s)",
        audio.overlap_checked,
        stroke.blocks(),
    )));
    Ok(())
}

pub fn edit(ui: &Ui, args: EditArgs) -> Result<(), String> {
    let (original, piano) = read(&args.file)?;
    let mut library = piano.library().map_err(|e| e.to_string())?;
    let mut changed = 0usize;

    if let Some(name) = &args.name {
        library.set_name(name).map_err(|e| format!("--name: {e}"))?;
        changed += 1;
    }
    if let Some(variant) = &args.variant {
        library
            .set_variant(variant)
            .map_err(|e| format!("--variant: {e}"))?;
        changed += 1;
    }
    if let Some(voicing) = &args.voicing {
        library
            .set_voicing(voicing)
            .map_err(|e| format!("--voicing: {e}"))?;
        changed += 1;
    }
    for spec in &args.tune {
        let (key, value) = split_pair(spec, "tune")?;
        let units = parse_tune(value)?;
        library
            .set_fine_tune(key, units)
            .map_err(|e| format!("--tune {spec}: {e}"))?;
        ui.out(format!(
            "  {} fine tune {units:+} ({:+.1} c)",
            note::name(key),
            f32::from(units) * npno::FINE_TUNE_CENTS_PER_UNIT
        ));
        changed += 1;
    }
    for spec in &args.map {
        let (key, value) = split_pair(spec, "map")?;
        let root = match value {
            "-" | "" => None,
            other => Some(note::parse(other)?),
        };
        library
            .set_key_root(key, root)
            .map_err(|e| format!("--map {spec}: {e}"))?;
        ui.out(format!(
            "  {} plays {}",
            note::name(key),
            root.map_or_else(|| "nothing".to_string(), note::name)
        ));
        changed += 1;
    }

    if changed == 0 {
        ui.note("no field changed; writing nothing");
        return Ok(());
    }

    let edited = to_bytes(&library, &args.file)?;
    match args.out {
        Some(out) => write_file(ui, &out, &edited),
        None => {
            ui.note(format!(
                "about to {} {} in place",
                ui.danger("overwrite"),
                args.file.display()
            ));
            ui.confirm(args.yes)?;
            write_file(ui, &args.file, &edited)?;
            ui.note(format!("{} bytes in, {} out", original.len(), edited.len()));
            Ok(())
        }
    }
}

/// `-4` is fine-tune units; `+2.1c` is cents, rounded to the nearest unit.
fn parse_tune(value: &str) -> Result<i8, String> {
    if let Some(cents) = value.strip_suffix(['c', 'C']) {
        let cents: f32 = cents
            .parse()
            .map_err(|_| format!("{value:?} is not a number of cents"))?;
        let units = (cents / npno::FINE_TUNE_CENTS_PER_UNIT).round();
        return i8::try_from(units as i32)
            .map_err(|_| format!("{cents} c is more than the per-key fine tune reaches"));
    }
    value.parse().map_err(|_| {
        format!(
            "{value:?} is not a fine-tune unit count (-128 to 127), or cents \
                              with a `c` suffix"
        )
    })
}

pub fn trim(ui: &Ui, args: TrimArgs) -> Result<(), String> {
    refuse_in_place(&args.file, &args.out)?;
    let (original, piano) = read(&args.file)?;
    let mut library = piano.library().map_err(|e| e.to_string())?;
    if args.drop_bank.is_empty() && args.layers.is_none() && args.range.is_none() {
        return Err("nothing to trim; give --drop-bank, --layers or --range".into());
    }

    let mut total = Change::default();
    for bank in &args.drop_bank {
        let bank = Bank::from(*bank);
        let present = library.strokes().iter().any(|s| s.bank() == Some(bank));
        if !present {
            return Err(format!("this library has no {bank} strokes to drop"));
        }
        let change = library.drop_bank(bank);
        ui.out(format!(
            "  dropped the {bank} bank: {} stroke(s)",
            change.strokes_removed
        ));
        total = add(total, change);
    }
    if let Some(spec) = &args.layers {
        let layers = parse_layers(spec)?;
        let change = library.keep_layers(&layers);
        ui.out(format!(
            "  kept {}: {} stroke(s) dropped",
            describe_layers(&layers),
            change.strokes_removed
        ));
        total = add(total, change);
    }
    if let Some(spec) = &args.range {
        let (lo, hi) = parse_range(spec)?;
        let change = library
            .cut_range(lo..=hi)
            .map_err(|e| format!("--range {spec}: {e}"))?;
        ui.out(format!(
            "  cut to {}..{}: {} key(s) uncovered, {} stroke(s) dropped",
            note::name(lo),
            note::name(hi),
            change.keys_uncovered,
            change.strokes_removed
        ));
        total = add(total, change);
    }

    if library.strokes().is_empty() {
        return Err("that would leave the library with no strokes at all".into());
    }
    if total.strokes_removed == 0 {
        ui.note("nothing matched; writing the library unchanged");
    }

    let trimmed = to_bytes(&library, &args.file)?;
    write_file(ui, &args.out, &trimmed)?;
    report_size(ui, original.len(), trimmed.len());
    if total.keys_uncovered > 0 {
        ui.note(format!(
            "{} key(s) are left playing nothing, and {} root(s) dropped out entirely",
            total.keys_uncovered, total.roots_removed
        ));
    }
    Ok(())
}

fn add(a: Change, b: Change) -> Change {
    Change {
        strokes_removed: a.strokes_removed + b.strokes_removed,
        roots_removed: a.roots_removed + b.roots_removed,
        keys_uncovered: a.keys_uncovered + b.keys_uncovered,
    }
}

fn report_size(ui: &Ui, before: usize, after: usize) {
    let percent = 100.0 * after as f64 / before.max(1) as f64;
    ui.note(format!(
        "{before} bytes in, {after} out ({percent:.1}% of the original)"
    ));
}

/// `N` keeps the N loudest; `=0,3,7` keeps exactly those layer values.
fn parse_layers(spec: &str) -> Result<Layers, String> {
    let spec = spec.trim();
    if let Some(list) = spec.strip_prefix('=') {
        let values: Result<BTreeSet<u8>, String> = list
            .split(',')
            .map(|v| {
                v.trim()
                    .parse::<u8>()
                    .map_err(|_| format!("{v:?} is not a layer number (0-255)"))
            })
            .collect();
        let values = values?;
        if values.is_empty() {
            return Err("--layers =LIST needs at least one layer".into());
        }
        return Ok(Layers::Only(values));
    }
    let n: usize = spec.parse().map_err(|_| {
        format!("--layers takes a count (`2`) or an explicit list (`=0,3,7`), got {spec:?}")
    })?;
    if n == 0 {
        return Err("--layers 0 would keep no stroke at all".into());
    }
    Ok(Layers::Loudest(n))
}

fn describe_layers(layers: &Layers) -> String {
    match layers {
        Layers::Loudest(n) => format!("the {n} loudest layer(s) of each root and bank"),
        Layers::Only(values) => format!(
            "layer(s) {}",
            values
                .iter()
                .map(u8::to_string)
                .collect::<Vec<_>>()
                .join(", ")
        ),
    }
}

fn parse_range(spec: &str) -> Result<(u8, u8), String> {
    let (lo, hi) = spec
        .split_once("..")
        .ok_or_else(|| format!("--range takes LO..HI, got {spec:?}"))?;
    let (lo, hi) = (note::parse(lo)?, note::parse(hi.trim_start_matches('='))?);
    if lo > hi {
        return Err(format!(
            "--range {spec}: {} is above {}",
            note::name(lo),
            note::name(hi)
        ));
    }
    Ok((lo, hi))
}

/// Rebuild each library from its model and compare, and with `--deep` decode every
/// stroke it holds.
pub fn verify(ui: &Ui, args: VerifyArgs) -> Result<(), String> {
    let mut failed = 0usize;
    let mut strokes = 0usize;
    let mut frames = 0usize;
    let mut overlap = 0usize;
    for path in &args.files {
        match verify_one(path, args.deep) {
            Ok(counted) => {
                strokes += counted.strokes;
                frames += counted.frames;
                overlap += counted.overlap;
                ui.out(format!(
                    "ok     {} ({})",
                    path.display(),
                    counted.line(args.deep)
                ));
            }
            Err(line) => {
                failed += 1;
                ui.out(format!(
                    "{} {} ({line})",
                    ui.danger("FAILED"),
                    path.display()
                ));
            }
        }
    }
    if args.deep {
        ui.note(format!(
            "{strokes} stroke(s), {frames} frame(s) decoded, {overlap} repeated sample(s) \
             matched the block before"
        ));
    }
    match failed {
        0 => Ok(()),
        n => Err(format!(
            "{n} of {} file(s) did not check out",
            args.files.len()
        )),
    }
}

#[derive(Default)]
struct Counted {
    strokes: usize,
    frames: usize,
    overlap: usize,
    bytes: usize,
}

impl Counted {
    fn line(&self, deep: bool) -> String {
        if deep {
            format!(
                "{} bytes, {} stroke(s), {} frame(s), {} repeated sample(s) matched",
                self.bytes, self.strokes, self.frames, self.overlap
            )
        } else {
            format!("{} bytes, {} stroke(s)", self.bytes, self.strokes)
        }
    }
}

fn verify_one(path: &Path, deep: bool) -> Result<Counted, String> {
    let (original, piano) = read(path)?;
    let library = piano.library().map_err(|e| e.to_string())?;
    let rebuilt = to_bytes(&library, path)?;
    if rebuilt != original {
        let at = rebuilt
            .iter()
            .zip(&original)
            .position(|(a, b)| a != b)
            .map(|i| format!("{i:#x}"))
            .unwrap_or_else(|| "the length".to_string());
        return Err(format!(
            "the rebuild differs at {at}; in {} bytes, out {}",
            original.len(),
            rebuilt.len()
        ));
    }
    let mut counted = Counted {
        strokes: library.strokes().len(),
        bytes: original.len(),
        ..Counted::default()
    };
    if deep {
        for stroke in library.strokes() {
            let audio = codec::decode(stroke, library.channels())
                .map_err(|e| format!("{stroke:?}: {e}"))?;
            if audio.clipped > 0 {
                return Err(format!(
                    "{stroke:?}: {} sample(s) left int16",
                    audio.clipped
                ));
            }
            counted.frames += audio.frames();
            counted.overlap += audio.overlap_checked;
        }
    }
    Ok(counted)
}

pub fn split(ui: &Ui, args: SplitArgs) -> Result<(), String> {
    let (original, piano) = read(&args.file)?;
    let library = piano.library().map_err(|e| e.to_string())?;
    let at = note::parse(&args.at)?;
    let (low, high) = library
        .split_at(at)
        .map_err(|e| format!("--at {}: {e}", args.at))?;
    for (label, half) in [("low", &low), ("high", &high)] {
        if half.strokes().is_empty() {
            return Err(format!(
                "splitting at {} leaves the {label} half with no strokes",
                note::name(at)
            ));
        }
    }

    std::fs::create_dir_all(&args.out).map_err(|e| format!("{}: {e}", args.out.display()))?;
    let stem = args
        .file
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "piano".to_string());
    for (label, half) in [("low", &low), ("high", &high)] {
        let path = args.out.join(format!("{stem} {label}.npno"));
        refuse_in_place(&args.file, &path)?;
        let bytes = to_bytes(half, &args.file)?;
        write_file(ui, &path, &bytes)?;
        let covered = covered_keys(half);
        ui.out(format!(
            "  {label}: {} stroke(s) over {} root(s), keys {}",
            half.strokes().len(),
            half.roots().len(),
            key_span(&covered),
        ));
        report_size(ui, original.len(), bytes.len());
    }
    ui.note("both halves keep the library's name; `nord piano edit --name` changes it");
    Ok(())
}

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

    #[test]
    fn a_layer_count_and_an_explicit_list_are_told_apart() {
        assert_eq!(parse_layers("2").unwrap(), Layers::Loudest(2));
        assert_eq!(
            parse_layers("=0,3,7").unwrap(),
            Layers::Only([0, 3, 7].into_iter().collect())
        );
        assert!(parse_layers("0").is_err(), "keeping no layer is a mistake");
        assert!(parse_layers("=").is_err());
        assert!(parse_layers("two").is_err());
    }

    #[test]
    fn a_range_takes_note_names_at_either_end() {
        assert_eq!(parse_range("C2..C6").unwrap(), (36, 84));
        assert_eq!(parse_range("36..84").unwrap(), (36, 84));
        assert!(
            parse_range("C6..C2").is_err(),
            "an inverted range is refused"
        );
        assert!(parse_range("C2").is_err());
    }

    #[test]
    fn a_tune_value_reads_units_by_default_and_cents_on_request() {
        assert_eq!(parse_tune("-4").unwrap(), -4);
        assert_eq!(parse_tune("+3").unwrap(), 3);
        // 2.1 cents at 0.7 cents a unit.
        assert_eq!(parse_tune("2.1c").unwrap(), 3);
        assert!(parse_tune("400c").is_err());
        assert!(parse_tune("loud").is_err());
    }

    #[test]
    fn a_pair_splits_on_the_first_equals_and_reads_its_key_as_a_note() {
        assert_eq!(split_pair("C4=60", "map").unwrap(), (60, "60"));
        assert_eq!(split_pair("60=-", "map").unwrap(), (60, "-"));
        assert!(split_pair("C4", "map").is_err());
    }

    /// Every verb that takes a key reads it here, so a key the tables cannot hold is
    /// refused before it reaches a transform.
    #[test]
    fn a_key_past_the_midi_range_is_refused_at_every_flag_that_takes_one() {
        assert!(split_pair("127=3", "tune").is_ok());
        assert!(split_pair("128=3", "tune").is_err());
        assert!(split_pair("128=C4", "map").is_err());
        assert!(note::parse("128").is_err(), "--at and --map's root");
        assert_eq!(parse_range("0..127").unwrap(), (0, 127));
        assert!(parse_range("0..128").is_err());
    }
}