Skip to content

Instantly share code, notes, and snippets.

@hsiaosiyuan0
Last active May 13, 2022 21:19
Show Gist options
  • Save hsiaosiyuan0/412a4ca26d00ff7c45318227e7599c3d to your computer and use it in GitHub Desktop.
Save hsiaosiyuan0/412a4ca26d00ff7c45318227e7599c3d to your computer and use it in GitHub Desktop.
hls demo
#!/usr/bin/env bash
# downloading mv.mp4
download_mv_if_needed() {
if [ ! -f "./videos/mv.mp4" ]; then
mkdir -p ./videos
curl -L https://www.dropbox.com/s/fl02xpyhz8693b0/mv.mp\?dl\=1 -o ./videos/mv.mp4
fi
}
# create dir for saving results
make_dest_dir() {
mkdir -p ./videos/dest
}
# do compress and segment
do_seg() {
make_dest_dir
ffmpeg -v verbose -i ./videos/mv.mp4 \
-vf scale=640:360 -c:a aac -c:v libx264 \
-hls_time 10 \
-hls_playlist_type vod -b:v 400k -maxrate 400k -bufsize 400k -b:a 96k \
-hls_segment_filename ./videos/dest/360p_%03d.ts -f hls ./videos/dest/360p.m3u8 \
-vf scale=854x480 -c:a aac -c:v libx264 \
-hls_time 10 \
-hls_playlist_type vod -b:v 800k -maxrate 800k -bufsize 800k -b:a 128k \
-hls_segment_filename ./videos/dest/480p_%03d.ts ./videos/dest/480p.m3u8 \
-vf scale=1280:720 -c:a aac -c:v libx264 \
-hls_time 10 \
-hls_playlist_type vod -b:v 1500k -maxrate 1500k -bufsize 1500k -b:a 256k \
-hls_segment_filename ./videos/dest/720p_%03d.ts ./videos/dest/720p.m3u8
}
do_seg_if_needed() {
if [ ! -d "./videos/dest/" ]; then
do_seg
fi
}
# create a master m3u8te
make_master_m3u8() {
cat <<EOF > mv.m3u8
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360
./videos/dest/360p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1300000,RESOLUTION=842x480
./videos/dest/480p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=2600000,RESOLUTION=1280x720
./videos/dest/720p.m3u8
EOF
}
# create index.html
make_index_html() {
cat <<EOF > index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>hls-demo</title>
<style>
#video {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<video id="video" width="500" controls></video>
</body>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
var video = document.getElementById('video');
var m3u8 = "http://localhost:8000/mv.m3u8";
if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(m3u8);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function() {
video.play();
});
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = m3u8;
video.addEventListener('loadedmetadata', function() {
video.play();
});
}
</script>
</html>
EOF
}
serve() {
npm install -g @svrx/cli
svrx
}
download_mv_if_needed
do_seg_if_needed
make_master_m3u8
make_index_html
serve
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment