#!/bin/bash
#
# FFMPEG SCRIPT FOR OBS VIRTUAL CAMERA under LINUX
# BY DG0OPK MARC-MAY 2021
#

# OUTPUT IP address and port for ADALM PLUTO
ip="192.168.xxx.xxx:8282"   

# SET TS OVERALL DATARATE
# use it with TS 960 -> 960Kbit/s   SR 1000K QPSK 1/3, SR 500 8PSK 2/3
# use it with TS 480 -> 480Kbit/s   SR 500 QPSK 1/2, SR333 QPSK 3/4, SR 250 8PSK 2/3 for **** QRP DATV ****
# use it with TS 320 -> 320Kbit/s   SR 500 QPSK 1/3, SR333 QPSK 1/2, SR250 QPSK 2/3, SR125 8PSK 8/9 for **** QRP DATV ****
TS="480"


# SET AUDIO DATARATE AND AUDIO SAMPLE RATE and CHANNELS
# AUDIO_RATE=64000 or more and AUDIO_SAMPLE_RATE=44100 it with TS 960
# AUDIO_RATE=32000 and AUDIO_SAMPLE_RATE=22050 it with TS 480 and TS 320
AUDIO_RATE="32000"
AUDIO_SAMPLE_RATE="22050"
AUDIO_CHAN="2"

#SET frames per second
#use FPS=25 or 15 or 10 (lower FPS gives better quality but lower timing resolution)
FPS="25"

# define VIDEO_FACTOR for best fitting of the stream to lower nullpackets
#  maybe 830 for  TS 320
#  maybe 870 for  TS 480
#  maybe 920 for  TS 960

VIDEO_FACTOR="850"


# AUDIO_RATE_K=$AUDIO_RATE*1000
TSBITRATE=$(($TS*1000))
TS_NO_AUDIO=$(($TSBITRATE-$AUDIO_RATE))
VIDEORATE=$(($TS_NO_AUDIO*$VIDEO_FACTOR/1000))
echo "****** USED PARAMETERS *******"
echo "TS-BITRATE:" $TSBITRATE
echo "AUDIORATE: "  $AUDIO_RATE
echo "TS-NOAUDIO:" $TS_NO_AUDIO
echo "VIDEORATE: "  $VIDEORATE
echo "******************************"

# KEYINT defines the delay for decoding picture after STREAM start, 
# for FPS*3 that means 3s, lower this if you need but maybe a loss in quality of picture, "0" for auto
KEYINT="0"

# SET VIDEO OUTPUT RESOLTUTION
#
# RESOLUTION="480x272"
# RESOLUTION="640x360"
# RESOLUTION="698x392"
# RESOLUTION="768x432"
# RESOLUTION="852x480"
# RESOLUTION="960x540" 
# RESOLUTION="1024x576"
RESOLUTION="1280x720" 
# RESOLUTION="1366x768"
# RESOLUTION="1600x900"
# RESOLUTION="1920x1080"
# RESOLUTION="2560x1440"

ffmpeg -f v4l2 -i /dev/video0 -thread_queue_size 256 -f pulse -i default -maxrate "$VIDEORATE" -bufsize "$VIDEORATE" -pix_fmt yuv420p -b:v "$VIDEORATE"  -vf: scale="$RESOLUTION" -r "$FPS" -c:v libx265 -preset fast -tune zerolatency -aspect 16:9 -profile:v main -x265-params bitrate="$VIDEORATE":"$KEYINT" -acodec aac -aac_coder twoloop -ac "$AUDIO_CHAN" -ar "$AUDIO_SAMPLE_RATE" -b:a "$AUDIO_RATE" \
-f mpegts -muxrate "$TSBITRATE" -streamid 0:256 -streamid 1:257  -max_delay 2500000 -pcr_period 40 -pat_period 0.4 \
udp://"$ip"?pkt_size=1316

