"""Rough cut: every shot as its generated clip when one exists (previz/clips/.mp4), else the storyboard cards. uv run --with pillow python previz/animatic.py --song song.m4a --live # (re)build previz/cards_live first python3 previz/roughcut.py --song song.m4a [--clips previz/clips] [--size 1280x720] [--out previz/roughcut.mp4] Clips of start/end shots are sped up or slowed down to fit the shot exactly, so the move lands on the end frame at the cut; single-frame clips are trimmed from the start. Cards (start, in-between, end) share the shot's time equally. Every segment is cut to an exact frame count on one 30 fps grid (the last frame is held if a source runs short), so rounding never accumulates into drift. For the final cut, point --clips at the 1080p downloads and use --size 1920x1080; the edit decisions below stay the same. Edit decisions (fill in per project; they are code so the cut can be rebuilt after every change): - EXACT: clips already on the shot's own timeline (e.g. V2V of a timed code blockout): trimmed, never speed-fit. - INPOINT: start a clip at this source time instead of speed-fitting (to land an action on a sung word). - WIPES: two clips joined by a hard wipe behind a black vertical bar sweeping left to right — (first clip, second clip, song time the bar crosses the middle of the frame, sweep duration). - RECUT: a run of shots replaced by pieces of existing clips, (clip, src_in, src_out, song_t0, song_t1), cut on beats. Use it for chained clips (one clip per keyframe pair), trims around a bad stretch, lengthening one shot by taking beats from the next, or intercutting two clips. Each piece is retimed to fill its slot. If any piece's clip is missing the shots fall back to their regular clips/cards, so a half-finished re-edit never breaks the build. """ import argparse, json, pathlib, subprocess ROOT = pathlib.Path(__file__).resolve().parent ap = argparse.ArgumentParser() ap.add_argument("--song", required=True) ap.add_argument("--clips", default=str(ROOT / "clips")) ap.add_argument("--size", default="1280x720") ap.add_argument("--out", default=str(ROOT / "roughcut.mp4")) args = ap.parse_args() CLIPS = pathlib.Path(args.clips) W, H = map(int, args.size.split("x")) SEG = ROOT / f"roughcut_segments_{H}" SEG.mkdir(exist_ok=True) FPS = 30 shots = json.load(open(ROOT / "shots.json")) pairs = {f["shot"] for f in json.load(open(ROOT / "keyframes.json")) if f["role"] == "end"} EXACT = set() # e.g. {"S30"} INPOINT = {} # e.g. {"S09": 0.82} # the object drops on the sung "drop" WIPES = {} # e.g. {"S37": ("S37_a", "S37_b", 110.248, 0.30)} RECUT = {} # e.g. # RECUT = { # "S11": (["S11"], [ # chained: three clips, each generated from the previous clip's cut frame # ("S11a", 0.00, 4.01, 30.395, 32.183), # ("S11b", 0.00, 2.875, 32.183, 34.389), # ("S11c", 0.00, 4.01, 34.389, 36.200), # ]), # "S35": (["S35", "S36"], [ # S35 needs time to read: it takes two beats from S36 # ("S35", 0.00, 2.182, 105.419, 107.601), # ("S36", 0.00, 1.765, 107.601, 109.366), # ]), # } V = ["-an", "-r", str(FPS), "-pix_fmt", "yuv420p", "-c:v", "libx264", "-crf", "20" if H <= 720 else "16", "-preset", "veryfast"] SCALE = f"scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H},setsar=1" def probe(p): return float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(p)], capture_output=True, text=True).stdout) def cards_for(sid): """Start card, in-between cards (_m1, _m2, ...) and end card, in order.""" d = ROOT / "cards_live" mids = sorted(d.glob(f"{sid}_m*.png"), key=lambda p: int(p.stem.split("_m")[1])) return [p for p in [d / f"{sid}.png", *mids, d / f"{sid}_end.png"] if p.exists()] parts, used, skip = [], [], set() for s in shots: sid, out = s["id"], SEG / f"{s['id']}.mp4" if sid in skip: continue if sid in WIPES and all((CLIPS / f"{c}.mp4").exists() for c in WIPES[sid][:2]): a_clip, b_clip, tm, sw = WIPES[sid] n = round(s["t1"] * FPS) - round(s["t0"] * FPS); dur = n / FPS off = tm - sw / 2 - s["t0"] # sweep starts here, relative to the shot bw = round(150 * W / 1280) # bar width fc = (f"[0:v]{SCALE},fps={FPS},tpad=stop_mode=clone:stop_duration=3,trim=duration={off + sw + 0.1:.3f}[a];" f"[1:v]{SCALE},fps={FPS},tpad=stop_mode=clone:stop_duration=3,trim=duration={dur + 0.2:.3f}[b];" f"[a][b]xfade=transition=custom:expr='if(lt(X\\,W*(1-P))\\,B\\,A)':duration={sw}:offset={off:.3f}[w];" f"color=black:s={bw}x{H}:r={FPS}[bar];" f"[w][bar]overlay=x='(t-{off:.3f})/{sw}*{W}-{bw}/2':y=0:enable='between(t,{off - 0.05:.3f},{off + sw + 0.05:.3f})'[o]") subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(CLIPS / f"{a_clip}.mp4"), "-i", str(CLIPS / f"{b_clip}.mp4"), "-filter_complex", fc, "-map", "[o]", "-frames:v", str(n), *V, str(out)], check=True) parts.append(out); used.append(sid) continue if sid in RECUT and all((CLIPS / f"{p[0]}.mp4").exists() for p in RECUT[sid][1]): covered, pieces = RECUT[sid] skip |= set(covered) for k, (src, a, b, t0, t1) in enumerate(pieces): n = round(t1 * FPS) - round(t0 * FPS) vf = (f"trim=start={a}:end={b},setpts=(PTS-STARTPTS)/{(b - a) / (t1 - t0):.5f},{SCALE},fps={FPS}," "tpad=stop_mode=clone:stop_duration=1") piece = SEG / f"{sid}_recut{k}.mp4" subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(CLIPS / f"{src}.mp4"), "-vf", vf, "-frames:v", str(n), *V, str(piece)], check=True) parts.append(piece) used += covered continue nframes = round(s["t1"] * FPS) - round(s["t0"] * FPS) dur = nframes / FPS clip = CLIPS / f"{sid}.mp4" if clip.exists(): length = probe(clip) fit = sid in pairs and sid not in EXACT and sid not in INPOINT and dur / length > 0.3 # sped-up start->end move; very short shots just trim vf = (f"setpts={dur / length:.5f}*PTS," if fit else "") + SCALE + ",tpad=stop_mode=clone:stop_duration=3" if sid in INPOINT: vf = f"trim=start={INPOINT[sid]},setpts=PTS-STARTPTS," + vf subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(clip), "-vf", vf, "-frames:v", str(nframes), *V, str(out)], check=True) used.append(sid) else: cards = cards_for(sid) each = dur / len(cards) inputs = sum((["-loop", "1", "-t", f"{each + 0.1:.3f}", "-i", str(c)] for c in cards), []) fc = "".join(f"[{i}:v]{SCALE},fps={FPS},trim=duration={each:.4f}[v{i}];" for i in range(len(cards))) + \ "".join(f"[v{i}]" for i in range(len(cards))) + f"concat=n={len(cards)}:v=1:a=0,tpad=stop_mode=clone:stop_duration=1[o]" subprocess.run(["ffmpeg", "-v", "error", "-y", *inputs, "-filter_complex", fc, "-map", "[o]", "-frames:v", str(nframes), *V, str(out)], check=True) parts.append(out) lst = SEG / "list.txt" lst.write_text("".join(f"file '{p.name}'\n" for p in parts)) subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", str(lst), "-i", args.song, "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-shortest", args.out], check=True) print(f"wrote {args.out} | video clips: {len(used)}/{len(shots)} shots ({' '.join(used)})")