NvBufSurfTransform (GPU) silently uses a destroyed SURFACE_ARRAY surface when a new NvBufSurface gets its address: stale frames, black output, leak

NvBufSurfTransform (GPU) silently uses a destroyed SURFACE_ARRAY surface when a new NvBufSurface gets its address: stale frames, black output, leak

• Hardware Platform: Jetson Orin NX 16 GB (Seeed reComputer)
• JetPack Version: 7.2 (Jetson Linux 39.2.0)
• DeepStream Version: 9.1 (only for the GStreamer repro; the C repro needs Jetson Linux only)
• GStreamer: 1.24.2
• Issue Type: bug
• How to reproduce: standalone C program and a GStreamer-only script, both below

Summary

With compute_mode = NvBufSurfTransformCompute_GPU, NvBufSurfTransform appears to cache its
GPU mapping of an NVBUF_MEM_SURFACE_ARRAY surface keyed (at least partly) by the NvBufSurface*
address, and NvBufSurfaceDestroy does not drop that entry. When a later NvBufSurfaceCreate
returns a struct at the same heap address (malloc reuses freed chunks, so this is common), the
transform uses the old surface’s buffer:

  • as source: the output shows the old surface’s picture;
  • as destination: the GPU writes into the old buffer and the new surface stays untouched (black);
  • the old buffers stay allocated until the process exits, so creating and destroying surfaces
    (e.g. every pipeline restart) leaks memory.

Every call returns 0, cudaDeviceSynchronize() and cudaGetLastError() report no error, and
DBGNVBUFSURFTRANSFORM=1 prints nothing.

The same happens with stock elements only: nvvideoconvert compute-hw=GPU in a pipeline that is
torn down and rebuilt in one process outputs frames from earlier pipeline instances.
compute-hw=VIC copy-hw=VIC is clean.

Repro 1: C, Jetson Linux only

stale_mapping.c (below) uses only NvBufSurfaceCreate/MemSet/Map/SyncForCpu/Destroy,
NvBufSurfTransformSetSessionParams (GPU) and NvBufSurfTransform. It builds against
/usr/src/jetson_multimedia_api and libnvbufsurf* from nvidia-l4t-multimedia. Each source
has its own grey level, so the output tells which surface was actually read.

make
./stale_mapping src            # new 1080p NV12 source per iteration -> one CUDA_PINNED destination
./stale_mapping src --overlap  # control: previous source destroyed after the next one is created
./stale_mapping dst            # new 320x240 RGB SURFACE_ARRAY destination per iteration
./stale_mapping dst --pinned   # control: CUDA_PINNED destination
./stale_mapping dst --overlap  # control: no address reuse
./stale_mapping pool 12 30     # 12 cycles: create 30 sources, transform each, destroy all

Source side: from iteration 8 on, the new source gets the address of source 7, and every
transform returns source 7’s picture:

src   6  surf 0xaaaadb9d9a80  want 202  got 202  ok
src   7  surf 0xaaaadb9dbd00  want 231  got 231  ok
src   8  surf 0xaaaadb9dbd00  want  27  got 231  STALE (grey of src 7)
src   9  surf 0xaaaadb9dbd00  want  57  got 231  STALE (grey of src 7)
...
src  14  surf 0xaaaadb9dbd00  want 202  got 231  STALE (grey of src 7)
src  15  surf 0xaaaadb9dbd00  want 231  got 231  ok
summary: 7 of 16 transforms read a stale source

src --overlap: 0 of 16 stale.

Destination side: same pattern, the new destination stays all zeros:

dst   7  surf 0xaaaaee9b9b20  want 190  got 190  ok
dst   8  surf 0xaaaaee9b9b20  want 190  got   0  BLACK
dst   9  surf 0xaaaaee9b9b20  want 190  got   0  BLACK
...
summary: 8 of 16 destinations black

dst --pinned: 0 of 16 black. dst --overlap: 0 of 16 black. DBGNVBUFSURFTRANSFORM=1 ./stale_mapping dst:
no output from the library.

Leak: (cycle 0 includes the CUDA context, about 200 MiB)

