Commit bfcecc1e10 for ffmpeg

commit bfcecc1e1010f1d3fc2c128c241cffb374ca380c
Author: Romain Beauxis <romain.beauxis@gmail.com>
Date:   Thu Dec 3 08:11:20 2026 -0600

    avformat/ogg/muxer: count the samples of Opus packets

    Opus granules count the samples of each packet from the start of its
    link, instead of the input timestamps, which demuxers round, clamp and
    repeat at the start of chained links.

    The end trim of the last packet comes off the granule of the last page,
    the only one that can signal it (RFC 7845 4.4), and an end trim inside
    the link is played with a warning.

    The Opus end trim of ogg-copy-trim-opus-end is kept.

diff --git a/libavcodec/opus/Makefile b/libavcodec/opus/Makefile
index d5bd03db36..c551d1b887 100644
--- a/libavcodec/opus/Makefile
+++ b/libavcodec/opus/Makefile
@@ -31,4 +31,5 @@ OBJS-$(CONFIG_OPUS_ENCODER) +=  \
 STLIBOBJS-$(CONFIG_MATROSKA_DEMUXER) += opus/frame_duration_tab.o
 STLIBOBJS-$(CONFIG_MATROSKA_MUXER)   += opus/frame_duration_tab.o
 STLIBOBJS-$(CONFIG_MOV_DEMUXER)      += opus/frame_duration_tab.o
+STLIBOBJS-$(CONFIG_OGG_MUXER)        += opus/frame_duration_tab.o
 STLIBOBJS-$(CONFIG_WEBM_MUXER)       += opus/frame_duration_tab.o
diff --git a/libavformat/Makefile b/libavformat/Makefile
index abdc081673..5d8d0d17a5 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -763,6 +763,7 @@ SHLIBOBJS-$(CONFIG_MOV_MUXER)            += mpeg4audio_sample_rates.o \
 SHLIBOBJS-$(CONFIG_MP3_MUXER)            += mpegaudiotabs.o
 SHLIBOBJS-$(CONFIG_MXF_MUXER)            += rangecoder_dec.o
 SHLIBOBJS-$(CONFIG_NUT_MUXER)            += mpegaudiotabs.o
+SHLIBOBJS-$(CONFIG_OGG_MUXER)            += opus_frame_duration_tab.o
 SHLIBOBJS-$(CONFIG_RTPDEC)               += jpegtables.o
 SHLIBOBJS-$(CONFIG_RTP_MUXER)            += jpegtables.o \
                                             mpeg4audio_sample_rates.o
diff --git a/libavformat/ogg/muxer.c b/libavformat/ogg/muxer.c
index 2df84433c0..ac775a2381 100644
--- a/libavformat/ogg/muxer.c
+++ b/libavformat/ogg/muxer.c
@@ -617,6 +617,17 @@ static int64_t ogg_packet_start_trim(const AVPacket *pkt)
     return skip && size >= 10 ? AV_RL32(skip) : 0;
 }

+/**
+ * Number of samples to discard from the end of pkt, from its side data.
+ */
+static int64_t ogg_packet_end_trim(const AVPacket *pkt)
+{
+    size_t size;
+    const uint8_t *skip = av_packet_get_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, &size);
+
+    return skip && size >= 10 ? AV_RL32(skip + 4) : 0;
+}
+
 /**
  * Input timestamp at which a link starting with pkt starts presenting.
  */
@@ -668,8 +679,8 @@ static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
     AVStream *st = s->streams[pkt->stream_index];
     OGGContext *oggcontext = s->priv_data;
     OGGStreamContext *oggstream = st->priv_data;
-    int64_t link_pts;
-    int ret, new_link = 0;
+    int64_t link_pts, end_trim = ogg_packet_end_trim(pkt);
+    int ret, new_link = 0, end_trim_signalled = 1;

     if (oggcontext->failed)
         return AVERROR_INVALIDDATA;
@@ -681,6 +692,21 @@ static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
         return ret;
     oggstream->packet_seen = 1;

