Skip to content

Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.

32.7 KB
Raw Blame
import asyncio
import itertools
import json
import os
import subprocess
import types
from pathlib import Path

import numpy as np
import pytest
import soundfile as sf
from mimvox_engine import media, videoexport
from mimvox_engine.redub import subtitles
from mimvox_engine.registry import EngineError

SR = 16000


def bursts(*parts):
    """(seconds, loud) pieces: noise where loud, silence elsewhere."""
    rng = np.random.default_rng(0)
    return np.concatenate(
        [
            (rng.uniform(-0.3, 0.3, int(s * SR)) if loud else np.zeros(int(s * SR))).astype(np.float32)
            for s, loud in parts
        ]
    )


def test_speech_regions_bridge_word_gaps_and_split_at_pauses():
    y = bursts((0.5, False), (0.6, True), (0.1, False), (0.4, True), (0.7, False), (0.5, True), (0.3, False))
    regions = videoexport.speech_regions(y, SR)
    assert len(regions) == 2
    (a0, b0), (a1, b1) = regions
    assert (a0, b0) == (pytest.approx(0.5, abs=0.03), pytest.approx(1.6, abs=0.03))
    assert (a1, b1) == (pytest.approx(2.3, abs=0.03), pytest.approx(2.8, abs=0.03))


def test_silence_has_no_speech():
    assert videoexport.speech_regions(np.zeros(SR, np.float32), SR) == []


def test_sentences_split_at_punctuation_and_lines():
    text = "First one.  Second one!\nA line without a stop\n\nLast?"
    assert videoexport.sentences(text) == ["First one.", "Second one!", "A line without a stop", "Last?"]


def test_estimate_moves_a_sentence_break_to_the_pause_near_it():
    lines = videoexport.estimate("One two three. Four.", [(0.5, 2.0), (3.0, 3.6)], 4.0)
    assert lines == [(0.5, 2.0, "One two three."), (3.0, 3.6, "Four.")]


def test_estimate_without_pauses_shares_the_speech_by_characters():
    (a0, b0, t0), (a1, b1, t1) = videoexport.estimate("Aaaa. Bbbbbbbb.", [(1.0, 11.0)], 12.0)
    assert (a0, t0, t1, b1) == (1.0, "Aaaa.", "Bbbbbbbb.", 11.0)
    assert b0 == a1 == pytest.approx(1.0 + 10.0 * 5 / 14)


def test_estimate_skips_far_pauses_and_keeps_order():
    regions = [(0.0, 1.0), (1.2, 9.0), (9.5, 10.0)]
    lines = videoexport.estimate("Short. A much longer second sentence here. End.", regions, 10.0)
    assert [t for *_, t in lines] == ["Short.", "A much longer second sentence here.", "End."]
    assert lines[0][1] == 1.0
    assert lines[1][0] == 1.2
    assert lines[2][:2] == (9.5, 10.0)
    for (_, b, _), (a, _, _) in itertools.pairwise(lines):
        assert b <= a


def test_estimate_without_speech_found_spreads_over_the_file():
    lines = videoexport.estimate("One. Two.", [], 4.0)
    assert lines[0][0] == 0.0
    assert lines[-1][1] == 4.0
    assert videoexport.estimate("   ", [(0.0, 1.0)], 1.0) == []


def test_recorded_segments_keep_the_valid_ones_inside_the_file():
    side = {
        "segments": [
            {"start": 0.5, "end": 1.5, "text": "Hi."},
            {"start": 2.0, "end": 9.0, "text": "Cut at the end."},
            {"start": 1.0, "end": 1.0, "text": "empty"},
            {"start": "x", "end": 2.0, "text": "bad"},
            {"start": 3.0, "end": 4.0, "text": "  "},
            "nope",
        ]
    }
    assert videoexport.recorded(side, 5.0) == [(0.5, 1.5, "Hi."), (2.0, 5.0, "Cut at the end.")]
    assert videoexport.recorded({"segments": "x"}, 5.0) == []


def test_even_schedule():
    spans = videoexport.schedule(10, None, 60.0)
    assert [a for a, _ in spans] == pytest.approx([6.0 * k for k in range(10)])
    assert spans[-1][1] == 60.0
    assert videoexport.schedule(0, None, 60.0) == []


def test_custom_schedule():
    assert videoexport.schedule(3, [0.0, 2.5, 7.0], 10.0) == [(0.0, 2.5), (2.5, 7.0), (7.0, 10.0)]
    with pytest.raises(EngineError, match="after the end") as err:
        videoexport.schedule(2, [0.0, 10.0], 10.0)
    assert err.value.code == "bad_request"


@pytest.fixture
def photos(tmp_path):
    out = []
    for k in range(3):
        p = tmp_path / f"p{k}.png"
        p.write_bytes(b"png")
        out.append(p)
    return out


def test_images_without_starts_are_evenly_spaced(photos):
    paths, starts = videoexport.parse_images([{"path": str(p)} for p in photos])
    assert (paths, starts) == (photos, None)
    assert videoexport.parse_images(None) == ([], None)
    assert videoexport.parse_images([]) == ([], None)


