Skip to content

Reverse-engineer any video, shot by shot: filmed, AI-generated or coded, and how to remake it. Breakdowns in the open VIDEO.md format. 逆向一切视频,逐个镜头看是拍的、AI 生成的还是代码做的,再告诉你怎么复刻;拆解结果按 VIDEO.md 格式输出。

26.6 KB
Raw Blame
"""Bridge to capsule-cinema (https://github.com/JuneYaooo/capsule-cinema).

1. export_capsule_analysis(): converts a rea-video breakdown into the analyzer JSON that
   capsule-cinema's video->capsule pipeline expects (scripts/analyze_video_to_capsule.py),
   so a reusable capsule draft can be produced from an accurate, evidence-backed breakdown.
2. build_remake_jobs(): turns the generation units of the remake plan into jobs for the chosen engine's
   capsule-cinema tool (one per call), with the source references cut and cleaned. Still-image shots are rebuilt locally.
"""
from __future__ import annotations

import re
from datetime import datetime
from pathlib import Path

from ..readings import shot_description
from ..classify import LABEL_ZH
from ..i18n import T, join, semi
from ..util import fmt_time, write_json

FORMAT_MAP = {"口播": "short_video", "剧情": "story", "商品展示": "product_showcase", "知识讲解": "explainer",
              "MV": "music_mv", "混剪": "short_video"}
CAMERA_ZH = {"static": "固定机位", "static_with_subject_motion": "固定机位、主体运动", "planar_zoom_pan": "整图推拉/平移",
             "handheld_like": "手持晃动", "smooth_move": "平滑运镜", "unknown": "未知"}
# generated by default; filmed shots are shot by the user (pass --labels live_action to approximate them with a model)


def _aspect(b: dict) -> str:
    ar = b["source"].get("aspect_ratio", "unknown")
    return ar if ar in ("9:16", "16:9", "1:1") else "unknown"


TRANS_ZH = {"cut": "硬切", "flash": "闪亮切", "fade": "淡入淡出", "dissolve": "叠化", "mg_transition": "版式切换", "start": "开场"}


def _top_tr(s: dict) -> str:
    tr = {k: v for k, v in s["transitions"].items() if k != "start"} or s["transitions"]
    return max(tr, key=tr.get)


def _mmss(t: float) -> str:
    return fmt_time(t)


def _shot_copy(s: dict) -> str:
    texts = []
    for tr in s.get("text", {}).get("tracks", []):
        if tr["kind"] in ("subtitle", "title"):
            texts += tr["texts"]
    v = s.get("vlm") or {}
    texts += v.get("overlay_text", []) or []
    seen, out = set(), []
    for t in texts:
        if t and t not in seen:
            seen.add(t)
            out.append(t)
    return " / ".join(out[:6])


