Files
opencv-MIRROR/modules/videoio
Loic Goossens ca26907f49 videoio(ffmpeg): keep frame properties across av_hwframe_transfer_data()
With hardware decoding, retrieveFrame() downloads the GPU frame into a new
AVFrame with av_hwframe_transfer_data(). That call copies the pixel data
only: colorspace, color_range, color_primaries, color_trc and
chroma_location are left unspecified in the system memory copy.

With swscale >= 8.12.100 the color conversion goes through
sws_scale_frame(), which configures itself from the properties of the source
frame. Given unspecified properties it falls back to BT.601 limited range, so
hardware-decoded frames are converted with the wrong matrix whatever the
stream signals, and full range streams additionally lose contrast. Software
decoding is not affected, the decoder output carries the properties.

fftools/ffmpeg_dec.c handles this by calling av_frame_copy_props() right
after the transfer; do the same. A failure is only logged: it can only be an
allocation failure on side data, and the picture itself is still valid.

With swscale < 8.12.100 the conversion context is initialized without the
frame properties, so this change has no effect on that path.

Measured on Windows x64 with the OpenCV 5.0.0 FFmpeg wrapper built by the
opencv_3rdparty MinGW recipe against FFmpeg n8.1.3 (libswscale 9.5.103),
D3D11VA decoding, on two synthetic BT.709 H.264 samples:

  ffmpeg -f lavfi -i testsrc2=size=1280x720:rate=30 -t 2 -c:v libx264 \
         -pix_fmt yuv420p -color_range tv -colorspace bt709 \
         -color_primaries bt709 -color_trc bt709 bt709_tv.mp4
  ffmpeg -f lavfi -i testsrc2=size=1280x720:rate=30 -t 2 -c:v libx264 \
         -pix_fmt yuvj420p -color_range pc -colorspace bt709 \
         -color_primaries bt709 -color_trc bt709 bt709_pc.mp4

Frame 0 is compared with a reference built from the same static FFmpeg
libraries: software decode, lossless repack to NV12 (the D3D11VA download
format), av_frame_copy_props(), then sws_scale_frame() to BGR24 exactly as
retrieveFrame() does.

  sample          before (mean / max abs diff)   after
  bt709_tv.mp4    7.424 / 94                     bit-exact
  bt709_pc.mp4    3.286 / 101                    bit-exact

Before the patch the output is bit-exact with the same reference built
without the frame properties, which confirms the cause. Software decoding
output is unchanged (bit-exact before and after). Two real H.264 recordings
(BT.709, full and limited range) behave the same way.

Hardware and software decoding still do not produce identical pictures after
this patch: swscale converts NV12 and yuv420p differently around sharp chroma
edges. That difference exists with the same properties outside OpenCV too
and is not addressed here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 15:41:41 +02:00
..
2025-09-05 01:00:28 +08:00