Make it LIVE: stream a video in a loop

Say you have a video available locally or via HTTP somewhere but channels will not play it cause it is not LIVE. Let's make it LIVE and play it in a loop forever.

Requires flask

If the video is not local or not named your_video.mp4 the VIDEO_PATH will need to be adjusted

flask app
import subprocess
from flask import Flask, Response

app = Flask(__name__)
VIDEO_PATH = "your_video.mp4"  # Path to the video you want to loop, could be remote

def start_ffmpeg():
    """Start FFmpeg to loop the video and stream it as MPEG-TS """
    cmd = [
        "ffmpeg",
        "-re",  # Read at native frame rate
        "-stream_loop", "-1",  # Loop infinitely
        "-i", VIDEO_PATH,  # Input file
        "-c:v", "copy",  # do not reencode
        "-c:a", "copy",  # 
        "-f", "mpegts",  # Use MPEG-TS format for non-seekable output
        "pipe:1"  # Send to stdout for Flask to stream
    ]
    return subprocess.Popen(cmd, stdout=subprocess.PIPE)

def generate_video_stream():
    """Generate a chunked video stream with FFmpeg logs."""
    process = start_ffmpeg()  # Start FFmpeg and capture the output
    while True:
        chunk = process.stdout.read(16*1024)  # Read 16 kB chunks from FFmpeg
        if not chunk:
            break  # Stop if no more data is available
        yield chunk  # Yield the chunk to Flask in a streaming fashion

@app.route('/video')
def video_feed():
    """Stream video as MPEG-TS in chunks."""
    return Response(generate_video_stream(), mimetype='video/mp2t')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001, debug=True)

available also as https://pastebin.com/jpgK9YhW

Now the video can be streamed from channels as http://APP_IP:5001/video after including it in a MPEG-TS playlist

2 Likes