Commit 7fdb4c2341 for ffmpeg

commit 7fdb4c23411c8dc0342f19b85a8729cd22afa0dc
Author: Baptiste Coudurier <baptiste.coudurier@gmail.com>
Date:   Tue Nov 24 17:02:15 2026 -0800

    avformat/mxfenc: write the JPEG 2000 Rsiz, Xsiz and Ysiz from SIZ

    Rsiz was always written as zero. Image offsets or component subsampling
    can make the reference grid differ from the decoded picture dimensions.

    Find the codestream by box length in JP2 packets to avoid false SOC
    markers. Propagate first-packet parser errors before writing the header.

    Use the coded component count for a JP2 palette that expands to RGB.

    Signed-off-by: Baptiste Coudurier <baptiste.coudurier@gmail.com>
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
    Assisted-by: Fairy

diff --git a/libavformat/mxfenc.c b/libavformat/mxfenc.c
index 5db632962d..c2d14bb776 100644
--- a/libavformat/mxfenc.c
+++ b/libavformat/mxfenc.c
@@ -86,7 +86,6 @@ typedef struct MXFIndexEntry {
 } MXFIndexEntry;

 typedef struct j2k_info_t {
-    uint16_t j2k_cap;        ///< j2k required decoder capabilities
     uint16_t j2k_rsiz;       ///< j2k required decoder capabilities (Rsiz)
     uint32_t j2k_xsiz;       ///< j2k width of the reference grid (Xsiz)
     uint32_t j2k_ysiz;       ///< j2k height of the reference grid (Ysiz)
@@ -96,6 +95,7 @@ typedef struct j2k_info_t {
     uint32_t j2k_ytsiz;      ///< j2k height of one reference tile with respect to the reference grid (YTsiz)
     uint32_t j2k_xt0siz;     ///< j2k horizontal offset from the origin of the reference grid to the left side of the first tile (XT0siz)
     uint32_t j2k_yt0siz;     ///< j2k vertical offset from the origin of the reference grid to the left side of the first tile (YT0siz)
+    uint16_t j2k_csiz;       ///< number of coded components (Csiz)
     uint8_t  j2k_comp_desc[12]; ///< j2k components descriptor (Ssiz(i), XRsiz(i), YRsiz(i))
 } j2k_info_t;

@@ -1596,7 +1596,7 @@ static int mxf_write_jpeg2000_subdesc(AVFormatContext *s, AVStream *st)
     MXFStreamContext *sc = st->priv_data;
     AVIOContext *pb = s->pb;
     int64_t pos;
-    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(st->codecpar->format);
+    unsigned int ncomponents = sc->j2k_info.j2k_csiz;

     /* JPEG2000 subdescriptor key */
     avio_write(pb, mxf_jpeg2000_subdescriptor_key, 16);
@@ -1611,10 +1611,10 @@ static int mxf_write_jpeg2000_subdesc(AVFormatContext *s, AVStream *st)
     avio_wb16(pb, sc->j2k_info.j2k_rsiz);
     /* Width of the JPEG2000 reference grid (Xsiz) */
     mxf_write_local_tag(s, 4, 0x8402);
-    avio_wb32(pb, st->codecpar->width);
+    avio_wb32(pb, sc->j2k_info.j2k_xsiz);
     /* Height of the JPEG2000 reference grid (Ysiz) */
     mxf_write_local_tag(s, 4, 0x8403);
-    avio_wb32(pb, st->codecpar->height);
+    avio_wb32(pb, sc->j2k_info.j2k_ysiz);
     /* Horizontal offset from the reference grid origin to the left side of the image area (X0siz) */
     mxf_write_local_tag(s, 4, 0x8404);
     avio_wb32(pb, sc->j2k_info.j2k_x0siz);
@@ -1635,15 +1635,15 @@ static int mxf_write_jpeg2000_subdesc(AVFormatContext *s, AVStream *st)
     avio_wb32(pb, sc->j2k_info.j2k_yt0siz);
     /* Image components number (Csiz) */
     mxf_write_local_tag(s, 2, 0x840A);
-    avio_wb16(pb, pix_desc->nb_components);
+    avio_wb16(pb, ncomponents);
     /* Array of picture components where each component comprises 3 bytes named Ssiz(i) (Pixel bitdepth - 1),
        XRSiz(i) (Horizontal sampling), YRSiz(i) (Vertical sampling). The array of 3-byte groups is preceded
        by the array header comprising a 4-byte value of the number of components followed by a 4-byte
        value of 3. */
-    mxf_write_local_tag(s, 8 + 3*pix_desc->nb_components, 0x840B);
-    avio_wb32(pb, pix_desc->nb_components);
+    mxf_write_local_tag(s, 8 + 3 * ncomponents, 0x840B);
+    avio_wb32(pb, ncomponents);
     avio_wb32(pb, 3);
-    avio_write(pb, sc->j2k_info.j2k_comp_desc, 3*pix_desc->nb_components);
+    avio_write(pb, sc->j2k_info.j2k_comp_desc, 3 * ncomponents);

     mxf_update_klv_size(pb, pos);
     return 0;
@@ -2838,34 +2838,73 @@ static int mxf_parse_ffv1_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
     return 1;
 }

