Skip to content

[BUG] nvstreammux (legacy): a stream-reset event arrives after later buffers of its pad when live-source=0 #149

Todo

Description

@sergeykad

Describe the bug

A GST_NVEVENT_STREAM_RESET sent into a source between two buffers can leave the legacy nvstreammux after a batch that already holds buffers that came after it on the same pad. GStreamer serialized events keep their place among the buffers of their pad, and the reset reaches the muxer's sink pad in the right place. The muxer moves it behind the batch.

This happens with live-source=0 when the muxer takes more than one frame of a pad into one batch, for example when the other pads are at EOS. With nvtracker behind the muxer, the first frames of the next stream on that source are tracked with the previous stream's tracks. In our pipeline 2 to 9 track ids carried over from one file into the next.

The cause seems to be in sources/gst-plugins/gst-nvmultistream/gstnvstreammux.cpp, gst_nvstreammux_src_collect_buffers (line numbers from the 9.2 image):

  • Lines 3070 to 3081: when the reset is at the head of the pad's queue and the pad already has a buffer in the current batch (pad_data->num_bufs_in_current_batch > 0), the reset goes to mux->event_list.
  • Lines 3110 to 3125: the muxer then keeps taking buffers of the same pad into the batch. With live-source=0 the limit is batch_size / (n - num_queues_empty); with live-source=1 it stops after one buffer per pad.
  • Lines 4628 to 4634: event_list is pushed only after the batch.

The same check also holds a reset back when another pad's event is already waiting in event_list (|| mux->event_list). Then the reset is late with live-source=1 too. We saw this in our pipeline, on a pad next to a pad that sends a reset for every still image. The script below shows only the first case.

Steps/Code to reproduce bug

Save the script below as repro_mux_reset_order.py and run it in the stock image. It needs no model, no media and no pip install. It uses only Python ctypes with the image's GStreamer and DeepStream libraries.

docker run --rm --gpus all -v "$PWD":/repro --entrypoint python3 \
  ghcr.io/nvidia/deepstream:9.2-triton-multiarch /repro/repro_mux_reset_order.py 0
# control:
docker run --rm --gpus all -v "$PWD":/repro --entrypoint python3 \
  ghcr.io/nvidia/deepstream:9.2-triton-multiarch /repro/repro_mux_reset_order.py 1

Pipeline: three appsrc ! nvvideoconvert ! nvstreammux.sink_N lanes, then nvstreammux (legacy, batch-size=3, batched-push-timeout=4000) ! fakesink. Lanes 1 and 2 send EOS at once. A thread pushes 10 "files" of 31 raw frames into lane 0 and calls gst_element_send_event(appsrc, gst_nvevent_new_stream_reset(0)) between two files, as deepstream_source_bin.c does. A probe on the muxer's sink_0 pad records the order of buffers and resets at the input. A probe on the muxer's src pad records each batch (pad_index, frame_num from NvDsFrameMeta) and each reset at the output.

Results, 4 runs per mode. In all runs every reset reached sink_0 between the last frame of one file and the first frame of the next (9 of 9).

live-source Runs Resets that left the muxer after frames of the next file (of 9) Frames of the next file before their reset Most frames of pad 0 in one batch
0 4 4, 4, 4, 5 6, 6, 6, 5 3
1 4 0, 0, 0, 0 0 1

Output with live-source=0:

EXAMPLE reset 2 was sent before frame 62 and left the muxer after the batch with frames [60, 61, 62]
RESULT live-source=0 frames_out=310/310 resets_in_order_at_mux_input=9/9 resets_out=9/9 late_resets=4 frames_before_their_reset=6 max_frames_per_batch=3 -> DEFECT

Output with live-source=1:

