Commit b8da6e3cba for ffmpeg

commit b8da6e3cba7ed9033edcec8387ec56efecb3e8e2
Author: Baptiste Coudurier <baptiste.coudurier@gmail.com>
Date:   Tue Nov 24 17:03:09 2026 -0800

    avformat/mxfenc: pad PCM elements to a constant size

    Some are one sample shorter at 30000/1001, which broke the element
    deltas and edit unit byte count. Also always write the KLV fill,
    ST 379-2 8.3. CBE ANC elements hold up to 984 bytes per edit unit.

    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 57035a5027..5db632962d 100644
--- a/libavformat/mxfenc.c
+++ b/libavformat/mxfenc.c
@@ -116,6 +116,7 @@ typedef struct MXFStreamContext {
     int video_bit_rate;
     int slice_offset;
     int frame_size;          ///< frame size in bytes
+    int element_size;        ///< KAG aligned element size, constant for PCM and CBE
     int seq_closed_gop;      ///< all gops in sequence are closed, used in mpeg-2 descriptor
     int max_gop;             ///< maximum gop size, used by mpeg-2 descriptor
     int b_picture_count;     ///< maximum number of consecutive b pictures, used in mpeg-2 descriptor
@@ -2055,6 +2056,13 @@ static unsigned klv_fill_size(uint64_t size)
         return pad & (KAG_SIZE-1);
 }

