for arg in "$@"; do
key=$(echo $arg | cut -f1 -d=)
value=$(echo $arg | cut -f2 -d=)
case "$key" in
-i | --inputfile)
if [ "${value}" = "-i" ]; then
inputfile=""
else
inputfile="$(echo -e "${value}" | tr -d '[:space:]')"
fi
;;
-o | --outputfolder)
if [ "${value}" = "-o" ]; then
outputfolder=""
else
outputfolder="$(echo -e "${value}" | tr -d '[:space:]')"
fi
;;
-h)
echo $'\n'
echo " Script to convert mp4 into adaptive or hls stream(\"*.m3u8\")"
echo $'\n'
echo " Arguments"
echo ''
echo " Argument Name Type Details"
echo ''
echo " -i | --inputfile REQUIRED Input File Location(only \".mp4\" supported)"
echo " -o | --outputfolder NOT REQUIRED Output Folder Location(default to \"inputfile_output\")"
echo $'\n'
exit 0
;;
*) ;;
esac
done
if [ "${inputfile}" = "" ]; then
echo "Input file is required as an argument. Use -i or --inputfile to provide it."
exit 1
elif [ ! -f "${inputfile}" ]; then
echo "File ${inputfile} does not exists"
exit 1
fi
file=$(basename -- "${inputfile}")
extension="${file##*.}"
filename="${file%.*}"
if [ "${extension}" != "mp4" ]; then
echo "Only mp4 files are allowed"
exit 1
fi
os="$(uname -s)"
case "${os}" in
Linux*)
echo $(dpkg-query -W -f'${Status}' "$pkg" 2>/dev/null | grep -q "ok installed" || sudo apt install ffmpeg)
;;
Darwin*)
echo $(brew list ffmpeg &>/dev/null || brew install ffmpeg)
;;
*)
echo "ffmpeg needs to be installed for this to work"
;;
esac
if [ ! -d ${outputfolder} ] || [ "${outputfolder}" = "" ]; then
outputfolder="${filename}_output"
echo $(mkdir "${outputfolder}")
fi
ffmpeg -i "${inputfile}" \
-filter_complex \
"[0:v]split=4[v1][v2][v3][v4]; \
[v1]scale=w=1920:h=1080[v1out]; \
[v2]scale=w=1280:h=720[v2out]; \
[v3]scale=w=854:h=480[v3out]; \
[v4]scale=w=640:h=360[v4out]" \
\
-map [v1out] -c:v:0 libx264 -x264-params \
"nal-hrd=cbr:force-cfr=1" -b:v:0 10M -maxrate:v:0 10M -minrate:v:0 10M \
-bufsize:v:0 10M -preset slow -g 48 -sc_threshold 0 -keyint_min 48 \
\
-map [v2out] -c:v:1 libx264 -x264-params \
"nal-hrd=cbr:force-cfr=1" -b:v:0 5M -maxrate:v:0 5M -minrate:v:0 5M \
-bufsize:v:0 5M -preset slow -g 48 -sc_threshold 0 -keyint_min 48 \
\
-map [v3out] -c:v:2 libx264 -x264-params \
"nal-hrd=cbr:force-cfr=1" -b:v:0 3M -maxrate:v:0 3M -minrate:v:0 3M \
-bufsize:v:0 3M -preset slow -g 48 -sc_threshold 0 -keyint_min 48 \
\
-map [v4out] -c:v:3 libx264 -x264-params \
"nal-hrd=cbr:force-cfr=1" -b:v:0 1M -maxrate:v:0 1M -minrate:v:0 1M \
-bufsize:v:0 1M -preset slow -g 48 -sc_threshold 0 -keyint_min 48 \
\
-map a:0 -c:a:0 aac -b:a:0 96k -ac 2 \
-map a:0 -c:a:1 aac -b:a:1 96k -ac 2 \
-map a:0 -c:a:2 aac -b:a:2 48k -ac 2 \
-map a:0 -c:a:3 aac -b:a:3 48k -ac 2 \
\
-f hls \
-hls_time 2 \
-hls_playlist_type vod \
-hls_flags independent_segments \
-hls_segment_type mpegts \
-hls_segment_filename "${outputfolder}/${filename}_%v/data%04d.ts" \
\
-master_pl_name "${filename}.m3u8" \
-var_stream_map "v:0,a:0 v:1,a:1 v:2,a:2 v:3,a:3" "${outputfolder}/${filename}_%v.m3u8"