简体   繁体   中英

Python flask video streaming can't handle multiple clients

I am trying to display a video in a HTML file with the python flask library. Online I found pleanty of code very similar to each other. I ended up with the code below

Code:

from flask import Flask, render_template, Response
import cv2

app = Flask(__name__)
camera = cv2.VideoCapture('path to file')
@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        success, frame = camera.read()
        ret, buffer = cv2.imencode('.jpg', frame)
        frame = buffer.tobytes()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(camera),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(debug=True)

HTML:

<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Live Streaming Demonstration</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-8  offset-lg-2">
            <h3 class="mt-5">Live Streaming</h3>
            <img src="{{ url_for('video_feed') }}" width="100%">
        </div>
    </div>
</div>
</body>
</html>

When I try to run my code with just one client it works fine, but when I open it in 2 different browsers at the same time the frames freeze and I receive the following error:

Assertion avci->compat_decode_consumed == 0 failed at libavcodec/decode.c:822

Is their some way I can fix this?

Flask is synchronous and single threaded, that can simultaneously serve as many connections, however it is not suitable for remote video, no matter what protocol you use. It may work with local web-cam, but definitely not rtsp.

Problem defined here: https://blog.miguelgrinberg.com/post/video-streaming-with-flask/page/10

A workaround is using a very complicated set of threads as discussed here: https://blog.miguelgrinberg.com/post/flask-video-streaming-revisited

You should try asynchronous frameworks, eg Sanic, this code will give a you a good starting point, very buggy but it works on 3 devices simultaneously for few seconds before it crashed: https://github.com/kxxoling/sanic_video_streaming

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM