#!/usr/bin/env bash
# Capture the virtual display + null-sink audio, push to YouTube.
# GPU=1 uses NVENC and allows a higher bitrate.
set -u
BASE="$(cd "$(dirname "$0")" && pwd)"
source "$BASE/stream.env"
export DISPLAY=":${DISPLAY_NUM}"
RW="${RENDER_WIDTH:-854}"; RH="${RENDER_HEIGHT:-480}"
GPU="${GPU:-0}"
export XDG_RUNTIME_DIR="/run/user/$(id -u)"
export PULSE_SERVER="unix:${XDG_RUNTIME_DIR}/pulse/native"

# wait for the display to exist
for i in $(seq 1 60); do xdpyinfo >/dev/null 2>&1 && break; sleep 2; done

if [ "$GPU" = "1" ]; then
  VCODEC=(-c:v h264_nvenc -preset p4 -tune ll -rc cbr)
  NICE=()
else
  # CPU-only: single thread + niced so the game gets the cores. Do NOT upscale.
  VCODEC=(-c:v libx264 -preset ultrafast -tune zerolatency -threads 1)
  NICE=(nice -n 15)
fi

exec "${NICE[@]}" ffmpeg -hide_banner -loglevel warning \
  -thread_queue_size 1024 -f x11grab -framerate "$FPS" -video_size "${RW}x${RH}" -i "${DISPLAY}.0" \
  -thread_queue_size 1024 -f pulse -i tf2sink.monitor \
  "${VCODEC[@]}" -pix_fmt yuv420p \
  -g $((FPS*2)) -keyint_min "$FPS" \
  -b:v "$VIDEO_BITRATE" -maxrate "$VIDEO_BITRATE" -bufsize 5000k \
  -c:a aac -b:a "$AUDIO_BITRATE" -ar 44100 -ac 2 \
  -f flv "${YT_INGEST}/${YT_KEY}" \
  >"$BASE/logs/ffmpeg.log" 2>&1