+/* Position the reader within the first Contiguous Codestream box (T.800, I.5.4). */
+static int mxf_jp2_find_codestream(GetByteContext *g)
+{
+    while (bytestream2_get_bytes_left(g) >= 8) {
+        unsigned int remaining = bytestream2_get_bytes_left(g);
+        uint64_t size = bytestream2_get_be32u(g);
+        uint32_t type = bytestream2_get_be32u(g);
+        unsigned int header_size = 8;
+
+        if (size == 1) {
+            size = bytestream2_get_be64(g);
+            header_size = 16;
+        } else if (!size) {
+            size = remaining;
+        }
+        if (size < header_size || size > remaining)
+            return AVERROR_INVALIDDATA;
+        if (type == MKBETAG('j', 'p', '2', 'c')) {
+            bytestream2_init(g, g->buffer, size - header_size);
+            return 0;
+        }
+        bytestream2_skipu(g, size - header_size);
+    }
+    return AVERROR_INVALIDDATA;
+}
+
 static int mxf_parse_jpeg2000_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
 {
     MXFContext *mxf = s->priv_data;
     MXFStreamContext *sc = st->priv_data;
     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(st->codecpar->format);
     GetByteContext g;
-    uint32_t j2k_ncomponents;
+    unsigned int j2k_ncomponents;
+    int is_jp2;

     if (mxf->header_written)
         return 1;

     bytestream2_init(&g,pkt->data,pkt->size);

-    while (bytestream2_get_bytes_left(&g) >= 3 && bytestream2_peek_be16(&g) != JPEG2000_SOC)
-        bytestream2_skip(&g, 1);
+    is_jp2 = bytestream2_peek_be64(&g) == 0x0000000c6a502020;
+    if (is_jp2) {
+        if (mxf_jp2_find_codestream(&g) < 0) {
+            av_log(s, AV_LOG_ERROR, "Could not locate JPEG 2000 codestream box\n");
+            return AVERROR_INVALIDDATA;
+        }
+    } else {
+        while (bytestream2_get_bytes_left(&g) >= 3 && bytestream2_peek_be16(&g) != JPEG2000_SOC)
+            bytestream2_skip(&g, 1);
+    }

-    if (bytestream2_get_be16u(&g) != JPEG2000_SOC) {
+    if (bytestream2_get_be16(&g) != JPEG2000_SOC) {
         av_log(s, AV_LOG_ERROR, "Mandatory SOC marker is not present\n");
         return AVERROR_INVALIDDATA;
     }

     /* Extract useful size information from the SIZ marker */
-    if (bytestream2_get_be16u(&g) != JPEG2000_SIZ) {
+    if (bytestream2_get_be16(&g) != JPEG2000_SIZ) {
         av_log(s, AV_LOG_ERROR, "Mandatory SIZ marker is not present\n");
         return AVERROR_INVALIDDATA;
     }
+    if (bytestream2_get_bytes_left(&g) < 38) {
+        av_log(s, AV_LOG_ERROR, "Truncated JPEG 2000 SIZ header\n");
+        return AVERROR_INVALIDDATA;
+    }
     bytestream2_skip(&g, 2); // Skip Lsiz
-    sc->j2k_info.j2k_cap = bytestream2_get_be16u(&g);
+    sc->j2k_info.j2k_rsiz = bytestream2_get_be16u(&g);
     sc->j2k_info.j2k_xsiz = bytestream2_get_be32u(&g);
     sc->j2k_info.j2k_ysiz = bytestream2_get_be32u(&g);
     sc->j2k_info.j2k_x0siz = bytestream2_get_be32u(&g);
@@ -2875,12 +2914,22 @@ static int mxf_parse_jpeg2000_frame(AVFormatContext *s, AVStream *st, AVPacket *
     sc->j2k_info.j2k_xt0siz = bytestream2_get_be32u(&g);
     sc->j2k_info.j2k_yt0siz = bytestream2_get_be32u(&g);
     j2k_ncomponents = bytestream2_get_be16u(&g);
-    if (j2k_ncomponents != pix_desc->nb_components) {
+    if (!j2k_ncomponents || j2k_ncomponents > sizeof(sc->j2k_info.j2k_comp_desc) / 3) {
+        av_log(s, AV_LOG_ERROR, "Unsupported JPEG 2000 component count: %u\n", j2k_ncomponents);
+        return AVERROR_INVALIDDATA;
+    }
+    /* JP2 component mapping can change the decoded channel count. */
+    if (!is_jp2 && j2k_ncomponents != pix_desc->nb_components) {
         av_log(s, AV_LOG_ERROR, "Incoherence about components image number.\n");
         return AVERROR_INVALIDDATA;
     }
+    if (bytestream2_get_bytes_left(&g) < 3 * j2k_ncomponents) {
+        av_log(s, AV_LOG_ERROR, "Truncated JPEG 2000 SIZ component records\n");
+        return AVERROR_INVALIDDATA;
+    }
     bytestream2_get_bufferu(&g, sc->j2k_info.j2k_comp_desc, 3 * j2k_ncomponents);

+    sc->j2k_info.j2k_csiz = j2k_ncomponents;
     sc->frame_size = pkt->size;
     sc->sub_descriptor = JPEG2000SubDescriptor;

@@ -3593,10 +3642,8 @@ static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
             return -1;
         }
     } else if (st->codecpar->codec_id == AV_CODEC_ID_JPEG2000) {
-        if (!mxf_parse_jpeg2000_frame(s, st, pkt)) {
-            av_log(s, AV_LOG_ERROR, "could not get jpeg2000 profile\n");
-            return -1;
-        }
+        if ((err = mxf_parse_jpeg2000_frame(s, st, pkt)) < 0)
+            return err;
     }

     // codecs without sequence headers: every key frame is a random access point
diff --git a/tests/fate/mxf.mak b/tests/fate/mxf.mak
index f93c8954af..9775ad25fa 100644
--- a/tests/fate/mxf.mak
+++ b/tests/fate/mxf.mak
@@ -50,6 +50,10 @@ FATE_MXF_PROBE-$(call DEMDEC, MXF, PRORES PCM_S24LE) += fate-mxf-probe-applehdr1
 fate-mxf-probe-applehdr10: SRC = $(TARGET_SAMPLES)/mxf/Meridian-Apple_ProResProxy-HDR10.mxf
 fate-mxf-probe-applehdr10: CMD = run $(PROBE_FORMAT_STREAMS_COMMAND) -i "$(SRC)"

+# JPEG 2000 sub descriptor Rsiz, Xsiz and Ysiz from a codestream with a nonzero image origin
+FATE_MXF-$(call DEMMUX, IMAGE_J2K_PIPE, MXF, JPEG2000_DECODER) += fate-mxf-jpeg2000-siz
+fate-mxf-jpeg2000-siz: CMD = md5 -y -i $(TARGET_SAMPLES)/jpeg2000/itu-iso/codestreams_profile1/p1_01.j2k -c:v copy -fflags +bitexact -f mxf
+
 # Tests remuxing ProRes as well as writing mastering display metadata.
 FATE_MXF_FFMPEG_FFPROBE-$(call REMUX, MXF, PRORES_DECODER) += fate-mxf-remux-applehdr10
 fate-mxf-remux-applehdr10: CMD = transcode mxf $(TARGET_SAMPLES)/mxf/Meridian-Apple_ProResProxy-HDR10.mxf mxf "-map 0 -c copy" "-c copy -t 0.3" "-show_entries format_tags:stream_side_data_list:stream=index,codec_name,codec_tag:stream_tags"
diff --git a/tests/ref/fate/mxf-jpeg2000-siz b/tests/ref/fate/mxf-jpeg2000-siz
new file mode 100644
index 0000000000..4b34156378
--- /dev/null
+++ b/tests/ref/fate/mxf-jpeg2000-siz
@@ -0,0 +1 @@
+4cad1dcc752ea42c23177fb2add70247