koan-core 0.60.10

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
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
//! Correction filters as other tools write them, made into a profile.
//!
//! Whatever is handed over — files, a folder, a zip as Roon takes one, or text
//! pasted from a chat — is sorted by what it is. A configuration that names
//! its files (a Convolver `.cfg`, a CamillaDSP YAML, an Equalizer APO
//! `Convolution:`) decides which file goes with which rate and channel, and
//! loose responses beside it are taken to be the ones it names. Without one,
//! each response's own rate is used, and mono files at one rate are matched to
//! channels by `L`/`R` in their names.

use std::collections::BTreeMap;
use std::io::Read as _;
use std::path::{Path, PathBuf};

use thiserror::Error;

use super::impulse::{Impulse, read_audio};
use super::raw::{self, RawFormat};
use super::{apo, camilla, convolver};
use crate::config::DspFilter;

#[derive(Debug, Error)]
pub enum ImportError {
    /// Headerless coefficients, and nothing saying what rate they are at.
    #[error("{0} does not say what sample rate it is at")]
    NeedsRate(String),
    #[error("{0}")]
    Failed(String),
}

impl From<String> for ImportError {
    fn from(s: String) -> Self {
        Self::Failed(s)
    }
}

#[derive(Debug, Default)]
pub struct Imported {
    /// A name for the profile, from the file it came from.
    pub name: String,
    /// What it was imported from, by file name.
    pub source: Vec<String>,
    pub filters: Vec<DspFilter>,
    pub impulses: Vec<Impulse>,
}

const AUDIO: &[&str] = &["wav", "wave", "flac", "aif", "aiff", "aifc", "m4a", "caf"];

/// Import files, folders and zips as one profile. `rate` is for headerless
/// coefficients that say nothing of it themselves.
pub fn import(paths: &[PathBuf], rate: Option<u32>) -> Result<Imported, ImportError> {
    let scratch = Scratch::new()?;
    let mut files = Vec::new();
    for path in paths {
        gather(path, &scratch, &mut files, true)?;
    }
    let name = paths
        .first()
        .map(|p| profile_name(p))
        .unwrap_or_else(|| "Imported".into());
    let mut imported = sort(files, rate)?;
    imported.name = name;
    imported.source = paths.iter().map(|p| file_name(p)).collect();
    Ok(imported)
}

/// What a selection of files imports as: one profile from them all, or a
/// group, a profile from each of which one plays at a time.
pub enum Batch {
    One(Imported),
    Group(Vec<BatchItem>),
}

/// One file of a selection imported as a group.
pub struct BatchItem {
    /// The file, by name.
    pub file: String,
    pub outcome: Outcome,
}

pub enum Outcome {
    /// Its profile, and why it is named otherwise than for its file, if it
    /// is: another profile, here already or earlier in the selection, has
    /// that name.
    Imported(Imported, Option<String>),
    Refused(ImportError),
    /// Left out, and why: AutoEQ's fixed-band file beside its parametric one.
    Skipped(String),
}

/// Whether a selection imports as a group, a profile from each file: when there are
/// several, and each is a whole EQ or filter configuration by itself
/// (Equalizer APO, AutoEQ or Qudelix text, CamillaDSP YAML), and they are not
/// REW's files for each side of one setup. Convolver `.cfg` files are one
/// correction's rates, a file for each, so they combine.
pub fn separately(paths: &[PathBuf]) -> bool {
    let whole = |path: &PathBuf| {
        if !path.is_file() {
            return false;
        }
        match extension(path).as_deref() {
            Some("yml" | "yaml") => true,
            Some(e)
                if AUDIO.contains(&e)
                    || matches!(e, "cfg" | "zip" | "pcm" | "dbl" | "raw" | "bin") =>
            {
                false
            }
            _ => std::fs::read_to_string(path)
                .is_ok_and(|t| apo::looks_like(&t) || camilla::looks_like(&t)),
        }
    };
    let sides = paths.iter().all(|p| side_in_name(p).is_some());
    paths.len() > 1 && !sides && paths.iter().all(whole)
}