def export_capsule_analysis(b: dict, out_path: Path, keep_source_text: bool = False) -> Path:
    """Analyzer JSON for a capsule draft. A capsule is a reusable recipe, so by default it carries the source's form only:
    no spoken or on-screen words, scene descriptions, or file path, any of which can name a brand, a person or a licence."""
    s = b["summary"]
    whole = dict(b.get("whole_video_vlm") or {})
    if not keep_source_text:
        for k in ("segments", "hook", "summary"):
            whole.pop(k, None)
    shots = b["shots"]
    mix_txt = "、".join(f"{m['label_zh']} {m['ratio']:.0%}" for m in s["production_mix"])
    segments = []
    literals: list[str] = []
    for sh in shots:
        f = sh["features"]
        copy = _shot_copy(sh) if keep_source_text else ""
        literals += [t for t in copy.split(" / ") if len(t) >= 2]
        motion = CAMERA_ZH.get(f.get("camera", "unknown"), "")
        if sh["base"]["label"] == "still_motion":
            motion += f";缩放 {f.get('zoom_per_s', 0) * 100:+.1f}%/s,平移 {f.get('pan_px_per_s', 0):.0f}px/s"
        segments.append({
            "start_time": _mmss(sh["start"]), "end_time": _mmss(sh["end"]),
            "beat": f"镜头 {sh['index']}({sh['duration']:.1f}s)",
            "visuals": f"[{sh['base']['label_zh']} {sh['base']['confidence']:.0%}] " + ((shot_description(sh) or sh["verdict"]) if keep_source_text else "按原片的景别和机位重新设计内容"),
            "material": (sh.get("material") or {}).get("origin_zh", ""),
            "motion": motion, "copy": copy,
            "audio": "",
            "reuse_lesson": f"该位置用「{LABEL_ZH[sh['base']['label']]}」制作,时长约 {sh['duration']:.1f}s,{motion}",
        })
    # prefer the VLM's narrative beats (with copy/audio) and attach the production method of
    # the shots they overlap; fall back to one segment per shot
    wsegs = [w for w in (whole.get("segments") or []) if isinstance(w, dict)]
    if wsegs:
        merged = []
        for w in wsegs:
            try:
                a, z = float(w.get("start", 0)), float(w.get("end", 0))
            except (TypeError, ValueError):
                continue
            over = [sh for sh in shots if sh["end"] > a and sh["start"] < z] or shots[:1]
            kinds = "、".join(sorted({sh["base"]["label_zh"] for sh in over}))
            merged.append({"start_time": _mmss(a), "end_time": _mmss(z), "beat": str(w.get("beat", "")),
                           "visuals": f"[{kinds}] " + ";".join(((sh.get("vlm") or {}).get("description") or sh["verdict"]) for sh in over[:3]),
                           "motion": "、".join(sorted({CAMERA_ZH.get(sh["features"].get("camera", "unknown"), "") for sh in over})),
                           "copy": str(w.get("copy", "")), "audio": str(w.get("audio", "")),
                           "reuse_lesson": f"这一段({w.get('beat', '')})用「{kinds}」实现"})
            if w.get("copy"):
                literals.append(str(w["copy"]))
        if merged:
            segments = merged
    lens = [x["duration"] for x in shots]
    structure_rules = [
        f"全片约 {s['duration']:.0f}s,{s['shots']} 个镜头,平均每镜 {s['avg_shot_s']}s(最短 {min(lens):.1f}s,最长 {max(lens):.1f}s)",
        f"转场以 {TRANS_ZH.get(_top_tr(s), _top_tr(s))} 为主:" + "、".join(f"{TRANS_ZH.get(k, k)}×{v}" for k, v in s["transitions"].items() if k != "start"),
    ]
    if whole.get("hook"):
        structure_rules.append(f"开头钩子:{whole['hook']}")
    visual_rules = [f"底层画面构成:{mix_txt}"]
    for m in s["production_mix"]:
        if m["label"] == "ai_video":
            visual_rules.append("AI 镜头先定首帧(或首尾帧)再生成视频,单镜 4–8 秒,同一角色跨镜头用参考图保持一致")
        if m["label"] == "code_render":
            visual_rules.append("文字、图表、界面类画面用代码/模板渲染,不交给生成模型")
        if m["label"] in ("still_motion", "static_hold"):
            visual_rules.append("部分镜头是静态图(推拉或定格),用图片 + 本地动效即可,不必生成视频")
    rm = s.get("real_material") or {}
    real_inputs: list[str] = []
    if rm.get("shots"):
        kinds = "、".join(rm.get("kinds", {}).keys())
        visual_rules.append(f"引入用户真实素材({kinds}):约 {rm['ratio']:.0%} 的时长使用真实截图/照片/实拍,"
                            "这些画面每期需要用户提供新素材,不能用模型生成替代")
        kind_input = {"界面截图": "screenshots", "录屏素材": "screen_recordings", "实拍视频素材": "real_footage",
                      "照片/图片素材": "photos", "真实照片": "photos", "嵌入视频片段": "video_clips", "商品实拍图": "product_photos",
                      "Logo/品牌标识": "brand_logo"}
        real_inputs = sorted({kind_input.get(k, "real_assets") for k in rm.get("kinds", {})})
    styles = sorted({(sh.get("vlm") or {}).get("style", "") for sh in shots} - {""})
    if styles:
        visual_rules.append("画风关键词:" + ";".join(styles[:4]))
    copy_rules = []
    if "subtitle" in s.get("overlay_kinds", []) or (whole.get("subtitles") or {}).get("present"):
        copy_rules.append("字幕由后期代码叠加(不要让模型在画面里生成文字)" + (f":{whole['subtitles'].get('style')}" if whole.get("subtitles", {}).get("style") else ""))
    if "title" in s.get("overlay_kinds", []):
        copy_rules.append("顶部有固定标题条,全片保持")
    audio_rules = []
    a = b.get("audio", {})
    n = whole.get("narration") or {}
    if n.get("type"):
        audio_rules.append(f"旁白:{n.get('type')} {n.get('voice', '')}".strip())
    elif a.get("speech_likely"):
        audio_rules.append("有人声旁白/对白")
    if (whole.get("music") or {}).get("style"):
        audio_rules.append(f"BGM:{whole['music']['style']}")
    elif a.get("music_likely"):
        audio_rules.append(f"有背景音乐,约 {a.get('tempo_bpm')} BPM" if a.get("tempo_bpm") else "有背景音乐(无明显节拍)")
    if a.get("beat_synced_edit"):
        audio_rules.append("切镜卡在音乐节拍上")
    mu = a.get("music") or {}
    srcs = b.get("sound_sources") or {}
    if srcs.get("music"):
        audio_rules.append(f"BGM 来源:{srcs['music']['source_zh']}(倾向 {srcs['music']['leaning']});"
                           + ("MV 类内容:歌是按内容定制的,每期要重新生成歌" if (srcs.get("format_context") or {}).get("music_mv") else "垫底配乐:按风格/BPM 选曲即可"))
    if mu.get("present") and mu.get("tempo_bpm"):
        key = mu.get("key") or {}
        audio_rules.append(f"BGM 约 {mu['tempo_bpm']} BPM" + (f"、{key.get('tonic')} {key.get('mode')}" if key else "")
                           + ";有音高的音效可以对齐 BGM 调性")
    sfx = (b.get("audio_plan") or {}).get("sfx_merged", [])
    if sfx:
        types: dict[str, int] = {}
        for e in sfx:
            types[str(e.get("type", "other"))] = types.get(str(e.get("type", "other")), 0) + 1
        audio_rules.append("音效:" + "、".join(f"{k}×{v}" for k, v in sorted(types.items(), key=lambda kv: -kv[1]))
                           + ",按画面事件(切镜/文字弹出/动作)逐点摆放")
    motion_rules = sorted({CAMERA_ZH.get(sh["features"].get("camera", "unknown"), "") for sh in shots} - {""})
    quality_rules = [
        {"id": "rea_production_mix", "type": "manual_qc_required", "severity": "warning",
         "rule": f"复刻时保持各镜头的制作方式与原片一致({mix_txt})"},
        {"id": "rea_ai_artifacts", "type": "manual_qc_required", "severity": "warning",
         "rule": "AI 镜头逐个检查手部、文字、主体形变与闪烁"},
    ]
    content_scope = {
        "schema_version": "capsule.content_scope.v1",
        "series_fixed": ["format_rules", "production_mix", "shot_rhythm", "overlay_style"],
        "episode_variable": ["topic", "subject_facts", "episode_copy", "characters_or_products"] + (["user_supplied_real_assets"] if rm.get("shots") else []),
        "forbidden_reusable_literals": sorted({t.strip() for t in literals if t.strip()}, key=str.casefold)[:80],
        "policies": {"allow_series_fixed_defaults": True, "forbid_episode_specific_defaults": True,
                     "active_recipe_examples_must_use_placeholders": True, "current_run_input_may_reuse_literal": True},
    }
    # de-duplicate case-insensitively (capsule-cinema validator requires it)
    seen, uniq = set(), []
    for t in content_scope["forbidden_reusable_literals"]:
        if t.casefold() not in seen:
            seen.add(t.casefold())
            uniq.append(t)
    content_scope["forbidden_reusable_literals"] = uniq
    fmt = FORMAT_MAP.get(str(whole.get("format", "")), "other" if whole else "short_video")
    data = {
        "summary": whole.get("summary") or s["verdict"],
        "source_profile": {"likely_format": fmt, "aspect_ratio": _aspect(b), "target_platform": "", "primary_audience": ""},
        "segments": segments,
        "capsule_recipe": {
            "when_to_use": ["想复用这条参考视频的镜头节奏、制作方式组合与叠加层风格"],
            "when_not_to_use": ["需要与原片逐帧一致的商业复制(版权/肖像风险)"],
            "structure_rules": structure_rules, "copy_rules": copy_rules, "visual_rules": visual_rules,
            "audio_rules": audio_rules, "motion_rules": motion_rules, "quality_rules": quality_rules,
            "default_runtime": {"aspect_ratio": b["source"].get("aspect_ratio")},
        },
        "execution_strategy": {"mode": "review_required", "reason": "由 rea-video 自动逆向拆解生成,需要人工确认后再固化为配方",
                               "deterministic_steps": [], "parameterized_inputs": ["topic", "reference_images"] + real_inputs,
                               "episode_specific_values": [], "evidence": {"successful_runs": 0, "cross_topic_verified": False}},
        "content_scope": content_scope,
        "warnings": [] if b["analysis"]["vlm"].get("used") else ["未启用 VLM:镜头描述与文案较少,建议用 --vlm 重新拆解"],
        "rea_video": {"verdict": s["verdict"], "production_mix": s["production_mix"], "confidence": s["confidence"],
                      **({"source": b["source"]["path"]} if keep_source_text else {})},
    }
    write_json(out_path, data)
    return out_path


