home/bin/record (view raw)
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | #!/bin/sh
# stolen from mitch weaver
: "${RECORD_FRAMERATE:=30}"
: "${RECORD_OUTPUT_DIR:=$PWD}"
mkdir -p /tmp/record
sock=/tmp/record/sock
pidfile=/tmp/record/pidfile
msg() { printf '* %s\n' "$*" ; }
die() { >&2 msg "$*" ; exit 1 ; }
usage() {
    die "Usage: ${0##*/} [-o output dir] [-r rate] [-f foreground]"
}
isrunning() { kill -0 "$(getpid)" 2>/dev/null ; return $? ; }
getpid() {
    [ -s $pidfile ] && read -r pid <$pidfile
    echo "${pid:-?}"
}
start() {
    isrunning && die "Another instance already exists: $(getpid)"
    file="$RECORD_OUTPUT_DIR/record-$(date "+%Y.%m.%d-%H:%M:%S").mp4"
    :>$sock
    if command -v xrectsel >/dev/null ; then
        xrectsel -f '%x %y %w %h'
    elif command -v slop >/dev/null ; then
        slop -f '%x %y %w %h'
    else
        die 'Needs xrectsel or slop'
    fi | {
        read -r x y w h
        <$sock ffmpeg -y -f x11grab -s "${w}x${h}" -r $RECORD_FRAMERATE \
        -i "${DISPLAY:-:0}+${x},${y}" -vcodec libx264 \
        -pix_fmt yuv420p -filter:v "crop=iw-mod(iw\\,2):ih-mod(ih\\,2)" \
        "$file" >/tmp/record/log 2>&1 &
        msg "recording on pid $!"
        if ${FOREGROUND:-false} ; then
            trap 'rm "$sock" /tmp/record/log 2>/dev/null ||: ; rmdir /tmp/record 2>/dev/null ||:' EXIT INT TERM
            wait
        else
            echo $! >$pidfile
            echo "$file" >/tmp/record/file
        fi
    }
}
end() {
    if isrunning ; then
        echo q >>$sock
        read -r name </tmp/record/file
        msg "Success! Saved as $name"
        rm /tmp/record/* 2>/dev/null ||:
        rmdir /tmp/record 2>/dev/null ||:
        exit
    else
        die 'Nothing being recorded.'
    fi
}
toggle() {
    if isrunning ; then
        end
    else
        start
    fi
}
while [ "$1" ] ; do
    case $1 in
        -f)
            FOREGROUND=true
            ;;
        -r)
            RECORD_FRAMERATE=$1
            ;;
        -o)
            [ -d "$2" ] || usage
            RECORD_OUTPUT_DIR=$2
            shift
            ;;
         *) usage
    esac
    shift
done
toggle
 |