Files
opencv-MIRROR/modules
KVR Vishnu 4d6a848f5e Merge pull request #31069 from VISHNU0906:fix-30955-hdr-colorspace
videoio(ffmpeg): keep HDR transfer and primaries so HLG/PQ frames are not clipped 🤖🤖🤖 - #31069

Merge with https://github.com/opencv/opencv_extra/pull/1473

Fixes #30955

Hi @peterroelants, thanks for the detailed report and the ramp repro, it made this easy to pin down.

### What changed

Since #27755, with swscale >= 8.12.100 the conversion is set up by `sws_scale_frame()` from the two frames. `rgb_picture` had no colour properties, so swscale treated the output as SDR BT.709 and converted HLG and PQ input to it, clipping everything above SDR white to 255. This is option 1 from the issue: copy the source primaries and transfer to `rgb_picture` before the call. swscale then has no colour conversion to do and returns the decoded values like the old `sws_scale()` path (and like `ffmpeg -pix_fmt bgr24` with no output tags). The matrix and range don't need copying, swscale always treats an RGB frame as RGB, full range.

Older FFmpeg (swscale < 8.12.100) still goes through `sws_init_context()`, which ignores these fields, so nothing changes there.

### Test

New `videoio_ffmpeg_hdr.keep_decoded_values_30955` (hlg, pq) reads a 64x4 10-bit gray ramp tagged HLG or PQ (samples in the opencv_extra PR) and checks every pixel against the plain limited-range mapping, with a 3 level margin for swscale's dither. Without the fix both cases fail (mid-tones off by 10 to 20 levels, the right side of the ramp at 255).

- Debian 13 x86_64, self-built FFmpeg n8.1 (swscale 9.5.100): new tests fail before the fix, pass after. Full `opencv_test_videoio` with opencv_extra data: 564/564 pass.
- Same with the distro FFmpeg 7.1 (swscale 8.3.100): 564/564 pass, the new tests pass with or without the fix as expected.
- I also tried a PQ file with mastering display metadata: values stay within 1 level of the plain ramp.

I used AI assistance for parts of this change and tested it locally against the full test suite.

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-11-24 10:59:58 +03:00
..