我在Python中遇到Gstream问题,我尝试制作一个RTSP监听器的POC。 我尝试保护我的代码。我现在遇到的问题就像一堵墙:D 我无法打破它。 当我使用 get_buffer() 并且 RTSP 不可用时,程序卡在那里。 有什么办法可以设置超时吗?或者有其他方法可以防止卡住? 我需要在断开连接时重新连接 RTSP,但是 get_buffer() 卡住了程序。
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst, GObject, GLib
from urllib.parse import quote
import cv2
import numpy as np
from PIL import Image
from io import BytesIO
import base64
import time
Gst.init(None)
passs = quote('asdA@Da32')
pipelines = []
rtsp_urls = [
f"rtsp://admin:{passs}@172.16.40.216:7001/21eaf170-115c-f23a-cc1a-0b12e82636dd",
f"rtsp://admin:{passs}@172.16.40.216:7001/21eaf170-115c-f24a-cc1a-0b12e82636dd",
f"rtsp://admin:{passs}@172.16.40.216:7001/21eaf170-115c-f25a-cc1a-0b12e82636dd",
f"rtsp://admin:{passs}@172.16.40.216:7001/21eaf170-115c-f26a-cc1a-0b12e82636dd",
]
def retry():
global pipelines
for url in rtsp_urls:
pipeline = Gst.parse_launch(f'rtspsrc location={url} ! decodebin ! videoconvert ! jpegenc ! appsink name=sink{len(pipelines)}')
appsink = pipeline.get_by_name(f'sink{len(pipelines)}')
appsink.set_property('sync', False)
appsink.set_property('max-buffers', 1)
appsink.set_property('drop', True)
pipelines.append(pipeline)
pipeline.set_state(Gst.State.PLAYING)
def rec():
global pipelines
print("rec")
for pipeline in pipelines:
pipeline.set_state(Gst.State.NULL)
pipelines.clear()
retry()
retry()
while True:
try:
for i, url in enumerate(rtsp_urls):
start = time.time()
try:
pipeline = pipelines[i]
result, state, pending = pipeline.get_state(0)
print(result)
print(state)
sample = pipeline.get_by_name(f"sink{i}").emit("pull-sample")
buffer = sample.get_buffer()
except Exception as e:
print(e)
rec()
#retry()
if buffer:
try:
caps = sample.get_caps()
height = caps.get_structure(0).get_int('height')[1]
width = caps.get_structure(0).get_int('width')[1]
data = buffer.extract_dup(0, buffer.get_size())
image = Image.open(BytesIO(data))
print(time.time()-start)
image.save(f"{i}zdjecie.jpg", "JPEG")
except Exception as e:
print(e)
else:
rec()
except Exception as e:
print(e)
您应该能够通过将
reconnect
设置为 True
来实现这一点。您必须先创建一个 source
,然后相应地设置 property
。
source = Gst.ElementFactory.make("rtspsrc", "rtsp-source")
source.set_property("reconnect", True)
您可能会遇到其他问题,例如 https://forums.developer.nvidia.com/t/inference-on-rtsp-stream/112296,因此请注意。