def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path) -> Path:
    """Write jobs.json for `rea-video remake-run` (rea_video/integrations/run_remake.py): one job per call of each
    generation unit in the remake plan (the model and intent the user chose), stills rebuilt locally, every other shot
    kept as the original. Refuses while the plan checks report an error (an image over the limit, a prompt that breaks
    the model's format...). Output dirs live under <capsule_root>/output/ to satisfy capsule-cinema's output guard."""
    from ..generation import checks, load_intent, load_prompts

    plan = b.get("production_plan") or {}
    plan = {**plan, "units": plan.get("units") or []}
    # the intent and the final prompts may have changed since the plan was written: check what will actually be sent
    prompts = load_prompts(bdir)
    cs = checks(plan, load_intent(bdir), prompts, plan.get("prompting"), sum(u["duration"] for u in plan["units"]), root=bdir) if plan["units"] else []
    errors = [c["msg"] for c in cs if c["level"] == "error"]
    if errors:
        raise ValueError(T("方案检查没过,先改:", "the plan checks failed, fix these first: ") + semi().join(errors))
    stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    slug = re.sub(r"[^A-Za-z0-9_-]+", "_", Path(b["source"]["filename"]).stem)[:40]
    run_dir = capsule_root / "output" / f"rea_remake_{slug}_{stamp}"
    jobs = _unit_jobs(b, bdir, run_dir, plan, prompts)
    covered = {i for j in jobs for i in j["shots"]}
    for sh in b["shots"]:
        if sh["index"] in covered:
            continue
        lab = sh["base"]["label"]
        rep = sh.get("replication") or {}
        if lab in ("still_motion", "static_hold"):
            jobs.append({"shot": sh["index"], "id": sh["id"], "shots": [sh["index"]], "executor": "local_ffmpeg", "label": lab,
                         "image": str((bdir / sh["assets"]["first_frame"]).resolve()), "duration": sh["duration"],
                         "motion": rep.get("local", {}), "user_assets": rep.get("user_assets", [])})
        else:
            jobs.append({"shot": sh["index"], "id": sh["id"], "shots": [sh["index"]], "executor": "keep_original", "label": lab,
                         "reason": rep.get("note", ""), "user_assets": rep.get("user_assets", [])})
    jobs.sort(key=lambda j: (j["shot"], j.get("part", 0)))
    write_handoff(b, bdir, jobs)
    out = bdir / "remake" / "jobs.json"
    write_json(out, {"breakdown": str((bdir / "breakdown.json").resolve()), "capsule_root": str(capsule_root),
                     "run_dir": str(run_dir), "engine": plan.get("model"), "strategy": plan.get("strategy"), "jobs": jobs})
    return out


