feat(extract): implement stage 1 audio/video extraction via ffmpeg

This commit is contained in:
2026-11-02 10:22:25 +01:00
parent bfb93a4007
commit 191133b006
2 changed files with 175 additions and 4 deletions

View File

@ -1,12 +1,42 @@
"""Stage 1: Extract audio to 44.1 kHz stereo WAV using ffmpeg."""
import json
import shutil
import subprocess
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
def get_audio_duration(file_path: Path) -> float:
"""Get audio duration in seconds using ffprobe."""
ffprobe_path = shutil.which("ffprobe")
if not ffprobe_path:
# Fallback to ffmpeg
return 0.0
cmd = [
ffprobe_path,
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"json",
str(file_path),
]
try:
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
data = json.loads(res.stdout)
return float(data.get("format", {}).get("duration", 0.0))
except Exception:
return 0.0
class ExtractStage(Stage):
"""Stage 1 extracts and standardizes input audio/video to 44.1 kHz stereo WAV."""
name = "s1_extract"
version = "1.0.0"
model_name = "ffmpeg"
@ -17,11 +47,52 @@ class ExtractStage(Stage):
return [ctx.source_file]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "extracted.wav"]
return [ctx.cache_dir / "extracted.wav"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"sample_rate": 44100, "channels": 2}
return {
"sample_rate": 44100,
"channels": 2,
"codec": "pcm_s16le",
}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M1
raise NotImplementedError("Stage s1_extract will be implemented in M1.")
ffmpeg_path = shutil.which("ffmpeg")
if not ffmpeg_path:
raise FileNotFoundError("ffmpeg executable not found in PATH")
output_wav = self.get_outputs(ctx)[0]
output_wav.parent.mkdir(parents=True, exist_ok=True)
# ffmpeg extraction command:
# -y : overwrite output
# -i <source>
# -vn : disable video recording
# -acodec pcm_s16le : 16-bit uncompressed PCM
# -ar 44100 : 44.1 kHz sample rate
# -ac 2 : stereo
cmd = [
ffmpeg_path,
"-y",
"-i",
str(ctx.source_file),
"-vn",
"-acodec",
"pcm_s16le",
"-ar",
"44100",
"-ac",
"2",
str(output_wav),
]
res = subprocess.run(cmd, capture_output=True, text=True)
if res.returncode != 0:
raise RuntimeError(f"ffmpeg extraction failed: {res.stderr}")
# Update duration in meta document if available
duration = get_audio_duration(output_wav)
if duration > 0.0:
meta = ctx.load_or_init_meta()
meta.duration_sec = duration
ctx.save_meta(meta)