choon 0.1.0

Check that lossless audio is actually lossless
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
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
//! the analyzer's reading of its measures: the cutoff read from its spread over the windows,
//! weighed with the grid scan, with the findings beside it

use crate::aggregate::{Measures, measures, middle, percentile, upsample_ratio};
use crate::decode::opus::OpusUse;
use crate::engine::{Measured, grid_looked_for};
use crate::flags::{Flag, findings};
use crate::grid::{self, Codec, Evidence, Family, Found};
use crate::limitation::{Limitation, khz};
use crate::thresholds::{EncoderProfile, ReadingThresholds};
use crate::window::{Step, Window};

/// the top of the band of a 48 kHz recording; a file whose band goes past it is hi-res
const HI_RES_TOP_HZ: f64 = 24_000.0;

/// What the analyzer makes of a file.
///
/// # Examples
///
/// ```
/// use choon::{ReadingThresholds, Verdict};
///
/// # fn main() -> Result<(), choon::Error> {
/// # let tone = choon::fixtures::TONE.to_vec();
/// # let measured = choon::measure_bytes(tone, &choon::Settings::default())?;
/// let reading = measured.read(&ReadingThresholds::default());
/// let lossy = match reading.verdict {
///   Verdict::LikelyTranscode | Verdict::MixedSources => true,
///   Verdict::Consistent | Verdict::PossiblyLossy | Verdict::Inconclusive => false,
/// };
/// println!("{}", if lossy { "lossy" } else { "no lossy source found" });
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum Verdict {
  /// Audio that reaches the top of the claimed band in nearly every window.
  ///
  /// It does so without an encoder's shelf.
  Consistent,
  /// Samples that show a codec's frame grid.
  ///
  /// In a file no grid is looked for in, one that claims a lossy codec or is DSD, nearly every
  /// window stops at the same known encoder cutoff with a sharp shelf.
  LikelyTranscode,
  /// Audio band-limited for part of the time or of the band, and full band for the rest.
  ///
  /// It is what one low-bitrate stem mixed into a lossless track looks like. A file a grid is
  /// looked for in reads as possibly lossy instead.
  MixedSources,
  /// Cutoff that reads as lossy where no codec's frame grid shows.
  ///
  /// The cutoff alone reads as a transcode or as mixed sources. A recording filtered where an
  /// encoder cuts and a decode resampled afterwards both look like this, and so does a file
  /// whose grid scan did not run.
  PossiblyLossy,
  /// Too little audio, or measures that fit no pattern.
  Inconclusive,
}

/// Encoder setting a cutoff matches.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct EncoderGuess {
  /// Profile whose cutoff the file's is nearest.
  pub profile: EncoderProfile,
  /// How sure the analyzer is of the match, from 0 to 1.
  pub confidence: f64,
}

/// What the analyzer makes of a file.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Reading {
  /// Reading of the file, the cutoff weighed with the grid scan.
  pub verdict: Verdict,
  /// Reading of the cutoff alone.
  pub cutoff_verdict: Verdict,
  /// Codec frame grid the samples show.
  pub grid: Option<Found>,
  /// How sure the reading is, from 0 to the confidence cap.
  pub confidence: f64,
  /// Findings independent of the cutoff.
  pub flags: Vec<Flag>,
  /// Encoder setting the cutoff matches.
  pub encoder_guess: Option<EncoderGuess>,
  /// What the reading found, in words.
  pub summary: String,
  /// Aggregate measures.
  pub measures: Measures,
  /// What made the reading less reliable.
  #[cfg_attr(feature = "serde", serde(serialize_with = "sentences"))]
  pub limitations: Vec<Limitation>,
  /// Cutoff to mark on the spectrogram, when the content stops short of the top.
  pub cutoff_hz: Option<f64>,
}

/// the reading of the cutoff alone, before the findings independent of it are added
struct CutoffReading {
  verdict: Verdict,
  confidence: f64,
  encoder_guess: Option<EncoderGuess>,
  summary: String,
  limitations: Vec<Limitation>,
  cutoff_hz: Option<f64>,
}

/// writes limitations as the sentences a person is shown
#[cfg(feature = "serde")]
fn sentences<S: serde::Serializer>(
  limitations: &[Limitation],
  serializer: S,
) -> Result<S::Ok, S::Error> {
  serializer.collect_seq(limitations.iter().map(ToString::to_string))
}

