XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

Cinematic-Game-Montage-skill

【Skill】电影感游戏剪辑Skill

公开
关注 0 Fork 0 Star 0
UTF-8
"""Real FFmpeg/PyAV test: remove a known hold and preserve matching audio/video."""
from __future__ import annotations

import argparse
from contextlib import nullcontext
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import wave

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "skills" / "cinematic-game-montage" / "scripts"))
import media
import timeline


def run(ffmpeg, args, data=None):
    result = subprocess.run([ffmpeg, "-hide_banner", "-nostdin", "-loglevel", "error", *args],
                            input=data, capture_output=True)
    if result.returncode:
        raise AssertionError(result.stderr.decode(errors="replace")[-6000:])
    return result


def decoded_video(path):
    import av
    with av.open(str(path)) as container:
        return [f.to_ndarray(format="rgb24") for f in container.decode(video=0)]


def decoded_audio(path):
    import av
    import numpy as np
    with av.open(str(path)) as container:
        return np.concatenate([f.to_ndarray().reshape(-1) for f in container.decode(audio=0)])


def exercise(root, ffmpeg):
    import numpy as np
    fps, sample_rate, width, height = 30, 48000, 160, 90
    indices = list(range(60))
    indices[12:17] = [11] * 5
    x, y = np.meshgrid(np.arange(width), np.arange(height))
    frames = []
    for index in indices:
        frames.append(np.stack(((x + 7 * index) % 256, (2 * y + 5 * index) % 256,
                                (x + y + 11 * index) % 256), axis=-1).astype(np.uint8))
    times = np.arange(sample_rate * 2) / sample_rate
    audio = (np.sin(times * 2 * np.pi * 440) * 1200).astype(np.int16)
    markers = [int(frame * sample_rate / fps) for frame in (6, 13, 42, 51)]
    audio[markers] = 26000
    wav = root / "source.wav"
    with wave.open(str(wav), "wb") as handle:
        handle.setnchannels(1)
        handle.setsampwidth(2)
        handle.setframerate(sample_rate)
        handle.writeframes(audio.tobytes())
    source = root / "fixture.mkv"
    run(ffmpeg, ["-f", "rawvideo", "-pixel_format", "rgb24", "-video_size", f"{width}x{height}",
                 "-framerate", str(fps), "-i", "pipe:0", "-i", str(wav), "-c:v", "ffv1",
                 "-c:a", "pcm_s16le", "-shortest", "-n", str(source)], np.stack(frames).tobytes())
    detected = media.scan_freezes(source, fps, 0, 60, ffmpeg, mad_threshold=.1, p99_threshold=.1)
    assert detected["decoded_frames"] == 60, detected
    assert [r["remove_candidate"] for r in detected["candidates"]] == [[12, 17]], detected
    plan = {"schema_version": 1, "fps": str(fps), "width": width, "height": height,
            "sample_rate": sample_rate, "sources": {"a": {"path": str(source), "normalized_frames": 60}},
            "shots": [{"id": "cleaned", "source": "a", "keep_ranges": [[0, 12], [17, 60]],
                       "frames": 55, "speed": "1", "repair_reviewed": True}]}
    compiled = timeline.compile_plan(plan, check_files=True)
    shot = compiled["shots"][0]
    graph = root / "cleaned.ffgraph"
    graph.write_text(timeline.shot_filter(shot, fps), encoding="utf-8")
    cleaned = root / "cleaned.mkv"
    def render(graph_path, destination):
        run(ffmpeg, ["-i", str(source), "-filter_complex_script", str(graph_path),
                     "-map", "[v]", "-map", "[a]", "-r", str(fps), "-fps_mode", "cfr",
                     "-enc_time_base:v", f"1:{fps}", "-c:v", "ffv1", "-c:a", "pcm_s16le", "-n", str(destination)])
    render(graph, cleaned)
    original_frames = decoded_video(source)
    actual_frames = decoded_video(cleaned)
    expected_frames = original_frames[:12] + original_frames[17:]
    assert len(actual_frames) == 55
    assert all(np.array_equal(a, b) for a, b in zip(actual_frames, expected_frames)), "video content differs from reviewed ranges"
    actual_audio = decoded_audio(cleaned)
    observed_markers = np.flatnonzero(actual_audio > 20000).tolist()
    expected_markers = [markers[0], markers[2] - 8000, markers[3] - 8000]
    assert observed_markers == expected_markers, (observed_markers, expected_markers)
    assert len(actual_audio) == 88000, len(actual_audio)
    verification = media.verify(cleaned, fps, 55, width, height, require_audio=True, av_tolerance_ms=1)
    assert verification["passed"], verification
    negative = media.verify(cleaned, fps, 56, width, height, require_audio=True)
    assert not negative["passed"], "wrong expected frame count was accepted"
    repaired_scan = media.scan_freezes(cleaned, fps, 0, 55, ffmpeg, mad_threshold=.1, p99_threshold=.1)
    assert repaired_scan["candidates"] == [], repaired_scan
    sheet = media.contact_sheet(source, [0, .4, 1.4], root / "contact-sheet.png", columns=3, width=240)

    # Speed changes are a separate case: doubled playback must keep the tone's pitch.
    fast = {"id": "fast", "keep_ranges": [[0, 60]], "frames": 30, "speed": "2", "start_frame": 0}
    fast_graph = root / "fast.ffgraph"
    fast_graph.write_text(timeline.shot_filter(fast, fps), encoding="utf-8")
    fast_file = root / "fast.mkv"
    render(fast_graph, fast_file)
    speed_verification = media.verify(fast_file, fps, 30, width, height, require_audio=True, av_tolerance_ms=1)
    assert speed_verification["passed"], speed_verification
    fast_audio = decoded_audio(fast_file).astype(float)
    spectrum = np.abs(np.fft.rfft(fast_audio * np.hanning(len(fast_audio))))
    frequency = float(np.fft.rfftfreq(len(fast_audio), 1 / sample_rate)[np.argmax(spectrum)])
    assert abs(frequency - 440) <= 3, frequency
    report = {"passed": True, "freeze_candidate": [12, 17], "source_frames": 60,
              "repaired_frames": 55, "video_frames_match_reviewed_ranges": True,
              "audio_markers_expected_samples": expected_markers,
              "audio_markers_observed_samples": observed_markers,
              "repaired_audio_samples": len(actual_audio), "freeze_candidates_after_repair": 0,
              "wrong_frame_count_rejected": True, "verification": verification,
              "speed_verification": speed_verification, "retimed_tone_hz": frequency,
              "contact_sheet": sheet}
    (root / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--ffmpeg")
    parser.add_argument("--work-dir", help="Preserve test fixtures in a NEW directory; otherwise use temporary files")
    args = parser.parse_args()
    ffmpeg = media.ffmpeg_binary(args.ffmpeg)
    if args.work_dir:
        root = Path(args.work_dir).resolve()
        root.mkdir(parents=True, exist_ok=False)
        context = nullcontext(str(root))
    else:
        context = tempfile.TemporaryDirectory(prefix="montage-media-test-")
    with context as folder:
        report = exercise(Path(folder), ffmpeg)
        print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()