Implemented track loudness analysis

This commit is contained in:
patben8 committed 2026-10-19 14:07:54 +02:00
1 parent 5c9387f136
commit d70a7c5de2
28 files changed
+1732 -144

No files matched your search

+72 -26
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy'
@@ -13,6 +13,7 @@ import { confirmDiscardUnsaved } from './lib/unsaved'
import { askConfirm } from './lib/confirm'
import {
COLUMN_MENU,
MASTERING_COLUMNS,
DEFAULT_COLUMN_ORDER,
DEFAULT_COLUMN_VISIBILITY,
} from './lib/trackColumns'
@@ -101,7 +102,9 @@ export default function App() {
// job, polled into the status bar. ONE at a time across both kinds — the
// backend refuses a second, since a grid run would move the beats a hotcue
// run is placing cues on.
const [analyzing, setAnalyzing] = useState<string[] | null>(null) // the Analyze dialog's selection
// 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 [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
@@ -143,6 +146,12 @@ export default function App() {
setColumnOrder(DEFAULT_COLUMN_ORDER)
setColumnSizing({})
}, [])
/** One checkbox row of the header's column chooser. */
const columnToggle = (id: string, label: string) => ({
label,
checked: columnVisibility[id] !== false,
onToggle: () => setColumnVisibility((v) => ({ ...v, [id]: v[id] === false })),
})
// Hydrate the saved layout once, tolerating partial / stale (new columns
// added since) data by merging against the current defaults.
@@ -563,7 +572,7 @@ export default function App() {
: source.name
const isAll = source.kind === 'all'
const tracks: Track[] = viewingFolder
const listed: Track[] = viewingFolder
? (folderView.data?.tracks ?? [])
: viewingDevice
? source.kind === 'device'
@@ -578,6 +587,30 @@ export default function App() {
: isAll
? (allTracks.data?.items ?? [])
: (playlistTracks.data ?? [])
// The Mastering columns' values: Konduktor's own store, keyed by the FILE
// (`/api/loudness`), joined into the rows — and only fetched while one of
// those columns is shown, since it stats every listed file. Keyed by a hash
// of the ids, so a list whose membership changes asks again; an analysis
// invalidates `['loudness']` itself.
const viewOrigin: TrackOrigin = viewingFolder ? 'folder' : viewingDevice ? 'device' : 'collection'
const masteringShown = MASTERING_COLUMNS.some((id) => columnVisibility[id] === true)
const listedIds = useMemo(() => listed.map((t) => t.id), [listed])
const listedKey = useMemo(() => {
let h = 5381
for (const id of listedIds) for (let i = 0; i < id.length; i++) h = ((h << 5) + h + id.charCodeAt(i)) | 0
return `${listedIds.length}:${h}`
}, [listedIds])
const loudness = useQuery({
queryKey: ['loudness', viewOrigin, listedKey],
queryFn: () => api.loudness(viewOrigin, listedIds),
enabled: masteringShown && listedIds.length > 0,
placeholderData: keepPreviousData,
})
const tracks: Track[] = useMemo(() => {
const values = masteringShown ? loudness.data?.values : undefined
if (!values) return listed
return listed.map((t) => (values[t.id] ? { ...t, loudness: values[t.id] } : t))
}, [listed, loudness.data, masteringShown])
// The deck holds a SNAPSHOT of its track, taken when it was loaded. When the
// view it came from refetches (Analyze wrote its key, Edit Tags its title),
// follow the fresh copy so the deck's KEY readout and header are current.
@@ -729,6 +762,7 @@ export default function App() {
if (!job.result) return
invalidateTrackLists(qc)
qc.invalidateQueries({ queryKey: ['facets'] })
qc.invalidateQueries({ queryKey: ['loudness'] })
const cancelled = job.state === 'cancelled'
const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`
let touched: string[]
@@ -744,18 +778,21 @@ export default function App() {
g.bpm ? `${plural(g.bpm, 'BPM')} (downbeat kept)` : '',
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}` : '',
].filter(Boolean)
const skipped = [
g.existing ? `${g.existing} with a grid` : '',
g.locked ? `${g.locked} locked` : '',
g.flexible ? `${g.flexible} multi-tempo` : '',
r.key.existing ? `${r.key.existing} with a key` : '',
r.loudness?.existing ? `${r.loudness.existing} already measured` : '',
].filter(Boolean)
parts = [
`${cancelled ? 'Cancelled — analyzed' : 'Analyzed'} ${plural(r.analysed.length, 'track')}` +
(wrote.length ? `: ${wrote.join(', ')}` : ''),
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)` : '',
]
} else {
const r = job.result as unknown as CueBatchResult
@@ -958,11 +995,22 @@ export default function App() {
setBatchCancelling(false)
setBatchJob({ id: job.id, kind: 'grid' })
}
// Offered where ANY of BPM / Grid / Key can be stored; the dialog disables
// the rest with a reason.
// Offered for ANY selection: loudness goes to Konduktor's own store, so it
// can always be measured (decided 2026-10-19). The dialog disables BPM /
// Grid / Key with a reason where they cannot be stored.
const canAnalyzeGrid = !!capabilities.data?.grid.editable
const canAnalyzeKey = !!capabilities.data?.tracks.key_writable
const canAnalyze = canEdit && !viewingDevice && (canAnalyzeGrid || canAnalyzeKey)
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. */
const analyzeRefusal = (origin: TrackOrigin): string | null =>
origin === 'device'
? 'A device is read-only: only its loudness can be measured'
: origin === 'folder'
? 'Add these files to your collection first'
: !canEdit
? ((capabilities.data && readOnlyNotice(capabilities.data)) ?? 'This library is read-only')
: null
const startCueBatch = (ids: string[]) => {
const byId = new Map(tracks.map((t) => [t.id, t]))
@@ -1273,16 +1321,14 @@ export default function App() {
},
]
: []),
...(canAnalyze
? [
{
label: 'Analyze…',
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
disabled: !!batchJob,
onClick: gated(() => setAnalyzing(menu.ids)),
},
]
: []),
// No "add it first" detour for loose files: their loudness can be
// measured where they are; the dialog explains the rest.
{
label: 'Analyze…',
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
disabled: !!batchJob,
onClick: () => setAnalyzing({ ids: menu.ids, origin: analyzeOrigin(menu.ids) }),
},
// The deck's ✨ Auto covers a single loaded track, with its
// existing cues shown; this is the same template over the selection.
...(canAutoCue
@@ -1356,12 +1402,11 @@ export default function App() {
items={[
{ heading: 'Columns' },
// Default-visible unless explicitly hidden, as in the Columns menu.
...COLUMN_MENU.map((c) => ({
label: c.label,
checked: columnVisibility[c.id] !== false,
onToggle: () =>
setColumnVisibility((v) => ({ ...v, [c.id]: v[c.id] === false })),
})),
...COLUMN_MENU.filter((c) => !c.group).map((c) => columnToggle(c.id, c.label)),
{
label: 'Mastering',
submenu: COLUMN_MENU.filter((c) => c.group === 'mastering').map((c) => columnToggle(c.id, c.label)),
},
{ separator: true as const },
{ label: 'Reset to defaults', onClick: resetColumns },
]}
@@ -1411,10 +1456,11 @@ export default function App() {
)}
{analyzing && (
<AnalyzeDialog
ids={analyzing}
gridEditable={canAnalyzeGrid}
keyWritable={canAnalyzeKey}
onRun={(opts) => runAnalysis(analyzing, opts)}
ids={analyzing.ids}
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')}
onRun={(opts) => runAnalysis(analyzing.ids, opts)}
onClose={() => setAnalyzing(null)}
onError={onError}
/>
+35 -2
View File
@@ -43,6 +43,23 @@ export interface Track {
* library's own display colour for it; both null when uncoloured. */
color: TrackColor | null
color_hex: string | 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. */
loudness?: Loudness
}
/** One file's loudness (`core/loudness.py`): integrated LUFS, RMS of the
* loudest 3 s blocks (dB, AES17), true peak (dBTP), loudness range (LU) and
* PLR (true peak − LUFS, dB). `stale`: the file changed since it was measured
* — shown dimmed, still sorted on. */
export interface Loudness {
lufs: number
rms: number
true_peak: number
lra: number
plr: number
stale: boolean
}
/** One occupied hotcue slot, as the library table previews it. */
@@ -590,16 +607,20 @@ export interface JobStatus {
finished_at: number | null
}
/** What a batch grid analysis did, per track outcome. */
/** What the Analyze dialog asks for. BPM and Grid are independent halves of
* a beatgrid: BPM alone keeps the downbeat, Grid alone keeps the tempo.
* `replace_grid` only guards a FULL re-analysis (both ticked). */
* `replace_grid` only guards a FULL re-analysis (both ticked). Loudness goes
* to Konduktor's own store, so it works for any `origin`; BPM / Grid / Key
* only for the loaded library's tracks. */
export interface AnalyzeOptions {
bpm: boolean
grid: boolean
key: boolean
loudness: boolean
replace_grid: boolean
replace_key: boolean
replace_loudness: boolean
origin: TrackOrigin
}
/** What an Analyze run WOULD do — the backend's `plan_grid`, per track. */
@@ -618,6 +639,10 @@ export interface AnalyzePreview {
key_existing: number
/** Tracks with a key — the key Replace tick's count. */
with_key: number
loudness_measure: number
loudness_existing: number
/** Measured and not stale — the loudness Replace tick's count. */
with_loudness: number
}
/** What an Analyze run did. */
@@ -626,6 +651,7 @@ export interface AnalyzeResult {
failed: { title: string; reason: string }[]
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 }
}
/** What a batch Auto Hotcues run did. `tracks` got the template (whatever it
@@ -1140,6 +1166,13 @@ export const api = {
* lands on the track, so refetch the track lists. */
autoGrid: (trackId: string) =>
send<TrackCues>('POST', '/api/tracks/grid/auto', { track_id: trackId }),
/** The Mastering columns' values for these tracks — measured ones only. */
loudness: (origin: TrackOrigin, trackIds: string[]) =>
send<{ values: Record<string, Loudness> }>('POST', '/api/loudness', { origin, track_ids: trackIds }),
/** Measure one track's loudness now (the deck's Analyze where it cannot
* write a grid: a read-only library, a device, a loose file). */
measureLoudness: (origin: TrackOrigin, trackId: string) =>
send<Loudness>('POST', '/api/tracks/loudness', { origin, track_id: trackId }),
/** Auto Hotcues over many tracks, one template for all, as a job. A track
* without a grid gets one analysed first. The finished job's `result` is a
* `CueBatchResult`. */
+61 -23
View File
@@ -1,71 +1,87 @@
import { createPortal } from 'react-dom'
import { useEffect, useState, type ReactNode } from 'react'
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type AnalyzeOptions, type AnalyzePreview } from '../api'
import { api, type AnalyzeOptions, type AnalyzePreview, type TrackOrigin } from '../api'
interface Props {
/** The selected tracks. */
ids: string[]
/** The library can write beatgrids (BPM and Grid). */
gridEditable: boolean
/** The library can store a key. */
keyWritable: boolean
/** Whose ids they are: a device's or a folder's loose files can only have
* their loudness measured. */
origin: TrackOrigin
/** Why BPM and Grid cannot be analysed here; null = they can. */
gridWhy: string | null
/** Why a key cannot be stored here; null = it can. */
keyWhy: string | null
onRun: (opts: AnalyzeOptions) => Promise<void>
onClose: () => void
onError: (msg: string) => void
}
type What = Pick<AnalyzeOptions, 'bpm' | 'grid' | 'key'>
type What = Pick<AnalyzeOptions, 'bpm' | 'grid' | 'key' | 'loudness'>
const PREF_KEY = 'analyzeWhat'
const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true }
// Loudness off unless asked for once: it adds a decode per track.
const DEFAULT_WHAT: What = { bpm: true, grid: true, key: true, loudness: 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') }
return { bpm: pick('bpm'), grid: pick('grid'), key: pick('key'), loudness: pick('loudness') }
}
const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
/**
* The context menu's "Analyze…" (decided 2026-10-04): which of BPM / Grid /
* Key to analyse, with the "already has one — replace?" questions folded in so
* there is never a second popup. BPM and Grid are independent 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). The
* ticks are remembered; the Replace ticks never are — overwriting is a
* decision about THESE tracks.
* Key / Loudness to analyse, with the "already has one — replace?" questions
* folded in so there is never a second popup. BPM and Grid are independent
* 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.
*/
export function AnalyzeDialog({ ids, gridEditable, keyWritable, onRun, onClose, onError }: Props) {
export function AnalyzeDialog({ ids, origin, gridWhy, keyWhy, 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 [busy, setBusy] = useState(false)
const gridEditable = gridWhy === null
const keyWritable = keyWhy === null
// Hydrate once from prefs, masked by what this library can store.
// 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
const w = loadWhat(prefs.data as Record<string, unknown> | undefined)
setWhat({ bpm: w.bpm && gridEditable, grid: w.grid && gridEditable, key: w.key && keyWritable })
setWhat({
bpm: w.bpm && gridEditable,
grid: w.grid && gridEditable,
key: w.key && keyWritable,
loudness: w.loudness || (!gridEditable && !keyWritable),
})
}, [what, prefs.isPending, prefs.data, gridEditable, keyWritable])
const opts: AnalyzeOptions | null = what && {
...what,
replace_grid: what.bpm && what.grid && replaceGrid,
replace_key: what.key && replaceKey,
replace_loudness: what.loudness && replaceLoudness,
origin,
}
const preview = useQuery({
queryKey: ['analyze-preview', ids, opts],
queryFn: () => api.analyzePreview(ids, opts!),
enabled: !!opts && (opts.bpm || opts.grid || opts.key),
enabled: !!opts && (opts.bpm || opts.grid || opts.key || opts.loudness),
placeholderData: keepPreviousData,
})
const p: AnalyzePreview | undefined = preview.data
const nothingTicked = !!what && !(what.bpm || what.grid || what.key)
const nothingTicked = !!what && !(what.bpm || what.grid || what.key || what.loudness)
const count = nothingTicked ? 0 : (p?.tracks_to_analyze ?? 0)
useEffect(() => {
@@ -77,8 +93,18 @@ export function AnalyzeDialog({ ids, gridEditable, keyWritable, onRun, onClose,
const run = async () => {
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.
const saved = loadWhat(prefs.data as Record<string, unknown> | undefined)
api
.patchPrefs({ [PREF_KEY]: { bpm: opts.bpm, grid: opts.grid, key: opts.key } })
.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(() => {})
try {
@@ -154,9 +180,10 @@ export function AnalyzeDialog({ ids, gridEditable, keyWritable, onRun, onClose,
</div>
<div className="space-y-0.5 px-3 pt-3">
{toggle('bpm', 'BPM', 'Detect the tempo', gridEditable, "This library's beatgrids cannot be edited")}
{toggle('grid', 'Grid', 'Find where the downbeats fall', gridEditable, "This library's beatgrids cannot be edited")}
{toggle('key', 'Key', 'Detect the musical key', keyWritable, "This library cannot store a key")}
{toggle('bpm', 'BPM', 'Detect the tempo', gridEditable, gridWhy ?? '')}
{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, '')}
</div>
<div className={`space-y-1.5 px-5 py-3 text-sm text-muted ${preview.isFetching ? 'opacity-70' : ''}`}>
@@ -173,6 +200,17 @@ export function AnalyzeDialog({ ids, gridEditable, keyWritable, onRun, onClose,
</label>
</div>
)}
{p && what?.loudness && p.with_loudness > 0 && (
<div className="flex items-center justify-between gap-3">
<span>
<span className="tabular-nums text-text">{p.with_loudness}</span> already measured
</span>
<label className="flex shrink-0 items-center gap-1.5 text-xs">
<input type="checkbox" checked={replaceLoudness} onChange={(e) => setReplaceLoudness(e.target.checked)} />
Measure again
</label>
</div>
)}
{nothingTicked && <div className="text-faint">Tick what to analyze.</div>}
</div>
+16 -5
View File
@@ -18,7 +18,7 @@ import {
import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid'
import { slotLabeller, useCaps } from '../lib/capabilities'
import { CUE_TYPE_LABELS, cueTypeColor } from '../lib/cues'
import { keyColor } from '../lib/format'
import { formatLoudness, keyColor } from '../lib/format'
import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy'
import { analyzeStems, analyzeWaveform, type WaveColumn } from '../lib/waveform'
import type { RawWave } from '../lib/rawWave'
@@ -1220,11 +1220,20 @@ export function PrepStrip({
// deck the fresh copy.
const runAnalyzeGrid = async () => {
if (!track || gridBusy) return
if (refuseGridEdit()) return
setGridBusy(true)
try {
applyCueEdit(await api.autoGrid(track.id))
onNotify?.('success', caps.tracks.key_writable ? 'Analyzed — set BPM, grid and key' : 'Analyzed — set BPM and grid')
if (canEditGrid) {
applyCueEdit(await api.autoGrid(track.id))
onNotify?.('success', caps.tracks.key_writable
? 'Analyzed — set BPM, grid and key, measured loudness'
: 'Analyzed — set BPM and grid, measured loudness')
} else {
// Nothing here can take a grid (a read-only library, a device, a loose
// file) — but loudness goes to Konduktor's own store, so measure that.
const l = await api.measureLoudness(origin, track.id)
onNotify?.('success', `Measured loudness — ${formatLoudness(l.lufs, 'LUFS')}, ${formatLoudness(l.true_peak, 'dBTP', true)}`)
}
qc.invalidateQueries({ queryKey: ['loudness'] })
} catch (e) {
onError?.((e as Error).message)
} finally {
@@ -1529,7 +1538,9 @@ export function PrepStrip({
<button
onClick={runAnalyzeGrid}
disabled={!track || gridBusy}
title="Detect BPM and first beat, then set the grid + hotcue 1 (fix the octave with ÷2 / ×2)"
title={canEditGrid
? 'Detect BPM and first beat, then set the grid + hotcue 1 (fix the octave with ÷2 / ×2); measure loudness'
: 'Measure loudness (this track’s grid cannot be edited here)'}
className="btn-glass flex h-9 shrink-0 items-center gap-2 rounded-full px-3.5 text-[13px] font-medium disabled:opacity-40"
>
<Icon name="wave" size={16} />
+21
View File
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest'
import { formatLoudness } from './format'
describe('formatLoudness', () => {
it('shows one decimal and the unit', () => {
expect(formatLoudness(-8.24, 'LUFS')).toBe('-8.2 LUFS')
expect(formatLoudness(5.06, 'LU')).toBe('5.1 LU')
})
it('signs a positive value only when asked (true peak)', () => {
expect(formatLoudness(0.31, 'dBTP', true)).toBe('+0.3 dBTP')
expect(formatLoudness(-1.0, 'dBTP', true)).toBe('-1.0 dBTP')
expect(formatLoudness(8.5, 'dB')).toBe('8.5 dB')
})
it('never shows a negative or signed zero', () => {
expect(formatLoudness(-0.04, 'dBTP', true)).toBe('0.0 dBTP')
expect(formatLoudness(0.04, 'dBTP', true)).toBe('0.0 dBTP')
})
it('an unmeasured value is a dash', () => {
expect(formatLoudness(undefined, 'LUFS')).toBe('—')
})
})
+11
View File
@@ -24,3 +24,14 @@ export function keyColor(wheel: number | null): string | undefined {
// Light and saturated: it is drawn as text on a tint of itself, on glass.
return `hsl(${((wheel % 12) / 12) * 360} 90% 76%)`
}
/** A Mastering column's value: one decimal and its unit, the sign shown where
* it carries meaning (true peak above 0 dBTP clips): `-8.2 LUFS`, `+0.3 dBTP`,
* `5.1 LU`. Rounds to the decimal (never to "-0.0"). */
export function formatLoudness(value: number | undefined, unit: string, signed = false): string {
if (value == null) return '—'
let fixed = value.toFixed(1)
if (fixed === '-0.0') fixed = '0.0'
if (signed && value > 0 && fixed !== '0.0') fixed = `+${fixed}`
return `${fixed} ${unit}`
}
+57 -9
View File
@@ -1,7 +1,7 @@
// Central definition of the library table's columns: the TanStack column defs,
// their default widths/visibility/order, and the (id,label) list the "Columns"
// menu renders. Both TrackTable and the Toolbar menu read from here so they stay
// in sync. Column layout (visibility, order, sizing) is persisted to userprefs.
// their default widths/visibility/order, and the (id,label) list the header's
// right-click column chooser renders. TrackTable and that menu both read from
// here so they stay in sync. Column layout (visibility, order, sizing) is persisted to userprefs.
//
// Safe metadata fields are inline-editable: double-click a cell value to edit it
// (the right-click "Edit Tags" dialog remains for multi-field edits). Editing is
@@ -15,7 +15,7 @@ import {
type VisibilityState,
} from '@tanstack/react-table'
import type { Track } from '../api'
import { formatBpm, formatDuration, keyColor } from './format'
import { formatBpm, formatDuration, formatLoudness, keyColor } from './format'
import { cueTypeColor } from './cues'
import { RatingStars } from '../components/RatingStars'
@@ -358,8 +358,50 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
)
},
}),
// The Mastering columns (`core/loudness.py`), grouped in the column chooser.
// Unmeasured is `undefined`, never null: TanStack sorts null as 0, which
// would rank every unmeasured track as the loudest; `sortUndefined: 'last'`
// keeps them at the bottom whichever way the column is sorted.
loudnessColumn('lufs', 'LUFS', 'LUFS'),
loudnessColumn('rms', 'RMS', 'dB'),
loudnessColumn('true_peak', 'True Peak', 'dBTP', true),
loudnessColumn('lra', 'LRA', 'LU'),
loudnessColumn('plr', 'PLR', 'dB'),
]
function loudnessColumn(field: 'lufs' | 'rms' | 'true_peak' | 'lra' | 'plr', header: string, unit: string,
signed = false): ColumnDef<Track, any> {
return col.accessor((t) => t.loudness?.[field], {
id: field,
header,
size: field === 'lufs' || field === 'true_peak' ? 112 : 96,
sortUndefined: 'last',
cell: (c) => {
const v = c.getValue() as number | undefined
if (v == null) return <span className="text-faint">—</span>
const stale = c.row.original.loudness?.stale
return (
<span
className={`whitespace-nowrap font-mono text-xs tabular-nums ${stale ? 'text-faint' : 'text-muted'}`}
title={stale ? 'File changed since analysed — Analyze again to refresh' : undefined}
>
{formatLoudness(v, unit, signed)}
</span>
)
},
})
}
/** The Mastering columns, in order: the column chooser's "Mastering ▸". */
export const MASTERING_COLUMNS: readonly string[] = ['lufs', 'rms', 'true_peak', 'lra', 'plr']
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)',
}
// Traktor dates arrive as "YYYY/M/D" strings; show them compactly (or raw).
function formatDate(v: string | null): string {
if (!v) return '—'
@@ -368,11 +410,17 @@ function formatDate(v: string | null): string {
return `${m[1]}-${m[2].padStart(2, '0')}-${m[3].padStart(2, '0')}`
}
/** (id, label) pairs for the header's column chooser, in definition order. */
export const COLUMN_MENU: { id: string; label: string }[] = TRACK_COLUMNS.map((c) => ({
id: c.id as string,
label: typeof c.header === 'string' ? c.header : (c.id as string),
}))
/** (id, label) pairs for the header's column chooser, in definition order.
* `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)
return {
id,
label: MASTERING_LABELS[id] ?? (typeof c.header === 'string' ? c.header : id),
...(mastering ? { group: 'mastering' as const } : {}),
}
})
export const DEFAULT_COLUMN_ORDER: string[] = TRACK_COLUMNS.map((c) => c.id as string)