#!/bin/bash
#Get the next PTS to timeIN in specified type stream
#
#This script requires ffmpeg (ffmpeg, ffprobe) and libxml2-utils (xmllint)
#
#Version: 1.0
#
#Usage:
# getnextpts source timeIN video/audio
#
#Examples:
# getnextpts in.ts 1.2 video
#
# getnextpts in.ts 3.0 audio

#Set global vars 
#----------------------------
ffprobe="ffprobe"
xmllint="xmllint"
getinfoparams="-print_format xml -show_packets"

#Set in vars
#----------------------------
source=$1
timeIN=$2
streamtype=$3

#Set intermediate files 
#----------------------------
sourceinfoxml=${source}.packets.xml

#Clean
#----------------------------
rm -f $sourceinfoxml
.
#Create video information file
#----------------------------
${ffprobe} $source ${getinfoparams} > ${sourceinfoxml}
if [ "$?" != "0" ]; then
	echo "Error getting TS information!" 1>&2
	exit 1
fi

#Get fisrt pts in TS file (any stream type!)
#----------------------------
#TODO: Use function min to ensure that the returned PTS is the minimum
startpts=$(${xmllint} --xpath "string(//ffprobe/packets/packet[@pts_time>=0]/@pts_time)" ${sourceinfoxml})

timeINnorm=$(bc <<< "scale=0;${startpts}+${timeIN}")

#Get next pts data to timeIN in specified stream type
#----------------------------
nextpts=$(${xmllint} --xpath "string(//ffprobe/packets/packet[@codec_type='${streamtype}' and @pts_time>${timeINnorm}]/@pts_time)" ${sourceinfoxml})

#Normalize to 0
#----------------------------
nextptsn=$(bc <<< "scale=0;${nextpts}-${startpts}")

#To check (to stderr)
#----------------------------
#echo "First PTS in file: $startpts" 1>&2
#echo "Timein in file: $timeINnorm" 1>&2
#echo "Next PTS in file: $nextpts" 1>&2	

#Return param
#----------------------------
echo "$nextptsn"	