+    if (oggstream->mapping->packet_samples) {
+        int samples = oggstream->mapping->packet_samples(st, pkt);
+        /* Without explicit end padding, a duration shorter than the coded
+         * samples by more than its rounding ends the presentation early,
+         * as MP4 does. Start skip on the same packet is independent. */
+        if (samples >= 0 && pkt->duration > 0 &&
+            samples - pkt->duration > ogg_timestamp_rounding(st) &&
+            !end_trim) {
+            end_trim = samples - pkt->duration;
+            end_trim_signalled = 0;
+        }
+        if (samples >= 0)
+            pkt->duration = samples;
+    }
+
     if (oggstream->link_start_pending) {
         oggstream->link_pts_offset    = ogg_link_start(pkt);
         oggstream->link_start_pending = 0;
@@ -699,14 +725,24 @@ static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
     }

     /* Audio granules count samples: the packet durations are followed while
-     * the timestamps agree with them within their rounding. */
+     * the timestamps agree with them within their rounding, and always when
+     * the durations are read from the packets. */
     if (oggstream->next_link_pts != AV_NOPTS_VALUE &&
-        FFABS(link_pts - oggstream->next_link_pts) <= ogg_timestamp_rounding(st))
+        (oggstream->mapping->packet_samples ||
+         FFABS(link_pts - oggstream->next_link_pts) <= ogg_timestamp_rounding(st)))
         link_pts = oggstream->next_link_pts;

     ret = ogg_buffer_packet(s, st, pkt, link_pts);
     if (ret < 0)
         return ret;
+    if (oggstream->mapping->packet_samples) {
+        if (oggstream->end_trim && oggstream->end_trim_signalled)
+            av_log(s, AV_LOG_WARNING, "Stream %d: %"PRId64" samples discarded "
+                   "inside the link cannot be signalled and are played\n",
+                   st->index, oggstream->end_trim);
+        oggstream->end_trim = av_clip64(end_trim, 0, pkt->duration);
+        oggstream->end_trim_signalled = end_trim_signalled;
+    }
     if (new_link && pkt->duration > 0)
         oggstream->link_anchor = link_pts + pkt->duration;
     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
@@ -718,6 +754,31 @@ static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
     return 0;
 }

+/**
+ * Take the end trim of the last packet of the link off the granule of the
+ * page it completes on, which ends the link. Called before that page is
+ * written by the trailer.
+ */
+static void ogg_apply_end_trim(AVFormatContext *s, AVStream *st)
+{
+    OGGContext *ogg = s->priv_data;
+    OGGStreamContext *oggstream = st->priv_data;
+    OGGPage *last = oggstream->page.granule == oggstream->last_granule ? &oggstream->page : NULL;
+
+    if (!oggstream->end_trim)
+        return;
+    for (OGGPageList *p = ogg->page_list; p && !last; p = p->next)
+        if (p->page.stream_index == st->index && p->page.granule == oggstream->last_granule)
+            last = &p->page;
+    if (last)
+        last->granule -= oggstream->end_trim;
+    else
+        av_log(s, AV_LOG_WARNING, "Stream %d: the last page was flushed before "
+               "the end of the link, its end trim of %"PRId64" samples is played\n",
+               st->index, oggstream->end_trim);
+    oggstream->end_trim = 0;
+}
+
 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     int i, ret;
@@ -744,6 +805,7 @@ static int ogg_write_trailer(AVFormatContext *s)
     for (i = 0; i < s->nb_streams; i++) {
         OGGStreamContext *oggstream = s->streams[i]->priv_data;

+        ogg_apply_end_trim(s, s->streams[i]);
         if (oggstream->page.segments_count &&
             (ret = ogg_buffer_page(s, oggstream)) < 0)
             return ret;
diff --git a/libavformat/ogg/muxer.h b/libavformat/ogg/muxer.h
index 889e8689d1..2d6c710797 100644
--- a/libavformat/ogg/muxer.h
+++ b/libavformat/ogg/muxer.h
@@ -67,6 +67,9 @@ typedef struct OGGStreamContext {
     /** End of the first packet of a later link, which the second one anchors to. */
     int64_t link_anchor;
     int64_t next_link_pts; ///< end of the previous audio packet in its link
+    /** End trim of the last packet, taken off the granule of the last page of the link. */
+    int64_t end_trim;
+    int end_trim_signalled; ///< end_trim comes from side data, not from a short duration
 } OGGStreamContext;

 /**
@@ -96,6 +99,19 @@ struct OGGMuxerMapping {
      *         packet's end timestamp plus OGGStreamContext.packet_granule_offset.
      */
     int64_t (*packet_granule)(AVStream *st, const AVPacket *pkt, int64_t pts);
+    /**
+     * Set when the codec lets the duration of a packet be read from its data.
+     * The granules of a link then count these durations from its first
+     * packet, whatever the timestamps. Without it, they follow the packet
+     * durations while the timestamps agree with them within their rounding,
+     * see ogg_timestamp_rounding().
+     *
+     * Called on every packet, in order.
+     *
+     * @return the duration of a packet in the stream time base, or a negative
+     *         value when it cannot be read
+     */
+    int (*packet_samples)(AVStream *st, const AVPacket *pkt);
 };

 /**
diff --git a/libavformat/ogg/muxer/opus.c b/libavformat/ogg/muxer/opus.c
index 90fbf788d7..de1c891131 100644
--- a/libavformat/ogg/muxer/opus.c
+++ b/libavformat/ogg/muxer/opus.c
@@ -20,6 +20,7 @@
  */

 #include "libavcodec/bytestream.h"
