"""Extract and normalize audio from video files using FFmpeg. The extractor shells out to the ``ffmpeg`` binary (the most reliable way to handle the full range of container/codec combinations) and produces mono, 16 kHz, 16-bit PCM WAV — the canonical input for ASR/TTS pipelines. """ from __future__ import annotations import shutil import subprocess from dataclasses import dataclass from functools import lru_cache from pathlib import Path from typing import Optional import numpy as np from video_vec2wav2_tokenizer.utils.io import ensure_dir from video_vec2wav2_tokenizer.utils.logging import get_logger logger = get_logger(__name__) @lru_cache(maxsize=1) def ffmpeg_available() -> bool: """Return True if the ffmpeg binary is on PATH.""" return shutil.which("ffmpeg") is not None class FFmpegError(RuntimeError): """Raised when an ffmpeg invocation fails.""" @dataclass(slots=True) class AudioExtractor: """Convert video files to normalized WAV audio.""" sample_rate: int = 16000 channels: int = 1 overwrite: bool = False def __post_init__(self) -> None: if not ffmpeg_available(): raise FFmpegError( "ffmpeg not found on PATH. Install it (https://ffmpeg.org/download.html) " "and ensure `ffmpeg` is callable." ) def extract(self, video_path: str | Path, output_path: str | Path) -> Path: """Extract audio from ``video_path`` to ``output_path`` (PCM WAV). Returns the output path. Skips work if the file already exists and ``overwrite`` is False. """ video_path = Path(video_path) output_path = Path(output_path) if not video_path.exists(): raise FileNotFoundError(f"Video not found: {video_path}") ensure_dir(output_path.parent) if output_path.exists() and not self.overwrite: logger.debug("Audio already extracted, skipping: %s", output_path) return output_path cmd = [ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y" if self.overwrite else "-n", "-i", str(video_path), "-vn", # drop video "-ac", str(self.channels), # channels (1 = mono) "-ar", str(self.sample_rate), # sample rate (16 kHz) "-acodec", "pcm_s16le", # 16-bit PCM "-f", "wav", str(output_path), ] logger.debug("Running ffmpeg: %s", " ".join(cmd)) proc = subprocess.run(cmd, capture_output=True, text=True) if proc.returncode != 0: # ``-n`` returns non-zero if the file exists; tolerate that case. if output_path.exists() and not self.overwrite: return output_path raise FFmpegError( f"ffmpeg failed for {video_path} (exit {proc.returncode}): {proc.stderr.strip()}" ) return output_path def extract_audio( video_path: str | Path, output_path: str | Path, *, sample_rate: int = 16000, channels: int = 1, overwrite: bool = False, ) -> Path: """Convenience wrapper around :class:`AudioExtractor`.""" extractor = AudioExtractor( sample_rate=sample_rate, channels=channels, overwrite=overwrite ) return extractor.extract(video_path, output_path) def load_wav( path: str | Path, *, sample_rate: Optional[int] = None ) -> tuple[np.ndarray, int]: """Load a WAV file as float32 mono samples in ``[-1, 1]``. Uses ``soundfile`` if available, falling back to the stdlib ``wave`` module so the core pipeline works without heavy dependencies. """ path = Path(path) try: import soundfile as sf # type: ignore data, sr = sf.read(str(path), dtype="float32", always_2d=False) if data.ndim > 1: # downmix to mono data = data.mean(axis=1) except ImportError: import wave with wave.open(str(path), "rb") as wf: sr = wf.getframerate() n_frames = wf.getnframes() sampwidth = wf.getsampwidth() n_channels = wf.getnchannels() raw = wf.readframes(n_frames) dtype = {1: np.int8, 2: np.int16, 4: np.int32}.get(sampwidth) if dtype is None: raise ValueError(f"Unsupported PCM sample width: {sampwidth} bytes") ints = np.frombuffer(raw, dtype=dtype).astype(np.float32) max_val = float(np.iinfo(dtype).max) data = ints / max_val if n_channels > 1: data = data.reshape(-1, n_channels).mean(axis=1) if sample_rate is not None and sr != sample_rate: data = _resample(data, sr, sample_rate) sr = sample_rate return data.astype(np.float32, copy=False), sr def _resample(data: np.ndarray, src_sr: int, dst_sr: int) -> np.ndarray: """Resample audio. Prefers librosa; falls back to linear interpolation.""" if src_sr == dst_sr: return data try: import librosa # type: ignore return librosa.resample(data, orig_sr=src_sr, target_sr=dst_sr) except ImportError: duration = data.shape[0] / src_sr n_target = int(round(duration * dst_sr)) src_idx = np.linspace(0.0, data.shape[0] - 1, num=n_target) return np.interp(src_idx, np.arange(data.shape[0]), data).astype(np.float32)