/// a window that is not near-silent, as the reading counts it
#[derive(Clone, Copy, Debug)]
struct Seen {
  cutoff_hz: Option<f64>,
  /// it stops with an encoder's low-pass
  sharp: bool,
  seconds: f64,
  inner_shelf: Option<Step>,
  rms_dbfs: f64,
}

impl Seen {
  /// `window` as the reading counts it against a band ending at `top`: hiss or dither that just
  /// clears the cutoff line above a step at an encoder's cutoff makes the window stop at that step
  fn of(window: &Window, top: f64, thresholds: &ReadingThresholds) -> Self {
    let floor = window.inner_shelf.filter(|step| {
      window
        .cutoff_hz
        .is_some_and(|c| c >= thresholds.full_band * top)
        && step.drop >= thresholds.inner_shelf_db
        && thresholds.profile_at(step.hz).is_some()
        && step.clearance < thresholds.clear_db
    });
    match floor {
      Some(step) => Self {
        cutoff_hz: Some(step.hz),
        // a drop of this size to the floor within a few hundred hertz is a wall, whatever the
        // floor's level makes the number
        sharp: true,
        inner_shelf: None,
        rms_dbfs: window.rms_dbfs,
        seconds: window.seconds,
      },
      None => Self {
        cutoff_hz: window.cutoff_hz,
        sharp: window.sharp(thresholds),
        inner_shelf: window.inner_shelf,
        rms_dbfs: window.rms_dbfs,
        seconds: window.seconds,
      },
    }
  }
}

/// the windows that are not near-silent, as the reading counts them
struct Heard<'a> {
  windows: Vec<Seen>,
  /// the top of the band the content is judged against, in Hz
  top: f64,
  thresholds: &'a ReadingThresholds,
}

impl<'a> Heard<'a> {
  /// how many seconds of audio the windows hold, a short last one by its length. summed from
  /// zero, as an empty `sum` of floats is -0.0, which is printed with its sign
  fn seconds(&self) -> f64 {
    self.windows.iter().fold(0.0, |sum, w| sum + w.seconds)
  }

  fn share(&self, keep: impl Fn(&Seen) -> bool) -> f64 {
    let kept = self.windows.iter().filter(|w| keep(w)).count();
    kept as f64 / self.windows.len().max(1) as f64
  }

  fn full(&self, window: &Seen) -> bool {
    window
      .cutoff_hz
      .is_some_and(|c| c >= self.thresholds.full_band * self.top)
  }

  /// a window that stops short of the top at an encoder's cutoff, with a sharp shelf
  fn limited(&self, window: &Seen) -> Option<&'a EncoderProfile> {
    let cutoff = window.cutoff_hz?;
    (!self.full(window) && window.sharp)
      .then(|| lower_profile_at(self.thresholds, cutoff))
      .flatten()
  }

  /// where a full-band window has a step of `depth` dB or more under its top
  fn stepped(&self, window: &Seen, depth: f64) -> Option<f64> {
    let step = window.inner_shelf?;
    (self.full(window) && step.drop >= depth).then_some(step.hz)
  }

  /// a full-band window with a band-limited layer under it at an encoder's cutoff
  fn layered(&self, window: &Seen) -> Option<f64> {
    self
      .stepped(window, self.thresholds.inner_shelf_db)
      .filter(|hz| lower_profile_at(self.thresholds, *hz).is_some())
  }
}

/// the profile at `hz` when it is one below the highest bitrates: a cut where those cut is
/// also where recordings are filtered, so it is no sign of a lossy part in a mix either
fn lower_profile_at(thresholds: &ReadingThresholds, hz: f64) -> Option<&EncoderProfile> {
  thresholds
    .profile_at(hz)
    .filter(|p| p.kbps < thresholds.high_bitrate_kbps)
}

