#!/usr/bin/env bash
#
# shot-extractor.sh
#
# Pulls one frame per second out of a video clip so I can scrub through
# the shot-by-shot composition in a folder instead of in a player.
# Requires ffmpeg.
#
# Usage:   ./shot-extractor.sh <input-file> [output-dir] [fps]
# Example: ./shot-extractor.sh warehouse-scene.mp4 out 2

set -euo pipefail

if [[ $# -lt 1 ]]; then
  echo "usage: $0 <input-file> [output-dir] [fps]" >&2
  exit 1
fi

INPUT="$1"
OUTDIR="${2:-frames}"
FPS="${3:-1}"

if [[ ! -f "$INPUT" ]]; then
  echo "error: input file '$INPUT' not found" >&2
  exit 1
fi

if ! command -v ffmpeg >/dev/null 2>&1; then
  echo "error: ffmpeg not installed" >&2
  exit 1
fi

mkdir -p "$OUTDIR"

base="$(basename "${INPUT%.*}")"

echo "Extracting frames from '$INPUT' at ${FPS} fps into '$OUTDIR/'..."

ffmpeg -hide_banner -loglevel warning \
       -i "$INPUT" \
       -vf "fps=${FPS}" \
       -q:v 3 \
       "${OUTDIR}/${base}_%04d.jpg"

count=$(find "$OUTDIR" -name "${base}_*.jpg" | wc -l)
echo "Done. ${count} frames written to ${OUTDIR}/"