HANDOFF_SCHEMA = "rea_video.remake_handoff.v1"


def write_handoff(b: dict, bdir: Path, jobs: list[dict]) -> Path:
    """What Capsule Cinema needs to generate, assemble and check the remake, with package-relative paths only. rea-video
    knows the shots' measured moves, the text to lay back on and what each shot still needs; the doing is Capsule's."""
    from ..packaging import fit_ass_sizes, to_ass
    from ..remake import _needs, _next_step, overlay_cues

    src = b["source"]
    w, h = src["width"], src["height"]
    if src.get("rotation") in (90, 270):
        w, h = h, w
    w, h = w - w % 2, h - h % 2
    rdir = bdir / "remake"
    rdir.mkdir(parents=True, exist_ok=True)
    duration = float(src.get("duration") or (b["shots"][-1]["end"] if b["shots"] else 0))
    pack = b.get("packaging") or {}  # a cue without text has nothing to lay back on
    readable = {**b, "packaging": {**pack, "text_cues": [c for c in pack.get("text_cues", []) if c.get("text")]}}
    cues, stickers = overlay_cues(readable, [(0.0, duration)])
    ass = None
    if cues:
        f = rdir / "overlays_all.ass"
        f.write_text(to_ass(cues, w, h), encoding="utf-8")
        try:
            fit_ass_sizes(f)
        except (OSError, RuntimeError, ValueError):
            pass  # the measured sizes stay; only the font-metric correction is lost
        ass = "remake/overlays_all.ass"
    plan = b.get("production_plan") or {}
    executor = {j["shot"]: j["executor"] for j in jobs}
    shots = [{"index": sh["index"], "start": sh["start"], "end": sh["end"], "label": sh["base"]["label"],
              "first_frame": (sh.get("assets") or {}).get("first_frame"), "local": (sh.get("replication") or {}).get("local") or {},
              "executor": executor.get(sh["index"], "keep_original"), "next": _next_step(sh, plan), "needs": _needs(sh)}
             for sh in b["shots"]]
    code = bdir / "code" / "remake.mp4"
    out = rdir / "handoff.json"
    api_opts = (plan.get("spec") or {}).get("api_params") or {}
    write_json(out, {"schema": HANDOFF_SCHEMA, "width": w, "height": h, "fps": src["fps"], "duration": duration,
                     "has_audio": bool(src.get("has_audio")), "engine": plan.get("model"),
                     **({"model_options": api_opts} if api_opts else {}), "shots": shots,
                     "overlays": {"ass": ass, "stickers": stickers}, "code_video": "code/remake.mp4" if code.is_file() else None})
    return out


