Merge branch 'FRHLS-8' of /home/ben/Documents/src.old/HLS-Stream-Creator
Merge branch 'FRHLS-8' of /home/ben/Documents/src.old/HLS-Stream-Creator

#!/bin/bash #!/bin/bash
# #
# A very simple BASH script to take an input video and split it down into Segments # A very simple BASH script to take an input video and split it down into Segments
# before creating an M3U8 Playlist, allowing the file to be served using HLS # before creating an M3U8 Playlist, allowing the file to be served using HLS
# #
# #
   
###################################################################################### ######################################################################################
# #
# Copyright (c) 2013, Ben Tasker # Copyright (c) 2013, Ben Tasker
# All rights reserved. # All rights reserved.
# #
# Redistribution and use in source and binary forms, with or without modification, # Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met: # are permitted provided that the following conditions are met:
# #
# Redistributions of source code must retain the above copyright notice, this # Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer. # list of conditions and the following disclaimer.
# #
# Redistributions in binary form must reproduce the above copyright notice, this # Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or # list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution. # other materials provided with the distribution.
# #
# Neither the name of the {organization} nor the names of its # Neither the name of Ben Tasker nor the names of his
# contributors may be used to endorse or promote products derived from # contributors may be used to endorse or promote products derived from
# this software without specific prior written permission. # this software without specific prior written permission.
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# #
###################################################################################### ######################################################################################
   
# Basic config # Basic config
  OUTPUT_DIRECTORY=${OUTPUT_DIRECTORY:-'./output'}
   
# Change this if you want to specify a path to use a specific version of FFMPeg # Change this if you want to specify a path to use a specific version of FFMPeg
FFMPEG='ffmpeg' FFMPEG=${FFMPEG:-'ffmpeg'}
   
  # Number of threads which will be used for transcoding. With newer FFMPEGs and x264
  # encoders "0" means "optimal". This is normally the number of CPU cores.
  NUMTHREADS=${NUMTHREADS:-"0"}
   
  # Video codec for the output video. Will be used as an value for the -vcodec argument
  VIDEO_CODEC=${VIDEO_CODEC:-"libx264"}
   
  # Video codec for the output video. Will be used as an value for the -acodec argument
  AUDIO_CODEC=${AUDIO_CODEC:-"libfdk_aac"}
   
  # Additional flags for ffmpeg
  FFMPEG_FLAGS=${FFMPEG_FLAGS:-""}
   
  # If the input is a live stream (i.e. linear video) this should be 1
  LIVE_STREAM=${LIVE_STREAM:-0}
   
# Lets put our functions here # Lets put our functions here
   
   
## Output the script's CLI Usage ## Output the script's CLI Usage
# #
# #
function print_usage(){ function print_usage(){
   
cat << EOM cat << EOM
HTTP Live Stream Creator HTTP Live Stream Creator
Version 1 Version 1
   
Copyright (C) 2013 B Tasker Copyright (C) 2013 B Tasker, D Atanasov
Released under BSD 3 Clause License Released under BSD 3 Clause License
See LICENSE See LICENSE
   
   
Usage: HLS-Stream-Creator.sh inputfile segmentlength(seconds) Usage: HLS-Stream-Creator.sh -[l] [-c segmentcount] -i [inputfile] -s [segmentlength(seconds)] -o [outputdir]
   
  -i Input file
  -s Segment length (seconds)
  -o Output directory (default: ./output)
  -l Input is a live stream
  -c Number of segments to include in playlist (live streams only) - 0 is no limit
   
  Deprecated Legacy usage:
  HLS-Stream-Creator.sh inputfile segmentlength(seconds) [outputdir='./output']
   
EOM EOM
   
exit exit
   
} }
   
  # This is used internally, if the user wants to specify their own flags they should be
## Create the Initial M3U8 file including the requisite headers # setting FFMPEG_FLAGS
# FFMPEG_ADDITIONAL=''
# Usage: create_m3u8 streamname segmentlength LIVE_SEGMENT_COUNT=0
#  
function create_m3u8(){  
   
# We'll add some more headers in a later version, basic support is all we need for now  
# The draft says we need CRLF so we'll use SED to ensure that happens  
cat << EOM | sed 's/$/\r/g' > output/$1.m3u8  
#EXTM3U  
#EXT-X-TARGETDURATION:$2  
#EXT-X-MEDIA-SEQUENCE:0  
#EXT-X-VERSION:3  
EOM  
}  
   
   
## Append a movie segment to the M3U8  
#  
# Usage: append_segment streamname SegmentLength(Seconds) SegmentFilename  
#  
function append_segment(){  
   
cat << EOM | sed 's/$/\r/g' >> output/$1.m3u8  
#EXTINF:$2  
$3  
EOM  
}  
   
   
## Close the M3U8 file  
#  
# Found that ffplay skips the first few segments if this isn't included.  
#  
# Usage: close_m3u8 streamname  
#  
function close_m3u8(){  
cat << EOM | sed 's/$/\r/g' >> output/$1.m3u8  
#EXT-X-ENDLIST  
EOM  
}  
   
   
# The fun begins! Think of this as function main  
   
   
# Get the input data # Get the input data
   