def test_images_with_starts(photos):
    items = [{"path": str(p), "start": s} for p, s in zip(photos, (0, 1.5, 4))]
    assert videoexport.parse_images(items) == (photos, [0.0, 1.5, 4.0])


@pytest.mark.parametrize(
    ("starts", "message"),
    [
        ((0, None, 3), "every image a start"),
        ((1, 2, 3), "start at 0"),
        ((0, 2, 2), "image 3 must start after image 2"),
        ((0, -1, 3), "number of seconds"),
        ((0, True, 3), "number of seconds"),
        ((0, "2", 3), "number of seconds"),
    ],
)
def test_bad_starts(photos, starts, message):
    items = [{"path": str(p)} if s is None else {"path": str(p), "start": s} for p, s in zip(photos, starts)]
    with pytest.raises(EngineError, match=message) as err:
        videoexport.parse_images(items)
    assert err.value.code == "bad_request"


def test_bad_or_missing_images(tmp_path, photos):
    for bad in ("x", [{"start": 0}], [{"path": ""}], ["a.png"]):
        with pytest.raises(EngineError) as err:
            videoexport.parse_images(bad)
        assert err.value.code == "bad_request"
    with pytest.raises(EngineError) as err:
        videoexport.parse_images([{"path": str(photos[0])}, {"path": str(tmp_path / "gone.png")}])
    assert err.value.code == "not_found"


def test_timeline_has_a_frame_at_every_change_and_one_a_second():
    frames = videoexport.timeline([(0.0, 2.5), (2.5, 4.0)], [0.3, 1.1, 3.9, 7.0], 4.0)
    assert [p for p, _ in frames] == [0, 0, 0, 0, 1, 1, 1]
    assert [t for _, t in frames] == pytest.approx([0.0, 0.3, 1.1, 1.8, 2.5, 3.2, 3.9])
    for (_, a), (_, b) in itertools.pairwise(frames):
        assert 0 < b - a <= videoexport.MAX_FRAME_S + 1e-9
    assert videoexport.timeline([], [], 2.0) == [(0, 0.0), (0, 1.0)]


def test_fades_start_from_black_and_blend_each_picture_into_the_next():
    spans = [(0.0, 2.0), (2.0, 2.3), (2.3, 5.0)]
    windows = videoexport.fade_windows(["a", "b", "b"], spans, "black")
    assert windows == [(0.0, videoexport.FADE_S, "black", "a"), (2.0, pytest.approx(0.3), "a", "b")]
    frames = [("a", 0.0), ("a", 1.0), ("a", 1.01), ("b", 2.0), ("b", 3.0)]
    faded = videoexport.fade_frames(frames, windows, 5.0)
    times = [t for _, t in faded]
    assert times == sorted(times) and times[0] == 0.0 and max(times) < 5.0
    n = round(videoexport.FADE_S * videoexport.FADE_FPS)
    assert faded[0] == ("black", 0.0)
    assert faded[1] == (("black", "a", 1, n), pytest.approx(videoexport.FADE_S / n))
    assert ("a", pytest.approx(videoexport.FADE_S)) in faded and ("a", 1.01) in faded
    blends = [x for x, t in faded if isinstance(x, tuple) and x[0] == "a"]
    assert blends and all(x[1] == "b" and 0 < x[2] < x[3] for x in blends)
    assert ("b", pytest.approx(2.3)) in faded
    with pytest.raises(EngineError, match="'transitions'"):
        videoexport.transitions({"transitions": "yes"})


def test_concat_list_repeats_the_last_picture():
    text = videoexport.concat_list(["a.y4m", "b.y4m"], [(0, 0.0), (1, 1.25)], 2.0)
    assert text.splitlines() == [
        "ffconcat version 1.0",
        "file 'a.y4m'",
        "duration 1.250000",
        "file 'b.y4m'",
        "duration 0.750000",
        "file 'b.y4m'",
    ]


def test_containers_follow_the_encoders():
    assert videoexport.containers({"libx264", "aac"}) == ["mp4", "mkv", "mov"]
    assert videoexport.containers({"libx264", "aac", "libvpx-vp9", "libopus"}) == ["mp4", "mkv", "webm", "mov"]
    assert videoexport.containers({"libvpx", "libvorbis"}) == ["webm"]
    assert videoexport.containers({"libx264"}) == []