impl Measured {
  /// Reads the measures with `thresholds`.
  ///
  /// The cutoff is read from its spread over the windows, so a band-limited minority of the
  /// time or of the band reads as mixed sources.
  ///
  /// In a file that claims a lossless format, the cutoff is weighed with the scan for a
  /// codec's frame grid ([`grid`]). Only a grid calls the file a likely transcode; a cutoff
  /// that reads as lossy without one makes the file possibly lossy, whether the scan found no
  /// grid or did not run. A DSD file is read by its cutoff alone, as a lossy file is.
  ///
  /// # Examples
  ///
  /// Thresholds can come from JSON, as a profile; keys left out keep their default:
  ///
  /// ```
  /// use choon::ReadingThresholds;
  ///
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// # let tone = choon::fixtures::TONE.to_vec();
  /// # let measured = choon::measure_bytes(tone, &choon::Settings::default())?;
  /// let thresholds: ReadingThresholds = serde_json::from_str(r#"{"sharpShelfDb": 25.0}"#)?;
  /// let reading = measured.read(&thresholds);
  /// println!("{:?}, {}", reading.verdict, reading.summary);
  /// # Ok(())
  /// # }
  /// ```
  pub fn read(&self, thresholds: &ReadingThresholds) -> Reading {
    let claimed = &self.claimed;
    let nyquist = f64::from(claimed.sample_rate) / 2.0;
    let windows: Vec<&Window> = self
      .windows
      .iter()
      .filter(|w| w.cutoff_hz.is_some())
      .collect();
    let upsample_ratio = (claimed.sample_rate > 48_000).then(|| upsample_ratio(&windows));
    let measures = measures(self, &windows, upsample_ratio);
    let median = measures.cutoff_median_hz.map(f64::from);
    let found_beside = findings(claimed, &windows, median, &measures, thresholds);
    // an upsampled file is judged against the band of the rate it was made at
    let top = found_beside.source_edge.unwrap_or(nyquist);
    let windows: Vec<Seen> = windows
      .iter()
      .map(|w| Seen::of(w, top, thresholds))
      .collect();
    let cutoffs: Vec<f64> = windows.iter().filter_map(|w| w.cutoff_hz).collect();
    let median = (!cutoffs.is_empty()).then(|| middle(&cutoffs));
    let heard = Heard {
      windows,
      top,
      thresholds,
    };
    let mut limitations = self.problems.clone();
    if self.sampled {
      limitations.push(Limitation::Sampled {
        windows: self.windows.len(),
      });
    }
    if self.channels_left_out > 0 {
      limitations.push(Limitation::ChannelsLeftOut {
        channels: claimed.channels,
      });
    }
    let mut found = verdict(&heard, median, claimed.lossless, self.bitrate_kbps);
    let heard_seconds = heard.seconds();
    if heard_seconds < thresholds.few_seconds() {
      limitations.push(Limitation::LittleAudio {
        seconds: heard_seconds,
      });
    }
    if quiet(&heard) {
      limitations.push(Limitation::Quiet);
    }
    // a lossy file read as consistent with its own bitrate stops where its own encoder cuts,
    // which needs no other explanation
    let own_cutoff = !claimed.lossless && found.verdict == Verdict::Consistent;
    if let Some(edge) = found_beside.source_edge
      && let Some(profile) = thresholds.profile_at(edge)
      && found.verdict != Verdict::MixedSources
      && !own_cutoff
    {
      // the edge of the lower rate is also where an encoder cuts: either could be the source
      found = CutoffReading {
        verdict: Verdict::Inconclusive,
        confidence: 0.4,
        encoder_guess: Some(EncoderGuess {
          profile: profile.clone(),
          confidence: 0.4,
        }),
        summary: format!(
          "The content stops sharply at {}, both the upper limit of a {} kHz recording and the \
         cutoff of an encoder at {}. The file was either upsampled from that rate or \
         transcoded from that encoder, and the analyzer cannot tell which.",
          khz(edge),
          format!("{:.2}", edge * 2.0 / 1000.0)
            .trim_end_matches('0')
            .trim_end_matches('.'),
          profile
        ),
        limitations: Vec::new(),
        cutoff_hz: Some(edge),
      };
    }
    if found.verdict != Verdict::Consistent
      && let Some(cut) = found.cutoff_hz
      && let Some(edge) = thresholds
        .other_rate_edges
        .iter()
        .find(|edge| (cut - edge.hz).abs() <= thresholds.cluster_hz)
    {
      limitations.push(Limitation::OtherRate {
        rate: edge.rate.clone(),
        hz: edge.hz,
      });
    }
    let cutoff_verdict = found.verdict;
    let grid = self
      .grid
      .as_ref()
      .and_then(|scan| grid::found(scan, thresholds));
    if grid_looked_for(claimed, self.dsd_rate) {
      found = weighed(found, grid.as_ref(), self.grid.is_some(), thresholds);
    }
    limitations.extend(found.limitations);
    if let Some(he_aac) = &self.he_aac {
      // the profiles are lowpasses of encoders that code the whole band, which neither the
      // guess nor the summary can name here
      found.encoder_guess = None;
      if let Some(hz) = found.cutoff_hz {
        found.summary = format!("The decoded band reaches about {}.", khz(hz));
      }
      limitations.push(Limitation::RebuiltBand {
        hz: he_aac.core_top_hz(),
      });
    }
    if self.dsd_rate.is_some() {
      limitations.push(Limitation::Dsd {
        pcm_rate: claimed.sample_rate,
      });
    }
    Reading {
      verdict: found.verdict,
      cutoff_verdict,
      grid,
      confidence: found.confidence.min(thresholds.confidence_cap),
      flags: found_beside.flags,
      encoder_guess: found.encoder_guess,
      summary: std::iter::once(found.summary)
        .chain(found_beside.notes)
        .chain(
          OpusUse::describe(&self.opus).map(|coding| format!("Its Opus packets are {coding}.")),
        )
        .chain(self.he_aac.map(|he_aac| format!("The file is {he_aac}.")))
        .chain(
          self
            .dsd_multiple()
            .map(|multiple| format!("The file is DSD{multiple}.")),
        )
        .collect::<Vec<_>>()
        .join(" "),
      measures,
      limitations,
      cutoff_hz: found.cutoff_hz,
    }
  }
}