RESULT live-source=1 frames_out=310/310 resets_in_order_at_mux_input=9/9 resets_out=9/9 late_resets=0 frames_before_their_reset=0 max_frames_per_batch=1 -> OK
repro_mux_reset_order.py
r"""Legacy nvstreammux: a stream-reset event sent between two buffers of a pad leaves the muxer after batches that
already hold later buffers of that pad (live-source=0).

Pipeline, three lanes into the legacy muxer (batch-size 3, batched-push-timeout 4000, live-source 0 or 1):

  appsrc src0 (raw NV12) ! nvvideoconvert ! video/x-raw(memory:NVMM) ! nvstreammux.sink_0
  appsrc src1                                                        ! nvstreammux.sink_1
  appsrc src2                                                        ! nvstreammux.sink_2
  nvstreammux ! fakesink

src1 and src2 send EOS at once, so src0 is the only lane with data, as when the other lanes of a multi-source
pipeline have finished. The muxer then takes up to 3 frames of src0 into one batch.

A thread pushes FILES x FILE_FRAMES frames into src0. Between two "files" it sends
gst_nvevent_new_stream_reset(0) to src0 with gst_element_send_event, the way deepstream_source_bin.c does. appsrc
queues serialized events in order with its buffers. Two pad probes record the order of buffers and resets:

  - on nvstreammux sink_0 (muxer input): each buffer (counted) and each stream-reset event;
  - on nvstreammux src (muxer output): each batch, with (pad_index, frame_num) of every frame from NvDsFrameMeta,
    and each stream-reset event. frame_num of pad 0 is the index of the buffer pushed into src0.

For every reset the script checks the input order (the reset arrives after the last buffer of the previous file and
before the first buffer of the next file) and counts the frames of the next file that leave the muxer before it.

The script uses only Python's ctypes and the image's libraries (GStreamer, libnvdsgst_meta, libnvdsgst_helper). No
model, no media file and no pip install are needed.

  repro_mux_reset_order.py <live-source 0|1>

Run in the stock image:

  docker run --rm --gpus all -v "$PWD":/repro --entrypoint python3 \
    ghcr.io/nvidia/deepstream:9.2-triton-multiarch /repro/repro_mux_reset_order.py 0
  # control: ... /repro/repro_mux_reset_order.py 1

Expected in both modes: every reset leaves the muxer before any frame pushed after it, so late_resets=0.

Actual, 4 runs per mode on an RTX A4000 Laptop GPU. Every reset reaches the muxer's sink pad in the right place
(9/9). With live-source=0, 4 or 5 of the 9 resets leave the muxer after a batch that holds frames of the next file:

  EXAMPLE reset 2 was sent before frame 62 and left the muxer after the batch with frames [60, 61, 62]
  RESULT live-source=0 frames_out=310/310 resets_in_order_at_mux_input=9/9 resets_out=9/9 late_resets=4
         frames_before_their_reset=6 max_frames_per_batch=3 -> DEFECT

With live-source=1 each batch holds one frame of the pad and every reset is in place:

  RESULT live-source=1 frames_out=310/310 resets_in_order_at_mux_input=9/9 resets_out=9/9 late_resets=0
         frames_before_their_reset=0 max_frames_per_batch=1 -> OK
"""

import ctypes
import sys
import threading
import time

FILES = 10
FILE_FRAMES = 31
LANES = 3
WIDTH, HEIGHT = 320, 240
FRAME_BYTES = WIDTH * HEIGHT * 3 // 2  # NV12
EOS_TIMEOUT_NS = 30 * 1_000_000_000

GST_PAD_PROBE_TYPE_BUFFER = 1 << 4
GST_PAD_PROBE_TYPE_BUFFER_LIST = 1 << 5
GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM = 1 << 6
GST_PAD_PROBE_OK = 1
GST_STATE_NULL, GST_STATE_PLAYING = 1, 4
GST_MESSAGE_EOS, GST_MESSAGE_ERROR = 1 << 0, 1 << 1
# gst-nvevent.h: GST_EVENT_MAKE_TYPE (404, DOWNSTREAM | SERIALIZED | STICKY | STICKY_MULTI)
GST_NVEVENT_STREAM_RESET = (404 << 8) | 2 | 4 | 8 | 16

