#!/bin/bash

declare -ga args=()
function + {
	args+=("$@")
}

filter="[1:a][2:a][3:a]amix=inputs=3"
+ -re -f x11grab -r 30 -s
+ $(xrandr | sed -nE '/\bconnected\b/s/^.+ ([0-9x]+)\+.+/\1/p') -i :0
+ -f pulse -i @DEFAULT_MONITOR@

if pactl info | grep -qE '^Default Source: .+\.monitor$'
then filter="[1:a][2:a]amix=inputs=2"
else + -f pulse -i @DEFAULT_SOURCE@
fi

+ -f lavfi -i anoisesrc=colour=white:sample_rate=48000:amplitude=0.0001
+ -filter_complex "$filter:duration=longest:dropout_transition=0[aout]" -map "[aout]" -map 0:v
+ -c:v libx264 -pix_fmt yuv420p -preset ultrafast -tune zerolatency
+ -c:a aac -b:a 128k
+ -movflags +faststart
+ -f rtsp -rtsp_transport tcp
+ $(ip -0 -j a \
	| jq -r '.[]
	| select((.flags|contains(["LOWER_UP", "UP"])) and .operstate == "UP")
	| .address | @base64 | @uri | split("%") | join("-")
	| "rtsp://192.168.0.168:8554/stream/\(.)"'
)
set -x
exec ffmpeg "${args[@]}"
