#!/bin/sh

set -e

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

while getopts 'ame' arg
do
    case ${arg} in
        a) MIC=1; ;;
        m) MON=1; ;;
        e) EONLY=1; ;;
    esac
done

_head_param="\
    -y \
    -loglevel error \
    -hide_banner"

_mon_in="\
        -thread_queue_size 16 \
        -f sndio \
        -i snd/mon"

_mon_proc="\
        -c:a pcm_s16le"

_mic_in="\
        -thread_queue_size 16 \
        -f sndio \
        -i snd/default"

_mic_proc="\
        -af pan='stereo|c0=FL|c1=FL' \
        -c:a pcm_s16le"

_vid_in="\
        -probesize 10000000 \
        -f x11grab \
        -i :0.0"

_vid_proc="\
        -framerate 30 \
        -c:v libx264rgb \
        -crf 0 \
        -qp 0 \
        -framerate 30 \
        -sws_flags neighbor \
        -preset ultrafast \
        -tune zerolatency"

_map=0;

_ffmpeg_map=0
_ffmpeg_param_input="${_vid_in}"
_ffmpeg_param_procs="-map ${_ffmpeg_map}:v ${_vid_proc}"

if [ "${MIC}" ]; then
    _ffmpeg_map=$(( _ffmpeg_map + 1 ))
    _ffmpeg_param_input="${_ffmpeg_param_input} ${_mic_in}"
    _ffmpeg_param_procs="${_ffmpeg_param_procs} -map ${_ffmpeg_map}:a ${_mic_proc}"
fi

if [ "${MON}" ]; then
    _ffmpeg_map=$(( _ffmpeg_map + 1 ))
    _ffmpeg_param_input="${_ffmpeg_param_input} ${_mon_in}"
    _ffmpeg_param_procs="${_ffmpeg_param_procs} -map ${_ffmpeg_map}:a ${_mon_proc}"
fi

_ffmpeg_param="${_ffmpeg_param_input} ${_ffmpeg_param_procs}"

if [ ${MON} ] || [ ${MIC} ]; then
    _audio_encode_param="-filter_complex amix=inputs=${_ffmpeg_map},stereotools=phase=5,compand=attacks=0:points=-80/-115|-35.1/-80|-35/-35|20/20 -c:a aac -b:a 160k"
fi

printf 'Press q to stop.\n'
set -x

ffmpeg \
    ${_head_param} \
    ${_ffmpeg_param} \
    -f nut pipe: \
        | ffmpeg \
            -hide_banner \
            -y \
            -i pipe: \
            -c:v libx265 \
            -crf 28 \
            -s 1920x1080 \
            -preset veryfast \
            -movflags faststart \
            -threads 8 \
            ${_audio_encode_param} \
            "${_outfile}"

set +x
printf '%s\n' "${_outfile}"