DS_LIB = "/opt/nvidia/deepstream/deepstream/lib"
gst = ctypes.CDLL("libgstreamer-1.0.so.0")
gstapp = ctypes.CDLL("libgstapp-1.0.so.0")
meta = ctypes.CDLL(f"{DS_LIB}/libnvdsgst_meta.so")
helper = ctypes.CDLL(f"{DS_LIB}/libnvdsgst_helper.so")
P, U, I = ctypes.c_void_p, ctypes.c_uint, ctypes.c_int


def fn(lib, name, restype, *argtypes):
    f = getattr(lib, name)
    f.restype, f.argtypes = restype, list(argtypes)
    return f


gst_init = fn(gst, "gst_init", None, P, P)
gst_parse_launch = fn(gst, "gst_parse_launch", P, ctypes.c_char_p, ctypes.POINTER(P))
gst_bin_get_by_name = fn(gst, "gst_bin_get_by_name", P, P, ctypes.c_char_p)
gst_element_get_static_pad = fn(gst, "gst_element_get_static_pad", P, P, ctypes.c_char_p)
gst_element_set_state = fn(gst, "gst_element_set_state", I, P, I)
gst_element_send_event = fn(gst, "gst_element_send_event", I, P, P)
gst_element_get_bus = fn(gst, "gst_element_get_bus", P, P)
gst_bus_timed_pop_filtered = fn(gst, "gst_bus_timed_pop_filtered", P, P, ctypes.c_uint64, U)
gst_message_parse_error = fn(gst, "gst_message_parse_error", None, P, ctypes.POINTER(P), ctypes.POINTER(P))
gst_pad_add_probe = fn(gst, "gst_pad_add_probe", ctypes.c_ulong, P, U, P, P, P)
gst_pad_probe_info_get_buffer = fn(gst, "gst_pad_probe_info_get_buffer", P, P)
gst_pad_probe_info_get_buffer_list = fn(gst, "gst_pad_probe_info_get_buffer_list", P, P)
gst_pad_probe_info_get_event = fn(gst, "gst_pad_probe_info_get_event", P, P)
gst_buffer_list_length = fn(gst, "gst_buffer_list_length", U, P)
gst_buffer_list_get = fn(gst, "gst_buffer_list_get", P, P, U)
gst_buffer_new_allocate = fn(gst, "gst_buffer_new_allocate", P, P, ctypes.c_size_t, P)
gst_buffer_memset = fn(gst, "gst_buffer_memset", ctypes.c_size_t, P, ctypes.c_size_t, ctypes.c_uint8, ctypes.c_size_t)
gst_app_src_push_buffer = fn(gstapp, "gst_app_src_push_buffer", I, P, P)
gst_app_src_end_of_stream = fn(gstapp, "gst_app_src_end_of_stream", I, P)
gst_buffer_get_nvds_batch_meta = fn(meta, "gst_buffer_get_nvds_batch_meta", P, P)
gst_nvevent_new_stream_reset = fn(helper, "gst_nvevent_new_stream_reset", P, U)
gst_nvevent_parse_stream_reset = fn(helper, "gst_nvevent_parse_stream_reset", None, P, ctypes.POINTER(U))


class GstMiniObject(ctypes.Structure):
    _fields_ = [("type", ctypes.c_size_t), ("refcount", I), ("lockstate", I), ("flags", U),
                ("copy", P), ("dispose", P), ("free", P), ("priv_uint", U), ("priv_pointer", P)]


class GstEvent(ctypes.Structure):
    _fields_ = [("mini_object", GstMiniObject), ("type", U)]


class GstPadProbeInfo(ctypes.Structure):
    _fields_ = [("type", U), ("id", ctypes.c_ulong), ("data", P)]


class GList(ctypes.Structure):
    _fields_ = [("data", P), ("next", P), ("prev", P)]


class NvDsBaseMeta(ctypes.Structure):
    _fields_ = [("batch_meta", P), ("meta_type", I), ("uContext", P), ("copy_func", P), ("release_func", P)]


class NvDsBatchMeta(ctypes.Structure):
    _fields_ = [("base_meta", NvDsBaseMeta), ("max_frames_in_batch", U), ("num_frames_in_batch", U)]
    _fields_ += [(f"pool{i}", P) for i in range(6)] + [("frame_meta_list", P)]


