mod cli {
pub mod inputs;
pub mod measures;
pub mod terminal;
}
use std::borrow::Cow;
use std::fs::File;
use std::io::{self, IsTerminal, Write};
use std::num::NonZeroUsize;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender};
use std::sync::{Arc, OnceLock};
use std::thread;
use std::time::{Duration, Instant};
use choon::grid::{Evidence, Family, Scan};
use choon::picture::Shown;
use choon::{
CancelCheck, Claimed, Coverage, Error, Flag, HeAac, Limitation, MeasureThresholds, Measured,
OpusUse, Reading, ReadingThresholds, Settings, Verdict,
};
use clap::{Args, ColorChoice, Parser, Subcommand};
use rayon::iter::{ParallelBridge, ParallelIterator};
use serde::{Deserialize, Serialize};
use crate::cli::inputs::{EXTENSIONS, Found, Inputs};
use crate::cli::measures::{self, Group, Groups, Kept};
use crate::cli::terminal::{self, Bars, Counted, Look, Row};
const CLEAN: u8 = 0;
const LOSSY: u8 = 1;
const FAILED: u8 = 2;
const INTERRUPTED: u8 = 130;
#[derive(Parser)]
#[command(version, about)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
#[command(after_help = "\
Exit status:
0 every file is consistent with its format, possibly lossy or inconclusive
1 at least one file reads as a likely transcode or mixed sources
2 a file could not be read, or an argument was wrong
130 an interrupt ended the run before every file was read
A file the analyzer cannot open as audio is one that could not be read. An interrupt is
Ctrl-C, or SIGTERM or SIGHUP on Unix. On one the files under way are dropped, the files
already read keep their lines, and stderr says how many were read. A second interrupt ends
the program at once.")]
Check(Check),
}
#[derive(Args)]
struct Check {
#[arg(
required_unless_present_any = ["defaults", "from_measures"],
conflicts_with = "from_measures",
value_name = "PATH",
long_help = paths_help()
)]
paths: Vec<PathBuf>,
#[arg(long)]
json: bool,
#[arg(long, value_name = "FILE")]
profile: Vec<PathBuf>,
#[arg(long, exclusive = true)]
defaults: bool,
#[arg(long, value_name = "FILE", conflicts_with = "from_measures")]
save_measures: Option<PathBuf>,
#[arg(
long,
value_name = "FILE",
conflicts_with_all = ["max_full_minutes", "sampled_windows", "timeout", "null", "follow"]
)]
from_measures: Option<PathBuf>,
#[arg(
long,
value_name = "MINUTES",
requires = "sampled_windows",
value_parser = minutes
)]
max_full_minutes: Option<f64>,
#[arg(long, value_name = "COUNT", requires = "max_full_minutes")]
sampled_windows: Option<NonZeroUsize>,
#[arg(long, value_name = "SECONDS", value_parser = seconds)]
timeout: Option<Duration>,
#[arg(long)]
fast: bool,
#[arg(short, long, value_name = "N", value_parser = jobs)]
jobs: Option<NonZeroUsize>,
#[arg(short = '0', long)]
null: bool,
#[arg(short = 'L', long)]
follow: bool,
#[arg(short, long)]
verbose: bool,
#[arg(long, value_name = "WHEN", default_value_t = ColorChoice::Auto)]
color: ColorChoice,
}
fn paths_help() -> String {
format!(
"Audio files and directories to read, or - for the paths listed on stdin\n\n\
A directory is read with the directories under it. Hidden files and directories are left \
out. Of the others, files with one of these extensions are read, in upper or lower case: \
{}. A file named here or on stdin is read whatever its name. Stdin lists one path per line.",
EXTENSIONS.join(", ")
)
}
#[derive(Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct Thresholds {
measure: MeasureThresholds,
reading: ReadingThresholds,
}
#[cfg_attr(test, derive(Clone))]
struct Checked {
claimed: Claimed,
duration: f64,
bitrate_kbps: Option<u32>,
sampled: bool,
windows: usize,
grid: Option<Scan>,
opus: Vec<OpusUse>,
he_aac: Option<HeAac>,
dsd_rate: Option<u32>,
dsd_multiple: Option<u32>,
readings: Vec<Read>,
}
impl Checked {
fn flag(&self) -> Option<Verdict> {
let reads = |verdict| {
let read = |read: &Read| read.reading.verdict == verdict;
self.readings.iter().any(read)
};
[
Verdict::LikelyTranscode,
Verdict::MixedSources,
Verdict::PossiblyLossy,
]
.into_iter()
.find(|verdict| reads(*verdict))
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Analyzed<'a> {
file: Cow<'a, str>,
#[serde(skip_serializing_if = "Option::is_none")]
file_bytes: Option<&'a [u8]>,
claimed: &'a Claimed,
duration_seconds: f64,
bitrate_kbps: Option<u32>,
sampled: bool,
windows: usize,
grid: Option<&'a Scan>,
#[serde(skip_serializing_if = "<[OpusUse]>::is_empty")]
opus: &'a [OpusUse],
#[serde(skip_serializing_if = "Option::is_none")]
he_aac: Option<HeAac>,
#[serde(skip_serializing_if = "Option::is_none")]
dsd_rate: Option<u32>,
readings: &'a [Read],
}
#[cfg_attr(test, derive(Clone))]
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Read {
profile: String,
measure_seconds: f64,
read_seconds: f64,
#[serde(flatten)]
reading: Reading,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct NotAudio<'a> {
file: Cow<'a, str>,
#[serde(skip_serializing_if = "Option::is_none")]
file_bytes: Option<&'a [u8]>,
error: &'a str,
}
fn main() -> ExitCode {
let Command::Check(check) = Cli::parse().command;
match run(&check) {
Ok(code) => ExitCode::from(code),
Err(e) => {
eprintln!("choon: {e}");
ExitCode::from(FAILED)
}
}
}
enum Failed {
Profile(PathBuf, String),
Stdin(io::Error),
Threads(rayon::ThreadPoolBuildError),
Output(io::Error),
Measures(PathBuf, io::Error),
Signals(ctrlc::Error),
}
enum Event {
Started {
file: usize,
name: String,
progress: Vec<Arc<AtomicU32>>,
},
Done {
file: usize,
path: PathBuf,
root: Option<usize>,
result: Result<Box<Checked>, Unread>,
kept: Vec<String>,
},
}
enum Unread {
Open(io::Error),
NotRead(String),
Unmeasured(String),
}
impl std::fmt::Display for Unread {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Open(e) => write!(f, "{e}"),
Self::NotRead(why) => f.write_str(why),
Self::Unmeasured(profile) => write!(
f,
"profile {profile}: its measure thresholds are not those the file was measured with"
),
}
}
}
const TICK: Duration = Duration::from_millis(100);
impl std::fmt::Display for Failed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Profile(path, e) => write!(f, "{}: {e}", path.display()),
Self::Stdin(e) => write!(f, "reading the paths on stdin: {e}"),
Self::Threads(e) => write!(f, "starting the threads: {e}"),
Self::Output(e) => write!(f, "writing the output: {e}"),
Self::Measures(path, e) => write!(f, "{}: {e}", path.display()),
Self::Signals(e) => write!(f, "setting the interrupt handler: {e}"),
}
}
}
fn run(check: &Check) -> Result<u8, Failed> {
if check.defaults {
let defaults =
serde_json::to_string_pretty(&Thresholds::default()).expect("thresholds serialize");
print(&mut io::stdout().lock(), &defaults)?;
return Ok(CLEAN);
}
let profiles = profiles(check)?;
let coverage = match (check.max_full_minutes, check.sampled_windows) {
(Some(minutes), Some(windows)) => Coverage::Sampled {
over_seconds: minutes * 60.0,
windows,
},
_ => Coverage::Full,
};
let mut code = CLEAN;
let mut roots = Vec::new();
let source = match &check.from_measures {
Some(path) => {
let file = File::open(path).map_err(|e| Failed::Measures(path.clone(), e))?;
Source::Kept(path, Groups::new(file))
}
None => {
let inputs = Inputs::gather(
&check.paths,
&mut io::stdin().lock(),
check.null,
check.follow,
)
.map_err(Failed::Stdin)?;
for problem in &inputs.problems {
eprintln!("{}", complaint(&problem.path, &problem.why));
if problem.unread {
code = FAILED;
}
}
if inputs.files.is_empty() {
eprintln!("choon: no audio files found");
return Ok(code);
}
roots = inputs.roots;
Source::Files(inputs.files)
}
};
let total = match &source {
Source::Files(files) => OnceLock::from(files.len()),
Source::Kept(..) => OnceLock::new(),
};
let mut keep = match &check.save_measures {
Some(path) => Some(Keep {
path,
file: File::create(path).map_err(|e| Failed::Measures(path.clone(), e))?,
}),
None => None,
};
let jobs = match check.jobs {
Some(jobs) => jobs.get(),
None => thread::available_parallelism().map_or(1, NonZeroUsize::get),
};
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(jobs)
.build()
.map_err(Failed::Threads)?;
let started = Instant::now();
let stop = Arc::new(AtomicBool::new(false));
let interrupted = Arc::new(AtomicBool::new(false));
ctrlc::set_handler({
let (stop, interrupted) = (stop.clone(), interrupted.clone());
move || {
if interrupted.swap(true, Ordering::Relaxed) {
std::process::exit(INTERRUPTED.into());
}
stop.store(true, Ordering::Relaxed);
}
})
.map_err(Failed::Signals)?;
let plan = Plan::new(&profiles, coverage, check.timeout, keep.is_some(), {
let stop = stop.clone();
Arc::new(move || stop.load(Ordering::Relaxed))
});
let (events, received) = mpsc::sync_channel(jobs);
thread::scope(|scope| {
let (pool, plan, stop, total) = (&pool, &plan, &*stop, &total);
scope.spawn(move || {
pool.install(|| match source {
Source::Files(files) => files
.iter()
.enumerate()
.par_bridge()
.for_each(|(file, found)| check_file(file, found, plan, &events)),
Source::Kept(measures, groups) => groups
.until(stop, total)
.enumerate()
.par_bridge()
.for_each(|(file, group)| check_group(measures, file, group, plan, &events)),
});
});
let mut tally = Tally {
code,
finished: 0,
read: 0,
};
let ended = if !check.json && io::stdout().is_terminal() {
let run = Run {
total,
roots: &roots,
profiled: profiles.len() > 1,
started,
interrupted: &interrupted,
};
shown(received, check, &run, &mut keep, &mut tally)
} else {
printed(received, check.json, &mut keep, &mut tally)
};
stop.store(true, Ordering::Relaxed);
ended?;
let total = total.get().copied();
if !cut_short(&interrupted, total, tally.finished) {
return Ok(tally.code);
}
match total {
Some(total) => eprintln!("choon: interrupted: {} of {total} files read", tally.read),
None => eprintln!("choon: interrupted: {} files read", tally.read),
}
Ok(INTERRUPTED)
})
}
fn profiles(check: &Check) -> Result<Vec<(String, Thresholds)>, Failed> {
let mut profiles = if check.profile.is_empty() {
vec![("default".to_string(), Thresholds::default())]
} else {
let profiles: Vec<(String, Thresholds)> = check
.profile
.iter()
.map(|path| profile(path))
.collect::<Result<_, _>>()?;
for (at, (name, _)) in profiles.iter().enumerate() {
if profiles[..at].iter().any(|(earlier, _)| earlier == name) {
let why = format!("another profile is named {name} too");
return Err(Failed::Profile(check.profile[at].clone(), why));
}
}
profiles
};
if check.fast {
for (_, thresholds) in &mut profiles {
thresholds.measure.scan_wma = false;
thresholds.measure.scan_other_rate = false;
}
}
Ok(profiles)
}
struct Plan<'a> {
profiles: &'a [(String, Thresholds)],
measures: Vec<&'a MeasureThresholds>,
coverage: Coverage,
timeout: Option<Duration>,
save: bool,
canceled: CancelCheck,
}
impl<'a> Plan<'a> {
fn new(
profiles: &'a [(String, Thresholds)],
coverage: Coverage,
timeout: Option<Duration>,
save: bool,
canceled: CancelCheck,
) -> Self {
let mut measures = Vec::new();
for (_, thresholds) in profiles {
if !measures.contains(&&thresholds.measure) {
measures.push(&thresholds.measure);
}
}
Self {
profiles,
measures,
coverage,
timeout,
save,
canceled,
}
}
}
fn check_file(file: usize, found: &Found, plan: &Plan<'_>, events: &SyncSender<Event>) {
if (plan.canceled)() {
return;
}
let path = &found.path;
let progress: Vec<Arc<AtomicU32>> = plan.measures.iter().map(|_| Arc::default()).collect();
let name = path.file_name().unwrap_or(path.as_os_str());
let event = Event::Started {
file,
name: terminal::legible(Path::new(name)),
progress: progress.clone(),
};
if events.send(event).is_err() {
return;
}
let run = AssertUnwindSafe(|| analyzed(path, plan, &progress));
let outcome = match catch_unwind(run) {
Ok(Ok((checked, _))) if checked.windows == 0 && out_of_time(&checked) => Err(Unread::NotRead(
"the analysis ran out of time before a window was measured".to_string(),
)),
Ok(Ok(read)) => Ok(read),
Ok(Err(Error::Canceled)) => return,
Ok(Err(Error::Open(e))) => Err(Unread::Open(e)),
Ok(Err(Error::NotAudio(why) | Error::Unsupported(why))) => Err(Unread::NotRead(why)),
Ok(Err(failed @ (Error::OutOfTime | Error::Panicked))) => {
Err(Unread::NotRead(failed.to_string()))
}
Err(_) => Err(Unread::NotRead(Error::Panicked.to_string())),
};
let (result, kept) = match outcome {
Ok((checked, kept)) => (Ok(Box::new(checked)), kept),
Err(unread) => (Err(unread), Vec::new()),
};
let done = Event::Done {
file,
path: path.clone(),
root: found.root,
result,
kept,
};
let _ = events.send(done);
}
fn check_group(
measures: &Path,
file: usize,
group: Group,
plan: &Plan<'_>,
events: &SyncSender<Event>,
) {
if (plan.canceled)() {
return;
}
let (path, result) = match group.path {
Ok(path) => {
let run = AssertUnwindSafe(|| read_again(&group.lines, plan.profiles));
let read =
catch_unwind(run).unwrap_or_else(|_| Err(Unread::NotRead(Error::Panicked.to_string())));
(path, read.map(Box::new))
}
Err(why) => (
PathBuf::from(format!("{}:{}", measures.display(), group.line)),
Err(Unread::NotRead(why)),
),
};
let done = Event::Done {
file,
path,
root: None,
result,
kept: Vec::new(),
};
let _ = events.send(done);
}
struct Tally {
code: u8,
finished: usize,
read: usize,
}
impl Tally {
fn count(&mut self, result: &Result<Box<Checked>, Unread>) {
self.code = self.code.max(status(result));
self.finished += 1;
self.read += usize::from(result.is_ok());
}
}
struct Run<'a> {
total: &'a OnceLock<usize>,
roots: &'a [PathBuf],
profiled: bool,
started: Instant,
interrupted: &'a AtomicBool,
}
fn cut_short(interrupted: &AtomicBool, total: Option<usize>, finished: usize) -> bool {
interrupted.load(Ordering::Relaxed) && total != Some(finished)
}
enum Source<'a> {
Files(Vec<Found>),
Kept(&'a Path, Groups),
}
struct Keep<'a> {
path: &'a Path,
file: File,
}
impl Keep<'_> {
fn write(&mut self, lines: &[String]) -> Result<(), Failed> {
for line in lines {
self
.file
.write_all(line.as_bytes())
.map_err(|e| Failed::Measures(self.path.to_path_buf(), e))?;
}
Ok(())
}
}
fn out_of_time(checked: &Checked) -> bool {
checked
.readings
.iter()
.any(|read| read.reading.limitations.contains(&Limitation::OutOfTime))
}
fn status(result: &Result<Box<Checked>, Unread>) -> u8 {
match result {
Ok(checked)
if checked
.readings
.iter()
.any(|read| lossy(read.reading.verdict)) =>
{
LOSSY
}
Ok(_) => CLEAN,
Err(_) => FAILED,
}
}
fn printed(
received: Receiver<Event>,
json: bool,
keep: &mut Option<Keep<'_>>,
tally: &mut Tally,
) -> Result<(), Failed> {
let mut out = io::stdout().lock();
for event in received {
let Event::Done {
path: file,
result,
kept,
..
} = event
else {
continue;
};
let file = &file;
tally.count(&result);
if let Some(keep) = keep {
keep.write(&kept)?;
}
let line = match result {
Ok(checked) => {
if json {
serde_json::to_string(&Analyzed {
file: file.to_string_lossy(),
file_bytes: raw(file),
claimed: &checked.claimed,
duration_seconds: checked.duration,
bitrate_kbps: checked.bitrate_kbps,
sampled: checked.sampled,
windows: checked.windows,
grid: checked.grid.as_ref(),
opus: &checked.opus,
he_aac: checked.he_aac,
dsd_rate: checked.dsd_rate,
readings: &checked.readings,
})
.expect("a reading serializes")
} else {
piped(file.display(), &checked, false)
}
}
Err(unread @ (Unread::Open(_) | Unread::Unmeasured(_))) => {
eprintln!("{}", complaint(file, unread));
continue;
}
Err(Unread::NotRead(why)) => {
if json {
serde_json::to_string(&NotAudio {
file: file.to_string_lossy(),
file_bytes: raw(file),
error: &why,
})
.expect("strings and bytes serialize")
} else {
piped_unread(file.display(), &why, false)
}
}
};
if !print(&mut out, &line)? {
return Ok(());
}
}
Ok(())
}
fn shown(
received: Receiver<Event>,
check: &Check,
run: &Run<'_>,
keep: &mut Option<Keep<'_>>,
tally: &mut Tally,
) -> Result<(), Failed> {
let Run {
total,
roots,
profiled,
started,
interrupted,
} = *run;
let colour = match check.color {
ColorChoice::Always => true,
ColorChoice::Never => false,
ColorChoice::Auto => {
anstream::AutoStream::choice(&io::stdout()) != anstream::ColorChoice::Never
}
};
let known = total.get().copied();
let one = known == Some(1);
let mut bars = Bars::new(known);
let mut rows = Vec::with_capacity(known.unwrap_or(0));
let mut alone = None;
loop {
match received.recv_timeout(TICK) {
Ok(Event::Started {
file,
name,
progress,
}) => bars.started(file, name, progress),
Ok(Event::Done {
file,
path,
root,
result,
kept,
}) => {
tally.count(&result);
if let Some(keep) = keep {
keep.write(&kept)?;
}
let outcome = match result {
Ok(checked) => {
bars.ended(file, checked.flag().map(Counted::Flagged));
Ok(checked)
}
Err(unread) => {
bars.ended(file, Some(Counted::NotRead));
match &unread {
Unread::Open(_) | Unread::Unmeasured(_) => {
if one || !io::stderr().is_terminal() {
bars.complain(&complaint(&path, &unread));
}
}
Unread::NotRead(why) => alone = Some(not_read(&path, why, colour)),
}
Err(unread.to_string())
}
};
rows.push(Row {
path,
root: root.map(|root| roots[root].as_path()),
outcome,
});
}
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => break,
}
bars.tick().map_err(Failed::Output)?;
}
bars.finish();
rows.sort_by(|a, b| a.path.cmp(&b.path));
let look = Look {
profiled,
verbose: check.verbose,
colour,
width: console::Term::stdout().size().1,
};
let total = total.get().copied();
let left = cut_short(interrupted, total, tally.finished).then(|| match total {
Some(total) => format!("{} of {total} files left", total - tally.finished),
None => "measures left unread".to_string(),
});
let text = match &rows[..] {
[
Row {
path,
outcome: Ok(checked),
..
},
] if one => terminal::readout(path, checked, look),
[] | [_] if one => alone.unwrap_or_default(),
_ => terminal::tables(
&rows,
look,
started.elapsed(),
check.from_measures.is_none(),
left.as_deref(),
),
};
if !text.is_empty() {
print(&mut io::stdout().lock(), text.trim_end())?;
}
Ok(())
}
#[cfg(unix)]
fn raw(path: &Path) -> Option<&[u8]> {
use std::os::unix::ffi::OsStrExt;
path.to_str().is_none().then(|| path.as_os_str().as_bytes())
}
#[cfg(not(unix))]
fn raw(_: &Path) -> Option<&[u8]> {
None
}
fn complaint(path: &Path, why: impl std::fmt::Display) -> String {
if io::stderr().is_terminal() {
format!("choon: {}: {why}", terminal::legible(path))
} else {
format!("choon: {}: {why}", path.display())
}
}
fn print(out: &mut impl Write, line: &str) -> Result<bool, Failed> {
match writeln!(out, "{line}") {
Ok(()) => Ok(true),
Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(false),
Err(e) => Err(Failed::Output(e)),
}
}
fn lossy(verdict: Verdict) -> bool {
match verdict {
Verdict::LikelyTranscode | Verdict::MixedSources => true,
Verdict::Consistent | Verdict::PossiblyLossy | Verdict::Inconclusive => false,
}
}
fn flagged(verdict: Verdict) -> bool {
lossy(verdict) || verdict == Verdict::PossiblyLossy
}
fn label(verdict: Verdict) -> &'static str {
match verdict {
Verdict::Consistent => "consistent",
Verdict::LikelyTranscode => "likely transcode",
Verdict::MixedSources => "mixed sources",
Verdict::PossiblyLossy => "possibly lossy",
Verdict::Inconclusive => "inconclusive",
}
}
fn encoder(reading: &Reading) -> Option<String> {
let profile = reading
.encoder_guess
.as_ref()
.filter(|_| flagged(reading.verdict))
.map(|guess| &guess.profile);
let Some(grid) = &reading.grid else {
return profile.map(ToString::to_string);
};
let codec = grid.codec;
let setting = profile
.filter(|_| matches!(grid.family, None | Some(Family::Lame | Family::Untagged)))
.filter(|profile| profile.codec == codec.to_string())
.map(|profile| profile.setting.as_str());
match (grid.family.and_then(family_words), setting) {
(None, None) => None,
(None, Some(setting)) => Some(format!("{codec} {setting}")),
(Some(family), None) => Some(format!("{codec} ({family})")),
(Some(family), Some(setting)) => Some(format!("{codec} ({family}) {setting}")),
}
}
const MAX_JOBS: usize = 1024;
fn jobs(text: &str) -> Result<NonZeroUsize, String> {
let jobs: NonZeroUsize = text.parse().map_err(|e| format!("{e}"))?;
if jobs.get() > MAX_JOBS {
return Err(format!("more than {MAX_JOBS} jobs"));
}
Ok(jobs)
}
fn minutes(text: &str) -> Result<f64, String> {
let minutes: f64 = text.parse().map_err(|e| format!("{e}"))?;
if !minutes.is_finite() || minutes <= 0.0 {
return Err("not a length in minutes".to_string());
}
Ok(minutes)
}
fn seconds(text: &str) -> Result<Duration, String> {
let seconds: f64 = text.parse().map_err(|e| format!("{e}"))?;
Duration::try_from_secs_f64(seconds)
.ok()
.filter(|time| !time.is_zero())
.ok_or_else(|| "not a time in seconds".to_string())
}
fn profile(path: &Path) -> Result<(String, Thresholds), Failed> {
let failed = |e: String| Failed::Profile(path.to_path_buf(), e);
let text = std::fs::read_to_string(path).map_err(|e| failed(e.to_string()))?;
let thresholds = serde_json::from_str(&text).map_err(|e| failed(e.to_string()))?;
let name = path.file_stem().map_or_else(
|| path.display().to_string(),
|stem| stem.to_string_lossy().into_owned(),
);
Ok((name, thresholds))
}
struct Measuring {
thresholds: MeasureThresholds,
measured: Measured,
seconds: f64,
}
fn analyzed(
path: &Path,
plan: &Plan<'_>,
progress: &[Arc<AtomicU32>],
) -> Result<(Checked, Vec<String>), Error> {
let deadline = plan
.timeout
.and_then(|timeout| Instant::now().checked_add(timeout));
let mut measurings = Vec::with_capacity(plan.measures.len());
for (thresholds, progress) in plan.measures.iter().zip(progress) {
let settings = Settings {
coverage: plan.coverage,
deadline,
thresholds: (*thresholds).clone(),
progress: Some(progress.clone()),
canceled: Some(plan.canceled.clone()),
};
let started = Instant::now();
let measured = choon::measure(path, &settings)?;
measurings.push(Measuring {
thresholds: settings.thresholds,
measured,
seconds: started.elapsed().as_secs_f64(),
});
}
if plan.save {
let windows = measurings
.iter_mut()
.flat_map(|measuring| &mut measuring.measured.windows);
for window in windows {
window.shown = Shown {
spectrum: Vec::new(),
columns: Vec::new(),
peaks: Vec::new(),
};
}
}
let kept = measurings
.iter()
.filter(|_| plan.save)
.map(|measuring| {
let kept = Kept {
file: path.to_string_lossy(),
file_bytes: raw(path).map(Cow::Borrowed),
version: Cow::Borrowed(env!("CARGO_PKG_VERSION")),
measure: Cow::Borrowed(&measuring.thresholds),
measured: Cow::Borrowed(&measuring.measured),
};
let mut line = serde_json::to_string(&kept).expect("measures serialize");
line.push('\n');
line
})
.collect();
let checked = checked(plan.profiles, measurings)
.unwrap_or_else(|profile| unreachable!("the file was measured for profile {profile}"));
Ok((checked, kept))
}
fn read_again(
lines: &[(usize, Vec<u8>)],
profiles: &[(String, Thresholds)],
) -> Result<Checked, Unread> {
let measurings = lines
.iter()
.map(|(number, line)| {
let kept: Kept<'_> = serde_json::from_slice(line)
.map_err(|e| Unread::NotRead(measures::unparsed(*number, &e)))?;
Ok(Measuring {
thresholds: kept.measure.into_owned(),
measured: kept.measured.into_owned(),
seconds: 0.0,
})
})
.collect::<Result<_, Unread>>()?;
checked(profiles, measurings).map_err(|profile| Unread::Unmeasured(profile.to_string()))
}
fn checked(
profiles: &[(String, Thresholds)],
mut measurings: Vec<Measuring>,
) -> Result<Checked, &str> {
let mut readings = Vec::with_capacity(profiles.len());
let mut of_first = None;
for (name, thresholds) in profiles {
let at = measurings
.iter()
.position(|alike| alike.thresholds == thresholds.measure)
.ok_or(name.as_str())?;
of_first.get_or_insert(at);
let measuring = &measurings[at];
let started = Instant::now();
let reading = measuring.measured.read(&thresholds.reading);
readings.push(Read {
profile: name.clone(),
measure_seconds: measuring.seconds,
read_seconds: started.elapsed().as_secs_f64(),
reading,
});
}
let first = measurings
.swap_remove(of_first.expect("a check has at least one profile"))
.measured;
Ok(Checked {
dsd_multiple: first.dsd_multiple(),
claimed: first.claimed,
duration: first.duration,
bitrate_kbps: first.bitrate_kbps,
sampled: first.sampled,
windows: first.windows.len(),
grid: first.grid,
opus: first.opus,
he_aac: first.he_aac,
dsd_rate: first.dsd_rate,
readings,
})
}
const VERDICT_WIDTH: usize = "likely transcode".len();
fn piped(path: impl std::fmt::Display, checked: &Checked, colour: bool) -> String {
format!("{path}: {}", said(checked, colour))
}
fn piped_unread(path: impl std::fmt::Display, why: &str, colour: bool) -> String {
let status = terminal::painted(None, NOT_READ, colour);
format!("{path}: {status} ({why})")
}
fn not_read(path: &Path, why: &str, colour: bool) -> String {
let pad = " ".repeat(VERDICT_WIDTH - NOT_READ.len());
format!(
"{}{pad} ({why}) {}",
terminal::painted(None, NOT_READ, colour),
terminal::legible(path)
)
}
const NOT_READ: &str = "not read";
fn said(checked: &Checked, colour: bool) -> String {
let kind = kind(checked);
let words = |reading: &Reading, kind: Option<String>| {
let mut found = found(reading, checked.grid.is_some());
found.extend(kind);
detailed(terminal::worded(reading.verdict, colour), &found)
};
match &checked.readings[..] {
[read] => words(&read.reading, kind),
readings => readings
.iter()
.map(|read| format!("[{}] {}", read.profile, words(&read.reading, None)))
.chain(kind)
.collect::<Vec<_>>()
.join("; "),
}
}
fn detailed(status: String, found: &[String]) -> String {
if found.is_empty() {
status
} else {
format!("{status} ({})", found.join(", "))
}
}
fn kind(checked: &Checked) -> Option<String> {
match (
OpusUse::describe(&checked.opus),
checked.he_aac,
checked.dsd_multiple,
) {
(Some(coding), ..) => Some(format!("Opus {coding}")),
(None, Some(he_aac), _) => Some(he_aac.to_string()),
(None, None, Some(multiple)) => Some(format!("DSD{multiple}")),
(None, None, None) => None,
}
}
fn khz(hz: f64) -> String {
format!("{:.1} kHz", hz / 1000.0)
}
fn found(reading: &Reading, scanned: bool) -> Vec<String> {
let mut found = Vec::new();
let cutoff = reading.cutoff_hz.map_or_else(
|| "no cutoff".to_string(),
|hz| format!("cutoff {}", khz(hz)),
);
let guess = encoder(reading);
if let Some(grid) = &reading.grid {
let codec = grid.codec;
found.push(match &grid.evidence {
Evidence::Count(_)
| Evidence::Steps { .. }
| Evidence::AacSteps { .. }
| Evidence::Lattice(_) => format!("{codec} grid"),
Evidence::CountAt { rate, .. } => {
format!("{codec} grid at {} kHz", f64::from(*rate) / 1000.0)
}
Evidence::Part { segments, scan } => format!(
"{codec} grid in {segments} of {} stretches",
scan.segment_z.len()
),
Evidence::Shifted { .. } => format!("{codec} grid at another level"),
Evidence::Hybrid { .. } => format!("{codec} hybrid grid"),
Evidence::Unfiltered { .. } => format!("{codec} grid under its pitch filter"),
Evidence::Short { short } => format!("{codec} grid, {} ms frames", short.milliseconds()),
});
found.push(cutoff);
found.extend(guess);
return found;
}
if reading.verdict == Verdict::PossiblyLossy {
if reading.cutoff_verdict == Verdict::MixedSources {
found.push("mixed sources by cutoff".to_string());
}
found.push(cutoff);
found.extend(guess);
found.push(
if scanned {
"no grid"
} else {
"grid not scanned"
}
.to_string(),
);
return found;
}
if reading.cutoff_hz.is_some() {
found.push(cutoff);
}
found.extend(guess);
found.extend(
reading
.flags
.iter()
.map(|flag| flag_words(*flag).to_string()),
);
if reading.verdict != Verdict::Inconclusive {
found.push(format!("confidence {:.2}", reading.confidence));
}
found
}
fn family_words(family: Family) -> Option<&'static str> {
match family {
Family::Lame => Some("LAME"),
Family::Helix => Some("Helix"),
Family::Apple => Some("Apple"),
Family::Faac => Some("FAAC"),
Family::Nero => Some("Nero"),
Family::FfmpegOrFdk => Some("ffmpeg or fdk-aac"),
Family::Fraunhofer => Some("Fraunhofer"),
Family::Libopus => Some("libopus"),
_ => None,
}
}
fn flag_words(flag: Flag) -> &'static str {
match flag {
Flag::Upsampled => "upsampled",
Flag::BitPadded => "bit padded",
Flag::DualMono => "dual mono",
}
}