/// the cutoff reading `found` of a file a grid is looked for in, weighed with the `grid` its
/// scan found: a grid makes a likely transcode, and a cutoff that reads as lossy without one
/// makes a doubt, whether the scan found none or, not `scanned`, did not run
fn weighed(
  found: CutoffReading,
  grid: Option<&Found>,
  scanned: bool,
  thresholds: &ReadingThresholds,
) -> CutoffReading {
  if let Some(grid) = grid {
    let name = grid.codec;
    let mut limitations = found.limitations;
    // a Vorbis decode's values do not sit on AAC's steps
    let stepped = grid.quantizer.is_some() || matches!(grid.evidence, Evidence::AacSteps { .. });
    if grid.codec == Codec::Aac && !stepped {
      limitations.push(Limitation::AacGridWithoutSteps);
    }
    let evidence = match &grid.evidence {
      Evidence::Count(scan) => format!(
        "The samples carry an {name} frame grid at offset {} (z {:.0}, {} of {} segments \
         agreeing), as audio decoded from {name} does.",
        scan.offset,
        scan.z,
        scan.segments_agreeing,
        grid::SEGMENTS,
      ),
      Evidence::CountAt { rate, scan } => format!(
        "Brought to {} kHz, the samples carry an {name} frame grid at offset {} (z {:.0}, {} of \
         {} segments agreeing), as audio decoded from {name} at that rate and converted does.",
        f64::from(*rate) / 1000.0,
        scan.offset,
        scan.z,
        scan.segments_agreeing,
        grid::SEGMENTS,
      ),
      Evidence::Steps { offset, steps } => format!(
        "With granules at offset {offset}, the values of {} scalefactor bands sit on whole \
         steps of MP3's quantizer, as in audio decoded from MP3.",
        steps.whole,
      ),
      Evidence::AacSteps { offset, steps } => format!(
        "With frames at offset {offset}, the values of {} scalefactor bands sit on whole steps \
         of AAC's quantizer, as in audio decoded from AAC.",
        steps.whole,
      ),
      // the frames of whichever count passed its threshold
      Evidence::Lattice(scan) if scan.frames >= thresholds.opus_grid_frames => format!(
        "The band energies of {} frames at offset {} sit on the lattice of Opus's quantizer, as \
         in audio decoded from Opus.",
        scan.frames, scan.offset,
      ),
      Evidence::Lattice(scan) => format!(
        "The band energies of {} frames sit on the lattice of Opus's quantizer, on the frame \
         grid of an Opus decode whose start was not cut.",
        scan.uncut_frames,
      ),
      Evidence::Shifted { shifted } => {
        let (offset, frames) = shifted.most();
        format!(
          "The band energies of {frames} frames at offset {offset} sit on the lattice of \
           Opus's quantizer once one change of level is taken off them, as in audio decoded \
           from Opus and made louder or quieter."
        )
      }
      Evidence::Hybrid { hybrid } => {
        let (offset, frames, tested) = hybrid.most();
        format!(
          "The energies of the bands from 9.6 to 15.6 kHz sit on the lattice of Opus's quantizer in \
           {frames} of {tested} frames at offset {offset}, as in audio decoded from Opus in its \
           hybrid mode."
        )
      }
      Evidence::Short { short } => {
        let (offset, frames) = short.most();
        format!(
          "The band energies of {frames} frames of {} ms at offset {offset} sit on the lattice \
           of Opus's quantizer.",
          short.milliseconds()
        )
      }
    };
    let family = grid.family.map_or_else(String::new, |family| match family {
      Family::Fraunhofer => format!(
        " The offset is the one an encoder that states no delay leaves in a decode whose start \
         was not cut, and the quantizer's steps move from band to band as {family} moves them."
      ),
      _ => format!(" The offset is the one {family} leaves in a decode whose start was not cut."),
    });
    let quantizer = grid.quantizer.as_ref().map_or_else(String::new, |steps| {
      format!(
        " The values of {} scalefactor bands sit on whole steps of AAC's quantizer.",
        steps.whole
      )
    });
    return CutoffReading {
      verdict: Verdict::LikelyTranscode,
      confidence: thresholds.confidence_cap,
      summary: format!("{evidence}{quantizer}{family} {}", found.summary),
      limitations,
      ..found
    };
  }
  match found.verdict {
    Verdict::LikelyTranscode | Verdict::MixedSources => {
      let mut limitations = found.limitations;
      limitations.push(Limitation::CutoffWithoutGrid);
      let unconfirmed = if scanned {
        "No MP3, AAC or Opus frame grid shows in the samples"
      } else {
        "The samples were not scanned for a codec's frame grid"
      };
      CutoffReading {
        verdict: Verdict::PossiblyLossy,
        confidence: 0.4,
        summary: format!(
          "{} {unconfirmed}, so the cutoff alone cannot confirm a lossy source.",
          found.summary
        ),
        limitations,
        ..found
      }
    }
    Verdict::Consistent | Verdict::PossiblyLossy | Verdict::Inconclusive => found,
  }
}