def test_slideshow_command(tmp_path):
    ass = tmp_path / "s.ass"
    cmd = videoexport.slideshow_command(
        "ffmpeg",
        tmp_path / "l.ffconcat",
        tmp_path / "a.wav",
        tmp_path / "o.mp4",
        "mp4",
        videoexport._X264,
        videoexport._AAC,
        3.0,
        ass,
    )
    assert cmd[cmd.index("-f") + 1] == "concat"
    graph = cmd[cmd.index("-filter_complex") + 1]
    assert graph.startswith("[0:v]subtitles=filename=") and graph.endswith("s.ass,format=yuv420p[v]")
    assert cmd[cmd.index("-c:v") + 1] == "libx264"
    assert cmd[cmd.index("-tune") + 1] == "stillimage"
    assert cmd[cmd.index("-c:a") + 1 : cmd.index("-c:a") + 4] == ["aac", "-aac_coder", "fast"]
    assert "+faststart" in cmd
    assert cmd[-1] == tmp_path / "o.mp4"
    webm = videoexport.slideshow_command(
        "ffmpeg",
        tmp_path / "l.ffconcat",
        tmp_path / "a.opus",
        tmp_path / "o.webm",
        "webm",
        videoexport._VP9,
        None,
        3.0,
    )
    assert webm[webm.index("-filter_complex") + 1] == "[0:v]format=yuv420p[v]"
    assert webm[webm.index("-deadline") + 1] == "realtime"
    assert "-tune" not in webm
    assert "+faststart" not in webm
    assert webm[webm.index("-c:a") + 1] == "copy"


def test_video_commands(tmp_path):
    remux = videoexport.remux_command("ffmpeg", tmp_path / "v.mp4", tmp_path / "o.mkv", "mkv")
    assert remux[remux.index("-c") + 1] == "copy"
    assert "-filter_complex" not in remux
    burn = videoexport.reencode_command(
        "ffmpeg", tmp_path / "v.mkv", tmp_path / "o.mp4", "mp4", videoexport._X264, None, tmp_path / "s.ass"
    )
    graph = burn[burn.index("-filter_complex") + 1]
    assert graph.startswith("[0:V:0]scale=") and "subtitles=filename=" in graph
    assert burn[burn.index("-c:a") + 1] == "copy"
    assert "-tune" not in burn
    assert burn.index("-hwaccel") < burn.index("-i")


def test_slideshow_command_joins_the_parts(tmp_path):
    parts = [
        videoexport.Part(tmp_path / "a.mp3", 0.0, 1.5, 1),
        videoexport.Part(tmp_path / "b.wav", 1.5, 0.5, 2),
    ]
    cmd = videoexport.slideshow_command(
        "ffmpeg", tmp_path / "l.ffconcat", parts, tmp_path / "o.mp4", "mp4", videoexport._X264, videoexport._AAC, 2.0
    )
    assert [cmd[i + 1] for i, a in enumerate(cmd) if a == "-i"] == [
        tmp_path / "l.ffconcat",
        tmp_path / "a.mp3",
        tmp_path / "b.wav",
    ]
    graph = cmd[cmd.index("-filter_complex") + 1]
    assert (
        "[1:a:0]aresample=48000,aformat=channel_layouts=stereo,apad=whole_len=72000,atrim=end_sample=72000[a1];"
        in graph
    )
    assert graph.endswith("[a1][a2]concat=n=2:v=0:a=1,asetpts=N/SR/TB[a]")
    assert cmd[cmd.index("[a]") - 1] == "-map"


def test_hardware_encoders_come_first_for_h264(monkeypatch, tmp_path):
    monkeypatch.setattr(media, "h264_hardware", lambda: "h264_vaapi")
    pictures = videoexport.pictures_for("mp4", {"libx264", "mpeg4", "libvpx-vp9"})
    assert [name for name, _ in pictures] == ["h264_vaapi", "libx264", "mpeg4"]
    assert pictures[0][1][pictures[0][1].index("-qp") + 1] == str(videoexport.HW_QUALITY)
    assert [name for name, _ in videoexport.pictures_for("webm", {"libx264", "libvpx-vp9"})] == ["libvpx-vp9"]
    cmd = videoexport.slideshow_command(
        "ffmpeg", tmp_path / "l", tmp_path / "a.wav", tmp_path / "o.mp4", "mp4", pictures[0], None, 1.0
    )
    assert cmd[cmd.index("-filter_complex") + 1] == "[0:v]format=nv12,hwupload[v]"
    assert "-tune" not in cmd


def test_the_hardware_probe_takes_the_first_encoder_that_runs(monkeypatch):
    tried = []

    def run(cmd, timeout=3600.0, data=None):
        name = cmd[cmd.index("-c:v") + 1]
        tried.append(name)
        return subprocess.CompletedProcess(cmd, 0 if name == "h264_qsv" else 1, b"", b"no device")

    monkeypatch.setattr(media, "_cache", {})
    monkeypatch.setattr(media, "ffmpeg_path", lambda: Path("ffmpeg"))
    monkeypatch.setattr(media, "_ffmpeg_lists", lambda: (set(), set(), {"libx264", "h264_nvenc", "h264_qsv"}, "8"))
    monkeypatch.setattr(media, "_run", run)
    assert media.h264_hardware() == "h264_qsv"
    assert media.h264_hardware() == "h264_qsv"
    assert tried == ["h264_nvenc", "h264_qsv"]


