# Deepstream Memory Leak

**URL:** <https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457>\
**Category:** DeepStream SDK\
**Created:** [September 29, 2021, 8:23pm UTC](https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457 "2021-09-29T20:23:50Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![doppleg](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@doppleg](https://forums.developer.nvidia.com/u/doppleg)\
**Post date:** [September 29, 2021, 8:23pm UTC](https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457/1 "2021-09-29T20:23:50Z")

</div>

• Jetson Xavier NX  
• deepstream 5.1  
• JetPack Version 4.5.1

While using deepstream connected to a gst camera feed I get the following error after approximately 20 minutes:

> PosixMemMap:71 [12] mmap failed  
> nvbufsurface: NvBufSurfaceMap function failed  
> nvbufsurface: mapping of buffer (0) failed  
> nvbufsurface: error in mapping  
> get\_nvds\_buf\_Surface: Failed to map buffer to CPU  
> Segmentation fault (core dumped)

I stripped down my program to minimize any outside issues as the following which still produces the error:

> 

```
def startVideoStream(self):
    # 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 ")
    pipeline = Gst.Pipeline()

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

    # Source element for reading from camera
    print("Creating Source \n ")
    source = Gst.ElementFactory.make("v4l2src", "usb-cam-source")
    if not source:
        sys.stderr.write(" Unable to create Source \n")

    caps_v4l2src = Gst.ElementFactory.make("capsfilter", "v4l2src_caps")
    if not caps_v4l2src:
        sys.stderr.write(" Unable to create v4l2src capsfilter \n")

    print("Creating Video Converter \n")

    # Adding videoconvert -> nvvideoconvert as not all
    # raw formats are supported by nvvideoconvert;
    # Say YUYV is unsupported - which is the common
    # raw format for many logi usb cams
    # In case we have a camera with raw format supported in
    # nvvideoconvert, GStreamer plugins' capability negotiation
    # shall be intelligent enough to reduce compute by
    # videoconvert doing passthrough (TODO we need to confirm this)

    # Use nvjpegdec for hardware accelerated decode on GPU
    print("Creating jpegdec \n")
    decoder = Gst.ElementFactory.make("jpegdec", "jpeg-decoder")
    if not decoder:
        sys.stderr.write(" Unable to create jpegdec Decoder \n")

    caps_vidconvsrc = Gst.ElementFactory.make("capsfilter", "nvmm_caps")
    if not caps_vidconvsrc:
        sys.stderr.write(" Unable to create capsfilter \n")

    # Create nvstreammux instance to form batches from one or more sources.
    streammux = Gst.ElementFactory.make("nvstreammux", "Stream-muxer")
    if not streammux:
        sys.stderr.write(" Unable to create NvStreamMux \n")

    # Use nvinfer to run inferencing on decoder's output,
    # behaviour of inferencing is set through config file
    pgie = Gst.ElementFactory.make("nvinfer", "primary-inference")
    if not pgie:
        sys.stderr.write(" Unable to create pgie \n")

    tracker = Gst.ElementFactory.make("nvtracker", "tracker")
    if not tracker:
        sys.stderr.write(" Unable to create tracker \n")

    # nvvideoconvert to convert incoming raw buffers to NVMM Mem (NvBufSurface API)
    nvvidconv = Gst.ElementFactory.make("nvvideoconvert", "convertor")
    if not nvvidconv:
        sys.stderr.write(" Unable to create nvvidconv \n")

    # Create OSD to draw on the converted RGBA buffer
    nvosd = Gst.ElementFactory.make("nvmultistreamtiler", "onscreendisplay")#nvdsosd

    if not nvosd:
        sys.stderr.write(" Unable to create nvosd \n")

    print("Creating EGLSink \n")
    sink = Gst.ElementFactory.make("fakesink", "nvvideo-renderer")
    if not sink:
        sys.stderr.write(" Unable to create egl sink \n")

    print("Playing cam /dev/video0")
    source.set_property('device', "/dev/video0")
    source.set_property('io-mode', 2)
    caps_v4l2src.set_property('caps', Gst.Caps.from_string("image/jpeg,width=640,height=480,framerate=30/1"))
    caps_vidconvsrc.set_property('caps', Gst.Caps.from_string("video/x-raw(memory:NVMM),format=RGBA"))
    streammux.set_property('width', self.resolution.width)
    streammux.set_property('height', self.resolution.height)
    streammux.set_property('live-source', 1)
    streammux.set_property('batch-size', 1)
    streammux.set_property('batched-push-timeout', 4000000)
    nvosd.set_property('rows', 1)
    nvosd.set_property('columns', 1)
    nvosd.set_property('width', 640)
    nvosd.set_property('height', 480)
    # Set sync = false to avoid late frame drops at the display-sink
    sink.set_property('sync', False)

    #Set properties of pgie and sgie
    pgie.set_property('config-file-path', "/home/drone1/Documents/GroundControl2/ConfigFiles/dstest2_pgie_config.txt")

    #Set properties of tracker
    config = configparser.ConfigParser()
    config.read('/home/drone1/Documents/GroundControl2/ConfigFiles/dstest2_tracker_config.txt')
    config.sections()

    for key in config['tracker']:
        if key == 'tracker-width' :
            tracker_width = config.getint('tracker', key)
            tracker.set_property('tracker-width', tracker_width)
        if key == 'tracker-height' :
            tracker_height = config.getint('tracker', key)
            tracker.set_property('tracker-height', tracker_height)
        if key == 'gpu-id' :
            tracker_gpu_id = config.getint('tracker', key)
            tracker.set_property('gpu_id', tracker_gpu_id)
        if key == 'll-lib-file' :
            tracker_ll_lib_file = config.get('tracker', key)
            tracker.set_property('ll-lib-file', tracker_ll_lib_file)
        if key == 'll-config-file' :
            tracker_ll_config_file = config.get('tracker', key)
            tracker.set_property('ll-config-file', tracker_ll_config_file)
        if key == 'enable-batch-process' :
            tracker_enable_batch_process = config.getint('tracker', key)
            tracker.set_property('enable_batch_process', tracker_enable_batch_process)
        if key == 'enable-past-frame' :
            tracker_enable_past_frame = config.getint('tracker', key)
            tracker.set_property('enable_past_frame', tracker_enable_past_frame)

    print("Adding elements to Pipeline \n")
    pipeline.add(source)
    pipeline.add(caps_v4l2src)
    pipeline.add(decoder)
    pipeline.add(nvvidconv)
    pipeline.add(caps_vidconvsrc)
    pipeline.add(streammux)
    pipeline.add(pgie)
    pipeline.add(tracker)
    pipeline.add(nvosd)
    pipeline.add(sink)
    #if is_aarch64():
        #pipeline.add(transform)

    # we link the elements together
    # file-source -> h264-parser -> nvh264-decoder ->
    # nvinfer -> nvvidconv -> nvosd -> video-renderer
    print("Linking elements in the Pipeline \n")
    self.link_element(source, caps_v4l2src)
    self.link_element(caps_v4l2src, decoder)
    self.link_element(decoder, nvvidconv)
    self.link_element(nvvidconv, caps_vidconvsrc)

    sinkpad = streammux.get_request_pad("sink_0")
    if not sinkpad:
        sys.stderr.write(" Unable to get the sink pad of streammux \n")
    srcpad = caps_vidconvsrc.get_static_pad("src")
    if not srcpad:
        sys.stderr.write(" Unable to get source pad of decoder \n")
    self.link_element(srcpad, sinkpad)
    self.link_element(streammux, pgie)
    self.link_element(pgie, tracker)
    self.link_element(tracker, nvosd)
    self.link_element(nvosd, sink)

    # create and event loop and feed gstreamer bus mesages to it
    loop = GObject.MainLoop()

    bus = pipeline.get_bus()
    bus.add_signal_watch()
    bus.connect ("message", bus_call, loop)

    # Lets add probe to get informed of the meta data generated, we add probe to
    # the sink pad of the osd element, since by that time, the buffer would have
    # had got all the metadata.
    osdsinkpad = nvosd.get_static_pad("sink")
    #osdsinkpad = caps_vidconvsrc.get_static_pad("sink")
    if not osdsinkpad:
        sys.stderr.write(" Unable to get sink pad of nvosd \n")
    osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, self.osd_sink_pad_buffer_probe, 0)

    print("Starting pipeline \n")
    
    # start play back and listed to events
    pipeline.set_state(Gst.State.PLAYING)
    try:
        loop.run()
    except:
        pass

    # cleanup
    pipeline.set_state(Gst.State.NULL)

def osd_sink_pad_buffer_probe(self,pad,info,u_data,):
    meta_data_list = []
    frame_number=0
    #Intiallizing object counter with 0.
    obj_counter = {
        self.PGIE_CLASS_ID_VEHICLE:0,
        self.PGIE_CLASS_ID_PERSON:0,
        self.PGIE_CLASS_ID_BICYCLE:0,
        self.PGIE_CLASS_ID_ROADSIGN:0
    }
    num_rects=0
    gst_buffer = info.get_buffer()
    if not gst_buffer:
        print("Unable to get GstBuffer ")
        return

    # Retrieve batch metadata from the gst_buffer
    # Note that pyds.gst_buffer_get_nvds_batch_meta() expects the
    # C address of gst_buffer as input, which is obtained with hash(gst_buffer)
    batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer))
    l_frame = batch_meta.frame_meta_list
    while l_frame is not None:
        try:
            # Note that l_frame.data needs a cast to pyds.NvDsFrameMeta
            # The casting is done by pyds.NvDsFrameMeta.cast()
            # The casting also keeps ownership of the underlying memory
            # in the C code, so the Python garbage collector will leave
            # it alone.
            frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data)
        except StopIteration:
            break

        frame_number=frame_meta.frame_num
        num_rects = frame_meta.num_obj_meta
        l_obj=frame_meta.obj_meta_list
        obj_meta = None

        while l_obj is not None:
            try:
                # Casting l_obj.data to pyds.NvDsObjectMeta
                obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data)
                
                if obj_meta is not None:
                    meta_data_list.append(obj_meta)
            except StopIteration:
                break
            obj_counter[obj_meta.class_id] += 1
            try: 
                l_obj=l_obj.next
            except StopIteration:
                break
        try:
            l_frame=l_frame.next
        except StopIteration:
            break

    # Getting Image data using nvbufsurface
    # the input should be address of buffer and batch_id
    n_frame = pyds.get_nvds_buf_surface(hash(gst_buffer), frame_meta.batch_id)
    
    return Gst.PadProbeReturn.OK

```

[VideoProcessDeep copy.py](https://forums.developer.nvidia.com/uploads/short-url/l8ccQKgeEFfSeDlJWo1oVgiUMpP.py) (11.3 KB)

I was wondering if there is a way to clear the buffer to prevent this issue from happening or perhaps a workaround for the issue?

Thanks

---

<div class="post-metadata">

**Author:** ![Amycao](https://sea2.discourse-cdn.com/nvidia/user_avatar/forums.developer.nvidia.com/amycao/32/11342_2.png) [@Amycao](https://forums.developer.nvidia.com/u/Amycao)\
**Post date:** [October 1, 2021, 8:49am UTC](https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457/3 "2021-10-01T08:49:25Z")

</div>

ModuleNotFoundError: No module named ‘SystemConstants’

Seems you miss share somthing?

---

<div class="post-metadata">

**Author:** ![doppleg](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@doppleg](https://forums.developer.nvidia.com/u/doppleg)\
**Post date:** [October 1, 2021, 1:20pm UTC](https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457/4 "2021-10-01T13:20:38Z")

</div>

My mistake, I’ve removed the dependency. See the new attachment below.

[VideoProcessDeep copy.py](https://forums.developer.nvidia.com/uploads/short-url/pEr0DKzsRkB9GQZdYx2brq43ILw.py) (11.2 KB)  
[dstest2\_pgie\_config.txt](https://forums.developer.nvidia.com/uploads/short-url/sWVjLHGNJ0c2wwpea60Pxvkntzg.txt) (3.3 KB)  
[dstest2\_tracker\_config.txt](https://forums.developer.nvidia.com/uploads/short-url/7p5SMroW85LG4Lb5Anu10MpKotz.txt) (1.8 KB)

---

<div class="post-metadata">

**Author:** ![Amycao](https://sea2.discourse-cdn.com/nvidia/user_avatar/forums.developer.nvidia.com/amycao/32/11342_2.png) [@Amycao](https://forums.developer.nvidia.com/u/Amycao)\
**Post date:** [October 15, 2021, 8:38am UTC](https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457/5 "2021-10-15T08:38:05Z")

</div>

Sorry for the long delay.  
Is this still be an issue?

---

<div class="post-metadata">

**Author:** ![doppleg](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@doppleg](https://forums.developer.nvidia.com/u/doppleg)\
**Post date:** [October 15, 2021, 12:57pm UTC](https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457/6 "2021-10-15T12:57:47Z")

</div>

It is when I have an MJPEG camera as the source and my gst stream is configured for that input format. If I use a camera compatible with the [deepstream USB example](https://github.com/NVIDIA-AI-IOT/deepstream_python_apps/blob/master/apps/deepstream-test1-usbcam/deepstream_test_1_usb.py) the memory issue does not present itself. Unfortunately the input device I need to use only outputs the MJPEG format.

---

<div class="post-metadata">

**Author:** ![Amycao](https://sea2.discourse-cdn.com/nvidia/user_avatar/forums.developer.nvidia.com/amycao/32/11342_2.png) [@Amycao](https://forums.developer.nvidia.com/u/Amycao)\
**Post date:** [October 20, 2021, 7:35am UTC](https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457/7 "2021-10-20T07:35:36Z")

</div>

I still can not run your app, i managed to run pipeline from your python script, it works, btw, i commented this line,  
wx.core import DataFormat, is there anything wrong?

gst-launch-1.0 v4l2src device=“/dev/video0” io-mode=2 ! “image/jpeg, width=640,height=480,framerate=25/1” ! jpegdec ! nvvideoconvert ! “video/x-raw(memory:NVMM),width=640,height=480,format=RGBA” ! m.sink\_0 nvstreammux name=m width=640 height=480 batch-size=1 live-source=1 batched-push-timeout=4000000 ! nvinfer config-file-path=dstest2\_pgie\_config.txt ! nvdsosd ! nvegltransform ! nveglglessink

nvidia@nvidia-desktop:/opt/nvidia/deepstream/deepstream-6.0/sources/deepstream\_python\_apps/apps/tmp$ python3 VideoProcessDeep.py  
Creating Pipeline

Creating Source

Creating Video Converter

Creating jpegdec

Creating EGLSink

Playing cam /dev/video0  
Adding elements to Pipeline

Linking elements in the Pipeline

src could not be linked to sink\_0  
Starting pipeline

gstnvtracker: Loading low-level lib at /opt/nvidia/deepstream/deepstream-6.0/lib/libnvds\_nvmultiobjecttracker.so  
gstnvtracker: Batch processing is ON  
gstnvtracker: Past frame output is ON  
[NvMultiObjectTracker] Initialized  
0:00:00.346014866 31284 0x2f1b4ef0 WARN nvinfer gstnvinfer.cpp:635:gst\_nvinfer\_logger: NvDsInferContext[UID 1]: Warning from NvDsInferContextImpl::initialize() \<nvdsinfer\_context\_impl.cpp:1161\> [UID = 1]: Warning, OpenCV has been deprecated. Using NMS for clustering instead of cv::groupRectangles with topK = 20 and NMS Threshold = 0.5  
^C^C^C^C0:00:04.932692129 31284 0x2f1b4ef0 INFO nvinfer gstnvinfer.cpp:638:gst\_nvinfer\_logger: NvDsInferContext[UID 1]: Info from NvDsInferContextImpl::deserializeEngineAndBackend() \<nvdsinfer\_context\_impl.cpp:1900\> [UID = 1]: deserialized trt engine from :/opt/nvidia/deepstream/deepstream-6.0/samples/models/Primary\_Detector/resnet10.caffemodel\_b1\_gpu0\_int8.engine  
INFO: [Implicit Engine Info]: layers num: 3  
0 INPUT kFLOAT input\_1 3x368x640  
1 OUTPUT kFLOAT conv2d\_bbox 16x23x40  
2 OUTPUT kFLOAT conv2d\_cov/Sigmoid 4x23x40

0:00:04.932871620 31284 0x2f1b4ef0 INFO nvinfer gstnvinfer.cpp:638:gst\_nvinfer\_logger: NvDsInferContext[UID 1]: Info from NvDsInferContextImpl::generateBackendContext() \<nvdsinfer\_context\_impl.cpp:2004\> [UID = 1]: Use deserialized engine model: /opt/nvidia/deepstream/deepstream-6.0/samples/models/Primary\_Detector/resnet10.caffemodel\_b1\_gpu0\_int8.engine  
0:00:05.107933616 31284 0x2f1b4ef0 INFO nvinfer gstnvinfer\_impl.cpp:313:notifyLoadModelStatus: [UID 1]: Load new model:dstest2\_pgie\_config.txt sucessfully  
Traceback (most recent call last):  
File “VideoProcessDeep.py”, line 294, in   
video.startVideoStream()  
File “VideoProcessDeep.py”, line 221, in startVideoStream  
pipeline.set\_state(Gst.State.PLAYING)  
KeyboardInterrupt

---

<div class="post-metadata">

**Author:** ![doppleg](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@doppleg](https://forums.developer.nvidia.com/u/doppleg)\
**Post date:** [October 21, 2021, 7:16pm UTC](https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457/8 "2021-10-21T19:16:00Z")

</div>

I’m not sure why the script won’t operate on your machine but I did identify that if I remove the following line from the script:

> n\_frame = pyds.get\_nvds\_buf\_surface(hash(gst\_buffer), frame\_meta.batch\_id)

I no longer get the error. Is there a way to release the memory associated with the command after operations are performed on the image?

I tried:

> del n\_frame

However the issue persisted so I’m assuming the object continues to exist outside my usage.

---

<div class="post-metadata">

**Author:** ![Amycao](https://sea2.discourse-cdn.com/nvidia/user_avatar/forums.developer.nvidia.com/amycao/32/11342_2.png) [@Amycao](https://forums.developer.nvidia.com/u/Amycao)\
**Post date:** [November 19, 2021, 9:40am UTC](https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457/9 "2021-11-19T09:40:22Z")

</div>

Sorry for the late.  
I can not run your python app. so i modified based on python test1-usb app for usb mjpg format to mimic your case. attached for your reference. i can not repro the issue. please let me know if you have more issue. [deepstream\_test\_1\_usb.py](https://forums.developer.nvidia.com/uploads/short-url/ujcogHigw84Nyeq00flU9IJn7gv.py) (13.8 KB)

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/nvidia/user_avatar/forums.developer.nvidia.com/system/32/68080_2.png) [@system](https://forums.developer.nvidia.com/u/system)\
**Post date:** [December 13, 2021, 6:14am UTC](https://forums.developer.nvidia.com/t/deepstream-memory-leak/190457/11 "2021-12-13T06:14:49Z")

</div>

Closed on December 13, 2021, 6:14am UTC

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
