avcodec/pngdec: support decoding sRGB chunks

If an sRGB chunk is present in the PNG file, this commit will cause the
png decoder to ignore the cHRM and gAMA chunks and tag the resulting AVFrames
with BT.709 primaries, and ISO/IEC 61966-2-1 transfer. If these tags are
present in the AVFrame, pngenc.c already writes this chunk, so no change was
needed on the encode-side.

The PNG spec does not define what happens if sRGB and iCCP are present at
the same time, it just recommends that this not happen. As of this patch,
the decoder will have the ICC profile take precedence, and it will not tag
the pixel data as sRGB.

Signed-off-by: Leo Izen <leo.izen@gmail.com>
This commit is contained in:
Leo Izen 2023-01-17 12:32:31 -05:00
parent 2548c32cc1
commit f7bab37c8e
No known key found for this signature in database
GPG Key ID: 5A71C331FD2FA19A

View File

@ -75,6 +75,7 @@ typedef struct PNGDecContext {
int have_chrm;
uint32_t white_point[2];
uint32_t display_primaries[3][2];
int have_srgb;
enum PNGHeaderState hdr_state;
enum PNGImageState pic_state;
@ -1313,6 +1314,11 @@ static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
}
break;
}
case MKTAG('s', 'R', 'G', 'B'):
/* skip rendering intent byte */
bytestream2_skip(&gb_chunk, 1);
s->have_srgb = 1;
break;
case MKTAG('i', 'C', 'C', 'P'): {
if ((ret = decode_iccp_chunk(s, &gb_chunk, p)) < 0)
goto fail;
@ -1468,6 +1474,7 @@ static void clear_frame_metadata(PNGDecContext *s)
s->stereo_mode = -1;
s->have_chrm = 0;
s->have_srgb = 0;
av_dict_free(&s->frame_metadata);
}
@ -1486,6 +1493,9 @@ static int output_frame(PNGDecContext *s, AVFrame *f)
memcpy(sd->data, s->iccp_data, s->iccp_data_len);
av_dict_set(&sd->metadata, "name", s->iccp_name, 0);
} else if (s->have_srgb) {
avctx->color_primaries = f->color_primaries = AVCOL_PRI_BT709;
avctx->color_trc = f->color_trc = AVCOL_TRC_IEC61966_2_1;
} else if (s->have_chrm) {
AVColorPrimariesDesc desc;
enum AVColorPrimaries prim;
@ -1504,8 +1514,8 @@ static int output_frame(PNGDecContext *s, AVFrame *f)
av_log(avctx, AV_LOG_WARNING, "unknown cHRM primaries\n");
}
/* this chunk overrides gAMA */
if (s->iccp_data)
/* these chunks overrides gAMA */
if (s->iccp_data || s->have_srgb)
av_dict_set(&s->frame_metadata, "gamma", NULL, 0);
avctx->colorspace = f->colorspace = AVCOL_SPC_RGB;