Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(audio): classify silent inputs without stderr matching (#9828)

Nianze Wu676f90f2f7b6
diff --git a/invokeai/app/util/video_audio.py b/invokeai/app/util/video_audio.py
index 0dcdb9cc49..3880ac8011 100644
--- a/invokeai/app/util/video_audio.py
+++ b/invokeai/app/util/video_audio.py
@@ -20,6 +20,7 @@ import subprocess
import tempfile
import time
import wave
+from contextlib import nullcontext
from pathlib import Path
from typing import Callable, Optional
@@ -47,7 +48,11 @@ def _ffmpeg_exe() -> str:
def run_ffmpeg_process(
- args: list[str], timeout: float, is_canceled: Optional[Callable[[], bool]] = None
+ args: list[str],
+ timeout: float,
+ is_canceled: Optional[Callable[[], bool]] = None,
+ *,
+ capture_stdout: bool = False,
) -> subprocess.CompletedProcess[bytes]:
"""Run the bundled ffmpeg (quiet, overwriting) with ``args``; returns its exit status and stderr.
@@ -55,12 +60,23 @@ def run_ffmpeg_process(
(checked before it starts, too) kills and reaps it and raises CanceledException, and
outliving ``timeout`` kills and reaps it and raises ``subprocess.TimeoutExpired``. A
canceled node therefore never waits on a long decode, encode or copy.
+
+ Stdout is discarded unless ``capture_stdout`` is set. Captured output goes to a
+ temporary file so waiting for the child cannot deadlock on a full pipe buffer.
"""
if is_canceled is not None and is_canceled():
raise CanceledException
command = [_ffmpeg_exe(), "-y", "-loglevel", "error", *args]
- with tempfile.TemporaryFile() as stderr:
- proc = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=stderr)
+ with (
+ tempfile.TemporaryFile() as stderr,
+ tempfile.TemporaryFile() if capture_stdout else nullcontext() as stdout,
+ ):
+ proc = subprocess.Popen(
+ command,
+ stdin=subprocess.DEVNULL,
+ stdout=stdout if stdout is not None else subprocess.DEVNULL,
+ stderr=stderr,
+ )
deadline = time.monotonic() + timeout
try:
while True:
@@ -79,7 +95,11 @@ def run_ffmpeg_process(
# Only the tail is ever reported; a decoder logging per packet could write a great deal.
stderr.seek(0, 2)
stderr.seek(max(0, stderr.tell() - _STDERR_TAIL_BYTES))
- return subprocess.CompletedProcess(command, proc.returncode, b"", stderr.read())
+ if stdout is not None:
+ stdout.seek(0)
+ return subprocess.CompletedProcess(
+ command, proc.returncode, stdout.read() if stdout is not None else b"", stderr.read()
+ )
class AudioExtractionError(RuntimeError):
@@ -121,9 +141,9 @@ def extract_audio_pcm(
raise AudioExtractionError(f"ffmpeg timed out extracting audio from {video_path.name}") from e
if proc.returncode != 0:
stderr = proc.stderr.decode("utf-8", errors="replace")
- # ffmpeg's phrasing for an input with no audio track ("Output file #0 does not
- # contain any stream" / newer "does not contain any stream" variants).
- if "does not contain any stream" in stderr:
+ # A PCM output without a stream is an error even with an optional map.
+ # Classify the input structurally, not by FFmpeg's version-dependent prose.
+ if _is_silent_container(video_path, is_canceled=is_canceled):
return None
raise AudioExtractionError(
f"ffmpeg could not extract audio from {video_path.name}: {stderr.strip()[-500:]}"
@@ -147,6 +167,49 @@ def extract_audio_pcm(
out_path.unlink(missing_ok=True)
+def _is_silent_container(video_path: Path, is_canceled: Optional[Callable[[], bool]] = None) -> bool:
+ """Confirm no audio stream with the bundled FFmpeg; unknown/failed probes aren't silence.
+
+ Unlike PCM muxers, ffmetadata can emit a valid header with zero streams. Optional
+ audio mapping emits a [STREAM] section when audio exists, without decoding samples.
+ Suppress non-audio streams and copied metadata so neither automatic selection nor
+ user-supplied tags can masquerade as a stream section. Only failed decodes pay for
+ this extra process; normal extraction and its stream-selection semantics are unchanged.
+ """
+ try:
+ proc = run_ffmpeg_process(
+ [
+ "-i",
+ str(video_path),
+ "-map",
+ "0:a:0?",
+ "-vn",
+ "-sn",
+ "-dn",
+ "-map_metadata",
+ "-1",
+ "-map_chapters",
+ "-1",
+ "-c",
+ "copy",
+ "-t",
+ "0",
+ "-f",
+ "ffmetadata",
+ "pipe:1",
+ ],
+ timeout=60,
+ is_canceled=is_canceled,
+ capture_stdout=True,
+ )
+ except subprocess.TimeoutExpired as e:
+ raise AudioExtractionError(f"ffmpeg timed out probing audio in {video_path.name}") from e
+ except OSError:
+ return False # Preserve the original extraction error if probing cannot start.
+ lines = proc.stdout.splitlines()
+ return proc.returncode == 0 and bool(lines) and lines[0] == b";FFMETADATA1" and b"[STREAM]" not in lines
+
+
def _probe_audio_sample_rate(video_path: Path) -> int | None:
"""The native sample rate of ``video_path``'s FIRST audio stream, or None without one.
diff --git a/tests/app/util/test_video_audio_process.py b/tests/app/util/test_video_audio_process.py
new file mode 100644
index 0000000000..512bc88b25
--- /dev/null
+++ b/tests/app/util/test_video_audio_process.py
@@ -0,0 +1,130 @@
+"""Process contracts exercised with real lightweight Python children, without FFmpeg."""
+
+import subprocess
+import sys
+from pathlib import Path
+from threading import Event
+from types import SimpleNamespace
+
+import pytest
+
+from invokeai.app.util import video_audio
+from invokeai.app.util.process_tree import kill_process_tree
+
+
+def child_process(monkeypatch):
+ children = []
+ launches = []
+ killed = []
+
+ def install(script):
+ def spawn(command, **kwargs):
+ launches.append((command, kwargs))
+ child = subprocess.Popen([sys.executable, "-c", script], **kwargs)
+ children.append(child)
+ return child
+
+ # Replace only this module's binding, never stdlib Popen used by process-tree cleanup.
+ monkeypatch.setattr(video_audio, "subprocess", SimpleNamespace(**{**vars(subprocess), "Popen": spawn}))
+ monkeypatch.setattr(video_audio, "_ffmpeg_exe", lambda: "test-ffmpeg")
+
+ def kill(child):
+ killed.append(child)
+ kill_process_tree(child)
+
+ monkeypatch.setattr(video_audio, "kill_process_tree", kill)
+ yield install, launches, children, killed
+ for child in children:
+ if child.poll() is None:
+ kill_process_tree(child)
+
+
[email protected]("capture", [False, True])
+def test_stdout_capture_and_default_keep_stdin_isolated_and_stderr_bounded(child_process, capture):
+ install, launches, children, killed = child_process
+ install(
+ "import sys\n"
+ "assert sys.stdin.buffer.read() == b''\n"
+ "sys.stdout.buffer.write(b';FFMETADATA1\\n' + b'x' * (2 * 1024 * 1024))\n"
+ "sys.stderr.buffer.write(b'prefix' + b'e' * 8192)\n"
+ "sys.exit(7)\n"
+ )
+ kwargs = {"capture_stdout": True} if capture else {}
+ result = video_audio.run_ffmpeg_process(["-version"], 20, **kwargs)
+ command, options = launches[0]
+ assert command == ["test-ffmpeg", "-y", "-loglevel", "error", "-version"]
+ assert options["stdin"] == subprocess.DEVNULL
+ if capture:
+ assert options["stdout"] != subprocess.PIPE
+ assert options["stdout"].closed
+ else:
+ assert options["stdout"] == subprocess.DEVNULL
+ assert options["stderr"].closed
+ assert result.args == command
+ assert result.returncode == children[0].returncode == 7
+ assert result.stdout == (b";FFMETADATA1\n" + b"x" * (2 * 1024 * 1024) if capture else b"")
+ assert result.stderr == b"e" * 8192
+ assert not killed
+
+
+def test_cancel_between_decode_and_probe_starts_no_probe(child_process, monkeypatch, tmp_path):
+ install, launches, _, _ = child_process
+ install("raise AssertionError('must not launch')")
+ canceled = Event()
+ real_run = video_audio.run_ffmpeg_process
+
+ def run(args, **kwargs):
+ if "ffmetadata" not in args:
+ canceled.set()
+ return subprocess.CompletedProcess(args, 1, b"", b"decode failed")
+ assert kwargs["is_canceled"] == canceled.is_set
+ return real_run(args, **kwargs)
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ monkeypatch.setattr(video_audio.tempfile, "tempdir", str(tmp_path))
+ with pytest.raises(video_audio.CanceledException):
+ video_audio.extract_audio_pcm(Path("silent.mp4"), is_canceled=canceled.is_set)
+ assert not launches
+ assert not list(tmp_path.glob("invokeai_audio_extract_*"))
+
+
[email protected]("stop", ["cancel", "timeout"])
+def test_running_probe_is_killed_reaped_and_output_cleaned(child_process, monkeypatch, tmp_path, stop):
+ install, launches, children, killed = child_process
+ install("from threading import Event; Event().wait()")
+ real_run = video_audio.run_ffmpeg_process
+ started = Event()
+
+ def is_canceled():
+ # The first check occurs before Popen. The next is after its bounded wait.
+ if children:
+ started.set()
+ return stop == "cancel" and started.is_set()
+
+ def run(args, **kwargs):
+ if "ffmetadata" not in args:
+ return subprocess.CompletedProcess(args, 1, b"", b"decode failed")
+ assert kwargs["timeout"] == 60
+ assert kwargs["is_canceled"] is is_canceled
+ assert kwargs["capture_stdout"] is True
+ # Expire on the first poll, without waiting out the production deadline.
+ return real_run(args, **{**kwargs, "timeout": 0 if stop == "timeout" else 20})
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ monkeypatch.setattr(video_audio.tempfile, "tempdir", str(tmp_path))
+ error = video_audio.CanceledException if stop == "cancel" else video_audio.AudioExtractionError
+ with pytest.raises(error) as caught:
+ video_audio.extract_audio_pcm(Path("silent.mp4"), is_canceled=is_canceled)
+ if stop == "timeout":
+ assert "timed out probing audio in silent.mp4" in str(caught.value)
+ assert isinstance(caught.value.__cause__, subprocess.TimeoutExpired)
+ assert started.is_set()
+ assert len(children) == 1
+ assert killed == children
+ assert children[0].returncode is not None
+ assert children[0].wait(timeout=0) == children[0].returncode
+ assert launches[0][1]["stdin"] == subprocess.DEVNULL
+ assert launches[0][1]["stdout"].closed
+ assert launches[0][1]["stderr"].closed
+ assert not list(tmp_path.glob("invokeai_audio_extract_*"))
diff --git a/tests/app/util/test_video_audio_streams.py b/tests/app/util/test_video_audio_streams.py
new file mode 100644
index 0000000000..0c960f2cbc
--- /dev/null
+++ b/tests/app/util/test_video_audio_streams.py
@@ -0,0 +1,528 @@
+"""No-audio detection must use container structure, not FFmpeg's error prose.
+
+Tiny real media fixtures exercise both PCM paths. Error-wording substitution is
+deliberate fault injection, not a claim that the bundled FFmpeg changed wording.
+"""
+
+import subprocess
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from threading import Barrier, Event, Lock
+
+import numpy as np
+import pytest
+
+from invokeai.app.util import video_audio
+
+pytestmark = pytest.mark.ffmpeg
+
+
+def media(tmp_path: Path, monkeypatch):
+ silent = tmp_path / "silent.mp4"
+ audio = tmp_path / "audio.wav"
+ ffmpeg = video_audio._ffmpeg_exe()
+ for args in (
+ ["-f", "lavfi", "-i", "color=size=16x16:rate=1", "-t", "1", "-c:v", "libx264", str(silent)],
+ ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100", "-t", "0.1", str(audio)],
+ ):
+ subprocess.run([ffmpeg, "-y", "-loglevel", "error", *args], check=True, capture_output=True, timeout=20)
+ monkeypatch.setattr(video_audio.tempfile, "tempdir", str(tmp_path))
+ return silent, audio
+
+
[email protected]("float_pcm", [False, True])
[email protected]("stderr", [b"No output audio track", b"Aucune piste audio"])
+def test_silent_clip_does_not_depend_on_error_wording(media, monkeypatch, float_pcm, stderr):
+ silent, _ = media
+ real_run = video_audio.run_ffmpeg_process
+
+ def run(command, **kwargs):
+ proc = real_run(command, **kwargs)
+ if "-acodec" in command:
+ assert proc.returncode != 0 # Real FFmpeg rejects a zero-stream PCM output.
+ return subprocess.CompletedProcess(command, proc.returncode, proc.stdout, stderr)
+ return proc
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ assert video_audio.extract_audio_pcm(silent, float_pcm=float_pcm) is None
+ assert not list(silent.parent.glob("invokeai_audio_extract_*"))
+
+
[email protected]("float_pcm", [False, True])
[email protected]("input_kind", ["corrupt", "missing"])
+def test_invalid_input_is_not_silence_even_if_error_mentions_no_stream(media, monkeypatch, float_pcm, input_kind):
+ silent, _ = media
+ invalid = silent.parent / f"{input_kind}.mp4"
+ if input_kind == "corrupt":
+ invalid.write_bytes(b"not a media container")
+ real_run = video_audio.run_ffmpeg_process
+
+ def run(command, **kwargs):
+ proc = real_run(command, **kwargs)
+ if "-acodec" in command:
+ assert proc.returncode != 0
+ return subprocess.CompletedProcess(command, proc.returncode, proc.stdout, b"does not contain any stream")
+ return proc
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ with pytest.raises(video_audio.AudioExtractionError):
+ video_audio.extract_audio_pcm(invalid, float_pcm=float_pcm)
+ assert not list(silent.parent.glob("invokeai_audio_extract_*"))
+
+
[email protected]("float_pcm", [False, True])
+def test_existing_audio_decode_error_is_not_silence(media, monkeypatch, float_pcm):
+ _, audio = media
+ real_run = video_audio.run_ffmpeg_process
+
+ def run(command, **kwargs):
+ if "-acodec" in command:
+ return subprocess.CompletedProcess(command, 1, b"", b"decoder does not contain any stream")
+ return real_run(command, **kwargs)
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ with pytest.raises(video_audio.AudioExtractionError, match="decoder does not contain any stream"):
+ video_audio.extract_audio_pcm(audio, float_pcm=float_pcm)
+ assert not list(audio.parent.glob("invokeai_audio_extract_*"))
+
+
[email protected]("float_pcm", [False, True])
+def test_unusual_audio_codec_is_not_silence_after_decode_failure(media, monkeypatch, float_pcm):
+ _, audio = media
+ unusual = audio.parent / "alaw.mkv"
+ subprocess.run(
+ [video_audio._ffmpeg_exe(), "-y", "-loglevel", "error", "-i", str(audio), "-c:a", "pcm_alaw", str(unusual)],
+ check=True,
+ capture_output=True,
+ timeout=20,
+ )
+ real_run = video_audio.run_ffmpeg_process
+ probes = []
+
+ def run(command, **kwargs):
+ if "-acodec" in command:
+ return subprocess.CompletedProcess(command, 1, b"", b"injected decoder failure")
+ proc = real_run(command, **kwargs)
+ probes.append(proc)
+ return proc
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ with pytest.raises(video_audio.AudioExtractionError, match="injected decoder failure"):
+ video_audio.extract_audio_pcm(unusual, float_pcm=float_pcm)
+ assert len(probes) == 1
+ assert probes[0].returncode == 0
+ assert b"[STREAM]" in probes[0].stdout.splitlines()
+ assert not list(audio.parent.glob("invokeai_audio_extract_*"))
+
+
[email protected]("float_pcm", [False, True])
+def test_successful_decode_does_not_add_a_structural_probe(media, monkeypatch, float_pcm):
+ _, audio = media
+ real_run = video_audio.run_ffmpeg_process
+ calls = []
+ rate_calls = []
+ real_probe = video_audio._probe_audio_sample_rate
+
+ def probe(path):
+ rate_calls.append(path)
+ return real_probe(path)
+
+ def run(command, **kwargs):
+ calls.append(command)
+ return real_run(command, **kwargs)
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ monkeypatch.setattr(video_audio, "_probe_audio_sample_rate", probe)
+ result = video_audio.extract_audio_pcm(audio, float_pcm=float_pcm)
+ assert result is not None
+ pcm, rate = result
+ assert rate == 44100
+ assert pcm.shape == (2, 4410)
+ assert len(calls) == 1
+ assert rate_calls == ([audio] if float_pcm else []) # Float PCM already probes its rate.
+ assert not any("ffmetadata" in call for call in calls)
+
+
+ "returncode,stdout",
+ [(1, b";FFMETADATA1\n"), (0, b""), (0, b"unexpected output"), (0, b";FFMETADATA2\n")],
+)
+def test_failed_or_unrecognized_probe_preserves_decode_error(media, monkeypatch, returncode, stdout):
+ silent, _ = media
+
+ def run(command, **kwargs):
+ if "ffmetadata" in command:
+ return subprocess.CompletedProcess(command, returncode, stdout, b"probe failed")
+ return subprocess.CompletedProcess(command, 1, b"", b"original decode error")
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ with pytest.raises(video_audio.AudioExtractionError, match="original decode error"):
+ video_audio.extract_audio_pcm(silent)
+ assert not list(silent.parent.glob("invokeai_audio_extract_*"))
+
+
+def test_structural_probe_timeout_is_bounded_and_cleans_output(media, monkeypatch):
+ silent, _ = media
+
+ def run(command, **kwargs):
+ if "ffmetadata" in command:
+ assert kwargs["timeout"] == 60
+ raise subprocess.TimeoutExpired(command, 60)
+ return subprocess.CompletedProcess(command, 1, b"", b"original decode error")
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ with pytest.raises(video_audio.AudioExtractionError, match="timed out probing audio"):
+ video_audio.extract_audio_pcm(silent)
+ assert not list(silent.parent.glob("invokeai_audio_extract_*"))
+
+
+def test_structural_probe_launch_failure_preserves_decode_error(media, monkeypatch):
+ silent, _ = media
+
+ def run(command, **kwargs):
+ if "ffmetadata" in command:
+ raise OSError("probe binary unavailable")
+ return subprocess.CompletedProcess(command, 1, b"", b"original decode error")
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ with pytest.raises(video_audio.AudioExtractionError, match="original decode error"):
+ video_audio.extract_audio_pcm(silent)
+
+
+def test_extraction_timeout_does_not_start_a_probe(media, monkeypatch):
+ silent, _ = media
+
+ def run(command, **kwargs):
+ assert "ffmetadata" not in command
+ raise subprocess.TimeoutExpired(command, kwargs["timeout"])
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ with pytest.raises(video_audio.AudioExtractionError, match="timed out extracting audio"):
+ video_audio.extract_audio_pcm(silent)
+ assert not list(silent.parent.glob("invokeai_audio_extract_*"))
+
+
[email protected]("float_pcm", [False, True])
+def test_damaged_audio_payload_is_not_silence(media, monkeypatch, float_pcm):
+ silent, audio = media
+ damaged = silent.parent / "damaged.m4a"
+ subprocess.run(
+ [video_audio._ffmpeg_exe(), "-y", "-loglevel", "error", "-i", str(audio), "-c:a", "aac", str(damaged)],
+ check=True,
+ capture_output=True,
+ timeout=20,
+ )
+ encoded = damaged.read_bytes()
+ marker = encoded.index(b"mdat")
+ atom_size = int.from_bytes(encoded[marker - 4 : marker], "big")
+ payload_end = marker - 4 + atom_size
+ damaged.write_bytes(encoded[: marker + 4] + bytes(payload_end - marker - 4) + encoded[payload_end:])
+ real_run = video_audio.run_ffmpeg_process
+ results = []
+
+ def run(command, **kwargs):
+ proc = real_run(command, **kwargs)
+ results.append((command, proc))
+ return proc
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ with pytest.raises(video_audio.AudioExtractionError):
+ video_audio.extract_audio_pcm(damaged, float_pcm=float_pcm)
+ assert results[0][1].returncode != 0 # Real AAC decoding, not an injected failure.
+ assert len(results) == 2
+ assert "ffmetadata" in results[1][0]
+ assert results[1][1].returncode == 0
+ assert b"[STREAM]" in results[1][1].stdout.splitlines()
+ assert not list(silent.parent.glob("invokeai_audio_extract_*"))
+
+
+def test_silent_clip_metadata_cannot_spoof_stream_section(media, monkeypatch):
+ silent, _ = media
+ tagged = silent.parent / "tagged.mp4"
+ subprocess.run(
+ [
+ video_audio._ffmpeg_exe(),
+ "-y",
+ "-loglevel",
+ "error",
+ "-i",
+ str(silent),
+ "-c",
+ "copy",
+ "-metadata",
+ "comment=prefix\n[STREAM]",
+ str(tagged),
+ ],
+ check=True,
+ capture_output=True,
+ timeout=20,
+ )
+ # This exact marker really occurs without metadata suppression. A trailing
+ # suffix would escape the newline after it and make this regression vacuous.
+ metadata = subprocess.run(
+ [
+ video_audio._ffmpeg_exe(),
+ "-loglevel",
+ "error",
+ "-i",
+ str(tagged),
+ "-map",
+ "0:a:0?",
+ "-vn",
+ "-sn",
+ "-dn",
+ "-map_metadata",
+ "0",
+ "-map_chapters",
+ "-1",
+ "-c",
+ "copy",
+ "-t",
+ "0",
+ "-f",
+ "ffmetadata",
+ "pipe:1",
+ ],
+ check=True,
+ capture_output=True,
+ timeout=20,
+ )
+ assert b"[STREAM]" in metadata.stdout.splitlines()
+ real_run = video_audio.run_ffmpeg_process
+
+ def run(command, **kwargs):
+ proc = real_run(command, **kwargs)
+ if "-acodec" in command:
+ return subprocess.CompletedProcess(command, proc.returncode, proc.stdout, b"No output audio track")
+ return proc
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ assert video_audio.extract_audio_pcm(tagged) is None
+ assert not list(silent.parent.glob("invokeai_audio_extract_*"))
+
+
[email protected](params=["subtitle_only", "video_subtitle", "video_subtitle_attachment"])
+def non_audio_streams(request, tmp_path: Path, monkeypatch):
+ subtitle = tmp_path / "captions.srt"
+ subtitle.write_text("1\n00:00:00,000 --> 00:00:00,500\nNo audio here\n", encoding="utf-8")
+ output = tmp_path / f"{request.param}.mkv"
+ command = [video_audio._ffmpeg_exe(), "-y", "-loglevel", "error"]
+ if request.param == "subtitle_only":
+ command += ["-i", str(subtitle), "-map", "0:s", "-c:s", "srt"]
+ else:
+ command += [
+ "-f",
+ "lavfi",
+ "-i",
+ "color=size=16x16:rate=2",
+ "-i",
+ str(subtitle),
+ "-map",
+ "0:v",
+ "-map",
+ "1:s",
+ "-t",
+ "1",
+ "-c:v",
+ "libx264",
+ "-c:s",
+ "srt",
+ ]
+ if request.param.endswith("attachment"):
+ attachment = tmp_path / "data.bin"
+ attachment.write_bytes(b"application-owned attachment; not an audio stream")
+ command += ["-attach", str(attachment), "-metadata:s:t:0", "mimetype=application/octet-stream"]
+ subprocess.run([*command, str(output)], check=True, capture_output=True, timeout=30)
+ monkeypatch.setattr(video_audio.tempfile, "tempdir", str(tmp_path))
+ return output
+
+
[email protected]("float_pcm", [False, True])
+def test_subtitles_and_attachments_are_not_audio(non_audio_streams, monkeypatch, float_pcm):
+ real_run = video_audio.run_ffmpeg_process
+ probes = []
+
+ def run(command, **kwargs):
+ proc = real_run(command, **kwargs)
+ if "ffmetadata" in command:
+ probes.append(proc)
+ if "-acodec" in command:
+ assert proc.returncode != 0 # Real decoder failure precedes prose substitution.
+ return subprocess.CompletedProcess(command, proc.returncode, proc.stdout, b"Aucune piste audio")
+ return proc
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ assert video_audio.extract_audio_pcm(non_audio_streams, float_pcm=float_pcm) is None
+ assert len(probes) == 1
+ assert probes[0].returncode == 0
+ assert b"[STREAM]" not in probes[0].stdout.splitlines()
+ assert not list(non_audio_streams.parent.glob("invokeai_audio_extract_*"))
+
+
+def test_stream_marker_alone_does_not_identify_audio(non_audio_streams):
+ # Real subtitle selection emits the same marker. Audio-only selection is
+ # therefore part of the classifier's contract, not merely an optimization.
+ command = [
+ video_audio._ffmpeg_exe(),
+ "-loglevel",
+ "error",
+ "-i",
+ str(non_audio_streams),
+ "-map",
+ "0:s:0?",
+ "-vn",
+ "-dn",
+ "-map_metadata",
+ "-1",
+ "-map_chapters",
+ "-1",
+ "-c",
+ "copy",
+ "-t",
+ "0",
+ "-f",
+ "ffmetadata",
+ "pipe:1",
+ ]
+ subtitles = subprocess.run(command, check=True, capture_output=True, timeout=30)
+ audio_only = subprocess.run(
+ ["0:a:0?" if argument == "0:s:0?" else argument for argument in command],
+ check=True,
+ capture_output=True,
+ timeout=30,
+ )
+ assert b"[STREAM]" in subtitles.stdout.splitlines()
+ assert b"[STREAM]" not in audio_only.stdout.splitlines()
+
+
[email protected]("float_pcm", [False, True])
+def test_failed_extractions_do_not_remove_concurrent_audio_outputs(media, monkeypatch, float_pcm):
+ silent, first = media
+ second = silent.parent / "second.wav"
+ corrupt = silent.parent / "corrupt.mp4"
+ missing = silent.parent / "missing.mp4"
+ corrupt.write_bytes(b"not a media container")
+ real_ffmpeg_run = subprocess.run
+ ffmpeg = video_audio._ffmpeg_exe()
+ real_ffmpeg_run(
+ [
+ ffmpeg,
+ "-y",
+ "-loglevel",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "sine=frequency=880:sample_rate=48000",
+ "-t",
+ "0.1",
+ str(second),
+ ],
+ check=True,
+ capture_output=True,
+ timeout=20,
+ )
+ successful = {first, second}
+ unsuccessful = {silent, corrupt, missing}
+ expected = {}
+ for path in successful:
+ # Decode a separate raw reference, not through the helper under test.
+ codec, format_name, dtype = (
+ ("pcm_f32le", "f32le", np.float32) if float_pcm else ("pcm_s16le", "s16le", np.int16)
+ )
+ reference = real_ffmpeg_run(
+ [
+ ffmpeg,
+ "-loglevel",
+ "error",
+ "-i",
+ str(path),
+ "-map",
+ "0:a:0",
+ "-ac",
+ "2",
+ "-acodec",
+ codec,
+ "-f",
+ format_name,
+ "pipe:1",
+ ],
+ check=True,
+ capture_output=True,
+ timeout=20,
+ )
+ samples = np.frombuffer(reference.stdout, dtype=dtype).reshape(-1, 2).T
+ expected[path] = samples if float_pcm else samples.astype(np.float32) / 32768.0
+
+ # All five calls allocate their outputs before any decoder can complete.
+ # Both successful decoders finish writing before failed decodes can return.
+ # Successes then retain their output until every failed call has returned
+ # through finally. This exercises cleanup, without sleeps or racing
+ # the host scheduler, while real FFmpeg does the decoding and probing.
+ allocated = Barrier(5, timeout=40)
+ written = {path: Event() for path in successful}
+ cleaned = {path: Event() for path in unsuccessful}
+ lock = Lock()
+ outputs = {}
+ errors = {}
+ probes = []
+
+ real_run = video_audio.run_ffmpeg_process
+
+ def run(command, **kwargs):
+ if "-i" not in command:
+ return real_run(command, **kwargs)
+ path = Path(command[command.index("-i") + 1])
+ is_decode = "-acodec" in command
+ if is_decode:
+ with lock:
+ outputs[path] = Path(command[-1])
+ allocated.wait()
+ proc = real_run(command, **kwargs)
+ if is_decode and path in successful:
+ assert proc.returncode == 0
+ written[path].set()
+ for event in cleaned.values():
+ assert event.wait(40), "A failed extraction did not finish cleanup"
+ assert outputs[path].is_file(), "Another extraction removed this call's PCM"
+ elif is_decode:
+ assert proc.returncode != 0 # Genuine invalid/no-audio inputs.
+ for event in written.values():
+ assert event.wait(40), "A successful decoder did not finish writing"
+ with lock:
+ errors[path] = proc.stderr.decode("utf-8", errors="replace").strip()[-500:]
+ elif "ffmetadata" in command:
+ with lock:
+ probes.append(path)
+ return proc
+
+ def extract(path):
+ try:
+ try:
+ return video_audio.extract_audio_pcm(path, float_pcm=float_pcm)
+ except video_audio.AudioExtractionError as error:
+ return error
+ finally:
+ if path in cleaned:
+ cleaned[path].set()
+
+ monkeypatch.setattr(video_audio, "run_ffmpeg_process", run)
+ inputs = [first, second, silent, corrupt, missing]
+ with ThreadPoolExecutor(max_workers=5) as pool:
+ results = dict(zip(inputs, pool.map(extract, inputs), strict=True))
+ assert len(outputs) == len(set(outputs.values())) == 5
+ for path, rate in ((first, 44100), (second, 48000)):
+ result = results[path]
+ assert isinstance(result, tuple)
+ pcm, actual_rate = result
+ assert actual_rate == rate
+ assert pcm.shape == (2, rate // 10)
+ assert np.array_equal(pcm, expected[path])
+ assert results[silent] is None
+ for path in (corrupt, missing):
+ assert isinstance(results[path], video_audio.AudioExtractionError)
+ assert errors[path]
+ assert errors[path] in str(results[path])
+ assert set(probes).issubset(unsuccessful)
+ assert not list(silent.parent.glob("invokeai_audio_extract_*"))