#!/bin/sh


audio() {
    # set mixer controls
    print configuring microphone
    mixerctl -q record.adc-0:1_source=mic2
    mixerctl -q record.adc-2:3_source=mic2
    mixerctl -q inputs.mix_source=mic2
}


webcam() {
    printf 'start webcam\n'
    doas mpv --quiet \
        --panscan=1 \
        --framedrop=vo \
        --ontop av://v4l2:/dev/video0 \
        --profile=low-latency \
        --untimed \
        --vf=hflip \
        --geometry=220x180 2>&1 > /dev/null &
    print move the picture to the right place and press any key
    read
}


capture() {
    printf 'starting recording... press q to stop\n'
    RES=$(xwininfo -root | grep 'geometry' | awk '{print $2;}' |cut -d"+" -f1)
    ffmpeg -y -loglevel warning \
        -thread_queue_size 256 \
        -probesize 10000000 \
        -hide_banner \
        -f sndio \
        -i default \
        -c:a flac \
        -f x11grab \
        -s $RES \
        -i :0.0 \
        -r 25 \
        -c:v libx265 \
        -crf 0 \
        -qp 0 \
        -preset ultrafast \
        -g 50 \
        -keyint_min 25 \
        $HOME/work/rec_screen.mkv
}

encode() {
    printf 'encoding video\n'
    ffmpeg -y \
        -i $HOME/work/rec_screen.mkv \
        -c:v libx265 \
        -crf 21 \
        -s 1920x1080 \
        -preset medium \
        $HOME/work/rec_screen.mp4
}

printf '
(1) desktop only (works on linux)
(2) desktop + audio
(3) desktop + webcam + audio
'
printf ": "
read sel

case $sel in
    1)  capture; 
        encode;
        ;;
    2)  audio;
        capture;
        encode;
        ;;
    3)  audio;
        webcam;
        capture;
        encode;
        ;;
esac
