Create RTSP server on Jetson Nano with Gstreamer python

Hi,
I am trying to build an RTSP server to stream the output from two RTSP cameras.
But when I run the code everything seems to work fine, but when I try to fetch the stream from the server with either VLC or OpenCV (entering rtsp://localhost:8554/test), I get an error.
I am fairly new to Gstreamer and tried multiple adjustments in the pipeline but without luck.

VLC says:

  • VLC is unable to open the MRL ‘rtsp://localhost:8554/test’.
  • VLC could not connect to ‘rtsp://localhost:8554/test’.

OpenCV says:
[ WARN:0] global /home/nvidia/host/build_opencv/nv_opencv/modules/videoio/src/cap_gstreamer.cpp (1757) handleMessage OpenCV | GStreamer warning: Embedded video playback halted; module source reported: Could not read from resource.

[ WARN:0] global /home/nvidia/host/build_opencv/nv_opencv/modules/videoio/src/cap_gstreamer.cpp (886) open OpenCV | GStreamer warning: unable to start pipeline

[ WARN:0] global /home/nvidia/host/build_opencv/nv_opencv/modules/videoio/src/cap_gstreamer.cpp (480) isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been created

[ERROR:0] global /home/nvidia/host/build_opencv/nv_opencv/modules/videoio/src/cap.cpp (116) open VIDEOIO(CV_IMAGES): raised OpenCV exception:

OpenCV(4.1.1) /home/nvidia/host/build_opencv/nv_opencv/modules/videoio/src/cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can’t find starting number (in the name of file): rtsp://localhost:8554/test in function ‘icvExtractPattern’

Can someone help me?

Thanks in advance!

Here is the code that I use:
import sys
sys.path.append(‘…/’)
import gi

gi.require_version('Gst', '1.0')
gi.require_version('GstRtspServer', '1.0')
from gi.repository import GObject, Gst, GstRtspServer
from gi.repository import GLib
from ctypes import *
import time
import cv2
import sys
import math
import platform
from streamer.common.is_aarch_64 import is_aarch64
from streamer.common.bus_call import bus_call
from streamer.common.FPS import GETFPS
import pyds


from utils import cprint

fps_streams={}

MAX_DISPLAY_LEN=64
PGIE_CLASS_ID_VEHICLE = 0
PGIE_CLASS_ID_BICYCLE = 1
PGIE_CLASS_ID_PERSON = 2
PGIE_CLASS_ID_ROADSIGN = 3
MUXER_OUTPUT_WIDTH=1920
MUXER_OUTPUT_HEIGHT=1080
MUXER_BATCH_TIMEOUT_USEC=4000000
TILED_OUTPUT_WIDTH=1280
TILED_OUTPUT_HEIGHT=720
GST_CAPS_FEATURES_NVMM="memory:NVMM"
OSD_PROCESS_MODE= 0
OSD_DISPLAY_TEXT= 0

# tiler_sink_pad_buffer_probe  will extract metadata received on OSD sink pad
# and update params for drawing rectangle, object information etc.
class RTSP_stream:
    def __init__(self):
        self.is_playing = False
        pass

    def cb_newpad(self, decodebin, decoder_src_pad,data):
        print("In cb_newpad\n")
        caps=decoder_src_pad.get_current_caps()
        gststruct=caps.get_structure(0)
        gstname=gststruct.get_name()
        source_bin=data
        features=caps.get_features(0)

        # Need to check if the pad created by the decodebin is for video and not
        # audio.
        print("gstname=",gstname)
        if(gstname.find("video")!=-1):
            # Link the decodebin pad only if decodebin has picked nvidia
            # decoder plugin nvdec_*. We do this by checking if the pad caps contain
            # NVMM memory features.
            print("features=",features)
            if features.contains("memory:NVMM"):
                # Get the source bin ghost pad
                bin_ghost_pad=source_bin.get_static_pad("src")
                if not bin_ghost_pad.set_target(decoder_src_pad):
                    sys.stderr.write("Failed to link decoder src pad to source bin ghost pad\n")
            else:
                sys.stderr.write(" Error: Decodebin did not pick nvidia decoder plugin.\n")

    def decodebin_child_added(self, child_proxy,Object,name,user_data):
        print("Decodebin child added:", name, "\n")
        if(name.find("decodebin") != -1):
            Object.connect("child-added",self.decodebin_child_added,user_data)
        if(is_aarch64() and name.find("nvv4l2decoder") != -1):
            print("Seting bufapi_version\n")
            Object.set_property("bufapi-version",True)

    def create_source_bin(self, index,uri):
        print("Creating source bin")

        # Create a source GstBin to abstract this bin's content from the rest of the
        # pipeline
        bin_name="source-bin-%02d" %index
        print(bin_name)
        nbin=Gst.Bin.new(bin_name)
        if not nbin:
            sys.stderr.write(" Unable to create source bin \n")

        # Source element for reading from the uri.
        # We will use decodebin and let it figure out the container format of the
        # stream and the codec and plug the appropriate demux and decode plugins.
        uri_decode_bin=Gst.ElementFactory.make("uridecodebin", "uri-decode-bin")
        if not uri_decode_bin:
            sys.stderr.write(" Unable to create uri decode bin \n")
        # We set the input uri to the source element
        uri_decode_bin.set_property("uri",uri)
        # Connect to the "pad-added" signal of the decodebin which generates a
        # callback once a new pad for raw data has beed created by the decodebin
        uri_decode_bin.connect("pad-added",self.cb_newpad,nbin)
        uri_decode_bin.connect("child-added",self.decodebin_child_added,nbin)

        # We need to create a ghost pad for the source bin which will act as a proxy
        # for the video decoder src pad. The ghost pad will not have a target right
        # now. Once the decode bin creates the video decoder and generates the
        # cb_newpad callback, we will set the ghost pad target to the video decoder
        # src pad.
        Gst.Bin.add(nbin,uri_decode_bin)
        bin_pad=nbin.add_pad(Gst.GhostPad.new_no_target("src",Gst.PadDirection.SRC))
        if not bin_pad:
            sys.stderr.write(" Failed to add ghost pad in source bin \n")
            return None
        return nbin

    def setup(self, args):
        # Check input arguments
        if len(args) < 2:
            sys.stderr.write("usage: %s <uri1> [uri2] ... [uriN]\n" % args[0])
            sys.exit(1)
        
        for i in range(0,len(args)-1):
            fps_streams["stream{0}".format(i)]=GETFPS(i)
        number_sources=len(args)-1

        # Standard GStreamer initialization
        GObject.threads_init()
        Gst.init(None)

        # Create gstreamer elements */
        # Create Pipeline element that will form a connection of other elements
        print("Creating Pipeline \n ")
        self.pipeline = Gst.Pipeline()
        is_live = False

        if not self.pipeline:
            sys.stderr.write(" Unable to create Pipeline \n")
        print("Creating streamux \n ")

        # Create nvstreammux instance to form batches from one or more sources.
        streammux = Gst.ElementFactory.make("nvstreammux", "Stream-muxer")
        if not streammux:
            self.pipeline.set_state(Gst.State.NULL)
            cprint.prRed("unable to create streammux. is the camera in use?")
            glbobj.shutdown("unable to create streammux")
            
        self.pipeline.add(streammux)
        for i in range(number_sources-1):
            print("Creating source_bin ",i," \n ")
            uri_name=args[i+1]
            if uri_name.find("rtsp://") == 0 :
                is_live = True
            print(uri_name.find("rtsp://"))
            source_bin=self.create_source_bin(i, uri_name)
            if not source_bin:
                sys.stderr.write("Unable to create source bin \n")
            self.pipeline.add(source_bin)
            padname="sink_%u" %i
            sinkpad= streammux.get_request_pad(padname)
            if not sinkpad:
                sys.stderr.write("Unable to create sink pad bin \n")
            srcpad=source_bin.get_static_pad("src")
            if not srcpad:
                sys.stderr.write("Unable to create src pad bin \n")
            srcpad.link(sinkpad)

        if is_live:
            print("Atle1ast one of the sources is live")
            streammux.set_property('live-source', 1)

        streammux.set_property('width', int(1920))
        streammux.set_property('height', int(1080))
        streammux.set_property('batch-size', number_sources)
        streammux.set_property('batched-push-timeout', 4000000)
        # streammux.set_property('enable-padding', 1)

        queue1=Gst.ElementFactory.make("queue","queue1")
        queue3=Gst.ElementFactory.make("queue","queue3")
        queue4=Gst.ElementFactory.make("queue","queue4")
        queue5=Gst.ElementFactory.make("queue","queue5")
        self.pipeline.add(queue1)
        self.pipeline.add(queue3)
        self.pipeline.add(queue4)
        self.pipeline.add(queue5)


        print("Creating tiler \n ")
        self.tiler=Gst.ElementFactory.make("nvmultistreamtiler", "nvtiler") # tiler can switch between input sources
        if not self.tiler:
            sys.stderr.write(" Unable to create tiler \n")
       
        tiler_rows=int(math.sqrt(number_sources))
        tiler_columns=int(math.ceil((1.0*number_sources)/tiler_rows))
        self.tiler.set_property("rows",tiler_rows)
        self.tiler.set_property("columns",tiler_columns)
        self.tiler.set_property("show-source", 1)
        self.tiler.set_property("width", TILED_OUTPUT_WIDTH)
        self.tiler.set_property("height", TILED_OUTPUT_HEIGHT)
            
        # Since the data format in the input file is elementary h264 stream,
        # we need a h264parser
        print("Creating H264Parser \n")
        h264parser = Gst.ElementFactory.make("h264parse", "h264-parser")
        if not h264parser:
            sys.stderr.write(" Unable to create h264 parser \n")
        
        # Use convertor to convert from NV12 to RGBA as required by nvosd
        nvvidconv = Gst.ElementFactory.make("nvvideoconvert", "convertor")
        if not nvvidconv:
            sys.stderr.write(" Unable to create nvvidconv \n")
        
        #Create a caps filter
        caps = Gst.ElementFactory.make("capsfilter", "filter")
        caps.set_property("caps", Gst.Caps.from_string("video/x-raw(memory:NVMM), format=I420"))

       
        # Make the h264 encoder
        encoder = Gst.ElementFactory.make("nvv4l2h264enc", "encoder")
        print("Creating H264 Encoder")
        if not encoder:
            sys.stderr.write(" Unable to create encoder")
        encoder.set_property('bitrate', 4000000)
        
        if is_aarch64():
            transform=Gst.ElementFactory.make("nvegltransform", "nvegl-transform")
            encoder.set_property('preset-level', 1)
            encoder.set_property('insert-sps-pps', 1)
            encoder.set_property('bufapi-version', 1)
        
        # Make the payload-encode video into RTP packets
        rtppay = Gst.ElementFactory.make("rtph264pay", "rtppay")
        print("Creating H264 rtppay")
        if not rtppay:
            sys.stderr.write(" Unable to create rtppay")
        
        # Make the UDP sink
        updsink_port_num = 5400
        sink = Gst.ElementFactory.make("udpsink", "udpsink")
        if not sink:
            sys.stderr.write(" Unable to create udpsink")
        sink.set_property('host', '224.224.255.255')
        sink.set_property('port', updsink_port_num)
        sink.set_property('async', False)
        sink.set_property('sync', 1)
    

        print("Adding elements to Pipeline \n")
        # self.pipeline.add(h264parser)
        self.pipeline.add(self.tiler)
        self.pipeline.add(nvvidconv)
        self.pipeline.add(caps)

        self.pipeline.add(encoder)
        self.pipeline.add(rtppay)
        self.pipeline.add(sink)

        # link alle elementen

        print("Linking elements in the Pipeline \n")
        streammux.link(queue1)
        queue1.link(self.tiler)
        self.tiler.link(nvvidconv)
        nvvidconv.link(queue4)
        queue4.link(caps)
        caps.link(encoder)
        encoder.link(rtppay)
        rtppay.link(queue5)
        queue5.link(sink)
        

        # create an event loop and feed gstreamer bus mesages to it
        self.loop = GObject.MainLoop()
        self.bus = self.pipeline.get_bus()
        self.bus.add_signal_watch()
        self.bus.connect ("message", bus_call, self.loop)

        rtsp_port_num = 8554
        server = GstRtspServer.RTSPServer.new()
        server.props.service = "%d" % rtsp_port_num
        server.attach(None)
        
        factory = GstRtspServer.RTSPMediaFactory.new()
        factory.set_launch( "( udpsrc name=pay0 port=%d buffer-size=524288 caps=\"application/x-rtp, media=video, clock-rate=90000, encoding-name=(string)%s, payload=96, h264parse \" )" % (updsink_port_num, "H264"))
        factory.set_shared(True)
        server.get_mount_points().add_factory("/test", factory)
        
        print("\n *** DeepStream: Launched RTSP Streaming at rtsp://localhost:%d/test ***\n\n" % rtsp_port_num)
        
        # List the sources
        print("Now playing...")
        for i, source in enumerate(args):
            if (i != 0):
                print(i, ": ", source)

        print("Starting pipeline \n")
        # start play back and listed to events            
        self.pipeline.set_state(Gst.State.PLAYING)

Hi,
We usually launch a RTSP server through test-launch. There are steps in

Q: Is there any example of running RTSP streaming?

For python sample, we have one for DeepStream SDK:

You may refer to it and check if you can successfully run it as reference. And customize it to your usecase.

1 Like

Hello,

Can I put rtsp id and password in deepstream_python_apps?

Thank you.