def test_hardware_candidates_follow_the_platform(monkeypatch):
    monkeypatch.setattr(media.sys, "platform", "darwin")
    amf = ["h264_amf"] if os.name == "nt" else []
    assert media._hardware_candidates(set(media.HARDWARE_H264)) == ["h264_nvenc", "h264_qsv", *amf, "h264_videotoolbox"]
    assert media._hardware_candidates({"libx264", "h264_qsv"}) == ["h264_qsv"]


def test_part_pictures_merge_with_the_images_by_time(photos):
    parts = [
        videoexport.Part(Path("a.wav"), 0.0, 10.0),
        videoexport.Part(Path("b.wav"), 10.0, 10.0, image=photos[0]),
        videoexport.Part(Path("c.wav"), 20.0, 10.0, image=photos[1]),
    ]
    shown, spans = videoexport.merge_images([photos[2]], [15.0], parts, 30.0)
    assert shown == [None, photos[0], photos[2], photos[1]]
    assert spans == [(0.0, 10.0), (10.0, 15.0), (15.0, 20.0), (20.0, 30.0)]
    shown, _ = videoexport.merge_images([photos[2]], [10.0], parts, 30.0)
    assert shown == [None, photos[0], photos[1]]
    shown, spans = videoexport.merge_images([photos[2]], None, parts[:1], 10.0)
    assert (shown, spans) == ([photos[2]], [(0.0, 10.0)])
    assert videoexport.merge_images([], None, parts[:1], 10.0) == ([], [])


def test_remux_needs_streams_the_container_takes():
    assert videoexport.fits("mkv", ("vp9", "opus"))
    assert videoexport.fits("mp4", ("h264", "aac"))
    assert not videoexport.fits("mp4", ("vp8", "vorbis"))
    assert not videoexport.fits("webm", ("h264", "aac"))
    assert videoexport.fits("webm", ("vp9", ""))
    assert not videoexport.fits("mov", ("", "aac"))


class Ctx:
    def __init__(self, tmp_path):
        self.data_dir = str(tmp_path / "data")
        self.runtime = {}
        self.events = []
        self.jobs = {}
        self.cancelled = []

    def emit(self, event, data, job=None):
        self.events.append((event, data))

    def start_job(self, fn):
        job = f"job-{len(self.jobs) + 1}"
        self.jobs[job] = fn
        return job

    def cancel(self, job):
        self.cancelled.append(job)


@pytest.mark.parametrize(
    ("params", "message"),
    [
        ({"format": "avi"}, "'format'"),
        ({"format": "mp4", "dest": "out.mp4"}, "absolute"),
        ({"format": "mp4", "dest": "{tmp}/out.mkv"}, r"end in \.mp4"),
        ({"format": "mp4", "dest": "{tmp}/out.mp4", "subtitles": {"position": "middle"}}, "'subtitles'"),
        ({"format": "mp4", "dest": "{tmp}/out.mp4", "subtitles": "bottom"}, "'subtitles'"),
    ],
)
def test_bad_requests(tmp_path, params, message):
    src = tmp_path / "a.wav"
    sf.write(src, np.zeros(SR, np.float32), SR)
    if "dest" in params:
        params = {**params, "dest": params["dest"].replace("{tmp}", str(tmp_path))}
    with pytest.raises(EngineError, match=message) as err:
        asyncio.run(videoexport.video_export(Ctx(tmp_path), {"path": str(src), **params}))
    assert err.value.code == "bad_request"


def test_cancel_without_a_job_running(tmp_path):
    ctx = Ctx(tmp_path)
    assert asyncio.run(videoexport.video_cancel(ctx, {})) == {"cancelled": False}
    assert asyncio.run(videoexport.video_cancel(ctx, {"job": "job-9"})) == {"cancelled": False}
    assert ctx.cancelled == []


def ffmpeg_can(*encoders):
    if media.ffmpeg_path() is None or media.ffprobe_path() is None:
        return False
    return set(encoders) <= media._ffmpeg_lists()[2]


needs_x264 = pytest.mark.skipif(not ffmpeg_can("libx264", "aac"), reason="needs ffmpeg with libx264 and aac")


def ff(*args):
    subprocess.run([str(media.ffmpeg_path()), "-v", "error", "-y", *map(str, args)], check=True)


@pytest.fixture
def clip(tmp_path):
    """1.5 s: two bursts of 'speech' with a pause, a Speak sidecar with two sentences, two photos."""
    path = tmp_path / "take.wav"
    sf.write(path, bursts((0.1, False), (0.5, True), (0.4, False), (0.4, True), (0.1, False)), SR)
    (tmp_path / "take.result.json").write_text(
        json.dumps({"kind": "speak", "language": "en", "text": "Hello there. Second line."}), encoding="utf-8"
    )
    ff("-f", "lavfi", "-i", "testsrc=s=64x48", "-frames:v", "1", tmp_path / "wide.png")
    ff("-f", "lavfi", "-i", "testsrc2=s=30x80", "-frames:v", "1", tmp_path / "tall.jpg")
    return path