/// reads the cutoff of the non-silent windows, whose median cutoff is `median`
fn verdict(
  heard: &Heard,
  median: Option<f64>,
  lossless: bool,
  bitrate: Option<u32>,
) -> CutoffReading {
  let t = heard.thresholds;
  let count = heard.windows.len();
  let seconds = heard.seconds();
  let mut reading = CutoffReading {
    verdict: Verdict::Inconclusive,
    confidence: 0.3,
    encoder_guess: None,
    summary: String::new(),
    limitations: Vec::new(),
    cutoff_hz: median.filter(|m| *m < t.full_band * heard.top),
  };
  let Some(median) = median.filter(|_| count >= t.min_windows && seconds >= t.min_seconds) else {
    reading.confidence = 0.2;
    reading.summary = format!(
      "Only {seconds:.1} s of the audio is above silence; a reading needs at least {:.0} s.",
      t.min_seconds
    );
    return reading;
  };
  let near = |hz: f64| heard.share(|w| w.cutoff_hz.is_some_and(|c| (c - hz).abs() <= t.cluster_hz));
  let clustered = near(median);
  let sharp_share = heard.share(|w| {
    w.sharp
      && w
        .cutoff_hz
        .is_some_and(|c| (c - median).abs() <= t.cluster_hz)
  }) / clustered.max(f64::EPSILON);
  // a lossy file's own encoder cuts off too: only a cutoff well below its bitrate's counts
  let below_claim = |profile: &EncoderProfile| {
    lossless || bitrate.is_some_and(|kbps| below_bitrate(profile.kbps, kbps))
  };

  if let Some(profile) = lower_profile_at(t, median).filter(|p| below_claim(p))
    && clustered >= t.transcode_share
    && sharp_share >= 0.5
  {
    let evidence = 0.6
      * ((clustered - t.transcode_share) / (1.0 - t.transcode_share)).clamp(0.0, 1.0)
      + 0.4 * sharp_share;
    let confidence = 0.6 + 0.38 * evidence;
    reading.limitations.push(Limitation::LowestCutoffOnly);
    reading.verdict = Verdict::LikelyTranscode;
    reading.confidence = confidence;
    reading.encoder_guess = Some(EncoderGuess {
      profile: profile.clone(),
      confidence: (clustered * (0.5 + 0.5 * sharp_share)).min(t.confidence_cap),
    });
    reading.cutoff_hz = Some(median);
    reading.summary = format!(
      "{} of the time stops at {} with a sharp shelf, where an encoder at {} cuts off.",
      percent(clustered),
      khz(median),
      profile
    );
    return reading;
  }

  if let Some(profile) = t.profile_at(median).filter(|_| lossless)
    && clustered >= t.transcode_share
    && sharp_share >= 0.5
  {
    reading.cutoff_hz = Some(median);
    // past the transcode rule, this is a sharp cutoff where the highest bitrates cut
    reading.encoder_guess = Some(EncoderGuess {
      profile: profile.clone(),
      confidence: 0.4,
    });
    reading.limitations.push(Limitation::FilteredAt20Khz);
    reading.summary = format!(
      "{} of the time stops at {} with a sharp shelf, where an encoder at {} cuts off or where \
       a recording was filtered when it was made.",
      percent(clustered),
      khz(median),
      profile
    );
    return reading;
  }

  let full = heard.share(|w| heard.full(w));
  let limited: Vec<f64> = heard
    .windows
    .iter()
    .filter(|w| heard.limited(w).is_some())
    .filter_map(|w| w.cutoff_hz)
    .collect();
  let limited_share = limited.len() as f64 / count as f64;
  if limited_share >= t.mixed_share && full >= t.mixed_share {
    let at = middle(&limited);
    reading.verdict = Verdict::MixedSources;
    reading.confidence = 0.5 + 0.35 * (limited_share.min(full) / 0.5).min(1.0);
    reading.encoder_guess = t.profile_at(at).map(|p| EncoderGuess {
      profile: p.clone(),
      confidence: 0.5,
    });
    reading.cutoff_hz = Some(at);
    reading.summary = format!(
      "{} of the time is full-band; {} stops at {} with a sharp shelf, as when part of the \
       track comes from a lossy source.",
      percent(full),
      percent(limited_share),
      khz(at)
    );
    return reading;
  }
  let layers: Vec<f64> = heard
    .windows
    .iter()
    .filter_map(|w| heard.layered(w))
    .collect();
  let layered_share = layers.len() as f64 / count as f64;
  if layered_share >= t.mixed_share {
    let at = middle(&layers);
    reading.verdict = Verdict::MixedSources;
    reading.confidence = 0.5 + 0.35 * layered_share.min(1.0);
    reading.encoder_guess = t.profile_at(at).map(|p| EncoderGuess {
      profile: p.clone(),
      confidence: 0.5,
    });
    reading.cutoff_hz = Some(at);
    reading.summary = format!(
      "The content reaches the top of the band, but {} of the time has a sharp step at {}, as \
       when a band-limited layer is mixed with full-band material.",
      percent(layered_share),
      khz(at)
    );
    return reading;
  }
  // a step where the highest bitrates cut, under a band that reaches the top: a high-bitrate
  // layer, or a recording filtered at 20 kHz with something above it
  let high_steps: Vec<f64> = heard
    .windows
    .iter()
    .filter_map(|w| heard.stepped(w, t.high_step_db))
    .filter(|hz| {
      t.profile_at(*hz)
        .is_some_and(|p| p.kbps >= t.high_bitrate_kbps)
    })
    .collect();
  // the middle step is one of the steps, each at a profile, so only no steps leave it without one
  let at = middle(&high_steps);
  if high_steps.len() as f64 / count as f64 >= t.mixed_share
    && let Some(profile) = t.profile_at(at)
  {
    reading.encoder_guess = Some(EncoderGuess {
      profile: profile.clone(),
      confidence: 0.4,
    });
    reading.cutoff_hz = Some(at);
    reading.limitations.push(Limitation::FilteredAt20Khz);
    reading.summary = format!(
      "The content reaches the top of the band, but {} of the time has a sharp step at {}, \
       where an encoder at {profile} cuts off. A layer at that bitrate and a recording \
       filtered there with other material above it look the same.",
      percent(high_steps.len() as f64 / count as f64),
      khz(at)
    );
    return reading;
  }

  let open = heard.share(|w| heard.full(w) || !w.sharp);
  if open >= t.consistent_share {
    if full >= t.consistent_share {
      let windows = ((count - t.min_windows) as f64 / 100.0).min(1.0);
      let mut confidence = 0.7 + 0.25 * windows;
      if quiet(heard) {
        confidence -= 0.1;
      }
      reading.verdict = Verdict::Consistent;
      reading.confidence = confidence;
      // a step that is no encoder's cutoff can still lie under the band
      let stepped = heard
        .windows
        .iter()
        .any(|w| heard.stepped(w, t.high_step_db).is_some());
      reading.summary = format!(
        "{} of the time reaches {}, near the top of the {} band{}.",
        percent(full),
        khz(median),
        khz(heard.top),
        if stepped {
          ""
        } else {
          ", with no encoder shelf"
        }
      );
      return reading;
    }
    reading.limitations.push(Limitation::EarlyRollOff);
    if median >= t.natural_limit * heard.top {
      reading.verdict = Verdict::Consistent;
      reading.confidence = 0.7;
      reading.summary = format!(
        "The content rolls off gently from about {}, without the sharp cutoff of an encoder.",
        khz(median)
      );
      return reading;
    }
    reading.confidence = 0.4;
    // a band above what a 48 kHz recording holds is mostly empty in honest hi-res audio too
    let like = if heard.top > HI_RES_TOP_HZ {
      "as in many hi-res recordings, where microphones and instruments produce little above \
       20 kHz"
    } else {
      "as in test tones, speech, old masters and lo-fi recordings"
    };
    reading.summary = format!(
      "The content stops at about {}, well below the top of the band, without the sharp shelf \
       of an encoder, {like}.",
      khz(median)
    );
    return reading;
  }
  // a lossy file that reaches past every cutoff too low for its bitrate is judged against what
  // its own bitrate keeps, at the top of its cutoffs: its encoder's cutoff is a ceiling that
  // moves from frame to frame, and windows under it only lack high content
  if !lossless && let Some(kbps) = bitrate {
    let cutoffs: Vec<f64> = heard.windows.iter().filter_map(|w| w.cutoff_hz).collect();
    let edge = percentile(&cutoffs, t.ceiling).unwrap_or(median);
    let too_low = t
      .profiles
      .iter()
      .rev()
      .find(|p| below_claim(p))
      .map_or(0.0, |p| p.hz);
    if edge > too_low + t.cluster_hz {
      reading.cutoff_hz = Some(edge);
      let profile = t.profile_at(edge);
      if keeps_its_bitrate(t, edge, kbps) {
        reading.verdict = Verdict::Consistent;
        reading.confidence = 0.7 + 0.1 * near(edge);
        reading.summary = match profile {
          Some(profile) => format!(
            "The content stops at about {}, where an encoder at {} cuts off, at or above what \
             a file of its bitrate keeps.",
            khz(edge),
            profile
          ),
          None => format!(
            "The content reaches about {}, the top of what a file of its bitrate keeps.",
            khz(edge)
          ),
        };
        return reading;
      }
      reading.confidence = 0.4;
      reading.encoder_guess = profile.map(|p| EncoderGuess {
        profile: p.clone(),
        confidence: 0.4,
      });
      let at = profile.map_or(String::new(), |p| {
        format!(", where an encoder at {p} cuts off")
      });
      reading.summary = format!(
        "The content stops at about {}{at}: below what a file of its bitrate keeps, but not \
         low enough to call a transcode. A second lossy generation at a nearby bitrate is one \
         explanation.",
        khz(edge)
      );
      return reading;
    }
  }
  reading.summary = if sharp_share >= 0.5 && clustered >= t.transcode_share {
    format!(
      "The content stops at {} with a sharp shelf, which is not the cutoff of a common encoder.",
      khz(median)
    )
  } else {
    "The windows do not fit one pattern.".to_string()
  };
  reading
}