+#include "libavcodec/opus/parse.h"
 #include "libavcodec/opus/tab.h"
 #include "libavutil/intreadwrite.h"
 #include "libavutil/mem.h"
@@ -75,8 +76,14 @@ static int opus_init(AVFormatContext *s, AVStream *st)
     return 0;
 }

+static int opus_packet_samples(AVStream *st, const AVPacket *pkt)
+{
+    return ff_opus_packet_samples(pkt->data, pkt->size);
+}
+
 const OGGMuxerMapping ff_ogg_opus_muxer_mapping = {
-    .codec_id  = AV_CODEC_ID_OPUS,
-    .new_links = 1,
-    .init      = opus_init,
+    .codec_id       = AV_CODEC_ID_OPUS,
+    .new_links      = 1,
+    .init           = opus_init,
+    .packet_samples = opus_packet_samples,
 };
diff --git a/tests/fate/ogg-copy-trim.mak b/tests/fate/ogg-copy-trim.mak
index bfaeb45259..547345709b 100644
--- a/tests/fate/ogg-copy-trim.mak
+++ b/tests/fate/ogg-copy-trim.mak
@@ -42,13 +42,13 @@ fate-ogg-copy-trim-opus-cut: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_CUT),

 # Opus cut 1 s after the start of the copy, which the pre-skip can hold.
 OGG_COPY_TRIM_OPUS_PRESKIP = tests/data/fate/ogg-copy-trim-opus-cut-preskip
-FATE_OGG_COPY_TRIM-$(call ALLYES, OPUS_PARSER OPUS_DECODER $(OGG_COPY_TRIM_AV_DEPS)) += fate-ogg-copy-trim-opus-cut-preskip
+FATE_OGG_COPY_TRIM-$(call ALLYES, OPUS_DECODER $(OGG_COPY_TRIM_AV_DEPS)) += fate-ogg-copy-trim-opus-cut-preskip
 fate-ogg-copy-trim-opus-cut-preskip: CMD = $(call OGG_COPY_TRIM_CUT,audiomatch/tones_opus_48000_stereo.opus,1.0,$(OGG_COPY_TRIM_OPUS_PRESKIP))
 fate-ogg-copy-trim-opus-cut-preskip: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_PRESKIP),.mkv $(OGG_COPY_TRIM_FILES))

 # Opus copied whole: only the encoder priming is trimmed.
 OGG_COPY_TRIM_OPUS_UNCUT = tests/data/fate/ogg-copy-trim-opus-uncut
-FATE_OGG_COPY_TRIM-$(call ALLYES, OPUS_PARSER OPUS_DECODER $(OGG_COPY_TRIM_AV_DEPS)) += fate-ogg-copy-trim-opus-uncut
+FATE_OGG_COPY_TRIM-$(call ALLYES, OPUS_DECODER $(OGG_COPY_TRIM_AV_DEPS)) += fate-ogg-copy-trim-opus-uncut
 fate-ogg-copy-trim-opus-uncut: CMD = $(call OGG_COPY_TRIM_AV,audiomatch/tones_opus_48000_stereo.opus,$(OGG_COPY_TRIM_OPUS_UNCUT)) && \
                                      $(call OGG_COPY_TRIM,$(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_UNCUT).mkv,,$(OGG_COPY_TRIM_OPUS_UNCUT))
 fate-ogg-copy-trim-opus-uncut: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_UNCUT),.mkv $(OGG_COPY_TRIM_FILES))
@@ -77,7 +77,7 @@ fate-ogg-copy-trim-vorbis-chained: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_VORB

 # Opus from Matroska whose last packet carries an end trim.
 OGG_COPY_TRIM_OPUS_END = tests/data/fate/ogg-copy-trim-opus-end