# Basic Usage is going to be # This exists to maintain b/c
# cmd.sh inputfile segmentlength LEGACY_ARGS=1
   
INPUTFILE=$1 # If even one argument is supplied, switch off legacy argument style
SEGLENGTH=$2 while getopts "i:o:s:c:l" flag
  do
  LEGACY_ARGS=0
  case "$flag" in
  i) INPUTFILE="$OPTARG";;
  o) OUTPUT_DIRECTORY="$OPTARG";;
  s) SEGLENGTH="$OPTARG";;
  l) LIVE_STREAM=1;;
  c) LIVE_SEGMENT_COUNT="$OPTARG";;
  esac
  done
   
   
  if [ "$LEGACY_ARGS" == "1" ]
  then
  # Old Basic Usage is
  # cmd.sh inputfile segmentlength
   
  INPUTFILE=${INPUTFILE:-$1}
  SEGLENGTH=${SEGLENGTH:-$2}
  if ! [ -z "$3" ]
  then
  OUTPUT_DIRECTORY=$3
  fi
  fi
   
   
# Check we've got the arguments we need # Check we've got the arguments we need
if [ "$INPUTFILE" == "" ] || [ "$SEGLENGTH" == "" ] if [ "$INPUTFILE" == "" ] || [ "$SEGLENGTH" == "" ]
then then
print_usage print_usage
fi fi
   
   
   
# FFMpeg is a pre-requisite, so let check for it # FFMpeg is a pre-requisite, so let check for it
if hash ffmpeg 2> /dev/null if hash $FFMPEG 2> /dev/null
then then
# FFMpeg exists # FFMpeg exists
echo "ffmpeg command found.... continuing" echo "ffmpeg command found.... continuing"
else else
# FFMPeg doesn't exist, uh-oh! # FFMPeg doesn't exist, uh-oh!
echo "Error: FFmpeg doesn't appear to exist in your PATH. Please addresss and try again" echo "Error: FFmpeg doesn't appear to exist in your PATH. Please addresss and try again"
exit 1 exit 1
fi fi
   
   
# Now we want to make sure out input file actually exists # Now we want to make sure out input file actually exists
  # This will need tweaking in future if we want to allow a RTMP stream (for example) to be used as input
if ! [ -f "$INPUTFILE" ] if ! [ -f "$INPUTFILE" ]
then then
echo "Error: You gave me an incorrect filename. Please re-run specifying something that actually exists!" echo "Error: You gave me an incorrect filename. Please re-run specifying something that actually exists!"
exit 1 exit 1
fi fi
   
  # Check output directory exists otherwise create it
  if [ ! -w $OUTPUT_DIRECTORY ]
# OK, so from here, what we want to do is to split the file into appropriately sized chunks, then
# re-encoding each to H.264 with MP3 audio, all to go into an MPEG2TS container echo "Creating $OUTPUT_DIRECTORY"
# mkdir -p $OUTPUT_DIRECTORY
# The protocol appears to support MP4 as well though, so we may well look at that later. fi
#  
# Essentially we want to create the chunks by running if [ "$LIVE_STREAM" == "1" ]
# then
# ffmpeg -i "$INPUTFILE" -vcodec libx264 -acodec mp3 -ss "START_POINT" -t "$SEGLENGTH" -f mpegts output/"$INPUTFILE"_"$N".ts FFMPEG_ADDITIONAL+="-segment_list_flags +live"
   
# First we need the duration of the video if [ "$LIVE_SEGMENT_COUNT" -gt 0 ]
DURATION=$($FFMPEG -i "$INPUTFILE" 2>&1 | grep Duration | cut -f 4 -d ' ') then
  FFMPEG_ADDITIONAL+=" -segment_list_size $LIVE_SEGMENT_COUNT"