GEN_TYPE = {"edit": "multimodal", "remix": "multimodal", "keyframes": "multimodal", "frames": "first_last_frame", "text": "text_to_video"}


def _unit_model_options(u: dict, spec: dict, eng: str | None, vids: list[str], images: list[dict]) -> dict:
    """Model-specific API switches from the capability map, plus structured multi-shot / audio flags where needed."""
    opts = dict(spec.get("api_params") or {})
    if opts.get("omni_reference_task_type") == "reference" and not (vids or images):
        opts.pop("omni_reference_task_type", None)  # only meaningful when reference media are sent
    if spec.get("no_audio_with_ref_video") and vids:
        opts["enable_audio"] = False
    if eng == "kling-3.0" and len(u.get("brief") or []) > 1:
        opts["shot_type"] = "customize"
        opts["multi_prompt"] = [{"index": idx, "prompt": str(x.get("action") or x.get("source") or "")[:512],
                                 "duration": max(1, int(round(x["duration"])))}
                                for idx, x in enumerate(u["brief"], 1)]
    return opts


def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[str, str]) -> list[dict]:
    """One job per call of each unit, fed as the plan says: the source stretch as reference video (remix), one source
    frame per shot (keyframes), the shot's first / last frame (frames) or nothing but text; the user's images first; the
    final prompt from remake/prompts.json, else the draft. Everything taken from the source has its subtitles erased."""
    from ..drive import scene_text
    from ..generation import redrawn_frame, resolve_redrawn_frame, unit_frame_aliases, unit_images

    spec = plan.get("spec") or {}
    lo, hi = int(spec.get("min") or 1), int(spec.get("max") or 15)
    eng = plan.get("model")
    jobs = []
    for u in plan["units"]:
        files = ref_clips(b, bdir, u)
        images = [{"tag": r["tag"], "path": r["path"] if r.get("user") else files[(1, r["tag"])], "what": r["what"]} for r in unit_images(u)]
        prompt = prompts.get(u["id"]) or u["draft"]
        parts = sorted({r.get("part", 1) for r in u["refs"] if r["tag"].startswith("@视频")}) or list(range(1, u["calls"] + 1))
        for part in parts:
            vids = [files[(part, r["tag"])] for r in u["refs"] if r["tag"].startswith("@视频") and r.get("part", 1) == part]
            secs = u["generate_s"]
            gtype = GEN_TYPE[u["strategy"]]
            params = {"prompt": prompt, "output_dir": str(run_dir / (u["id"] if len(parts) == 1 else f"{u['id']}-{part}")),
                      "generation_type": gtype, "engine": eng, "aspect_ratio": b["source"].get("aspect_ratio") or "9:16",
                      "duration": int(u.get("call_s") or min(hi, max(lo, round(secs + 0.49))))}
            if vids:
                params["video_paths"] = vids
            if images:
                params["image_paths"] = [x["path"] for x in images]
            bookend = False
            if u["strategy"] == "frames":
                first, last = files.get((part, "first")), files.get((part, "last"))
                if last:
                    params.update(start_image_path=first, end_image_path=last)
                    bookend = True
                else:
                    params.update(generation_type="image_to_video", image_path=first)
            jid = u["id"] if len(parts) == 1 else f"{u['id']}-{part}"
            times = [r["t"] for r in u["refs"] if r.get("keyframe") and not redrawn_frame(bdir, f"shot{int(r['keyframe']):03d}")]
            if u["strategy"] == "frames":
                times += [t for key, t in _part_frame_times(u, part)
                          if (part, key) in files and not resolve_redrawn_frame(bdir, unit_frame_aliases(u, part, key))]
            words = list(dict.fromkeys(w for t in times for w in scene_text(b, t)))
            warning = T("参考帧里还有画面内文字({w}),模型可能照着生成:换成干净图,或确认有授权", "the reference frames still show text in the picture ({w}), which the model may copy: use a clean image or confirm you have the rights",
                        w=join(words[:6])) if words else None
            m_opts = _unit_model_options(u, spec, eng, vids, images)
            jobs.append({"shot": u["shots"][0], "id": jid, "unit": u["id"], "part": part, "parts": len(parts), "shots": u["shots"],
                         "executor": "capsule_cinema", "label": u["label"], "strategy": u["strategy"], "bookend": bookend,
                         "images": images, "params": params, **({"model_options": m_opts} if m_opts else {}),
                         "trim_to": round(secs, 3), "prompt_source": "final" if u["id"] in prompts else "draft",
                         **({"warning": warning} if warning else {})})
    return jobs