/// whether a profile at `profile_kbps` cuts well below what a file of `kbps` keeps: the file's
/// bitrate is at least one and a half times the profile's
fn below_bitrate(profile_kbps: u32, kbps: u32) -> bool {
  u64::from(profile_kbps) * 3 / 2 <= u64::from(kbps)
}

/// whether a cut at `edge` keeps what a file of `kbps` does: it sits at the cutoff of a bitrate
/// no lower than the highest one up to `kbps`, or past every cutoff of that bitrate. a file below
/// every bitrate known keeps whatever it does.
fn keeps_its_bitrate(thresholds: &ReadingThresholds, edge: f64, kbps: u32) -> bool {
  let profiles = &thresholds.profiles;
  let Some(own) = profiles.iter().map(|p| p.kbps).filter(|p| *p <= kbps).max() else {
    return true;
  };
  match thresholds.profile_at(edge) {
    Some(profile) => profile.kbps >= own,
    None => profiles
      .iter()
      .filter(|p| p.kbps == own)
      .all(|p| edge > p.hz),
  }
}

/// whether the middle window is quiet
fn quiet(heard: &Heard) -> bool {
  let levels: Vec<f64> = heard.windows.iter().map(|w| w.rms_dbfs).collect();
  percentile(&levels, 0.5).is_some_and(|level| level < heard.thresholds.quiet_dbfs)
}

