PR #26120 opened by noahdavis319
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26120
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26120.patch

# Summary of changes

This patch series fixes how MPEG-TS handles KLV metadata, particularly 
synchronous KLV (MISB ST 1402).

Previously, the muxer did not write the required metadata access unit headers 
(ISO/IEC 13818-1, Section 2.12.4). The demuxer also handled these headers 
incorrectly, removing only the first header and only for KLV streams. As a 
result, remuxing could produce invalid MPEG-TS output or cause synchronous KLV 
to be treated as asynchronous.

This series fixes these issues by:

- **Muxer:** Writes the required metadata access unit headers and metadata 
descriptor.
- **Demuxer:** Removes all metadata access unit headers when extracting 
payloads.
- **KLV profile:** Preserves the synchronous/asynchronous designation across 
remuxing.

```fate-samples
mpegts/klv_sync.ts
```


>From 8e1d599d117e73519a41fe289d016d900b1dc258 Mon Sep 17 00:00:00 2001
From: Noah Davis <[email protected]>
Date: Mon, 16 Nov 2026 16:01:37 -0500
Subject: [PATCH 1/5] avformat/mpegtsenc: factor out writing the metadata
 descriptor

Move the metadata_descriptor writing of timed ID3 into a helper, so it
can be reused for other metadata formats, and fix the field names in the
comments. The written bytes do not change.

Signed-off-by: Noah Davis <[email protected]>
---
 libavformat/mpegtsenc.c | 26 +++++++++++++++++---------
 1 file changed, 17 insertions(+), 9 deletions(-)

diff --git a/libavformat/mpegtsenc.c b/libavformat/mpegtsenc.c
index 6682abfac4d..f1d7c5e785d 100644
--- a/libavformat/mpegtsenc.c
+++ b/libavformat/mpegtsenc.c
@@ -360,6 +360,22 @@ static void put_registration_descriptor(uint8_t **q_ptr, 
uint32_t tag)
     *q_ptr = q;
 }
 
+static void put_metadata_descriptor(uint8_t **q_ptr, int app_format,
+                                    const char *format_id)
+{
+    uint8_t *q = *q_ptr;
+    *q++ = METADATA_DESCRIPTOR;
+    *q++ = app_format == 0xffff ? 13 : 9;
+    put16(&q, app_format);      /* metadata application format */
+    if (app_format == 0xffff)
+        putbuf(&q, format_id, 4);
+    *q++ = 0xff;                /* metadata format */
+    putbuf(&q, format_id, 4);
+    *q++ = 0;                   /* metadata service ID */
+    *q++ = 0xF;                 /* decoder_config_flags|DSM-CC_flag|reserved */
+    *q_ptr = q;
+}
+
 static int get_dvb_stream_type(AVFormatContext *s, AVStream *st)
 {
     MpegTSWrite *ts = s->priv_data;
@@ -872,15 +888,7 @@ static int mpegts_write_pmt(AVFormatContext *s, 
MpegTSService *service)
             } else if (codec_id == AV_CODEC_ID_SMPTE_2038) {
                 put_registration_descriptor(&q, MKTAG('V', 'A', 'N', 'C'));
             } else if (codec_id == AV_CODEC_ID_TIMED_ID3) {
-                const char *tag = "ID3 ";
-                *q++ = METADATA_DESCRIPTOR;
-                *q++ = 13;
-                put16(&q, 0xffff);    /* metadata application format */
-                putbuf(&q, tag, strlen(tag));
-                *q++ = 0xff;        /* metadata format */
-                putbuf(&q, tag, strlen(tag));
-                *q++ = 0;            /* metadata service ID */
-                *q++ = 0xF;          /* 
metadata_locator_record_flag|MPEG_carriage_flags|reserved */
+                put_metadata_descriptor(&q, 0xffff, "ID3 ");
             }
             break;
         }
-- 
2.54.0


>From dddd16704bf4288d012705c5910af1024a67ce61 Mon Sep 17 00:00:00 2001
From: Noah Davis <[email protected]>
Date: Mon, 16 Nov 2026 16:02:41 -0500
Subject: [PATCH 2/5] avformat/mpegtsenc: write metadata streams correctly

ISO/IEC 13818-1 2.12.4 carries metadata in PES packets with stream_id
0xfc (metadata stream) as a sequence of metadata access unit cells, each
starting with a 5 byte header, and requires a metadata_descriptor for the
metadata services of a metadata stream. The muxer wrote neither, so any
metadata stream it wrote, such as SMPTE KLV with profile 0 (synchronous
KLV, MISB ST 1402), was invalid, and the demuxer, which skips the header,
dropped the first 5 bytes of every packet when reading it back.