def export(ctx, **params):
    job = asyncio.run(videoexport.video_export(ctx, params))["job"]
    assert job in videoexport._running
    asyncio.run(ctx.jobs[job](job))
    assert job not in videoexport._running
    return ctx.events[-1]


def picture_and_length(path):
    info = media.probe(path)
    return info["has_video"], info["duration_s"]


@needs_x264
def test_slideshow_with_estimated_subtitles(tmp_path, clip):
    ctx = Ctx(tmp_path)
    dest = tmp_path / "out" / "take.mp4"
    images = [{"path": str(tmp_path / "wide.png")}, {"path": str(tmp_path / "tall.jpg")}]
    event, data = export(
        ctx, path=str(clip), dest=str(dest), format="mp4", subtitles={"position": "top"}, images=images
    )
    assert event == "video.done", data
    assert data["subtitles"] == {"lines": 2, "source": "estimated"}
    assert data["copied"] is False
    assert "subtitle_note" not in data
    has_video, length = picture_and_length(dest)
    assert has_video
    assert length == pytest.approx(1.5, abs=0.1)
    assert data["duration_s"] == pytest.approx(length, abs=0.01)
    stages = [d["stage"] for e, d in ctx.events if e == "video.progress"]
    assert stages[0] == "prepare"
    pcts = [d["pct"] for e, d in ctx.events if e == "video.progress"]
    assert pcts == sorted(pcts)
    assert not list((tmp_path / "out").glob("*.part*"))
    assert not (tmp_path / "data" / "tmp" / "video_job-1").exists()


@needs_x264
def test_recorded_segments_win_and_custom_starts(tmp_path, clip):
    side = tmp_path / "take.json"
    side.write_text(json.dumps({"text": "Ignored.", "segments": [{"start": 0.1, "end": 0.6, "text": "Recorded."}]}))
    images = [{"path": str(tmp_path / "wide.png"), "start": 0}, {"path": str(tmp_path / "tall.jpg"), "start": 1}]
    dest = tmp_path / "take.mkv"
    event, data = export(
        Ctx(tmp_path),
        path=str(clip),
        dest=str(dest),
        format="mkv",
        subtitles={"position": "bottom"},
        images=images,
        sidecar=str(side),
    )
    assert event == "video.done", data
    assert data["subtitles"] == {"lines": 1, "source": "recorded"}
    assert picture_and_length(dest) == (True, pytest.approx(1.5, abs=0.1))


@needs_x264
def test_a_tall_picture_keeps_square_pixels(tmp_path, clip):
    dest = tmp_path / "tall.mp4"
    images = [{"path": str(tmp_path / "tall.jpg")}]
    event, data = export(Ctx(tmp_path), path=str(clip), dest=str(dest), format="mp4", images=images)
    assert event == "video.done", data
    shape = ["-select_streams", "v:0", "-show_entries", "stream=width,height,sample_aspect_ratio", "-of", "csv=p=0"]
    probed = subprocess.run(
        [str(media.ffprobe_path()), "-v", "error", *shape, str(dest)], capture_output=True, text=True, check=True
    )
    assert probed.stdout.strip() == f"{videoexport.WIDTH},{videoexport.HEIGHT},1:1"


@needs_x264
def test_photos_fade_in_and_into_each_other(tmp_path, clip):
    ff("-f", "lavfi", "-i", "color=c=white:s=64x48", "-frames:v", "1", tmp_path / "white.png")
    ff("-f", "lavfi", "-i", "color=c=0x404040:s=64x48", "-frames:v", "1", tmp_path / "gray.png")
    images = [{"path": str(tmp_path / "white.png"), "start": 0}, {"path": str(tmp_path / "gray.png"), "start": 0.8}]
    dest = tmp_path / "faded.mp4"
    event, data = export(Ctx(tmp_path), path=str(clip), dest=str(dest), format="mp4", images=images, transitions=True)
    assert event == "video.done", data

    def level(at):
        grab = ["-ss", str(at), "-i", str(dest), "-frames:v", "1", "-vf", "scale=64:36,format=gray", "-f", "rawvideo"]
        raw = subprocess.run(
            [str(media.ffmpeg_path()), "-v", "error", *grab, "-"],
            capture_output=True,
            check=True,
        ).stdout
        return float(np.median(np.frombuffer(raw, np.uint8)))

    assert level(0.0) < 40
    assert 40 < level(0.3) < 220
    assert level(0.7) > 230
    assert 80 < level(1.1) < 220
    assert level(1.45) < 80


@needs_x264
def test_black_video_without_text_has_no_subtitles(tmp_path, clip):
    (tmp_path / "take.result.json").write_text(json.dumps({"kind": "redub"}))
    dest = tmp_path / "take.mov"
    event, data = export(Ctx(tmp_path), path=str(clip), dest=str(dest), format="mov", subtitles={"position": "bottom"})
    assert event == "video.done", data
    assert data["subtitles"] is None
    assert "no saved text" in data["subtitle_note"]
    assert picture_and_length(dest) == (True, pytest.approx(1.5, abs=0.1))


