import: records named by their own tags, and covers resampled where the pixels are

Two threads from one session, both of them the same shape: something was
being decided from the wrong source.

THE PROVIDERS WERE ASKED ABOUT A FOLDER. The picker sent the directory name
to Deezer and MusicBrainz — the ripper's naming, carrying catalogue numbers,
years and initials. "[WARP CD 156] Battles - Mirrored - 2007" matches
nothing anywhere; "Mirrored" matches instantly. Across the reference library
501 of 515 records carry a tag album and 315 disagree with their folder, and
no amount of cleaning turns "ACPP" into "Prospect Park, Brooklyn NY". The
record's own claim now leads and the folder is the fallback, in one place
(src/lib/import-title.js) that apply and the picker both read — apply
already resolved it this way, and only the picker did not. The verdict judge
had the same split: it compared candidates against the folder too, so an
exact answer scored as mere containment and a clean match wore a warning.

Identification also stops searching when searching cannot work. A folder
named "1989 Pauls Boutique" is a hopeless query and an easy comparison, so
after Deezer and MusicBrainz come back empty the artist's own catalogue is
ranked by title similarity. Scoring rather than stripping is the point: 1989,
1984 and 2001 are real albums, and any cleaner aggressive enough to rescue
Paul's Boutique would have destroyed them. Words split on whitespace with
punctuation folded inside them, so "Paul's" stays one token; pressing
vocabulary is ignored for scoring only; coverage is measured from both sides.
15 assertions pin the cases that would break it.

Cached verdicts now carry the engine that produced them. A cached match is
good forever, a cached "nothing found" only as good as the thing that
looked — and nothing ever re-asked. Negatives from an older engine, or from
a query that has since changed, are dropped and asked again.

Soulseek was asked the same wrong question, with the artist said twice:
"battles battles - mirrored - 2007". The server matches on ALL terms, so
every leftover token narrows the search — that copy was only found because
the peer happened to have 2007 in its path. The ladder now leads with the
record's name and keeps the folder as the narrower rung behind it.

AVAILABILITY OUTRANKS ENCODING. Candidate copies were ranked with avgBitrate
above hasFreeSlot, and queue depth — captured on every candidate — was never
read at all. A peer with no free slot and 277 people ahead beat a free peer
with a queue of two, because its files reported a bitrate and the others
reported none, and `?? 0` scores "didn't say" as the worst possible answer.
Bitrate is now ignored between two fully-lossless copies, where it describes
the material rather than the quality.

And nothing ever gave up. Track 1 is requested alone so it is not queued
behind eleven of our own files, the rest follow once the peer proves it will
serve us, and a copy that makes no progress for 45s is abandoned for the next
ranked one — cancelling the transfers it leaves, which used to trickle on
forever. A refusal falls through to the next peer instead of ending the
record. "Try another peer" is reachable while one is loading, which it never
was.

RE-IMPORTING BUILT A DUPLICATE FACTORY. Apply decided a track was already
filed by comparing the destination's size to its source — but apply itself
rewrites that file, embedding the chosen cover, so it is 582 KB larger from
the moment it is written and the sizes can never match again. Every run laid
down another " (n)" copy with its own library row: three runs left three of
everything, 2.16 GB. A file at the destination that this run did not write is
now simply an earlier import; within one run a repeated name is still a
collision, which is what `kept` is for.

ARTWORK FOLLOWS THE RECORD, ONLY THE AUDIO FOLLOWS THE CHOICE. Apply read
art from whichever folder the audio came from, which for a kept found copy is
the pen — and a downloaded album often carries no picture, so three records
imported with no cover while their own files held a 1500px one. It also only
ever looked at tags, never at the Folder.jpg the review had just offered as
"yours".

COVERS ARE RESAMPLED BY RUST, NOT BY THE COMPOSITOR. The webview was handed
2000px masters to paint 132px tiles — a 15x single-step reduction that reads
as aliasing on photographic covers, and carries megabytes of base64 to draw a
thumbnail. Artist portraits already had this exact fix; album covers never
got it. getArt is now bounded by default and getArtMaster is the deliberate
act, because ~60 places paint a cover and only two want real pixels: with the
polarity the other way round, every surface anyone forgets is silently wrong.
The fullscreen viewer also framed non-square art inside a square element, so
its rounded corners and shadow wrapped 96px of nothing; it takes the
artwork's own ratio now, bounded on both axes.

Smaller, from the same passes: the preview play button is a real transport
rather than a restart, and leaving a record silences its own preview without
touching music started elsewhere; bucket chips navigate with per-lens memory
instead of overwriting the saved resume position; Next counts from the
record's real place in a queue that re-sorts under it, which was skipping one
record for every one reviewed under a filter; a cover URL with nothing behind
it is shown as the empty answer it is rather than a broken image in a
pickable frame; write_tags returns early when there is nothing to change,
instead of rewriting the whole file to write values it already had; and the
import window has a Start over, which says what it costs before it costs it.
This commit is contained in:
KeelrLeek committed 2026-08-10 18:08:58 -05:00
1 parent e7d0971de2
commit c4ff6269a3
14 files changed
+1326 -138

No files matched your search

+34 -5
View File
@@ -6,7 +6,7 @@
// at the full resolution of the canonical cover (3000px-class for
// library albums). Click anywhere, Escape, or the corner button closes.
import { fade } from "svelte/transition";
import { ui, getArt, getCatalogArt } from "../lib/state.svelte.js";
import { ui, getArtMaster, getCatalogArt } from "../lib/state.svelte.js";
import Icon from "./Icon.svelte";
// { src, local, title, subtitle } — the caller says which cover and how to
@@ -22,6 +22,14 @@
const AMBIENT_BLUR = 18;
let artUrl = $state(null);
let ambientUrl = $state(null);
/** The artwork's own width/height, once it has decoded.
*
* The frame is the IMG element itself — it carries the rounded corners and
* the drop shadow — so a fixed square box around a 4:3 cover framed empty
* letterbox bands instead of the picture. Sizing the element to the real
* ratio makes the frame hug the artwork whatever shape it is. 1 until the
* image reports, which is also what the placeholder wants. */
let ratio = $state(1);
async function makeAmbient(src, isActive) {
const img = new Image();
@@ -61,9 +69,13 @@
const source = art;
artUrl = null;
ambientUrl = null;
ratio = 1;
if (!source?.src) return;
let active = true;
const pending = source.local ? getArt(source.src) : getCatalogArt(source.src);
// The master, deliberately: this window's whole point is the artwork at
// its real resolution, so it is one of the two places that opts out of
// the tile-sized default.
const pending = source.local ? getArtMaster(source.src) : getCatalogArt(source.src);
pending
.then(async (url) => {
if (!active || !url) return;
@@ -121,7 +133,17 @@
</button>
{#if artUrl}
<img class="art" src={artUrl} alt={art.title ? `${art.title} artwork` : "Album artwork"} draggable="false" />
<img
class="art"
style="--ar:{ratio}"
src={artUrl}
alt={art.title ? `${art.title} artwork` : "Album artwork"}
draggable="false"
onload={(e) => {
const { naturalWidth: w, naturalHeight: h } = e.currentTarget;
if (w > 0 && h > 0) ratio = w / h;
}}
/>
{:else}
<div class="art placeholder"><Icon name="disc" size={72} /></div>
{/if}
@@ -181,8 +203,15 @@
.art {
position: relative;
z-index: 2;
width: min(94vh, 94vw);
aspect-ratio: 1;
/* Sized to the artwork's own ratio (--ar), bounded by BOTH axes: a wide
cover is capped by the viewport width, a tall one by its height. The
old `width: min(94vh, 94vw); aspect-ratio: 1` forced a square, so
anything non-square wore its frame around empty letterbox space.
Still fills the viewport for small masters, as it did before. */
--ar: 1;
aspect-ratio: var(--ar);
width: min(94vw, 94vh * var(--ar));
height: auto;
object-fit: contain;
border-radius: 10px;
box-shadow: 0 48px 110px -34px rgba(0, 0, 0, 0.9);
+164 -43
View File
@@ -13,12 +13,20 @@
import { fade } from "svelte/transition";
import * as api from "../lib/api.js";
import Icon from "./Icon.svelte";
import { getArt, playLocalFile } from "../lib/state.svelte.js";
import { onDestroy } from "svelte";
import { getArtMaster, playLocalFile, player, togglePlayPause } from "../lib/state.svelte.js";
import { evidence as matchEvidence, normx } from "../lib/import-evidence.js";
import { IDENTIFY_ENGINE } from "../lib/import-title.js";
let {
album: a, // derived album from ImportWindow (rel, title, …)
artist, // the resolved artist (plan logic, not folder-blind)
albumName, // the resolved album NAME — tags first, folder as
// fallback. This is what the record IS: the
// heading, the verdict, what the providers are
// asked, and what the player announces. `a.title`
// is the folder on disk and survives as a hover.
sourceRoot,
index, total, // where the queue cursor is
found, // rel -> { state, result } identify cache ($state, shared)
@@ -31,6 +39,8 @@
audition, // the found-copy state for this record (window-owned)
live, // in-flight transfer facts + stall verdict, or null
onFindCopy, // () => void — search + start the audition download
onTryAnother, // () => void — abandon this peer for the next
// ranked copy, without a fresh search
accentStyle, // this record's --accent pair, cast by the window
} = $props();
@@ -90,11 +100,15 @@
found[rel] = { state: "loading", result: null };
(async () => {
try {
const r = await api.importIdentify(artist, a.title);
found[rel] = { state: "done", result: r };
const ask = albumName ?? a.title;
const r = await api.importIdentify(artist, ask);
// Stamped with the engine that produced it: a cached "nothing
// found" is only trustworthy while the thing that looked has
// not learned anything new. See IDENTIFY_ENGINE.
found[rel] = { state: "done", result: r, engine: IDENTIFY_ENGINE };
if (r.candidate?.cover) {
const rep = await api.importCoverReport(
artist, r.used ?? a.title, r.candidate.cover);
artist, r.used ?? ask, r.candidate.cover);
reports[rel] = rep;
}
} catch (e) {
@@ -124,12 +138,14 @@
() => {});
});
// Local art renders through the same data-URL path every cover uses.
// The MASTER, not the tile-sized default: this card exists to judge one
// cover against another, and the loupe magnifies it 3x. A resampled copy
// would hide exactly the difference being judged.
let yoursSrc = $state(null);
$effect(() => {
const p = yours?.path;
yoursSrc = null;
if (p) getArt(p).then((u) => { if (yours?.path === p) yoursSrc = u; });
if (p) getArtMaster(p).then((u) => { if (yours?.path === p) yoursSrc = u; });
});
// ---- provider covers, as the mock's tiles ---------------------------
@@ -182,21 +198,40 @@
// for which of two very different situations the panel is in: the report
// is still coming, or it came back with nothing. Neither is "no service
// has this record" — the identify already proved one does.
/** Candidate cover URLs the webview could not load, by url.
*
* A provider can name a cover it does not have: MusicBrainz identifies a
* release group and the cover URL is built from its MBID, but the Cover
* Art Archive answers 404 when nothing has been uploaded for it. Only the
* <img> knows — the report says "size unknown", which is also what a
* measurement that merely timed out says. */
let deadArt = $state({});
/** Every candidate turned out to be a URL with nothing behind it — which
* is a different sentence from "the sizes could not be measured": the
* service was reached and simply has no picture. */
const allDead = $derived(covers.length > 0 && covers.every((c) => deadArt[c.url]));
const unmeasured = $derived(covers.length === 1 && covers[0].px == null);
const measuring = $derived(unmeasured && !report);
const measureFailed = $derived(unmeasured && !!report);
const measureFailed = $derived(unmeasured && !!report && !allDead);
/** A match with no cover at all — a real answer, and not the same as
* nobody having heard of the record. */
const matchHasNoArt = $derived(
idn?.state === "done" && !!candidate && !candidate.cover && !covers.length);
// ---- evidence (shared with the window's outcome buckets) -------------
const ev = $derived(matchEvidence(candidate, artist, a.title, a.tracks.length));
// Judged against the record's own NAME, the same string the provider was
// asked about — not the folder. Comparing a candidate to the folder made
// an exact hit look doubtful: "Mirrored" against
// "[WARP CD 156] Battles - Mirrored - 2007" is a containment, so a clean
// match wore a "!" on its title row.
const ev = $derived(matchEvidence(candidate, artist, albumName ?? a.title, a.tracks.length));
const verdictLine = $derived.by(() => {
const c = candidate;
const v = {
none: ["warn", "Nothing on the provider matches this folder. It may be a bootleg, a session, or named differently."],
none: ["warn", "Nothing on the provider matches this record. It may be a bootleg, a session, or named differently."],
bad: ["bad", "<b>This does not look like the same record.</b> Applying it would replace your files with a different album."],
warn: ["warn", "<b>Close, but not identical.</b> Check the tracklist and listen before applying — it may be a different edition."],
ok: ["ok", "Artist, title and track count all agree. Listen to be certain."],
@@ -403,25 +438,53 @@
const yoursPath = $derived(
a.tracks[0] ? `${sourceRoot}\\${a.rel}\\${a.tracks[0].name}` : null);
const resolvedAudio = $derived(choice?.audio ?? "yours");
// ---- preview transport ----------------------------------------------
// A preview plays through the MAIN player (playLocalFile replaces the
// queue), so "is this one playing?" is a question about the player's
// current local path — not about anything this card owns.
const nowPath = $derived(player.track?.source === "local" ? player.track.path : null);
const isLive = (p) => !!p && nowPath === p;
/** Sounding right now (buffering counts — the button must offer the stop
* before the audio arrives, or a slow start is unstoppable). */
const isSounding = (p) => isLive(p) && (player.status === "playing" || player.status === "buffering");
/** One button, both jobs: start this preview, or pause/resume it if it is
* already the thing playing. Previously every press re-issued
* playLocalFile, which restarted the track — there was no way to stop it. */
function togglePreview(path, start) {
if (!path) return;
if (isLive(path)) togglePlayPause();
else start();
}
function playYours() {
if (!yoursPath) return;
playLocalFile(
yoursPath,
a.tracks[0].name.replace(/\.[a-z0-9]+$/i, ""),
`${artist} — ${a.title} · yours`,
`${artist} — ${albumName ?? a.title} · yours`,
yours?.path ?? null,
);
}
function playTheirs() {
if (!audition?.track1Path) return;
playLocalFile(
audition.track1Path,
(audition.probe?.title ?? "Track 1"),
`${artist} — ${a.title} · found copy`,
`${artist} — ${albumName ?? a.title} · found copy`,
yours?.path ?? null,
);
}
// Leaving the record silences ITS preview. The card is re-keyed per record,
// so this fires on every move as well as on closing the window.
//
// Deliberately narrow: only when what is sounding is one of THIS record's
// two files. Music the user started before opening the importer is theirs,
// and walking through records must not silence it.
onDestroy(() => {
const mine = [yoursPath, audition?.track1Path].filter(Boolean);
if (mine.includes(nowPath) && player.status === "playing") togglePlayPause();
});
// Real peaks for both lanes, drawn against the JOINT maximum so a
// quieter master honestly looks smaller — the shapes are comparable
// because the scale is shared (his ask: match the waveforms).
@@ -499,7 +562,11 @@
<span class="im-out" data-out="later"
title="You skipped this one — still in the run, still undecided">skipped for now</span>
{/if}</div>
<h3>{a.title}</h3>
<!-- The RECORD, not the folder it happens to sit in. The folder is the
ripper's naming ("[WARP CD 156] Battles - Mirrored - 2007"); the
heading says what the record is, and the folder stays one hover
away for when you need to know which directory this is. -->
<h3 title={a.title === (albumName ?? a.title) ? undefined : `folder: ${a.title}`}>{albumName ?? a.title}</h3>
<small>{artist} · {a.tracks.length} tracks · {fmtMB(a.bytes)} · {ext} {a.avgBitrate ?? "—"}k</small>
</div>
<div class="im-hero-side">
@@ -517,6 +584,7 @@
<em>{#if !idn || idn.state === "loading"}looking the record up…
{:else if idn.state === "error"}the lookup failed
{:else if measuring}found it — measuring what each service has…
{:else if allDead}found it, but no service has a cover for it
{:else if measureFailed}found it, but the sizes could not be measured
{:else if matchHasNoArt}the matching release carries no artwork
{:else if !covers.length}no service has this record
@@ -547,23 +615,42 @@
<div class="im-art-pick">{resolvedArt === "yours" ? "✓ using this" : "use this"}</div>
</div>
{#each covers as c, n (c.url)}
{@const dead = !!deadArt[c.url]}
{@const smaller = yours && c.px && c.px < yours.w}
{@const wrongTitle = c.title && norm2(c.title) !== norm2(a.title)}
<!-- A candidate whose picture will not load is shown as the empty
answer it is, and cannot be chosen. The Cover Art Archive
answers 404 for a release group with no art on file, and the
URL is built from the MBID without knowing that — so the tile
used to be a broken-image icon inside a frame that still said
"use this", and using it silently fell back at apply time. -->
<div class="im-art {smaller ? 'worse' : 'better'}"
class:picked={resolvedArt === c.provider}
role="button" tabindex="0" title="Use {c.provider}'s artwork"
onclick={() => onChoose({ art: c.provider })}
onkeydown={(e) => e.key === "Enter" && onChoose({ art: c.provider })}>
<div class="im-art-box zoom"
onclick={(e) => { e.stopPropagation(); openFs(n + 1); }}
class:dead
role={dead ? "presentation" : "button"} tabindex={dead ? -1 : 0}
title={dead
? `${c.provider} has no cover on file for this release`
: `Use ${c.provider}'s artwork`}
onclick={() => !dead && onChoose({ art: c.provider })}
onkeydown={(e) => !dead && e.key === "Enter" && onChoose({ art: c.provider })}>
<div class="im-art-box" class:zoom={!dead}
onclick={(e) => { if (!dead) { e.stopPropagation(); openFs(n + 1); } }}
role="presentation">
<img src={c.url} alt="" /></div>
<div class="im-art-lab"><span class="im-art-res" class:im-dim={!c.px}>{c.px
? `${c.px} × ${c.realH ?? c.px}`
: measuring ? "measuring…" : "size unknown"}</span>
<i>{c.provider}{smaller ? " · smaller than yours" : ""}</i></div>
{#if dead}
<div class="im-art-none">nothing on file here —<br />{c.provider} has no cover for this release</div>
{:else}
<img src={c.url} alt="" onerror={() => (deadArt[c.url] = true)} />
{/if}</div>
<div class="im-art-lab"><span class="im-art-res" class:im-dim={!c.px || dead}>{dead
? "no cover"
: c.px
? `${c.px} × ${c.realH ?? c.px}`
: measuring ? "measuring…" : "size unknown"}</span>
<i>{c.provider}{smaller && !dead ? " · smaller than yours" : ""}</i></div>
{#if wrongTitle}<div class="im-art-lab"><i class="im-amber">“{c.title}”</i></div>{/if}
<div class="im-art-pick">{resolvedArt === c.provider ? "✓ using this" : "use this"}</div>
<div class="im-art-pick">{dead
? "nothing to use"
: resolvedArt === c.provider ? "✓ using this" : "use this"}</div>
</div>
{/each}
<!-- Only once the lookup has actually SETTLED with nothing. While it
@@ -611,7 +698,7 @@
? "the transfer went quiet"
: "found a copy — fetching track 1 first, so the comparison can start"}
{:else if audition.status === "complete"}the whole copy is cached — keeping it is instant
{:else}{audition.arrived ?? 1} of {audition.ids?.length ?? "…"} tracks cached · the rest keep arriving
{:else}{audition.arrived ?? 1} of {audition.expected ?? audition.ids?.length ?? "…"} tracks cached · the rest keep arriving
{/if}</em>
<span class="im-card-hint">the lit version is what gets imported</span></div>
@@ -619,9 +706,10 @@
<div class="im-ver" class:picked={true} role="button" tabindex="0"
onclick={() => onChoose({ audio: "yours" })}
onkeydown={(e) => e.key === "Enter" && onChoose({ audio: "yours" })}>
<button class="im-play" disabled={!yoursPath} title="Play your copy"
onclick={(e) => { e.stopPropagation(); playYours(); }}>
<Icon name="play" size={13} />
<button class="im-play" disabled={!yoursPath}
title={isSounding(yoursPath) ? "Pause" : "Play your copy"}
onclick={(e) => { e.stopPropagation(); togglePreview(yoursPath, playYours); }}>
<Icon name={isSounding(yoursPath) ? "pause" : "play"} size={13} />
</button>
<div class="im-ablab"><b>Yours</b><i>{ext} {a.avgBitrate ?? "—"}k · {a.tracks.length} tracks · {fmtMB(a.bytes)}</i></div>
<div class="im-wave">{#each (peaksYours ?? waveFloor().map((b) => 0)) as v, i (i)}<i style:height={peaksYours ? waveScale(v) : "2px"} style:--fill="0" style:--i={i}></i>{/each}</div>
@@ -652,9 +740,10 @@
title="Keep your own files"
onclick={() => onChoose({ audio: "yours" })}
onkeydown={(e) => e.key === "Enter" && onChoose({ audio: "yours" })}>
<button class="im-play" disabled={!yoursPath} title="Play your copy"
onclick={(e) => { e.stopPropagation(); playYours(); }}>
<Icon name="play" size={13} />
<button class="im-play" disabled={!yoursPath}
title={isSounding(yoursPath) ? "Pause" : "Play your copy"}
onclick={(e) => { e.stopPropagation(); togglePreview(yoursPath, playYours); }}>
<Icon name={isSounding(yoursPath) ? "pause" : "play"} size={13} />
</button>
<div class="im-ablab"><b>Yours</b><i>{ext} {a.avgBitrate ?? "—"}k · {a.tracks.length} tracks · {fmtMB(a.bytes)}</i></div>
<div class="im-wave">{#each (peaksYours ?? []) as v, i (i)}<i style:height={waveScale(v)} style:--fill="0" style:--i={i}></i>{/each}</div>
@@ -672,12 +761,20 @@
onclick={() => theirsReady && onChoose({ audio: "theirs" })}
onkeydown={(e) => e.key === "Enter" && theirsReady && onChoose({ audio: "theirs" })}>
<button class="im-play" disabled={!theirsReady}
title={theirsReady ? "Play the found copy" : "Still arriving"}
onclick={(e) => { e.stopPropagation(); playTheirs(); }}>
<Icon name="play" size={13} />
title={!theirsReady
? "Still arriving"
: isSounding(au.track1Path) ? "Pause" : "Play the found copy"}
onclick={(e) => { e.stopPropagation(); togglePreview(au.track1Path, playTheirs); }}>
<Icon name={isSounding(au.track1Path) ? "pause" : "play"} size={13} />
</button>
<div class="im-ablab">
<b>{au.candidate.folderLeaf}</b>
<!-- "Found copy", to match "Yours" on the lane above. This
used to lead with the PEER's folder name ("[WARP 156CD]
Battles …"), which is the same rip-descriptor noise the
heading carried — and in a 150px label it truncated to
nothing useful anyway. Which peer and which folder is what
the sub-line and the hover are for. -->
<div class="im-ablab" title={`${au.candidate.folderLeaf} · ${au.candidate.username}`}>
<b>Found copy</b>
<i>{au.probe
? `${(au.candidate.files[0]?.name ?? "").split(".").pop().toUpperCase()} ${au.probe.bitrate ?? "—"}k${au.probe.bitDepth ? ` · ${au.probe.bitDepth}-bit` : ""} · measured`
: theirsReady
@@ -707,16 +804,18 @@
nothing used to say so — the pill changed and that was all. -->
{#if !theirsReady && live?.stalled}
<b class="im-amber">Nothing has arrived for {Math.round(live.quietMs / 1000)}s.</b>
The peer may have gone offline or dropped the queue. You can wait, search
again, or keep your own copy — nothing is lost either way.
The peer may have gone offline or dropped the queue. You can wait, try
another peer, or keep your own copy — nothing is lost either way.
{:else if !theirsReady}
Track 1 comes first on purpose: the comparison can start before the rest of
the album is down.
Track 1 is asked for on its own, so it is not queued behind the other
{au.candidate.trackCount - 1} files of its own album.{#if au.switchedFrom}
&nbsp;·&nbsp;Moved on from <b>{au.switchedFrom}</b>{au.reason ? ` — ${au.reason}` : ""}.
{/if}
{:else if au.probe?.seconds && a.tracks[0]?.seconds}
{@const d = Math.abs(a.tracks[0].seconds - au.probe.seconds)}
{#if d <= 2}
<b class="im-ready">Ready to compare.</b>
Track 1 is the same length in both ({mmss(au.probe.seconds)}) — the strongest signal it is the same recording. The waveforms share one scale, so shape and loudness compare honestly.{#if au.status !== "complete"} The other {Math.max(0, (au.ids?.length ?? 0) - (au.arrived ?? 0))} tracks are still coming; keeping this version waits for them.{/if}
Track 1 is the same length in both ({mmss(au.probe.seconds)}) — the strongest signal it is the same recording. The waveforms share one scale, so shape and loudness compare honestly.{#if au.status !== "complete"} The other {Math.max(0, (au.expected ?? au.ids?.length ?? 0) - (au.arrived ?? 0))} tracks are still coming; keeping this version waits for them.{/if}
{:else}
<b class="im-amber">Track 1 differs by {d}s</b> — different recording, different edit, or a different record. Listen before keeping it.
{/if}
@@ -726,6 +825,22 @@
The whole album downloads into the cache — if you keep it, nothing is fetched twice; if you keep yours, the sweep reclaims it in a week.
{/if}
</div>
<!-- Reachable WHILE a peer is loading. There was no way out of a bad
peer once one was chosen: the only "Find a better copy" button
lives in the no-audition state, so a queue of 277 could only be
waited out. Alternates are already ranked and held, so switching
costs no new search. -->
{#if !theirsReady}
{@const alts = au.alts?.length ?? 0}
<div class="im-ab-find">
<button class="pill ghost" onclick={alts ? onTryAnother : onFindCopy}>
{alts ? "Try another peer" : "Search again"}
</button>
<small>{alts
? `${alts} more ${alts === 1 ? "copy" : "copies"} ranked behind this one${au.candidate.queue ? ` — this peer has ${au.candidate.queue} ahead of you` : ""}. Switching cancels this download; nothing already cached is lost.`
: "No ranked alternates left for this copy — this asks the network again."}</small>
</div>
{/if}
{/if}
</div>
@@ -916,7 +1031,7 @@
&nbsp;vs&nbsp; {right.provider} {right.px} × {right.realH ?? right.px}
</div>
<div class="im-fs-bot">
{#each covers as c, n (c.url)}
{#each covers.filter((c) => !deadArt[c.url]) as c, n (c.url)}
<div class="im-fs-pick" role="button" tabindex="0"
aria-selected={fsPick === n + 1}
onclick={() => (fsPick = n + 1)}
@@ -1028,6 +1143,12 @@
.im-art-res { font-variant-numeric: tabular-nums; }
.im-art.better .im-art-res { color: var(--accent-hover); }
.im-art.worse .im-art-res { color: #e9b949; }
/* Not an option, so it does not look like one: no pointer, no hover lift,
and the size line stays muted rather than reading as a measurement. */
.im-art.dead { cursor: default; }
.im-art.dead:hover { background: none; }
.im-art.dead .im-art-res,
.im-art.dead .im-art-pick { color: var(--text-muted); }
.im-art-none { display: grid; place-items: center; height: 100%; color: var(--text-muted); font-size: 12px; text-align: center; padding: 12px; }
.im-ev { display: flex; flex-wrap: wrap; gap: 7px; }
+353 -52
View File
@@ -16,6 +16,7 @@
import ImportPicker from "./ImportPicker.svelte";
import { evidence as matchEvidence } from "../lib/import-evidence.js";
import { foldReleases } from "../lib/import-fold.js";
import { majority, albumNameOf, artistNameOf, IDENTIFY_ENGINE } from "../lib/import-title.js";
import { findAlbumCopies, startAudition } from "../lib/import-audio.js";
const STEPS = [
@@ -83,14 +84,17 @@
// would dress a transfer that is not running as one that is —
// reading either "53% of track 1" or, once the stall clock caught
// up, "the peer went quiet" about a peer nobody is talking to.
// `switching` goes too: it is a re-entry guard for one in-flight
// cancel-and-retry. Persisted true, it would come back as a record
// that can never switch peers again.
const auditionsToSave = Object.fromEntries(
Object.entries(auditions).map(([rel, au]) => {
const { xfer, ...rest } = au ?? {};
const { xfer, switching, ...rest } = au ?? {};
return [rel, rest];
}));
await api.importSessionSet(JSON.stringify({
step, root, scan, layout: layoutChoice, choices, found: done, pick, pickRel,
bucket, auditions: auditionsToSave, keepSeparate,
bucket, bucketRel, auditions: auditionsToSave, keepSeparate,
}));
} catch (e) {
console.warn("import: session save failed", e);
@@ -112,6 +116,7 @@
pick = v.pick ?? 0;
pickRel = v.pickRel ?? null;
bucket = v.bucket ?? "all";
bucketRel = v.bucketRel ?? {};
// Auditions survive by their files: ids are stale after a
// restart, but a cached track 1 (or full album) on disk is
// still every bit as comparable and keepable.
@@ -405,22 +410,19 @@
albums
.filter((a) => !a.junk)
.map((a) => {
const tagArtist = majority(a.tracks.map((t) => t.artist));
const tagYear = majority(a.tracks.map((t) => t.year));
// The album NAME comes from the tags when they agree on one —
// the folder is the ripper's naming ("Heartleap - WEB V0"),
// the tags are the record's own claim ("Heartleap"), and the
// row title is what the catalog joins on. Folder as fallback.
// One definition, in import-title.js, so the picker asks the
// provider the same question apply writes (they disagreed: the
// picker searched the folder and found nothing for records
// whose tags name them perfectly well).
return {
rel: a.rel,
artist: a.depth >= 2 ? a.artistFolder : (tagArtist ?? a.artistFolder),
// A folded release takes its FOLDER's name. The tags on a
// folded record describe the parts ("Analord 01"…"Analord
// 11"), so a tag majority would title the whole set after
// whichever volume happened to carry the most tracks.
album: a.parts
? a.title
: majority(a.tracks.map((t) => t.album)) ?? a.title,
artist: artistNameOf(a),
album: albumNameOf(a),
year: a.year ?? tagYear ?? null,
// Where the audio actually is, relative to `rel`. Empty for
// an ordinary record; apply reads its own folder then.
@@ -428,13 +430,6 @@
};
}));
function majority(values) {
const tally = new Map();
for (const v of values) if (v != null && v !== "") tally.set(v, (tally.get(v) ?? 0) + 1);
let best = null, n = 0;
for (const [v, c] of tally) if (c > n) { best = v; n = c; }
return best;
}
// ---- the upgrades picker's queue -------------------------------------
// Artist A–Z, then chronological within the artist — the shelf order,
@@ -465,6 +460,10 @@
let bucket = $state("all");
const bucketByRel = $derived.by(() => {
const artistOf = new Map(plan.map((p) => [p.rel, p.artist]));
// Judged against the name the provider was ASKED about, so the bucket
// and the picker's verdict panel agree — and so a record whose folder
// is a rip descriptor is not filed as merely "close" to its own match.
const albumOf = new Map(plan.map((p) => [p.rel, p.album]));
const m = new Map();
for (const x of pickerBase) {
const f = found[x.rel];
@@ -475,7 +474,7 @@
k = matchEvidence(
f.result.candidate,
artistOf.get(x.rel) ?? x.artistFolder,
x.title,
albumOf.get(x.rel) ?? x.title,
x.tracks.length,
).verdict;
m.set(x.rel, k);
@@ -568,9 +567,58 @@
schedulePersist();
}
// A cached verdict is an answer to the question that was ASKED. The picker
// used to ask about the folder, so every "nothing found" in a resumed
// session answers a question we no longer ask — and because the cache is
// never revisited (`if (found[rel]) return`), those records would stay
// unmatched forever behind a stale no.
//
// Drop exactly the ones whose question changed, and only when the answer
// was NOTHING: a real match is left alone, so this cannot cost a good
// answer, and re-asking is deferred until the record is actually opened.
let sweptStale = false;
$effect(() => {
if (sweptStale || !albums.length) return;
const rels = Object.keys(found);
if (!rels.length) return;
sweptStale = true;
const byRel = new Map(albums.map((a) => [a.rel, a]));
let dropped = 0;
for (const rel of rels) {
const f = found[rel];
if (f?.result?.candidate) continue; // a real answer stands
// Looked with an older engine: the question may be unchanged but
// the answer is not, so it gets asked again.
if ((f?.engine ?? 1) < IDENTIFY_ENGINE) {
delete found[rel];
dropped++;
continue;
}
const rec = byRel.get(rel);
if (!rec) continue;
const asked = f?.result?.tries?.[0] ?? null;
const asksNow = albumNameOf(rec);
if (asked != null && asksNow != null && asked !== asksNow) {
delete found[rel];
dropped++;
}
}
if (dropped) {
console.info(`import: re-asking ${dropped} record(s) — the query changed`);
schedulePersist();
}
});
function pickerArtist(x) {
return plan.find((p) => p.rel === x.rel)?.artist ?? x.artistFolder;
}
/** The name the picker asks the PROVIDERS about. The artist already came
* from the plan rather than the folder; the album did not, which is why a
* record whose tags say "Mirrored" was searched for as
* "[WARP CD 156] Battles - Mirrored - 2007" and matched nothing. */
function pickerAlbum(x) {
return plan.find((p) => p.rel === x.rel)?.album ?? x.title;
}
let persistTimer = 0;
function schedulePersist() {
clearTimeout(persistTimer);
@@ -593,46 +641,142 @@
* audition download (whole album into the cache pen, track 1 first).
* Identification never gates this — deep cuts get their find too; a
* TRUSTED provider match just strengthens the query ladder. */
/** How many ranked runners-up to keep, so a bad peer costs a retry rather
* than a whole new search. */
const AUDITION_ALTS = 4;
/** How long track 1 may make NO progress before we stop waiting on this
* peer. A queue place that never moves reads exactly like a live transfer
* otherwise — there was nothing that ever gave up, so a peer with 277
* people ahead held the card indefinitely. */
const AUDITION_WAIT_MS = 45000;
/** Only what the card and a retry need — the raw search result carries the
* whole response object. */
const slimCandidate = (c) => ({
username: c.username,
folderLeaf: c.folderLeaf,
trackCount: c.trackCount,
avgBitrate: c.avgBitrate,
lossless: c.lossless,
bytes: c.bytes,
countMatch: c.countMatch,
queue: c.queue ?? null,
hasFreeSlot: !!c.hasFreeSlot,
files: (c.files ?? []).map((f) => ({ path: f.path, name: f.name, size: f.size ?? 0 })),
});
/** Begin (or re-begin) an audition on `cand`, keeping `alts` as fallbacks.
* TRACK 1 ONLY — the rest is requested once it lands. */
async function beginAudition(rel, cand, alts, { attempt = 1, dead = [], switchedFrom = null, reason = null } = {}) {
const { ids } = await startAudition(rel, cand, { from: 0, count: 1 });
auditions[rel] = {
status: "downloading",
candidate: cand,
alts,
attempt,
switchedFrom,
reason,
// The album's real length. `ids` only holds track 1 until the rest
// are asked for, so it cannot be what "all of it arrived" counts.
expected: cand.trackCount,
ids,
dead,
arrived: 0,
track1Path: null,
probe: null,
startedAt: Date.now(),
};
schedulePersist();
}
/** The remaining tracks, once track 1 has proved the peer will actually
* serve us. */
async function startRest(rel) {
const au = auditions[rel];
if (!au || au.restStarted || !au.candidate?.files?.length) return;
au.restStarted = true;
if (au.candidate.files.length <= 1) return;
try {
const { ids } = await startAudition(rel, au.candidate, { from: 1 });
const cur = auditions[rel];
if (cur && cur.candidate?.username === au.candidate.username) {
cur.ids = [...(cur.ids ?? []), ...ids];
schedulePersist();
}
} catch (e) {
console.warn("import: rest of album failed to start", e);
}
}
/** Stop waiting on this peer and drop to the next ranked copy.
*
* Cancels the transfers first — without that, a switch left the old peer
* trickling in the background forever. Their ids go on a `dead` list so a
* late event from a cancelled transfer cannot be credited to the new one. */
async function switchPeer(rel, reason) {
const au = auditions[rel];
if (!au || au.switching || au.status === "searching") return;
au.switching = true;
const dead = [...(au.dead ?? []), ...(au.ids ?? [])];
for (const id of au.ids ?? []) {
try { await api.cancelDownload(id); } catch {}
}
const [next, ...rest] = au.alts ?? [];
if (!next) {
auditions[rel] = { status: "none", dead, exhausted: true, reason };
schedulePersist();
return;
}
try {
await beginAudition(rel, next, rest, {
attempt: (au.attempt ?? 1) + 1,
dead,
switchedFrom: au.candidate?.username ?? null,
reason,
});
} catch (e) {
console.warn("import: switching peer failed", e);
auditions[rel] = { status: "failed", error: String(e), dead };
schedulePersist();
}
}
async function findBetterCopy(rel) {
const x = pickerBase.find((r) => r.rel === rel);
if (!x || auditions[rel]?.status === "searching") return;
auditions[rel] = { status: "searching" };
// A re-search from a live audition stops the old peer first; otherwise
// its transfers keep running with nothing watching them.
const prev = auditions[rel];
const dead = [...(prev?.dead ?? []), ...(prev?.ids ?? [])];
for (const id of prev?.ids ?? []) {
try { await api.cancelDownload(id); } catch {}
}
auditions[rel] = { status: "searching", dead };
try {
const trusted = ["ok", "warn"].includes(bucketByRel.get(rel));
const list = await findAlbumCopies({
artist: pickerArtist(x),
title: x.title,
// The record's own name leads; its folder is the narrower
// fallback for when the tags are wrong or absent.
album: pickerAlbum(x),
folder: x.title,
candidate: trusted ? found[rel]?.result?.candidate : null,
wantTracks: x.tracks.length,
});
if (!list.length) {
auditions[rel] = { status: "none" };
auditions[rel] = { status: "none", dead };
schedulePersist();
return;
}
const best = list[0];
const { ids } = await startAudition(rel, best);
auditions[rel] = {
status: "downloading",
candidate: {
username: best.username,
folderLeaf: best.folderLeaf,
trackCount: best.trackCount,
avgBitrate: best.avgBitrate,
lossless: best.lossless,
bytes: best.bytes,
countMatch: best.countMatch,
files: best.files.map((f) => ({ path: f.path, name: f.name, size: f.size ?? 0 })),
},
ids,
arrived: 0,
track1Path: null,
probe: null,
};
schedulePersist();
await beginAudition(
rel,
slimCandidate(list[0]),
list.slice(1, 1 + AUDITION_ALTS).map(slimCandidate),
{ dead },
);
} catch (e) {
console.warn("import: find copy failed", e);
auditions[rel] = { status: "failed", error: String(e) };
auditions[rel] = { status: "failed", error: String(e), dead };
}
}
@@ -662,19 +806,32 @@
const au = rel ? auditions[rel] : null;
const idx = typeof p.idx === "number" ? p.idx : (au?.ids?.indexOf(p.id) ?? -1);
if (!au || idx < 0) return;
// A peer we walked away from can still emit — the cancel and its last
// event race. Crediting those to the copy that replaced it would
// inflate its count and, for a Complete, fake a track it never sent.
if (p.id != null && (au.dead ?? []).includes(p.id)) return;
if (p.done) {
au.arrived = (au.arrived ?? 0) + 1;
if (idx === 0) {
au.track1Path = p.localPath;
au.status = "ready";
probeAudition(rel, p.localPath);
// The peer has proved it will serve us; ask for the rest now.
startRest(rel);
}
if (au.arrived >= (au.ids?.length ?? 0)) au.status = "complete";
if (au.arrived >= (au.expected ?? au.ids?.length ?? 0)) au.status = "complete";
au.xfer = { ...(au.xfer ?? {}), phase: "transferring", at: Date.now(), bytesAt: Date.now() };
schedulePersist();
} else if (p.failed && idx === 0 && !au.track1Path) {
au.status = "failed";
// A refusal is an answer, and the answer is "not this peer". Giving
// up here wasted the four ranked copies already in hand — the same
// dead end as waiting forever, reached faster.
au.error = p.failed;
if ((au.alts?.length ?? 0) && !au.switching) {
switchPeer(rel, `the peer could not send it — ${p.failed}`);
} else {
au.status = "failed";
}
} else if (!p.failed) {
// Progress. Before track 1 lands the row speaks for track 1
// specifically — that is the file the comparison needs — and
@@ -711,6 +868,24 @@
const t = setInterval(() => (now = Date.now()), 1000);
return () => clearInterval(t);
});
// Nothing used to give up. A peer that accepts the request and then parks
// you at #277 looks identical to one about to send — the row said "queued
// at the peer · nothing to do but wait", and meant it literally.
//
// The clock is on PROGRESS, not on the attempt: a copy that is actually
// transferring keeps its slot however long it takes, and only silence is
// punished. `bytesAt` already tracks the last byte that really landed.
$effect(() => {
const t = now;
for (const [rel, au] of Object.entries(auditions)) {
if (!au || au.status !== "downloading" || au.track1Path || au.switching) continue;
const since = au.xfer?.bytesAt ?? au.startedAt ?? t;
if (t - since > AUDITION_WAIT_MS) {
switchPeer(rel, `no progress for ${Math.round(AUDITION_WAIT_MS / 1000)}s`);
}
}
});
/** No bytes for this long, while actually transferring, is a stall. A
* QUEUED transfer is not stalled — it is behaving exactly as told. */
const STALL_MS = 30_000;
@@ -775,10 +950,24 @@
* record would otherwise seek to where it already is and look like a
* dead button. Only with nothing left undecided does Review get it. */
function advanceCursor() {
if (pick + 1 < pickerQueue.length) seekIndex(pick + 1);
// Where "next" is depends on whether the record you just dealt with is
// still IN the lens. A filtered queue re-sorts itself under you: in
// "Not looked yet", merely opening a record identifies it, so it leaves
// the bucket while you are looking at it and every later index shifts
// down by one. `pick` does not follow (the cursor effect only tracks a
// record the queue still contains), so `pick + 1` stepped over the
// record that had just slid into the vacated slot — one skipped for
// every record reviewed under that filter.
const at = pickerQueue.findIndex((x) => x.rel === curPick?.rel);
const next = at >= 0 ? at + 1 : pick;
if (next < pickerQueue.length) seekIndex(next);
else if (!widenPastBucket()) {
// Exclude the record just dealt with by its position in THIS queue.
// `pick` is not it once the record has left the lens, and excluding
// the wrong index is how a wrap could hand back the very record it
// meant to skip past.
const back = pickerQueue.findIndex(
(x, i) => i !== pick && !choices[x.rel]?.seen);
(x, i) => i !== at && !choices[x.rel]?.seen);
if (back >= 0) seekIndex(back);
else step = "review";
}
@@ -799,14 +988,36 @@
if (pick <= 0) step = "review";
else seekIndex(pick - 1);
}
/** Changing the lens keeps the record under the cursor when the new lens
* still shows it — the old `pick = 0` threw the position away on every
* bucket click, which is half of why the position was never worth
* saving. */
/** Where each lens was last looking. A chip is a place you go, so it has to
* be a place you can come BACK to — otherwise browsing "Not looked yet"
* from the middle of a review costs you your position, which is exactly
* what the old `seekIndex` fallback did (it writes `pickRel`, the saved
* resume point, so the place was not merely lost on screen but persisted
* over). Remembering each lens separately means the chips can navigate —
* visibly do something — without any of them being able to lose a place. */
let bucketRel = $state({});
/** Changing the lens takes you into it, and remembers where you were.
*
* Where you land, in order:
* 1. Where you last were IN THIS LENS. Tabs that keep their own place
* are the whole point — "All" has to be able to hand you back the
* record you were reviewing, and it can only do that from memory:
* "keep the current record if the lens shows it" can never lose for
* All, which contains everything, so it would win every time and the
* memory would be dead code.
* 2. The record already under the cursor, when this lens shows it and
* has no memory of its own — switching lenses on the record you are
* reading should not move you for no reason.
* 3. The lens's first undecided record. */
function setBucket(k) {
if (k === bucket) return;
const keep = curPick?.rel;
if (keep) bucketRel[bucket] = keep;
bucket = k;
if (!(keep && seekTo(keep))) seekIndex(Math.max(0, nextUndecided(pickerQueue)));
if (bucketRel[k] && seekTo(bucketRel[k])) { schedulePersist(); return; }
if (keep && seekTo(keep)) { schedulePersist(); return; }
seekIndex(Math.max(0, nextUndecided(pickerQueue)));
schedulePersist();
}
@@ -1060,6 +1271,50 @@
}
const stepIndex = $derived(STEPS.findIndex(([k]) => k === step));
// ---- start over ------------------------------------------------------
// A session is sticky by design — it survives closing the window, and the
// resume machinery exists to put you back exactly where you were. That
// left no way to say "forget all this and scan something else": the only
// route was deleting import-session.json by hand.
let confirmReset = $state(false);
/** What the reset actually costs, counted rather than guessed at. */
const resetCost = $derived.by(() => ({
records: pickerBase.length,
decided: Object.values(choices).filter((c) => c?.seen).length,
cached: Object.values(auditions).filter(
(a) => a?.track1Path || a?.status === "complete" || a?.status === "ready").length,
}));
async function startOver() {
// Clears the session file AND the audition pen — every penned copy is
// one this run downloaded and did not keep, so the run ending is what
// makes it collectable.
try {
await api.importSessionClear();
} catch (e) {
console.warn("import: could not clear the session", e);
error = String(e);
}
step = "source";
root = null;
scan = null;
scanProg = null;
scanEta = null;
ledger = [];
choices = {};
found = {};
auditions = {};
keepSeparate = [];
localArts = {};
reports = {};
pick = 0;
pickRel = null;
bucket = "all";
bucketRel = {};
report = null;
confirmReset = false;
updateResume();
}
</script>
<svelte:window onkeydown={onKey} />
@@ -1076,11 +1331,34 @@
<i>{i < stepIndex ? "✓" : i + 1}</i>{label}
</div>
{/each}
<!-- Only once there is a run to throw away. On the empty Source
step there is nothing to start over FROM. -->
{#if root || scan}
<button class="im-rail-reset" onclick={() => (confirmReset = !confirmReset)}
aria-expanded={confirmReset}
title="Forget this scan and every decision in it, and begin a new import">
Start over</button>
{/if}
<button class="im-rail-close" onclick={close}
title="Save and close — nothing is lost">✕</button>
</div>
<div class="im-body">
<!-- Says what it costs before it costs it. The counts are real, so
the sentence cannot quietly become untrue as the run grows. -->
{#if confirmReset}
<div class="im-left im-reset">
<b>Start over?</b>
This forgets the scan of {nfmt(resetCost.records)} record{resetCost.records === 1 ? "" : "s"}{#if resetCost.decided}, the
{nfmt(resetCost.decided)} decision{resetCost.decided === 1 ? "" : "s"} made so far{/if}{#if resetCost.cached}, and
{nfmt(resetCost.cached)} downloaded cop{resetCost.cached === 1 ? "y" : "ies"} waiting in the cache{/if}.
<b>Your music is not touched</b> — not the source folder, and not what is already in the library.
<div class="im-reset-row">
<button class="pill ghost" onclick={() => (confirmReset = false)}>Keep this run</button>
<button class="pill danger" onclick={startOver}>Discard it and start over</button>
</div>
</div>
{/if}
<!-- What the last apply left behind, carried into whatever step
you come back to. A background bank has no Done screen to
show it on, so without this the only trace of a refusal was
@@ -1366,6 +1644,7 @@
<ImportPicker
album={curPick}
artist={pickerArtist(curPick)}
albumName={pickerAlbum(curPick)}
sourceRoot={scan?.root ?? root}
index={Math.min(pick, pickerQueue.length - 1)}
total={pickerQueue.length}
@@ -1374,6 +1653,7 @@
audition={auditions[curPick.rel]}
live={liveOf(auditions[curPick.rel])}
onFindCopy={() => findBetterCopy(curPick.rel)}
onTryAnother={() => switchPeer(curPick.rel, "you asked for another peer")}
onChoose={(patch) => choose(curPick.rel, patch)}
onSnapshot={(snap) => snapshot(curPick.rel, snap)}
onReset={() => { delete choices[curPick.rel]; schedulePersist(); }}
@@ -1545,6 +1825,16 @@
font-size: 14px; font-family: inherit;
}
.im-rail-close:hover { color: var(--text-primary); }
/* Sits before the ✕ and takes its `margin-left: auto`, so the pair stays
pinned right however many steps the rail carries. */
.im-rail-reset {
margin-left: auto; border: 0; background: none;
color: var(--text-muted); padding: 4px 8px; cursor: pointer;
font-family: inherit; font-size: 11px; font-weight: 800;
letter-spacing: 0.05em; text-transform: uppercase;
}
.im-rail-reset:hover, .im-rail-reset[aria-expanded="true"] { color: #f0a0a0; }
.im-rail-reset + .im-rail-close { margin-left: 0; }
.im-body {
flex: 1; min-height: 0; position: relative; z-index: 1;
@@ -1839,6 +2129,17 @@
.im-left-rows { margin-top: 7px; display: flex; flex-direction: column; gap: 3px; }
.im-left-rows b { color: var(--text-primary); font-weight: 700; }
/* Red rather than amber: the band above reports something that already
happened, this one asks permission to destroy something. */
.im-reset {
background: rgba(233, 90, 90, 0.1);
box-shadow: inset 0 0 0 1px rgba(233, 90, 90, 0.32);
}
.im-reset b { color: #f0a0a0; }
.im-reset-row { margin-top: 10px; display: flex; gap: 8px; }
.pill.danger { background: rgba(233, 90, 90, 0.9); color: #1a0d0d; }
.pill.danger:hover { background: rgba(233, 90, 90, 1); }
.im-err {
margin-top: 14px; padding: 11px 13px; border-radius: var(--radius);
font-size: 12.5px; line-height: 1.5;
+6 -1
View File
@@ -97,13 +97,18 @@
// Covers resolve asynchronously through the shared art cache; keep the
// resolved data URLs keyed by path so a re-render never re-requests.
//
// These are the smallest tiles in the app — 40px — so they take a smaller
// bound than the app-wide default rather than carrying a 512px cover to
// draw a thumbnail. A couple of kilobytes per row.
const RECENT_EDGE = 128;
let artUrls = $state({});
$effect(() => {
for (const a of recentsStore.albums) {
const p = a.art_path;
if (!p || artUrls[p] !== undefined) continue;
artUrls[p] = null;
getArt(p).then((u) => (artUrls[p] = u)).catch(() => {});
getArt(p, RECENT_EDGE).then((u) => (artUrls[p] = u)).catch(() => {});
}
});
+8 -4
View File
@@ -130,7 +130,10 @@ export const smtcMetadata = (title, artist, album, art) =>
});
// The WebView blocks target="_blank"; external links open via the backend.
export const openExternal = (url) => invoke("open_external", { url });
export const albumArt = (path) => invoke("album_art", { path });
// `maxEdge` asks the backend for a Lanczos3 thumbnail bounded to that many
// pixels on the long side. Omit it only where true pixels matter (the
// fullscreen viewer, the import picker's comparison and loupe).
export const albumArt = (path, maxEdge = null) => invoke("album_art", { path, maxEdge });
export const refreshAlbumArt = (albumId) => invoke("refresh_album_art", { albumId });
export const refreshAllAlbumArt = () => invoke("refresh_all_album_art");
export const getSettings = () => invoke("get_settings");
@@ -244,9 +247,10 @@ export const importLocalArt = (sourceRoot, rel) => invoke("import_local_art", {
// Prune rows whose files are gone, then index anything new — the real rescan.
export const rescanLibrary = () => invoke("rescan_library");
// Download a found album copy into (Cache)\_audition\<rel>\ for the version
// comparison. files ordered track-1-first; returns transfer ids.
export const importAudition = (username, rel, files) =>
invoke("import_audition", { username, rel, files });
// comparison. Called track 1 first, then the rest — `startIndex` keeps the
// second batch's indices continuing, since index 0 means "track 1".
export const importAudition = (username, rel, files, startIndex = 0) =>
invoke("import_audition", { username, rel, files, startIndex });
export const onImportAudition = (cb) => listen("import:audition", (e) => cb(e.payload));
// Measured facts about one audio file (the version card's quality chips).
export const importProbeFile = (path) => invoke("import_probe_file", { path });
Binary file not shown.
+7 -1
View File
@@ -21,7 +21,13 @@ export const coreTitle = (s) =>
/** What is actually known about whether candidate `c` is the same record as
* the scanned album (title + artist + your track count). Each row is a
* fact the user can check, not a score they have to trust. */
* fact the user can check, not a score they have to trust.
*
* `artist` and `title` must be the RESOLVED names — what the provider was
* actually asked about (see import-title.js), never the raw folder. Judging a
* candidate against a folder like "[WARP CD 156] Battles - Mirrored - 2007"
* turns an exact answer into a mere containment, and files a clean match as
* "close". */
export function evidence(c, artist, title, trackCount) {
if (!c) return { items: [], verdict: "none", edition: false };
const artistOk = normx(c.artist) === normx(artist);
+64
View File
@@ -0,0 +1,64 @@
// What a scanned record calls ITSELF — the name the catalog should be asked
// about.
//
// The folder is the ripper's naming. It carries catalog numbers, rip
// descriptors, years and initials: "[WARP CD 156] Battles - Mirrored - 2007",
// "AJJ_ChristmasIsland", "ACPP". The tags are the record's own claim:
// "Mirrored", "Christmas Island", "Prospect Park, Brooklyn NY (7.12.2011)".
// Across the reference library 501 of 515 records carry a tag album and 315 of
// those disagree with their folder — so asking a provider about the folder is
// asking the wrong question, and no amount of cleaning turns "ACPP" into the
// right one.
//
// This is deliberately NOT used for the Soulseek search. Peers are searched by
// FILE NAME, where the ripper's descriptors are exactly what finds a match —
// the folder that fails at Deezer is the one that found "[WARP 156CD] Battles"
// on the network. Catalog lookups want the claim; file search wants the naming.
/** Which generation of the identify logic produced a cached answer.
*
* A cached MATCH is good forever. A cached "nothing found" is only as good as
* the thing that did the looking, so when identification learns a new way to
* find a record, every stored negative becomes a stale opinion — and nothing
* re-asks, because the cache is never revisited once written.
*
* Bump this whenever identify gains ground. Negatives stamped with an older
* number are dropped on the next session load and asked again.
*
* 1. Deezer try-list, MusicBrainz fallback.
* 2. + the artist's own catalogue, ranked by title similarity — finds records
* whose folder name no release carries ("1989 Pauls Boutique"). */
export const IDENTIFY_ENGINE = 2;
/** The value most of the list agrees on, ignoring blanks. Ties go to the first
* value seen, which keeps the result stable for a re-render. */
export function majority(values) {
const tally = new Map();
for (const v of values) if (v != null && v !== "") tally.set(v, (tally.get(v) ?? 0) + 1);
let best = null;
let n = 0;
for (const [v, c] of tally) if (c > n) { best = v; n = c; }
return best;
}
/** The album name to ask a provider about: the tags' majority, the folder as
* fallback.
*
* A FOLDED release is the exception and takes its folder's name. Its parts'
* tags describe the parts ("Analord 01"…"Analord 11"), so a tag majority
* would title the whole set after whichever volume carried the most tracks.
*
* `record` is a scanned album: { parts?, title, tracks: [{ album }] }. */
export function albumNameOf(record) {
if (!record) return null;
if (record.parts) return record.title;
return majority((record.tracks ?? []).map((t) => t.album)) ?? record.title;
}
/** The artist to ask about. A record nested under an artist folder is named by
* that folder; a loose one has only its tags to go on. */
export function artistNameOf(record) {
if (!record) return null;
if (record.depth >= 2) return record.artistFolder;
return majority((record.tracks ?? []).map((t) => t.artist)) ?? record.artistFolder;
}
+67 -1
View File
@@ -404,9 +404,22 @@ const ART_CACHE_MAX_CHARS = 32 * MIB;
export function evictArt(path) {
artCache.delete(path);
// The thumbnails are keyed by edge as well, so a replaced cover has to drop
// every size it was cached at — otherwise refreshing art repaints the tiles
// from the old picture while the viewer shows the new one.
for (const key of [...artThumbCache.keys()]) {
if (key.endsWith(`|${path}`)) artThumbCache.delete(key);
}
}
export async function getArt(path) {
/** The art FILE, at whatever resolution it was stored — masters here run past
* 4000px. Only for surfaces that must show true pixels: the fullscreen viewer
* and the import picker's A/B comparison and loupe.
*
* Everything else wants `getArt`. Painting a master into a tile makes the
* webview reduce it in one step, which is what made photographic covers look
* aliased, and it carries megabytes of base64 to draw a 132px square. */
export async function getArtMaster(path) {
if (!path) return null;
if (artCache.has(path)) return touchCache(artCache, path);
// PlayerBar, NowPlaying, and accent extraction can all request the same
@@ -442,6 +455,59 @@ export async function getArt(path) {
return pending;
}
// `${edge}|${path}` -> data URL. Tile-sized art, resampled by Rust instead of
// by the compositor: a 2000px master squeezed into a 132px card is a 15x
// single-step reduction, which aliases badly on photographic covers. Held
// separately from `artCache` because the two answer different questions —
// this one is what a card should paint, that one is the actual file, and the
// viewer and the import picker must keep getting the actual file.
//
// The entry budget is higher and the byte budget lower than the full-size
// cache on purpose: thumbnails are ~50KB where masters run to megabytes, so
// far more of them fit in far less memory.
const artThumbCache = new Map();
const ART_THUMB_CACHE_MAX = 512;
const ART_THUMB_CACHE_MAX_CHARS = 16 * MIB;
/** How big a cover comes back when nobody says otherwise. Covers the largest
* thing that paints one short of the viewer — the library expander's ~300px
* rail — with room for a 2x display, and never upscales anything smaller. */
export const ART_EDGE_DEFAULT = 512;
/** Album art as a data URL, bounded to `edge` px on the long side.
*
* This is the DEFAULT path on purpose. Asking for the master has to be the
* deliberate act (`getArtMaster`), because there are ~60 places in this app
* that paint a cover and only two of them want real pixels — with the polarity
* the other way round, every surface anyone forgets is silently wrong.
*
* Aspect ratio is preserved, so a non-square cover arrives non-square and the
* tile's own `object-fit` still decides the crop. Sources already within
* `edge` come back untouched rather than re-encoded. Pass `null` to opt out
* and get the master. */
export async function getArt(path, edge = ART_EDGE_DEFAULT) {
if (!path) return null;
if (edge == null) return getArtMaster(path);
const key = `${edge}|${path}`;
if (artThumbCache.has(key)) return touchCache(artThumbCache, key);
const pending = api.albumArt(path, edge).then(
(url) => {
if (artThumbCache.get(key) === pending) {
setResolvedCache(artThumbCache, key, url, ART_THUMB_CACHE_MAX, ART_THUMB_CACHE_MAX_CHARS);
}
return url;
},
() => {
if (artThumbCache.get(key) === pending) {
setResolvedCache(artThumbCache, key, null, ART_THUMB_CACHE_MAX, ART_THUMB_CACHE_MAX_CHARS);
}
return null;
},
);
artThumbCache.set(key, pending);
return pending;
}
// Catalog cover URLs → data URLs, proxied through Rust (no CORS on CDNs).
const catalogArtCache = new Map();
const CATALOG_ART_CACHE_MAX = 160;