#!/bin/sh
# camv: preview /dev/video0; s to start recording, q to stop.
#   camv              -> /tmp/cam-<date>.mp4
#   camv movie.mp4    -> save to that path

out=${1:-/tmp/cam-$(date +%Y%m%d-%H%M%S).mp4}
raw=$(mktemp --suffix=.mkv)
conf=$(mktemp)
trap 'rm -f "$conf" "$raw"' EXIT

printf 's set stream-record "%s" ; show-text REC\n' "$raw" > "$conf"

mpv av://v4l2:/dev/video0 \
    --demuxer-lavf-format=video4linux2 \
    --demuxer-lavf-o=input_format=mjpeg,video_size=640x480 \
    --profile=low-latency \
    --force-window=immediate \
    --geometry=50%:50% \
    --input-conf="$conf" \
    --title=camv --osd-msg1="s: rec   q: stop" \
    --really-quiet 2>/dev/null

[ -s "$raw" ] || exit 0

ffmpeg -hide_banner -loglevel fatal -nostdin \
    -vaapi_device /dev/dri/renderD128 -i "$raw" \
    -vf 'format=nv12,hwupload' \
    -c:v h264_vaapi -qp 28 -y "$out"
echo "$out"
