网页上的实时视频编码和流式传输

Live Video Encoding and Streaming on a Webpage

我正在尝试在网页上显示实时网络摄像头视频流,并且我有一份工作草稿。但是,我对性能并不满意,正在寻找更好的方法来完成这项工作。

我有一个连接到 Raspberry PI 的网络摄像头和一个简单的 python-Flask 服务器网络服务器。网络摄像头图像是使用 OpenCV 捕获的,格式为 JPEG。随后,这些 JPEG 被发送到服务器的一个 UDP 端口。到目前为止,我所做的类似于自制的 MJPEG(motion-jpeg)流媒体。

在服务器端,我有一个简单的 python 脚本,它连续读取 UDP 端口并将 JPEG 图像放入 HTML5 canvas。这速度足以让人产生对直播的感觉。

问题:

备选方案:

Is this applicable on Raspberry PI ?

Is there any Media Player to embed on HTML/Javascript to handle network stream like the VLC does ?

Does these apply for this case ? If it does,how should I use them ?

Is there any other way to show live stream on webpage ?

What is the best practice for transport layer protocol in video streaming ?

您可以使用 FFmpeg 将视频流复用到 mp4 容器中的 H.264,然后可以直接在 HTML5 视频元素中使用。

我会尽可能多地回答您列出的 "Problems":

FPS is low and also quality of the stream is not that good.

由于您使用的是 Flask,您可以使用非常强大的 url_for 关键字将流式传输的帧直接显示到 img 标签中。以下是实现此目标的方法:
在网页上,将 <img src="{{url_for('video_feed')}}" 添加到您希望流式传输 Feed 的位置。
在后端,执行以下操作:

def gen(camera):
    frame = camera.read()
    yield (b'--frame\r\n'
    b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

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

现在,img 标签将显示出现在端点 video_feed 上的多部分类型的图像。因此,它会不断要求您提供更新的零件(更新的框架)。
我发现这种方法非常快!

学分:Miguel Grinberg's blog post

It is not a major point for now but UDP is not a secure way to stream video.

大多数视频流设备不会对它们流式传输的视频进行加密,因为这样做的计算成本很高。因此,虽然您可能通过 HTTPS 连接到设备上的嵌入式 Web 服务器,并且您可能必须登录设备才能控制它,但所有安全性都仅限于“控制平面”。视频本身几乎肯定会在未加密的情况下传输。如果它符合开放标准,它可能会通过 RTP/RTSP 或通过 HTTP 实时流媒体 (HLS) 发送。

来源:Thoughts on Streaming Videos Securely

Server is busy with image picking from UDP. Needs threaded server design.

使用上述方法,即使在流式传输视频时,我也能够与服务器进行交互。使用 Flask 开发 Web 服务器,您可以将 threaded=True 添加到 app.run() 调用,或者如果您使用 Flask CLI,则添加 --with-threads
您还可以将 Gunicorngeventeventlet 结合使用,以进一步控制您的线程。