384 lines
12 KiB
Python
384 lines
12 KiB
Python
|
|
"""V2音频用真实样本与有界FFmpeg验证,避免逐段帧舍入漂移。"""
|
|||
|
|
|
|||
|
|
from copy import deepcopy
|
|||
|
|
import shutil
|
|||
|
|
import struct
|
|||
|
|
import wave
|
|||
|
|
from pathlib import Path
|
|||
|
|
from types import SimpleNamespace
|
|||
|
|
|
|||
|
|
import pytest
|
|||
|
|
from pydantic import ValidationError
|
|||
|
|
|
|||
|
|
from app.schemas.editor_audio import AudioSegmentV2, AudioSelectionV2, EditorAudioV2
|
|||
|
|
from app.domain.audio_timeline import compile_audio_timeline, audio_sample_ranges
|
|||
|
|
from app.adapters.provider.audio_timeline import normalize, mix
|
|||
|
|
|
|||
|
|
|
|||
|
|
A, B, C, D, SCENE = [c * 32 for c in "abcde"]
|
|||
|
|
|
|||
|
|
|
|||
|
|
def manifest():
|
|||
|
|
return {
|
|||
|
|
"schema_version": 2,
|
|||
|
|
"shot_ids": [A, B],
|
|||
|
|
"spec": {
|
|||
|
|
"schema_version": 4,
|
|||
|
|
"scenes": [{"id": SCENE}],
|
|||
|
|
"shots": [
|
|||
|
|
{
|
|||
|
|
"id": A,
|
|||
|
|
"scene_id": SCENE,
|
|||
|
|
"continuity": {"group_id": "g"},
|
|||
|
|
"edit": {"start_frame": 0, "duration_frames": 124, "dedup_frames": 0},
|
|||
|
|
},
|
|||
|
|
{
|
|||
|
|
"id": B,
|
|||
|
|
"scene_id": SCENE,
|
|||
|
|
"continuity": {"transition": "continue", "group_id": "g"},
|
|||
|
|
"edit": {"start_frame": 0, "duration_frames": 124, "dedup_frames": 1},
|
|||
|
|
},
|
|||
|
|
],
|
|||
|
|
},
|
|||
|
|
"audio": {
|
|||
|
|
"mode": "generated_narration",
|
|||
|
|
"segments": [
|
|||
|
|
{"id": C, "shot_id": A, "anchor": "shot", "text": "第一句"},
|
|||
|
|
{
|
|||
|
|
"id": D,
|
|||
|
|
"anchor": "scene",
|
|||
|
|
"scene_id": SCENE,
|
|||
|
|
"offset_sample": 247001,
|
|||
|
|
"text": "跨切镜旁白",
|
|||
|
|
},
|
|||
|
|
],
|
|||
|
|
"layers": [],
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def bindings():
|
|||
|
|
return {
|
|||
|
|
"audio:" + C: {"asset_id": "speech1", "sample_count": 247001, "sample_rate": 48000},
|
|||
|
|
"audio:" + D: {"asset_id": "speech2", "sample_count": 2001, "sample_rate": 48000},
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def test_v2_audio_anchor_and_integer_source_contract():
|
|||
|
|
value = AudioSegmentV2.model_validate(
|
|||
|
|
{"id": C, "anchor": "scene", "scene_id": SCENE, "text": "旁白"}
|
|||
|
|
)
|
|||
|
|
assert value.shot_id is None
|
|||
|
|
assert (
|
|||
|
|
EditorAudioV2.model_validate({"segments": [value.model_dump()]}).segments[0].anchor
|
|||
|
|
== "scene"
|
|||
|
|
)
|
|||
|
|
with pytest.raises(ValidationError):
|
|||
|
|
AudioSegmentV2.model_validate({"id": C, "anchor": "scene", "shot_id": A, "text": "错误"})
|
|||
|
|
with pytest.raises(ValidationError):
|
|||
|
|
AudioSelectionV2(asset_id="a", source_start_sample=10, source_end_sample=10)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def test_scene_narration_crosses_cut_with_no_per_segment_rounding():
|
|||
|
|
m = manifest()
|
|||
|
|
original = deepcopy(m)
|
|||
|
|
plan = compile_audio_timeline(m, bindings())
|
|||
|
|
assert m == original
|
|||
|
|
assert plan["total_frames"] == 247
|
|||
|
|
assert plan["total_samples"] == 494000
|
|||
|
|
assert [s["offset_sample"] for s in plan["segments"]] == [0, 247001]
|
|||
|
|
assert audio_sample_ranges(m, bindings())[D] == (247001, 249002)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def test_audio_requires_measured_normalized_samples_and_bounds():
|
|||
|
|
b = bindings()
|
|||
|
|
b["audio:" + C].pop("sample_count")
|
|||
|
|
with pytest.raises(ValueError, match="样本|归一化"):
|
|||
|
|
compile_audio_timeline(manifest(), b)
|
|||
|
|
b = bindings()
|
|||
|
|
b["audio:" + C]["sample_count"] = 249000
|
|||
|
|
with pytest.raises(ValueError, match="超出"):
|
|||
|
|
compile_audio_timeline(manifest(), b)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def test_bgm_overlap_is_supported_and_bad_clip_is_not_silently_truncated():
|
|||
|
|
m = manifest()
|
|||
|
|
m["audio"]["layers"] = [
|
|||
|
|
{
|
|||
|
|
"id": "f" * 32,
|
|||
|
|
"role": "bgm",
|
|||
|
|
"asset_id": "music",
|
|||
|
|
"anchor": "absolute",
|
|||
|
|
"source_start_sample": 3,
|
|||
|
|
"source_end_sample": 490003,
|
|||
|
|
"offset_sample": 0,
|
|||
|
|
"gain_db": -12.0,
|
|||
|
|
"fade_in_samples": 1200,
|
|||
|
|
"fade_out_samples": 2400,
|
|||
|
|
}
|
|||
|
|
]
|
|||
|
|
plan = compile_audio_timeline(m, bindings(), source_samples={"music": 500000})
|
|||
|
|
assert len(plan["segments"]) == 3
|
|||
|
|
assert plan["segments"][-1]["source_start_sample"] == 3
|
|||
|
|
m["audio"]["layers"][0]["source_end_sample"] = 500001
|
|||
|
|
with pytest.raises(ValueError, match="超出"):
|
|||
|
|
compile_audio_timeline(m, bindings(), source_samples={"music": 500000})
|
|||
|
|
|
|||
|
|
|
|||
|
|
def test_caption_quantization_uses_global_samples_once_and_preserves_overrides():
|
|||
|
|
from app.services.editor_media import compile_captions
|
|||
|
|
|
|||
|
|
m = manifest()
|
|||
|
|
m["captions"] = {"mode": "script", "cues": []}
|
|||
|
|
assert compile_captions(m, bindings()) == [
|
|||
|
|
{"start_frame": 0, "end_frame": 124, "text": "第一句"},
|
|||
|
|
{"start_frame": 124, "end_frame": 125, "text": "跨切镜旁白"},
|
|||
|
|
]
|
|||
|
|
m["captions"]["cues"] = [
|
|||
|
|
{
|
|||
|
|
"id": D,
|
|||
|
|
"anchor": "audio_segment",
|
|||
|
|
"segment_id": D,
|
|||
|
|
"text": "人工字幕",
|
|||
|
|
"start_frame": 0,
|
|||
|
|
"end_frame": 1,
|
|||
|
|
"text_override": True,
|
|||
|
|
"timing_override": True,
|
|||
|
|
}
|
|||
|
|
]
|
|||
|
|
assert compile_captions(m, bindings())[-1] == {
|
|||
|
|
"start_frame": 124,
|
|||
|
|
"end_frame": 125,
|
|||
|
|
"text": "人工字幕",
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def test_sample_audio_render_selection_is_accepted_by_v4_only():
|
|||
|
|
from app.domain.stories import parse_story_spec, StorySpecV3
|
|||
|
|
|
|||
|
|
raw = {
|
|||
|
|
"schema_version": 4,
|
|||
|
|
"shots": [{"id": A, "visual_prompt": "海边", "edit": {"duration_frames": 25}}],
|
|||
|
|
"render": {
|
|||
|
|
"audio": {
|
|||
|
|
"asset_id": "mix",
|
|||
|
|
"source_start_sample": 0,
|
|||
|
|
"source_end_sample": 50000,
|
|||
|
|
"offset_sample": 0,
|
|||
|
|
"sample_rate": 48000,
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
assert parse_story_spec(raw).render.audio.source_end_sample == 50000
|
|||
|
|
with pytest.raises(ValidationError):
|
|||
|
|
StorySpecV3.model_validate({**raw, "schema_version": 3})
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.parametrize("anchor", ["scene", "absolute"])
|
|||
|
|
def test_editor_issues_accept_caption_anchor_on_cross_shot_narration(anchor):
|
|||
|
|
from app.domain.editors import editor_issues
|
|||
|
|
|
|||
|
|
m = manifest()
|
|||
|
|
m["audio"]["mode"] = "silent"
|
|||
|
|
m["audio"]["segments"][1].update(anchor=anchor)
|
|||
|
|
if anchor == "absolute":
|
|||
|
|
m["audio"]["segments"][1].pop("scene_id")
|
|||
|
|
m["captions"] = {
|
|||
|
|
"mode": "script",
|
|||
|
|
"cues": [
|
|||
|
|
{
|
|||
|
|
"id": D,
|
|||
|
|
"anchor": "audio_segment",
|
|||
|
|
"segment_id": D,
|
|||
|
|
"start_frame": 0,
|
|||
|
|
"end_frame": 24,
|
|||
|
|
"text": "人工保留字幕",
|
|||
|
|
"timing_override": True,
|
|||
|
|
"text_override": True,
|
|||
|
|
}
|
|||
|
|
],
|
|||
|
|
}
|
|||
|
|
assert editor_issues(m) == []
|
|||
|
|
|
|||
|
|
|
|||
|
|
def write_wav(path, frames, value=3000, rate=48000):
|
|||
|
|
with wave.open(str(path), "wb") as stream:
|
|||
|
|
stream.setparams((2, 2, rate, 0, "NONE", "not compressed"))
|
|||
|
|
stream.writeframes(struct.pack("<hh", value, value) * frames)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.fixture
|
|||
|
|
def provider(tmp_path):
|
|||
|
|
def asset(aid, assets):
|
|||
|
|
path = Path(assets[aid]).resolve()
|
|||
|
|
assert path.is_relative_to(tmp_path)
|
|||
|
|
return path
|
|||
|
|
|
|||
|
|
def json_file(work, name, value):
|
|||
|
|
import json
|
|||
|
|
|
|||
|
|
path = work / name
|
|||
|
|
path.write_text(json.dumps(value), encoding="utf-8")
|
|||
|
|
return path
|
|||
|
|
|
|||
|
|
return SimpleNamespace(
|
|||
|
|
settings=SimpleNamespace(ffmpeg_bin=shutil.which("ffmpeg"), max_output_bytes=2**24),
|
|||
|
|
_asset=asset,
|
|||
|
|
_json_file=json_file,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.skipif(not shutil.which("ffmpeg"), reason="FFmpeg required")
|
|||
|
|
async def test_mix_real_samples_preserves_non_millisecond_endpoint(provider, tmp_path):
|
|||
|
|
source = tmp_path / "source.wav"
|
|||
|
|
write_wav(source, 50000)
|
|||
|
|
work = tmp_path / "mix"
|
|||
|
|
work.mkdir()
|
|||
|
|
inputs = {
|
|||
|
|
"total_frames": 25,
|
|||
|
|
"segments": [
|
|||
|
|
{
|
|||
|
|
"asset_id": "a",
|
|||
|
|
"source_start_sample": 0,
|
|||
|
|
"source_end_sample": 50000,
|
|||
|
|
"offset_sample": 0,
|
|||
|
|
"gain_db": 0.0,
|
|||
|
|
"fade_in_samples": 0,
|
|||
|
|
"fade_out_samples": 0,
|
|||
|
|
"role": "narration",
|
|||
|
|
"segment_id": C,
|
|||
|
|
}
|
|||
|
|
],
|
|||
|
|
}
|
|||
|
|
result = await mix(provider, inputs, {}, {"a": source}, work)
|
|||
|
|
assert result.result["sample_count"] == 50000
|
|||
|
|
with wave.open(str(result.outputs[0]), "rb") as audio:
|
|||
|
|
assert audio.getnframes() == 50000
|
|||
|
|
audio.setpos(49999)
|
|||
|
|
assert struct.unpack("<hh", audio.readframes(1)) == (3000, 3000)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.skipif(not shutil.which("ffmpeg"), reason="FFmpeg required")
|
|||
|
|
async def test_mix_overlaps_layers_with_gain_and_fades(provider, tmp_path):
|
|||
|
|
source = tmp_path / "tone.wav"
|
|||
|
|
write_wav(source, 48000, value=2000)
|
|||
|
|
work = tmp_path / "mixed"
|
|||
|
|
work.mkdir()
|
|||
|
|
segment = {
|
|||
|
|
"asset_id": "a",
|
|||
|
|
"source_start_sample": 0,
|
|||
|
|
"source_end_sample": 48000,
|
|||
|
|
"offset_sample": 0,
|
|||
|
|
"gain_db": 0.0,
|
|||
|
|
"fade_in_samples": 0,
|
|||
|
|
"fade_out_samples": 0,
|
|||
|
|
"role": "narration",
|
|||
|
|
"segment_id": C,
|
|||
|
|
}
|
|||
|
|
result = await mix(
|
|||
|
|
provider,
|
|||
|
|
{
|
|||
|
|
"total_frames": 24,
|
|||
|
|
"segments": [
|
|||
|
|
segment,
|
|||
|
|
{
|
|||
|
|
**segment,
|
|||
|
|
"role": "bgm",
|
|||
|
|
"segment_id": D,
|
|||
|
|
"gain_db": -6.020599913,
|
|||
|
|
"fade_in_samples": 2400,
|
|||
|
|
},
|
|||
|
|
],
|
|||
|
|
},
|
|||
|
|
{},
|
|||
|
|
{"a": source},
|
|||
|
|
work,
|
|||
|
|
)
|
|||
|
|
with wave.open(str(result.outputs[0]), "rb") as audio:
|
|||
|
|
audio.setpos(10000)
|
|||
|
|
values = struct.unpack("<hh", audio.readframes(1))
|
|||
|
|
assert all(abs(v - 3000) <= 2 for v in values)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.skipif(not shutil.which("ffmpeg"), reason="FFmpeg required")
|
|||
|
|
async def test_normalize_reports_actual_decoded_sample_count(provider, tmp_path):
|
|||
|
|
source = tmp_path / "22k.wav"
|
|||
|
|
write_wav(source, 11027, rate=22050)
|
|||
|
|
work = tmp_path / "normalized"
|
|||
|
|
work.mkdir()
|
|||
|
|
result = await normalize(provider, {"asset_id": "a"}, {}, {"a": source}, work)
|
|||
|
|
with wave.open(str(result.outputs[0]), "rb") as audio:
|
|||
|
|
assert (audio.getframerate(), audio.getnchannels(), audio.getsampwidth()) == (48000, 2, 2)
|
|||
|
|
assert result.result["sample_count"] == audio.getnframes()
|
|||
|
|
assert abs(audio.getnframes() - 11027 * 48000 / 22050) < 2
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.mark.skipif(
|
|||
|
|
not shutil.which("ffmpeg") or not shutil.which("ffprobe"), reason="FFmpeg required"
|
|||
|
|
)
|
|||
|
|
async def test_final_compose_uses_sample_selection_without_millisecond_roundtrip(
|
|||
|
|
tmp_path, monkeypatch
|
|||
|
|
):
|
|||
|
|
from app.adapters import media
|
|||
|
|
from app.domain.stories import compile_story_render
|
|||
|
|
|
|||
|
|
source, voice = tmp_path / "video.mp4", tmp_path / "mix.wav"
|
|||
|
|
write_wav(voice, 50000)
|
|||
|
|
await media.run_process(
|
|||
|
|
[
|
|||
|
|
shutil.which("ffmpeg"),
|
|||
|
|
"-v",
|
|||
|
|
"error",
|
|||
|
|
"-f",
|
|||
|
|
"lavfi",
|
|||
|
|
"-i",
|
|||
|
|
"color=c=blue:s=256x256:r=24",
|
|||
|
|
"-frames:v",
|
|||
|
|
"25",
|
|||
|
|
"-c:v",
|
|||
|
|
"libx264",
|
|||
|
|
"-y",
|
|||
|
|
str(source),
|
|||
|
|
]
|
|||
|
|
)
|
|||
|
|
settings = SimpleNamespace(
|
|||
|
|
workspace_root=tmp_path,
|
|||
|
|
ffmpeg_bin=shutil.which("ffmpeg"),
|
|||
|
|
ffprobe_bin=shutil.which("ffprobe"),
|
|||
|
|
max_output_bytes=2**24,
|
|||
|
|
)
|
|||
|
|
raw = {
|
|||
|
|
"schema_version": 4,
|
|||
|
|
"shots": [{"id": A, "visual_prompt": "蓝色", "edit": {"duration_frames": 25}}],
|
|||
|
|
"render": {
|
|||
|
|
"audio": {"asset_id": "mix", "source_start_sample": 0, "source_end_sample": 50000}
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
frozen = {
|
|||
|
|
"fps": 24,
|
|||
|
|
"canvas": [1920, 1080],
|
|||
|
|
"clips": [
|
|||
|
|
{
|
|||
|
|
"shot_id": A,
|
|||
|
|
"asset_id": "video",
|
|||
|
|
"start_frame": 0,
|
|||
|
|
"duration_frames": 25,
|
|||
|
|
"width": 256,
|
|||
|
|
"height": 256,
|
|||
|
|
}
|
|||
|
|
],
|
|||
|
|
}
|
|||
|
|
plan = compile_story_render(raw, frozen)
|
|||
|
|
calls, actual = [], media.run_process
|
|||
|
|
|
|||
|
|
async def record(argv, **kwargs):
|
|||
|
|
calls.append(argv)
|
|||
|
|
return await actual(argv, **kwargs)
|
|||
|
|
|
|||
|
|
monkeypatch.setattr(media, "run_process", record)
|
|||
|
|
result = await media.compose_workflow(
|
|||
|
|
plan, tmp_path / "render", settings=settings, sources=[source], audio=voice
|
|||
|
|
)
|
|||
|
|
assert any("atrim=start_sample=0:end_sample=50000" in part for argv in calls for part in argv)
|
|||
|
|
assert (await media.inspect_video_track(result.outputs[0], settings))["frames"] == 25
|