#!/bin/bash
## © University of Southampton IT Innovation Centre, 2018
##
## Copyright in this software belongs to University of Southampton
## IT Innovation Centre of Gamma House, Enterprise Road, 
## Chilworth Science Park, Southampton, SO16 7NS, UK.
##
## This software may not be used, sold, licensed, transferred, copied
## or reproduced in whole or in part in any manner or form or in or
## on any media by any person other than in accordance with the terms
## of the Licence Agreement supplied with the software, or otherwise
## without the prior written consent of the copyright owners.
##
## This software is distributed WITHOUT ANY WARRANTY, without even the
## implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE, except where stated in the Licence Agreement supplied with
## the software.
##
##      Created By :            Michael Boniface
##      Created Date :          09-02-2018
##      Created for Project :   FLAME

#
# Bento4 must be manually obtained from https://www.bento4.com/downloads/ ffmpeg can be installed as follows 
# (Debian - http://www.deb-multimedia.org/) ~$ 
# sudo echo deb http://www.deb-multimedia.org jessie main non-free >> /etc/apt/sources.list
# ~$ sudo apt update ~$ sudo apt install deb-multimedia-keyring ~$ sudo apt update && sudo apt-get dist-upgrade
#
# First encode the video to 24fps!!! and MP4 (h.264)
#
# Video MP4 file
INPUT=$1
OUTPUT_iFRAMES="$1-iFrames.mp4"
OUTPUT_FRAGMENTED="$OUTPUT_iFRAMES-Fragmented.mp4"

OUTPUT_FOLDER_NAME=$(date +%Y%m%d%H%M%S)$1
echo "OUTPUT_FOLDER_NAME: "$OUTPUT_FOLDER_NAME

rm -rf $OUTPUT_FOLDER_NAME
mkdir $OUTPUT_FOLDER_NAME

# Insert Correct number of I frames
#ffmpeg -y -i $INPUT -profile:v baseline -level 3.0 -c:a libfdk_aac -ac 2 -ab 128k -c:v libx264 -x264opts 'keyint=24:min-keyint=24:no-scenecut' -b:v 400k -maxrate 400k -bufsize 1000k -vf "scale=-1:360" $OUTPUT_iFRAMES

ffmpeg -y -i $INPUT -profile:v baseline -level 3.0 -c:a aac -ac 2 -ab 128k -c:v libx264 -x264opts 'keyint=24:min-keyint=24:no-scenecut' -b:v 400k -maxrate 400k -bufsize 1000k -vf "scale=-1:360" -strict experimental $OUTPUT_FOLDER_NAME"/"$OUTPUT_iFRAMES

# fragment MP4
/opt/Bento4-SDK-1-5-1-621.x86_64-unknown-linux/bin/mp4fragment --timescale 1000 $OUTPUT_FOLDER_NAME"/"$OUTPUT_iFRAMES $OUTPUT_FOLDER_NAME"/"$OUTPUT_FRAGMENTED

# Option 1 with Bento4
/opt/Bento4-SDK-1-5-1-621.x86_64-unknown-linux/bin/mp4dash --mpd-name=stream.mpd --use-segment-list --use-compat-namespace -o $OUTPUT_FOLDER_NAME"/"$OUTPUT_FOLDER_NAME $OUTPUT_FOLDER_NAME"/"$OUTPUT_FRAGMENTED 

cd $OUTPUT_FOLDER_NAME
tar -cvzf $OUTPUT_FOLDER_NAME".gz" $OUTPUT_FOLDER_NAME