CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

gamussa/reels-producer-skill

Write talking-head scripts and produce Instagram reels and YouTube shorts

1.07x
Quality

96%

Does it follow best practices?

Impact

98%

1.07x

Average score across 8 eval scenarios

SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

render_reel.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""Render a reel from cut_plan.json: trim segments, concat, lay audio, grade.

The plan's "music" key is optional. With it, the track is the spine (music-video
mode) and --natural-audio mixes clip sound underneath. Without it, the clips'
own audio is the spine (talking-head mode) — the VO carries the reel.

--vo-overlay lays a CONTINUOUS voiceover over the finished picture instead of
taking audio from the segments. Segments are concatenated, so a b-roll segment
otherwise replaces its slice of VO and punches a hole in the narration; with
--vo-overlay the picture cuts freely while the voice runs unbroken.

--duck words.json lays the plan's music as a BED under the voice (the VO file,
or the clips' own audio) and lowers it while words are spoken, keyed to the
transcript rather than the audio so breaths and room noise never pump it.
Pauses shorter than DUCK_HOLD_GAP stay ducked; the bed swells back only in
real gaps. Word times are in the voice's own timeline: the VO file's
transcript with --vo-overlay (--vo-start is subtracted), otherwise the cut's.

The plan can carry the voice itself, so it never depends on remembering flags:
  "vo": {"file": "raw/take.wav", "start": 0.0, "words": "work/take.words.json"}
lays that file as the continuous voice (--vo-overlay/--vo-start), and with a
"music" key ducks the bed under "words". Explicit flags override the plan.

The audio fades out over the last END_FADE seconds. "fade_out": {"seconds": s,
"video": true} sets the length and fades the picture with it; "speech_end"
(where the last word ends, in reel seconds — a promoted excerpt's provenance
carries it) keeps the fade off the words, so a talk short never fades its
payoff line.

Every finished render gets <out>.render.json beside it (provenance.py): the
plan's hash, a fingerprint of every input, and these settings. pipeline.py
reads it to decide staleness and to bind approvals to the exact file.

Grades:
  gritty  - teal/orange "Gritty Authentic Energy": cool shadows, warm mids/highs,
            lifted contrast, mild saturation, subtle vignette
  clean   - contrast + slight warmth only
  rapha   - muted painterly editorial: desaturated, faded blacks, warm mids,
            subtle grain, no vignette
  cine    - contrasty and grainy, colour-faithful: S-curve + grain with
            saturation held near original so hues do not shift
  punch   - harder contrast and grain than cine, slightly desaturated and
            warmer; the aggressive end of the set
  none    - passthrough
  (or --lut file.cube for a custom 3D LUT)

Usage:
  render_reel.py plan/cut_plan.json --preview --out preview/draft_v1.mp4
  render_reel.py plan/cut_plan.json --grade gritty --out work/master.mp4 [--srt caps.srt]
  render_reel.py plan/cut_plan.json --resolution 4k --out work/master_4k.mp4
  render_reel.py plan/cut_plan.json --vo-overlay vo.wav --duck vo.words.json \
      --music-gain-db -6 --out work/master.mp4
