#!/bin/sh -xe

[ -z "$1" ] \
    && echo "usage: hlsvideo.sh video.mp4"

FULLPATH="$(readlink -f "$1")"
BASENAME="$(basename "$FULLPATH")"
NAME="${BASENAME%%.*}"
EXT="$(echo "${BASENAME##*.}" | tr '[:upper:]' '[:lower:]' )"

[ "$EXT" != "mp4" ] \
    && echo "Convert video to mp4 first"

mkdir -p "${NAME}"
cd "${NAME}"

#too slow.
# ffmpeg -i "${FULLPATH}" \
#     -c:v libvpx-vp9 -crf 28 -b:v 4000k \
#     -c:a libvorbis -qscale:a 5 \
#     "${NAME}.webm"

ffmpeg -i "${FULLPATH}" \
    -c:v libx264 -crf 28 -b:v 4000k \
    -c:a aac -ar 44100 \
    -profile:v baseline \
    -level:v 13 \
    -g 250 \
    -r 25 \
    -keyint_min 250 \
    -strict experimental \
    -b:a 128k \
    -threads 0 \
    -preset veryfast \
    "${NAME}.mp4"

ffmpeg -i "$FULLPATH" \
  -map 0:v:0 -map 0:a:0 \
  -map 0:v:0 -map 0:a:0 \
  -map 0:v:0 -map 0:a:0 \
  -map 0:v:0 -map 0:a:0 \
  -c:v libx264 -crf 28 -c:a aac -ar 44100 \
  -filter:v:0 scale=w=480:h=360   -maxrate:v:0 600k  -b:a:0 500k \
  -filter:v:1 scale=w=640:h=480   -maxrate:v:1 1500k -b:a:1 1000k \
  -filter:v:2 scale=w=1280:h=720  -maxrate:v:2 3000k -b:a:2 2000k \
  -filter:v:3 scale=w=1920:h=1080 -maxrate:v:3 6000k -b:a:3 4000k \
  -var_stream_map \
    "v:0,a:0,name:360p v:1,a:1,name:480p v:2,a:2,name:720p v:3,a:3,name:1080p" \
  -preset veryfast \
  -hls_list_size 10 \
  -threads 0 \
  -f hls \
  -hls_time 3 \
  -hls_flags independent_segments \
  -master_pl_name "${NAME}.m3u8" \
  -y "${NAME}-%v.m3u8"

ffmpegthumbnailer -i "${FULLPATH}" -s 720 -o "${NAME}.jpg"

cat <<EOF > index.html
<h1>$NAME</h1>
<body>
    <video width="720" poster="$NAME.jpg"
           controls preload="none">
      <source src="$NAME.m3u8"
              type="application/vnd.apple.mpegurl">
      <source src="$NAME.mp4"
              type='video/mp4; codecs="avc1.42c00d,mp4a.40.2"'>
    </video>
</body>
EOF
