File size: 7,551 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d649252
 
 
 
 
 
 
 
 
 
 
 
 
 
25e4412
 
d649252
 
25e4412
 
 
 
 
 
d649252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
"""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]