@pytest.mark.skipif(not ffmpeg_can("libvpx-vp9", "libopus"), reason="needs ffmpeg with libvpx-vp9 and libopus")
def test_webm_slideshow(tmp_path, clip):
    dest = tmp_path / "take.webm"
    event, data = export(Ctx(tmp_path), path=str(clip), dest=str(dest), format="webm", subtitles=None)
    assert event == "video.done", data
    assert data["subtitles"] is None
    assert "subtitle_note" not in data
    assert picture_and_length(dest) == (True, pytest.approx(1.5, abs=0.1))
    assert videoexport._codecs(dest) == ("vp9", "opus")


@pytest.fixture
def redub_video(tmp_path):
    path = tmp_path / "redub.mp4"
    ff(
        "-f",
        "lavfi",
        "-i",
        "testsrc=s=96x64:r=25:d=1.2",
        "-f",
        "lavfi",
        "-i",
        "sine=d=1.2",
        "-c:v",
        "libx264",
        "-pix_fmt",
        "yuv420p",
        "-c:a",
        "aac",
        "-shortest",
        path,
    )
    (tmp_path / "redub.result.json").write_text(
        json.dumps({"kind": "redub", "segments": [{"start": 0.1, "end": 0.9, "text": "Placed line."}]})
    )
    return path


@needs_x264
def test_video_in_the_same_container_is_copied(tmp_path, redub_video):
    dest = tmp_path / "copy.mp4"
    event, data = export(Ctx(tmp_path), path=str(redub_video), dest=str(dest), format="mp4", subtitles=None)
    assert event == "video.done", data
    assert data["copied"] is True
    assert dest.read_bytes() == redub_video.read_bytes()


@needs_x264
def test_video_is_remuxed_into_another_container(tmp_path, redub_video):
    dest = tmp_path / "remux.mkv"
    event, data = export(Ctx(tmp_path), path=str(redub_video), dest=str(dest), format="mkv", subtitles=None)
    assert event == "video.done", data
    assert data["copied"] is False
    assert videoexport._codecs(dest) == ("h264", "aac")
    assert picture_and_length(dest) == (True, pytest.approx(1.2, abs=0.1))


@needs_x264
def test_video_with_subtitles_is_burned(tmp_path, redub_video):
    dest = tmp_path / "burned.mp4"
    event, data = export(
        Ctx(tmp_path), path=str(redub_video), dest=str(dest), format="mp4", subtitles={"position": "bottom"}
    )
    assert event == "video.done", data
    if "subtitles" not in media._ffmpeg_filters():
        assert "libass" in data["subtitle_note"]
        return
    assert data["copied"] is False
    assert data["subtitles"] == {"lines": 1, "source": "recorded"}
    assert picture_and_length(dest) == (True, pytest.approx(1.2, abs=0.1))


@needs_x264
def test_one_export_at_a_time(tmp_path, clip):
    videoexport._running.add("job-0")
    try:
        with pytest.raises(EngineError) as err:
            asyncio.run(
                videoexport.video_export(
                    Ctx(tmp_path), {"path": str(clip), "dest": str(tmp_path / "x.mp4"), "format": "mp4"}
                )
            )
        assert err.value.code == "busy"
        ctx = Ctx(tmp_path)
        assert asyncio.run(videoexport.video_cancel(ctx, {})) == {"cancelled": True}
        assert ctx.cancelled == ["job-0"]
    finally:
        videoexport._running.discard("job-0")


@needs_x264
def test_a_picture_ffmpeg_cannot_read_fails_the_job(tmp_path, clip):
    bad = tmp_path / "bad.png"
    bad.write_bytes(b"not a picture")
    dest = tmp_path / "bad.mp4"
    event, data = export(
        Ctx(tmp_path), path=str(clip), dest=str(dest), format="mp4", images=[{"path": str(bad)}], subtitles=None
    )
    assert (event, data["code"]) == ("video.error", "bad_request")
    assert "bad.png" in data["message"]
    assert not dest.exists()


def test_formats_list_has_export_video():
    out = media.formats()
    assert set(out["export_video"]) <= set(videoexport.FORMATS)
    if out["ffmpeg"]:
        assert out["export_video"] == videoexport.containers(media._ffmpeg_lists()[2])


def test_subtitle_cues_need_libass(tmp_path, monkeypatch):
    monkeypatch.setattr(media, "_ffmpeg_filters", lambda: {"atempo"})
    req = types.SimpleNamespace(sidecar=None, path=tmp_path / "a.wav", duration=1.0)
    subs = videoexport.subtitle_cues(req)
    assert subs.cues == []
    assert "libass" in subs.note


