Skip to content

[BUG] nvv4l2decoder: decoded picture buffer is sized from the first SPS and never grown, later streams with a larger DPB decode corrupt without an error #133

Open

Description

@sergeykad

Describe the bug

nvv4l2decoder sets up its decoded picture buffer (DPB) and its output delay from the first SPS it sees. It does not resize them when a later in-band SPS at the same frame size declares a larger DPB. The frames of the later sequence then decode corrupt, and no warning or error is printed.

A new SPS at an IDR frame with a larger max_num_ref_frames is legal H.264. ffmpeg decodes the same bytes correctly.

In the repro below, a baseline stream (max_num_ref_frames 1, no reordering) is followed by a main stream (max_num_ref_frames 4, B-frames), both 1280x720. 27 of the 30 frames of the second stream differ from ffmpeg's decode (median mean absolute difference of the Y plane 13, a correct frame is about 1.3). With the order swapped (main first, then baseline) every frame matches.

The key is the DPB size of the first SPS, not the profile. A high profile stream with a DPB of 1 followed by a main stream corrupts the same way. A high profile stream with a DPB of 4 followed by a high profile stream with 16 reference frames also corrupts.

h264parse is not the cause. It sends the new SPS and PPS in-band and new caps. The plugin logs "Pix format is h264 or h265. Bypassing set_format" for the new caps, and its in-band SPS check logs only the frame size (sps width = 1280 height = 720), so it does not reset the decoder.

A related symptom: when the input buffers carry PTS (for example from appsrc with do-timestamp=true), one frame of the later stream is also lost. The decoder logs "discarding ghost frame" at LOG level (GST_DEBUG=videodecoder:6,v4l2videodec:6), so the default log level never shows it. The corruption is the main defect.

Steps/Code to reproduce bug

The image has no ffmpeg, so the test media and the reference decode are made on the host.

Get the public sample clip from the image and make two 30-frame H.264 streams from it:

docker run --rm --entrypoint cat ghcr.io/nvidia/deepstream:9.2-triton-multiarch \
  /opt/nvidia/deepstream/deepstream/samples/streams/sample_720p.mp4 > sample_720p.mp4
ffmpeg -v error -i sample_720p.mp4 -an -c:v libx264 -preset veryfast -frames:v 30 -profile:v baseline -g 30 base.mp4
ffmpeg -v error -i sample_720p.mp4 -an -c:v libx264 -preset veryfast -frames:v 30 -profile:v main -g 30 main.mp4
for f in base main; do ffmpeg -v error -i $f.mp4 -c copy -bsf:v h264_mp4toannexb -f h264 $f.h264; done

Any 1280x720 H.264 clip works in place of sample_720p.mp4, as long as the two encodes differ in max_num_ref_frames as above.

Save as dpb_resize_repro.sh in the same folder (needs python3 with numpy, and ffmpeg, on the host):

#!/usr/bin/env bash
# nvv4l2decoder: a later clip with a larger decoded picture buffer decodes corrupt, with no error.
#
# Decodes two 1280x720 H.264 streams back to back through
#   filesrc ! h264parse ! nvv4l2decoder ! nvvideoconvert ! video/x-raw,format=I420 ! filesink
# and compares every frame with ffmpeg's decode of the same stream. The first stream is baseline
# (max_num_ref_frames 1, no reordering), the second is main (max_num_ref_frames 4, B-frames). Each SPS sits at an IDR
# frame, which makes the second stream legal. The control puts the main stream first.
#
# Test media, made on the host (the image has no ffmpeg):
#   docker run --rm --entrypoint cat ghcr.io/nvidia/deepstream:9.2-triton-multiarch \
#     /opt/nvidia/deepstream/deepstream/samples/streams/sample_720p.mp4 > sample_720p.mp4
#   ffmpeg -v error -i sample_720p.mp4 -an -c:v libx264 -preset veryfast -frames:v 30 -profile:v baseline -g 30 base.mp4
#   ffmpeg -v error -i sample_720p.mp4 -an -c:v libx264 -preset veryfast -frames:v 30 -profile:v main -g 30 main.mp4
#   for f in base main; do ffmpeg -v error -i $f.mp4 -c copy -bsf:v h264_mp4toannexb -f h264 $f.h264; done
#
# Run from the folder that holds base.h264 and main.h264 (needs python3 with numpy and ffmpeg on the host):
#   ./dpb_resize_repro.sh base main    # the bug
#   ./dpb_resize_repro.sh main base    # the control
#
# Expected: every frame of both streams matches ffmpeg (mean absolute difference of the Y plane about 1.3 after the
# colour conversion).
# Actual: after base then main, most frames of the main stream differ (27 of 30, median difference 13, in 3 of 3
# runs); a
# stream that needs a larger decoded picture buffer than the first stream of the pipeline is decoded wrong. The
# control matches. No warning or error is printed.
set -eu
first=${1:?usage: $0 <first> <second>}
second=${2:?usage: $0 <first> <second>}
cat "$first.h264" "$second.h264" >both.h264
docker run --rm --gpus all -v "$PWD":/w --entrypoint gst-launch-1.0 ghcr.io/nvidia/deepstream:9.2-triton-multiarch \
  filesrc location=/w/both.h264 ! h264parse ! nvv4l2decoder ! nvvideoconvert ! video/x-raw,format=I420 \
  ! filesink location=/w/out.yuv
