#!/usr/bin/env bash
# publish.sh — M1 PoC test publisher.
#
# Generates a synthetic test pattern + sine tone, encodes to H.264
# baseline (PT=102) and Opus (PT=111), then sends both RTP streams
# muxed on a single UDP port to match the M1 webrtc-poc server, which
# reads one UDP port and dispatches by payload type.
#
# Usage:
#   ./test/publish.sh [host] [port]
#
# Defaults: host=127.0.0.1 port=10000
set -euo pipefail

HOST="${1:-127.0.0.1}"
PORT="${2:-10000}"

echo "publishing test pattern + tone to rtp://${HOST}:${PORT}"
echo "video PT=102 (H.264 baseline), audio PT=111 (Opus)"
echo "press Ctrl-C to stop."

# -re                   real-time pace (wall-clock)
# testsrc / sine        synthetic A/V so no devices needed
# libx264 baseline      widely compatible profile for WebRTC
# -tune zerolatency     minimize encoder buffering
# -bsf:v h264_mp4toannexb  ensure Annex-B for RTP packetization
# -payload_type 102/111 match the hard-coded PTs in forward.go
# -f rtp_mpegts fails   (we need plain rtp, not mpegts-in-rtp)
# Using two separate -f rtp outputs, both to the same UDP port.
# FFmpeg 4.x requires an SDP file per output; we write them to /tmp
# but the server doesn't use them — it only cares about PT.
exec ffmpeg -hide_banner -loglevel warning \
  -re \
  -f lavfi -i "testsrc2=size=640x360:rate=30" \
  -f lavfi -i "sine=frequency=440:sample_rate=48000" \
  -map 0:v:0 \
    -c:v libx264 -profile:v baseline -preset veryfast -tune zerolatency \
    -g 30 -keyint_min 30 -x264-params "repeat-headers=1" \
    -pix_fmt yuv420p \
    -bsf:v h264_mp4toannexb \
    -payload_type 102 \
    -f rtp "rtp://${HOST}:${PORT}?pkt_size=1200" \
  -map 1:a:0 \
    -c:a libopus -b:a 64k -ar 48000 -ac 2 \
    -payload_type 111 \
    -f rtp "rtp://${HOST}:${PORT}?pkt_size=1200"
