mod svg;
mod wav;
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use clap::Args;
use duet_capture::{
Analysis, Event, FileSource, Origin, PerformanceFrames, PerformanceHead, Prepare, ReadNote,
Reading, Source, Stage,
};
use duet_schemas::{Document, Stream};
use super::write_new;
const LENGTH_SLACK_SECS: f64 = 0.1;
#[derive(Args)]
pub struct CompareArgs {
input: PathBuf,
#[arg(short, long, value_name = "STEM")]
output: Option<PathBuf>,
#[arg(long, value_name = "ANALYSIS")]
reading: Option<PathBuf>,
#[arg(long, value_name = "SECS")]
from: Option<f64>,
#[arg(long, value_name = "SECS")]
to: Option<f64>,
#[arg(long, conflicts_with = "gapped")]
legato: bool,
#[arg(long)]
gapped: bool,
#[arg(long, value_enum, default_value_t, value_name = "RENDERING")]
render: wav::Render,
}
pub fn run(args: &CompareArgs) -> Result<()> {
let from_secs = args.from.unwrap_or(0.0);
if !(from_secs.is_finite() && from_secs >= 0.0) {
bail!("--from {from_secs}: the window starts at a number of seconds, 0 or more");
}
if let Some(to) = args.to
&& !(to.is_finite() && to > from_secs)
{
bail!("--to {to}: the window ends after it starts, at {from_secs} s");
}
let stem = args
.output
.clone()
.unwrap_or_else(|| args.input.with_extension(""));
let performance_path = with_suffix(&stem, ".performance.duet.jsonl");
let analysis_path = with_suffix(&stem, ".capture.duet");
let compared_path = args
.reading
.clone()
.unwrap_or_else(|| analysis_path.clone());
let gaps = if args.legato {
wav::Gaps::Legato
} else if args.gapped {
wav::Gaps::Gapped
} else {
wav::Gaps::Bridged
};
let out_stem = with_suffix(
&stem_of(&compared_path),
&format!(
"{}{}",
window_name(args.from, args.to),
args.render.suffix()
),
);
let (svg_path, wav_path) = (
with_suffix(&out_stem, ".svg"),
with_suffix(&out_stem, ".wav"),
);
for path in [&svg_path, &wav_path] {
if path.exists() {
bail!(
"{} exists; compare writes new files and never overwrites one, so move it",
path.display()
);
}
}
let frames = performance(&performance_path)?;
let compared = analysis(&compared_path)?;
let own = match &args.reading {
Some(_) => Some(analysis(&analysis_path)?),
None => None,
};
for (analysis, path) in [
(Some(&compared), &compared_path),
(own.as_ref(), &analysis_path),
] {
if let Some(analysis) = analysis
&& analysis.rate != frames.rate
{
bail!(
"{} counts frames at {} Hz and {} at {} Hz: they are not of one performance",
path.display(),
analysis.rate,
performance_path.display(),
frames.rate
);
}
}
let reading = reading_of(&compared, &compared_path)?;
let beside = own
.as_ref()
.map(|own| reading_of(own, &analysis_path))
.transpose()?;
let onsets: Vec<u64> = compared
.events
.iter()
.filter_map(|e| match *e {
Event::Onset { frame, .. } => Some(frame),
_ => None,
})
.collect();
let take = take(&args.input, frames.rate)?;
let rate = f64::from(frames.rate);
let take_secs = take.len() as f64 / rate;
if let Some(last) = frames.len().checked_sub(1).map(|k| frames.frame(k))
&& last as f64 / rate > take_secs + LENGTH_SLACK_SECS
{
bail!(
"{} is {take_secs:.2} s long, and {}'s frames run to {:.2} s: it is not the take \
that performance was read from",
args.input.display(),
performance_path.display(),
last as f64 / rate
);
}
let from = (from_secs * rate).round() as u64;
let to = args.to.map_or(take.len() as u64, |t| {
((t * rate).round() as u64).min(take.len() as u64)
});
if from >= to {
bail!(
"--from {from_secs}: {} is {take_secs:.2} s long, so the window holds nothing",
args.input.display()
);
}
let title = format!(
"{}: {}{} on A4 = {:.1} Hz ({:+.0} cents{}), {} to {}",
args.input.display(),
compared_path.display(),
match args.render {
wav::Render::Melody => "",
wav::Render::Steps => ", its excursions as steps,",
wav::Render::Bends => ", its residual as bends,",
},
reading.tuning.a4_hz(),
reading.tuning.offset_cents(),
if matches!(reading.tuning.a4, Origin::Given(_)) {
", given"
} else {
", estimated"
},
seconds(from as f64 / rate),
seconds(to as f64 / rate)
);
let voice = wav::Voice::new(reading, &frames, gaps, args.render);
let plot = svg::render(&svg::Plot {
title: &title,
frames: &frames,
from,
to,
reading,
beside,
onsets: &onsets,
voice: &voice,
});
let right = wav::sine(&voice, from, to);
let audio = wav::stereo(frames.rate, &take[from as usize..to as usize], &right);
write_new(&svg_path, &plot)?;
if let Err(e) = write_bytes_new(&wav_path, &audio) {
let _ = fs::remove_file(&svg_path);
return Err(e.context(format!(
"compare wrote nothing: removed {} again",
svg_path.display()
)));
}
print!("{}", notes_table(&title, reading, from, to, rate));
Ok(())
}
fn notes_table(title: &str, reading: &Reading, from: u64, to: u64, rate: f64) -> String {
let parts = reading.residual.is_some();
let mut out = format!("# {title}\n# time key centre");
if parts {
out.push_str(&format!(
" {:>7} {:>8} {:<13} {:<13} {:<13} {:>6} excursions",
"held", "drift/s", "vibrato", "scoop", "fall", "rest"
));
}
out.push('\n');
for note in reading.notes.iter().filter(|n| svg::shown(n, from, to)) {
let mut line = format!(
"{:>10} {:<5} {:>+6.1}c",
format!("{:.3} s", note.start as f64 / rate),
svg::key_name(note.key),
note.centre,
);
if let Some(r) = ¬e.residual {
let transition = |t: Option<(f32, f32)>| {
t.map_or_else(|| "-".to_owned(), |(c, ms)| format!("{c:+.0}c {ms:.0} ms"))
};
line.push_str(&format!(
" {:>+6.1}c {:>+8.1} {:<13} {:<13} {:<13} {:>5.1}c",
r.centre,
r.drift.cents_per_sec,
r.modulation.map_or_else(
|| "-".to_owned(),
|m| format!("{:.1} Hz ±{:.0}c", m.rate_hz, m.depth_cents)
),
transition(r.scoop.map(|t| (t.cents, t.ms))),
transition(r.fall.map(|t| (t.cents, t.ms))),
r.rest_cents,
));
line.push_str(" ");
line.push_str(&excursions(note, rate));
}
if note.between_keys {
line.push_str(" between keys");
}
out.push_str(line.trim_end());
out.push('\n');
}
match &reading.residual {
Some(take) => out.push_str(&format!(
"# loss: pitch {:.1}, voicing {:.1}, unread {:.1}, notes {:.1} ({} frames read, {} \
unread)\n",
take.loss.pitch,
take.loss.voicing,
take.loss.unread,
take.loss.notes,
take.read_frames,
take.unread_frames
)),
None => out.push_str(
"# no residual or loss: this reading holds neither (it was written before \
capture-analysis 1.2)\n",
),
}
out
}
fn excursions(note: &ReadNote, rate: f64) -> String {
let all: Vec<_> = note.residual.iter().flat_map(|r| &r.excursions).collect();
if all.is_empty() {
return "-".to_owned();
}
all.iter()
.map(|e| {
format!(
"{:+.0}c {:.0} ms @ {:.3} s",
e.cents,
(e.end - e.start) as f64 / rate * 1000.0,
e.start as f64 / rate
)
})
.collect::<Vec<_>>()
.join("; ")
}
fn performance(path: &Path) -> Result<PerformanceFrames> {
let text = fs::read_to_string(path).with_context(|| {
format!(
"{}: compare reads the performance duet capture melody wrote",
path.display()
)
})?;
let stream =
Stream::<PerformanceHead>::read(&text).with_context(|| path.display().to_string())?;
let mut frames = PerformanceFrames::new(&stream.head);
for block in &stream.records {
frames
.push(block)
.with_context(|| path.display().to_string())?;
}
Ok(frames)
}
fn analysis(path: &Path) -> Result<Analysis> {
let text = fs::read_to_string(path).with_context(|| path.display().to_string())?;
Ok(Document::<Analysis>::read(&text)
.with_context(|| path.display().to_string())?
.body)
}
fn reading_of<'a>(analysis: &'a Analysis, path: &Path) -> Result<&'a Reading> {
analysis.reading.as_ref().with_context(|| {
format!(
"{} holds no reading: it is a rhythm take's, or was written before capture-analysis \
1.1; capture the melody again with duet capture melody",
path.display()
)
})
}
fn take(path: &Path, rate: u32) -> Result<Vec<f32>> {
let named = || path.display().to_string();
let mut source = FileSource::open(path)?;
let mut prepare = Prepare::new(rate);
let mut mono = Vec::new();
while let Some(chunk) = source.next_chunk().with_context(named)? {
prepare.push(chunk, &mut mono).with_context(named)?;
}
prepare.finish(&mut mono).with_context(named)?;
let mut samples = Vec::new();
for m in mono {
let at = usize::try_from(m.start_frame).context("a frame past the address space")?;
if samples.len() < at {
samples.resize(at, 0.0);
}
samples.truncate(at);
samples.extend_from_slice(&m.samples);
}
Ok(samples)
}
fn window_name(from: Option<f64>, to: Option<f64>) -> String {
if from.is_none() && to.is_none() {
return ".compare".to_owned();
}
let from = format!("{:?}", from.unwrap_or(0.0));
let to = to.map_or_else(|| "end".to_owned(), |t| format!("{t:?}"));
format!(".compare.{from}-{to}")
}
fn with_suffix(stem: &Path, suffix: &str) -> PathBuf {
let mut path = stem.as_os_str().to_owned();
path.push(suffix);
PathBuf::from(path)
}
fn stem_of(analysis: &Path) -> PathBuf {
let name = analysis.as_os_str().to_string_lossy();
for suffix in [".capture.duet", ".duet"] {
if let Some(stem) = name.strip_suffix(suffix) {
return PathBuf::from(stem);
}
}
analysis.to_path_buf()
}
fn seconds(t: f64) -> String {
format!("{t:.2} s")
}
fn write_bytes_new(path: &Path, bytes: &[u8]) -> Result<()> {
use std::io::Write as _;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.with_context(|| path.display().to_string())?;
if let Err(e) = file.write_all(bytes) {
let _ = fs::remove_file(path);
return Err(e).with_context(|| path.display().to_string());
}
Ok(())
}