pool: 12 cycles, 30 NV12 1920x1080 surfaces each, MemAvailable 14379 MiB
cycle  0  stale  0 of 30  MemAvailable 14155 MiB (-224)
cycle  1  stale  0 of 30  MemAvailable 14057 MiB (-322)
cycle  2  stale  5 of 30  MemAvailable 13961 MiB (-418)
cycle  3  stale  6 of 30  MemAvailable 13881 MiB (-498)
cycle  4  stale 13 of 30  MemAvailable 13804 MiB (-575)
...
cycle 11  stale  9 of 30  MemAvailable 13402 MiB (-977)
summary: 102 stale transforms, MemAvailable -977 MiB

Roughly 60 to 100 MiB per cycle for a pool of 30 × 3.1 MB. Memory comes back when the process
exits. With 60 surfaces of 3840×2160 per cycle, the device was down 10.5 GiB after 21 cycles.

From a larger test program (available on request), on the same device:

  • First surface wins, permanently: transform A, transform B, destroy A, create C. When C landed
    on A’s address it showed A’s picture (50 of 57 trials; the other 7 had A’s grey level by chance),
    always the picture of the first surface ever transformed at that address. So it is not a
    “last used” cache.
  • Where the writes go: keeping a destroyed destination’s dmabuf alive via dup() and mapping
    it shows that the transform result meant for the new (black) destination lands in that old
    buffer.
  • No per-transform leak: 20 000 transforms between the same two long-lived surfaces keep
    MemAvailable flat.
  • No foreign memory touched: surfaces allocated right after a destroy (to receive freed pages)
    were never read or written by the stale transforms; the old buffers are simply kept.
  • Address is not the whole key: with one surface per cycle, struct address, surfaceList
    address and fd all repeated, yet the output was correct; memory still dropped by about one frame
    per cycle.

Repro 2: GStreamer elements only

gst_restart.py (below) builds, runs (120 frames) and tears down this pipeline 12 times in one
process. Each cycle uses its own grey level and burns “frame from cycle N” into the source and
“now: cycle N” in after the GPU stage, so old frames are also visible in a recording (--record).

videotestsrc ! video/x-raw,format=RGBA,width=1920,height=1080 ! textoverlay
  ! nvvideoconvert output-buffers=60 ! video/x-raw(memory:NVMM),format=NV12
  ! nvvideoconvert compute-hw=GPU ! video/x-raw(memory:NVMM),format=RGBA,width=640,height=360
  ! nvvideoconvert ! video/x-raw,format=RGBA ! textoverlay ! appsink

python3 gst_restart.py --pattern ball:

compute-hw=GPU, copy-hw=GPU, ball, pool 60, 120 frames per cycle, MemAvailable 13546 MiB
cycle  0 grey  40 MemAvailable 13416 MiB (-130)  frames: 120 ok
cycle  1 grey  56 MemAvailable 13410 MiB (-136)  frames: 118 ok, 2 OLD(cycle 0)
cycle  2 grey  72 MemAvailable 13404 MiB (-142)  frames: 114 ok, 6 OLD(cycle 1)
cycle  3 grey  88 MemAvailable 13386 MiB (-160)  frames: 106 ok, 10 OLD(cycle 1), 2 OLD(cycle 2), 2 OLD(cycle 0)
cycle  4 grey 104 MemAvailable 13205 MiB (-341)  frames: 98 ok, 10 OLD(cycle 3), 2 OLD(cycle 2), 10 OLD(cycle 1)
cycle  5 grey 120 MemAvailable 13204 MiB (-342)  frames: 50 ok, 18 OLD(cycle 3), 42 OLD(cycle 4), 4 OLD(cycle 2), 6 OLD(cycle 1)
cycle  6 grey 136 MemAvailable 13207 MiB (-339)  frames: 32 ok, 40 OLD(cycle 5), 14 OLD(cycle 3), 30 OLD(cycle 4), 2 OLD(cycle 2), 2 OLD(cycle 1)
cycle  7 grey 152 MemAvailable 13202 MiB (-344)  frames: 12 ok, 30 OLD(cycle 4), 28 OLD(cycle 6), 36 OLD(cycle 5), 10 OLD(cycle 3), 2 OLD(cycle 1), 2 OLD(cycle 2)
cycle  8 grey 168 MemAvailable 13209 MiB (-337)  frames: 14 ok, 26 OLD(cycle 6), 28 OLD(cycle 4), 28 OLD(cycle 5), 10 OLD(cycle 7), 12 OLD(cycle 3), 2 OLD(cycle 1)
cycle  9 grey 184 MemAvailable 13209 MiB (-337)  frames: 84 ok, 8 OLD(cycle 4), 6 OLD(cycle 6), 6 OLD(cycle 7), 8 OLD(cycle 5), 6 OLD(cycle 3), 2 OLD(cycle 8)
cycle 10 grey 200 MemAvailable 13214 MiB (-332)  frames: 12 ok, 76 OLD(cycle 9), 6 OLD(cycle 6), 6 OLD(cycle 7), 4 OLD(cycle 4), 8 OLD(cycle 5), 6 OLD(cycle 3), 2 OLD(cycle 8)
cycle 11 grey 216 MemAvailable 13210 MiB (-336)  frames: 4 ok, 72 OLD(cycle 9), 12 OLD(cycle 10), 6 OLD(cycle 6), 4 OLD(cycle 4), 6 OLD(cycle 7), 6 OLD(cycle 3), 8 OLD(cycle 5), 2 OLD(cycle 8)

