#!/bin/sh

FILE="$1"
NAME="${1%%.*}"
EXT="${1##*.}"

ffmpeg -i "$FILE" \
  -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 22 -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:2 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 "${NAME}.mp4" -s 720 -o "${NAME}.jpg"

cat <<EOF > test.html
<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.4d401f, mp4a.40.2"'>
    </video>
</body>
EOF
