#!/usr/bin/env bash
# normalize_hero.sh <clip.mp4> [fps]
#
# Normalize a hero lip-sync clip to CFR fps (default 24) + even dimensions,
# in place.
#
# Load-bearing, and easy to forget when the clip came from Magnific by hand:
# OmniHuman returns 25 fps, and the music-video assembler cuts with frame-accurate
# `-ss` / `-frames:v`, which lands on the WRONG FRAME against a 25 fps source.
# `vclaw video lipsync` does this automatically; the Magnific path bypasses it.
# Idempotent — a clip already at the target fps is left alone.
set -euo pipefail

CLIP="${1:-}"; FPS="${2:-24}"
[ -n "$CLIP" ] || { echo "usage: normalize_hero.sh <clip.mp4> [fps]" >&2; exit 1; }
[ -f "$CLIP" ] || { echo "normalize_hero: not found: $CLIP" >&2; exit 1; }

have_fps="$(ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate \
  -of default=nk=1:nw=1 "$CLIP" | head -1)"
if [ "$have_fps" = "$FPS/1" ]; then
  echo "normalize_hero: $CLIP already CFR ${FPS} — nothing to do" >&2
  exit 0
fi

TMP="${CLIP%.mp4}.norm.mp4"
ffmpeg -v error -y -nostdin -i "$CLIP" \
  -vf "fps=${FPS},scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1" \
  -c:v libx264 -crf 18 -preset medium -pix_fmt yuv420p \
  -c:a aac -b:a 192k -movflags +faststart "$TMP"
mv -f "$TMP" "$CLIP"
echo "normalize_hero: $CLIP -> CFR ${FPS} (was ${have_fps})" >&2