/// Import a selection: a group, a profile from each file, where
/// [`separately`] says so, one from them all otherwise, as [`import`] does,
/// for what are parts
/// of one: responses a file per channel or rate, a folder, a zip, or REW's
/// file for each side.
///
/// Imported as a group, no file takes a name in `taken` (the profiles
/// there already) or one an earlier file took: it is named for its whole
/// file name instead, or numbered. AutoEQ's `FixedBandEQ` file is left out
/// beside its `ParametricEQ` one from the same folder, which is the same
/// correction.
pub fn import_batch(
    paths: &[PathBuf],
    rate: Option<u32>,
    taken: &[String],
) -> Result<Batch, ImportError> {
    if !separately(paths) {
        return import(paths, rate).map(Batch::One);
    }
    let mut names: Vec<String> = taken.to_vec();
    let mut out = Vec::new();
    for path in paths {
        let file = file_name(path);
        let stem = path
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_default();
        if let Some(head) = stem.strip_suffix("FixedBandEQ") {
            let parametric = path.with_file_name(format!("{head}ParametricEQ.txt"));
            if paths.contains(&parametric) {
                out.push(BatchItem {
                    file,
                    outcome: Outcome::Skipped(format!(
                        "the same correction as {}, which was imported",
                        file_name(&parametric)
                    )),
                });
                continue;
            }
        }
        let outcome = match import(std::slice::from_ref(path), rate) {
            Err(e) => Outcome::Refused(e),
            Ok(mut imported) => {
                let wanted = imported.name.clone();
                // Taken by name, or by the folder a name's files go in.
                let free = |n: &str| {
                    let folder = crate::audio::dsp::profiles::dir(n);
                    !names
                        .iter()
                        .any(|t| t == n || crate::audio::dsp::profiles::dir(t) == folder)
                };
                let name = std::iter::once(wanted.clone())
                    .chain(std::iter::once(stem.clone()))
                    .chain((2..).map(|n| format!("{wanted} {n}")))
                    .find(|n| !n.is_empty() && free(n))
                    .expect("some number is free");
                let note =
                    (name != wanted).then(|| format!("{wanted} is taken; imported as {name}"));
                imported.name = name.clone();
                names.push(name);
                Outcome::Imported(imported, note)
            }
        };
        out.push(BatchItem { file, outcome });
    }
    Ok(Batch::Group(out))
}

/// What importing `paths` will do, before it is done: whether they become a
/// group, the files by name, and a name to suggest for the group or the one
/// profile they combine into.
pub struct Plan {
    pub group: bool,
    pub files: Vec<String>,
    pub name: String,
}

pub fn plan(paths: &[PathBuf]) -> Plan {
    let group = separately(paths);
    let names: Vec<String> = paths.iter().map(|p| profile_name(p)).collect();
    Plan {
        group,
        files: paths.iter().map(|p| file_name(p)).collect(),
        name: if group {
            group_name(&names)
        } else {
            names.first().cloned().unwrap_or_else(|| "Imported".into())
        },
    }
}

/// A name for the group of `members`: the words they begin with alike
/// ("AFUL Performer 8S" for "AFUL Performer 8S Warm" and "AFUL Performer 8S
/// Bright"), or the first's when they have none in common.
pub fn group_name(members: &[String]) -> String {
    let words: Vec<Vec<&str>> = members
        .iter()
        .map(|m| m.split_whitespace().collect())
        .collect();
    let Some(first) = words.first() else {
        return "Imported".into();
    };
    let common = (0..first.len())
        .take_while(|&i| words.iter().all(|w| w.get(i) == first.get(i)))
        .count();
    let name = first[..common].join(" ");
    let name = name.trim_end_matches(['-', '_', ',', '(']).trim();
    if name.is_empty() {
        members[0].clone()
    } else {
        name.to_owned()
    }
}

