Skip to content

Video to HLS

Isaac edited this page Sep 18, 2020 · 11 revisions

Utilizing ffmpeg, any video file and be converted into HLS media.

Q: Why use ffmpeg and convert to HLS when you can just stream?

A: Higher quality, subtitle support, no need to setup the streaming container.

Below is an example script of converting an MKV file to HLS files. This script only converts into the original video's resolution and not lower qualities. If you would like to convert to more qualities, making use of the adaptive bitrate, I would suggest looking into this article.

Here is a link to the script in the above article but updated with improvements.

The same user also made a Nvidia GPU version.

First we need to find the audio and video tracks in our MKV, this can be accomplished using ffprobe.

ffprobe -hide_banner FILE.mkv

The command will spit out all the tracks in the MKV file. Locate the audio and video tracks, find their numbers, and note them. ffprobe

Now that the audio and video tracks are known, we can convert to HLS.

ffmpeg -i INPUT.mkv -s 1920x1080 -map 0:1 -c:a aac -ar 48000 -b:a 128k -ac 2 -map 0:0 -hls_time 5 -hls_list_size 0 -f hls OUTPUT_DIR/output.m3u8  

or nvidia cuda accelerated

ffmpeg -hwaccel cuda -i INPUT.mkv -s 1920x1080 -map 0:1 -c:a aac -ar 48000 -b:a 128k -ac 2 -map 0:0 -c:v h264_nvenc -hls_time 5 -hls_list_size 0 -f hls OUTPUT_DIR/output.m3u8

Breakdown

-i INPUT.mkv Input MKV file

-s 1920x1080 Size of 1920x1080 (change if your video is different)

-map 0:1 FIRST MAP - Select the audio track

-c:a aac -ar 48000 -b:a 128k -ac 2 Convert the audio track into aac as many MKV files have audio codecs that are not supported in the browser

-map 0:0 SECOND MAP - Select the video track

-hls_time 5 -hls_list_size 0 5 second long HLS segments

-f hls OUTPUT_DIR/output.m3u8 Output as HLS in the folder OUTPUT_DIR and filename of output.m3u8

Note

This can take awhile depending on the file and your CPU, if you would like stream the MKV file instead of converting it, checkout the RTMP to HLS page.

Hosting the HLS media

HLS uses HTTP meaning that it needs to be served over a web server. Below are some example.

  1. If you already have the RTMP to HLS container running, an environment variable can be passed through allowing you to serve static files by transferring the files to the directory (information can be found on the rtmp to hls page).
  2. Use an existing http server (nginx, apache, etc) or launch a container then transfer the HLS files to the http server to be served.
  3. Use Caddy

It is strongly suggested to use https when serving your HLS media