"""

import argparse
import subprocess
import sys
import tempfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import plan_schema  # noqa: E402  — owner of cut_plan.json reads and writes
from ffsafe import escape_filter_path  # noqa: E402
from provenance import write_render_record  # noqa: E402

PAN_X = {"left": "0", "center": "(iw-ow)/2", "right": "iw-ow"}


def pan_expr(pan):
    """ffmpeg crop x-offset for a segment's pan.

    Accepts left/center/right or a 0..1 fraction, so a clip reused at several
    in-points can be reframed per cut. Requires a mezzanine built with
    --no-crop; a pre-cropped one has no pixels left to move to.
    """
    if pan is None:
        return PAN_X["center"]
    if isinstance(pan, (int, float)):
        f = min(1.0, max(0.0, float(pan)))
        return f"(iw-ow)*{f:.4f}"
    return PAN_X.get(str(pan).lower(), PAN_X["center"])


GRADES = {
    "gritty": (
        "eq=contrast=1.08:saturation=1.12,"
        "colorbalance=rs=-0.06:gs=-0.02:bs=0.08:rm=0.05:gm=0.01:bm=-0.05:"
        "rh=0.04:bh=-0.04,"
        "curves=all='0/0.02 0.5/0.5 1/0.98',"
        "vignette=PI/5:mode=backward"
    ),
    "clean": "eq=contrast=1.05:saturation=1.05,colorbalance=rm=0.03:bm=-0.03",
    "rapha": (
        # muted painterly editorial: desaturated, warm mids/highs, cool-neutral
        # shadows, lifted blacks + softened highs (faded film), gentle contrast,
        # subtle grain, no vignette
        "eq=contrast=1.04:saturation=0.82:gamma=1.02,"
        "colorbalance=rs=0.02:gs=-0.01:bs=-0.03:rm=0.05:gm=0.00:bm=-0.05:"
        "rh=0.03:gh=0.00:bh=-0.04,"
        "curves=all='0/0.03 0.5/0.5 1/0.97',"
        "noise=alls=5:allf=t+u"
    ),
    "cine": (
        # rapha's tonal shape with more contrast and grain, but saturation
        # held near original (0.97) so the look does not shift colour
        "eq=contrast=1.14:saturation=0.97:gamma=1.01,"
        "colorbalance=rs=0.01:bs=-0.02:rm=0.03:bm=-0.03:rh=0.02:bh=-0.03,"
        "curves=all='0/0.02 0.25/0.21 0.75/0.79 1/0.98',"
        "noise=alls=8:allf=t+u"
    ),
    "punch": (
        # harder contrast and grain than cine, slightly desaturated and warmer
        "eq=contrast=1.20:saturation=0.94:gamma=0.99,"
        "colorbalance=rs=0.02:bs=-0.03:rm=0.06:bm=-0.05:rh=0.03:bh=-0.04,"
        "curves=all='0/0.0 0.25/0.19 0.75/0.82 1/1.0',"
        "noise=alls=10:allf=t+u"
    ),
    "none": None,
}

# Frame sizes by aspect then resolution. Must match the mezzanine built by
# normalize_clips.py, which takes the same --aspect / --resolution flags.
# 9:16 is the reel/short default; 16:9 is for landscape YouTube cuts.
ASPECTS = {
    "9:16": {"1080": (1080, 1920), "4k": (2160, 3840)},
    "16:9": {"1080": (1920, 1080), "4k": (3840, 2160)},
    "1:1": {"1080": (1080, 1080), "4k": (2160, 2160)},
}
# Kept for importers that only ever needed the vertical sizes.
RESOLUTIONS = ASPECTS["9:16"]

PREVIEW = {"9:16": (540, 960), "16:9": (960, 540), "1:1": (540, 540)}


def dims_for(aspect, resolution, preview=False):
    return PREVIEW[aspect] if preview else ASPECTS[aspect][resolution]


def run(cmd, label):
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode != 0:
        sys.exit(f"{label} failed:\n{r.stderr[-1200:]}")


DUCK_DB = -12.0  # music drop while the voice speaks
DUCK_ATTACK = 0.15  # s: the dip starts this long before a word
DUCK_RELEASE = 0.40  # s: and recovers over this long after the last word
DUCK_HOLD_GAP = 0.8  # s: shorter pauses stay ducked, so the bed never pumps
BED_LIMIT = 0.891  # -1 dBFS ceiling on voice + bed, before export loudnorm
END_FADE = 1.2  # s: default audio fade at the end of every render
VOICE_END_FADE = 0.04  # s: where a voice file ends before the picture (an end card), so
# the cut never clicks or lets the next speaker's syllable in


def end_fade(plan, total):
    """(start, duration, fade the picture too) for the closing fade.

    The plan's "fade_out": {"seconds": s, "video": true} sets the length and
    adds a matching picture fade. "speech_end" (seconds into the reel where the
    last word ends) keeps the fade off the words: it starts no earlier than
    that, and shortens to fit the room after it.
    """
    spec = plan.get("fade_out") if isinstance(plan.get("fade_out"), dict) else {}
    secs = float(spec.get("seconds", END_FADE))
    st = max(0.0, total - secs)
    speech_end = plan.get("speech_end")
    if isinstance(speech_end, (int, float)) and st < speech_end:
        st = min(float(speech_end), total)
    return round(st, 3), round(max(0.0, total - st), 3), bool(spec.get("video"))


def duck_spans(
    words, offset=0.0, total=None, hold_gap=DUCK_HOLD_GAP, attack=DUCK_ATTACK, release=DUCK_RELEASE
):
    """Speech spans on the output timeline, merged across short pauses.

    Spans closer than attack + release are merged too, so the ramps of two
    spans never overlap and the duck depth never exceeds one.
    """
    merge = max(hold_gap, attack + release)
    spans = []
    for w in sorted(words, key=lambda w: w["start"]):
        a, b = float(w["start"]) - offset, float(w["end"]) - offset
        if b <= 0 or (total is not None and a >= total):
            continue
        a = max(a, 0.0)
        b = min(b, total) if total is not None else b
        if spans and a - spans[-1][1] < merge:
            spans[-1][1] = max(spans[-1][1], b)
        else:
            spans.append([a, b])
    return [(round(a, 3), round(b, 3)) for a, b in spans]


def _clip01(x):
    return min(max(x, 0.0), 1.0)


def duck_gain(t, spans, duck_db=DUCK_DB, attack=DUCK_ATTACK, release=DUCK_RELEASE):
    """Linear music gain at time t — the same curve duck_expr() hands ffmpeg."""
    depth = sum(
        min(_clip01((t - (a - attack)) / attack), _clip01(((b + release) - t) / release))
        for a, b in spans
    )
    return 1.0 - (1.0 - 10 ** (duck_db / 20)) * _clip01(depth)


def duck_expr(spans, duck_db=DUCK_DB, attack=DUCK_ATTACK, release=DUCK_RELEASE):
    """ffmpeg `volume` expression (eval=frame) for duck_gain()."""
    if not spans:
        return "1"
    terms = "+".join(
        f"min(clip((t-{a - attack:.3f})/{attack:.3f},0,1),"
        f"clip(({b + release:.3f}-t)/{release:.3f},0,1))"
        for a, b in spans
    )
    return f"1-{1 - 10 ** (duck_db / 20):.5f}*clip({terms},0,1)"


def apply_plan_vo(args, plan):
    """Fill --vo-overlay / --vo-start / --duck from the plan's "vo" block when
    the caller did not pass them. Shared with resolve_render.py."""
    vo = plan.get("vo")
    if not vo:
        return
    if not isinstance(vo, dict) or not vo.get("file"):
        sys.exit(
            'plan "vo" must be {"file": <voice file>, "start": <sec>, '
            '"words": <words.json>} — "file" is required'
        )
    if not args.vo_overlay:
        args.vo_overlay = vo["file"]
        args.vo_start = float(vo.get("start", 0.0))
    if not getattr(args, "duck", None) and vo.get("words") and plan.get("music"):
        args.duck = vo["words"]


def media_seconds(path):
    r = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],
        capture_output=True,
        text=True,
    )
    try:
        return float(r.stdout.strip())
    except ValueError:
        sys.exit(f"cannot read the duration of {path} — is it a media file?")


def voice_chain(vo_overlay, vo_start, total):
    """The continuous voice, ending cleanly and padded with silence to the
    picture: a voice shorter than the cut (an end card held after the last
    word) fades out over VOICE_END_FADE where it ends, instead of the mux
    cutting the picture short or the voice clicking off."""
    end = media_seconds(vo_overlay) - vo_start
    if end >= total:
        return "anull"
    return f"afade=t=out:st={max(0.0, end - VOICE_END_FADE):.3f}:d={VOICE_END_FADE},apad"


def lay_audio_spine(
    video,
    out_tmp,
    plan,
    total,
    vf,
    music,
    nat_db,
    vo_overlay,
    vo_start,
    music_gain_db,
    preview,
    crf,
    abr,
    duck=None,
):
    """Mux the audio spine (music, VO, or the clips' own sound) onto a cut
    picture, applying any video filter chain in the same pass.

    Shared with resolve_render.py, which hands over a picture Resolve already
    graded and passes an empty `vf`: the sound design is one place either way.

    `duck` (a duck_expr() string) with `music` lays the music as a bed under
    the voice — the VO file if given, else the segment audio at `nat_db`.
    """
    cmd = ["ffmpeg", "-y", "-i", str(video)]
    if vo_overlay:
        cmd += ["-ss", str(vo_start), "-i", str(vo_overlay)]
    if music:
        cmd += ["-ss", str(plan.get("music_start", 0)), "-i", music]
    st, d, fade_video = end_fade(plan, total)
    fade = f"afade=t=out:st={st}:d={d}" if d > 0 else "anull"
    if fade_video and d > 0:
        vf = [*vf, f"fade=t=out:st={st}:d={d}"]
    enc = ["-c:v", "libx264", "-preset", "veryfast" if preview else "slow", "-crf", crf]
    if music and duck:
        vchain = f"[0:v]{','.join(vf)}[vout];" if vf else ""
        vmap = "[vout]" if vf else "0:v:0"
        voice, mus = (
            (f"[1:a]{voice_chain(vo_overlay, vo_start, total)}", "[2:a]")
            if vo_overlay
            else (f"[0:a]volume={nat_db or 0}dB", "[1:a]")
        )
        cmd += [
            "-filter_complex",
            vchain + f"{voice}[voice];"
            f"{mus}volume={music_gain_db}dB,volume=volume='{duck}':eval=frame[bed];"
            f"[voice][bed]amix=inputs=2:duration=longest:normalize=0,"
            f"alimiter=limit={BED_LIMIT}:level=false,{fade}[aout]",
            "-map",
            vmap,
            "-map",
            "[aout]",
        ]
        cmd += enc if vf else ["-c:v", "copy"]
    elif music and nat_db is not None:
        # single filter_complex graph for both video grade and audio mix
        vchain = f"[0:v]{','.join(vf)}[vout];" if vf else ""
        vmap = "[vout]" if vf else "0:v:0"
        cmd += [
            "-filter_complex",
            vchain + f"[0:a]volume={nat_db}dB[nat];"
            f"[1:a]volume={music_gain_db}dB[mus];"
            f"[nat][mus]amix=inputs=2:duration=first:normalize=0,{fade}[aout]",
            "-map",
            vmap,
            "-map",
            "[aout]",
        ]
        cmd += enc if vf else ["-c:v", "copy"]
    elif music:
        cmd += (["-vf", ",".join(vf)] + enc) if vf else ["-c:v", "copy"]
        cmd += ["-filter:a", f"volume={music_gain_db}dB,{fade}", "-map", "0:v:0", "-map", "1:a:0"]
    elif vo_overlay:
        # picture from the segments, voice from the VO file, unbroken
        cmd += (["-vf", ",".join(vf)] + enc) if vf else ["-c:v", "copy"]
        cmd += [
            "-filter:a",
            f"{voice_chain(vo_overlay, vo_start, total)},{fade}",
            "-map",
            "0:v:0",
            "-map",
            "1:a:0",
        ]
    else:
        # talking-head: the segments' own audio is the only spine
        cmd += (["-vf", ",".join(vf)] + enc) if vf else ["-c:v", "copy"]
        cmd += ["-filter:a", f"volume={nat_db}dB,{fade}", "-map", "0:v:0", "-map", "0:a:0"]
    cmd += ["-c:a", "aac", "-b:a", abr, "-shortest", "-movflags", "+faststart", str(out_tmp)]
    run(cmd, "final mux")


def add_duck_args(ap):
    """--duck flags, shared with resolve_render.py."""

    def positive(v):
        f = float(v)
        if f <= 0:
            raise argparse.ArgumentTypeError("must be > 0")
        return f

    ap.add_argument(
        "--duck",
        metavar="WORDS_JSON",
        help="Lay the plan's music as a bed under the voice and duck it "
        "while these words are spoken (word-level transcript of "
        "the voice; the VO file's with --vo-overlay)",
    )
    ap.add_argument(
        "--duck-db",
        type=float,
        default=DUCK_DB,
        help=f"Music drop under speech (default {DUCK_DB:g})",
    )
    ap.add_argument(
        "--duck-attack",
        type=positive,
        default=DUCK_ATTACK,
        help=f"Seconds the dip leads a word (default {DUCK_ATTACK:g})",
    )
    ap.add_argument(
        "--duck-release",
        type=positive,
        default=DUCK_RELEASE,
        help=f"Seconds to recover after speech (default {DUCK_RELEASE:g})",
    )


def duck_from_args(args, music, total):
    """duck_expr() for the parsed --duck flags, or None without --duck."""
    if not args.duck:
        return None
    if not music:
        sys.exit(
            "--duck lowers the plan's music under the voice, and this plan has "
            'no "music" key — add one, or drop --duck'
        )
    from gen_captions import load_words

    words = load_words(args.duck)
    offset = args.vo_start if args.vo_overlay else 0.0
    spans = duck_spans(words, offset, total, attack=args.duck_attack, release=args.duck_release)
    if not spans:
        sys.exit(
            f"--duck: no word in {args.duck} falls inside the reel "
            f"(0-{total:g}s after a {offset:g}s offset) — is it the transcript "
            "of this voice?"
        )
    print(f"  ducking the bed {args.duck_db:g} dB over {len(spans)} speech span(s)", flush=True)
    return duck_expr(spans, args.duck_db, args.duck_attack, args.duck_release)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("plan")
    ap.add_argument("--out", required=True)
    ap.add_argument("--preview", action="store_true", help="fast 540x960 draft")
    ap.add_argument("--grade", default="none", choices=list(GRADES))
    ap.add_argument("--lut", help="Custom .cube LUT (overrides --grade)")
    ap.add_argument("--srt", help="Burn in captions from SRT file")
    ap.add_argument(
        "--resolution",
        choices=("1080", "4k"),
        default="1080",
        help="Output size (default 1080). Use the same value "
        "normalize_clips.py built the mezzanine at.",
    )
    ap.add_argument(
        "--vo-overlay",
        metavar="FILE",
        help="Lay continuous voiceover audio from FILE over the "
        "cut picture, so b-roll does not interrupt the VO.",
    )
    ap.add_argument(
        "--vo-start",
        type=float,
        default=0.0,
        metavar="SEC",
        help="Where in the VO file the reel's t=0 sits (default 0).",
    )
    ap.add_argument(
        "--aspect",
        choices=sorted(ASPECTS),
        default="9:16",
        help="Frame aspect (default 9:16 for reels/shorts). Use "
        "16:9 for a landscape YouTube cut. Must match the "
        "mezzanine.",
    )
    ap.add_argument(
        "--crf",
        type=int,
        default=None,
        metavar="N",
        help="x264 quality, lower is better (default 16 master / "
        "26 preview). 12 is near-lossless for an archival "
        "master; below 10 mostly grows the file.",
    )
    ap.add_argument(
        "--audio-bitrate",
        default=None,
        metavar="RATE",
        help="AAC bitrate (default 192k). 320k for an archival master.",
    )
    ap.add_argument("--music-gain-db", type=float, default=-3.0)
    add_duck_args(ap)
    ap.add_argument(
        "--natural-audio",
        type=float,
        metavar="DB",
        default=None,
        help="Keep clips' natural audio mixed under music at this gain "
        "(e.g. -18). 30ms fades at every cut prevent pops. "
        "Music-less plans use the clip audio at 0dB by default.",
    )
    args = ap.parse_args()

    plan = plan_schema.load_or_exit(args.plan)
    segs = plan["segments"]
    apply_plan_vo(args, plan)

    # Audio spine. Music-video plans carry a "music" track; talking-head plans
    # omit it and let the clips' own audio (the VO) carry the reel, so keep the
    # segment audio at unity unless the caller asked for a different gain.
    music = plan.get("music")
    nat_db = args.natural_audio
    # Hand-authored plans omit total_duration; derive it from the segments.
    total = plan.get("total_duration") or sum(s["duration"] for s in segs)
    duck = duck_from_args(args, music, total)
    if args.vo_overlay:
        # The VO file is the spine; segment audio would only fight it.
        if not Path(args.vo_overlay).exists():
            sys.exit(f"--vo-overlay file not found: {args.vo_overlay}")
        if music and not duck:
            print(
                "note: the plan's music is not used with --vo-overlay; pass "
                "--duck <vo words.json> to lay it as a bed under the voice",
                file=sys.stderr,
            )
            music = None
        nat_db = None
    elif (duck or not music) and nat_db is None:
        nat_db = 0.0

    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    # render to .tmp, rename after validation — never expose a partial file
    out_tmp = out.with_name(out.stem + ".tmp" + out.suffix)

    with tempfile.TemporaryDirectory() as td:
        td = Path(td)
        # 1. Cut each segment losslessly-ish (re-encode for frame accuracy)
        parts = []
        rw, rh = dims_for(args.aspect, args.resolution, args.preview)
        crf = str(args.crf) if args.crf else ("26" if args.preview else "16")
        abr = args.audio_bitrate or "192k"
        for n, s in enumerate(segs):
            p = td / f"seg{n:03d}.mp4"
            # scale-to-cover then crop, so a full-frame mezzanine is reframed
            # rather than squashed; on an already-cropped one the crop is a
            # no-op and the pan is simply ignored.
            # lanczos, matching normalize_clips.py: this is the second and
            # last resample a shipped frame sees, and ffmpeg's default bicubic
            # softens a 4K-sourced mezzanine on the way down to 1080.
            geom = (
                f"scale={rw}:{rh}:force_original_aspect_ratio=increase"
                f":flags=lanczos,"
                f"crop={rw}:{rh}:{pan_expr(s.get('pan'))}:(ih-oh)/2"
            )
            cut = [
                "ffmpeg",
                "-y",
                "-ss",
                str(s["in"]),
                "-i",
                s["clip"],
                "-t",
                str(s["duration"]),
                "-vf",
                f"{geom},fps=30,format=yuv420p",
                "-c:v",
                "libx264",
                "-preset",
                "veryfast",
                "-crf",
                crf,
            ]
            if nat_db is not None:
                fade_out = max(0.0, s["duration"] - 0.03)
                cut += [
                    "-af",
                    f"afade=t=in:d=0.03,afade=t=out:st={fade_out}:d=0.03",
                    "-c:a",
                    "aac",
                    "-b:a",
                    abr,
                    "-ar",
                    "48000",
                ]
            else:
                cut += ["-an"]
            run(cut + [str(p)], f"segment {n}")
            parts.append(p)
            print(f"  cut {n + 1}/{len(segs)}", flush=True)

        # 2. Concat
        lst = td / "list.txt"
        lst.write_text("".join(f"file '{p}'\n" for p in parts))
        video = td / "video.mp4"
        run(
            [
                "ffmpeg",
                "-y",
                "-f",
                "concat",
                "-safe",
                "0",
                "-i",
                str(lst),
                "-c",
                "copy",
                str(video),
            ],
            "concat",
        )

        # 3. Grade + captions
        vf = []
        if args.lut:
            vf.append(f"lut3d={escape_filter_path(args.lut)}")
        elif GRADES.get(args.grade):
            vf.append(GRADES[args.grade])
        if args.srt:
            vf.append(
                f"subtitles='{args.srt}':force_style="
                "'FontName=Arial Black,FontSize=14,PrimaryColour=&HFFFFFF,"
                "OutlineColour=&H000000,Outline=2,Alignment=2,MarginV=60'"
            )

        # 4. Lay the audio spine
        lay_audio_spine(
            video,
            out_tmp,
            plan,
            total,
            vf,
            music,
            nat_db,
            args.vo_overlay,
            args.vo_start,
            args.music_gain_db,
            args.preview,
            crf,
            abr,
            duck=duck,
        )

    # validate, then publish under the final name
    r = subprocess.run(
        [
            "ffprobe",
            "-v",
            "quiet",
            "-show_entries",
            "format=duration",
            "-of",
            "csv=p=0",
            str(out_tmp),
        ],
        capture_output=True,
        text=True,
    )
    if r.returncode != 0 or not r.stdout.strip():
        out_tmp.unlink(missing_ok=True)
        sys.exit("Rendered file failed ffprobe validation — output discarded")
    out_tmp.rename(out)
    write_render_record(
        out,
        args.plan,
        inputs={
            "music": plan.get("music") if music else None,
            "vo": args.vo_overlay,
            "duck_words": args.duck,
            "lut": args.lut,
            "srt": args.srt,
            "clips": sorted({s["clip"] for s in segs}),
        },
        settings={
            "engine": "ffmpeg",
            "preview": args.preview,
            "grade": args.grade,
            "aspect": args.aspect,
            "resolution": args.resolution,
            "crf": crf,
            "vo_start": args.vo_start,
            "music_gain_db": args.music_gain_db,
            "natural_audio": nat_db,
            "duck_db": args.duck_db if duck else None,
        },
    )
    rw, rh = dims_for(args.aspect, args.resolution, args.preview)
    print(
        f"Rendered {out} ({float(r.stdout.strip()):.1f}s, {rw}x{rh} "
        f"{args.aspect}, {'preview' if args.preview else 'master'}, "
        f"grade={args.lut or args.grade})"
    )


if __name__ == "__main__":
    main()

skills

tile.json