How to stream dynamically generated videos

58 Views Asked by At

I have been trying to generate small video clips through pytorch. The videos generates successfully but when I try to stream it to the html client it only plays the first video part sent via yield and stops. Each video part can be of arbitrary length and file size. No matter what I try it always plays the first one only.

Since generating the video can take up a minute or so waiting for all the videos to generate and combine them is also a non viable option as the user may have to wait for a long time.

I know the final length of all the videos combined, I dont know how many video parts will be generated nor their lengths.

Please help me.

    <h1>Video streaming</h1>
    <form id="stream_form">
        <label for="filename">Enter Video Name:</label><br>
        <input type="text" id="filename" name="filename" value="videoname"><br>
        <input type="submit" value="Stream">
    </form>

    <video id="stream_video" controls autoplay width="400">
        <source src="" type="videofile/mp4">
        Your browser does not support the video tag.
    </video>

    <script>
        document.getElementById('stream_form').addEventListener('submit', event => {
            event.preventDefault();
            let videoName = document.getElementById('filename').value;
            let videoElement = document.getElementById('stream_video');
            videoElement.src = `localhost:8000/stream_video?video_name=${encodeURIComponent(videoName)}`;
            
        });
    </script>

the python code


def gen(videoname):
    for frame in generate_video_pytorch(videoname):
        with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:
            temp_filename = temp_file.name
            frame.write_videofile(temp_filename, codec="libx264", audio_codec="aac", logger=None)
    
        with open(temp_filename, "rb") as f:
            video_content = f.read()
            yield video_content


@app.get("/stream_video")
async def stream_video(videoname: str, response: Response, url=None):
    response.headers["Cache-Control"] = "no-cache"
    response.headers["Connection"] = "keep-alive"
    response.headers["Content-Type"] = "video/mp4"
    return StreamingResponse(gen(videoname), media_type="multipart/x-mixed-replace;boundary=frame")

I am not married this approach (apart from the pytorch part :) ), ready to try anything that works.

0

There are 0 best solutions below