Write each packet of a stream written with stream_type 0x15 and PES
stream_id 0xfc as one complete access unit cell, or, if it does not fit
in one PES packet, as fragments in several. Timed ID3, which uses
private_stream_1, is not affected. Applications that added the cell
header to the packets themselves must stop doing so.

Write a metadata_descriptor with the values of MISB ST 1402 for KLV
streams written with stream_type 0x15, in addition to the KLVA
registration descriptor written for all KLV streams.

KLV packets with PES stream_id 0xbd (private_stream_1) were written
without timestamps, as asynchronous KLV is. A KLV stream written with
stream_type 0x15 is a metadata stream and needs timestamps whatever its
stream_id, as timed ID3 has, so only drop them for other streams.

Signed-off-by: Noah Davis <[email protected]>
---
 libavformat/mpegtsenc.c | 55 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 54 insertions(+), 1 deletion(-)

diff --git a/libavformat/mpegtsenc.c b/libavformat/mpegtsenc.c
index f1d7c5e785d..936880bad2c 100644
--- a/libavformat/mpegtsenc.c
+++ b/libavformat/mpegtsenc.c
@@ -255,6 +255,7 @@ typedef struct MpegTSWriteStream {
     int cc;
     int discontinuity;
     int payload_size;
+    int stream_type;
     int first_timestamp_checked; ///< first pts/dts check needed
     int prev_payload_key;
     int64_t payload_pts;
@@ -271,6 +272,9 @@ typedef struct MpegTSWriteStream {
     int opus_queued_samples;
     int opus_pending_trim_start;
 
+    /* For metadata streams */
+    uint8_t metadata_au_cell_seq;
+
     DVBAC3Descriptor *dvb_ac3_desc;
 
     int nb_stream_groups;
@@ -592,7 +596,7 @@ static int mpegts_write_pmt(AVFormatContext *s, 
MpegTSService *service)
             break;
         }
 
-        stream_type = ts->m2ts_mode ? get_m2ts_stream_type(s, st) : 
get_dvb_stream_type(s, st);
+        stream_type = ts_st->stream_type;
 
         *q++ = stream_type;
         put16(&q, 0xe000 | ts_st->pid);
@@ -885,6 +889,8 @@ static int mpegts_write_pmt(AVFormatContext *s, 
MpegTSService *service)
         case AVMEDIA_TYPE_DATA:
             if (codec_id == AV_CODEC_ID_SMPTE_KLV) {
                 put_registration_descriptor(&q, MKTAG('K', 'L', 'V', 'A'));
+                if (stream_type == STREAM_TYPE_METADATA) /* see MISB ST 1402 */
+                    put_metadata_descriptor(&q, 0x0100, "KLVA");
             } else if (codec_id == AV_CODEC_ID_SMPTE_2038) {
                 put_registration_descriptor(&q, MKTAG('V', 'A', 'N', 'C'));
             } else if (codec_id == AV_CODEC_ID_TIMED_ID3) {
@@ -1261,6 +1267,9 @@ static int mpegts_init(AVFormatContext *s)
             return AVERROR(ENOMEM);
         }
 
+        ts_st->stream_type = ts->m2ts_mode ? get_m2ts_stream_type(s, st)
+                                           : get_dvb_stream_type(s, st);
+
         /* MPEG pid values < 16 are reserved. Applications which set st->id in
          * this range are assigned a calculated pid. */
         if (st->id < 16) {
@@ -1583,7 +1592,9 @@ static int get_pes_stream_id(AVFormatContext *s, AVStream 
*st, int stream_id, in
                st->codecpar->codec_id == AV_CODEC_ID_TIMED_ID3) {
         return STREAM_ID_PRIVATE_STREAM_1;
     } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
+        MpegTSWriteStream *ts_st = st->priv_data;
         if (st->codecpar->codec_id == AV_CODEC_ID_SMPTE_KLV &&
+            ts_st->stream_type != STREAM_TYPE_METADATA &&
             stream_id == STREAM_ID_PRIVATE_STREAM_1) /* asynchronous KLV */
             *async = 1;
         return stream_id != -1 ? stream_id : STREAM_ID_METADATA_STREAM;
@@ -2000,6 +2011,44 @@ static uint8_t *h26x_prefix_aud(const uint8_t *aud, 
const int aud_size,
 }
 
 #define H264_NAL_TYPE(state) (state & 0x1f)
+/* cell data that fits in one PES packet with PTS, DTS and cell header */
+#define METADATA_AU_CELL_MAX_DATA (0xffff - 3 - 10 - 5)
+
+/* metadata access unit cells - see ISO/IEC 13818-1 */
+static int mpegts_write_metadata_au(AVFormatContext *s, AVStream *st,
+                                    const uint8_t *buf, int size,
+                                    int64_t pts, int64_t dts, int key,
+                                    int stream_id)
+{
+    MpegTSWriteStream *ts_st = st->priv_data;
+    uint8_t *cell = av_malloc(5 + FFMIN(size, METADATA_AU_CELL_MAX_DATA));
+    int first = 1;
+
+    if (!cell)
+        return AVERROR(ENOMEM);
+
+    do {
+        int len = FFMIN(size, METADATA_AU_CELL_MAX_DATA);
+        int last = len == size;
+        /* 3: complete access unit, 2: first, 0: middle, 1: last fragment */
+        int fragment = (first << 1) | last;
+
+        cell[0] = 0;                               /* metadata service ID */
+        cell[1] = ts_st->metadata_au_cell_seq++;   /* sequence number */
+        cell[2] = fragment << 6 | 1 << 4 | 0x0f;   /* random access */
+        AV_WB16(cell + 3, len);
+        memcpy(cell + 5, buf, len);
+        mpegts_write_pes(s, st, cell, 5 + len, pts, dts, key, stream_id);
+
+        buf  += len;
+        size -= len;
+        first = 0;
+    } while (size > 0);
+
+    av_free(cell);
+    return 0;
+}
+
 #define HEVC_NAL_TYPE(state) ((state & 0x7e) >> 1)
 #define VVC_NAL_TYPE(state)  ((state >> 11) & 0x1f)
 static int mpegts_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
@@ -2342,6 +2391,10 @@ static int mpegts_write_packet_internal(AVFormatContext 
*s, AVPacket *pkt)
         mpegts_write_pes(s, st, buf, size, pts, dts,
                          pkt->flags & AV_PKT_FLAG_KEY, stream_id);
         return 0;
+    } else if (ts_st->stream_type == STREAM_TYPE_METADATA &&
+               get_pes_stream_id(s, st, stream_id, &(int){0}) == 
STREAM_ID_METADATA_STREAM) {
+        return mpegts_write_metadata_au(s, st, buf, size, pts, dts,
+                                        pkt->flags & AV_PKT_FLAG_KEY, 
stream_id);
     }
 
     if (ts_st->payload_size && (ts_st->payload_size + size > 
ts->pes_payload_size ||
-- 
2.54.0


>From b55762024ca819f778e5a46cc9c772d227955691 Mon Sep 17 00:00:00 2001
From: Noah Davis <[email protected]>
Date: Mon, 16 Nov 2026 16:04:31 -0500
Subject: [PATCH 3/5] avformat/mpegts: parse all metadata access unit cells of
 metadata streams

ISO/IEC 13818-1 2.12.4 carries metadata in PES packets with stream_id
0xfc (metadata stream) as a sequence of metadata access unit cells. The
demuxer skipped only the first 5 bytes of a PES payload, and only for
KLV, so the cell headers of any further cells, such as the fragments of
an access unit, were left in the data, and other metadata formats kept
all of them.

Remove the headers of all cells of a metadata stream PES packet whatever
its codec. A payload that is not a sequence of whole cells, such as
those written by the muxer before it wrote cells, is returned unchanged
instead of losing its first 5 bytes.

Signed-off-by: Noah Davis <[email protected]>
---
 libavformat/mpegts.c | 40 +++++++++++++++++++++++++++++++---------
 1 file changed, 31 insertions(+), 9 deletions(-)

diff --git a/libavformat/mpegts.c b/libavformat/mpegts.c
index 8e6d175e9a6..3a0a353aaf0 100644
--- a/libavformat/mpegts.c
+++ b/libavformat/mpegts.c
@@ -288,6 +288,7 @@ typedef struct PESContext {
     int data_index;
     int flags; /**< copied to the AVPacket flags */
     int PES_packet_length;
+    int metadata_au_cell_warned;
     int pes_header_size;
     int extended_stream_id;
     uint8_t stream_id;
@@ -1099,6 +1100,31 @@ end:
     return ret;
 }
 
+static void unwrap_metadata_au_cells(PESContext *pes, AVPacket *pkt)
+{
+    const uint8_t *p = pkt->data, *end = pkt->data + pkt->size;
+    uint8_t *q = pkt->data;
+
+    while (end - p >= 5)
+        p += 5 + AV_RB16(p + 3);
+    if (p != end) {
+        if (!pes->metadata_au_cell_warned)
+            av_log(pes->stream, AV_LOG_WARNING, "PID %d: metadata stream 
payload "
+                   "is not made of metadata access unit cells\n", pes->pid);
+        pes->metadata_au_cell_warned = 1;
+        return;
+    }
+
+    p = pkt->data;
+    while (p < end) {
+        int len = AV_RB16(p + 3);
+        memmove(q, p + 5, len);
+        q += len;
+        p += 5 + len;
+    }
+    pkt->size = q - pkt->data;
+}
+
 static int new_pes_packet(PESContext *pes, AVPacket *pkt)
 {
     uint8_t *sd;
@@ -1132,6 +1158,11 @@ static int new_pes_packet(PESContext *pes, AVPacket *pkt)
         }
     }
 
+    /* remove metadata access unit cell headers - see ISO/IEC 13818-1 */
+    if (pes->stream_type == STREAM_TYPE_METADATA &&
+        pes->stream_id == STREAM_ID_METADATA_STREAM)
+        unwrap_metadata_au_cells(pes, pkt);
+
     memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
 
     // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
@@ -1419,15 +1450,6 @@ skip:
                     p += sl_header_bytes;
                     buf_size -= sl_header_bytes;
                 }
-                if (pes->stream_type == STREAM_TYPE_METADATA &&
-                    pes->stream_id == STREAM_ID_METADATA_STREAM &&
-                    pes->st->codecpar->codec_id == AV_CODEC_ID_SMPTE_KLV &&
-                    buf_size >= 5) {
-                    /* skip metadata access unit header - see MISB ST 1402 */
-                    pes->pes_header_size += 5;
-                    p += 5;
-                    buf_size -= 5;
-                }
                 if (   pes->ts->fix_teletext_pts
                     && (   pes->st->codecpar->codec_id == 
AV_CODEC_ID_DVB_TELETEXT
                         || pes->st->codecpar->codec_id == 
AV_CODEC_ID_DVB_SUBTITLE)
-- 
2.54.0


>From e0725af79eebea7d60ca34f9bb2683ebd668d7ae Mon Sep 17 00:00:00 2001
From: Noah Davis <[email protected]>
Date: Mon, 16 Nov 2026 16:05:05 -0500
Subject: [PATCH 4/5] avformat/mpegts: export the KLV profile

The muxer writes KLV as a metadata stream (stream_type 0x15) only for
profile AV_PROFILE_KLVA_SYNC, but the demuxer never set the profile, so
remuxing synchronous KLV wrote it as a private data stream.

Set AV_PROFILE_KLVA_SYNC for KLV carried in a metadata stream and
AV_PROFILE_KLVA_ASYNC otherwise. ffprobe now shows the profile of KLV
streams as 0 or 1.

Signed-off-by: Noah Davis <[email protected]>
---
 libavformat/mpegts.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/libavformat/mpegts.c b/libavformat/mpegts.c
index 3a0a353aaf0..9672c2db1cd 100644
--- a/libavformat/mpegts.c
+++ b/libavformat/mpegts.c
@@ -3001,6 +3001,16 @@ static void pmt_cb(MpegTSFilter *filter, const uint8_t 
*section, int section_len
             }
         }
         p = desc_list_end;
+
+        /* synchronous KLV - see MISB ST 1402 */
+        if (st->codecpar->codec_id == AV_CODEC_ID_SMPTE_KLV) {
+            int profile = stream_type == STREAM_TYPE_METADATA ?
+                          AV_PROFILE_KLVA_SYNC : AV_PROFILE_KLVA_ASYNC;
+            if (st->codecpar->profile != profile) {
+                st->codecpar->profile = profile;
+                ffstream(st)->need_context_update = 1;
+            }
+        }
     }
 
     if (!ts->pids[pcr_pid])
