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

+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}