/// Import text with no file behind it: Equalizer APO or AutoEQ lines,
/// CamillaDSP YAML, or a list of coefficients.
pub fn import_text(text: &str, rate: Option<u32>) -> Result<Imported, ImportError> {
    let parsed = if apo::looks_like(text) {
        apo::parse(text)?
    } else if camilla::looks_like(text) {
        camilla::parse(text, None)?
    } else if raw::looks_like_coefficients(text) {
        let rate = rate.ok_or_else(|| ImportError::NeedsRate("The coefficients".into()))?;
        apo::Parsed {
            impulses: vec![Impulse::from_channels(rate, vec![raw::parse_text(text)?])],
            ..Default::default()
        }
    } else {
        return Err(ImportError::Failed(
            "Not EQ or a filter koan recognises: expected AutoEQ or Equalizer APO lines, CamillaDSP YAML, or coefficients".into(),
        ));
    };
    let name = if parsed.impulses.is_empty() {
        "Shared EQ"
    } else {
        "Shared filter"
    };
    Ok(Imported {
        name: name.into(),
        source: vec!["Shared text".into()],
        filters: parsed.filters,
        impulses: parsed.impulses,
    })
}

/// A file found, and whether it was named outright rather than found inside a
/// folder or zip. Something named outright that koan cannot read is an error;
/// a readme in a zip is not.
struct Found {
    path: PathBuf,
    named: bool,
}

fn gather(path: &Path, scratch: &Scratch, out: &mut Vec<Found>, named: bool) -> Result<(), String> {
    let hidden = path
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|n| n.starts_with('.') || n == "__MACOSX");
    if hidden && !named {
        return Ok(());
    }
    if path.is_dir() {
        let mut entries: Vec<_> = std::fs::read_dir(path)
            .map_err(|e| format!("{}: {e}", path.display()))?
            .filter_map(|e| e.ok().map(|e| e.path()))
            .collect();
        entries.sort();
        for entry in entries {
            gather(&entry, scratch, out, false)?;
        }
    } else if extension(path).as_deref() == Some("zip") {
        let dir = scratch.unzip(path)?;
        gather(&dir, scratch, out, false)?;
    } else {
        out.push(Found {
            path: path.to_path_buf(),
            named,
        });
    }
    Ok(())
}

fn extension(path: &Path) -> Option<String> {
    path.extension()
        .and_then(|e| e.to_str())
        .map(str::to_ascii_lowercase)
}