-- 
2.54.0


>From ec6536e3a828fc1436ece80022856f2e251d09e4 Mon Sep 17 00:00:00 2001
From: Noah Davis <[email protected]>
Date: Mon, 16 Nov 2026 16:05:39 -0500
Subject: [PATCH 5/5] tests/fate/mpegts: add a metadata stream remux test

Remux synchronous KLV carried in metadata access unit cells, with both
complete and fragmented access units, and check the demuxed packets, the
profile and the muxed stream.

The test needs the new sample mpegts/klv_sync.ts.

Signed-off-by: Noah Davis <[email protected]>
---
 tests/fate/mpegts.mak                |  8 ++++++++
 tests/ref/fate/mpegts-klv-sync-remux | 19 +++++++++++++++++++
 2 files changed, 27 insertions(+)
 create mode 100644 tests/ref/fate/mpegts-klv-sync-remux

diff --git a/tests/fate/mpegts.mak b/tests/fate/mpegts.mak
index d9136c25c7c..3a8f5cc2eb9 100644
--- a/tests/fate/mpegts.mak
+++ b/tests/fate/mpegts.mak
@@ -80,6 +80,14 @@ fate-mpegts-dvbsub-multi-service: CMD = \
   ffmpeg -i pipe: -map 0:s -c copy -disposition:s:0 hearing_impaired -bitexact 
-f mpegts - | \
   probe -count_packets -show_entries stream_disposition=hearing_impaired -of 
default=nw=1:nk=1 pipe:
 
+# Metadata streams (stream_type 0x15, stream_id 0xfc) carry metadata access
+# unit cells (ISO/IEC 13818-1 2.12.4). On remux the demuxer must remove the
+# headers of all cells, including fragments, and the muxer must write cells
+# and the metadata descriptor again. The sample holds synchronous KLV.
+FATE_MPEGTS_FFMPEG_FFPROBE-$(call REMUX, MPEGTS) += fate-mpegts-klv-sync-remux
+fate-mpegts-klv-sync-remux: CMD = transcode mpegts 
$(TARGET_SAMPLES)/mpegts/klv_sync.ts mpegts \
+  "-map 0:d -c copy" "-map 0:d -c copy" "-show_entries 
stream=codec_name,profile"
+
 FATE_SAMPLES_FFPROBE += $(FATE_MPEGTS_PROBE-yes)
 FATE_SAMPLES_FFMPEG_FFPROBE += $(FATE_MPEGTS_FFMPEG_FFPROBE-yes)
 
diff --git a/tests/ref/fate/mpegts-klv-sync-remux 
b/tests/ref/fate/mpegts-klv-sync-remux
new file mode 100644
index 00000000000..7fe6a6f5cad
--- /dev/null
+++ b/tests/ref/fate/mpegts-klv-sync-remux
@@ -0,0 +1,19 @@
+6502afe3682c2e8e083a77b4d9ba664b *tests/data/fate/mpegts-klv-sync-remux.mpegts
+6392 tests/data/fate/mpegts-klv-sync-remux.mpegts
+#tb 0: 1/90000
+#media_type 0: data
+#codec_id 0: klv
+0,          0,          0,        0,      154, 0x13552257, S=1, MPEGTS Stream 
ID,        1, 0x00fc00fc
+0,      18000,      18000,        0,      154, 0x45492365, S=1, MPEGTS Stream 
ID,        1, 0x00fc00fc
+0,      36000,      36000,        0,      154, 0x763f2374, S=1, MPEGTS Stream 
ID,        1, 0x00fc00fc
+0,      54000,      54000,        0,      154, 0xa8332482, S=1, MPEGTS Stream 
ID,        1, 0x00fc00fc
+0,      72000,      72000,        0,      154, 0x52b32294, S=1, MPEGTS Stream 
ID,        1, 0x00fc00fc
+0,      90000,      90000,        0,      154, 0x84a723a2, S=1, MPEGTS Stream 
ID,        1, 0x00fc00fc
+0,     108000,     108000,        0,      154, 0xb69b24b0, S=1, MPEGTS Stream 
ID,        1, 0x00fc00fc
+0,     126000,     126000,        0,      154, 0xe59123bf, S=1, MPEGTS Stream 
ID,        1, 0x00fc00fc
+0,     144000,     144000,        0,      154, 0x584722cf, S=1, MPEGTS Stream 
ID,        1, 0x00fc00fc
+0,     162000,     162000,        0,      154, 0x893d22de, S=1, MPEGTS Stream 
ID,        1, 0x00fc00fc
+[STREAM]
+codec_name=klv
+profile=0
+[/STREAM]
-- 
2.54.0

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to