#!/usr/bin/env sh
# Record a screencast on X11 using ffmpeg
#
# ffmpeg-screencast [<flags>]
#
# Flag | Description
# ---- | -----------
# -w   | Will prompt to click on existing window;
#      | recording will be limited to coordinates of that window.
# -a   | Do not record audio.
# -r   | Change the default framerate of 30.
# -h   | Show this help.

target='root'
framerate=30
now=$(date --rfc-3339=date)

while getopts war:h opt; do
    case $opt in
    w) target='frame';;
    a) noaudio=1;;
    r) framerate="$OPTARG";;
    h) awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
       exit;;
    esac
done
shift $(( OPTIND - 1 ))

xwininfo -stats "-${target}" \
    | awk -F':' '
        /Absolute.*X/ { x=$2 }
        /Absolute.*Y/ { y=$2 }
        /Width/ { w=$2 }
        /Height/ { h=$2 }
        END { print w, h, x, y }' \
    | while read -r sizex sizey offsetx offsety; do
        ffmpeg -f pulse -ac 2 -i default \
            -f x11grab -r "$framerate" \
            -s "${sizex}x${sizey}" \
            -i "${DISPLAY}+${offsetx},${offsety}" \
            -c:v libvpx -minrate 1M -maxrate 1M -b:v 1M -c:a libvorbis \
            ${noaudio:+-an} \
            -y "${HOME}/screencast-${now}.webm"

            # webm or h264?
            # -acodec pcm_s16le ${noaudio:+-an} \
            # -vcodec libx264 -preset ultrafast \
            # -y "${HOME}/screencast-${now}.mkv"
    done