def test_estimated_cues_cover_the_text(tmp_path, monkeypatch):
    monkeypatch.setattr(media, "_ffmpeg_filters", lambda: {"subtitles"})
    path = tmp_path / "a.wav"
    (tmp_path / "a.result.json").write_text(json.dumps({"kind": "speak", "text": "One. Two."}))
    monkeypatch.setattr(media, "decode_pcm", lambda p, sr: bursts((0.5, True), (0.5, False), (0.5, True)))
    req = videoexport.Request(path, tmp_path / "a.mp4", "mp4", "bottom", [], [], None, 1.5, False, "pcm_s16le")
    subs = videoexport.subtitle_cues(req)
    assert subs.source == "estimated"
    assert [c.lines for c in subs.cues] == [("One.",), ("Two.",)]
    assert isinstance(subs.cues[0], subtitles.Cue)


@pytest.mark.parametrize(
    ("params", "message"),
    [
        ({"path": "{wav}", "parts": [{"path": "{wav}"}]}, "'path' or 'parts'"),
        ({"parts": []}, "'parts' must be a list"),
        ({"parts": [{"image": "{wav}"}]}, "part 1 needs a 'path'"),
        ({"parts": [{"path": "{wav}"}], "segments": []}, "'segments' goes into each part"),
        ({"parts": [{"path": "{wav}"}, {"path": "{wav}", "image": 3}]}, "part 2: 'image'"),
        ({"parts": [{"path": "{wav}", "segments": [], "segments_path": "{wav}"}]}, "not both"),
        ({"parts": [{"path": "{wav}", "segments": [{"start": 0, "text": "x"}]}]}, "part 1: segment 1 needs"),
        ({"path": "{wav}", "segments": "x"}, "'segments' must be a list"),
        ({"path": "{wav}", "segments_path": "{wav}"}, "has no 'segments'"),
        ({"parts": [{"path": "{wav}"}, {"path": "{mp4}"}]}, "part 2 .* is a video"),
    ],
)
def test_bad_part_requests(tmp_path, params, message):
    wav = tmp_path / "a.wav"
    sf.write(wav, np.zeros(SR, np.float32), SR)
    mp4 = tmp_path / "v.mp4"
    if "{mp4}" in json.dumps(params):
        if not ffmpeg_can("libx264", "aac"):
            pytest.skip("needs ffmpeg with libx264 and aac")
        ff("-f", "lavfi", "-i", "testsrc=s=64x48:d=1", "-f", "lavfi", "-i", "sine=d=1", "-c:v", "libx264", mp4)
    text = (
        json.dumps(params).replace("{wav}", str(wav).replace("\\", "/")).replace("{mp4}", str(mp4).replace("\\", "/"))
    )
    with pytest.raises(EngineError, match=message) as err:
        asyncio.run(
            videoexport.video_export(
                Ctx(tmp_path), {**json.loads(text), "dest": str(tmp_path / "o.mp4"), "format": "mp4"}
            )
        )
    assert err.value.code == "bad_request"


def test_a_missing_segments_file_is_not_found(tmp_path):
    wav = tmp_path / "a.wav"
    sf.write(wav, np.zeros(SR, np.float32), SR)
    params = {"parts": [{"path": str(wav), "segments_path": str(tmp_path / "gone.json")}]}
    with pytest.raises(EngineError) as err:
        asyncio.run(
            videoexport.video_export(Ctx(tmp_path), {**params, "dest": str(tmp_path / "o.mp4"), "format": "mp4"})
        )
    assert err.value.code == "not_found"


def audio_stream(path):
    res = subprocess.run(
        [
            str(media.ffprobe_path()),
            "-v",
            "error",
            "-select_streams",
            "a:0",
            "-show_entries",
            "stream=sample_rate,channels,duration",
            "-of",
            "json",
            str(path),
        ],
        capture_output=True,
        check=True,
    )
    return json.loads(res.stdout)["streams"][0]


