I'm going to post the results of my investigation, hoping it will shed some light into what's happening inside ffmpeg for people who come upon this answer.
I added 3 different implementations of the conversion logic from raw Y'UV values (see below):
- The original ffmpeg pipeline from
libswscale\output.c:yuv2gbrpf32_full_X_c. Should yield the exact same values as those extracted using ffmpeg.exe.
- The original ffmpeg pipeline, implemented using floating-point math instead of integer operations. Should yield the exact same values, up to rounding.
- A corrected pipeline using correct scaling, implemented using floating-point math.
Applying [1] to the same signals as the question above yields the exact same values, which confirms that this is where ffmpeg does the potentially wrong conversions:
>>> print("YUV (limited-range) : 235 128 128")
... print("RGB48 (ffmpeg int) : ", *yuv2rgb_ffmpeg_16bit_pipeline(235, 128, 128, False, 8))
... print("RGB24 (ffmpeg int) : ", *np.floor(np.array(yuv2rgb_ffmpeg_16bit_pipeline(235, 128, 128, False, 8))/256).tolist())
... print("")
... print("YUV (full-range) : 255 128 128")
... print("RGB48 (ffmpeg int) : ", *yuv2rgb_ffmpeg_16bit_pipeline(255, 128, 128, True, 8))
... print("RGB24 (ffmpeg int) : ", *np.floor(np.array(yuv2rgb_ffmpeg_16bit_pipeline(255, 128, 128, True, 8))/256).tolist())
... print("")
YUV (limited range) : 235 128 128
RGB48 (ffmpeg int) : 65283.0 65283.0 65283.0
RGB24 (ffmpeg int) : 255.0 255.0 255.0
YUV (full range) : 255 128 128
RGB48 (ffmpeg int) : 65280.0 65280.0 65280.0
RGB24 (ffmpeg int) : 255.0 255.0 255.0
A subsequent question is : what is causing these 16-bit values to be different from 65535? Are the differences caused by a rounding operation inside of this pipeline, or are the coefficients and scaling factors wrong in the first place?
[2] lets us prove the first hypothesis false, since it outputs the same values using only floating-point math, up to rounding:
>>> print("YUV (limited-range) : 235 128 128")
... print("RGB48 (ffmpeg int) : ", *yuv2rgb_ffmpeg_float_pipeline(235, 128, 128, False, 8))
... print("RGB24 (ffmpeg int) : ", *np.floor(np.array(yuv2rgb_ffmpeg_float_pipeline(235, 128, 128, False, 8))/256).tolist())
... print("")
... print("YUV (full-range) : 255 128 128")
... print("RGB48 (ffmpeg int) : ", *yuv2rgb_ffmpeg_float_pipeline(255, 128, 128, True, 8))
... print("RGB24 (ffmpeg int) : ", *np.floor(np.array(yuv2rgb_ffmpeg_float_pipeline(255, 128, 128, True, 8))/256).tolist())
YUV (limited-range) : 235 128 128
RGB48 (ffmpeg int) : 65283.0 65283.0 65283.0
RGB24 (ffmpeg int) : 255.0 255.0 255.0
YUV (full-range) : 255 128 128
RGB48 (ffmpeg int) : 65280.5 65280.5 65280.5
RGB24 (ffmpeg int) : 255.0 255.0 255.0
Finally, [3] is a slightly modified version of the float pipeline using the same Y'UV to RGB conversion coefficients, but removing the unneeded bit shifts and replacing the 256/65536 multiplicative factor used to convert from 8-bit to 16-bit values to 255/65535. This indeed yields the correct full-range RGB signal at 65535 for 100% signal.
>>> print("YUV (limited-range) : 235 128 128")
... print("RGB48 (ffmpeg int) : ", *yuv2rgb_ffmpeg_full_float_pipeline_correct(235, 128, 128, False, 8))
... print("RGB24 (ffmpeg int) : ", *np.floor(np.array(yuv2rgb_ffmpeg_full_float_pipeline_correct(235, 128, 128, False, 8))/256).tolist())
... print("")
... print("YUV (full-range) : 255 128 128")
... print("RGB48 (ffmpeg int) : ", *yuv2rgb_ffmpeg_full_float_pipeline_correct(255, 128, 128, True, 8))
... print("RGB24 (ffmpeg int) : ", *np.floor(np.array(yuv2rgb_ffmpeg_full_float_pipeline_correct(255, 128, 128, True, 8))/256).tolist())
YUV (limited-range) : 235 128 128
RGB48 (ffmpeg int) : 65535.0 65535.0 65535.0
RGB24 (ffmpeg int) : 255.0 255.0 255.0
YUV (full-range) : 255 128 128
RGB48 (ffmpeg int) : 65535.0 65535.0 65535.0
RGB24 (ffmpeg int) : 255.0 255.0 255.0
Additionally, here is the working version with zscale:
import cv2
import subprocess
import numpy as np
ffmpeg = "ffmpeg -hide_banner -loglevel error -y"
flags = "-sws_flags accurate_rnd+bitexact+full_chroma_int+neighbor -sws_dither none"
for input_color_range in ("tv", "pc"):
# Generate YUV444 video and encode it losslessly
subprocess.check_call(rf"{ffmpeg} -y {flags} -color_range {input_color_range} -f lavfi -i yuvtestsrc {flags} -pix_fmt yuv444p -color_range {input_color_range} -colorspace bt2020nc -x264-params qp=0 -frames 1 -c:v libx264 video_temp.mp4", shell=True)
# Extract YUV444 frame, as well as 8-bit int, 16-bit int and 32-bit float frame
subprocess.check_call(rf"{ffmpeg} -y {flags} -i video_temp.mp4 {flags} -f rawvideo video_temp_444_frame1.yuv", shell=True)
subprocess.check_call(rf"{ffmpeg} -y {flags} -i video_temp.mp4 {flags} -vf zscale,format=gbrp16le -color_range pc -pix_fmt rgb24 video_temp_444_frame1_8u.png", shell=True)
subprocess.check_call(rf"{ffmpeg} -y {flags} -i video_temp.mp4 {flags} -vf zscale,format=gbrp16le -color_range pc -pix_fmt rgb48be video_temp_444_frame1_16u.png", shell=True)
subprocess.check_call(rf"{ffmpeg} -y {flags} -i video_temp.mp4 {flags} -vf zscale,format=gbrp16le -color_range pc -pix_fmt gbrpf32be -f rawvideo video_temp_444_frame1_32f.gbrpf32be", shell=True)
# Reead these frames into (height, width, 3) Numpy arrays containing YUV or RGB data
data_8u = cv2.imread("video_temp_444_frame1_8u.png", cv2.IMREAD_UNCHANGED)[..., ::-1]
data_16u = cv2.imread("video_temp_444_frame1_16u.png", cv2.IMREAD_UNCHANGED)[..., ::-1]
data_yuv = np.rollaxis(np.frombuffer(open("video_temp_444_frame1.yuv", "rb").read()).view(np.uint8).reshape((3, 240, 320)), 0, 3).copy()
data_32f = np.rollaxis(np.frombuffer(open("video_temp_444_frame1_32f.gbrpf32be", "rb").read()).view(np.dtype(">f4")).reshape((3, 240, 320)), 0, 3).copy()
data_32f[..., (0, 1, 2)] = data_32f[..., (2, 0, 1)]
# This pixel in yuvtestsrc corresponds to limited-range YUV=(235, 128,
# 128)=(100%, 0.0, 0.0), which should correspond to 100% white, i.e.
# RGB=(100%, 100%, 100%).
if input_color_range == "tv":
i, j = 10, 294
# This pixel in yuvtestsrc corresponds to full-range YUV=(255, 128,
# 128)=(100%, 0.0, 0.0), which should correspond to 100% white, i.e.
# RGB=(100%, 100%, 100%).
elif input_color_range == "pc":
i, j = 10, 319
else:
raise Exception(input_color_range)
# Print pixel values
print("")
print(f"Values for {input_color_range}-range input video at ({i}, {j}):")
print("- 8-bit YUV input = %s" % data_yuv[i, j, :])
print("- 8-bit RGB output = %s (= %s)" % (data_8u[i, j, :], data_8u[i, j, :] / 255))
print("- 16-bit RGB output = %s (= %s)" % (data_16u[i, j, :], data_16u[i, j, :] / 65535))
print("- Float RGB output = %s" % data_32f[i, j, :])
The values are indeed correct:
Values for tv-range input video at (10, 294):
- 8-bit YUV input = [235 128 128]
- 8-bit RGB output = [255 255 255] (= [1. 1. 1.])
- 16-bit RGB output = [65535 65535 65535] (= [1. 1. 1.])
- Float RGB output = [0.99998474 1. 1. ]
Values for pc-range input video at (10, 319):
- 8-bit YUV input = [255 128 128]
- 8-bit RGB output = [255 255 255] (= [1. 1. 1.])
- 16-bit RGB output = [65535 65535 65535] (= [1. 1. 1.])
- Float RGB output = [0.99998474 1. 1. ]
[1] Original pipeline used in ffmpeg gbrpf32 conversion routine:
def yuv2rgb_ffmpeg_16bit_pipeline(pY, pU, pV, fullRange, depth):
# Coefficients for ITU-R BT.2020 NCL
# libswscale\yuv2rgb.c:ff_yuv2rgb_coeffs:58 (ffmpeg 5.1.2)
crv, cbu, cgu, cgv = 110013, 140363, 12277, 42626
# libswscale\yuv2rgb.c:roundToInt16:762 (ffmpeg 5.1.2)
def roundToInt16(f: np.int64) -> np.int16:
r = (f + (np.int64(1) << 15)) >> 16
if r < -0x7FFF:
return np.int16(0x8000)
elif r > 0x7FFF:
return np.int16(0x7FFF)
return np.int16(r)
# libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:813 (ffmpeg 5.1.2)
cy = np.int64(1) << 16
oy = np.int64(0)
# libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:817 (ffmpeg 5.1.2)
if not fullRange:
cy = (cy * 255) // 219
oy = np.int64(16) << 16
else:
crv = (crv * 224) // 255
cbu = (cbu * 224) // 255
cgu = (cgu * 224) // 255
cgv = (cgv * 224) // 255
# libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:811 (ffmpeg 5.1.2)
cgu = -cgu
cgv = -cgv
# libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:836 (ffmpeg 5.1.2)
yuv2rgb_y_coeff = roundToInt16(cy * (np.int64(1) << 13))
yuv2rgb_y_offset = roundToInt16(oy * (np.int64(1) << 9))
yuv2rgb_v2r_coeff = roundToInt16(crv * (np.int64(1) << 13))
yuv2rgb_v2g_coeff = roundToInt16(cgv * (np.int64(1) << 13))
yuv2rgb_u2g_coeff = roundToInt16(cgu * (np.int64(1) << 13))
yuv2rgb_u2b_coeff = roundToInt16(cbu * (np.int64(1) << 13))
# libswscale\output.c:yuv2gbrpf32_full_X_c:2389 (ffmpeg 5.1.2)
Y = -np.int64(0x40000000)
U = -(np.int64(128) << 23)
V = -(np.int64(128) << 23)
# libswscale\output.c:yuv2gbrpf32_full_X_c:2394 (ffmpeg 5.1.2)
# NOTE: Ffmpeg refers to a filter with multiple pixels, here we only add one.
Y += np.int64(pY) << (31-depth)
U += np.int64(pU) << (31-depth)
V += np.int64(pV) << (31-depth)
# libswscale\output.c:yuv2gbrpf32_full_X_c:2402 (ffmpeg 5.1.2)
Y >>= 14
Y += 0x10000
U >>= 14
V >>= 14
# libswscale\output.c:yuv2gbrpf32_full_X_c:2417 (ffmpeg 5.1.2)
Y -= yuv2rgb_y_offset
Y *= yuv2rgb_y_coeff
Y += 1 << 13
# libswscale\output.c:yuv2gbrpf32_full_X_c:2420 (ffmpeg 5.1.2)
R = Y + V * yuv2rgb_v2r_coeff
G = Y + V * yuv2rgb_v2g_coeff + U * yuv2rgb_u2g_coeff
B = Y + U * yuv2rgb_u2b_coeff
# libswscale\output.c:yuv2gbrpf32_full_X_c:2424 (ffmpeg 5.1.2)
pR = np.round(np.clip(float(R >> 14), 0, 65535), 1)
pG = np.round(np.clip(float(G >> 14), 0, 65535), 1)
pB = np.round(np.clip(float(B >> 14), 0, 65535), 1)
return pR, pG, pB
[2] Same as the original pipeline, but computed using floating-point math instead of integers:
def yuv2rgb_ffmpeg_float_pipeline(pY, pU, pV, fullRange, depth):
# Color space conversion coefficients for YCbCr -> RGB mapping.
#
# Comment from libswscale\yuv2rgb.c:
#
# Entries are {crv, cbu, cgu, cgv}
#
# crv = (255 / 224) * 65536 * (1 - cr) / 0.5
# cbu = (255 / 224) * 65536 * (1 - cb) / 0.5
# cgu = (255 / 224) * 65536 * (cb / cg) * (1 - cb) / 0.5
# cgv = (255 / 224) * 65536 * (cr / cg) * (1 - cr) / 0.5
#
# where Y = cr * R + cg * G + cb * B and cr + cg + cb = 1.
#
# Compute the crv, cbu, cgu and cgv coefficients in float, with the same
# scaling as ffmpeg.
cr, cb = 0.2627, 0.0593
cg = 1.0 - cr - cb
fcrv = (255 / 224) * 65536 * (1 - cr) / 0.5
fcbu = (255 / 224) * 65536 * (1 - cb) / 0.5
fcgu = (255 / 224) * 65536 * (cb / cg) * (1 - cb) / 0.5
fcgv = (255 / 224) * 65536 * (cr / cg) * (1 - cr) / 0.5
# libswscale\yuv2rgb.c:roundToInt16:762 (ffmpeg 5.1.2)
def froundToInt16(f):
r = np.round(float(f) / 65536.0)
if r < -0x7FFF:
return float(0x8000)
elif r > 0x7FFF:
return float(0x7FFF)
return float(r)
# libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:813 (ffmpeg 5.1.2)
fcy = float(1 << 16)
foy = 0.0
# libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:817 (ffmpeg 5.1.2)
if not fullRange:
fcy = (fcy * 255) / 219
foy = float(16 << 16)
else:
fcrv = (fcrv * 224) / 255
fcbu = (fcbu * 224) / 255
fcgu = (fcgu * 224) / 255
fcgv = (fcgv * 224) / 255
# libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:811 (ffmpeg 5.1.2)
fcgu = -fcgu
fcgv = -fcgv
# libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:836 (ffmpeg 5.1.2)
fyuv2rgb_y_coeff = froundToInt16(fcy * float(np.int64(1) << 13))
fyuv2rgb_y_offset = froundToInt16(foy * float(np.int64(1) << 9))
fyuv2rgb_v2r_coeff = froundToInt16(fcrv * float(np.int64(1) << 13))
fyuv2rgb_v2g_coeff = froundToInt16(fcgv * float(np.int64(1) << 13))
fyuv2rgb_u2g_coeff = froundToInt16(fcgu * float(np.int64(1) << 13))
fyuv2rgb_u2b_coeff = froundToInt16(fcbu * float(np.int64(1) << 13))
# libswscale\output.c:yuv2gbrpf32_full_X_c:2389 (ffmpeg 5.1.2)
fY = -float(np.int64(128) << (31 - 8))
fU = -float(np.int64(128) << (31 - 8))
fV = -float(np.int64(128) << (31 - 8))
# libswscale\output.c:yuv2gbrpf32_full_X_c:2394 (ffmpeg 5.1.2)
# NOTE: Ffmpeg refers to a filter with multiple pixels, here we only add one.
fY += float(np.int64(pY) << (31-depth))
fU += float(np.int64(pU) << (31-depth))
fV += float(np.int64(pV) << (31-depth))
# libswscale\output.c:yuv2gbrpf32_full_X_c:2402 (ffmpeg 5.1.2)
fY /= 2**14
fY += 0x10000
fU /= 2**14
fV /= 2**14
# libswscale\output.c:yuv2gbrpf32_full_X_c:2417 (ffmpeg 5.1.2)
fY -= fyuv2rgb_y_offset
fY *= fyuv2rgb_y_coeff
fY += 1 << 13
# libswscale\output.c:yuv2gbrpf32_full_X_c:2420 (ffmpeg 5.1.2)
fR = fY + fV * fyuv2rgb_v2r_coeff
fG = fY + fV * fyuv2rgb_v2g_coeff + fU * fyuv2rgb_u2g_coeff
fB = fY + fU * fyuv2rgb_u2b_coeff
# libswscale\output.c:yuv2gbrpf32_full_X_c:2424 (ffmpeg 5.1.2)
fR = np.round(np.clip((fR / (2**14)), 0, 65535), 1)
fG = np.round(np.clip((fG / (2**14)), 0, 65535), 1)
fB = np.round(np.clip((fB / (2**14)), 0, 65535), 1)
return fR, fG, fB
[3] Correct pipeline, using the same conversion coefficients:
def yuv2rgb_ffmpeg_full_float_pipeline_correct(pY, pU, pV, fullRange, depth):
# Coefficients for ITU-R BT.2020 NCL
# libswscale\yuv2rgb.c:ff_yuv2rgb_coeffs:58 (ffmpeg 5.1.2)
crv, cbu, cgu, cgv = 110013, 140363, 12277, 42626
fcrv = crv / 65536
fcbu = cbu / 65536
fcgu = cgu / 65536
fcgv = cgv / 65536
# Equivalent to libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:813 (ffmpeg 5.1.2)
fcy = 1.0
foy = 0.0
# Equivalent to libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:817 (ffmpeg 5.1.2)
if not fullRange:
fcy = (fcy * 255) / 219
foy = 16.0 * 65535 / 255.0
else:
fcrv = (fcrv * 224) / 255
fcbu = (fcbu * 224) / 255
fcgu = (fcgu * 224) / 255
fcgv = (fcgv * 224) / 255
# Equivalent to libswscale\yuv2rgb.c:ff_yuv2rgb_c_init_tables:811 (ffmpeg 5.1.2)
fcgu = -fcgu
fcgv = -fcgv
# Equivalent to libswscale\output.c:yuv2gbrpf32_full_X_c:2389 (ffmpeg 5.1.2)
fY = float(-128) * 65535 / 255
fU = float(-128) * 65535 / 255
fV = float(-128) * 65535 / 255
# Equivalent to libswscale\output.c:yuv2gbrpf32_full_X_c:2394 (ffmpeg 5.1.2)
fY += pY * 65535 / (2**depth-1)
fU += pU * 65535 / (2**depth-1)
fV += pV * 65535 / (2**depth-1)
# Equivalent to libswscale\output.c:yuv2gbrpf32_full_X_c:2402 (ffmpeg 5.1.2)
fY += float(128) * 65535 / 255
# Equivalent to libswscale\output.c:yuv2gbrpf32_full_X_c:2417 (ffmpeg 5.1.2)
fY -= foy
fY *= fcy
# Equivalent to libswscale\output.c:yuv2gbrpf32_full_X_c:2420 (ffmpeg 5.1.2)
fR = fY + fV*fcrv
fG = fY + fV*fcgv + fU*fcgu
fB = fY + fU*fcbu
# libswscale\output.c:yuv2gbrpf32_full_X_c:2424 (ffmpeg 5.1.2)
fR = np.round(np.clip(fR, 0, 65535), 1)
fG = np.round(np.clip(fG, 0, 65535), 1)
fB = np.round(np.clip(fB, 0, 65535), 1)
return fR, fG, fB
-pix_fmt rgb48le(use Little Endian instead of Big Endian). It would be strange if the endianness of those numbers was the issue, but you never know...