#!/bin/bash
# Deliver mixer1 output to file.
#
# Comment out width and height settings to set width and height to Snowmix system geometry
#width=512
#height=288

ext=avi
MUXER=avimux
if [ $# -gt 0 ] ; then
  if [ X$1 = Xavi ] ; then
    ext=avi
    MUXER=avimux
  else
    if [ X$1 = Xmp4 ] ; then
      ext=mp4
      MUXER=mp4mux
    else
      if [ X$1 = Xts ] ; then
        ext=ts
        MUXER=mpegtsmux
      else
       echo "parameter error. Usage : $0 [avi | mp4 | ts]"
       exit 1
      fi
    fi
  fi
fi
  

# IMPORTANT >>>>>You need to get port, ip and feed_id right<<<<<
if [ "X$SNOWMIX" = X ] ; then
  echo "You need to set the SNOWMIX environment variable to the base of the Snowmix installed directory"
  exit 1
fi
if [ "X$SNOWMIX_PORT" = X ] ; then export SNOWMIX_PORT=9999 ;fi
if [ "X$SNOWMIX_IP" = X ] ; then export SNOWMIX_IP=127.0.0.1 ;fi

# Check for the snowmix and gstreamer settings
if [ ! -f $SNOWMIX/scripts/gstreamer-settings -o ! -f $SNOWMIX/scripts/snowmix-settings ] ; then
  echo "Can not find the scripts/gstreamer-settings or the scripts/snowmix-settings in the directory set by the SNOWMIX environment variable"
  exit 1
fi

# Load the Snowmix and GStreamer settings
. $SNOWMIX/scripts/gstreamer-settings
. $SNOWMIX/scripts/snowmix-settings
# This will set
# a) feed_rate
# b) feed_channels
# c) feed_control_pipe
# d) feed_width
# e) feed_height
# f) ctrsocket
# g) system_width
# h) system_height
# i) ratefraction
# j) snowmix
# k) channels
# l) rate

if [ X$ctrsocket = X -o X$system_width = X -o X$system_height = X ] ; then
  echo Failed to get control pipe or width or height from running snowmix
  exit 1
fi

if [ X$video_format = XRGBA ] ; then
  VIDEO_PREPEND=$VIDEORGBA
else
  if [ X$video_format = XBGRA ] ; then
    VIDEO_PREPEND=$VIDEOBGRA
  else
    echo "ERROR. video_format not set to either RGBA or BGRA"
    exit 1
  fi
fi
VIDEOFORMAT=$VIDEO_PREPEND',width='$system_width',height='$system_height',framerate='$ratefraction
VIDEOFORMAT=$VIDEO_PREPEND',width='$system_width',height='$system_height',framerate=30/1'

i=0
file=snowmix-$i.$ext
while true ; do
  if [ -s $file ] ; then
    i=`expr $i + 1`
    file=snowmix-$i.$ext
  else
    $gstlaunch -e -v shmsrc socket-path=$ctrsocket do-timestamp=true is-live=true ! \
	queue leaky=0		! \
	$VIDEOFORMAT            ! \
    	$VIDEOCONVERT		! \
	videoscale		! \
    	x264enc bitrate=8000 tune=zerolatency speed-preset=2 ! \
	h264parse		! \
    	$MUXER			! \
	queue			! \
    	filesink location=$file
    sleep 1
  fi
done