class NvDsFrameMeta(ctypes.Structure):
    _fields_ = [("base_meta", NvDsBaseMeta), ("pad_index", U), ("batch_id", U), ("frame_num", I)]


PROBE = ctypes.CFUNCTYPE(I, P, P, P)
lock = threading.Lock()
inputs: list[tuple[str, int]] = []  # ("buf", index) or ("reset", source id) at nvstreammux sink_0
outputs: list[tuple] = []  # ("batch", [(pad, frame_num), ...]) or ("reset", source id) at nvstreammux src
in_count = 0


def reset_source(info) -> int | None:
    event = gst_pad_probe_info_get_event(info)
    if GstEvent.from_address(event).type != GST_NVEVENT_STREAM_RESET:
        return None
    source = U()
    gst_nvevent_parse_stream_reset(event, ctypes.byref(source))
    return source.value


def frames_of(buffer) -> list[tuple[int, int]]:
    batch = gst_buffer_get_nvds_batch_meta(buffer)
    frames = []
    node = NvDsBatchMeta.from_address(batch).frame_meta_list if batch else None
    while node:
        item = GList.from_address(node)
        frame = NvDsFrameMeta.from_address(item.data)
        frames.append((frame.pad_index, frame.frame_num))
        node = item.next
    return frames


@PROBE
def on_mux_sink(_pad, info, _data) -> int:
    global in_count
    kind = GstPadProbeInfo.from_address(info).type
    with lock:
        if kind & GST_PAD_PROBE_TYPE_BUFFER:
            inputs.append(("buf", in_count))
            in_count += 1
        elif (source := reset_source(info)) is not None:
            inputs.append(("reset", source))
    return GST_PAD_PROBE_OK


@PROBE
def on_mux_src(_pad, info, _data) -> int:
    kind = GstPadProbeInfo.from_address(info).type
    with lock:
        if kind & GST_PAD_PROBE_TYPE_BUFFER:
            outputs.append(("batch", frames_of(gst_pad_probe_info_get_buffer(info))))
        elif kind & GST_PAD_PROBE_TYPE_BUFFER_LIST:
            buffers = gst_pad_probe_info_get_buffer_list(info)
            count = gst_buffer_list_length(buffers)
            outputs.append(("batch", [f for i in range(count) for f in frames_of(gst_buffer_list_get(buffers, i))]))
        elif (source := reset_source(info)) is not None:
            outputs.append(("reset", source))
    return GST_PAD_PROBE_OK


def build(live: int) -> tuple[int, list[int]]:
    caps = f"video/x-raw,format=NV12,width={WIDTH},height={HEIGHT},framerate=30/1"
    lanes = " ".join(
        f"appsrc name=src{i} is-live=true do-timestamp=true format=time block=true max-buffers=4 caps={caps} "
        f"! nvvideoconvert ! video/x-raw(memory:NVMM),format=NV12 ! mux.sink_{i}"
        for i in range(LANES)
    )
    desc = (
        f"nvstreammux name=mux batch-size={LANES} width={WIDTH} height={HEIGHT} batched-push-timeout=4000 "
        f"live-source={live} ! fakesink sync=false async=false {lanes}"
    )
    error = P()
    pipeline = gst_parse_launch(desc.encode(), ctypes.byref(error))
    if not pipeline:
        sys.exit(f"gst_parse_launch failed: {desc}")
    mux = gst_bin_get_by_name(pipeline, b"mux")
    probes = GST_PAD_PROBE_TYPE_BUFFER | GST_PAD_PROBE_TYPE_BUFFER_LIST | GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM
    gst_pad_add_probe(gst_element_get_static_pad(mux, b"sink_0"), probes, ctypes.cast(on_mux_sink, P), None, None)
    gst_pad_add_probe(gst_element_get_static_pad(mux, b"src"), probes, ctypes.cast(on_mux_src, P), None, None)
    return pipeline, [gst_bin_get_by_name(pipeline, f"src{i}".encode()) for i in range(LANES)]


