Hello,
I am trying to run a python script that reads a camera video from a rtsp, performs some yolo detections and stream the output in a multicast.
Setup: I am using a Jetson Orin NX and running the script from a conda environment.
I was able to read the rtsp and broadcast the same original video over the multicast using gstreamer.
but I’m having issues streaming the modified_frames.
In my understanding I need to add the appsink to the pipeline since I want to modify the frames by adding bounding boxes, labels or filters. The problem comes when I add the appsink to the pipeline, the callback is never triggered.
Here is my code
from ultralytics import YOLO
# GStreamer
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst, GLib
# Initialize GStreamer
Gst.init(None)
# Gst.debug_set_active(True)
# Gst.debug_set_default_threshold(Gst.DebugLevel.DEBUG)
# YOLO Model
model = YOLO("yolo11n.pt")
def on_message(bus, message, pipeline):
print('on_message')
"""
Callback function to handle messages from the pipeline's bus.
"""
message_type = message.type
if message_type == Gst.MessageType.EOS:
print("End of Stream reached")
pipeline.set_state(Gst.State.NULL)
elif message_type == Gst.MessageType.ERROR:
err, debug = message.parse_error()
print(f"Error: {err}, {debug}")
pipeline.set_state(Gst.State.NULL)
def rebroadcast_rtsp_with_annotations(rtsp_url, multicast_ip, multicast_port):
print('rebroadcast_rtsp_with_annotations')
"""
This function takes an RTSP URL, runs YOLO on each frame, and rebroadcasts the annotated video over UDP multicast.
"""
# Create a new GStreamer pipeline
pipeline = Gst.Pipeline.new("rtsp-rebroadcast-pipeline")
# Create elements for the pipeline
rtspsrc = Gst.ElementFactory.make("rtspsrc", "rtsp-source")
rtph265depay = Gst.ElementFactory.make("rtph265depay", "rtp-depayloader")
h265parse = Gst.ElementFactory.make("h265parse", "h265-parser")
mpegtsmux = Gst.ElementFactory.make("mpegtsmux", "mpegts-muxer")
udpsink = Gst.ElementFactory.make("udpsink", "udp-sink")
appsink = Gst.ElementFactory.make("appsink", "appsink")
if not rtspsrc or not rtph265depay or not h265parse or not mpegtsmux or not udpsink or not appsink:
print("Failed to create one or more GStreamer elements.")
return
# Set properties
rtspsrc.set_property("location", rtsp_url)
udpsink.set_property("host", multicast_ip)
udpsink.set_property("port", multicast_port)
udpsink.set_property("sync", False) # Disable sync to reduce latency
appsink.set_property("emit-signals", True)
appsink.set_property("sync", False)
appsink.set_property("drop", True)
appsink.connect("new-sample", on_new_sample_from_appsink, None)
# Add elements to the pipeline
pipeline.add(rtspsrc)
pipeline.add(rtph265depay)
pipeline.add(h265parse)
pipeline.add(mpegtsmux)
pipeline.add(udpsink)
pipeline.add(appsink)
# Link elements
rtph265depay.link(h265parse)
h265parse.link(mpegtsmux)
mpegtsmux.link(udpsink)
mpegtsmux.link(appsink)
# Create pad-added callback
def on_pad_added(src, pad):
print("Pad added:", pad)
caps = pad.query_caps(None)
print("Pad added with capabilities:", caps.to_string())
if caps.to_string().startswith("application/x-rtp"):
if "H265" in caps.to_string():
pad.link(rtph265depay.get_static_pad("sink"))
print("Pad linked to depayloader.")
rtspsrc.connect("pad-added", on_pad_added)
# Start the pipeline
pipeline.set_state(Gst.State.PLAYING)
print("Pipeline is playing...")
# Set up the bus to listen for messages
bus = pipeline.get_bus()
bus.add_signal_watch()
bus.connect("message", on_message, pipeline)
print(f"Rebroadcasting RTSP stream {rtsp_url} to UDP multicast {multicast_ip}:{multicast_port}")
# Start main loop
try:
print('===== loop =========')
loop = GLib.MainLoop()
loop.run()
except KeyboardInterrupt:
print("Interrupted by user. Stopping...")
pipeline.set_state(Gst.State.NULL)
def on_new_sample_from_appsink(sink, user_data):
print('====== on_new_sample_from_appsink ====')
"""
Called when new frames are available from the appsink.
Processes the frame and pushes it back to the pipeline.
"""
sample = sink.emit("pull-sample")
if sample:
# Extract the frame from the sample
buffer = sample.get_buffer()
caps = sample.get_caps()
width = caps.get_structure(0).get_int("width")[1]
height = caps.get_structure(0).get_int("height")[1]
# Map the buffer to get raw frame data
success, map_info = buffer.map(Gst.MapFlags.READ)
if success:
raw_data = map_info.data
frame = np.ndarray(
shape=(height, width, 3),
dtype=np.uint8,
buffer=raw_data
)
# Process the frame with YOLO
annotated_frame = process_frame(frame)
# Create a new GstBuffer with the annotated frame
new_buffer = Gst.Buffer.new_wrapped(annotated_frame.tobytes())
# Push the new annotated buffer to the pipeline
sink.emit("push-sample", new_buffer)
return Gst.FlowReturn.OK
return Gst.FlowReturn.ERROR
def process_frame(frame):
print('process frame')
"""
Process each frame with YOLO and annotate the detections.
"""
# Perform YOLO object detection
results = model.track(frame)
annotated_frame = frame.copy()
# Here my custon logic to iterate through the results and modify the annotated_frame
return annotated_frame
if __name__ == "__main__":
rtsp_url = "rtsp://xx.xx.xx.xx:port/video1"
multicast_ip = "xxx.x.x.x"
multicast_port = port
rebroadcast_rtsp_with_annotations(rtsp_url, multicast_ip, multicast_port)
If I comment out the line pipeline.add(appsink), I can see the (raw) camera video in the multicast port.
How can I stream the modify frames in a multicast using gstream from a python script?
I appreciate any help