#! /usr/bin/env nix-shell
#! nix-shell -i bash -p ffmpeg
#
# https://wiki.archlinux.org/index.php/Streaming_to_twitch.tv

FILE=$(date +%Y.%m.%d..%H.%M)

INRES="1920x1080"
OUTRES="1920x1080"
FPS="15"
GOP="30"
GOPMIN="15"
THREADS="2"
CBR="1000k"
QUALITY="ultrafast"
AUDIO_RATE="44100"
KEY=$(pass internet/twitch.tv-key)
SERVER="live-lax"

ffmpeg \
  -f alsa -i default \
  -f x11grab -s "$INRES" -r "$FPS" -i :0.0 \
  -f video4linux2 -i /dev/video0 \
  -filter_complex '[2:v]scale=480:-1[cam];[1:v][cam]overlay=W-w-10:H-h-10' \
  -f flv "rtmp://$SERVER.twitch.tv/app/$KEY"
  -c:v libx264 \
  -preset veryfast \
  -maxrate 1984k \
  -bufsize 3968k \
  -g "$GOP" \
  -keyint_min "$GOPMIN" \
  -b:v "$CBR" \
  -minrate "$CBR" \
  -maxrate "$CBR" \
  -pix_fmt yuv420p \
  -s "$OUTRES" \
  -preset "$QUALITY" \
  -tune film \
  -crf:v 18 \
  -c:a libmp3lame \
  -b:a 128k \
  -threads "$THREADS" \
  -strict normal \
  -bufsize "$CBR" \
  -ar "$AUDIO_RATE" \
  -ac 2 \