cmvr-visual/backend/tests/test_native_av_media.py

429 lines
15 KiB
Python

"""使用本地合成媒体验证音轨偏移和双声道,不启动模型。"""
import os
import shutil
import struct
import subprocess
import wave
from pathlib import Path
from types import SimpleNamespace
import pytest
from app.adapters.provider.dialogue_media import run_cpu
from app.domain.errors import MediaError
def test_native_sidecar_requires_policy_and_is_a_protected_job_input():
from app.adapters.provider.dialogue_media import validate_cpu
from app.services.jobs import input_ids
inputs = {"video_asset_id": "a" * 32, "audio_asset_id": "b" * 32}
p = {"start_frame": 0, "duration_frames": 124, "audio_policy": "native_av_v1"}
validate_cpu("audio.dialogue.extract", inputs, p)
assert set(input_ids(inputs, p)) == {"a" * 32, "b" * 32}
for task, params in (
("video.dialogue.select", p),
("audio.dialogue.extract", {"start_frame": 0, "duration_frames": 124}),
):
with pytest.raises(MediaError):
validate_cpu(task, inputs, params)
@pytest.mark.skipif(
not (shutil.which("ffmpeg") or os.environ.get("FFMPEG_BIN")), reason="ffmpeg unavailable"
)
async def test_native_sidecar_preserves_pcm_tail_without_aac_offset_or_padding(tmp_path):
ffmpeg = os.environ.get("FFMPEG_BIN") or shutil.which("ffmpeg")
ffprobe = (
os.environ.get("FFPROBE_BIN")
or shutil.which("ffprobe")
or str(Path(ffmpeg).with_name("ffprobe.exe"))
)
video, sidecar = tmp_path / "aac.mp4", tmp_path / "native.wav"
# 画内 AAC 故意有另一段时序;侧车必须来自明确的素材引用,不能误用 AAC。
subprocess.run(
[
ffmpeg,
"-v",
"error",
"-y",
"-f",
"lavfi",
"-i",
"testsrc2=size=64x64:rate=24:duration=1",
"-itsoffset",
"0.25",
"-f",
"lavfi",
"-i",
"sine=frequency=440:sample_rate=32000:duration=1",
"-c:v",
"libx264",
"-c:a",
"aac",
str(video),
],
check=True,
)
with wave.open(str(sidecar), "wb") as pcm:
pcm.setparams((2, 2, 32000, 0, "NONE", "not compressed"))
pcm.writeframes(struct.pack("<hh", 8192, 16384) * 32400)
provider = SimpleNamespace(
settings=SimpleNamespace(
ffmpeg_bin=ffmpeg, ffprobe_bin=ffprobe, workspace_root=tmp_path, max_output_bytes=10**8
),
_asset=lambda aid, assets: assets[aid],
)
result = await run_cpu(
provider,
"audio.dialogue.extract",
{"video_asset_id": "a" * 32, "audio_asset_id": "b" * 32},
{"start_frame": 0, "duration_frames": 24, "audio_policy": "native_av_v1"},
{"a" * 32: video, "b" * 32: sidecar},
tmp_path,
)
assert result.result["sample_count"] == 48600
assert result.result["audio_offset_samples"] == 0
assert result.result["source_audio_offset_samples"] == 0
assert result.result["source_audio_asset_id"] == "b" * 32
with wave.open(str(result.outputs[0]), "rb") as pcm:
assert (pcm.getnchannels(), pcm.getframerate(), pcm.getnframes()) == (2, 48000, 48600)
values = struct.unpack("<" + "h" * 97200, pcm.readframes(48600))
assert min(values[2000:90000:2]) > 8000
assert min(values[2001:90000:2]) > 16000
@pytest.mark.skipif(
not (shutil.which("ffmpeg") or os.environ.get("FFMPEG_BIN")), reason="ffmpeg unavailable"
)
async def test_native_sidecar_submission_checks_owner_and_protects_both_sources(
system, other_client, tmp_path
):
import io
from datetime import datetime, timedelta, timezone
from sqlalchemy import select
from app.models import JobAsset
ffmpeg = os.environ.get("FFMPEG_BIN") or shutil.which("ffmpeg")
ffprobe = (
os.environ.get("FFPROBE_BIN")
or shutil.which("ffprobe")
or str(Path(ffmpeg).with_name("ffprobe.exe"))
)
system.settings.ffmpeg_bin, system.settings.ffprobe_bin = ffmpeg, ffprobe
video = tmp_path / "upload.mp4"
subprocess.run(
[
ffmpeg,
"-v",
"error",
"-y",
"-f",
"lavfi",
"-i",
"testsrc2=size=64x64:rate=24:duration=1",
"-an",
str(video),
],
check=True,
)
pcm = io.BytesIO()
with wave.open(pcm, "wb") as audio:
audio.setparams((2, 2, 32000, 0, "NONE", "not compressed"))
audio.writeframes(struct.pack("<hh", 8192, 16384) * 32400)
uploaded = await system.client.post(
"/api/assets", files={"file": ("video.mp4", video.read_bytes(), "video/mp4")}
)
assert uploaded.status_code == 201, uploaded.text
video_id = uploaded.json()["id"]
foreign = await other_client.post(
"/api/assets", files={"file": ("foreign.wav", pcm.getvalue(), "audio/wav")}
)
assert foreign.status_code == 201, foreign.text
body = dict(
task_type="audio.dialogue.extract",
input=dict(video_asset_id=video_id, audio_asset_id=foreign.json()["id"]),
parameters=dict(start_frame=0, duration_frames=24, audio_policy="native_av_v1"),
scheduled_at=(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
)
denied = await system.client.post("/api/jobs", json=body)
assert denied.status_code == 404, denied.text
owned = await system.client.post(
"/api/assets", files={"file": ("native.wav", pcm.getvalue(), "audio/wav")}
)
assert owned.status_code == 201, owned.text
audio_id = owned.json()["id"]
body["input"]["audio_asset_id"] = audio_id
accepted = await system.client.post("/api/jobs", json=body)
assert accepted.status_code == 202, accepted.text
job_id = accepted.json()["jobs"][0]["id"]
async with system.app.state.db.session() as session:
refs = (await session.scalars(select(JobAsset).where(JobAsset.job_id == job_id))).all()
assert {ref.asset_id for ref in refs} == {video_id, audio_id}
for asset_id in (video_id, audio_id):
assert (await system.client.delete(f"/api/assets/{asset_id}")).status_code == 409
def test_alignment_uses_true_words_and_rejects_chunk_only_reports():
from app.domain.native_av import align_native_utterances
report = dict(
sample_rate=48000,
timestamp_source="whisper-word-timestamps",
timestamp_origin="audio_asset",
words=[
dict(text="你好", start_sample=4800, end_sample=14400),
dict(text="。", start_sample=14400, end_sample=14400),
dict(text="再见", start_sample=24000, end_sample=33600),
],
)
lines = [dict(id="a" * 32, text="你好!"), dict(id="b" * 32, text="再见。")]
aligned = align_native_utterances(report, lines, audio_offset_samples=2400)
assert [(r["utterance_id"], r["start_sample"], r["end_sample"]) for r in aligned] == [
("a" * 32, 7200, 16800),
("b" * 32, 26400, 36000),
]
for broken in (
{**report, "words": [], "segments": [dict(text="你好。再见", start=0, end=1)]},
{**report, "timestamp_source": "uniform-chunk-split"},
{**report, "words": [dict(text="你好再见", start_sample=4800, end_sample=33600)]},
{
**report,
"words": [
dict(text="你好", start_sample=4800, end_sample=14400),
dict(text="再见", start_sample=12000, end_sample=33000),
],
},
):
with pytest.raises(ValueError):
align_native_utterances(broken, lines)
@pytest.mark.skipif(
not (shutil.which("ffmpeg") or os.environ.get("FFMPEG_BIN")), reason="ffmpeg unavailable"
)
async def test_native_extract_keeps_audio_onset_channels_and_real_sample_count(tmp_path):
ffmpeg = os.environ.get("FFMPEG_BIN") or shutil.which("ffmpeg")
ffprobe = (
os.environ.get("FFPROBE_BIN")
or shutil.which("ffprobe")
or str(Path(ffmpeg).with_name("ffprobe.exe"))
)
source = tmp_path / "late-audio.mkv"
subprocess.run(
[
ffmpeg,
"-v",
"error",
"-y",
"-f",
"lavfi",
"-i",
"testsrc2=size=64x64:rate=24:duration=2",
"-itsoffset",
"0.25",
"-f",
"lavfi",
"-i",
"aevalsrc=0.25|0.5:s=32000:d=1.5",
"-c:v",
"libx264",
"-c:a",
"pcm_s16le",
str(source),
],
check=True,
)
settings = SimpleNamespace(
ffmpeg_bin=ffmpeg, ffprobe_bin=ffprobe, workspace_root=tmp_path, max_output_bytes=10**8
)
provider = SimpleNamespace(settings=settings, _asset=lambda aid, assets: assets[aid])
result = await run_cpu(
provider,
"audio.dialogue.extract",
{"video_asset_id": "a" * 32},
{"start_frame": 0, "duration_frames": 48, "audio_policy": "native_av_v1"},
{"a" * 32: source},
tmp_path,
)
assert result.result["sample_rate"] == 48000
assert result.result["sample_count"] == 72000
assert result.result["channels"] == 2
assert result.result["audio_offset_samples"] == 12000
with wave.open(str(result.outputs[0]), "rb") as audio:
assert (audio.getnchannels(), audio.getnframes()) == (2, 72000)
left, right = struct.unpack("<hh", audio.readframes(1))
assert 7000 < left < 9000 and 15000 < right < 18000
@pytest.mark.skipif(
not (shutil.which("ffmpeg") or os.environ.get("FFMPEG_BIN")), reason="ffmpeg unavailable"
)
async def test_native_extract_rejects_silent_video(tmp_path):
ffmpeg = os.environ.get("FFMPEG_BIN") or shutil.which("ffmpeg")
ffprobe = (
os.environ.get("FFPROBE_BIN")
or shutil.which("ffprobe")
or str(Path(ffmpeg).with_name("ffprobe.exe"))
)
source = tmp_path / "silent.mp4"
subprocess.run(
[
ffmpeg,
"-v",
"error",
"-y",
"-f",
"lavfi",
"-i",
"testsrc2=size=64x64:rate=24:duration=1",
"-an",
str(source),
],
check=True,
)
provider = SimpleNamespace(
settings=SimpleNamespace(
ffmpeg_bin=ffmpeg, ffprobe_bin=ffprobe, workspace_root=tmp_path, max_output_bytes=10**8
),
_asset=lambda aid, assets: assets[aid],
)
with pytest.raises(MediaError) as exc:
await run_cpu(
provider,
"audio.dialogue.extract",
{"video_asset_id": "a" * 32},
{"start_frame": 0, "duration_frames": 24, "audio_policy": "native_av_v1"},
{"a" * 32: source},
tmp_path,
)
assert exc.value.code == "missing_native_audio"
@pytest.mark.skipif(
not (shutil.which("ffmpeg") or os.environ.get("FFMPEG_BIN")), reason="ffmpeg unavailable"
)
async def test_native_full_selection_keeps_official_audio_tail(tmp_path):
ffmpeg = os.environ.get("FFMPEG_BIN") or shutil.which("ffmpeg")
ffprobe = (
os.environ.get("FFPROBE_BIN")
or shutil.which("ffprobe")
or str(Path(ffmpeg).with_name("ffprobe.exe"))
)
source = tmp_path / "native-tail.mkv"
subprocess.run(
[
ffmpeg,
"-v",
"error",
"-y",
"-f",
"lavfi",
"-i",
"testsrc2=size=64x64:rate=24:duration=1",
"-f",
"lavfi",
"-i",
"aevalsrc=0.25|0.5:s=32000:d=1.0125",
"-c:v",
"libx264",
"-c:a",
"pcm_s16le",
str(source),
],
check=True,
)
provider = SimpleNamespace(
settings=SimpleNamespace(
ffmpeg_bin=ffmpeg, ffprobe_bin=ffprobe, workspace_root=tmp_path, max_output_bytes=10**8
),
_asset=lambda aid, assets: assets[aid],
)
result = await run_cpu(
provider,
"audio.dialogue.extract",
{"video_asset_id": "a" * 32},
{"start_frame": 0, "duration_frames": 24, "audio_policy": "native_av_v1"},
{"a" * 32: source},
tmp_path,
)
assert result.result["sample_count"] == 48600
selected = await run_cpu(
provider,
"video.dialogue.select",
{"video_asset_id": "a" * 32},
{"start_frame": 0, "duration_frames": 24, "audio_policy": "native_av_v1"},
{"a" * 32: source},
tmp_path,
)
assert selected.outputs[0].read_bytes() == source.read_bytes()
@pytest.mark.skipif(
not (shutil.which("ffmpeg") or os.environ.get("FFMPEG_BIN")), reason="ffmpeg unavailable"
)
async def test_native_partial_selection_keeps_stereo_audio_at_selected_video_time(tmp_path):
from app.adapters.media import inspect_video_track
ffmpeg = os.environ.get("FFMPEG_BIN") or shutil.which("ffmpeg")
ffprobe = (
os.environ.get("FFPROBE_BIN")
or shutil.which("ffprobe")
or str(Path(ffmpeg).with_name("ffprobe.exe"))
)
source = tmp_path / "onset.mkv"
subprocess.run(
[
ffmpeg,
"-v",
"error",
"-y",
"-f",
"lavfi",
"-i",
"testsrc2=size=64x64:rate=24:duration=2",
"-f",
"lavfi",
"-i",
"aevalsrc=0.25*between(t\\,1\\,1.25)|0.5*between(t\\,1\\,1.25):s=32000:d=2",
"-c:v",
"libx264",
"-c:a",
"pcm_s16le",
str(source),
],
check=True,
)
settings = SimpleNamespace(
ffmpeg_bin=ffmpeg, ffprobe_bin=ffprobe, workspace_root=tmp_path, max_output_bytes=10**8
)
provider = SimpleNamespace(settings=settings, _asset=lambda aid, assets: assets[aid])
selected = await run_cpu(
provider,
"video.dialogue.select",
{"video_asset_id": "a" * 32},
{"start_frame": 12, "duration_frames": 24, "audio_policy": "native_av_v1"},
{"a" * 32: source},
tmp_path,
)
track = await inspect_video_track(selected.outputs[0], settings)
assert (track["frames"], track["fps"]) == (24, 24)
extracted = await run_cpu(
provider,
"audio.dialogue.extract",
{"video_asset_id": "a" * 32},
{"start_frame": 0, "duration_frames": 24, "audio_policy": "native_av_v1"},
{"a" * 32: selected.outputs[0]},
tmp_path,
)
with wave.open(str(extracted.outputs[0]), "rb") as audio:
assert audio.getnchannels() == 2
values = struct.unpack(
"<" + "h" * (audio.getnframes() * 2), audio.readframes(audio.getnframes())
)
left, right = values[::2], values[1::2]
assert max(abs(v) for v in left[:22000]) < 20
assert min(left[25000:34000]) > 6000
assert min(right[25000:34000]) > 12000