-FATE_OGG_COPY_TRIM-$(call ALLYES, MATROSKA_DEMUXER OPUS_PARSER OPUS_DECODER $(OGG_COPY_TRIM_DEPS)) += fate-ogg-copy-trim-opus-end
+FATE_OGG_COPY_TRIM-$(call ALLYES, MATROSKA_DEMUXER OPUS_DECODER $(OGG_COPY_TRIM_DEPS)) += fate-ogg-copy-trim-opus-end
 fate-ogg-copy-trim-opus-end: CMD = $(call OGG_COPY_TRIM,$(TARGET_SAMPLES)/mkv/codec_delay_opus.mkv,,$(OGG_COPY_TRIM_OPUS_END))
 fate-ogg-copy-trim-opus-end: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_END),$(OGG_COPY_TRIM_FILES))

@@ -159,7 +159,7 @@ fate-ogg-copy-trim-opus-nut: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_NUT),
 # first one falls inside the link. Use file: URLs so relative sample paths
 # are interpreted by the target rather than relative to the concat list.
 OGG_COPY_TRIM_OPUS_CONCAT = tests/data/fate/ogg-copy-trim-opus-concat
-FATE_OGG_COPY_TRIM-$(call ALLYES, CONCAT_DEMUXER MATROSKA_DEMUXER OPUS_PARSER OPUS_DECODER $(OGG_COPY_TRIM_DEPS)) += fate-ogg-copy-trim-opus-concat
+FATE_OGG_COPY_TRIM-$(call ALLYES, CONCAT_DEMUXER MATROSKA_DEMUXER OPUS_DECODER $(OGG_COPY_TRIM_DEPS)) += fate-ogg-copy-trim-opus-concat
 fate-ogg-copy-trim-opus-concat: CMD = \
     echo file file:$(TARGET_SAMPLES)/mkv/codec_delay_opus.mkv > $(OGG_COPY_TRIM_OPUS_CONCAT).txt && \
     echo file file:$(TARGET_SAMPLES)/mkv/codec_delay_opus.mkv >> $(OGG_COPY_TRIM_OPUS_CONCAT).txt && \
diff --git a/tests/ref/fate/ogg-copy-trim-opus-concat b/tests/ref/fate/ogg-copy-trim-opus-concat
index c1040663c4..207f83a1e2 100644
--- a/tests/ref/fate/ogg-copy-trim-opus-concat
+++ b/tests/ref/fate/ogg-copy-trim-opus-concat
@@ -12,5 +12,5 @@
 0,       4488,       4488,      960,      153, 0x3d0b4f93
 streams.stream.0.initial_padding=312
 streams.stream.0.start_time="0.006500"
-decoded copy: 199056 bytes, decoded source: 195608 bytes
-timestamp gaps: 1
+decoded copy: 197644 bytes, decoded source: 195608 bytes
+timestamp gaps: 0
diff --git a/tests/ref/fate/ogg-copy-trim-opus-end b/tests/ref/fate/ogg-copy-trim-opus-end
index 3dae7bb72c..250733d06c 100644
--- a/tests/ref/fate/ogg-copy-trim-opus-end
+++ b/tests/ref/fate/ogg-copy-trim-opus-end
@@ -12,4 +12,4 @@
 0,       4488,       4488,      960,      153, 0x3d0b4f93
 streams.stream.0.initial_padding=312
 streams.stream.0.start_time="-0.000500"
-decoded copy: 99216 bytes, decoded source: 97804 bytes
+decoded copy: 97804 bytes, decoded source: 97804 bytes
diff --git a/tests/ref/fate/ogg-copy-trim-opus-nut b/tests/ref/fate/ogg-copy-trim-opus-nut
index 9fceff229b..6f05b5aabd 100644
--- a/tests/ref/fate/ogg-copy-trim-opus-nut
+++ b/tests/ref/fate/ogg-copy-trim-opus-nut
@@ -11,5 +11,5 @@
 0,       3528,       3528,      960,      377, 0x7a62c054
 0,       4488,       4488,      960,      369, 0x08c1c043
 streams.stream.0.initial_padding=312
-streams.stream.0.start_time="-0.013500"
+streams.stream.0.start_time="0.006500"
 decoded copy: 386592 bytes, decoded source: 386592 bytes