"""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("