@needs_x264
def test_parts_are_joined_with_their_pictures_and_lines(tmp_path, clip):
    second = tmp_path / "two.wav"
    sf.write(second, np.zeros((22050, 2), np.float32), 22050)
    third = tmp_path / "three.wav"
    sf.write(third, np.zeros(SR // 2, np.float32), SR)
    seg = tmp_path / "002.json"
    rows = [{"text": "Two", "start": 0.1, "end": 0.5, "kind": "title"}, {"text": "Body.", "start": 0.6, "end": 0.9}]
    seg.write_text(json.dumps({"chapter": 1, "title": "Two", "path": str(second), "duration_s": 1.0, "segments": rows}))
    parts = [
        {
            "path": str(clip),
            "segments": [{"start": 0.1, "end": 0.6, "text": "Given."}],
            "image": str(tmp_path / "wide.png"),
        },
        {"path": str(second), "segments_path": str(seg), "image": str(tmp_path / "tall.jpg")},
        {"path": str(third)},
    ]
    dest = tmp_path / "episode.mp4"
    event, data = export(Ctx(tmp_path), parts=parts, dest=str(dest), format="mp4", subtitles={"position": "bottom"})
    assert event == "video.done", data
    assert data["parts"] == [
        {"path": str(clip), "start": 0.0, "duration_s": 1.5},
        {"path": str(second), "start": 1.5, "duration_s": 1.0},
        {"path": str(third), "start": 2.5, "duration_s": 0.5},
    ]
    assert data["subtitles"] == {"lines": 3, "source": "recorded"}
    assert data["subtitle_note"] == "Part 3 has no saved text, so no subtitles."
    assert picture_and_length(dest) == (True, pytest.approx(3.0, abs=0.1))
    sound = audio_stream(dest)
    assert (sound["sample_rate"], sound["channels"]) == ("48000", 2)
    assert float(sound["duration"]) == pytest.approx(3.0, abs=0.03)


@needs_x264
def test_given_lines_win_over_the_sidecar(tmp_path, clip):
    dest = tmp_path / "given.mp4"
    lines = [{"start": 0.1, "end": 0.6, "text": "Only this."}]
    event, data = export(
        Ctx(tmp_path), path=str(clip), dest=str(dest), format="mp4", subtitles={"position": "top"}, segments=lines
    )
    assert event == "video.done", data
    assert data["subtitles"] == {"lines": 1, "source": "given"}
    assert data["parts"] == [{"path": str(clip), "start": 0.0, "duration_s": 1.5}]


@needs_x264
def test_a_failing_encoder_falls_back_to_the_next(tmp_path, clip, monkeypatch):
    monkeypatch.setattr(videoexport, "pictures_for", lambda fmt, encoders: [("h264_missing", []), videoexport._X264])
    dest = tmp_path / "fallback.mp4"
    event, data = export(Ctx(tmp_path), path=str(clip), dest=str(dest), format="mp4", subtitles=None)
    assert event == "video.done", data
    assert picture_and_length(dest) == (True, pytest.approx(1.5, abs=0.1))


def save(**params):
    return videoexport.save_subtitles(params)


def test_subtitle_file_of_given_lines_uses_their_words(tmp_path):
    words = [[0.5, 0.9, "Hello"], [1.0, 1.4, "there."], [5.0, 5.5, "Bye."]]
    lines = [{"start": 0.5, "end": 5.5, "text": "Hello there. Bye.", "words": words}]
    r = save(dest=str(tmp_path / "a.vtt"), format="vtt", segments=lines)
    assert (r["cues"], r["source"]) == (2, "given")
    doc = (tmp_path / "a.vtt").read_text(encoding="utf-8")
    assert doc.startswith("WEBVTT\n\n00:00:00.500 --> 00:00:01.700\nHello there.\n")
    assert "00:00:05.000 --> " in doc
    assert r["size_bytes"] == (tmp_path / "a.vtt").stat().st_size
    assert not list(tmp_path.glob("*.part*"))


def test_subtitle_file_of_a_result_reads_its_sidecar_or_estimates(tmp_path):
    path = tmp_path / "take.wav"
    sf.write(path, bursts((0.1, False), (0.5, True), (0.4, False), (0.4, True), (0.1, False)), SR)
    side = tmp_path / "take.result.json"
    side.write_text(json.dumps({"segments": [{"start": 0.1, "end": 0.6, "text": "Recorded."}]}), encoding="utf-8")
    r = save(path=str(path), dest=str(tmp_path / "take.srt"), format="srt")
    assert (r["cues"], r["source"]) == (1, "recorded")
    assert (tmp_path / "take.srt").read_text(encoding="utf-8").startswith("1\n00:00:00,100 --> ")
    if media.ffmpeg_path() is None:
        return
    side.write_text(json.dumps({"text": "Hello there. Second line."}), encoding="utf-8")
    r = save(path=str(path), dest=str(tmp_path / "take.sbv"), format="sbv")
    assert (r["cues"], r["source"]) == (2, "estimated")


def test_subtitle_file_refuses_bad_requests(tmp_path):
    path = tmp_path / "take.wav"
    sf.write(path, np.zeros(SR, np.float32), SR)
    lines = [{"start": 0, "end": 1, "text": "Hi."}]
    cases = [
        ({"format": "ass", "dest": str(tmp_path / "a.ass"), "segments": lines}, "bad_request"),
        ({"format": "srt", "dest": "a.srt", "segments": lines}, "bad_request"),
        ({"format": "srt", "dest": str(tmp_path / "a.vtt"), "segments": lines}, "bad_request"),
        ({"format": "srt", "dest": str(tmp_path / "a.srt")}, "bad_request"),
        (
            {"format": "srt", "dest": str(tmp_path / "a.srt"), "segments": [{"start": 1, "end": 1, "text": "x"}]},
            "bad_request",
        ),
        ({"format": "srt", "dest": str(tmp_path / "a.srt"), "path": str(path)}, "bad_request"),
        ({"format": "srt", "dest": str(tmp_path / "a.srt"), "path": str(tmp_path / "gone.wav")}, "not_found"),
    ]
    for params, code in cases:
        with pytest.raises(EngineError) as e:
            save(**params)
        assert e.value.code == code, params
    assert not (tmp_path / "a.srt").exists()