+// KAG-aligned size including the 16-byte key and 4-byte BER length,
+// and the fill KLV that always follows, ST 379-2 8.3.
+static unsigned mxf_element_size(unsigned payload)
+{
+    return FFALIGN(16 + 4 + payload + 16 + 4, KAG_SIZE);
+}
+
 /**
  * Number of slices minus 1. Elements following the VBE picture are in slice 1,
  * there should be no slices if the picture is the last element, ST 377-1 11.1.4.
@@ -2171,21 +2179,24 @@ static void mxf_write_index_table_segment_header(AVFormatContext *s, int64_t sta
         } else { // audio or data track
             avio_w8(pb, 1);
             avio_wb32(pb, element_delta);
-            // each element is KAG aligned and starts with its 16 byte key and 4 byte length
-            element_delta += 16 + 4 + sc->frame_size;
-            element_delta += klv_fill_size(element_delta);
+            element_delta += sc->element_size;
         }
     }
 }

+static void mxf_write_fill(AVIOContext *pb, unsigned size)
+{
+    avio_write(pb, klv_fill_key, 16);
+    size -= 16 + 4;
+    klv_encode_ber4_length(pb, size);
+    ffio_fill(pb, 0, size);
+}
+
 static void mxf_write_klv_fill(AVFormatContext *s)
 {
     unsigned pad = klv_fill_size(avio_tell(s->pb));
     if (pad) {
-        avio_write(s->pb, klv_fill_key, 16);
-        pad -= 16 + 4;
-        klv_encode_ber4_length(s->pb, pad);
-        ffio_fill(s->pb, 0, pad);
+        mxf_write_fill(s->pb, pad);
         av_assert1(!(avio_tell(s->pb) & (KAG_SIZE-1)));
     }
 }
@@ -3225,15 +3236,19 @@ static int mxf_init(AVFormatContext *s)

                 mxf->edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->ch_layout.nb_channels) >> 3;
                 sc->index = INDEX_WAV;
-            } else {
-                sc->frame_size = st->codecpar->ch_layout.nb_channels *
-                                 av_rescale_rnd(st->codecpar->sample_rate, mxf->time_base.num, mxf->time_base.den, AV_ROUND_UP) *
-                                 av_get_bits_per_sample(st->codecpar->codec_id) / 8;
             }
             snprintf(bsf_arg, sizeof(bsf_arg), "r=%d/%d", mxf->tc.rate.num, mxf->tc.rate.den);
             ret = ff_stream_add_bitstream_filter(st, "pcm_rechunk", bsf_arg);
             if (ret < 0)
                 return ret;
+            if (!IS_D10(s) && !IS_OPATOM(s)) {
+                // pcm_rechunk checked the channel count and frame size
+                int sample_size = st->codecpar->ch_layout.nb_channels *
+                                  (av_get_bits_per_sample(st->codecpar->codec_id) / 8);
+                sc->frame_size = sample_size * av_rescale_rnd(st->codecpar->sample_rate, mxf->time_base.num,
+                                                              mxf->time_base.den, AV_ROUND_UP);
+                sc->element_size = mxf_element_size(sc->frame_size);
+            }
         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA || st->codecpar->codec_id == AV_CODEC_ID_EIA_608) {
             AVDictionaryEntry* e = av_dict_get(st->metadata, "data_type", NULL, 0);
             if ((e && !strcmp(e->value, "vbi_vanc_smpte_436M")) ||
@@ -3513,8 +3528,12 @@ static void mxf_compute_edit_unit_byte_count(AVFormatContext *s)
         AVStream *st = s->streams[i];
         MXFStreamContext *sc = st->priv_data;
         sc->slice_offset = mxf->edit_unit_byte_count;
-        mxf->edit_unit_byte_count += 16 + 4 + sc->frame_size;
-        mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
+        // ANC packets have no fixed size, keep a KAG of payload plus the fill
+        if (sc->index == INDEX_S436M)
+            sc->element_size = mxf_element_size(KAG_SIZE - 16 - 4);
+        else if (!sc->element_size)
+            sc->element_size = mxf_element_size(sc->frame_size);
+        mxf->edit_unit_byte_count += sc->element_size;
     }
 }

@@ -3525,7 +3544,7 @@ static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
     AVStream *st = s->streams[pkt->stream_index];
     MXFStreamContext *sc = st->priv_data;
     MXFIndexEntry ie = {0};
-    int err;
+    int err, pad = 0;

     if (!mxf->header_written && pkt->stream_index != 0 &&
         !IS_OPATOM(s)) {
@@ -3647,6 +3666,22 @@ static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
             mxf->body_offset - mxf->index_entries[mxf->edit_units_count-1].offset;
     }

+    // keep fill presence consistent across content packages, ST 379-2 8.3,
+    // and pad to a constant element size
+    if (sc->index != INDEX_D10_AUDIO) {
+        unsigned element_size = sc->element_size ? sc->element_size : mxf_element_size(pkt->size);
+        unsigned max_size = element_size - 2 * (16 + 4);
+
+        if (sc->element_size && sc->frame_size)
+            max_size = FFMIN(max_size, sc->frame_size);
+        if ((unsigned)pkt->size > max_size) {
+            av_log(s, AV_LOG_ERROR, "track %d: packet size %d exceeds %u bytes per edit unit\n",
+                   st->index, pkt->size, max_size);
+            return AVERROR(EINVAL);
+        }
+        pad = element_size - 16 - 4 - pkt->size;
+    }
+
     mxf_write_klv_fill(s);
     avio_write(pb, sc->track_essence_element_key, 16); // write key
     if (IS_D10(s) && st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
@@ -3654,7 +3689,8 @@ static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
     } else {
         klv_encode_ber4_length(pb, pkt->size); // write length
         avio_write(pb, pkt->data, pkt->size);
-        mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);
+        mxf_write_fill(pb, pad);
+        mxf->body_offset += 16 + 4 + (unsigned)pkt->size + pad;
     }

     return 0;
diff --git a/tests/fate/mxf.mak b/tests/fate/mxf.mak
index 33174628c5..b711448bc5 100644
--- a/tests/fate/mxf.mak
+++ b/tests/fate/mxf.mak
@@ -96,3 +96,26 @@ fate-mxf-opatom-index-segments: CMD = md5 -filter_complex color=s=64x64:r=25 -fr

 FATE_FFMPEG += $(FATE_MXF_INDEX-yes)
 fate-mxf: $(FATE_MXF_INDEX-yes)
+
+# DV CBE with PCM alternating 1602 and 1601 samples at 30000/1001 and
+# 136, 492 and 2 byte ANC packets keeps a constant edit unit byte count.
+FATE_MXF_INDEX_FFPROBE-$(call REMUX, MXF, LAVFI_INDEV TESTSRC2_FILTER FORMAT_FILTER ANULLSRC_FILTER AFORMAT_FILTER DVVIDEO_ENCODER PCM_S24LE_ENCODER \
+                                          PCM_S32$(if $(filter yes,$(HAVE_BIGENDIAN)),BE,LE)_DECODER PCM_RECHUNK_BSF WRAPPED_AVFRAME_DECODER \
+                                          MCC_DEMUXER) += fate-mxf-pcm-anc-cbe
+tests/data/mxf-anc.mcc: TAG = COPY
+tests/data/mxf-anc.mcc: $(SRC_PATH)/tests/mxf-anc.mcc | tests/data
+	$(M)cp $< $@
+
+fate-mxf-pcm-anc-cbe: tests/data/mxf-anc.mcc
+fate-mxf-pcm-anc-cbe: CMD = transcode lavfi "testsrc2=s=720x480:r=30000/1001:d=0.1001,format=yuv411p[out0];anullsrc=r=48000:cl=5.0:d=0.1001,aformat=s32[out1]" mxf "-map 0:v -map 0:a -map 1:d -c:v dvvideo -c:a pcm_s24le -c:d copy" "-map 0 -c copy" "-show_entries packet=stream_index,pos,size -of compact" "-eia608_extract 0 -f mcc -i $(TARGET_PATH)/tests/data/mxf-anc.mcc"
+
+# VBE with 27 channel s16 PCM at 30000/1001: the 1601 sample elements are padded
+# so the delta of the next track is constant, and the 1602 sample KLV, which ends
+# on the KAG, keeps its fill, ST 379-2 8.3.
+FATE_MXF_INDEX_FFPROBE-$(call REMUX, MXF, LAVFI_INDEV TESTSRC2_FILTER ANULLSRC_FILTER AFORMAT_FILTER ARESAMPLE_FILTER \
+                                          WRAPPED_AVFRAME_DECODER PCM_U8_DECODER PCM_S16LE_ENCODER PCM_RECHUNK_BSF MPEG2VIDEO_ENCODER \
+                                          MPEGVIDEO_PARSER EXTRACT_EXTRADATA_BSF) += fate-mxf-vbe-fill-audio
+fate-mxf-vbe-fill-audio: CMD = transcode lavfi "testsrc2=s=128x96:r=30000/1001[out0];anullsrc=r=48000:cl=27C,aformat=sample_fmts=u8[out1];anullsrc=r=48000:cl=mono,aformat=sample_fmts=u8[out2]" mxf "-map 0 -c:v mpeg2video -g 0 -q:v 29 -af aresample=osf=s16 -c:a pcm_s16le -t 0.1001" "-map 0 -c copy" "-show_entries packet=stream_index,pos,size -print_format compact"
+
+FATE_FFMPEG_FFPROBE += $(FATE_MXF_INDEX_FFPROBE-yes)
+fate-mxf: $(FATE_MXF_INDEX_FFPROBE-yes)
diff --git a/tests/mxf-anc.mcc b/tests/mxf-anc.mcc
new file mode 100644
index 0000000000..c9dcf86867
--- /dev/null
+++ b/tests/mxf-anc.mcc
@@ -0,0 +1,46 @@
+File Format=MacCaption_MCC V2.0
+
+///////////////////////////////////////////////////////////////////////////////////
+// Computer Prompting and Captioning Company
+// Ancillary Data Packet Transfer File
+//
+// Permission to generate this format is granted provided that
+//   1. This ANC Transfer file format is used on an as-is basis and no warranty is given, and
+//   2. This entire descriptive information text is included in a generated .mcc file.
+//
+// General file format:
+//   HH:MM:SS:FF(tab)[Hexadecimal ANC data in groups of 2 characters]
+//     Hexadecimal data starts with the Ancillary Data Packet DID (Data ID defined in S291M)
+//       and concludes with the Check Sum following the User Data Words.
+//     Each time code line must contain at most one complete ancillary data packet.
+//     To transfer additional ANC Data successive lines may contain identical time code.
+//     Time Code Rate=[24, 25, 30, 30DF, 50, 60, 60DF]
+//
+//   ANC data bytes may be represented by one ASCII character according to the following schema:
+//     G  FAh 00h 00h
+//     H  2 x (FAh 00h 00h)
+//     I  3 x (FAh 00h 00h)
+//     J  4 x (FAh 00h 00h)
+//     K  5 x (FAh 00h 00h)
+//     L  6 x (FAh 00h 00h)
+//     M  7 x (FAh 00h 00h)
+//     N  8 x (FAh 00h 00h)
+//     O  9 x (FAh 00h 00h)
+//     P  FBh 80h 80h
+//     Q  FCh 80h 80h
+//     R  FDh 80h 80h
+//     S  96h 69h
+//     T  61h 01h
+//     U  E1h 00h 00h 00h
+//     Z  00h
+//
+///////////////////////////////////////////////////////////////////////////////////
+
+Time Code Rate=30DF
+
+00:00:00:00	T49S494F43FFFF72F4QROO74FFFFC3AB
+00:00:00:00.0,10	410104890A83015D
+00:00:00:00.1,10	410104890A83015D
+00:00:00:01	5001928080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080E3
+00:00:00:01	5001918080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808062
+00:00:00:01	5001918080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808062
diff --git a/tests/ref/fate/mxf-pcm-anc-cbe b/tests/ref/fate/mxf-pcm-anc-cbe
new file mode 100644
index 0000000000..3060d02ec0
--- /dev/null
+++ b/tests/ref/fate/mxf-pcm-anc-cbe
@@ -0,0 +1,33 @@
+48cd94e1c59f187995ef2d7b0bc6e22d *tests/data/fate/mxf-pcm-anc-cbe.mxf
+447533 tests/data/fate/mxf-pcm-anc-cbe.mxf
+#tb 0: 1001/30000
+#media_type 0: video
+#codec_id 0: dvvideo
+#dimensions 0: 720x480
+#sar 0: 8/9
+#tb 1: 1/48000
+#media_type 1: audio
+#codec_id 1: pcm_s24le
+#sample_rate 1: 48000
+#channel_layout_name 1: 5.0
+#tb 2: 1001/30000
+#media_type 2: data
+#codec_id 2: smpte_436m_anc
+0,          0,          0,        1,   120000, 0x7fc9c8da
+1,          0,          0,     1602,    24030, 0x00000000
+2,          0,          0,        1,      136, 0x9d18224f
+0,          1,          1,        1,   120000, 0x7e5fe0a5
+2,          1,          1,        1,      492, 0x49e2e054
+1,       1602,       1602,     1601,    24015, 0x00000000
+1,       3203,       3203,     1602,    24030, 0x00000000
+0,          2,          2,        1,   120000, 0x3e20d97c
+2,          2,          2,        1,        2, 0x00000000
+packet|stream_index=0|size=120000|pos=8192
+packet|stream_index=1|size=24030|pos=128512
+packet|stream_index=2|size=136|pos=153088
+packet|stream_index=0|size=120000|pos=154624
+packet|stream_index=1|size=24015|pos=274944
+packet|stream_index=2|size=492|pos=299520
+packet|stream_index=0|size=120000|pos=301056
+packet|stream_index=1|size=24030|pos=421376
+packet|stream_index=2|size=2|pos=445952
diff --git a/tests/ref/fate/mxf-vbe-fill-audio b/tests/ref/fate/mxf-vbe-fill-audio
new file mode 100644
index 0000000000..ced0d69e27
--- /dev/null
+++ b/tests/ref/fate/mxf-vbe-fill-audio
@@ -0,0 +1,36 @@
+54f12355523e485b285657d127ba1c78 *tests/data/fate/mxf-vbe-fill-audio.mxf
+286777 tests/data/fate/mxf-vbe-fill-audio.mxf
+#extradata 0:       22, 0x449e058b
+#tb 0: 1001/30000
+#media_type 0: video
+#codec_id 0: mpeg2video
+#dimensions 0: 128x96
+#sar 0: 1/1
+#tb 1: 1/48000
+#media_type 1: audio
+#codec_id 1: pcm_s16le
+#sample_rate 1: 48000
+#channel_layout_name 1: 27 channels
+#tb 2: 1/48000
+#media_type 2: audio
+#codec_id 2: pcm_s16le
+#sample_rate 2: 48000
+#channel_layout_name 2: mono
+0,         -1,          0,        1,     1016, 0xb524fc59
+0,          0,          1,        1,     1004, 0x1436ee54
+1,          0,          0,     1602,    86508, 0x00000000
+2,          0,          0,     1602,     3204, 0x00000000
+0,          1,          2,        1,     1004, 0xfe01f0b6
+1,       1602,       1602,     1601,    86454, 0x00000000
+2,       1602,       1602,     1601,     3202, 0x00000000
+1,       3203,       3203,     1602,    86508, 0x00000000
+2,       3203,       3203,     1602,     3204, 0x00000000
+packet|stream_index=0|size=1016|pos=8192
+packet|stream_index=1|size=86508|pos=9728
+packet|stream_index=2|size=3204|pos=96768
+packet|stream_index=0|size=1004|pos=100864
+packet|stream_index=1|size=86454|pos=102400
+packet|stream_index=2|size=3202|pos=189440
+packet|stream_index=0|size=1004|pos=193536
+packet|stream_index=1|size=86508|pos=195072
+packet|stream_index=2|size=3204|pos=282112