"""Audio-Metadaten (Dauer, Tags, Format). Primaer wird Mutagen verwendet; wenn Mutagen eine Datei nicht lesen kann, wird PyAV als Fallback genutzt. Beide Wege lesen nur Header bzw. Container, nicht die komplette Audiodatei. """ from __future__ import annotations from dataclasses import dataclass, field from pathlib import Path from typing import Any from ..utils.logging import get_logger logger = get_logger("core.metadata") SUPPORTED_EXTENSIONS = frozenset( {".mp3", ".wav", ".flac", ".m4a", ".ogg", ".opus", ".wma"} ) # WMA ist nur zuverlaessig dekodierbar, wenn ffmpeg/PyAV den Codec kennt. CONDITIONAL_EXTENSIONS = frozenset({".wma"}) class AudioMetadataError(RuntimeError): """Die Datei konnte nicht als Audio gelesen werden.""" @dataclass class AudioInfo: """Ergebnis der Metadatenanalyse.""" path: str duration: float | None = None codec: str | None = None sample_rate: int | None = None channels: int | None = None bitrate: int | None = None tags: dict[str, str] = field(default_factory=dict) source: str = "mutagen" def is_supported_audio(path: str | Path) -> bool: return Path(path).suffix.lower() in SUPPORTED_EXTENSIONS def _clean_tags(raw: dict[str, Any]) -> dict[str, str]: tags: dict[str, str] = {} for key, value in raw.items(): try: if isinstance(value, (list, tuple)): text = ", ".join(str(item) for item in value if item is not None) else: text = str(value) except Exception: # defekte Tag-Objekte duerfen den Scan nicht stoppen continue if text: tags[str(key).lower()] = text return tags def _read_with_mutagen(path: Path) -> AudioInfo: import mutagen audio = mutagen.File(str(path)) if audio is None: raise AudioMetadataError("Format wurde von Mutagen nicht erkannt") info = getattr(audio, "info", None) duration = getattr(info, "length", None) if duration is None: raise AudioMetadataError("Mutagen konnte keine Dauer ermitteln") return AudioInfo( path=str(path), duration=float(duration), codec=type(audio).__name__, sample_rate=getattr(info, "sample_rate", None), channels=getattr(info, "channels", None), bitrate=getattr(info, "bitrate", None), tags=_clean_tags(dict(audio.tags or {})), source="mutagen", ) def _read_with_pyav(path: Path) -> AudioInfo: import av try: with av.open(str(path)) as container: if not container.streams.audio: raise AudioMetadataError("Keine Audiospur gefunden") stream = container.streams.audio[0] duration = None if stream.duration is not None and stream.time_base is not None: duration = float(stream.duration * stream.time_base) elif container.duration is not None: duration = float(container.duration / 1_000_000) if duration is None or duration <= 0: raise AudioMetadataError("Keine gueltige Dauer ermittelbar") return AudioInfo( path=str(path), duration=duration, codec=stream.codec_context.name, sample_rate=stream.codec_context.sample_rate, channels=stream.codec_context.channels, bitrate=stream.bit_rate, source="pyav", ) except AudioMetadataError: raise except Exception as exc: # PyAV wirft verschiedene Fehlertypen raise AudioMetadataError(f"PyAV konnte die Datei nicht lesen: {exc}") from exc def read_metadata(path: str | Path) -> AudioInfo: """Liest Metadaten ueber Mutagen, bei Bedarf ueber PyAV.""" file_path = Path(path) if not file_path.is_file(): raise AudioMetadataError(f"Datei nicht gefunden: {file_path}") errors: list[str] = [] try: return _read_with_mutagen(file_path) except Exception as exc: errors.append(f"mutagen: {exc}") logger.debug("Mutagen fehlgeschlagen fuer %s: %s", file_path, exc) try: return _read_with_pyav(file_path) except Exception as exc: errors.append(f"pyav: {exc}") logger.debug("PyAV fehlgeschlagen fuer %s: %s", file_path, exc) raise AudioMetadataError("; ".join(errors)) def read_duration(path: str | Path) -> float | None: """Dauer einer Datei oder ``None``, wenn sie nicht ermittelbar ist.""" try: return read_metadata(path).duration except AudioMetadataError: return None