def feed(sources: list[int]) -> None:
    """Ends the other lanes at once, then pushes FILES files into src0 with a stream reset before every file after
    the first."""
    for source in sources[1:]:
        gst_app_src_end_of_stream(source)
    for file in range(FILES):
        if file:
            gst_element_send_event(sources[0], gst_nvevent_new_stream_reset(0))
        for _ in range(FILE_FRAMES):
            buffer = gst_buffer_new_allocate(None, FRAME_BYTES, None)
            gst_buffer_memset(buffer, 0, 128, FRAME_BYTES)
            gst_app_src_push_buffer(sources[0], buffer)
    gst_app_src_end_of_stream(sources[0])


def wait_eos(pipeline) -> None:
    bus = gst_element_get_bus(pipeline)
    message = gst_bus_timed_pop_filtered(bus, EOS_TIMEOUT_NS, GST_MESSAGE_EOS | GST_MESSAGE_ERROR)
    if not message:
        sys.exit("no EOS within the timeout")
    if GstEvent.from_address(message).type == GST_MESSAGE_ERROR:  # GstMessage.type sits where GstEvent.type does
        err, debug = P(), P()
        gst_message_parse_error(message, ctypes.byref(err), ctypes.byref(debug))
        sys.exit(f"pipeline error: {ctypes.cast(ctypes.cast(err, ctypes.POINTER(P))[1], ctypes.c_char_p).value}")


def verdict(live: int) -> str:
    in_order = 0
    for k in range(1, FILES):
        position = [i for i, item in enumerate(inputs) if item[0] == "reset"][k - 1]
        before = sum(1 for item in inputs[:position] if item[0] == "buf")
        in_order += before == k * FILE_FRAMES
    late_resets = early_frames = 0
    seen = -1  # highest frame_num of pad 0 that left the muxer so far
    resets_out = 0
    max_per_batch = 0
    last_batch: list[int] = []
    for kind, value in outputs:
        if kind == "batch":
            last_batch = [n for pad, n in value if pad == 0]
            max_per_batch = max(max_per_batch, len(last_batch))
            seen = max([seen, *last_batch])
        elif value == 0:
            resets_out += 1
            first_of_next_file = resets_out * FILE_FRAMES
            early = seen - first_of_next_file + 1
            if early > 0:
                if not late_resets:
                    print(
                        f"EXAMPLE reset {resets_out} was sent before frame {first_of_next_file} and left the muxer "
                        f"after the batch with frames {last_batch}",
                        flush=True,
                    )
                late_resets += 1
                early_frames += early
    frames_out = sum(1 for kind, value in outputs if kind == "batch" for pad, _ in value if pad == 0)
    result = "DEFECT" if late_resets else "OK"
    return (
        f"RESULT live-source={live} frames_out={frames_out}/{FILES * FILE_FRAMES} resets_in_order_at_mux_input="
        f"{in_order}/{FILES - 1} resets_out={resets_out}/{FILES - 1} late_resets={late_resets} "
        f"frames_before_their_reset={early_frames} max_frames_per_batch={max_per_batch} -> {result}"
    )


def main() -> None:
    live = int(sys.argv[1])
    gst_init(None, None)
    pipeline, sources = build(live)
    gst_element_set_state(pipeline, GST_STATE_PLAYING)
    feeder = threading.Thread(target=feed, args=(sources,), daemon=True)
    started = time.monotonic()
    feeder.start()
    wait_eos(pipeline)
    feeder.join()
    gst_element_set_state(pipeline, GST_STATE_NULL)
    print(f"run took {time.monotonic() - started:.1f} s", flush=True)
    print(verdict(live), flush=True)


if __name__ == "__main__":
    main()

Expected behavior

The reset leaves the muxer in the same place among its pad's buffers as it came in. Every frame pushed after the reset is in a batch that comes after the reset, so nvtracker removes the stream before it sees the first frame of the next stream. One way to get this: when a held event of a pad is waiting, stop taking more buffers of that pad into the current batch.

Environment overview

  • Environment: Docker
  • Method of install: stock image ghcr.io/nvidia/deepstream:9.2-triton-multiarch

