#!/bin/sh
set -e

doas rcctl set sndiod flags -f rsnd/0 -m play -s play -m mon -s mon -F rsnd/1 -m rec -s rec
doas rcctl restart sndiod
export AUDIOPLAYDEVICE=snd/0.play
export AUDIOMONDEVICE=snd/0.mon
export AUDIORECDEVICE=snd/1.rec

_vidfile="/home/sdk/rec-screen.mkv"
_outfile="/home/sdk/rec-encoded-$(date "+%Y%m%d_%H%M%S").mp4"

_res="1920x1080"
_fps="24"

_mon_dev="snd/mon"
_mic_dev="snd/rec"

_mon_in="-thread_queue_size 16  -use_wallclock_as_timestamps 1 -f sndio -i ${_mon_dev}"
_mon_proc="-c:a pcm_s16le"

_mic_in="-thread_queue_size 16 -use_wallclock_as_timestamps 1 -f sndio -i ${_mic_dev}"
_mic_proc="-af pan='stereo|c0=FL|c1=FL' -c:a pcm_s16le"

_vid_in="-framerate ${_fps} -f x11grab -i :0.0"
_vid_proc="-c:v libx264rgb -crf 0 -qp 0 -framerate ${_fps} -sws_flags neighbor -preset ultrafast -tune zerolatency"

_ffmpeg_param="${_vid_in} ${_mic_in} ${_mon_in} -map 0:v ${_vid_proc} -map 1:a ${_mic_proc} -map 2:a ${_mon_proc}"

printf 'Press q to stop.\n'
set -x
ffmpeg -y -loglevel error -hide_banner ${_ffmpeg_param} "${_vidfile}"
set +x

# # with audio?
# [ "$1" == "-a" ] \
#     && _audio_encode_param="-filter_complex amix=inputs=2,stereotools=phase=5,compand=attacks=0:points=-80/-115|-35.1/-80|-35/-35|20/20 -c:a aac -b:a 160k"
_audio_encode_param="-filter_complex amix=inputs=2,stereotools=phase=5,compand=attacks=0:points=-80/-115|-35.1/-80|-35/-35|20/20 -c:a aac -b:a 160k"

printf 'Encoding...\n'
set -x
ffmpeg -hide_banner -y \
    -i "${_vidfile}" \
    -c:v libx264 \
    -crf 28 \
    -s ${_res} \
    -preset veryfast \
    -movflags faststart \
    -threads 12 \
    ${_audio_encode_param} \
    "${_outfile}"
set +x
printf '%s\n' "${_outfile}"


doas rcctl set sndiod flags -f rsnd/0 -F rsnd/1 -F rsnd/2 -F rsnd/3 -F rsnd/4 -F rsnd/5 -m play -s default
doas rcctl restart sndiod

unset AUDIOPLAYDEVICE
unset AUDIORECDEVICE
