Setting up HLS streaming using ffmpeg utility on Docker


install Docker Engine - Community and Docker Compose as described here

create the /etc/docker/hls/docker-compose.yml file

version: '3.8'

networks:
  default:
    ipam:
      config:
        - subnet: 192.168.199.0/24

services:
  hls:
    build:
      context: .
    container_name: hls
    volumes:
      - /var/lib/video:/video
    tmpfs:
      - /usr/local/apache2/htdocs
    networks:
      - default
    ports:
      - 80:80
    environment:
      - URL_PREFIX=http://hls.domain.lan
      - PLAYLIST_NAME=playlist
      - SEGMENT_LENGTH=10
      - SEGMENT_COUNT=30
    restart: always

create the /etc/docker/hls/dockerfile file

FROM httpd:bullseye

RUN \
apt-get update && \
apt-get install ffmpeg supervisor -y && \
rm -R /usr/local/apache2/htdocs/*

COPY stream-udp stream-hls /usr/local/sbin/
COPY supervisor-httpd.conf supervisor-stream-udp.conf supervisor-stream-hls.conf /etc/supervisor/conf.d/

ENTRYPOINT /usr/bin/supervisord -n

create the /etc/docker/hls/stream-udp file

#!/bin/bash

while true
do
    IFS=$'\n'
    files=($(find /video -maxdepth 1 -type f))
    if [ "${#files[@]}" -gt "0" ]; then
        index=$(shuf -i 0-$((${#files[@]}-1)) -n 1)
        ffmpeg -re -i "${files[$index]}" -vcodec copy -acodec copy -f mpegts udp://127.0.0.1:51386
    else
        sleep 60s
    fi
done

create the /etc/docker/hls/stream-hls file

#!/bin/bash

format="%${#SEGMENT_COUNT}d"
destination=/usr/local/apache2/htdocs

ffmpeg \
    -i udp://127.0.0.1:51386 \
    -vcodec copy \
    -acodec copy \
    -f ssegment \
    -segment_list_flags +live \
    -segment_time $SEGMENT_LENGTH \
    -segment_list_entry_prefix $URL_PREFIX/ \
    -segment_list_size $SEGMENT_COUNT \
    -segment_wrap $SEGMENT_COUNT \
    -segment_list "$destination/$PLAYLIST_NAME.m3u8" "$destination/$PLAYLIST_NAME$format.ts"

create the /etc/docker/hls/supervisor-httpd.conf file

[program:httpd]
command=httpd-foreground
autostart=true
autorestart=true
stdout_logfile=/var/log/supervisor-httpd.out
stderr_logfile=/var/log/supervisor-httpd.err

create the /etc/docker/hls/supervisor-stream-udp.conf file

[program:stream-udp]
command=/usr/local/sbin/stream-udp
autostart=true
autorestart=true
stdout_logfile=none
stderr_logfile=none

create the /etc/docker/hls/supervisor-stream-hls.conf file

[program:stream-hls]
command=/usr/local/sbin/stream-hls
autostart=true
autorestart=true
stdout_logfile=none
stderr_logfile=none

build the image, create and start the container

docker-compose -f /etc/docker/hls/docker-compose.yml up -d

open the http://hls.domain.lan/playlist.m3u8 link in a media player (e.g. SMPlayer)

Leave a Reply