ffmpeg -v error -y -i both.h264 -f rawvideo -pix_fmt yuv420p ref.yuv
python3 - <<'PY'
import numpy as np
F, Y = 1280 * 720 * 3 // 2, 1280 * 720
ref = np.fromfile("ref.yuv", np.uint8).reshape(-1, F)[:, :Y].astype(np.int16)
out = np.fromfile("out.yuv", np.uint8).reshape(-1, F)[:, :Y].astype(np.int16)
print("frames: reference", len(ref), "decoder", len(out))
for name, lo in (("first stream", 0), ("second stream", 30)):
    diffs = [float(np.abs(out[i] - ref[i]).mean()) for i in range(lo, min(lo + 30, len(out)))]
    median = sorted(diffs)[len(diffs) // 2]
    print(f"{name}: {sum(d > 3 for d in diffs)} of {len(diffs)} frames differ (median {median:.1f})")
PY

Run it:

chmod +x dpb_resize_repro.sh
./dpb_resize_repro.sh base main    # the bug
./dpb_resize_repro.sh main base    # the control

Output of ./dpb_resize_repro.sh base main (the same in 3 of 3 runs):

frames: reference 60 decoder 60
first stream: 0 of 30 frames differ (median 1.3)
second stream: 27 of 30 frames differ (median 13.0)

Output of the control ./dpb_resize_repro.sh main base:

frames: reference 60 decoder 60
first stream: 0 of 30 frames differ (median 1.3)
second stream: 0 of 30 frames differ (median 1.3)

The decoder outputs all 60 frames in both runs and prints no warning or error.

Expected behavior

Both streams decode correctly in either order, as in ffmpeg. When an in-band SPS at an IDR frame declares a larger DPB than the one in use, the decoder grows its DPB and output delay (or resets) before decoding that sequence.

Environment details (please complete the following information):

  • Environment location: Docker on bare-metal (Ubuntu 26.04.1 LTS host, kernel 7.0.0-43, NVIDIA RTX A4000 Laptop GPU 8 GB, driver 615.71.09)
  • Method of DeepStream install: Docker, ghcr.io/nvidia/deepstream:9.2-triton-multiarch (digest sha256:94a49674eb475f0416ce49742430cfbd644258b4e6512b09c76ddd90164c6dc7), DeepStream 9.2.0, TensorRT 10.16.0.72, CUDA 13.2
    • docker pull ghcr.io/nvidia/deepstream:9.2-triton-multiarch
    • docker run --rm --gpus all -v "$PWD":/w --entrypoint gst-launch-1.0 ghcr.io/nvidia/deepstream:9.2-triton-multiarch filesrc location=/w/both.h264 ! h264parse ! nvv4l2decoder ! nvvideoconvert ! video/x-raw,format=I420 ! filesink location=/w/out.yuv (run by the script above)
  • scripts/print_env.sh output, run inside the same container:
Click here to see environment details
 **git***
 Not inside a git repository
 
 ***OS Information***
 DISTRIB_ID=Ubuntu
 DISTRIB_RELEASE=24.04
 DISTRIB_CODENAME=noble
 DISTRIB_DESCRIPTION="Ubuntu 24.04.4 LTS"
 PRETTY_NAME="Ubuntu 24.04.4 LTS"
 NAME="Ubuntu"
 VERSION_ID="24.04"
 VERSION="24.04.4 LTS (Noble Numbat)"
 VERSION_CODENAME=noble
 ID=ubuntu
 ID_LIKE=debian
 HOME_URL="https://www.ubuntu.com/"
 SUPPORT_URL="https://help.ubuntu.com/"
 BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
 PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
 UBUNTU_CODENAME=noble
 LOGO=ubuntu-logo
 Linux 8e0a7babcb2f 7.0.0-43-generic #43-Ubuntu SMP PREEMPT_DYNAMIC Fri Oct 23 13:25:25 UTC 2026 x86_64 x86_64 x86_64 GNU/Linux
 
 ***GPU Information***
 Tue Nov 17 12:24:40 2026
 +-----------------------------------------------------------------------------------------+
 | NVIDIA-SMI 615.71.09              KMD Version: 615.71.09     CUDA UMD Version: 13.4     |
 +-----------------------------------------+------------------------+----------------------+
 | GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
 | Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
 |                                         |                        |               MIG M. |
 |=========================================+========================+======================|
 |   0  NVIDIA RTX A4000 Laptop GPU    Off |   00000000:01:00.0 Off |                  N/A |
 | N/A   56C    P8             16W /   80W |      13MiB /   8192MiB |      0%      Default |
 |                                         |                        |                  N/A |
 +-----------------------------------------+------------------------+----------------------+
 
 +-----------------------------------------------------------------------------------------+
 | Processes:                                                                              |
 |  GPU   GI   CI              PID   Type   Process name                        GPU Memory |
 |        ID   ID                                                               Usage      |
 |=========================================================================================|
 |  No running processes found                                                             |
 +-----------------------------------------------------------------------------------------+
 
 ***CPU***
 Architecture:                            x86_64
 CPU op-mode(s):                          32-bit, 64-bit
 Address sizes:                           39 bits physical, 48 bits virtual
 Byte Order:                              Little Endian
 CPU(s):                                  16
 On-line CPU(s) list:                     0-15
 Vendor ID:                               GenuineIntel
 Model name:                              11th Gen Intel(R) Core(TM) i9-11950H @ 2.60GHz
 CPU family:                              6
 Model:                                   141
 Thread(s) per core:                      2
 Core(s) per socket:                      8
 Socket(s):                               1
 Stepping:                                1
 CPU(s) scaling MHz:                      44%
 CPU max MHz:                             5000.0000
 CPU min MHz:                             800.0000
 BogoMIPS:                                5222.40
 Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear ibt flush_l1d arch_capabilities
 Virtualization:                          VT-x
 L1d cache:                               384 KiB (8 instances)
 L1i cache:                               256 KiB (8 instances)
 L2 cache:                                10 MiB (8 instances)
 L3 cache:                                24 MiB (1 instance)
 NUMA node(s):                            1
 NUMA node0 CPU(s):                       0-15
 Vulnerability Gather data sampling:      Vulnerable
 Vulnerability Ghostwrite:                Not affected
 Vulnerability Indirect target selection: Mitigation; Aligned branch/return thunks
 Vulnerability Itlb multihit:             Not affected
 Vulnerability L1tf:                      Not affected
 Vulnerability Mds:                       Not affected
 Vulnerability Meltdown:                  Not affected
 Vulnerability Mmio stale data:           Not affected
 Vulnerability Old microcode:             Not affected
 Vulnerability Reg file data sampling:    Not affected
 Vulnerability Retbleed:                  Not affected
 Vulnerability Spec rstack overflow:      Not affected
 Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
 Vulnerability Spectre v1:                Mitigation; usercopy/swapgs barriers and __user pointer sanitization
 Vulnerability Spectre v2:                Mitigation; Enhanced / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
 Vulnerability Srbds:                     Not affected
 Vulnerability Tsa:                       Not affected
 Vulnerability Tsx async abort:           Not affected
 Vulnerability Vmscape:                   Not affected
 
 ***CMake***
 /usr/bin/cmake
 cmake version 3.28.3
 
 CMake suite maintained and supported by Kitware (kitware.com/cmake).
 
 ***g++***
 /usr/bin/g++
 g++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0
 Copyright (C) 2023 Free Software Foundation, Inc.
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 
 ***nvcc***
 /usr/local/cuda/bin/nvcc
 nvcc: NVIDIA (R) Cuda compiler driver
 Copyright (c) 2005-2026 NVIDIA Corporation
 Built on Mon_Mar_02_09:52:23_PM_PST_2026
 Cuda compilation tools, release 13.2, V13.2.51
 Build cuda_13.2.r13.2/compiler.37434383_0
 
 ***Python***
 
 ***Environment Variables***
 PATH                            : /opt/proto/bin:/opt/tritonserver/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/mpi/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/ucx/bin:/opt/amazon/efa/bin:/.local/bin
 LD_LIBRARY_PATH                 : /opt/tritonserver/lib:/opt/tritonclient/lib:/usr/src/tensorrt/lib:/opt/riva/lib:/usr/local/cuda-13/lib64:/usr/lib/x86_64-linux-gnu:/opt/hpcx/ucc/lib/:/opt/hpcx/ucx/lib/:/usr/local/cuda/compat/lib:/usr/local/nvidia/lib:/usr/local/nvidia/lib64:/.local/lib
 NUMBAPRO_NVVM                   :
 NUMBAPRO_LIBDEVICE              :
 CONDA_PREFIX                    :
 PYTHON_PATH                     :
 
 conda not found
 ***pip packages***
 /usr/bin/pip
 Package             Version
 ------------------- ---------------
 annotated-doc       0.0.4
 annotated-types     0.7.0
 anyio               4.12.1
 apparmor            4.0.1
 certifi             2026.2.25
 cupy-cuda13x        13.6.0
 distlib             0.4.0
 distro              1.9.0
 fastapi             0.143.3
 fastrlock           0.8.3
 filelock            3.25.2
 h11                 0.16.0
 httpcore            1.0.9
 httpx               0.27.2
 idna                3.11
 iniconfig           2.3.0
 jaraco.context      6.1.0
 jiter               0.13.0
 LibAppArmor         4.0.1
 numpy               1.26.4
 openai              1.107.3
 opentelemetry-api   1.45.1
 packaging           24.0
 partial-json-parser 0.2.1.1.post7
 pip                 24.0
 platformdirs        4.9.4
 pluggy              1.6.0
 pydantic            2.10.6
 pydantic_core       2.27.2
 Pygments            2.19.2
 pyservicemaker      0.0.1
 pytest              9.0.2
 python-apt          2.7.7+ubuntu5.3
 python-discovery    1.1.3
 scipy               1.16.3
 setuptools          78.1.1
 sniffio             1.3.1
 starlette           0.52.1
 tqdm                4.67.3
 tritonfrontend      2.67.0
 tritonserver        0.0.0
 typing_extensions   4.15.0
 typing-inspection   0.4.4
 virtualenv          21.2.0
 wheel               0.42.0

Additional context

I have not seen the nvv4l2decoder sources (the image ships none), so the cause above rests on the plugin's log lines and on measurements.

What I tried:

  • Workaround that works: start the stream with a sequence that declares the largest DPB (1280x720, level 5.1, 16 reference frames, 3 B-frames, for example -profile:v high -level 5.1 -refs 16 -bf 3). After it, every later stream of the same frame size decodes correctly, in 0 of 120 frames corrupt over four clips of different profiles. The primer must have the same frame size as the later streams.
  • num-extra-surfaces=8 on nvv4l2decoder: no effect on the corruption (27 of 30 frames still differ).
  • h264parse config-interval=-1: no effect. The SPS already reaches the decoder in-band.
  • disable-dpb=true: nothing is lost, but pictures come out in decode order, so streams with B-frames are reordered wrongly.
  • An EOS between the sequences: not usable on a long-lived live appsrc, because the pipeline takes no more data after EOS. It also did not bring back the lost frame in the PTS case.

Activity

  1. nv-support commented on Nov 18, 2026

    @nv-support
    Collaborator

    We need to discuss whether to support this scenario; in the meantime, you can use the patch below as a workaround.

    diff --git a/src/3rdparty/gst-v4l2/gstv4l2videodec.c b/src/3rdparty/gst-v4l2/gstv4l2videodec.c
    index d715f900..7fedbb0c 100644
    --- a/src/3rdparty/gst-v4l2/gstv4l2videodec.c
    +++ b/src/3rdparty/gst-v4l2/gstv4l2videodec.c
    @@ -1529,6 +1529,8 @@ gst_h265_parse_process_nal (GstV4l2VideoDec *self, H265NalUnit * nalu)
           }
           self->current_width = sps.width;
           self->current_height = sps.height;
    +      self->current_dpb_size =
    +          sps.max_dec_pic_buffering_minus1[sps.max_sub_layers_minus1] + 1;
           break;
       }
     
    @@ -1572,6 +1574,7 @@ gst_h264_parse_process_nal (GstV4l2VideoDec *self, H264NalUnit * nalu)
     
           self->current_width = (sps.pic_width_in_mbs_minus1 + 1) << 4;
           self->current_height = (sps.pic_height_in_map_units_minus1 + 1) << 4;
    +      self->current_dpb_size = sps.num_ref_frames;
     
           break;
       }
    @@ -1814,10 +1817,20 @@ gst_v4l2_video_dec_handle_frame (GstVideoDecoder * decoder,
                                     self->old_width, self->old_height, self->current_width, self->current_height);
                     trigger_drc = true;
                 }
    +            else if (self->current_dpb_size > self->old_dpb_size)
    +            {
    +                /* Same size, but the new sequence needs a larger DPB than the
    +                 * previous one: restart the decoder like a resolution change. */
    +                GST_INFO_OBJECT(self, "Decoder found larger DPB. triggering DRC seq.");
    +                GST_INFO_OBJECT(self, "Old DPB: %u, New DPB: %u",
    +                                self->old_dpb_size, self->current_dpb_size);
    +                trigger_drc = true;
    +            }
             }
     
             self->old_width = self->current_width;
             self->old_height = self->current_height;
    +        self->old_dpb_size = self->current_dpb_size;
     
             if (trigger_drc == true)
             {
    @@ -2712,6 +2725,8 @@ gst_v4l2_video_dec_init (GstV4l2VideoDec * self)
       self->rate = 1;
       self->old_width = 0;
       self->old_height = 0;
    +  self->current_dpb_size = 0;
    +  self->old_dpb_size = 0;
       self->cap_buf_dynamic_allocation = DEFAULT_CAP_BUF_DYNAMIC_ALLOCATION;
     #endif
     
    diff --git a/src/3rdparty/gst-v4l2/gstv4l2videodec.h b/src/3rdparty/gst-v4l2/gstv4l2videodec.h
    index be3f8360..976bcc42 100644
    --- a/src/3rdparty/gst-v4l2/gstv4l2videodec.h
    +++ b/src/3rdparty/gst-v4l2/gstv4l2videodec.h
    @@ -109,6 +109,9 @@ struct _GstV4l2VideoDec
       guint32 current_height;
       guint32 old_width;
       guint32 old_height;
    +  /* DPB frames required by the latest SPS and by the previous one */
    +  guint32 current_dpb_size;
    +  guint32 old_dpb_size;
       gboolean valid_vpx;
       GMutex pts_hashtable_lock;
       guint64 ts;
  2. sergeykad commented on Nov 18, 2026

    @sergeykad
    Author

    Thank you for the patch. We built libgstnvvideo4linux2.so with it and ran the script of this issue on the stock 9.2-triton-multiarch image.

    It fixes the problem: every frame of the second stream now matches ffmpeg's decode in 7 of 7 runs (baseline then main, and baseline or main then a stream with 16 reference frames). The same source built with no patch still gives 27 of 30 wrong frames.

    Our pipeline decodes recorded clips from many encoders one after another on one decoder, so a later clip with a larger DPB is normal for us. A release with this fix would let us drop our workaround.

  3. added
    documentation
    enhancement
    question
    on Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

documentationenhancementquestion

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions