#!/bin/sh
# cam: snap a frame from /dev/video0. press s to capture, q to cancel.
#   cam              -> clipboard
#   cam photo.png    -> file

if [ -n "$1" ]; then
    out=$1
    keep=1
else
    out=$(mktemp --suffix=.png)
    keep=
fi
conf=$(mktemp)
trap 'rm -f "$conf"; [ -z "$keep" ] && rm -f "$out"' EXIT

printf 's screenshot-to-file "%s" ; quit\n' "$out" > "$conf"

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

[ -s "$out" ] || exit 0
[ -n "$keep" ] && exit 0

xclip -selection clipboard -t image/png -loops 1 < "$out" &
sleep 0.1
