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

+243 -59
View File
@@ -8,6 +8,7 @@ from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from pathlib import Path
from types import SimpleNamespace
@@ -15,10 +16,10 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from . import __version__, exporter, exports, prefs
from . import __version__, exporter, exports, loudness_store, prefs
from .app_state import STATE
from .core import auto_hotcues as ah
from .core import grid_detect, key_detect, structure
from .core import grid_detect, key_detect, loudness, structure
from .core.grid_plan import GridStep, plan_grid
from . import importer
from .core import export as core_export
@@ -44,6 +45,10 @@ from .schemas import (
RelocationVolume,
AnalyzePreview,
AnalyzeRequest,
LoudnessRequest,
LoudnessValue,
LoudnessValues,
MeasureLoudnessRequest,
AutoGridBatchRequest,
AutoGridRequest,
AutoCueOutcome,
@@ -456,6 +461,12 @@ def remap_paths(body: PathMappingInfo) -> RemapResult:
return RemapResult(rewritten=0, commit=None)
if moved and STATE.library_id:
exports.retarget(STATE.library_id, moved)
# The files now live under `to`: carry their loudness values across (they
# are keyed by the path they were measured at). Not an edit, so not saved.
try:
STATE.loudness.remap(mapping)
except Exception: # noqa: BLE001 — bookkeeping must never fail a remap
log.warning("could not move loudness values for %s", mapping, exc_info=True)
# Through AppState, not the adapter: this is the one route besides /api/save
# that writes, and skipping it would leave a gap in the version history.
_outcome, commit = STATE.save()
@@ -1543,6 +1554,14 @@ def auto_grid(body: AutoGridRequest) -> TrackCues:
a.set_key(body.track_id, found.wheel, found.mode)
except Exception: # noqa: BLE001 — the grid is written; a key is a bonus
log.warning("key detection failed for %s", body.track_id, exc_info=True)
try: # so is loudness, into Konduktor's own store — always re-measured here
looked = _loud_lookup("collection", [body.track_id]).get(body.track_id)
if looked is not None:
_measure_loudness(looked[0], looked[1], path)
except _AnalysisError as ex:
log.warning("no loudness for %s: %s", body.track_id, ex)
except Exception: # noqa: BLE001
log.warning("loudness measurement failed for %s", body.track_id, exc_info=True)
return cues
@@ -1635,10 +1654,14 @@ def _analyse_grid(a, track_id: str, step: GridStep = GridStep("full"), *,
# ---- Analyze (the context menu's "Analyze…": BPM / Grid / Key) -------------
def _require_analysable(a, body: AnalyzeRequest) -> None:
caps = a.capabilities()
def _require_analysable(body: AnalyzeRequest) -> None:
if not (body.bpm or body.grid or body.key or body.loudness):
raise HTTPException(400, "Nothing to analyse: tick BPM, Grid, Key or Loudness")
if not (body.bpm or body.grid or body.key):
raise HTTPException(400, "Nothing to analyse: tick BPM, Grid or Key")
return # loudness: Konduktor's own store, so any track, any library
if body.origin != "collection":
raise HTTPException(400, "BPM, grid and key are analysed only for the library's own tracks")
caps = require_adapter().capabilities()
if (body.bpm or body.grid) and not caps.grid.editable:
raise HTTPException(422, "This library's beatgrids cannot be edited")
if body.key and not caps.tracks.key_writable:
@@ -1665,30 +1688,46 @@ def _wants_key(track, body: AnalyzeRequest) -> bool:
@app.post("/api/tracks/analyze/preview", response_model=AnalyzePreview)
def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview:
"""Counts for the Analyze dialog, from the same `plan_grid` the run uses."""
a = require_adapter()
"""Counts for the Analyze dialog, from the same `plan_grid` the run uses
(and, for loudness, the same store lookups)."""
a = require_adapter() if body.origin == "collection" else None
looked = _loud_lookup(body.origin, body.track_ids) if body.loudness or a is None else {}
out = AnalyzePreview(total=0)
for tid in dict.fromkeys(body.track_ids):
track = a.track(tid)
if track is None:
if a is not None:
track = a.track(tid)
if track is None:
continue
elif tid not in looked:
continue
out.total += 1
if track.grid_marker_count and not track.grid_locked:
out.with_grid += 1
step = _grid_step(a, track, body, exact=False)
if step.action in ("full", "bpm", "phase") or _wants_key(track, body):
out.tracks_to_analyze += 1
if step.action in ("full", "bpm", "phase"):
setattr(out, f"grid_{step.action}", getattr(out, f"grid_{step.action}") + 1)
elif step.action == "skip":
setattr(out, f"grid_{step.reason}", getattr(out, f"grid_{step.reason}") + 1)
if track.key_wheel is not None:
out.with_key += 1
if body.key:
if _wants_key(track, body):
out.key_set += 1
busy = False
if a is not None:
if track.grid_marker_count and not track.grid_locked:
out.with_grid += 1
step = _grid_step(a, track, body, exact=False)
busy = step.action in ("full", "bpm", "phase") or _wants_key(track, body)
if step.action in ("full", "bpm", "phase"):
setattr(out, f"grid_{step.action}", getattr(out, f"grid_{step.action}") + 1)
elif step.action == "skip":
setattr(out, f"grid_{step.reason}", getattr(out, f"grid_{step.reason}") + 1)
if track.key_wheel is not None:
out.with_key += 1
if body.key:
if _wants_key(track, body):
out.key_set += 1
else:
out.key_existing += 1
if body.loudness:
_target, facts, entry = looked.get(tid, (None, None, None))
fresh = entry is not None and not entry.stale(facts)
out.with_loudness += fresh
if fresh and not body.replace_loudness:
out.loudness_existing += 1
else:
out.key_existing += 1
out.loudness_measure += 1
busy = True
out.tracks_to_analyze += busy
return out
@@ -1703,50 +1742,80 @@ def _decode_for_analysis(path: Path):
def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None:
"""Analyse one track as `body` asks, folding the outcome into `result`.
The file is decoded ONCE and shared by grid and key. A failing half is
reported and does not stop the other: a track whose grid cannot be fitted
`a` is the loaded library for BPM / Grid / Key (None for a device's or a
folder's tracks, which can only have their loudness measured). The file is
decoded ONCE and shared by grid and key; loudness decodes on its own, at
the file's own rate and channels (`core/loudness.py`). A failing part is
reported and does not stop the others: a track whose grid cannot be fitted
(a one-shot) can still have a key, and the reverse."""
track = a.track(track_id)
try:
looked = _loud_lookup(body.origin, [track_id]).get(track_id) if body.loudness or a is None else None
except HTTPException: # the source went away mid-run
looked = None
if a is not None:
track, src, sid = a.track(track_id), a, track_id
elif looked is not None:
src, sid = looked[0].src, looked[0].sid
track = src.track(sid)
else:
track = None
title = (track.title or track_id) if track else track_id
if track is None:
result["failed"].append({"title": title, "reason": "Track not found"})
return
step = _grid_step(a, track, body, exact=True)
step = _grid_step(a, track, body, exact=True) if a is not None else GridStep("none")
if step.action == "skip":
result["grid"][step.reason] += 1
want_key = _wants_key(track, body)
want_key = a is not None and _wants_key(track, body)
if body.key and not want_key:
result["key"]["existing"] += 1
if step.action not in ("full", "bpm", "phase") and not want_key:
want_loud = False
if body.loudness and looked is not None:
_target, facts, entry = looked
want_loud = body.replace_loudness or entry is None or entry.stale(facts)
if not want_loud:
result["loudness"]["existing"] += 1
want_grid = step.action in ("full", "bpm", "phase")
if not (want_grid or want_key or want_loud):
return
path = a.audio_path(track_id)
path = src.audio_path(sid)
if path is None or not path.exists():
result["failed"].append({"title": title, "reason": "Audio file not found (is the drive mounted?)"})
return
try:
y, sr = _decode_for_analysis(path)
except Exception as ex: # noqa: BLE001 — an undecodable file is one failure
result["failed"].append({"title": title, "reason": f"Could not decode: {ex}"})
return
wrote = False
if step.action in ("full", "bpm", "phase"):
if want_grid or want_key:
try:
_analyse_grid(a, track_id, step, y=y, sr=sr)
result["grid"][step.action] += 1
wrote = True
except (_AnalysisError, AdapterError) as ex:
result["failed"].append({"title": title, "reason": f"Grid: {ex}"})
if want_key:
try:
found = key_detect.detect_key_samples(y, sr)
if found is None:
result["key"]["none"] += 1
else:
a.set_key(track_id, found.wheel, found.mode)
result["key"]["set"] += 1
y, sr = _decode_for_analysis(path)
except Exception as ex: # noqa: BLE001 — an undecodable file is one failure
result["failed"].append({"title": title, "reason": f"Could not decode: {ex}"})
return
if want_grid:
try:
_analyse_grid(a, track_id, step, y=y, sr=sr)
result["grid"][step.action] += 1
wrote = True
except (AdapterError, ValueError) as ex:
result["failed"].append({"title": title, "reason": f"Key: {ex}"})
except (_AnalysisError, AdapterError) as ex:
result["failed"].append({"title": title, "reason": f"Grid: {ex}"})
if want_key:
try:
found = key_detect.detect_key_samples(y, sr)
if found is None:
result["key"]["none"] += 1
else:
a.set_key(track_id, found.wheel, found.mode)
result["key"]["set"] += 1
wrote = True
except (AdapterError, ValueError) as ex:
result["failed"].append({"title": title, "reason": f"Key: {ex}"})
if want_loud:
try:
if _measure_loudness(looked[0], looked[1], path) is None:
result["loudness"]["none"] += 1
else:
result["loudness"]["measured"] += 1
wrote = True
except (_AnalysisError, AdapterError) as ex:
result["failed"].append({"title": title, "reason": f"Loudness: {ex}"})
if wrote:
result["analysed"].append(track_id)
@@ -1759,13 +1828,14 @@ def _analyze_job(a, body: AnalyzeRequest):
"analysed": [], "failed": [],
"grid": {"full": 0, "bpm": 0, "phase": 0, "locked": 0, "existing": 0, "flexible": 0},
"key": {"set": 0, "existing": 0, "none": 0},
"loudness": {"measured": 0, "existing": 0, "none": 0},
}
handle.progress(done=0, total=len(ids))
for i, track_id in enumerate(ids):
if handle.cancelled:
break # keep what is done; return it rather than raise
track = a.track(track_id)
handle.progress(message=(track.title or track_id) if track else track_id)
track = a.track(track_id) if a is not None else None
handle.progress(message=(track.title or track_id) if track else Path(track_id).name)
_analyse_one(a, track_id, body, result)
handle.progress(done=i + 1)
# The names the context menu's toast read before the dialog existed.
@@ -1781,11 +1851,14 @@ def analyze_batch(body: AnalyzeRequest) -> JobStatus:
Each track is written as it finishes, into the in-memory model like any
other edit — so a cancel keeps what is done (it is all unsaved until Save),
and the result is returned even from a cancelled run. A track that fails is
reported and skipped, never fatal: one unmounted drive must not stop 400
other tracks."""
a = require_adapter()
_require_analysable(a, body)
and the result is returned even from a cancelled run. Loudness is stored
as each track is measured and is not an edit at all (`loudness_store.py`).
A track that fails is reported and skipped, never fatal: one unmounted
drive must not stop 400 other tracks."""
_require_analysable(body)
if body.origin == "device":
require_source()
a = require_adapter() if body.origin == "collection" else None
_require_no_batch()
job = _submit_batch(GRID_JOB, _analyze_job(a, body))
return JobStatus(**job.as_dict())
@@ -1799,6 +1872,117 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
key=False, replace_grid=body.replace_existing))
# ---- Loudness (the Mastering columns) --------------------------------------
#
# Measured by `core/loudness.py` into Konduktor's own store (`loudness_store.py`),
# keyed by the FILE: the loaded library's (on a remote library, the server's),
# this computer's for a device's or a Files folder's tracks. Never an edit.
@dataclass
class _LoudTarget:
src: object # .track / .audio_facts / .audio_path for `sid`
sid: str
store: object # loudness_store.LoudnessStore
def _loud_target(origin: str, track_id: str) -> _LoudTarget | None:
"""Where a track's file and its loudness value live, by whose id it is."""
if origin == "device":
source = require_source()
return _LoudTarget(source, track_id, loudness_store.local()) if source.track(track_id) else None
if origin == "folder":
raw = _on_server(track_id)
if raw is not None:
if STATE.remote is None or STATE.adapter is None:
return None
files = STATE.adapter.listed_files([raw])
return _LoudTarget(files, raw, STATE.loudness) if files else None
source = FOLDERS.source_for_file(track_id)
if source is not None:
return _LoudTarget(source, track_id, loudness_store.local())
if not STATE.loaded:
return None
# Not a listed file: a folder view's held row, which IS a library track.
a = require_adapter()
return _LoudTarget(a, track_id, STATE.loudness) if a.track(track_id) else None
def _loud_lookup(origin: str, track_ids) -> dict:
"""`{id: (target, facts | None, entry | None)}` for the known ids. Each
source is asked for its facts once and each store once — a whole library's
worth for the table's columns. Facts never download (`audio_facts`); a
file that is missing has none, and so no value."""
targets = {tid: t for tid in dict.fromkeys(track_ids) if (t := _loud_target(origin, tid)) is not None}
facts: dict[str, object] = {}
by_source: dict[int, list[str]] = {}
for tid, t in targets.items():
by_source.setdefault(id(t.src), []).append(tid)
for tids in by_source.values():
src = targets[tids[0]].src
found = src.audio_facts([targets[tid].sid for tid in tids])
for tid in tids:
facts[tid] = found.get(targets[tid].sid)
entries: dict[str, object] = {}
by_store: dict[int, list[str]] = {}
for tid, t in targets.items():
if facts[tid] is not None:
by_store.setdefault(id(t.store), []).append(tid)
for tids in by_store.values():
store = targets[tids[0]].store
got = store.get([facts[tid].key for tid in tids])
for tid in tids:
entries[tid] = got.get(facts[tid].key)
return {tid: (t, facts[tid], entries.get(tid)) for tid, t in targets.items()}
def _measure_loudness(target: _LoudTarget, facts, path: Path | None = None):
"""Measure one file and store it (None: silent, or under 3 s). Raises
`_AnalysisError` with a user-facing reason. The facts stored are the ones
read BEFORE decoding, so a file changing meanwhile reads as stale."""
if not getattr(target.store, "available", True):
raise _AnalysisError("This Konduktor server is too old to keep loudness — update it")
if facts is None:
raise _AnalysisError("Audio file not found (is the drive mounted?)")
if path is None:
path = target.src.audio_path(target.sid)
if path is None or not Path(path).exists():
raise _AnalysisError("Audio file not found (is the drive mounted?)")
try:
values = loudness.measure_file(path)
except Exception as ex: # noqa: BLE001 — an undecodable file is one failure
raise _AnalysisError(f"Could not decode: {ex}")
if values is not None:
target.store.put(facts, values)
return values
@app.post("/api/loudness", response_model=LoudnessValues)
def loudness_values(body: LoudnessRequest) -> LoudnessValues:
"""The Mastering columns' values for a list's tracks — measured ones only."""
values = {}
for tid, (_target, facts, entry) in _loud_lookup(body.origin, body.track_ids).items():
if entry is not None:
values[tid] = LoudnessValue(**entry.values.as_dict(), stale=entry.stale(facts))
return LoudnessValues(values=values)
@app.post("/api/tracks/loudness", response_model=LoudnessValue)
def measure_loudness(body: MeasureLoudnessRequest) -> LoudnessValue:
"""The deck's Analyze where it cannot write a grid (a read-only library, a
device, a loose file): measure loudness alone, always afresh."""
looked = _loud_lookup(body.origin, [body.track_id]).get(body.track_id)
if looked is None:
raise HTTPException(404, "Track not found")
try:
values = _measure_loudness(looked[0], looked[1])
except _AnalysisError as ex:
raise HTTPException(400, str(ex))
if values is None:
raise HTTPException(400, "Nothing to measure: the track is silent or under 3 seconds")
return LoudnessValue(**values.as_dict())
@app.post("/api/tracks/cue/auto-batch", response_model=JobStatus)
def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus:
"""Place one Auto Hotcues template on many tracks, as a JOB.