File size: 4,518 Bytes
45d92cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import math
import subprocess
import sys
import wave
from array import array
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any


@dataclass(frozen=True, slots=True)
class AudioAnalysis:
    duration_s: float
    sample_rate: int
    channels: int
    peak_dbfs: float
    rms_dbfs: float
    crest_db: float
    zero_crossing_rate: float
    character: str

    def as_dict(self) -> dict[str, Any]:
        return asdict(self)


def _dbfs(amplitude: float) -> float:
    if amplitude <= 0:
        return -96.0
    return max(-96.0, 20 * math.log10(amplitude / 32767.0))


def _describe_character(rms_dbfs: float, crest_db: float, zero_crossing_rate: float) -> str:
    density = "dicht" if rms_dbfs > -12 else "ausgewogen" if rms_dbfs > -20 else "dynamisch"
    tone = (
        "brillant/perkussiv"
        if zero_crossing_rate > 0.14
        else "warm/dunkel"
        if zero_crossing_rate < 0.055
        else "tonal balanciert"
    )
    transients = "kompakt" if crest_db < 7 else "transientenreich" if crest_db > 13 else "offen"
    return f"{density}, {tone}, {transients}"


def _read_audio_as_pcm16(audio_path: Path) -> tuple[int, int, int, bytes]:
    try:
        with wave.open(str(audio_path), "rb") as wav_file:
            channels = wav_file.getnchannels()
            sample_width = wav_file.getsampwidth()
            sample_rate = wav_file.getframerate()
            frame_count = wav_file.getnframes()
            frames = wav_file.readframes(frame_count)
        if sample_width == 2:
            return channels, sample_rate, frame_count, frames
    except wave.Error:
        pass

    probe = subprocess.run(
        [
            "ffprobe",
            "-v",
            "error",
            "-select_streams",
            "a:0",
            "-show_entries",
            "stream=sample_rate,channels",
            "-of",
            "json",
            str(audio_path),
        ],
        check=False,
        capture_output=True,
        text=True,
        timeout=30,
    )
    if probe.returncode != 0:
        raise ValueError(f"FFprobe konnte die WAV-Datei nicht lesen: {probe.stderr[-500:]}")
    payload = json.loads(probe.stdout)
    streams = payload.get("streams", [])
    if not streams:
        raise ValueError("Die WAV-Datei enthält keinen Audiostream.")
    channels = int(streams[0]["channels"])
    sample_rate = int(streams[0]["sample_rate"])
    decoded = subprocess.run(
        [
            "ffmpeg",
            "-v",
            "error",
            "-nostdin",
            "-i",
            str(audio_path),
            "-f",
            "s16le",
            "-acodec",
            "pcm_s16le",
            "-",
        ],
        check=False,
        capture_output=True,
        timeout=120,
    )
    if decoded.returncode != 0:
        detail = decoded.stderr.decode("utf-8", errors="replace")[-500:]
        raise ValueError(f"FFmpeg konnte die WAV-Datei nicht dekodieren: {detail}")
    frame_count = len(decoded.stdout) // (2 * channels)
    return channels, sample_rate, frame_count, decoded.stdout


def analyze_wav(path: str | Path) -> AudioAnalysis:
    audio_path = Path(path)
    channels, sample_rate, frame_count, frames = _read_audio_as_pcm16(audio_path)
    if channels < 1 or sample_rate < 1 or frame_count < 1:
        raise ValueError("Die WAV-Datei enthält keine analysierbaren Audiodaten.")

    samples = array("h")
    samples.frombytes(frames)
    if sys.byteorder != "little":
        samples.byteswap()

    peak = max(abs(sample) for sample in samples)
    square_sum = sum(sample * sample for sample in samples)
    rms = math.sqrt(square_sum / len(samples))
    mono_samples = samples[::channels]
    crossings = sum(
        1
        for previous, current in zip(mono_samples, mono_samples[1:], strict=False)
        if (previous < 0 <= current) or (previous >= 0 > current)
    )
    zero_crossing_rate = crossings / max(1, len(mono_samples) - 1)
    peak_dbfs = _dbfs(float(peak))
    rms_dbfs = _dbfs(rms)
    crest_db = max(0.0, peak_dbfs - rms_dbfs)

    return AudioAnalysis(
        duration_s=frame_count / sample_rate,
        sample_rate=sample_rate,
        channels=channels,
        peak_dbfs=round(peak_dbfs, 2),
        rms_dbfs=round(rms_dbfs, 2),
        crest_db=round(crest_db, 2),
        zero_crossing_rate=round(zero_crossing_rate, 4),
        character=_describe_character(rms_dbfs, crest_db, zero_crossing_rate),
    )