#!/bin/bash
# build_rtsp_pipeline.sh — Test GStreamer RTSP pipeline on Jetson Orin Nano Super
#
# Usage: ./build_rtsp_pipeline.sh [--software]  (--software = use x264 instead of nvenc)
#
# Tests the GStreamer pipeline that rtsp_server_node.py uses.
# View with: vlc rtsp://jetson-ip:8554/test

set -euo pipefail

USE_NVENC=true
if [[ "${1:-}" == "--software" ]]; then
  USE_NVENC=false
fi

if $USE_NVENC; then
  ENCODER="nvvidconv ! nvv4l2h264enc bitrate=4000000 iframeinterval=30 ! rtph264pay name=pay0 pt=96"
  echo "Using NVENC hardware encoder"
else
  ENCODER="videoconvert ! x264enc bitrate=4000 tune=zerolatency speed-preset=superfast ! rtph264pay name=pay0 pt=96"
  echo "Using software x264 encoder"
fi

echo "Starting test RTSP server on rtsp://0.0.0.0:8554/test"
echo "Connect with: vlc rtsp://$(hostname -I | awk '{print $1}'):8554/test"

gst-launch-1.0 -v \
  videotestsrc pattern=ball ! \
  video/x-raw,width=1920,height=960,framerate=15/1 ! \
  ${ENCODER} ! \
  rtspclientsink location=rtsp://127.0.0.1:8554/test 2>/dev/null || \
gst-rtsp-server-launch \
  "( videotestsrc pattern=ball ! video/x-raw,width=1920,height=960,framerate=15/1 ! ${ENCODER} )" &
echo "Pipeline running. Ctrl+C to stop."
wait
