Implemented auto gain analysis

This commit is contained in:
patben8 committed 2026-10-19 18:20:13 +02:00
1 parent 6eecb2288a
commit 284a7514fe
30 files changed
+673 -71

No files matched your search

+33 -1
View File
@@ -104,7 +104,9 @@ export default function App() {
// run is placing cues on.
// The Analyze dialog's selection, and whose ids they are (a device's or a
// folder's loose files can only have their loudness measured).
const [analyzing, setAnalyzing] = useState<{ ids: string[]; origin: TrackOrigin } | null>(null)
const [analyzing, setAnalyzing] = useState<
{ 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)
// Convert to Stems: the dialog's selection, a finished run's Details, and a
@@ -779,6 +781,7 @@ export default function App() {
g.phase ? `${plural(g.phase, 'grid')} at its BPM` : '',
r.key.set ? plural(r.key.set, 'key') : '',
r.loudness?.measured ? `loudness of ${r.loudness.measured}` : '',
r.gain?.set ? `auto gain of ${r.gain.set}` : '',
].filter(Boolean)
const skipped = [
g.existing ? `${g.existing} with a grid` : '',
@@ -786,6 +789,7 @@ export default function App() {
g.flexible ? `${g.flexible} multi-tempo` : '',
r.key.existing ? `${r.key.existing} with a key` : '',
r.loudness?.existing ? `${r.loudness.existing} already measured` : '',
r.gain?.existing ? `${r.gain.existing} with an auto gain` : '',
].filter(Boolean)
parts = [
`${cancelled ? 'Cancelled — analyzed' : 'Analyzed'} ${plural(r.analysed.length, 'track')}` +
@@ -793,6 +797,7 @@ export default function App() {
skipped.length ? `skipped ${skipped.join(', ')}` : '',
r.key.none ? `no key found in ${r.key.none}` : '',
r.loudness?.none ? `nothing to measure in ${r.loudness.none} (silent or under 3 s)` : '',
r.gain?.none ? `no auto gain for ${r.gain.none} (silent or under 3 s)` : '',
]
} else {
const r = job.result as unknown as CueBatchResult
@@ -1000,6 +1005,7 @@ export default function App() {
// Grid / Key with a reason where they cannot be stored.
const canAnalyzeGrid = !!capabilities.data?.grid.editable
const canAnalyzeKey = !!capabilities.data?.tracks.key_writable
const canAutoGain = !!capabilities.data?.tracks.auto_gain
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. */
@@ -1329,6 +1335,30 @@ export default function App() {
disabled: !!batchJob,
onClick: () => setAnalyzing({ ids: menu.ids, origin: analyzeOrigin(menu.ids) }),
},
// Level work in one place: the same Analyze run, opened for one
// option (its remembered ticks untouched).
{
label: 'Mastering',
submenu: [
{
label: 'Auto gain…',
hint: batchJob ? 'busy' : undefined,
disabled: !!batchJob || analyzeRefusal(analyzeOrigin(menu.ids)) !== null || !canAutoGain,
title:
analyzeRefusal(analyzeOrigin(menu.ids)) ??
(canAutoGain ? undefined : 'This library has no auto gain'),
onClick: () =>
setAnalyzing({ ids: menu.ids, origin: analyzeOrigin(menu.ids), preset: 'gain' }),
},
{
label: 'Measure loudness',
hint: batchJob ? 'busy' : undefined,
disabled: !!batchJob,
onClick: () =>
setAnalyzing({ ids: menu.ids, origin: analyzeOrigin(menu.ids), preset: 'loudness' }),
},
],
},
// The deck's ✨ Auto covers a single loaded track, with its
// existing cues shown; this is the same template over the selection.
...(canAutoCue
@@ -1460,6 +1490,8 @@ export default function App() {
origin={analyzing.origin}
gridWhy={analyzeRefusal(analyzing.origin) ?? (canAnalyzeGrid ? null : "This library's beatgrids cannot be edited")}
keyWhy={analyzeRefusal(analyzing.origin) ?? (canAnalyzeKey ? null : 'This library cannot store a key')}
gainWhy={analyzeRefusal(analyzing.origin) ?? (canAutoGain ? null : 'This library has no auto gain')}
preset={analyzing.preset}
onRun={(opts) => runAnalysis(analyzing.ids, opts)}
onClose={() => setAnalyzing(null)}
onError={onError}
+13
View File
@@ -43,6 +43,9 @@ export interface Track {
* library's own display colour for it; both null when uncoloured. */
color: TrackColor | null
color_hex: string | null
/** The DJ app's own auto gain in dB (Traktor's deck gain, rekordbox's Auto
* Gain); null = the track has none. */
auto_gain_db: number | null
/** The Mastering columns' values — NOT part of the backend's `Track`: joined
* in client-side from `/api/loudness` (Konduktor's own store, keyed by the
* FILE), and only while a Mastering column is shown. Absent = unmeasured. */
@@ -311,6 +314,8 @@ export interface Capabilities {
reference: boolean
/** The track colours this library can store; empty = no track colour. */
colors: ColorSwatch[]
/** The library keeps a per-track auto gain (`Track.auto_gain_db`). */
auto_gain: boolean
}
playlists: {
folders: boolean
@@ -617,9 +622,12 @@ export interface AnalyzeOptions {
grid: boolean
key: boolean
loudness: boolean
/** Write the DJ app's auto gain from the loudness (measured first if needed). */
gain: boolean
replace_grid: boolean
replace_key: boolean
replace_loudness: boolean
replace_gain: boolean
origin: TrackOrigin
}
@@ -643,6 +651,10 @@ export interface AnalyzePreview {
loudness_existing: number
/** Measured and not stale — the loudness Replace tick's count. */
with_loudness: number
gain_set: number
gain_existing: number
/** Tracks with an auto gain — the gain Replace tick's count. */
with_gain: number
}
/** What an Analyze run did. */
@@ -652,6 +664,7 @@ export interface AnalyzeResult {
grid: { full: number; bpm: number; phase: number; locked: number; existing: number; flexible: number }
key: { set: number; existing: number; none: number }
loudness: { measured: number; existing: number; none: number }
gain: { set: number; existing: number; none: number }
}
/** What a batch Auto Hotcues run did. `tracks` got the template (whatever it
+57 -23
View File
@@ -13,22 +13,28 @@ interface Props {
gridWhy: string | null
/** Why a key cannot be stored here; null = it can. */
keyWhy: string | null
/** Why the DJ app's auto gain cannot be written here; null = it can. */
gainWhy: string | null
/** Opened for ONE option (the context menu's Mastering ▸ Auto gain… /
* Measure loudness): only it is ticked, and the remembered ticks are left
* as they were. */
preset?: keyof What
onRun: (opts: AnalyzeOptions) => Promise<void>
onClose: () => void
onError: (msg: string) => void
}
type What = Pick<AnalyzeOptions, 'bpm' | 'grid' | 'key' | 'loudness'>
type What = Pick<AnalyzeOptions, 'bpm' | 'grid' | 'key' | 'loudness' | 'gain'>
const PREF_KEY = 'analyzeWhat'
// Loudness off unless asked for once: it adds a decode per track.
const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true, loudness: false }
// Loudness and gain off unless asked for once: they add a decode per track.
const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true, loudness: false, gain: false }
/** The remembered ticks; anything malformed falls back to the default. */
function loadWhat(prefs: Record<string, unknown> | undefined): What {
const saved = prefs?.[PREF_KEY] as Partial<What> | undefined
if (!saved || typeof saved !== 'object') return DEFAULT_WHAT
const pick = (k: keyof What) => (typeof saved[k] === 'boolean' ? (saved[k] as boolean) : DEFAULT_WHAT[k])
return { bpm: pick('bpm'), grid: pick('grid'), key: pick('key'), loudness: pick('loudness') }
return { bpm: pick('bpm'), grid: pick('grid'), key: pick('key'), loudness: pick('loudness'), gain: pick('gain') }
}
const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
@@ -40,48 +46,58 @@ const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? o
* halves of a beatgrid — BPM alone keeps the downbeat, Grid alone keeps the
* tempo — and the grid Replace tick only guards a FULL re-analysis (both
* ticked). Loudness goes to Konduktor's own store, so it is never disabled
* (decided 2026-10-19). The ticks are remembered; the Replace ticks never
* are — overwriting is a decision about THESE tracks.
* (decided 2026-10-19). Gain writes the DJ app's own auto gain from the
* loudness, only where a track has none unless Replace. The ticks are
* remembered; the Replace ticks never are — overwriting is a decision about
* THESE tracks.
*/
export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, onRun, onClose, onError }: Props) {
export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, gainWhy, preset, onRun, onClose, onError }: Props) {
const qc = useQueryClient()
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
const [what, setWhat] = useState<What | null>(null)
const [replaceGrid, setReplaceGrid] = useState(false)
const [replaceKey, setReplaceKey] = useState(false)
const [replaceLoudness, setReplaceLoudness] = useState(false)
const [replaceGain, setReplaceGain] = useState(false)
const [busy, setBusy] = useState(false)
const gridEditable = gridWhy === null
const keyWritable = keyWhy === null
const gainWritable = gainWhy === null
// Hydrate once from prefs, masked by what can be stored here. Where loudness
// is ALL that can be done (a device, loose files), it is ticked.
useEffect(() => {
if (what || prefs.isPending) return
if (preset) {
setWhat({ bpm: false, grid: false, key: false, loudness: false, gain: false, [preset]: true })
return
}
const w = loadWhat(prefs.data as Record<string, unknown> | undefined)
setWhat({
bpm: w.bpm && gridEditable,
grid: w.grid && gridEditable,
key: w.key && keyWritable,
loudness: w.loudness || (!gridEditable && !keyWritable),
gain: w.gain && gainWritable,
loudness: w.loudness || (!gridEditable && !keyWritable && !gainWritable),
})
}, [what, prefs.isPending, prefs.data, gridEditable, keyWritable])
}, [what, preset, prefs.isPending, prefs.data, gridEditable, keyWritable, gainWritable])
const opts: AnalyzeOptions | null = what && {
...what,
replace_grid: what.bpm && what.grid && replaceGrid,
replace_key: what.key && replaceKey,
replace_loudness: what.loudness && replaceLoudness,
replace_gain: what.gain && replaceGain,
origin,
}
const preview = useQuery({
queryKey: ['analyze-preview', ids, opts],
queryFn: () => api.analyzePreview(ids, opts!),
enabled: !!opts && (opts.bpm || opts.grid || opts.key || opts.loudness),
enabled: !!opts && (opts.bpm || opts.grid || opts.key || opts.loudness || opts.gain),
placeholderData: keepPreviousData,
})
const p: AnalyzePreview | undefined = preview.data
const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness)
const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness || what.gain)
const count = nothingTicked ? 0 : (p?.tracks_to_analyze ?? 0)
useEffect(() => {
@@ -94,19 +110,22 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, onRun, onClose, on
if (!opts || busy || count === 0) return
setBusy(true)
// A tick that was disabled here keeps what it was: analysing a device's
// loudness must not forget that the collection's keys are wanted.
// loudness must not forget that the collection's keys are wanted. A
// one-option run (a preset) remembers nothing.
const saved = loadWhat(prefs.data as Record<string, unknown> | undefined)
api
.patchPrefs({
[PREF_KEY]: {
bpm: gridEditable ? opts.bpm : saved.bpm,
grid: gridEditable ? opts.grid : saved.grid,
key: keyWritable ? opts.key : saved.key,
loudness: opts.loudness,
},
})
.then((x) => qc.setQueryData(['prefs'], x))
.catch(() => {})
if (!preset)
api
.patchPrefs({
[PREF_KEY]: {
bpm: gridEditable ? opts.bpm : saved.bpm,
grid: gridEditable ? opts.grid : saved.grid,
key: keyWritable ? opts.key : saved.key,
gain: gainWritable ? opts.gain : saved.gain,
loudness: opts.loudness,
},
})
.then((x) => qc.setQueryData(['prefs'], x))
.catch(() => {})
try {
await onRun(opts)
} catch (e) {
@@ -184,6 +203,8 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, onRun, onClose, on
{toggle('grid', 'Grid', 'Find where the downbeats fall', gridEditable, gridWhy ?? '')}
{toggle('key', 'Key', 'Detect the musical key', keyWritable, keyWhy ?? '')}
{toggle('loudness', 'Loudness', 'Measure LUFS, RMS, true peak and dynamics', true, '')}
{toggle('gain', 'Auto gain', "Set the DJ app's own gain from the loudness (measured first if needed)",
gainWritable, gainWhy ?? '')}
</div>
<div className={`space-y-1.5 px-5 py-3 text-sm text-muted ${preview.isFetching ? 'opacity-70' : ''}`}>
@@ -211,6 +232,19 @@ export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, onRun, onClose, on
</label>
</div>
)}
{p && what?.gain && p.with_gain > 0 && (
<div className="flex items-center justify-between gap-3">
<span>
<span className="tabular-nums text-text">{p.with_gain}</span>{' '}
{p.with_gain === 1 ? 'already has an auto gain' : 'already have an auto gain'}
</span>
<label className="flex shrink-0 items-center gap-1.5 text-xs"
title="Replacing puts Konduktor's measure in place of the DJ app's own">
<input type="checkbox" checked={replaceGain} onChange={(e) => setReplaceGain(e.target.checked)} />
Replace {p.with_gain === 1 ? 'it' : 'them'}
</label>
</div>
)}
{nothingTicked && <div className="text-faint">Tick what to analyze.</div>}
</div>
+23 -2
View File
@@ -367,6 +367,24 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
loudnessColumn('true_peak', 'True Peak', 'dBTP', true),
loudnessColumn('lra', 'LRA', 'LU'),
loudnessColumn('plr', 'PLR', 'dB'),
// The DJ app's own auto gain (Traktor's deck gain, rekordbox's Auto Gain),
// from the backend's Track — not Konduktor's loudness store — so showing it
// fetches nothing. None sorts last, like an unmeasured loudness.
col.accessor((t) => t.auto_gain_db ?? undefined, {
id: 'auto_gain',
header: 'Auto Gain',
size: 104,
sortUndefined: 'last',
cell: (c) => {
const v = c.getValue() as number | undefined
if (v == null) return <span className="text-faint" title="No auto gain: Mastering ▸ Auto gain… sets one">—</span>
return (
<span className="whitespace-nowrap font-mono text-xs tabular-nums text-muted">
{formatLoudness(v, 'dB', true)}
</span>
)
},
}),
]
function loudnessColumn(field: 'lufs' | 'rms' | 'true_peak' | 'lra' | 'plr', header: string, unit: string,
@@ -392,14 +410,17 @@ function loudnessColumn(field: 'lufs' | 'rms' | 'true_peak' | 'lra' | 'plr', hea
})
}
/** The Mastering columns, in order: the column chooser's "Mastering ▸". */
/** The loudness columns: shown, they fetch `/api/loudness` (see App). */
export const MASTERING_COLUMNS: readonly string[] = ['lufs', 'rms', 'true_peak', 'lra', 'plr']
/** The column chooser's "Mastering ▸", in order: loudness, then auto gain. */
const MASTERING_MENU: readonly string[] = [...MASTERING_COLUMNS, 'auto_gain']
const MASTERING_LABELS: Record<string, string> = {
lufs: 'LUFS (integrated loudness)',
rms: 'RMS (loudest sections)',
true_peak: 'True Peak',
lra: 'LRA (loudness range)',
plr: 'PLR (peak to loudness)',
auto_gain: "Auto Gain (the DJ app's)",
}
// Traktor dates arrive as "YYYY/M/D" strings; show them compactly (or raw).
@@ -414,7 +435,7 @@ function formatDate(v: string | null): string {
* `group` puts a column in a submenu (the Mastering columns). */
export const COLUMN_MENU: { id: string; label: string; group?: 'mastering' }[] = TRACK_COLUMNS.map((c) => {
const id = c.id as string
const mastering = MASTERING_COLUMNS.includes(id)
const mastering = MASTERING_MENU.includes(id)
return {
id,
label: MASTERING_LABELS[id] ?? (typeof c.header === 'string' ? c.header : id),