Django StreamingHttpResponse: How to quit Popen process when client disconnects?

580 views Asked by At

In django, i want to convert a m3u8 playlist to mp4 and stream it to the client with ffmpeg pipe. The code works and the ffmpeg process also quits, but only when client waits till the end and received the whole file.

I want to quit the process when the client disconnects but the process keeps running forever.

I have this code:

import subprocess
from functools import partial
from django.http.response import StreamingHttpResponse
from django.shortcuts import get_object_or_404
from django.utils.text import slugify


def stream(request, uuid):
    vod = get_object_or_404(Vod, uuid=uuid)

    def iterator(proc):
        for data in iter(partial(proc.stdout.read, 4096), b""):
            if not data:
                proc.kill()
            yield data

    cmd = ["ffmpeg", "-i", "input.m3u8", "-c", "copy", "-bsf:a", "aac_adtstoasc", "-movflags", "frag_keyframe+empty_moov", "-f", "mp4", "-"]
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    response = StreamingHttpResponse(iterator(proc), content_type="video/mp4")
    response["Content-Disposition"] = f"attachment; filename={slugify(vod.date)}-{slugify(vod.title)}.mp4"
    return response

I've seen this answer but I'm not sure if I could use threading to solve my problem.

0

There are 0 answers