def _part_frame_times(unit: dict, part: int) -> tuple[tuple[str, float], tuple[str, float]]:
    """Where one call of a frames unit takes its first and last frame from: just inside its share of the unit."""
    n = max(1, int(unit.get("calls") or 1))
    span = max(0.0, unit["end"] - unit["start"])
    a, z = unit["start"] + span * (part - 1) / n, unit["start"] + span * part / n
    return ("first", min(z, a + min(0.05, (z - a) / 4))), ("last", max(a, z - min(0.08, (z - a) / 4)))


def ref_clips(b: dict, bdir: Path, unit: dict) -> dict[tuple[int, str], str]:
    """What one unit takes from the source, subtitles and laid-on text erased, written once into remake/refs/:
    reference clips ({(part, "@视频1"): path}), per-shot keyframes ({(1, "@图片3"): path}) and the first / last frame of
    a frames unit, per call ({(part, "first"): path, (part, "last"): path}). Files are named by span, so a re-plan never reuses a stale one."""
    from ..drive import clean_clip, clean_frame, control_clip
    from ..generation import load_intent, part_frame_name, redrawn_frame, resolve_redrawn_frame, unit_frame_aliases, wants_last_frame

    d = bdir / "remake" / "refs"
    intent = (b.get("production_plan") or {}).get("intent") or b.get("intent") or load_intent(bdir)
    out = {}
    for r in unit.get("refs") or []:
        if r.get("keyframe"):
            f = redrawn_frame(bdir, f"shot{int(r['keyframe']):03d}") or d / f"{unit['id']}_shot{int(r['keyframe']):03d}_{r['t']:.2f}.jpg"
            if not f.is_file():
                clean_frame(b, r["t"], f)
            out[(1, r["tag"])] = str(f.resolve())
        elif r["tag"].startswith("@视频") and r.get("ranges"):
            a, z = r["ranges"][0][0], r["ranges"][-1][1]
            vkind = r.get("video_kind") or "source"
            prefix = "v" if vkind == "source" else f"{vkind}_v"
            f = d / f"{unit['id']}_p{r.get('part', 1)}_{prefix}{r['tag'][3:]}_{a:.1f}-{z:.1f}.mp4"
            if not f.is_file():
                if vkind in ("depth", "edge"):
                    control_clip(b, r["ranges"], f, kind=vkind)
                else:
                    clean_clip(b, r["ranges"], f)
            out[(r.get("part", 1), r["tag"])] = str(f.resolve())
    if unit.get("strategy") == "frames":
        for part in range(1, max(1, int(unit.get("calls") or 1)) + 1):
            first_rd = resolve_redrawn_frame(bdir, unit_frame_aliases(unit, part, "first"))
            last_rd = resolve_redrawn_frame(bdir, unit_frame_aliases(unit, part, "last"))
            subject_redesigned = (first_rd is not None or bool(intent.get("swaps"))
                                  or str(intent.get("image_ref") or "auto") not in ("", "auto"))
            for key, t in _part_frame_times(unit, part):
                if key == "last":
                    if not wants_last_frame(unit):
                        continue
                    # Never pair a redesigned/swapped first frame with an unredrawn source last frame (causes mid-shot morphing back)
                    if subject_redesigned and last_rd is None:
                        continue
                name = part_frame_name(unit, part, key)
                rd = first_rd if key == "first" else last_rd
                f = rd or d / f"{name}_{t:.2f}.jpg"
                if not f.is_file():
                    clean_frame(b, t, f)
                out[(part, key)] = str(f.resolve())
    return out


def image_ref_frames(b: dict, bdir: Path, plan: dict) -> list[Path]:
    """Export cleaned/depth/edge still reference frames into remake/refs/ when image_ref is explicitly set."""
    from ..drive import clean_frame, control_frame

    iref = str((plan.get("intent") or {}).get("image_ref") or "auto").strip().lower()
    if iref not in ("source", "depth", "edge"):
        return []
    d = bdir / "remake" / "refs"
    written: list[Path] = []
    for t in plan.get("image_tasks") or []:
        if t.get("role") != "first_frame":
            continue
        idx = int(t["shot"])
        ts = float(t.get("t") or 0.0)
        suffix = "clean" if iref == "source" else iref
        dst = d / f"shot{idx:03d}_{suffix}.jpg"
        if not dst.is_file():
            if iref == "source":
                clean_frame(b, ts, dst)
            else:
                control_frame(b, ts, dst, kind=iref)
        written.append(dst)
    return written