fn sort(files: Vec<Found>, rate: Option<u32>) -> Result<Imported, ImportError> {
    let mut imported = Imported::default();
    let mut configured = false;
    let mut loose_audio = Vec::new();
    let mut loose_raw = Vec::new();
    let mut eq_files: Vec<(PathBuf, Vec<DspFilter>)> = Vec::new();

    for Found { path, named } in files {
        let ext = extension(&path);
        match ext.as_deref() {
            Some("cfg") => {
                imported.impulses.extend(convolver::read(&path)?);
                configured = true;
            }
            Some("yml" | "yaml") => {
                let parsed = camilla::read(&path)?;
                configured |= !parsed.impulses.is_empty();
                imported.filters.extend(parsed.filters);
                imported.impulses.extend(parsed.impulses);
            }
            Some(e) if AUDIO.contains(&e) => loose_audio.push(path),
            Some("pcm") => loose_raw.push((path, RawFormat::F32Le)),
            Some("dbl") => loose_raw.push((path, RawFormat::F64Le)),
            Some("raw" | "bin") => loose_raw.push((path, RawFormat::F32Le)),
            _ => {
                let text = match std::fs::read_to_string(&path) {
                    Ok(t) => t,
                    Err(_) if !named => continue,
                    Err(e) => return Err(format!("{}: {e}", path.display()).into()),
                };
                if apo::looks_like(&text) {
                    let parsed = apo::read(&path)?;
                    configured |= !parsed.impulses.is_empty();
                    eq_files.push((path, parsed.filters));
                    imported.impulses.extend(parsed.impulses);
                } else if camilla::looks_like(&text) {
                    let parsed = camilla::read(&path)?;
                    configured |= !parsed.impulses.is_empty();
                    imported.filters.extend(parsed.filters);
                    imported.impulses.extend(parsed.impulses);
                } else if raw::looks_like_coefficients(&text) {
                    loose_raw.push((path, RawFormat::Text));
                } else if named {
                    return Err(format!("{}: not a filter or EQ koan reads", path.display()).into());
                }
            }
        }
    }

    // REW writes a file of bands per speaker. Several, each naming a side and
    // none choosing channels itself, are each that side's.
    let per_side = eq_files.len() > 1
        && eq_files.iter().all(|(path, filters)| {
            side_in_name(path).is_some()
                && filters
                    .iter()
                    .all(|f| !matches!(f, DspFilter::Mix(_)) && f.channels().is_empty())
        });
    for (path, mut filters) in eq_files {
        if per_side {
            let side = side_in_name(&path).expect("checked above") as u16;
            for c in filters.iter_mut().filter_map(DspFilter::channels_mut) {
                *c = vec![side];
            }
        }
        imported.filters.extend(filters);
    }

    // A configuration names its responses; loose ones beside it are those.
    if !configured {
        imported
            .impulses
            .extend(loose(loose_audio, loose_raw, rate)?);
    }
    if imported.filters.is_empty() && imported.impulses.is_empty() {
        return Err(ImportError::Failed(
            "Nothing to import: no EQ or filters found".into(),
        ));
    }
    Ok(imported)
}

/// A response file and its channels.
type Loaded = (PathBuf, Vec<Vec<f32>>);

/// Responses with no configuration naming them: each at its own rate, or the
/// one in its name, or `rate`.
fn loose(
    audio: Vec<PathBuf>,
    raw_files: Vec<(PathBuf, RawFormat)>,
    rate: Option<u32>,
) -> Result<Vec<Impulse>, ImportError> {
    let mut by_rate: BTreeMap<u32, Vec<Loaded>> = BTreeMap::new();
    for path in audio {
        let (r, channels) = read_audio(&path).map_err(|e| format!("{}: {e}", path.display()))?;
        by_rate.entry(r).or_default().push((path, channels));
    }
    let mut unrated = Vec::new();
    for (path, format) in raw_files {
        let Some(r) = rate_in_name(&path).or(rate) else {
            unrated.push(file_name(&path));
            continue;
        };
        let samples =
            raw::read(&path, format, 0, 0).map_err(|e| format!("{}: {e}", path.display()))?;
        by_rate.entry(r).or_default().push((path, vec![samples]));
    }
    if !unrated.is_empty() {
        return Err(ImportError::NeedsRate(unrated.join(", ")));
    }

    by_rate
        .into_iter()
        .map(|(rate, mut files)| {
            if files.len() == 1 {
                let (_, channels) = files.remove(0);
                return Ok(Impulse::from_channels(rate, channels));
            }
            // Mono files for each side, as REW and rePhase export them.
            if files.iter().any(|(_, c)| c.len() != 1) {
                return Err(ImportError::Failed(format!(
                    "Several files at {rate} Hz and no .cfg to say which is for which channel"
                )));
            }
            let mut sides: [Option<Vec<f32>>; 2] = [None, None];
            for (path, mut channels) in files {
                let side = side_in_name(&path).ok_or_else(|| {
                    ImportError::Failed(format!(
                        "Can't tell which channel {} is for: name it L or R, or add a .cfg",
                        file_name(&path)
                    ))
                })?;
                if sides[side].replace(channels.remove(0)).is_some() {
                    return Err(ImportError::Failed(format!(
                        "Two {} files at {rate} Hz",
                        ["left", "right"][side]
                    )));
                }
            }
            match sides {
                [Some(l), Some(r)] => Ok(Impulse::from_channels(rate, vec![l, r])),
                _ => Err(ImportError::Failed(format!(
                    "Only one side's response at {rate} Hz"
                ))),
            }
        })
        .collect()
}