# Now we need to break out the duration into a time we can use fi
DUR_H=$(echo "$DURATION" | cut -d ':' -f 1) fi
DUR_M=$(echo "$DURATION" | cut -d ':' -f 2)  
DUR_X=$(echo "$DURATION" | cut -d ':' -f 3 | cut -d '.' -f 1) # Pulls file name from INPUTFILE which may be an absolute or relative path.
  INPUTFILENAME=${INPUTFILE##*/}
# Calculate the duration in seconds  
let "DURATION_S = ( DUR_H * 60 + DUR_M ) * 60 + DUR_X"  
   
   
# Check we've not got empty media  
if [ "$DURATION_S" == "0" ]  
then  
echo "You've given me an empty media file!"  
exit 1  
fi  
   
   
# Now we've got our Duration, we need to work out how many segments to create  
N='1'  
START_POS='0'  
let 'N_FILES = DURATION_S / SEGLENGTH + 1'  
   
# For now, INPUTFILENAME is going to == INPUTFILE  
# Later, we'll change so that INPUTFILE could be an absolute path, whilst INPUTFILENAME will just be the filename  
INPUTFILENAME=$INPUTFILE  
   
   
# Create the M3U8 file  
create_m3u8 "$INPUTFILENAME" "$SEGLENGTH"  
   
# Finally, lets build the output filename format # Finally, lets build the output filename format
OUT_NAME=$INPUTFILENAME"_%03d.ts" OUT_NAME=$INPUTFILENAME"_%05d.ts"
   
  echo "Generating HLS segments - this may take some time"
   
# Processing Starts # Processing Starts
  $FFMPEG -i "$INPUTFILE" \
while [ "$START_POS" -lt "$DURATION_S" ] -loglevel error -y \
do -vcodec "$VIDEO_CODEC" \
  -acodec "$AUDIO_CODEC" \
OUTPUT=$( printf "$OUT_NAME" "$N" ) -threads "$NUMTHREADS" \
echo "Creating $OUTPUT ($N/$N_FILES)..." -map 0 \
$FFMPEG -i "$INPUTFILE" -loglevel quiet -vcodec libx264 -acodec mp3 -ss "$START_POS" -t "$SEGLENGTH" -f mpegts output/"$OUTPUT" -flags \
  -global_header \
let "N = N + 1" -f segment \
let "START_POS = START_POS + SEGLENGTH" -segment_list "$OUTPUT_DIRECTORY/$INPUTFILENAME.m3u8" \
  -segment_time "$SEGLENGTH" \
# If we're on the last segment, the duration may be less than the seglenth, so we need to reflect this in the m3u8 -segment_format mpeg_ts \
if ! [ "$START_POS" -lt "$DURATION_S" ] $FFMPEG_ADDITIONAL \
then $FFMPEG_FLAGS \
SEG_DURATION=$($FFMPEG -i output/"$OUTPUT" 2>&1 | grep Duration | cut -f 4 -d ' ') $OUTPUT_DIRECTORY/"$OUT_NAME" || exit 1
# Now we need to break out the duration into a time we can use  
DUR_H=$(echo "$SEG_DURATION" | cut -d ':' -f 1)  
DUR_M=$(echo "$SEG_DURATION" | cut -d ':' -f 2)  
DUR_X=$(echo "$SEG_DURATION" | cut -d ':' -f 3 | cut -d '.' -f 1)  
   
# Calculate the duration in seconds  
let "SEGLENGTH = ( DUR_H * 60 + DUR_M ) * 60 + DUR_X"  
fi  
   
# Append the file reference to the M3U8  
append_segment "$INPUTFILENAME" "$SEGLENGTH" "$OUTPUT"  
   
done  
   
# Add the close tag (ffplay gives some weird behaviour without this!)  
close_m3u8 "$INPUTFILENAME"  
file:a/README.md -> file:b/README.md
HLS-Stream-Creator HLS-Stream-Creator
================== ==================
   
Introduction Introduction
------------- -------------
   
HLS-Stream-Creator is a simple BASH Script designed to take a media file, segment it and create an M3U8 playlist for serving using HLS. HLS-Stream-Creator is a simple BASH Script designed to take a media file, segment it and create an M3U8 playlist for serving using HLS.
There are numerous tools out there which are far better suited to the task, and offer many more options. This project only exists because I was asked to look There are numerous tools out there which are far better suited to the task, and offer many more options. This project only exists because I was asked to look
into HTTP Live Streaming in depth, so after reading the [IETF Draft](http://tools.ietf.org/html/draft-pantos-http-live-streaming-11 "HLS on IETF") I figured I'd start with the basics by creating a script to encode arbitrary video into a VOD style HLS feed. into HTTP Live Streaming in depth, so after reading the [IETF Draft](http://tools.ietf.org/html/draft-pantos-http-live-streaming-11 "HLS on IETF") I figured I'd start with the basics by creating a script to encode arbitrary video into a VOD style HLS feed.
   
   
   
Usage Usage
------ ------
   
Usage is incredibly simple Usage is incredibly simple
   
``` ```
./HLS-Stream-Creator.sh inputfile segmentlength(seconds) ./HLS-Stream-Creator.sh -[l] [-c segmentcount] -i [inputfile] -s [segmentlength(seconds)] -o [outputdir]
   
   
  Deprecated Legacy usage:
  HLS-Stream-Creator.sh inputfile segmentlength(seconds) [outputdir='./output']
   
``` ```
   
So to split a video file called *example.avi* into segments of 10 seconds, we'd run So to split a video file called *example.avi* into segments of 10 seconds, we'd run
   
``` ```
./HLS-Stream-Creator.sh example.avi 10 ./HLS-Stream-Creator.sh -i example.avi -s 10
  ```
   
  **Arguments**
   
  ```
  -i [file] Input file
  -s [s] Segment length (seconds)
  -o [directory] Output directory (default: ./output)
  -c [count] Number of segments to include in playlist (live streams only) - 0 is no limit
  -l Input is a live stream
   
``` ```
   
   
   
Output Output
------- -------
   
As of version 1, the HLS resources will be output to the directory *output*. These will consist of video segments encoded in H.264 with MP3 audio (should be AAC really, but I'd compiled *ffmpeg* without) and an m3u8 file in the format As of version 1, the HLS resources will be output to the directory *output*. These will consist of video segments encoded in H.264 with AAC audio and an m3u8 file in the format
   
>#EXTM3U >\#EXTM3U
>#EXT-X-MEDIA-SEQUENCE:0 >\#EXT-X-MEDIA-SEQUENCE:0
>#EXT-X-VERSION:3 >\#EXT-X-VERSION:3
>#EXT-X-TARGETDURATION:10 >\#EXT-X-TARGETDURATION:10
>#EXTINF:10, no desc >\#EXTINF:10, no desc
>example_001.ts >example_00001.ts
>#EXTINF:10, no desc >\#EXTINF:10, no desc
>example_002.ts >example_00002.ts
>#EXTINF:10, no desc >\#EXTINF:10, no desc
>example_003.ts >example_00003.ts
>#EXTINF:5, no desc >\#EXTINF:5, no desc
>example_004.ts >example_00004.ts
>#EXT-X-ENDLIST >\#EXT-X-ENDLIST
   
   
   
   
   
Using a Specific FFMPEG binary Using a Specific FFMPEG binary
------------------------------- -------------------------------
   
There may be occasions where you don't want to use the *ffmpeg* that appears in PATH. At the top of the script, the ffmpeg command is defined, so change this to suit your needs There may be occasions where you don't want to use the *ffmpeg* that appears in PATH. At the top of the script, the ffmpeg command is defined, so change this to suit your needs
   
``` ```
FFMPEG='/path/to/different/ffmpeg' FFMPEG='/path/to/different/ffmpeg'
``` ```
   
   
  Additional Environment Variables
  -------------------------------
   
  There are few environment variables which can control the ffmpeg behaviour.
   
  * `VIDEO_CODEC` - The encoder which will be used by ffmpeg for video streams. Examples: _libx264_, _nvenc_
  * `AUDIO_CODEC` - Encoder for the audio streams. Examples: _aac_, _libfdk_acc_, _mp3_, _libfaac_
  * `NUMTHREADS` - A number which will be passed to the `-threads` argument of ffmpeg. Newer ffmpegs with modern libx264 encoders will use the optimal number of threads by default.
  * `FFMPEG_FLAGS` - Additional flags for ffmpeg. They will be passed without any modification.
   
  Example usage:
   
  ```
  export VIDEO_CODEC="nvenc"
  export FFMPEG_FLAGS="-pix_fmt yuv420p -profile:v"
  ./HLS-Stream-Creator.sh example.avi 10
  ```
   
License License
-------- --------
   
HLS-Stream-Creator is licensed under the [BSD 3 Clause License](http://opensource.org/licenses/BSD-3-Clause) and is Copyright (C) 2013 [Ben Tasker](http://www.bentasker.co.uk) HLS-Stream-Creator is licensed under the [BSD 3 Clause License](http://opensource.org/licenses/BSD-3-Clause) and is Copyright (C) 2013 [Ben Tasker](http://www.bentasker.co.uk)
   
   
  Issue Tracking
  ----------------
   
  Although the Github issue tracker can be used, the bulk of project management (such as it is) happens in JIRA. See [projects.bentasker.co.uk](http://projects.bentasker.co.uk/jira_projects/browse/HLS.html) for a HTML mirror of the tracking.