/// a share as a whole percentage
fn percent(share: f64) -> String {
  format!("{:.0}%", share * 100.0)
}

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

  fn heard<'a>(cutoffs: &[f64], thresholds: &'a ReadingThresholds) -> Heard<'a> {
    Heard {
      windows: cutoffs
        .iter()
        .map(|c| Seen {
          cutoff_hz: Some(*c),
          sharp: true,
          seconds: 1.0,
          inner_shelf: None,
          rms_dbfs: -20.0,
        })
        .collect(),
      top: 24_000.0,
      thresholds,
    }
  }

  fn spread(cuts: &[(f64, usize)]) -> Vec<f64> {
    cuts.iter().flat_map(|(c, n)| [*c].repeat(*n)).collect()
  }

  #[test]
  fn a_bitrate_at_the_top_of_its_type_is_compared_without_overflow() {
    assert!(below_bitrate(128, 192));
    assert!(!below_bitrate(128, 191));
    assert!(!below_bitrate(u32::MAX, u32::MAX));
  }

  #[test]
  fn a_moving_cutoff_at_the_top_of_a_256_kbps_aac_is_its_own() {
    let cuts = spread(&[
      (20_000.0, 30),
      (20_500.0, 30),
      (21_000.0, 30),
      (15_500.0, 20),
    ]);
    let found = verdict(
      &heard(&cuts, &ReadingThresholds::default()),
      Some(20_250.0),
      false,
      Some(256),
    );
    assert_eq!(found.verdict, Verdict::Consistent, "{}", found.summary);
  }

  #[test]
  fn a_ceiling_too_low_for_the_bitrate_is_not_called_consistent() {
    let cuts = spread(&[(15_500.0, 40), (16_500.0, 40), (17_500.0, 40)]);
    let found = verdict(
      &heard(&cuts, &ReadingThresholds::default()),
      Some(16_500.0),
      false,
      Some(256),
    );
    assert_ne!(found.verdict, Verdict::Consistent, "{}", found.summary);
  }

  #[test]
  fn a_full_band_minority_too_small_to_mix_does_not_hide_a_transcode() {
    // a 128 kbps source in a 320 kbps MP3 with a full-band intro under the mixed-sources share
    let cuts = spread(&[(16_000.0, 88), (20_000.0, 12)]);
    let found = verdict(
      &heard(&cuts, &ReadingThresholds::default()),
      Some(16_000.0),
      false,
      Some(320),
    );
    assert_eq!(found.verdict, Verdict::LikelyTranscode, "{}", found.summary);
  }

  #[test]
  fn a_cutoff_below_its_bitrates_own_but_above_two_thirds_of_it_is_inconclusive() {
    let cuts = spread(&[(16_000.0, 100)]);
    let found = verdict(
      &heard(&cuts, &ReadingThresholds::default()),
      Some(16_000.0),
      false,
      Some(190),
    );
    assert_eq!(found.verdict, Verdict::Inconclusive, "{}", found.summary);
    assert_eq!(found.confidence, 0.4);
    let guess = found.encoder_guess.unwrap();
    assert_eq!(
      (guess.profile.to_string().as_str(), guess.confidence),
      ("MP3 ~128 kbps", 0.4)
    );
    assert!(
      found.summary.contains("second lossy generation"),
      "{}",
      found.summary
    );
    let own = verdict(
      &heard(&spread(&[(18_600.0, 100)]), &ReadingThresholds::default()),
      Some(18_600.0),
      false,
      Some(190),
    );
    assert_eq!(own.verdict, Verdict::Consistent, "{}", own.summary);
  }
}