Environment details

  • Docker on bare metal (Ubuntu host, RTX A4000 Laptop GPU, driver 615.71.09)
  • ghcr.io/nvidia/deepstream:9.2-triton-multiarch (digest sha256:94a49674eb475f0416ce49742430cfbd644258b4e6512b09c76ddd90164c6dc7)
  • GStreamer 1.24.2 (from the image)

Additional context

The failure is silent: no warning in the log, and all frames and all resets come out. Only their order is wrong. live-source=1 avoids the first case, because the muxer then takes one buffer per pad into a batch. It does not avoid the second case (another pad's event waiting).

Activity

  1. wyw1267 commented on Nov 25, 2026

    @wyw1267
    Collaborator

    For your use case, we consider the streams before and after the reset to be the same source. Therefore, nvstreammux does not intentionally split the batch at the stream-reset boundary. We may not handle the stream-reset boundary explicitly for frames within the same batch. Could you use live-source=1 as a temporary workaround?

  2. sergeykad commented on Nov 25, 2026

    @sergeykad
    Author

    Thank you. We now run the muxer with live-source=1, and on our lane shape the first case is gone: no late reset in any live run.

    One case remains with live-source=1. In gst_nvstreammux_src_collect_buffers (sources/gst-plugins/gst-nvmultistream/gstnvstreammux.cpp in the 9.2 image, lines 3070 to 3081), the muxer also moves a reset to event_list when another pad's event is already waiting there (|| mux->event_list). We saw a late reset on a video pad with live-source=1 while the pad next to it sent a reset for every still image, and this check looks like the cause. Is that also by design?

    For nvtracker, a reset means that the frames after it belong to a new stream. If the muxer can batch frames from both sides of a reset, is there a supported way for an element after the muxer to tell which frames of a batch come after it? For example, a field in NvDsFrameMeta. Or does the new nvstreammux keep the reset in place?

  3. wyw1267 commented on Nov 26, 2026

    @wyw1267
    Collaborator

    Thank you for the additional details. Could you provide more details about your actual use case, particularly how often stream-reset events occur and why the still-image source sends a reset for every image?

    Currently, nvstreammux cannot insert a serialized reset event between individual frames inside an already assembled batched GstBuffer. Would it be acceptable in your application for a small number of frames immediately following a reset to be processed with the pre-reset state? We will evaluate whether this new scenarios needs to be supported.

  4. sergeykad commented on Nov 26, 2026

    @sergeykad
    Author

    Thank you. Our use case is a service that answers object-detection requests from a message queue. Each request is one file: a still image or a short video clip. One pipeline runs several lanes, each an appsrc into the legacy nvstreammux and then nvtracker, and each lane takes one file after another. For a video, the reply lists each tracked object once, with its best frames, under its track id. So a track id must name one object within one file, and we send a stream reset before each file.

    The still images were behind the tracker only because they shared the pipeline with the video lanes. We are moving them to a pipeline without a tracker, so stills will send no resets. In our soak, one pipeline with 4 still lanes and 1 video lane answered about 3,700 files per minute, and most of those were stills. After the change, a pipeline sends one reset per video clip, so the rate depends on clip length.

    For video, a few frames processed with the pre-reset state are acceptable. We keep the track ids the lane gave the previous file and leave them out of the next file's reply. So a late reset costs only those first frames.

    The case that remains is the one with live-source=1 from my previous comment: a reset held in event_list because another pad's event is already waiting there. With live-source=1 a batch holds at most one frame per pad, so if that reset left the muxer before the batch with its pad's next frame, no frame would meet the old state.

  5. wyw1267 commented on Nov 27, 2026

    @wyw1267
    Collaborator

    Separating still-image and video workloads into different pipelines is a good idea. Also, we will evaluate whether native support for this scenario should be added in a future update.

    One possible solution is to treat a deferred stream-reset event as a batch boundary: stop collecting additional buffers, push the current partial batch, forward the reset event downstream, and process subsequent frames in the next batch. Since nvstreammux is now open source, you are also welcome to experiment with this approach.

    Thank you for the detailed explanation and feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions