stemdeck-gpu / stemdeck /audio_io.py
AnjaneyaTurai's picture
Deploy the StemDeck GPU service
d649252 verified
Raw History Blame Contribute Delete
7.55 kB
"""Audio file helpers: ffmpeg conversion, float I/O, length fitting, level measurements."""
from __future__ import annotations
import json
import os
import shutil
import subprocess
from pathlib import Path
import numpy as np
import soundfile as sf
SAMPLE_RATE = 44100
CHANNELS = 2
PROBE_TIMEOUT_SEC = 60.0
DECODE_TIMEOUT_SEC = 600.0
# Uploaded files are untrusted: ffmpeg must only read the file itself, never follow a playlist or a URL inside it.
SAFE_INPUT = ("-nostdin", "-protocol_whitelist", "file,pipe")
class AudioError(RuntimeError):
"""A user-facing audio problem (bad file, too long, ffmpeg missing)."""
def ffmpeg_path() -> str:
path = shutil.which("ffmpeg")
if path is None:
raise AudioError("ffmpeg was not found on PATH. Run the setup script or install ffmpeg.")
return path
BAD_FILE = "Couldn't read this file. Is it a valid audio or video file?"
def _positive(value: object) -> float | None:
try:
seconds = float(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return None
return seconds if seconds > 0 else None
def _header_duration(ffprobe: str, path: Path) -> tuple[bool, float | None]:
"""(has an audio stream, length from the file's header). Browser recordings (WebM from MediaRecorder) and some
streamed files carry no length in their header, so the second value can be None for a perfectly good file."""
try:
proc = subprocess.run(
[ffprobe, "-v", "error", "-protocol_whitelist", "file,pipe", "-show_entries",
"format=duration:stream=codec_type,duration", "-of", "json", str(path)],
capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,
timeout=PROBE_TIMEOUT_SEC, stdin=subprocess.DEVNULL,
)
except subprocess.TimeoutExpired as exc:
raise AudioError("Reading this file took too long. Is it a valid audio or video file?") from exc
try:
info = json.loads(proc.stdout or "{}")
except json.JSONDecodeError:
return False, None
audio = [s for s in info.get("streams") or [] if s.get("codec_type") == "audio"]
if not audio:
return False, None
length = _positive((info.get("format") or {}).get("duration"))
if length is None:
length = max((d for d in (_positive(s.get("duration")) for s in audio) if d), default=None)
return True, length
def _decoded_duration(path: Path) -> float | None:
"""Length found by decoding the audio track to nowhere (fast: no resampling, no output file)."""
try:
proc = subprocess.run(
[ffmpeg_path(), "-v", "error", *SAFE_INPUT, "-i", str(path), "-vn", "-map", "0:a:0",
"-f", "null", "-progress", "pipe:1", "-nostats", "-"],
capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,
timeout=DECODE_TIMEOUT_SEC, stdin=subprocess.DEVNULL,
)
except subprocess.TimeoutExpired as exc:
raise AudioError("Reading this file took too long. Is it a valid audio or video file?") from exc
if proc.returncode != 0:
return None
micros = [line.split("=", 1)[1] for line in proc.stdout.splitlines() if line.startswith("out_time_us=")]
seconds = _positive(micros[-1]) if micros else None
return seconds / 1_000_000 if seconds else None
def probe_duration(path: Path) -> float:
ffprobe = shutil.which("ffprobe")
if ffprobe is None:
raise AudioError("ffprobe was not found on PATH. Run the setup script or install ffmpeg.")
has_audio, length = _header_duration(ffprobe, path)
if not has_audio:
raise AudioError(BAD_FILE)
length = length or _decoded_duration(path)
if not length:
raise AudioError(BAD_FILE)
return length
def convert_to_master(src: Path, dst: Path) -> None:
"""Decode any audio/video file to 44.1 kHz stereo 32-bit float WAV (the master `source.wav`)."""
dst.parent.mkdir(parents=True, exist_ok=True)
try:
proc = subprocess.run(
[ffmpeg_path(), "-y", "-v", "error", *SAFE_INPUT, "-i", str(src), "-vn", "-map", "0:a:0",
"-ac", str(CHANNELS), "-ar", str(SAMPLE_RATE), "-c:a", "pcm_f32le", str(dst)],
capture_output=True, text=True, encoding="utf-8", errors="replace", check=False,
timeout=DECODE_TIMEOUT_SEC, stdin=subprocess.DEVNULL,
)
except subprocess.TimeoutExpired as exc:
raise AudioError("Decoding this file took too long. Is it a valid audio or video file?") from exc
if proc.returncode != 0 or not dst.exists():
raise AudioError("Couldn't decode the audio in this file. Is it a valid audio or video file?")
def read_audio(path: Path) -> np.ndarray:
"""Read as float32 (frames, channels), forcing stereo."""
data, sr = sf.read(str(path), dtype="float32", always_2d=True)
if sr != SAMPLE_RATE:
raise AudioError(f"Unexpected sample rate {sr} in {path.name}")
if data.shape[1] == 1:
data = np.repeat(data, 2, axis=1)
return data[:, :CHANNELS]
def write_float_wav(path: Path, audio: np.ndarray) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
sf.write(str(path), audio, SAMPLE_RATE, subtype="FLOAT")
def write_flac(path: Path, audio: np.ndarray) -> None:
"""FLAC for playback: 24-bit, or 16-bit with STEMDECK_FLAC_SUBTYPE=PCM_16 (the cloud version, where every stem
is downloaded to the browser). Values beyond ±1 are clipped (only possible on extreme stems)."""
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp.flac")
subtype = os.environ.get("STEMDECK_FLAC_SUBTYPE", "PCM_24")
sf.write(str(tmp), np.clip(audio, -1.0, 1.0), SAMPLE_RATE, subtype=subtype, format="FLAC")
tmp.replace(path)
def fit_length(audio: np.ndarray, n_frames: int) -> np.ndarray:
"""Pad with silence or trim so every stem has exactly the source's sample count."""
if len(audio) == n_frames:
return audio
if len(audio) > n_frames:
return audio[:n_frames]
return np.pad(audio, ((0, n_frames - len(audio)), (0, 0)))
def rms_dbfs(audio: np.ndarray) -> float:
if audio.size == 0:
return -200.0
return float(20.0 * np.log10(np.sqrt(np.mean(np.square(audio, dtype=np.float64))) + 1e-10))
def snr_db(reference: np.ndarray, estimate: np.ndarray) -> float:
noise = reference.astype(np.float64) - estimate.astype(np.float64)
signal_power = float(np.sum(np.square(reference, dtype=np.float64)))
noise_power = float(np.sum(np.square(noise)))
if noise_power == 0.0:
return 200.0
return float(10.0 * np.log10((signal_power + 1e-20) / noise_power))
def peaks(audio: np.ndarray, points: int) -> list[float]:
"""Interleaved [min, max] pairs of the mono mix, `points` buckets, rounded for compact JSON."""
mono = audio.mean(axis=1) if audio.ndim == 2 else audio
n = len(mono)
if n == 0:
return [0.0, 0.0] * points
edges = np.linspace(0, n, points + 1, dtype=np.int64)
out = np.empty(points * 2, dtype=np.float32)
for i in range(points):
a, b = int(edges[i]), max(int(edges[i + 1]), int(edges[i]) + 1)
seg = mono[a:min(b, n)]
out[2 * i] = seg.min() if seg.size else 0.0
out[2 * i + 1] = seg.max() if seg.size else 0.0
return [round(float(v), 4) for v in out]