[英]Why can't my Python server handle data from multiple clients simultaneously using select.select()?
[英]Python flask video streaming can't handle multiple clients
我正在嘗試使用 python flask 庫在 HTML 文件中顯示視頻。 在網上我發現很多代碼彼此非常相似。 我最終得到了下面的代碼
代碼:
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>
當我嘗試僅使用一個客戶端運行我的代碼時,它工作正常,但是當我同時在 2 個不同的瀏覽器中打開它時,幀凍結並且我收到以下錯誤:
斷言 avci->compat_decode_consumed == 0 在 libavcodec/decode.c:822 失敗
他們有辦法解決這個問題嗎?
Flask 是同步單線程的,可以同時服務多個連接,但是無論你使用什么協議,它都不適合遠程視頻。 它可能適用於本地網絡攝像頭,但絕對不適用於 rtsp。
此處定義的問題: https://blog.miguelgrinberg.com/post/video-streaming-with-flask/page/10
一種解決方法是使用一組非常復雜的線程,如下所述: https://blog.miguelgrinberg.com/post/flask-video-streaming-revisited
您應該嘗試異步框架,例如 Sanic,此代碼將為您提供一個很好的起點,非常有問題,但它在崩潰前可同時在 3 個設備上運行幾秒鍾: https://github.com/kxxoling/sanic_video_streaming
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.