Implemented basic track normalizing

This commit is contained in:
patben8 committed 2026-10-19 20:45:35 +02:00
1 parent 284a7514fe
commit 64b0396d66
33 files changed
+2584 -262

No files matched your search

+57 -5
View File
@@ -8,7 +8,7 @@ import { invalidateTrackLists } from './lib/trackQueries'
import { addTracksToPlaylist } from './lib/addTracks'
import { isForeign, useDragPayload, useDropTarget, type TracksOrFiles } from './lib/drag'
import { useNativeFileDrop } from './lib/fileDrop'
import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type NormalizeOptions, type NormalizeResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
import { confirmDiscardUnsaved } from './lib/unsaved'
import { askConfirm } from './lib/confirm'
import {
@@ -26,6 +26,7 @@ import { CollectionPicker } from './components/CollectionPicker'
import { ContextMenu, type MenuItem } from './components/ContextMenu'
import { EditTagsDialog } from './components/EditTagsDialog'
import { AnalyzeDialog } from './components/AnalyzeDialog'
import { NormalizeDialog } from './components/NormalizeDialog'
import { AutoCueDialog } from './components/AutoCueDialog'
import { ConfirmDialog, type ConfirmRequest } from './components/ConfirmDialog'
import { PathMappingDialog } from './components/PathMappingDialog'
@@ -108,7 +109,8 @@ export default function App() {
{ ids: string[]; origin: TrackOrigin; preset?: 'loudness' | 'gain' } | null
>(null)
const [cueBatch, setCueBatch] = useState<{ ids: string[]; withoutGrid: number } | null>(null)
const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' | 'stems' } | null>(null)
const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' | 'stems' | 'normalize' } | null>(null)
const [normalizing, setNormalizing] = useState<string[] | null>(null)
// Convert to Stems: the dialog's selection, a finished run's Details, and a
// running engine download (which outlives the dialog — decided).
const [stemDialog, setStemDialog] = useState<string[] | null>(null)
@@ -757,7 +759,7 @@ export default function App() {
return
}
if (job.state === 'failed') {
const what = kind === 'grid' ? 'Analysis' : 'Auto Hotcues'
const what = kind === 'grid' ? 'Analysis' : kind === 'normalize' ? 'Normalize' : 'Auto Hotcues'
onError(`${what} failed: ${job.error ?? 'unknown error'}`)
return
}
@@ -770,7 +772,17 @@ export default function App() {
let touched: string[]
let parts: string[]
let failures: CueBatchResult['failed']
if (kind === 'grid') {
if (kind === 'normalize') {
const r = job.result as unknown as NormalizeResult
touched = r.normalised
failures = r.failed
qc.invalidateQueries({ queryKey: ['state'] })
parts = [
`${cancelled ? 'Cancelled — normalized' : 'Normalized'} ${plural(r.normalised.length, 'track')}` +
(r.normalised.length ? ' — Save to keep the new levels, Discard to undo' : ''),
r.skipped.length ? `${r.skipped.length} left as they were` : '',
]
} else if (kind === 'grid') {
const r = job.result as unknown as AnalyzeResult
touched = r.analysed
failures = r.failed
@@ -924,6 +936,11 @@ export default function App() {
if (id && !batchJob) setBatchJob({ id, kind: 'stems' })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editState.data?.stem_job])
useEffect(() => {
const id = editState.data?.normalize_job
if (id && !batchJob) setBatchJob({ id, kind: 'normalize' })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editState.data?.normalize_job])
// Tell the user once what crash recovery did about an interrupted conversion.
const recovery = editState.data?.stem_recovery
const recoveryShown = useRef<unknown>(null)
@@ -1006,6 +1023,14 @@ export default function App() {
const canAnalyzeGrid = !!capabilities.data?.grid.editable
const canAnalyzeKey = !!capabilities.data?.tracks.key_writable
const canAutoGain = !!capabilities.data?.tracks.auto_gain
/** Why Normalize cannot change these tracks' files, if so. */
const normalizeRefusal = (ids: string[]): string | null =>
analyzeRefusal(analyzeOrigin(ids)) ??
(editState.data?.remote
? 'Normalize is not available on a remote library yet'
: capabilities.data?.tracks.normalizable
? null
: "This library's audio files cannot be normalized")
const analyzeOrigin = (ids: string[]): TrackOrigin =>
viewingDevice ? 'device' : viewingFolder && ids.some((id) => !folderFiles[id]) ? 'folder' : 'collection'
/** Why BPM / Grid / Key cannot be analysed for these tracks at all, if so. */
@@ -1340,6 +1365,13 @@ export default function App() {
{
label: 'Mastering',
submenu: [
{
label: 'Normalize…',
hint: batchJob ? 'busy' : undefined,
disabled: !!batchJob || !!normalizeRefusal(menu.ids),
title: normalizeRefusal(menu.ids) ?? undefined,
onClick: () => setNormalizing(menu.ids),
},
{
label: 'Auto gain…',
hint: batchJob ? 'busy' : undefined,
@@ -1455,6 +1487,19 @@ export default function App() {
onError={onError}
/>
)}
{normalizing && (
<NormalizeDialog
ids={normalizing}
onRun={async (opts: NormalizeOptions) => {
const job = await api.normalize(normalizing, opts)
setNormalizing(null)
setBatchCancelling(false)
setBatchJob({ id: job.id, kind: 'normalize' })
}}
onClose={() => setNormalizing(null)}
onError={onError}
/>
)}
{stemReport && <StemReportDialog result={stemReport} onClose={() => setStemReport(null)} />}
{positioning && (
<SetPositionDialog
@@ -1934,7 +1979,14 @@ export default function App() {
job={
batchJob
? {
label: batchJob.kind === 'grid' ? 'Analyzing' : batchJob.kind === 'stems' ? 'Converting to stems' : 'Placing hotcues',
label:
batchJob.kind === 'grid'
? 'Analyzing'
: batchJob.kind === 'stems'
? 'Converting to stems'
: batchJob.kind === 'normalize'
? 'Normalizing'
: 'Placing hotcues',
done: batchJobStatus.data?.done ?? 0,
total: batchJobStatus.data?.total ?? 0,
detail: batchJobStatus.data?.message,
+53
View File
@@ -316,6 +316,8 @@ export interface Capabilities {
colors: ColorSwatch[]
/** The library keeps a per-track auto gain (`Track.auto_gain_db`). */
auto_gain: boolean
/** Tracks' files can be normalized in place (`audio_changed`). */
normalizable: boolean
}
playlists: {
folders: boolean
@@ -369,6 +371,11 @@ export interface EditState {
stem_job: string | null
/** What this open's crash recovery did about an interrupted conversion. */
stem_recovery: { committed: number; restored: number; kept: number } | null
/** Normalized tracks awaiting Save or Discard; `lossless` = files whose
* change Save makes permanent. */
pending_gain: { tracks: number; lossless: number } | null
/** A running Normalize's job id, so a reloaded page can find it. */
normalize_job: string | null
/** A remote library's connection, null for a local one. */
remote: RemoteConnection | null
}
@@ -657,6 +664,47 @@ export interface AnalyzePreview {
with_gain: number
}
/** Normalize's choices (`gain/normalize.py`). */
export interface NormalizeOptions {
measure: 'lufs' | 'rms'
target: number
ceiling: number
}
/** One track in Normalize's preview — the backend's `plan_gain`. */
export interface NormalizeRow {
track_id: string
title: string
/** The measure now; null = not measured yet (the run measures it first). */
level: number | null
/** Why nothing can be done (missing file, already pending). */
skip: string | null
gain_db?: number
outcome?: 'apply' | 'capped' | 'at_target' | 'hot_peak_left' | 'unsupported' | 'unmeasured'
short_by?: number
lossless?: boolean
}
export interface NormalizePreview {
total: number
to_change: number
to_measure: number
tracks_to_process: number
/** Lossless files that would change — permanent once saved. */
lossless: number
counts: Record<string, number>
rows: NormalizeRow[]
}
/** What a Normalize run did. */
export interface NormalizeResult {
normalised: string[]
skipped: { track_id: string; title: string; reason: string }[]
failed: { track_id: string; title: string; reason: string }[]
counts: Record<string, number>
cancelled: boolean
}
/** What an Analyze run did. */
export interface AnalyzeResult {
analysed: string[]
@@ -1216,6 +1264,11 @@ export const api = {
stemEngineRemove: () => send<StemEngineStatus>('DELETE', '/api/stems/engine'),
analyzePreview: (trackIds: string[], opts: AnalyzeOptions) =>
send<AnalyzePreview>('POST', '/api/tracks/analyze/preview', { track_ids: trackIds, ...opts }),
normalizePreview: (trackIds: string[], opts: NormalizeOptions) =>
send<NormalizePreview>('POST', '/api/tracks/normalize/preview', { track_ids: trackIds, ...opts }),
/** Starts a Normalize job; its `result` is a `NormalizeResult`. */
normalize: (trackIds: string[], opts: NormalizeOptions) =>
send<JobStatus>('POST', '/api/tracks/normalize', { track_ids: trackIds, ...opts }),
/** Starts an analysis job; its `result` is an `AnalyzeResult`. */
analyze: (trackIds: string[], opts: AnalyzeOptions) =>
send<JobStatus>('POST', '/api/tracks/analyze', { track_ids: trackIds, ...opts }),
+66
View File
@@ -16,6 +16,11 @@ export const APP_SETTING_DEFAULTS = {
exportRootFolder: false,
/** Decimal places on the deck's ELAPSED / REMAIN readouts (0–3). */
timeReadoutDecimals: 1,
/** Normalize's defaults (each run can change them): the measure brought to
* the target, and the true-peak ceiling a raise stops at. */
levelMeasure: 'lufs' as 'lufs' | 'rms',
levelTarget: -9,
levelCeiling: -1,
}
type AppSettingKey = keyof typeof APP_SETTING_DEFAULTS
@@ -32,6 +37,9 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
const expandFolders = useAppSetting('expandPlaylistFolders')
const exportRootFolder = useAppSetting('exportRootFolder')
const timeDecimals = useAppSetting('timeReadoutDecimals')
const levelMeasure = useAppSetting('levelMeasure')
const levelTarget = useAppSetting('levelTarget')
const levelCeiling = useAppSetting('levelCeiling')
const [error, setError] = useState<string | null>(null)
useEffect(() => {
@@ -120,6 +128,36 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
</select>
</label>
</section>
<section className="space-y-2">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-faint">Normalize</h3>
<span className="block text-xs text-faint">
The defaults Mastering ▸ Normalize… starts from; each run can change them.
</span>
<label className="flex items-center justify-between gap-4">
<span className="text-sm text-text">Level by</span>
<select
className="shrink-0 rounded-lg well px-2 py-1 text-sm text-text outline-none"
value={levelMeasure}
onChange={(e) => void set({ levelMeasure: e.target.value as 'lufs' | 'rms' })}
>
<option value="lufs">LUFS (integrated loudness)</option>
<option value="rms">RMS (loudest sections)</option>
</select>
</label>
<label className="flex items-center justify-between gap-4">
<span className="text-sm text-text">Target</span>
<LevelInput value={levelTarget} unit={levelMeasure === 'lufs' ? 'LUFS' : 'dB'} min={-30} max={0}
onCommit={(v) => void set({ levelTarget: v })} />
</label>
<label className="flex items-center justify-between gap-4">
<span className="min-w-0">
<span className="block text-sm text-text">Peak ceiling</span>
<span className="block text-xs text-faint">A raise stops here, so nothing clips.</span>
</span>
<LevelInput value={levelCeiling} unit="dBTP" min={-12} max={0}
onCommit={(v) => void set({ levelCeiling: v })} />
</label>
</section>
{error && <div className="text-xs text-pink">{error}</div>}
</div>
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
@@ -132,3 +170,31 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
document.body,
)
}
/** A dB value typed in place, committed on blur / Enter, clamped to its range. */
export function LevelInput({ value, unit, min, max, onCommit }: {
value: number; unit: string; min: number; max: number; onCommit: (v: number) => void
}) {
const [text, setText] = useState(String(value))
useEffect(() => setText(String(value)), [value])
const commit = () => {
const v = Number(text.replace(',', '.'))
if (!Number.isFinite(v)) return setText(String(value))
const clamped = Math.min(max, Math.max(min, Math.round(v * 10) / 10))
setText(String(clamped))
if (clamped !== value) onCommit(clamped)
}
return (
<span className="flex shrink-0 items-center gap-1.5">
<input
className="w-16 rounded-lg well px-2 py-1 text-right font-mono text-sm tabular-nums text-text outline-none"
value={text}
inputMode="decimal"
onChange={(e) => setText(e.target.value)}
onBlur={commit}
onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()}
/>
<span className="w-10 text-xs text-faint">{unit}</span>
</span>
)
}
+194
View File
@@ -0,0 +1,194 @@
import { createPortal } from 'react-dom'
import { useEffect, useMemo, useState } from 'react'
import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { api, type NormalizeOptions, type NormalizePreview, type NormalizeRow } from '../api'
import { LevelInput, useAppSetting } from './AppSettings'
import { Icon } from '../lib/icons'
interface Props {
ids: string[]
onRun: (opts: NormalizeOptions) => Promise<void>
onClose: () => void
onError: (msg: string) => void
}
const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
const db = (v: number) => `${v > 0 ? '+' : ''}${v.toFixed(1)} dB`
/** What a row's outcome means, in the dialog's words. */
function rowNote(r: NormalizeRow): string {
if (r.skip) return r.skip
switch (r.outcome) {
case 'apply': return db(r.gain_db ?? 0)
case 'capped':
return r.gain_db ? `${db(r.gain_db)} — ${r.short_by?.toFixed(1)} dB short (peak ceiling)` : 'no headroom under the ceiling'
case 'at_target': return 'already at the target'
case 'hot_peak_left': return 'peak already over the ceiling — left alone'
case 'unsupported': return 'this format cannot be changed losslessly'
case 'unmeasured': return 'measured first, then levelled'
default: return ''
}
}
/**
* The track menu's Mastering ▸ Normalize… (decided 2026-10-19): change the
* selected files' audio LEVEL in place, toward a target in the chosen measure,
* a raise stopping at the true-peak ceiling. Every number comes from the
* backend's own plan (`/api/tracks/normalize/preview`). The defaults are the
* app settings; changes here apply to this run only. The originals are parked
* until Save — and Save makes a lossless file's change permanent, which the
* dialog says before it runs.
*/
export function NormalizeDialog({ ids, onRun, onClose, onError }: Props) {
const defaultMeasure = useAppSetting('levelMeasure')
const defaultTarget = useAppSetting('levelTarget')
const defaultCeiling = useAppSetting('levelCeiling')
const [opts, setOpts] = useState<NormalizeOptions | null>(null)
const [busy, setBusy] = useState(false)
useEffect(() => {
if (!opts) setOpts({ measure: defaultMeasure, target: defaultTarget, ceiling: defaultCeiling })
}, [opts, defaultMeasure, defaultTarget, defaultCeiling])
const preview = useQuery({
queryKey: ['normalize-preview', ids, opts],
queryFn: () => api.normalizePreview(ids, opts!),
enabled: !!opts,
placeholderData: keepPreviousData,
})
const p: NormalizePreview | undefined = preview.data
const count = p?.tracks_to_process ?? 0
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [busy, onClose])
const summary = useMemo(() => {
if (!p) return []
const rows = p.rows
const up = rows.filter((r) => (r.gain_db ?? 0) > 0).length
const down = rows.filter((r) => (r.gain_db ?? 0) < 0).length
const c = p.counts
const lines: string[] = []
if (up || down)
lines.push(`${plural(up + down, 'track')} change: ${[up && `${up} raised`, down && `${down} lowered`].filter(Boolean).join(', ')}`)
if (p.to_measure) lines.push(`${plural(p.to_measure, 'track')} measured first`)
if (c.capped) lines.push(`${plural(c.capped, 'track')} held short by the peak ceiling`)
if (c.at_target) lines.push(`${c.at_target} already at the target`)
if (c.hot_peak_left) lines.push(`${plural(c.hot_peak_left, 'hot peak')} left alone`)
if (c.unsupported) lines.push(`${plural(c.unsupported, 'file')} in a format that cannot be changed losslessly`)
if (c.skipped) lines.push(`${c.skipped} skipped`)
return lines
}, [p])
const run = async () => {
if (!opts || busy || count === 0) return
setBusy(true)
try {
await onRun(opts)
} catch (e) {
onError((e as Error).message)
setBusy(false)
}
}
const measureUnit = opts?.measure === 'rms' ? 'dB' : 'LUFS'
return createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
onClick={() => !busy && onClose()}
>
<div className="flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
<div className="border-b border-line px-5 py-4">
<div className="text-[15px] font-semibold tracking-tight">Normalize</div>
<div className="text-xs text-muted">
{plural(ids.length, 'track')} selected · changes the audio files' level
</div>
</div>
{opts && (
<div className="space-y-2 border-b border-line px-5 py-3 text-sm">
<label className="flex items-center justify-between gap-4">
<span className="text-text">Level by</span>
<select
className="rounded-lg well px-2 py-1 text-sm text-text outline-none"
value={opts.measure}
onChange={(e) => setOpts({ ...opts, measure: e.target.value as 'lufs' | 'rms' })}
>
<option value="lufs">LUFS (integrated loudness)</option>
<option value="rms">RMS (loudest sections)</option>
</select>
</label>
<label className="flex items-center justify-between gap-4">
<span className="text-text">Target</span>
<LevelInput value={opts.target} unit={measureUnit} min={-30} max={0}
onCommit={(v) => setOpts({ ...opts, target: v })} />
</label>
<label className="flex items-center justify-between gap-4">
<span className="text-text" title="A raise stops here, so nothing clips">Peak ceiling</span>
<LevelInput value={opts.ceiling} unit="dBTP" min={-12} max={0}
onCommit={(v) => setOpts({ ...opts, ceiling: v })} />
</label>
</div>
)}
<div className={`min-h-0 flex-1 overflow-y-auto px-5 py-3 text-sm ${preview.isFetching ? 'opacity-70' : ''}`}>
<div className="space-y-1 text-muted">
{summary.map((line) => (
<div key={line}>{line}</div>
))}
{p && count === 0 && <div className="text-faint">Nothing to change at this target.</div>}
</div>
{p && p.rows.length > 1 && (
<div className="mt-3 space-y-0.5">
{p.rows.map((r) => (
<div key={r.track_id} className="flex items-baseline justify-between gap-3 text-xs">
<span className="min-w-0 truncate text-text" title={r.title}>
{r.title}
</span>
<span className={`shrink-0 tabular-nums ${r.gain_db ? 'text-muted' : 'text-faint'}`}>
{r.level != null && `${r.level.toFixed(1)} ${measureUnit} · `}
{rowNote(r)}
</span>
</div>
))}
</div>
)}
{p && p.rows.length === 1 && <div className="mt-1 text-xs text-faint">{rowNote(p.rows[0])}</div>}
</div>
{p && p.lossless > 0 && (
<div className="mx-5 mb-2 flex gap-1.5 rounded-xl bg-gold/10 px-2.5 py-1.5 text-[11px] leading-snug text-gold">
<Icon name="warning" size={13} className="mt-px shrink-0" />
<span>
Saving makes the change to {plural(p.lossless, 'lossless file')} permanent: the original
{p.lossless === 1 ? ' is' : 's are'} deleted. MP3s keep an undo tag. Until then, Discard puts
everything back.
</span>
</div>
)}
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
<button
onClick={onClose}
disabled={busy}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
>
Cancel
</button>
<button
onClick={run}
disabled={busy || count === 0 || !p}
className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold disabled:opacity-40"
>
{`Normalize${count ? ` ${count}` : ''}`}
</button>
</div>
</div>
</div>,
document.body,
)
}
+15
View File
@@ -58,6 +58,7 @@ export function SaveBar({ onError, trailing, onDiscarded }: Props) {
const exportWarning = exportManagedWarning(caps.save)
const dirty = state?.dirty ?? false
const pending = state?.pending_stems
const gain = state?.pending_gain
const readOnly = readOnlyNotice(caps)
// A read-only library has no save to offer, and saying so plainly is the whole
@@ -100,6 +101,20 @@ export function SaveBar({ onError, trailing, onDiscarded }: Props) {
</span>
</div>
)}
{/* Normalize: the new levels are files on disk; Save deletes the parked
originals, which makes a lossless file's change permanent. */}
{gain && gain.tracks > 0 && (
<div className="mb-2 flex gap-1.5 rounded-xl bg-gold/10 px-2.5 py-1.5 text-[11px] leading-snug text-gold">
<Icon name="warning" size={13} className="mt-px shrink-0" />
<span>
Saving keeps the new level of {gain.tracks} file{gain.tracks === 1 ? '' : 's'}
{gain.lossless > 0
? ` — permanently for ${gain.lossless} lossless file${gain.lossless === 1 ? '' : 's'}, whose originals are deleted`
: ' (MP3s keep an undo tag)'}
. Discard to put the originals back.
</span>
</div>
)}
<div className="flex items-stretch gap-2">
<button
disabled={!dirty || save.isPending}