#!/bin/sh

# Receive RTP video and audio streams

set -e
CAMIP=${CAMIP:-$1} # origin host - default: use multicast group
ACOUNT=${ACOUNT:-${2:-0}} # number of audio stream(s) to play - default: 0
VCOUNT=${VCOUNT:-${3:-1}} # number of video stream(s) to display - default: 1
AFORMAT=${AFORMAT:-$4} # AMR OPUS RAW - default: RAW
VFORMAT=${VFORMAT:-$5} # H264 VP8 RAW - default: RAW
ASINK=${ASINK:-autoaudiosink}
VSINK=${VSINK:-autovideosink}
set -u

# set multicast groups (also for recorder host) if camera host is wildcard
[ -n "$CAMIP" ] || RECMIP=239.255.0.1
[ -n "$CAMIP" ] || CAMMIP=239.255.0.2
RECHOST="${RECMIP:+address=$RECMIP auto-multicast=true}"
CAMHOST="${CAMIP:+host=$CAMIP}${CAMMIP:+host=$CAMMIP auto-multicast=true}"

# http://stackoverflow.com/a/42237307
ABUFFERS=80000
NETLATENCY=20

case "$AFORMAT" in
 AMR)
  ACAPS=application/x-rtp,media=audio,clock-rate=8000,encoding-name=AMR,encoding-params="(string)1",octet-align="(string)1",payload=96
  ADEC="rtpamrdepay ! amrnbdec"
  ;;
 OPUS)
  ACAPS=audio/x-raw,rate=48000,channels=1,format=S16LE,layout=interleaved
  ADEC="rtpopusdepay ! opusdec"
  ;;
 RAW|'')
  ACAPS=application/x-rtp,media=audio,clock-rate=44100,encoding-name=L16,encoding-params=1,channels=1,payload=96
  ADEC="rtpL16depay"
  ;;
 *)
  echo "ERROR: Unsupported audio format: \"$AFORMAT\""
  exit 1
  ;;
esac

case "$VFORMAT" in
 H264)
  VCAPS=application/x-rtp,media=video,clock-rate=90000,payload=96,encoding-name=H264
  VDEC="rtph264depay ! avdec_h264"
  ;;
 VP8)
  VCAPS=application/x-rtp,media=video,clock-rate=90000,payload=96,encoding-name=VP8
  VDEC="rtpvp8depay ! vp8dec"
  ;;
 RAW|'')
  VCAPS=application/x-rtp,media=video,clock-rate=90000,encoding-name=RAW,sampling=YCbCr-4:2:0,depth="(string)8",width="(string)432",height="(string)240",payload=96,a-framerate=30
  VDEC="rtpvrawdepay ! videoconvert ! queue"
  ;;
 *)
  echo "ERROR: Unsupported video format: \"$VFORMAT\""
  exit 1
  ;;
esac

stream() {
 ID=$1
 CAPS=$2
 SINK=$3
 echo \
 udpsrc port=$((5000+ID-1)) $RECHOST caps=\""$CAPS"\" \
  ! rtpbin."recv_rtp_sink_$ID" rtpbin. \
  ! $SINK \
 udpsrc port=$((5010+ID-1)) $RECHOST \
  ! rtpbin."recv_rtcp_sink_$ID" \
 rtpbin."send_rtcp_src_$ID" \
  ! udpsink port=$((5020+ID-1)) $CAMHOST sync=false async=false
}

gst-launch-1.0 -v \
 rtpbin name=rtpbin latency=$NETLATENCY drop-on-latency=true \
 $(n=0;\
  for i in $(seq "$ACOUNT"); do n=$((n+1)); stream "$n" "$ACAPS" "$ADEC ! $ASINK buffer-time=$ABUFFERS"; done;\
  for i in $(seq "$VCOUNT"); do n=$((n+1)); stream "$n" "$VCAPS" "$VDEC ! $VSINK"; done;\
 )