Control, python3 gst_restart.py --pattern ball --compute VIC --copy-hw VIC: 120 of 120 correct in
every cycle, MemAvailable −39 → −48 MiB.

The memory loss in the GStreamer case varies between runs: in this run (fresh boot) it stopped
growing after cycle 4; in earlier runs it was about 170 MB per restart for all 12 cycles
(−456 → −2114 MiB). The stale frames reproduce every time. With compute-hw=VIC and the default
copy-hw (GPU), the system-memory↔NVMM copies are affected too, but rarely (30 old frames in 1 of
24 cycles across two runs).

Newer releases

The newest Jetson Linux in the r39.2 apt repo is 39.2.1. Its nvidia-l4t-multimedia ships a
byte-identical libnvbufsurftransform.so.1.0.0 (same md5 as 39.2.0; only libnvvideo.so and
libnvmmlite_video.so changed), so we expect the same behaviour there.

Questions

  1. Is this a known issue, and is there a fixed libnvbufsurftransform for Jetson Linux 39.2 /
    JetPack 7.2?
  2. Is there a supported way to release the library’s mapping for a surface before
    NvBufSurfaceDestroy, or to reset it, other than using VIC?
  3. What exactly is the cache key? Knowing it would tell us which allocation patterns are safe
    until a fix is available.

Disclosure

This issue was tracked down with the help of an AI coding assistant (Claude by Anthropic), which
also helped write the repro programs and this post. All outputs above are from runs on the device
listed at the top.

stale_mapping.c

/*
 * NvBufSurfTransform on the GPU resolves a new NVBUF_MEM_SURFACE_ARRAY surface to an already
 * destroyed one when the new NvBufSurface struct is allocated at the destroyed one's address.
 * Every call returns success.
 *
 *   ./stale_mapping dst  [--pinned] [--overlap] [N]
 *       N times: create a 320x240 RGB destination, memset 0, transform a grey 1080p NV12 frame
 *       into it, read it back, destroy it. Expected: grey every time.
 *
 *   ./stale_mapping src  [--overlap] [N]
 *       N times: create a 1080p NV12 source with its own grey level, transform it into one
 *       long-lived CUDA_PINNED destination, destroy it. Expected: the output shows that level.
 *
 *   ./stale_mapping pool [C] [P]
 *       C times, like a pipeline restart: create a pool of P 1080p NV12 sources with the cycle's
 *       grey level, transform each into a CUDA_PINNED destination, destroy the pool. Prints
 *       MemAvailable after each cycle. Expected: correct output and flat memory.
 *
 * --pinned  destination in NVBUF_MEM_CUDA_PINNED instead of SURFACE_ARRAY (control)
 * --overlap destroy the previous surface only after the next one exists, so the struct address
 *           cannot repeat (control)
 */
#include <cuda_runtime_api.h>
#include <nvbufsurface.h>
#include <nvbufsurftransform.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SRC_W 1920
#define SRC_H 1080
#define DST_W 320
#define DST_H 240

