diff --git a/src/songsplit/pipeline/s1_extract.py b/src/songsplit/pipeline/s1_extract.py index e43109f..9621b80 100644 --- a/src/songsplit/pipeline/s1_extract.py +++ b/src/songsplit/pipeline/s1_extract.py @@ -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 + # -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) diff --git a/tests/test_s1_extract.py b/tests/test_s1_extract.py new file mode 100644 index 0000000..8bee3d3 --- /dev/null +++ b/tests/test_s1_extract.py @@ -0,0 +1,100 @@ +"""Unit tests for Stage 1 (Audio extraction via ffmpeg).""" + +import shutil +import subprocess +from pathlib import Path + +import pytest + +from songsplit.pipeline.runner import PipelineContext +from songsplit.pipeline.s1_extract import ExtractStage, get_audio_duration + + +@pytest.fixture +def sample_video_and_audio(tmp_path: Path): + """Generate synthetic test audio and video files using ffmpeg.""" + ffmpeg = shutil.which("ffmpeg") + if not ffmpeg: + pytest.skip("ffmpeg not available") + + audio_file = tmp_path / "sine.mp3" + # Create 1.5s 440Hz test MP3 + subprocess.run( + [ + ffmpeg, + "-y", + "-f", + "lavfi", + "-i", + "sine=frequency=440:duration=1.5", + "-c:a", + "libmp3lame", + "-b:a", + "128k", + str(audio_file), + ], + check=True, + capture_output=True, + ) + + video_file = tmp_path / "test_video.mp4" + # Create 1.0s synthetic MP4 video with test tone + subprocess.run( + [ + ffmpeg, + "-y", + "-f", + "lavfi", + "-i", + "color=c=blue:s=320x240:d=1.0", + "-f", + "lavfi", + "-i", + "sine=frequency=880:duration=1.0", + "-c:v", + "libx264", + "-c:a", + "aac", + "-shortest", + str(video_file), + ], + check=True, + capture_output=True, + ) + + return audio_file, video_file + + +def test_extract_stage_audio_input(sample_video_and_audio, tmp_path: Path): + audio_file, _ = sample_video_and_audio + out_dir = tmp_path / "song_pkg" + ctx = PipelineContext(source_file=audio_file, output_dir=out_dir) + + stage = ExtractStage() + stage.run(ctx) + + out_wav = stage.get_outputs(ctx)[0] + assert out_wav.exists() + + # Check duration using get_audio_duration + duration = get_audio_duration(out_wav) + assert duration == pytest.approx(1.5, abs=0.1) + + # Check updated meta.json + meta = ctx.load_or_init_meta() + assert meta.duration_sec == pytest.approx(1.5, abs=0.1) + + +def test_extract_stage_video_input(sample_video_and_audio, tmp_path: Path): + _, video_file = sample_video_and_audio + out_dir = tmp_path / "song_pkg_video" + ctx = PipelineContext(source_file=video_file, output_dir=out_dir) + + stage = ExtractStage() + stage.run(ctx) + + out_wav = stage.get_outputs(ctx)[0] + assert out_wav.exists() + + duration = get_audio_duration(out_wav) + assert duration == pytest.approx(1.0, abs=0.1)