fn file_name(path: &Path) -> String {
    path.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// A file's name split into runs of letters and runs of digits:
/// `room_L44.1k` → `room`, `l`, `44.1`, `k`.
fn tokens(path: &Path) -> Vec<String> {
    let stem = path
        .file_stem()
        .map(|s| s.to_string_lossy().to_ascii_lowercase())
        .unwrap_or_default();
    let mut out: Vec<String> = Vec::new();
    let mut last: Option<bool> = None;
    for c in stem.chars() {
        let digit = c.is_ascii_digit() || (c == '.' && last == Some(true));
        if !(c.is_ascii_alphanumeric() || digit) {
            last = None;
            continue;
        }
        if last == Some(digit) {
            out.last_mut().expect("a run is open").push(c);
        } else {
            out.push(c.to_string());
        }
        last = Some(digit);
    }
    out
}

/// `44100`, `44.1k`, `44k`, `48`, `96khz`… in a file's name.
fn rate_in_name(path: &Path) -> Option<u32> {
    tokens(path).iter().rev().find_map(|t| match t.as_str() {
        "44100" | "44.1" | "441" | "44" => Some(44100),
        "48000" | "48" => Some(48000),
        "88200" | "88.2" | "882" | "88" => Some(88200),
        "96000" | "96" => Some(96000),
        "176400" | "176.4" | "1764" | "176" => Some(176400),
        "192000" | "192" => Some(192000),
        "352800" | "352.8" | "352" => Some(352800),
        "384000" | "384" => Some(384000),
        _ => None,
    })
}

/// 0 for left, 1 for right.
fn side_in_name(path: &Path) -> Option<usize> {
    let t = tokens(path);
    let left = t.iter().any(|t| t == "l" || t == "left");
    let right = t.iter().any(|t| t == "r" || t == "right");
    match (left, right) {
        (true, false) => Some(0),
        (false, true) => Some(1),
        _ => None,
    }
}

/// `Sennheiser HD 600 ParametricEQ.txt` → `Sennheiser HD 600`, and squig.link's
/// `Moondrop Aria Filters.txt` → `Moondrop Aria`.
fn profile_name(path: &Path) -> String {
    let stem = path
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();
    let name = stem
        .trim_end_matches("ParametricEQ")
        .trim_end_matches(" Filters")
        .trim_end_matches(['_', '-', ' '])
        .to_string();
    if name.is_empty() {
        "Imported".into()
    } else {
        name
    }
}

/// Where zips are unpacked, removed when the import is done with it.
struct Scratch(PathBuf);

impl Scratch {
    fn new() -> Result<Self, String> {
        let dir = std::env::temp_dir().join(format!(
            "koan-dsp-import-{}-{}",
            std::process::id(),
            uuid::Uuid::now_v7()
        ));
        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
        Ok(Self(dir))
    }

    fn unzip(&self, path: &Path) -> Result<PathBuf, String> {
        let fail = |e: &dyn std::fmt::Display| format!("{}: {e}", path.display());
        let file = std::fs::File::open(path).map_err(|e| fail(&e))?;
        let mut archive = zip::ZipArchive::new(file).map_err(|e| fail(&e))?;
        let dir = self.0.join(uuid::Uuid::now_v7().to_string());
        for i in 0..archive.len() {
            let mut entry = archive.by_index(i).map_err(|e| fail(&e))?;
            // `enclosed_name` refuses `..` and absolute paths.
            let Some(rel) = entry.enclosed_name() else {
                continue;
            };
            let dest = dir.join(rel);
            if entry.is_dir() {
                std::fs::create_dir_all(&dest).map_err(|e| fail(&e))?;
                continue;
            }
            // A filter is a few megabytes; anything near this is not one.
            if entry.size() > 512 << 20 {
                return Err(fail(&"an entry is too large to be a filter"));
            }
            if let Some(parent) = dest.parent() {
                std::fs::create_dir_all(parent).map_err(|e| fail(&e))?;
            }
            let mut bytes = Vec::new();
            entry.read_to_end(&mut bytes).map_err(|e| fail(&e))?;
            std::fs::write(&dest, bytes).map_err(|e| fail(&e))?;
        }
        Ok(dir)
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audio::dsp::raw::write_wav;
    use std::io::Write as _;

    fn imported(batch: Batch) -> Vec<(String, Result<String, String>)> {
        let Batch::Group(each) = batch else {
            panic!("one profile from them all");
        };
        each.into_iter()
            .map(|i| {
                let r = match i.outcome {
                    Outcome::Imported(p, _) => Ok(p.name),
                    Outcome::Refused(e) => Err(e.to_string()),
                    Outcome::Skipped(why) => Err(format!("skipped: {why}")),
                };
                (i.file, r)
            })
            .collect()
    }

    /// Four presets chosen together (Qudelix's, its header and footer lines
    /// aside) are four profiles, each named for its file; a broken one is
    /// refused by itself, the rest kept.
    #[test]
    fn each_whole_file_is_its_own_profile() {
        let dir = tempfile::tempdir().unwrap();
        let preset = |gain: f64| {
            format!(
                "Channel: L\r\nPreamp: -2.3 dB \r\n\
                 Filter 1: ON PK Fc 1000 Hz Gain {gain} dB Q 1.0 \r\n\
                 Channel: R\r\nPreamp: -2.3 dB \r\n\
                 Filter 1: ON PK Fc 1000 Hz Gain {gain} dB Q 1.0 \r\n"
            )
        };
        let mut paths = Vec::new();
        for (i, name) in ["Warm", "Bright", "Flat", "Vocal"].iter().enumerate() {
            let path = dir.path().join(format!("{name}.txt"));
            std::fs::write(&path, preset(i as f64)).unwrap();
            paths.push(path);
        }
        let names: Vec<String> = imported(import_batch(&paths, None, &[]).unwrap())
            .into_iter()
            .map(|(_, r)| r.unwrap())
            .collect();
        assert_eq!(names, ["Warm", "Bright", "Flat", "Vocal"]);

        std::fs::write(&paths[2], "Filter 1: ON XX Fc 1000 Hz\n").unwrap();
        let each = imported(import_batch(&paths, None, &[]).unwrap());
        assert_eq!(each.iter().filter(|(_, r)| r.is_ok()).count(), 3);
        assert_eq!(each[2].0, "Flat.txt");
        assert!(each[2].1.is_err());
    }

    /// A group is named by what its members' names share; parts of one
    /// profile by the first file.
    #[test]
    fn a_plan_says_what_will_happen() {
        assert_eq!(
            group_name(&[
                "AFUL Performer 8S Warm".into(),
                "AFUL Performer 8S Bright".into()
            ]),
            "AFUL Performer 8S"
        );
        assert_eq!(group_name(&["Warm".into(), "Bright".into()]), "Warm");
        let dir = tempfile::tempdir().unwrap();
        let mut presets = Vec::new();
        for name in ["AFUL Performer 8S Warm", "AFUL Performer 8S Bright"] {
            let path = dir.path().join(format!("{name}.txt"));
            std::fs::write(&path, "Filter 1: ON PK Fc 100 Hz Gain -3 dB Q 1\n").unwrap();
            presets.push(path);
        }
        let p = plan(&presets);
        assert!(p.group);
        assert_eq!(p.name, "AFUL Performer 8S");
        let wav = dir.path().join("room.wav");
        crate::audio::dsp::raw::write_wav(&wav, 48000, &[vec![1.0, 0.0]]).unwrap();
        let p = plan(&[presets[0].clone(), wav]);
        assert!(!p.group, "a response is part of one profile");
        assert_eq!(p.name, "AFUL Performer 8S Warm");
    }

    /// The parts of one profile chosen together are still one: a Convolver
    /// `.cfg` with its responses, an APO config with the response its
    /// `Convolution:` names, REW's file for each side.
    #[test]
    fn parts_of_one_profile_stay_one() {
        let dir = tempfile::tempdir().unwrap();
        let file = |name: &str, text: &str| {
            let path = dir.path().join(name);
            std::fs::write(&path, text).unwrap();
            path
        };
        let wav = dir.path().join("room.wav");
        crate::audio::dsp::raw::write_wav(&wav, 48000, &[vec![1.0, 0.0]]).unwrap();
        let cfg = file("room.cfg", "48000 1 2 0\n0\n0\nroom.wav\n0\n0.0\n0.0\n");
        assert!(!separately(&[cfg, wav.clone()]));
        let apo = file("config.txt", "Preamp: -3 dB\nConvolution: room.wav\n");
        assert!(!separately(&[apo, wav]));
        let left = file("room_L.txt", "Filter 1: ON PK Fc 100 Hz Gain -3 dB Q 1\n");
        let right = file("room_R.txt", "Filter 1: ON PK Fc 120 Hz Gain -2 dB Q 1\n");
        assert!(!separately(&[left, right]));

        // A .cfg for each rate, chosen without the responses beside them:
        // one correction, a response for each rate.
        let mut cfgs = Vec::new();
        for rate in [44100, 48000] {
            let wav = dir.path().join(format!("{rate}.wav"));
            crate::audio::dsp::raw::write_wav(&wav, rate, &[vec![1.0, 0.0]]).unwrap();
            cfgs.push(file(
                &format!("{rate}.cfg"),
                &format!(
                    "{rate} 2 2 0\n0 0\n0 0\n{rate}.wav\n0\n0.0\n0.0\n{rate}.wav\n0\n1.0\n1.0\n"
                ),
            ));
        }
        assert!(!separately(&cfgs));
        let Batch::One(one) = import_batch(&cfgs, None, &[]).unwrap() else {
            panic!("a group of rates")
        };
        let mut rates: Vec<u32> = one.impulses.iter().map(|i| i.rate).collect();
        rates.sort();
        assert_eq!(rates, [44100, 48000]);
    }

    /// A file whose name is taken, by a profile there already or one earlier
    /// in the selection, is imported under another, and says so; AutoEQ's
    /// fixed-band file beside its parametric one is left out, saying why.
    #[test]
    fn a_taken_name_is_never_written_over() {
        let dir = tempfile::tempdir().unwrap();
        let band = "Preamp: -3 dB\nFilter 1: ON PK Fc 100 Hz Gain -3 dB Q 1\n";
        let mut paths = Vec::new();
        for (folder, name) in [
            ("a", "Sennheiser HD 600 ParametricEQ.txt"),
            ("a", "Sennheiser HD 600 FixedBandEQ.txt"),
            ("a", "Flat.txt"),
            ("b", "Flat.txt"),
        ] {
            let path = dir.path().join(folder).join(name);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, band).unwrap();
            paths.push(path);
        }
        let each = imported(import_batch(&paths, None, &["Flat".to_string()]).unwrap());
        assert_eq!(each[0].1.as_deref(), Ok("Sennheiser HD 600"));
        assert!(
            each[1]
                .1
                .as_ref()
                .unwrap_err()
                .starts_with("skipped: the same correction as")
        );
        assert_eq!(
            each[2].1.as_deref(),
            Ok("Flat 2"),
            "named for its stem, which is taken too"
        );
        assert_eq!(each[3].1.as_deref(), Ok("Flat 3"));
    }

    #[test]
    fn rates_and_sides_in_names() {
        let p = |s: &str| PathBuf::from(s);
        assert_eq!(rate_in_name(&p("room-44.1k.txt")), Some(44100));
        assert_eq!(rate_in_name(&p("Cor1S192.wav")), Some(192000));
        assert_eq!(rate_in_name(&p("filter_96000_L.dbl")), Some(96000));
        assert_eq!(rate_in_name(&p("room.txt")), None);
        assert_eq!(side_in_name(&p("L44.wav")), Some(0));
        assert_eq!(side_in_name(&p("room_right_48k.wav")), Some(1));
        assert_eq!(side_in_name(&p("stereo.wav")), None);
        assert_eq!(
            profile_name(&p("Sennheiser HD 600 ParametricEQ.txt")),
            "Sennheiser HD 600"
        );
        assert_eq!(
            profile_name(&p("Moondrop Aria Filters.txt")),
            "Moondrop Aria"
        );
    }

    #[test]
    fn a_zip_of_mono_sides_at_two_rates() {
        let dir = tempfile::tempdir().unwrap();
        let zip_path = dir.path().join("Living room.zip");
        let mut zip = zip::ZipWriter::new(std::fs::File::create(&zip_path).unwrap());
        let opts = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        for (name, rate, v) in [
            ("L44.wav", 44100, 0.5),
            ("R44.wav", 44100, 0.25),
            ("L48.wav", 48000, 0.5),
            ("R48.wav", 48000, 0.25),
        ] {
            let tmp = dir.path().join(name);
            write_wav(&tmp, rate, &[vec![v]]).unwrap();
            zip.start_file(format!("filters/{name}"), opts).unwrap();
            zip.write_all(&std::fs::read(&tmp).unwrap()).unwrap();
        }
        zip.start_file("__MACOSX/._L44.wav", opts).unwrap();
        zip.write_all(b"junk").unwrap();
        zip.start_file("readme.pdf", opts).unwrap();
        zip.write_all(b"%PDF").unwrap();
        zip.finish().unwrap();

        let imported = import(&[zip_path], None).unwrap();
        assert_eq!(imported.name, "Living room");
        assert_eq!(imported.impulses.len(), 2);
        for ir in &imported.impulses {
            assert_eq!(ir.as_channels().unwrap(), vec![&[0.5][..], &[0.25][..]]);
        }
    }

    #[test]
    fn coefficients_need_a_rate_from_somewhere() {
        let dir = tempfile::tempdir().unwrap();
        let text: String = (0..32)
            .map(|i| format!("{}\n", if i == 0 { 1.0 } else { 0.0 }))
            .collect();
        let bare = dir.path().join("room.txt");
        std::fs::write(&bare, &text).unwrap();
        assert!(matches!(
            import(std::slice::from_ref(&bare), None),
            Err(ImportError::NeedsRate(_))
        ));
        assert_eq!(
            import(&[bare], Some(48000)).unwrap().impulses[0].rate,
            48000
        );

        let named = dir.path().join("room 96k.txt");
        std::fs::write(&named, &text).unwrap();
        assert_eq!(import(&[named], None).unwrap().impulses[0].rate, 96000);
    }

    #[test]
    fn rew_bands_for_each_speaker_land_on_its_channel() {
        let dir = tempfile::tempdir().unwrap();
        let l = dir.path().join("Room Left.txt");
        let r = dir.path().join("Room Right.txt");
        std::fs::write(&l, "Filter 1: ON PK Fc 50 Hz Gain -6 dB Q 4\n").unwrap();
        std::fs::write(&r, "Filter 1: ON PK Fc 60 Hz Gain -3 dB Q 4\n").unwrap();
        let imported = import(&[l, r], None).unwrap();
        assert_eq!(imported.filters[0].channels(), [0]);
        assert_eq!(imported.filters[1].channels(), [1]);
    }

    #[test]
    fn shared_text_is_read_as_what_it_is() {
        let eq = import_text(
            "Preamp: -3 dB\nFilter 1: ON PK Fc 100 Hz Gain 3 dB Q 1\n",
            None,
        )
        .unwrap();
        assert_eq!(eq.filters.len(), 1);
        assert!(import_text("hello there", None).is_err());
    }
}