#define CHECK(call)                                                                   \
    do {                                                                              \
        int rc_ = (call);                                                             \
        if (rc_ != 0) {                                                               \
            fprintf(stderr, "%s:%d: %s failed: %d\n", __FILE__, __LINE__, #call, rc_); \
            exit(1);                                                                  \
        }                                                                             \
    } while (0)

static NvBufSurface *create(NvBufSurfaceMemType mem, NvBufSurfaceColorFormat fmt, uint32_t w,
                            uint32_t h) {
    NvBufSurfaceCreateParams p = {0};
    p.width = w;
    p.height = h;
    p.colorFormat = fmt;
    p.layout = NVBUF_LAYOUT_PITCH;
    p.memType = mem;
    NvBufSurface *s = NULL;
    CHECK(NvBufSurfaceCreate(&s, 1, &p));
    s->numFilled = 1;
    return s;
}

/* NV12 with constant luma and neutral chroma: the GPU turns it into RGB grey (Y-16)*255/219. */
static NvBufSurface *grey_nv12(int luma) {
    NvBufSurface *s = create(NVBUF_MEM_SURFACE_ARRAY, NVBUF_COLOR_FORMAT_NV12, SRC_W, SRC_H);
    CHECK(NvBufSurfaceMemSet(s, 0, 0, luma));
    CHECK(NvBufSurfaceMemSet(s, 0, 1, 128));
    return s;
}

static int luma_of(int i) { return 40 + (i % 8) * 25; }
static int grey_of(int luma) { return (luma - 16) * 255 / 219; }

static void transform(NvBufSurface *src, NvBufSurface *dst) {
    NvBufSurfTransformRect src_rect = {.top = 0, .left = 0, .width = SRC_W, .height = SRC_H};
    NvBufSurfTransformRect dst_rect = {.top = 0, .left = 0, .width = DST_W, .height = DST_H};
    NvBufSurfTransformParams params = {0};
    params.transform_flag =
        NVBUFSURF_TRANSFORM_CROP_SRC | NVBUFSURF_TRANSFORM_CROP_DST | NVBUFSURF_TRANSFORM_FILTER;
    params.transform_filter = NvBufSurfTransformInter_Default;
    params.src_rect = &src_rect;
    params.dst_rect = &dst_rect;
    CHECK(NvBufSurfTransform(src, dst, &params));
    CHECK(cudaDeviceSynchronize());
    CHECK(cudaGetLastError());
}

/* Red channel of the centre pixel. SURFACE_ARRAY destinations must be mapped by the caller. */
static int centre(NvBufSurface *dst) {
    NvBufSurfaceParams *p = &dst->surfaceList[0];
    const uint8_t *px = p->dataPtr;
    uint32_t pitch = p->pitch;
    if (dst->memType == NVBUF_MEM_SURFACE_ARRAY) {
        CHECK(NvBufSurfaceSyncForCpu(dst, 0, 0));
        px = p->mappedAddr.addr[0];
        pitch = p->planeParams.pitch[0];
    }
    return px[(size_t)(DST_H / 2) * pitch + (DST_W / 2) * 3];
}

static long mem_available_mib(void) {
    FILE *f = fopen("/proc/meminfo", "r");
    char line[128];
    long kb = -1;
    while (f && fgets(line, sizeof line, f))
        if (sscanf(line, "MemAvailable: %ld kB", &kb) == 1) break;
    if (f) fclose(f);
    return kb / 1024;
}

static void destroy_dst(NvBufSurface *dst) {
    if (dst->memType == NVBUF_MEM_SURFACE_ARRAY) CHECK(NvBufSurfaceUnMap(dst, 0, 0));
    CHECK(NvBufSurfaceDestroy(dst));
}

static int test_dst(int n, NvBufSurfaceMemType mem, int overlap) {
    NvBufSurface *src = grey_nv12(180), *prev = NULL;
    int want = grey_of(180), black = 0;
    for (int i = 0; i < n; i++) {
        NvBufSurface *dst = create(mem, NVBUF_COLOR_FORMAT_RGB, DST_W, DST_H);
        if (prev) destroy_dst(prev);
        prev = NULL;
        CHECK(NvBufSurfaceMemSet(dst, 0, 0, 0));
        if (mem == NVBUF_MEM_SURFACE_ARRAY) CHECK(NvBufSurfaceMap(dst, 0, 0, NVBUF_MAP_READ));
        transform(src, dst);
        int got = centre(dst);
        black += got == 0;
        printf("dst %3d  surf %p  want %3d  got %3d  %s\n", i, (void *)dst, want, got,
               got == want ? "ok" : got == 0 ? "BLACK" : "WRONG");
        if (overlap) prev = dst;
        else destroy_dst(dst);
    }
    if (prev) destroy_dst(prev);
    CHECK(NvBufSurfaceDestroy(src));
    printf("summary: %d of %d destinations black\n", black, n);
    return black ? 2 : 0;
}

static int test_src(int n, int overlap) {
    NvBufSurface *dst = create(NVBUF_MEM_CUDA_PINNED, NVBUF_COLOR_FORMAT_RGB, DST_W, DST_H);
    NvBufSurface *prev = NULL;
    int stale = 0;
    for (int i = 0; i < n; i++) {
        NvBufSurface *src = grey_nv12(luma_of(i));
        if (prev) CHECK(NvBufSurfaceDestroy(prev));
        prev = NULL;
        transform(src, dst);
        int want = grey_of(luma_of(i)), got = centre(dst);
        stale += got != want;
        printf("src %3d  surf %p  want %3d  got %3d  %s", i, (void *)src, want, got,
               got == want ? "ok" : "STALE");
        for (int j = i - 1; got != want && j >= 0; j--)
            if (got == grey_of(luma_of(j))) {
                printf(" (grey of src %d)", j);
                break;
            }
        printf("\n");
        if (overlap) prev = src;
        else CHECK(NvBufSurfaceDestroy(src));
    }
    if (prev) CHECK(NvBufSurfaceDestroy(prev));
    CHECK(NvBufSurfaceDestroy(dst));
    printf("summary: %d of %d transforms read a stale source\n", stale, n);
    return stale ? 2 : 0;
}

static int test_pool(int cycles, int size) {
    NvBufSurface *dst = create(NVBUF_MEM_CUDA_PINNED, NVBUF_COLOR_FORMAT_RGB, DST_W, DST_H);
    NvBufSurface **pool = calloc(size, sizeof *pool);
    long start = mem_available_mib();
    int total_stale = 0;
    printf("pool: %d cycles, %d NV12 1920x1080 surfaces each, MemAvailable %ld MiB\n", cycles,
           size, start);
    for (int c = 0; c < cycles; c++) {
        int want = grey_of(luma_of(c)), stale = 0;
        for (int i = 0; i < size; i++) pool[i] = grey_nv12(luma_of(c));
        for (int i = 0; i < size; i++) {
            transform(pool[i], dst);
            stale += centre(dst) != want;
        }
        for (int i = 0; i < size; i++) CHECK(NvBufSurfaceDestroy(pool[i]));
        total_stale += stale;
        long mib = mem_available_mib();
        printf("cycle %2d  stale %2d of %d  MemAvailable %ld MiB (%+ld)\n", c, stale, size, mib,
               mib - start);
        if (mib < 2048) {
            printf("stopping: MemAvailable below 2 GiB\n");
            break;
        }
    }
    free(pool);
    CHECK(NvBufSurfaceDestroy(dst));
    printf("summary: %d stale transforms, MemAvailable %+ld MiB\n", total_stale,
           mem_available_mib() - start);
    return 0;
}

int main(int argc, char **argv) {
    NvBufSurfaceMemType mem = NVBUF_MEM_SURFACE_ARRAY;
    int overlap = 0, nums[2] = {0, 0}, nnums = 0;
    if (argc < 2) goto usage;
    for (int i = 2; i < argc; i++) {
        if (!strcmp(argv[i], "--pinned")) mem = NVBUF_MEM_CUDA_PINNED;
        else if (!strcmp(argv[i], "--overlap")) overlap = 1;
        else if (nnums < 2 && atoi(argv[i]) > 0) nums[nnums++] = atoi(argv[i]);
        else goto usage;
    }

    NvBufSurfTransformConfigParams cfg = {0};
    cfg.compute_mode = NvBufSurfTransformCompute_GPU;
    cfg.gpu_id = 0;
    CHECK(NvBufSurfTransformSetSessionParams(&cfg));

    if (!strcmp(argv[1], "dst")) return test_dst(nums[0] ? nums[0] : 16, mem, overlap);
    if (!strcmp(argv[1], "src")) return test_src(nums[0] ? nums[0] : 16, overlap);
    if (!strcmp(argv[1], "pool")) return test_pool(nums[0] ? nums[0] : 12, nums[1] ? nums[1] : 30);

usage:
    fprintf(stderr, "usage: %s dst [--pinned] [--overlap] [N] | src [--overlap] [N] | pool [C] [P]\n",
            argv[0]);
    return 64;
}

Makefile

# Jetson Linux only (nvidia-l4t-multimedia, nvidia-l4t-jetson-multimedia-api, CUDA); no DeepStream.
MMAPI := /usr/src/jetson_multimedia_api
L4T := /usr/lib/aarch64-linux-gnu/nvidia
CUDA := /usr/local/cuda

stale_mapping: stale_mapping.c
	gcc -std=gnu11 -O2 -Wall -Wextra -o $@ $< \
		-I$(MMAPI)/include -I$(CUDA)/include \
		-L$(L4T) -lnvbufsurface -lnvbufsurftransform -Wl,-rpath,$(L4T) \
		-L$(CUDA)/lib64 -lcudart -Wl,-rpath,$(CUDA)/lib64

gst_restart.py

"""nvvideoconvert compute-hw=GPU across pipeline restarts in one process, GStreamer elements only.

    python3 gst_restart.py [--cycles C] [--frames N] [--pool P] [--compute GPU|VIC]
                         [--copy-hw GPU|VIC] [--pattern solid|ball] [--record out.mp4]

Each cycle builds a pipeline, runs N frames through a GPU nvvideoconvert (NVMM NV12 -> NVMM
RGBA), checks every frame that comes out, and tears the pipeline down -- a camera reconnect in
miniature. Every cycle has its own grey level (the whole frame, or the background behind the
moving ball), so a frame showing an earlier cycle's level is an old picture, and 0 is a frame
never written. The source picture carries "frame from cycle N" at the top; after the GPU stage
"now: cycle N" is added at the bottom, so in the recording an old picture gives itself away.
MemAvailable is printed after every teardown.

The converters that copy between system memory and NVMM (first and last) copy on the GPU by
default (copy-hw=GPU), which goes through the same transform path even with compute-hw=VIC.
The clean control is --compute VIC --copy-hw VIC.

The recorder encodes in software (x264enc), so no NVIDIA element touches the recording.
"""

import argparse
import gc

import gi

gi.require_version("Gst", "1.0")
gi.require_version("GstApp", "1.0")
from gi.repository import Gst, GstApp  # noqa: E402, F401  (GstApp adds AppSink.try_pull_sample)

MAX_CYCLES = 13
WIDTH, HEIGHT, FPS = 640, 360, 30
PROBES = [(10, HEIGHT // 2), (WIDTH - 10, HEIGHT // 2), (WIDTH // 2, HEIGHT // 2)]


def grey(cycle: int) -> int:
    return 40 + 16 * cycle


def mem_available_mib() -> int:
    with open("/proc/meminfo") as f:
        for line in f:
            if line.startswith("MemAvailable:"):
                return int(line.split()[1]) // 1024
    raise RuntimeError("no MemAvailable")


def classify(value: int, cycle: int) -> str:
    if abs(value - grey(cycle)) <= 6:
        return "ok"
    if value <= 6:
        return "BLACK"
    for earlier in range(cycle):
        if abs(value - grey(earlier)) <= 6:
            return f"OLD(cycle {earlier})"
    return f"other({value})"


def frame_verdict(data: bytes, cycle: int) -> str:
    # The ball can cover one probe; the background shows through at least one of the others.
    verdicts = [classify(data[(y * WIDTH + x) * 4], cycle) for x, y in PROBES]
    return "ok" if "ok" in verdicts else max(set(verdicts), key=verdicts.count)


def argb(v: int) -> int:
    return 0xFF000000 | v << 16 | v << 8 | v


class Recorder:
    """One long-lived software encoding pipeline that all cycles' frames are appended to."""

    def __init__(self, path: str) -> None:
        self._pipeline = Gst.parse_launch(
            "appsrc name=src format=time"
            f" caps=video/x-raw,format=RGBA,width={WIDTH},height={HEIGHT},framerate={FPS}/1"
            " ! videoconvert ! x264enc speed-preset=ultrafast ! h264parse ! mp4mux"
            f" ! filesink location={path}"
        )
        self._src = self._pipeline.get_by_name("src")
        self._frames = 0
        self._pipeline.set_state(Gst.State.PLAYING)

    def push(self, buf: Gst.Buffer) -> None:
        ok, info = buf.map(Gst.MapFlags.READ)
        if not ok:
            raise RuntimeError("cannot map buffer")
        out = Gst.Buffer.new_wrapped(bytes(info.data))
        buf.unmap(info)
        out.pts = self._frames * Gst.SECOND // FPS
        out.duration = Gst.SECOND // FPS
        self._frames += 1
        self._src.emit("push-buffer", out)

    def close(self) -> None:
        self._src.emit("end-of-stream")
        self._pipeline.get_bus().timed_pop_filtered(30 * Gst.SECOND, Gst.MessageType.EOS | Gst.MessageType.ERROR)
        self._pipeline.set_state(Gst.State.NULL)


def run_cycle(cycle: int, args: argparse.Namespace, recorder: Recorder | None) -> dict[str, int]:
    v = grey(cycle)
    if args.pattern == "solid":
        source = f"videotestsrc num-buffers={args.frames} pattern=solid-color foreground-color={argb(v)}"
    else:
        source = f"videotestsrc num-buffers={args.frames} pattern=ball background-color={argb(v)}"
    desc = (
        f"{source} ! video/x-raw,format=RGBA,width=1920,height=1080,framerate={FPS}/1"
        f' ! textoverlay text="frame from cycle {cycle}" valignment=top halignment=center font-desc="Sans 48"'
        f" ! nvvideoconvert output-buffers={args.pool} copy-hw={args.copy_hw}"
        " ! video/x-raw(memory:NVMM),format=NV12"
        f" ! nvvideoconvert compute-hw={args.compute} copy-hw={args.copy_hw}"
        f" ! video/x-raw(memory:NVMM),format=RGBA,width={WIDTH},height={HEIGHT}"
        f" ! nvvideoconvert copy-hw={args.copy_hw} ! video/x-raw,format=RGBA"
        f' ! textoverlay text="now: cycle {cycle}" valignment=bottom halignment=center'
        ' font-desc="Sans 20" color=0xFFFFFF00 ! appsink name=sink sync=false'
    )
    pipeline = Gst.parse_launch(desc)
    sink = pipeline.get_by_name("sink")
    pipeline.set_state(Gst.State.PLAYING)
    seen: dict[str, int] = {}
    while True:
        sample = sink.try_pull_sample(5 * Gst.SECOND)
        if sample is None:
            break
        buf = sample.get_buffer()
        ok, info = buf.map(Gst.MapFlags.READ)
        if not ok:
            raise RuntimeError("cannot map buffer")
        verdict = frame_verdict(info.data, cycle)
        buf.unmap(info)
        seen[verdict] = seen.get(verdict, 0) + 1
        if recorder is not None:
            recorder.push(buf)
    msg = pipeline.get_bus().pop_filtered(Gst.MessageType.ERROR)
    if msg is not None:
        raise RuntimeError(msg.parse_error()[0].message)
    pipeline.set_state(Gst.State.NULL)
    del sink, pipeline
    gc.collect()
    return seen


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--cycles", type=int, choices=range(1, MAX_CYCLES + 1), default=12, metavar="C")
    parser.add_argument("--frames", type=int, default=120)
    parser.add_argument("--pool", type=int, default=60)
    parser.add_argument("--compute", choices=["GPU", "VIC"], default="GPU")
    parser.add_argument("--copy-hw", choices=["GPU", "VIC"], default="GPU")
    parser.add_argument("--pattern", choices=["solid", "ball"], default="solid")
    parser.add_argument("--record", metavar="PATH")
    args = parser.parse_args()
    Gst.init(None)
    recorder = Recorder(args.record) if args.record else None
    start = mem_available_mib()
    print(
        f"compute-hw={args.compute}, copy-hw={args.copy_hw}, {args.pattern}, pool {args.pool}, {args.frames} frames per cycle,"
        f" MemAvailable {start} MiB"
    )
    for cycle in range(args.cycles):
        seen = run_cycle(cycle, args, recorder)
        mem = mem_available_mib()
        summary = ", ".join(f"{v} {k}" for k, v in sorted(seen.items(), key=lambda kv: kv[0] != "ok"))
        print(f"cycle {cycle:2d} grey {grey(cycle):3d} MemAvailable {mem} MiB ({mem - start:+d})  frames: {summary}")
    if recorder is not None:
        recorder.close()


if __name__ == "__main__":
    main()

Hi,
Do you mean there is memory leak on Orin Jetpack 7.2 r39.2.0, but no this issue on Jetpack 6.2.2 r36.5?

Hi,

We have only tested Jetson Linux r39.2.0 (JetPack 7.2) so far; we have not run it on JetPack 6.2.2
(r36.5), so we cannot say whether it is a regression. We have a single Orin NX, and moving it to
JetPack 6 would mean reflashing it; which we dont really want.

One clarification: the leak is the secondary symptom. The main problem is wrong output without any
error: when a new NVBUF_MEM_SURFACE_ARRAY surface gets the NvBufSurface address of a destroyed one,
a GPU NvBufSurfTransform reads the old surface’s picture (source) or writes into the old buffer and
leaves the new one black (destination). The leak comes from the old buffers being kept alive.
./stale_mapping src and ./stale_mapping dst show this directly; ./stale_mapping pool 12 30
shows the leak.

Thanks for looking into it.

Hi,
There is a known fix to allocating NvBufSurface on r39.2.1/Orin. Please apply attached lib and try again.

$ md5sum libnvbufsurface.so
897b4d4ef85c83f9c6877358e089c0c9 *libnvbufsurface.so

r39_21_TEST_libnvbufsurface.zip (360.9 KB)

Hi,

I tried it, but unfortunately it doesn’t change the behaviour on our side. Some details:

  • Our device runs Jetson Linux 39.2.0 (JetPack 7.2), not 39.2.1. Before testing I checked that libnvbufsurface.so.1.0.0 in nvidia-l4t-multimedia-utils 39.2.1-20260806224157 is byte-identical to our 39.2.0 version (md5 e7f33ffeb6bc77721fd7344f42fd4c43), so the test should be valid on 39.2.0. Please let me know if that assumption is wrong.
  • Your library (md5 897b4d4ef85c83f9c6877358e089c0c9) was loaded via LD_LIBRARY_PATH. LD_DEBUG=files confirms it is the only libnvbufsurface in the process; the system copy is never loaded.
  • Results with stale_mapping from my post, same as with the stock library:
Test Stock lib Test lib
./stale_mapping dst 8 of 16 destinations black 8 of 16 destinations black
./stale_mapping src 7 of 16 transforms read a stale source 7 of 16 transforms read a stale source
./stale_mapping pool 8 4 14 stale transforms, MemAvailable −202 MiB 14 stale transforms, MemAvailable −169 MiB

I’m happy to test another build or run anything that helps, e.g. with extra debug output.

Hi,
It is still not clear what the issue is. If the NvBufSurface is destroyed and then a new NvBufSurface is allocated, it seems fine that the new allocated NvBufSurface is with same pointer address.

Hi,

sorry, I buried the point. Reusing the same address is fine, that’s not the issue.

The issue is that after NvBufSurfaceDestroy, NvBufSurfTransform (GPU) seems to keep some state for the old surface, and a new surface at the same address is then resolved to the old buffer. It goes both ways:

  • new surface as source: the transform reads the old surface’s picture
  • new surface as destination: the transform writes into the old buffer, the new one stays black

All calls return 0 and CUDA reports no error. With --overlap (new surface created before the old one is destroyed, so the address differs) the output is always correct.

stale_mapping.c shows it without any pipeline: 7 of 16 transforms read a stale source, 8 of 16 destinations stay black.