Commit 8ddcf66551 for ffmpeg

commit 8ddcf66551b5e5fc734abf21bceb6309d1fedd07
Author: Romain Beauxis <romain.beauxis@gmail.com>
Date:   Thu Dec 3 08:14:51 2026 -0600

    avformat/ogg/muxer: keep link starts within the pre-roll the decoder needs

    A link starts where the input decoder presents its first sample, the
    packet timestamp plus its start skip or else the input pre-skip, and
    the Opus packets before it are dropped once the pre-roll kept covers
    the 400 ms of OPUS_SEEK_PREROLL_US or the new start_preroll option.

    The held Opus headers take the samples kept before the start as their
    pre-skip, other codecs drop the packets ending before the start, and
    Vorbis keeps them all, as its start trim needs a page layout of its own.

    The Opus cuts now decode to their source, the dropped packets of the gap
    tests keep their timestamps, and the FLAC cut plays only the start of
    its first packet.

diff --git a/doc/muxers.texi b/doc/muxers.texi
index c565420cb8..b8716890ec 100644
--- a/doc/muxers.texi
+++ b/doc/muxers.texi
@@ -3461,6 +3461,14 @@ The packet carrying it and the ones that follow are dropped, and their writes
 still return success.
 New extradata on the first packet is ignored.

+Opus granules count the coded samples of the packets.
+A gap between the timestamps of two packets of a link is therefore closed.
+A packet timestamp within 1 ms of that count can be taken as rounding.
+Such a timestamp follows the count, which can absorb a small
+@option{-output_ts_offset}.
+Samples trimmed in the middle of a link cannot be signalled, they are played.
+The muxer warns about those that side data trims.
+
 @table @option
 @item -page_duration @var{duration}
 Preferred page duration, in microseconds. The muxer will attempt to create
@@ -3486,6 +3494,31 @@ A link the muxer starts itself on new stream metadata or extradata keeps the
 offset of the link before it.
 With an explicit offset it then reuses its serial number.
 With the default it does so when its headers and tags are unchanged.
+@item -start_preroll @var{duration}
+Pre-roll kept before the start of a stream that begins mid-stream, as a stream
+copy cut does.
+Packets the decoder needs to converge are kept and trimmed, earlier ones are
+dropped.
+The start is where the input decoder presents its first sample: the packet
+timestamp plus its start skip, or plus the input pre-skip without one.
+An Opus start less than 1 ms from zero is taken as zero, as Matroska rounds
+timestamps to the millisecond.
+The default, written @code{-1us}, keeps the target of the codec: 400 ms for
+Opus.
+This gives a decoder started inside the stream more time to converge.
+RFC 7845 recommends at least 80 ms.
+A finite pre-roll does not guarantee bit-exact output.
+The muxer warns when it can tell that a link starts with less pre-roll than
+this option asks for.
+Encoder priming can require more than this target.
+With several streams, or after a flush before the start, the headers can
+keep less.
+They then play the samples their pre-skip cannot skip, never skipping
+samples after the start.
+Only Opus keeps a pre-roll of a set duration, of at most the 65535 samples its
+pre-skip can hold.
+Vorbis keeps all of it, which is played.
+Other codecs drop it and play the part of the first packet before the start.

 @end table

diff --git a/libavformat/ogg/muxer.c b/libavformat/ogg/muxer.c
index b93c9a5853..186c602c0d 100644
--- a/libavformat/ogg/muxer.c
+++ b/libavformat/ogg/muxer.c
@@ -49,6 +49,7 @@ typedef struct OGGContext {
     OGGPageList *page_list;
     int64_t pref_duration;      ///< preferred page duration (0 => fill all segments)
     int serial_offset;
+    int64_t start_preroll;      ///< pre-roll kept before a cut, -1 for the mapping's
     int failed; // if true all packet submission will fail.
     int ended;  ///< a new link could not be started, the packets that follow are dropped
 } OGGContext;
@@ -76,6 +77,8 @@ static const AVOption options[] = {
         OFFSET(serial_offset), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, PARAM },
     { "page_duration", "preferred page duration, in microseconds",
         OFFSET(pref_duration), AV_OPT_TYPE_INT64, { .i64 = 1000000 }, 0, INT64_MAX, PARAM },
+    { "start_preroll", "pre-roll kept before the start of a link cut mid-stream, -1us for what the codec needs",
+        OFFSET(start_preroll), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, PARAM },
     { NULL },
 };

@@ -100,6 +103,9 @@ static void ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
     OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
     uint8_t buf[4 + 1 + 1 + 8 + 4 + 4 + 4 + 1 + 255], *ptr = buf, *crc_pos;
     const AVCRC *crc_table = av_crc_get_table(AV_CRC_32_IEEE);
+    /* Header pages held past ogg_write_header() are still marked as such. */
+    enum AVIODataMarkerType marker = ffiocontext(s->pb)->current_type;
+    int mark_header = page->header && marker != AVIO_DATA_MARKER_HEADER;
     uint32_t crc;

     bytestream_put_le32(&ptr, MKTAG('O', 'g', 'g', 'S'));
@@ -117,8 +123,13 @@ static void ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
     crc = av_crc(crc_table, crc, page->data, page->size);
     bytestream_put_be32(&crc_pos, crc);

+    if (mark_header)
+        avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
     avio_write(s->pb, buf, ptr - buf);
     avio_write(s->pb, page->data, page->size);
+    if (mark_header)
+        avio_write_marker(s->pb, AV_NOPTS_VALUE,
+                          marker == AVIO_DATA_MARKER_TRAILER ? marker : AVIO_DATA_MARKER_UNKNOWN);
     avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
     oggstream->page_count--;
 }
@@ -153,6 +164,7 @@ static int ogg_reset_cur_page(OGGStreamContext *oggstream)
 {
     oggstream->page.granule = -1;
     oggstream->page.flags = 0;
+    oggstream->page.header = 0;
     oggstream->page.segments_count = 0;
     oggstream->page.size = 0;
     return 0;
@@ -181,7 +193,8 @@ static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
     while (*p) {
         if ((*p)->page.stream_index == l->page.stream_index)
             earlier_pages--;
-        else if (!earlier_pages && ogg_compare_granule(s, &(*p)->page, &l->page))
+        else if (!earlier_pages && !(*p)->page.header &&
+                 ogg_compare_granule(s, &(*p)->page, &l->page))
             break;
         p = &(*p)->next;
     }
@@ -230,6 +243,7 @@ static int ogg_buffer_data(AVFormatContext *s, AVStream *st,

         if (i && !page->segments_count)
             page->flags |= 1; // continued packet
+        page->header |= header;

         memset(page->segments+page->segments_count, 255, segments - 1);
         page->segments_count += segments - 1;
@@ -364,7 +378,13 @@ static void ogg_write_pages(AVFormatContext *s, int flush)
     for (p = ogg->page_list; p; ) {
         OGGStreamContext *oggstream =
             s->streams[p->page.stream_index]->priv_data;
-        if (oggstream->page_count < 2 && !flush)
+        /* Data pages are queued behind header pages, see ogg_buffer_page(). */
+        if (oggstream->headers_held && flush != 1)
+            break;
+        /* The last data page of a stream waits for EOS. A page still
+         * being filled is later than any page already in the queue. */
+        if (oggstream->page_count < 2 && !oggstream->page.segments_count &&
+            !flush && !p->page.header)
             break;
         ogg_write_page(s, &p->page,
                        flush == 1 && oggstream->page_count == 1 ? 4 : 0); // eos
@@ -460,6 +480,12 @@ static int ogg_init(AVFormatContext *s)
         oggstream->mapping = mapping;
         oggstream->link_anchor = AV_NOPTS_VALUE;
         oggstream->next_link_pts = AV_NOPTS_VALUE;
+        oggstream->coded_start   = AV_NOPTS_VALUE;
+        oggstream->start_pending = st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
+        /* Held headers stop the pages of all streams, the start trim is
+         * only written into those of a single stream. */
+        oggstream->headers_held  = oggstream->start_pending && mapping->set_start_trim &&
+                                   s->nb_streams == 1;
         if (mapping->priv_data_size) {
             oggstream->priv_data = av_mallocz(mapping->priv_data_size);
             if (!oggstream->priv_data)
@@ -506,6 +532,7 @@ static int ogg_write_header(AVFormatContext *s)
                     return ret;
             }
         }
+        oggstream->page.header = 1;
         ret = ogg_buffer_page(s, oggstream);
         if (ret < 0)
             return ret;
@@ -540,7 +567,7 @@ static int ogg_skip_new_link(AVFormatContext *s, const uint8_t *new_extradata,

 static int ogg_check_new_link(AVFormatContext *s, AVPacket *pkt)
 {
-    int ret = 0;
+    int ret = 0, replaced, rebased;
     const char *refused;
     size_t metadata_size, extradata_size;
     OGGContext *oggcontext = s->priv_data;
@@ -576,8 +603,12 @@ static int ogg_check_new_link(AVFormatContext *s, AVPacket *pkt)
         (refused = oggstream->mapping->new_link_refused(st, pkt, new_extradata, extradata_size)))
         return ogg_skip_new_link(s, new_extradata, refused);

-    ret = ogg_write_trailer(s);
-    if (ret < 0)
+    /* A link of which nothing is written yet is replaced, keeping its timing. */
+    replaced  = oggstream->headers_held && oggstream->start_pending;
+    rebased   = replaced ? oggstream->rebased : 1;
+    if (replaced)
+        ogg_free_pages(s);
+    else if ((ret = ogg_write_trailer(s)) < 0)
         goto end;

     if (side_metadata) {
@@ -603,7 +634,8 @@ static int ogg_check_new_link(AVFormatContext *s, AVPacket *pkt)
         goto end;

     /* Each link restarts its timestamps, the input packets do not. */
-    oggstream->link_start_pending = par->codec_type == AVMEDIA_TYPE_AUDIO;
+    oggstream->rebased            = rebased;
+    oggstream->link_start_pending = rebased && par->codec_type == AVMEDIA_TYPE_AUDIO;

     ret = ogg_write_header(s);

@@ -634,14 +666,6 @@ static int64_t ogg_packet_end_trim(const AVPacket *pkt)
     return skip && size >= 10 ? AV_RL32(skip + 4) : 0;
 }

-/**
- * Input timestamp at which a link starting with pkt starts presenting.
- */
-static int64_t ogg_link_start(const AVPacket *pkt)
-{
-    return pkt->pts + ogg_packet_start_trim(pkt);
-}
-
 /**
  * Buffer a data packet at its link timestamp link_pts.
  */
@@ -671,6 +695,27 @@ static int ogg_buffer_packet(AVFormatContext *s, AVStream *st,
     return 0;
 }

+/**
+ * Write the start trim of a link into its held header packets and
+ * identification header page.
+ */
+static void ogg_set_start_trim(AVFormatContext *s, AVStream *st, int64_t trim)
+{
+    OGGContext *ogg = s->priv_data;
+    OGGStreamContext *oggstream = st->priv_data;
+
+    oggstream->mapping->set_start_trim(st, trim);
+    /* The identification header starts the first page of the link. */
+    for (OGGPageList *p = ogg->page_list; p; p = p->next)
+        if (p->page.stream_index == st->index && (p->page.flags & 2)) {
+            memcpy(p->page.data, oggstream->header[0],
+                   FFMIN(oggstream->header_len[0], p->page.size));
+            break;
+        }
+    if (s->flags & AVFMT_FLAG_BITEXACT && ogg->serial_offset < 0)
+        ogg_set_serial(s, st);
+}
+
 /**
  * Largest error of timestamps rounded by the input: Matroska rounds them to
  * the millisecond.
@@ -680,13 +725,163 @@ static int64_t ogg_timestamp_rounding(const AVStream *st)
     return av_rescale_q(1, (AVRational){ 1, 1000 }, st->time_base);
 }

+/**
+ * Samples the input decoder skips at the start of pkt, the first packet of a
+ * link: its start skip, or else the pre-skip of the input headers.
+ */
+static int64_t ogg_decoder_start_skip(const OGGStreamContext *oggstream,
+                                      const AVPacket *pkt)
+{
+    int64_t skip = ogg_packet_start_trim(pkt);
+
+    return skip ? skip : oggstream->codec_start_trim;
+}
+
+/**
+ * Samples of pre-roll the decoder needs to converge, in the stream time base.
+ */
+static int64_t ogg_start_preroll(const AVFormatContext *s, const AVStream *st)
+{
+    const OGGContext *ogg = s->priv_data;
+    const OGGStreamContext *oggstream = st->priv_data;
+    const OGGMuxerMapping *mapping = oggstream->mapping;
+
+    if (mapping->start_preroll != OGG_START_PREROLL_DURATION)
+        return 0;
+    return av_rescale_q(ogg->start_preroll >= 0 ? ogg->start_preroll : mapping->start_preroll_us,
+                        AV_TIME_BASE_Q, st->time_base);
+}
+
+/**
+ * Link timestamp of the first coded sample of pkt, a packet before the start
+ * of the link, and the samples the input decoder skips from there on.
+ */
+static int64_t ogg_preroll_packet_start(const AVStream *st, const AVPacket *pkt,
+                                        int64_t link_pts)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+    int64_t skip = ogg_packet_start_trim(pkt);
+
+    if (oggstream->coded_start == AV_NOPTS_VALUE) {
+        oggstream->start_skip = ogg_decoder_start_skip(oggstream, pkt);
+        /* Matroska rounds the timestamp, the pre-skip is exact. */
+        if (oggstream->mapping->set_start_trim &&
+            FFABS(link_pts + oggstream->start_skip) < ogg_timestamp_rounding(st))
+            return -oggstream->start_skip;
+        return link_pts;
+    }
+    /* The decoder replaces the skip left with a new one. */
+    if (skip)
+        oggstream->start_skip = skip;
+    /* Duplicate Opus timestamps do not undo the progress made by the
+     * dropped packet. A distinct timestamp can still mark a real gap. */
+    if ((oggstream->mapping->packet_samples && link_pts == oggstream->last_dropped_pts) ||
+        FFABS(link_pts - oggstream->coded_start) <= ogg_timestamp_rounding(st))
+        return oggstream->coded_start;
+    return link_pts;
+}
+
+/**
+ * Write the start trim of a link, and report what its headers cannot
+ * signal.
+ *
+ * @param trim samples to skip before the start of the presentation
+ * @return the start trim written
+ */
+static int64_t ogg_write_start_trim(AVFormatContext *s, AVStream *st, int64_t trim)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+    const OGGMuxerMapping *mapping = oggstream->mapping;
+    const char *codec = avcodec_get_name(st->codecpar->codec_id);
+    int64_t converge = ogg_start_preroll(s, st);
+    int64_t written;
+
+    if (!mapping->set_start_trim)
+        written = 0;
+    else if (!oggstream->headers_held)
+        written = oggstream->codec_start_trim;
+    else
+        written = FFMIN(trim, mapping->max_start_trim);
+
+    if (oggstream->dropped_packets)
+        av_log(s, AV_LOG_VERBOSE, "Stream %d: dropped %d %s pre-roll packets "
+               "(%"PRId64" samples) before the start\n", st->index,
+               oggstream->dropped_packets, codec, oggstream->dropped_samples);
+    if (trim > written)
+        av_log(s, AV_LOG_WARNING, "Stream %d: %"PRId64" samples before the start "
+               "cannot be trimmed in %s and are played\n", st->index,
+               trim - written, codec);
+    else if (trim < written)
+        av_log(s, AV_LOG_WARNING, "Stream %d: the headers were written before "
+               "the first packet, they skip %"PRId64" presented samples\n",
+               st->index, written - trim);
+    else if (trim < converge &&
+             (trim != oggstream->codec_start_trim || oggstream->dropped_packets))
+        av_log(s, AV_LOG_WARNING, "Stream %d: the link starts mid-stream with "
+               "%"PRId64" samples of pre-roll, less than the %"PRId64" %s needs to "
+               "converge\n", st->index, trim, converge, codec);
+
+    if (mapping->set_start_trim && oggstream->headers_held)
+        ogg_set_start_trim(s, st, written);
+    return written;
+}
+
+/**
+ * Handle a packet of a link of which no packet is written yet. Packets
+ * presenting no sample are dropped once the pre-roll kept covers what the
+ * decoder needs; the first packet kept sets the start trim.
+ *
+ * @return 1 when pkt is to be written, 0 when it was dropped
+ */
+static int ogg_start_link(AVFormatContext *s, AVStream *st,
+                          const AVPacket *pkt, int64_t link_pts)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+    const OGGMuxerMapping *mapping = oggstream->mapping;
+    /* Encoder priming is kept whole. */
+    int64_t preroll = FFMAX(ogg_start_preroll(s, st), oggstream->codec_start_trim);
+    int64_t max_trim = oggstream->headers_held ? mapping->max_start_trim
+                                               : oggstream->codec_start_trim;
+    int64_t coded, trim, next_trim, written;
+
+    if (mapping->start_preroll == OGG_START_PREROLL_ALL) {
+        oggstream->start_pending = 0;
+        return 1;
+    }
+    coded     = ogg_preroll_packet_start(st, pkt, link_pts);
+    trim      = FFMAX(oggstream->start_skip, -coded);
+    next_trim = FFMAX(oggstream->start_skip - pkt->duration, -(coded + pkt->duration));
+
+    /* A packet of unknown duration may hold presented samples. Written
+     * headers keep their trim, which must not skip presented samples. */
+    if (pkt->duration > 0 && trim >= pkt->duration &&
+        (next_trim >= preroll ||
+         (mapping->set_start_trim && trim > max_trim &&
+          (oggstream->headers_held || next_trim >= max_trim)))) {
+        oggstream->dropped_packets++;
+        oggstream->dropped_samples += pkt->duration;
+        oggstream->start_skip       = FFMAX(oggstream->start_skip - pkt->duration, 0);
+        oggstream->coded_start      = coded + pkt->duration;
+        oggstream->last_dropped_pts = link_pts;
+        return 0;
+    }
+
+    oggstream->start_pending = 0;
+    written = ogg_write_start_trim(s, st, trim);
+    /* What the start trim cannot skip is presented from the start. */
+    coded = FFMAX(coded, coded + trim - written);
+    oggstream->link_pts_offset = pkt->pts - coded;
+
+    return 1;
+}
+
 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, end_trim = ogg_packet_end_trim(pkt);
-    int ret, new_link = 0, end_trim_signalled = 1;
+    int ret, new_link = 0, starting, end_trim_signalled = 1;

     if (oggcontext->failed)
         return AVERROR_INVALIDDATA;
@@ -712,14 +907,21 @@ static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
         if (samples >= 0)
             pkt->duration = samples;
     }
+    starting = oggstream->start_pending || oggstream->link_start_pending;

     if (oggstream->link_start_pending) {
-        oggstream->link_pts_offset    = ogg_link_start(pkt);
+        oggstream->link_pts_offset    = pkt->pts + ogg_decoder_start_skip(oggstream, pkt);
         oggstream->link_start_pending = 0;
         new_link = 1;
     }
-
     link_pts = pkt->pts - oggstream->link_pts_offset;
+
+    if (oggstream->start_pending) {
+        ret = ogg_start_link(s, st, pkt, link_pts);
+        if (ret <= 0)
+            return ret;
+        link_pts = pkt->pts - oggstream->link_pts_offset;
+    }
     /* The first packet of a later link may carry the timestamps of the
      * previous link. */
     if (oggstream->link_anchor != AV_NOPTS_VALUE) {
@@ -748,6 +950,14 @@ static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
                    st->index, oggstream->end_trim);
         oggstream->end_trim = av_clip64(end_trim, 0, pkt->duration);
         oggstream->end_trim_signalled = end_trim_signalled;
+        /* An end trim can put this packet wholly before the presentation. */
+        if (oggstream->last_granule - oggstream->end_trim > oggstream->packet_granule_offset ||
+            pkt->duration <= 0)
+            oggstream->headers_held = 0;
+        if (!starting && ogg_packet_start_trim(pkt))
+            av_log(s, AV_LOG_WARNING, "Stream %d: %"PRId64" samples skipped "
+                   "inside the link cannot be signalled and are played\n",
+                   st->index, ogg_packet_start_trim(pkt));
     }
     if (new_link && pkt->duration > 0)
         oggstream->link_anchor = link_pts + pkt->duration;
@@ -770,19 +980,21 @@ 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;
+    int64_t end_trim = oggstream->end_trim;

-    if (!oggstream->end_trim)
+    oggstream->end_trim = 0;
+    if (!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
+    if (last) {
+        last->granule -= 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;
+               st->index, end_trim);
+    }
 }

 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
@@ -794,6 +1006,8 @@ static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)

     for (i = 0; i < s->nb_streams; i++) {
         OGGStreamContext *oggstream = s->streams[i]->priv_data;
+        /* A flush writes the headers, whatever the start trim. */
+        oggstream->headers_held = 0;
         if (oggstream->page.segments_count &&
             (ret = ogg_buffer_page(s, oggstream)) < 0)
             return ret;
@@ -803,15 +1017,34 @@ static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
     return 1;
 }

+/**
+ * A link ending inside its pre-roll presents nothing: its headers, still
+ * held, skip all samples up to its trimmed EOS granule.
+ */
+static void ogg_end_preroll_link(AVFormatContext *s, AVStream *st)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+
+    int64_t end_granule = oggstream->last_granule - oggstream->end_trim;
+
+    if (!oggstream->headers_held || oggstream->start_pending ||
+        end_granule >= oggstream->packet_granule_offset)
+        return;
+    ogg_set_start_trim(s, st, end_granule);
+}
+
 static int ogg_write_trailer(AVFormatContext *s)
 {
     int i, ret;

     /* flush current page if needed */
     for (i = 0; i < s->nb_streams; i++) {
-        OGGStreamContext *oggstream = s->streams[i]->priv_data;
+        AVStream *st = s->streams[i];
+        OGGStreamContext *oggstream = st->priv_data;
+
+        ogg_end_preroll_link(s, st);
+        ogg_apply_end_trim(s, st);

-        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 2d6c710797..7e08d4c58e 100644
--- a/libavformat/ogg/muxer.h
+++ b/libavformat/ogg/muxer.h
@@ -34,6 +34,7 @@ typedef struct OGGPage {
     int64_t granule;
     int stream_index;
     uint8_t flags;
+    uint8_t header; ///< holds header packets, which precede all data pages
     uint8_t segments_count;
     uint8_t segments[255];
     uint8_t data[MAX_PAGE_SIZE];
@@ -42,6 +43,17 @@ typedef struct OGGPage {

 typedef struct OGGMuxerMapping OGGMuxerMapping;

+/**
+ * Pre-roll kept before the start of a link cut mid-stream.
+ */
+enum OGGStartPreroll {
+    OGG_START_PREROLL_NONE,
+    /** OGGMuxerMapping.start_preroll_us, for the decoder to converge. */
+    OGG_START_PREROLL_DURATION,
+    /** All of it: the codec has no start trim and needs the packets before. */
+    OGG_START_PREROLL_ALL,
+};
+
 typedef struct OGGStreamContext {
     unsigned page_counter;
     uint8_t *header[3];
@@ -56,12 +68,14 @@ typedef struct OGGStreamContext {
     int64_t granule_delta_mask;
     int64_t granule_key_mask;  ///< bits all clear on keyframes, 0 when no granule marks one
     int packet_granule_offset; ///< added to the end timestamp of a packet without packet_granule
+    int codec_start_trim; ///< start trim of the input headers, the encoder priming
     int eos;
     unsigned page_count; ///< number of page buffered
     OGGPage page; ///< current page
     unsigned serial_num; ///< serial number
     int64_t last_granule; ///< last packet granule
     int packet_seen; ///< true when packets have been submitted
+    int rebased; ///< the link follows another one, its timestamps restart
     int link_start_pending; ///< the next packet sets link_pts_offset
     int64_t link_pts_offset; ///< input timestamp at which the current link starts presenting
     /** End of the first packet of a later link, which the second one anchors to. */
@@ -70,6 +84,15 @@ typedef struct OGGStreamContext {
     /** 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
+    int start_pending; ///< no packet of the link is written yet
+    /** The header pages are held until the start trim of the link is written in them. */
+    int headers_held;
+    /** Expected link timestamp of the next packet before the start of the link. */
+    int64_t coded_start;
+    int64_t last_dropped_pts; ///< input link timestamp of the last dropped packet
+    int64_t start_skip; ///< samples the input decoder still skips before the start
+    int dropped_packets; ///< pre-roll packets dropped at the start of the link
+    int64_t dropped_samples; ///< duration of dropped_packets
 } OGGStreamContext;

 /**
@@ -81,11 +104,19 @@ struct OGGMuxerMapping {
     size_t priv_data_size;  ///< size of OGGStreamContext.priv_data
     int optional_extradata; ///< the headers can be built without extradata
     int new_links;          ///< a new link can replace the current one
+    enum OGGStartPreroll start_preroll;
+    int start_preroll_us;   ///< for OGG_START_PREROLL_DURATION
+    int max_start_trim;     ///< largest start trim set_start_trim can write
     /**
      * Build the header packets in OGGStreamContext.header, adjusting the
      * stream time base when the codec sets its own.
      */
     int (*init)(AVFormatContext *s, AVStream *st);
+    /**
+     * Write the start trim of the link into OGGStreamContext.header, and into
+     * the granules when they count it.
+     */
+    void (*set_start_trim)(AVStream *st, int64_t trim);
     /**
      * @return why a new link cannot start with this packet, NULL if it can.
      *         When the callback is NULL, the codec imposes no additional
diff --git a/libavformat/ogg/muxer/opus.c b/libavformat/ogg/muxer/opus.c
index 45e483c394..9d4a53f36e 100644
--- a/libavformat/ogg/muxer/opus.c
+++ b/libavformat/ogg/muxer/opus.c
@@ -74,7 +74,8 @@ static int opus_init(AVFormatContext *s, AVStream *st)
     }

     /* The pre-skip of the link's OpusHead, in the 48 kHz time base. */
-    oggstream->packet_granule_offset = AV_RL16(oggstream->header[0] + 10);
+    oggstream->packet_granule_offset =
+    oggstream->codec_start_trim      = AV_RL16(oggstream->header[0] + 10);
     return 0;
 }

@@ -83,9 +84,22 @@ static int opus_packet_samples(AVStream *st, const AVPacket *pkt)
     return ff_opus_packet_samples(pkt->data, pkt->size);
 }

+static void opus_set_start_trim(AVStream *st, int64_t trim)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+
+    AV_WL16(oggstream->header[0] + 10, trim);
+    oggstream->packet_granule_offset = trim;
+}
+
 const OGGMuxerMapping ff_ogg_opus_muxer_mapping = {
     .codec_id       = AV_CODEC_ID_OPUS,
     .new_links      = 1,
+    /* More than the 80 ms minimum of RFC 7845, see OPUS_SEEK_PREROLL_US. */
+    .start_preroll    = OGG_START_PREROLL_DURATION,
+    .start_preroll_us = OPUS_SEEK_PREROLL_US,
+    .max_start_trim = UINT16_MAX, /* the pre-skip field */
     .init           = opus_init,
+    .set_start_trim = opus_set_start_trim,
     .packet_samples = opus_packet_samples,
 };
diff --git a/libavformat/ogg/muxer/vorbis.c b/libavformat/ogg/muxer/vorbis.c
index a3a219706b..b72a0d8034 100644
--- a/libavformat/ogg/muxer/vorbis.c
+++ b/libavformat/ogg/muxer/vorbis.c
@@ -29,5 +29,7 @@ static int vorbis_init(AVFormatContext *s, AVStream *st)
 const OGGMuxerMapping ff_ogg_vorbis_muxer_mapping = {
     .codec_id  = AV_CODEC_ID_VORBIS,
     .new_links = 1,
+    /* A Vorbis start trim needs its own page layout, see Vorbis I A.2. */
+    .start_preroll = OGG_START_PREROLL_ALL,
     .init      = vorbis_init,
 };
diff --git a/tests/fate/ogg-copy-trim.mak b/tests/fate/ogg-copy-trim.mak
index 547345709b..872306acc9 100644
--- a/tests/fate/ogg-copy-trim.mak
+++ b/tests/fate/ogg-copy-trim.mak
@@ -34,18 +34,25 @@ OGG_COPY_TRIM_DEPS = OGG_MUXER OGG_DEMUXER FRAMECRC_MUXER ARESAMPLE_FILTER \
                      PCM_S16LE_ENCODER PCM_S16LE_MUXER FILE_PROTOCOL PIPE_PROTOCOL
 OGG_COPY_TRIM_AV_DEPS = MOV_DEMUXER MATROSKA_MUXER MATROSKA_DEMUXER H264_PARSER $(OGG_COPY_TRIM_DEPS)

-# Opus cut 1.5 s after the start of the copy, more than the pre-skip can hold.
+# Opus cut 1.5 s after the start of the copy, more than the pre-skip field can hold.
 OGG_COPY_TRIM_OPUS_CUT = tests/data/fate/ogg-copy-trim-opus-cut
 FATE_OGG_COPY_TRIM-$(call ALLYES, OPUS_DECODER $(OGG_COPY_TRIM_AV_DEPS)) += fate-ogg-copy-trim-opus-cut
 fate-ogg-copy-trim-opus-cut: CMD = $(call OGG_COPY_TRIM_CUT,audiomatch/tones_opus_48000_stereo.opus,1.5,$(OGG_COPY_TRIM_OPUS_CUT))
 fate-ogg-copy-trim-opus-cut: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_CUT),.mkv $(OGG_COPY_TRIM_FILES))

-# Opus cut 1 s after the start of the copy, which the pre-skip can hold.
+# Opus cut 1 s after the start of the copy, which the pre-skip field can hold:
+# only the pre-roll the decoder needs is kept either way.
 OGG_COPY_TRIM_OPUS_PRESKIP = tests/data/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))

+# The same cut keeping the 80 ms pre-roll of RFC 7845.
+OGG_COPY_TRIM_OPUS_PREROLL = tests/data/fate/ogg-copy-trim-opus-cut-preroll
+FATE_OGG_COPY_TRIM-$(call ALLYES, OPUS_DECODER $(OGG_COPY_TRIM_AV_DEPS)) += fate-ogg-copy-trim-opus-cut-preroll
+fate-ogg-copy-trim-opus-cut-preroll: CMD = $(call OGG_COPY_TRIM_CUT,audiomatch/tones_opus_48000_stereo.opus,1.0,$(OGG_COPY_TRIM_OPUS_PREROLL),-start_preroll 0.08)
+fate-ogg-copy-trim-opus-cut-preroll: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_PREROLL),.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_DECODER $(OGG_COPY_TRIM_AV_DEPS)) += fate-ogg-copy-trim-opus-uncut
@@ -194,6 +201,88 @@ fate-ogg-copy-trim-opus-duration-only: CMD = \
     $(call OGG_CHAIN_COPY_COMPARE,$(OGG_COPY_TRIM_OPUS_DURATION_ONLY).pcm,$(OGG_COPY_TRIM_OPUS_DURATION_ONLY).copy.pcm,decoded copy)
 fate-ogg-copy-trim-opus-duration-only: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_DURATION_ONLY),$(OGG_COPY_TRIM_FILES))

+# The first retained Opus packet starts after a timestamp gap, with the
+# packet containing the original priming dropped.
+OGG_COPY_TRIM_OPUS_GAP = tests/data/fate/ogg-copy-trim-opus-gap
+FATE_OGG_COPY_TRIM-$(call ALLYES, SETTS_BSF OPUS_DECODER OGG_MUXER OGG_DEMUXER FILE_PROTOCOL) += fate-ogg-copy-trim-opus-gap
+fate-ogg-copy-trim-opus-gap: CMD = \
+    ffmpeg -i $(TARGET_SAMPLES)/audiomatch/tones_opus_48000_stereo.opus -map 0:a -c copy -frames:a 3 \
+           -bsf:a "setts=ts=if(eq(N\,0)\,-1440\,PTS)" \
+           -avoid_negative_ts disabled -start_preroll 0 -f ogg -y $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_GAP).ogg && \
+    probe -show_frames -show_entries frame=pts,nb_samples:frame_tags=:stream=initial_padding,start_time \
+          -of compact $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_GAP).ogg
+fate-ogg-copy-trim-opus-gap: CLEANFILES = $(OGG_COPY_TRIM_OPUS_GAP).ogg
+
+# Drop the packet carrying the start skip while retaining some of the
+# samples that skip covers. The second packet starts after a timestamp gap.
+OGG_COPY_TRIM_OPUS_GAP_PARTIAL = tests/data/fate/ogg-copy-trim-opus-gap-partial
+FATE_OGG_COPY_TRIM-$(call ALLYES, SETTS_BSF OPUS_DECODER $(OGG_COPY_TRIM_AV_DEPS)) += fate-ogg-copy-trim-opus-gap-partial
+fate-ogg-copy-trim-opus-gap-partial: CMD = \
+    $(call OGG_COPY_TRIM_AV,audiomatch/tones_opus_48000_stereo.opus,$(OGG_COPY_TRIM_OPUS_GAP_PARTIAL)) && \
+    ffmpeg -ss 1 -i $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_GAP_PARTIAL).mkv -map 0:a -c copy \
+           -start_preroll 0.08 -fflags +bitexact -f ogg -y $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_GAP_PARTIAL).cut.ogg && \
+    ffmpeg -i $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_GAP_PARTIAL).cut.ogg -map 0:a -c copy -frames:a 12 \
+           -bsf:a "setts=ts=if(eq(N\,0)\,-6600\,648+(N-1)*960)" \
+           -avoid_negative_ts disabled -start_preroll 0 -f ogg -y $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_GAP_PARTIAL).ogg && \
+    probe -show_frames -show_entries frame=pts,nb_samples:frame_tags=:stream=initial_padding,start_time \
+          -of compact $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_GAP_PARTIAL).ogg
+fate-ogg-copy-trim-opus-gap-partial: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_GAP_PARTIAL),.mkv .cut.ogg .ogg)
+
+# A concat cut between two inputs: the first packet kept carries its own
+# start skip, which replaces the skip left from the dropped packets.
+OGG_COPY_TRIM_OPUS_CONCAT_SKIP = tests/data/fate/ogg-copy-trim-opus-concat-skip
+FATE_OGG_COPY_TRIM-$(call ALLYES, CONCAT_DEMUXER OPUS_DECODER $(OGG_COPY_TRIM_DEPS)) += fate-ogg-copy-trim-opus-concat-skip
+fate-ogg-copy-trim-opus-concat-skip: CMD = \
+    echo file file:$(TARGET_SAMPLES)/audiomatch/tones_opus_48000_stereo.opus > $(OGG_COPY_TRIM_OPUS_CONCAT_SKIP).txt && \
+    echo duration 3 >> $(OGG_COPY_TRIM_OPUS_CONCAT_SKIP).txt && \
+    echo file file:$(TARGET_SAMPLES)/audiomatch/tones_opus_48000_stereo.opus >> $(OGG_COPY_TRIM_OPUS_CONCAT_SKIP).txt && \
+    ffmpeg -f concat -safe 0 -copyts -itsoffset -2.1 -i $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_CONCAT_SKIP).txt -map 0:a -c copy \
+           -avoid_negative_ts disabled -start_preroll 0 -fflags +bitexact -f ogg -y $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_CONCAT_SKIP).ogg && \
+    probe -read_intervals "%+\#2" -show_frames -show_entries frame=pts,nb_samples:frame_tags=:stream=initial_padding,start_time \
+          -of compact $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_CONCAT_SKIP).ogg
+fate-ogg-copy-trim-opus-concat-skip: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_CONCAT_SKIP),.txt .ogg)
+
+# Pre-roll timestamps repeated before advancing: the copy matches the one
+# of the same packets with advancing timestamps.
+OGG_COPY_TRIM_OPUS_REPEATED = tests/data/fate/ogg-copy-trim-opus-repeated
+FATE_OGG_COPY_TRIM-$(call ALLYES, SETTS_BSF OPUS_DECODER $(OGG_COPY_TRIM_DEPS)) += fate-ogg-copy-trim-opus-repeated
+fate-ogg-copy-trim-opus-repeated: CMD = \
+    ffmpeg -i $(TARGET_SAMPLES)/audiomatch/tones_opus_48000_stereo.opus -map 0:a -c copy \
+           -bsf:a "setts=ts=if(lt(N\,75)\,-72000\,PTS-71688)" \
+           -avoid_negative_ts disabled -fflags +bitexact -f ogg -y $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_REPEATED).ogg && \
+    ffmpeg -i $(TARGET_SAMPLES)/audiomatch/tones_opus_48000_stereo.opus -map 0:a -c copy \
+           -bsf:a "setts=ts=PTS-71688" \
+           -avoid_negative_ts disabled -fflags +bitexact -f ogg -y $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_REPEATED).control.ogg && \
+    probe -show_entries stream=initial_padding -of flat $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_REPEATED).ogg && \
+    $(call OGG_CHAIN_COPY_COMPARE,$(OGG_COPY_TRIM_OPUS_REPEATED).control.ogg,$(OGG_COPY_TRIM_OPUS_REPEATED).ogg,copy)
+fate-ogg-copy-trim-opus-repeated: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_REPEATED),.control.ogg .ogg)
+
+# A cut 49 samples past a packet boundary, next to FLAC: the headers written
+# with the input pre-skip play those 49 samples rather than skip later ones.
+OGG_COPY_TRIM_OPUS_WRITTEN = tests/data/fate/ogg-copy-trim-opus-written-headers
+FATE_OGG_COPY_TRIM-$(call ALLYES, FLAC_DEMUXER OPUS_DECODER $(OGG_COPY_TRIM_AV_DEPS)) += fate-ogg-copy-trim-opus-written-headers
+fate-ogg-copy-trim-opus-written-headers: CMD = \
+    $(call OGG_COPY_TRIM_AV,audiomatch/tones_opus_48000_stereo.opus,$(OGG_COPY_TRIM_OPUS_WRITTEN)) && \
+    ffmpeg -ss 1 -i $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_WRITTEN).mkv -map 0:a -c copy \
+           -start_preroll 0.08 -fflags +bitexact -f ogg -y $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_WRITTEN).cut.ogg && \
+    ffmpeg -copyts -itsoffset -0.001021 -i $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_WRITTEN).cut.ogg \
+           -i $(TARGET_SAMPLES)/filter/hdcd.flac -map 0:a -map 1:a -c copy -t 1 \
+           -avoid_negative_ts disabled -fflags +bitexact -f ogg -y $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_WRITTEN).ogg && \
+    probe -select_streams a:0 -read_intervals "%+\#1" -show_frames \
+          -show_entries frame=pts,nb_samples:frame_tags=:stream=initial_padding,start_time \
+          -of compact $(TARGET_PATH)/$(OGG_COPY_TRIM_OPUS_WRITTEN).ogg
+fate-ogg-copy-trim-opus-written-headers: CLEANFILES = $(addprefix $(OGG_COPY_TRIM_OPUS_WRITTEN),.mkv .cut.ogg .ogg)
+
+# FLAC shifted by less than 1 ms keeps its exact first granule.
+OGG_COPY_TRIM_FLAC_OFFSET = tests/data/fate/ogg-copy-trim-flac-offset.ogg
+FATE_OGG_COPY_TRIM-$(call ALLYES, FLAC_DEMUXER OGG_MUXER FILE_PROTOCOL) += fate-ogg-copy-trim-flac-offset
+fate-ogg-copy-trim-flac-offset: libavformat/tests/ogg_pages$(EXESUF)
+fate-ogg-copy-trim-flac-offset: CMD = \
+    ffmpeg -i $(TARGET_SAMPLES)/filter/hdcd.flac -map 0:a -c copy -output_ts_offset 0.0005 -page_duration 1 \
+           -frames:a 3 -fflags +bitexact -f ogg -y $(TARGET_PATH)/$(OGG_COPY_TRIM_FLAC_OFFSET) && \
+    run libavformat/tests/ogg_pages$(EXESUF) $(TARGET_PATH)/$(OGG_COPY_TRIM_FLAC_OFFSET)
+fate-ogg-copy-trim-flac-offset: CLEANFILES = $(OGG_COPY_TRIM_FLAC_OFFSET)
+
 FATE_SAMPLES_FFMPEG_FFPROBE += $(FATE_OGG_COPY_TRIM-yes)

 fate-ogg-copy-trim: $(FATE_OGG_COPY_TRIM-yes)
diff --git a/tests/ref/fate/ogg-copy-trim-flac-cut b/tests/ref/fate/ogg-copy-trim-flac-cut
index a32b6e2dc6..2fb97eafaa 100644
--- a/tests/ref/fate/ogg-copy-trim-flac-cut
+++ b/tests/ref/fate/ogg-copy-trim-flac-cut
@@ -4,12 +4,12 @@
 #codec_id 0: flac
 #sample_rate 0: 44100
 #channel_layout_name 0: stereo
-0,          0,          0,     4096,    11736, 0xdb0073ee
-0,       4096,       4096,     4096,    12370, 0xca19a21f
-0,       8192,       8192,     4096,    11903, 0xb493bd69
-0,      12288,      12288,     4096,    11242, 0x3240cab4
-0,      16384,      16384,     4096,    11372, 0x96b59721
-0,      16384,      16384,     4096,    10645, 0x05b74a79
+0,          0,          0,     4096,     8113, 0x9acd9413
+0,       4096,       4096,     4096,     8521, 0x2070136c
+0,       8192,       8192,     4096,     8687, 0xe48f4c68
+0,      12288,      12288,     4096,    10582, 0xe2d10986
+0,      16384,      16384,     4096,    11175, 0xda5442f1
+0,      20480,      20480,     4096,     8563, 0x31a3565e
 streams.stream.0.initial_padding=0
 streams.stream.0.start_time="0.000000"
-decoded copy: 360448 bytes, decoded source: 131128 bytes
+decoded copy: 147456 bytes, decoded source: 131128 bytes
diff --git a/tests/ref/fate/ogg-copy-trim-flac-offset b/tests/ref/fate/ogg-copy-trim-flac-offset
new file mode 100644
index 0000000000..51efbec1fc
--- /dev/null
+++ b/tests/ref/fate/ogg-copy-trim-flac-offset
@@ -0,0 +1,5 @@
+pos=0 serial=698810505 sequence=0 granule=0 flags=-b- segments=1 size=51
+pos=79 serial=698810505 sequence=1 granule=0 flags=--- segments=1 size=18
+pos=125 serial=698810505 sequence=2 granule=4118 flags=--- segments=47 size=11736
+pos=11935 serial=698810505 sequence=3 granule=8214 flags=--- segments=49 size=12370
+pos=24381 serial=698810505 sequence=4 granule=12310 flags=--e segments=47 size=11903
diff --git a/tests/ref/fate/ogg-copy-trim-opus-concat-skip b/tests/ref/fate/ogg-copy-trim-opus-concat-skip
new file mode 100644
index 0000000000..98b31435b0
--- /dev/null
+++ b/tests/ref/fate/ogg-copy-trim-opus-concat-skip
@@ -0,0 +1,3 @@
+frame|pts=43200|nb_samples=648
+frame|pts=43848|nb_samples=960
+stream|initial_padding=312|start_time=0.900000
diff --git a/tests/ref/fate/ogg-copy-trim-opus-cut b/tests/ref/fate/ogg-copy-trim-opus-cut
index a231f6ee95..697e474a19 100644
--- a/tests/ref/fate/ogg-copy-trim-opus-cut
+++ b/tests/ref/fate/ogg-copy-trim-opus-cut
@@ -1,9 +1,15 @@
-#extradata 0:       19, 0x38100445
+#extradata 0:       19, 0x3a680490
 #tb 0: 1/48000
 #media_type 0: audio
 #codec_id 0: opus
 #sample_rate 0: 48000
 #channel_layout_name 0: stereo
-streams.stream.0.initial_padding=312
-streams.stream.0.start_time="N/A"
-decoded copy: 0 bytes, decoded source: 96000 bytes
+0,     -19512,     -19512,      960,      362, 0xe63eb7da, S=1, Skip Samples,       10, 0x04dc0084
+0,     -18552,     -18552,      960,      353, 0xd2fab5b4
+0,     -17592,     -17592,      960,      357, 0x4989ac82
+0,     -16632,     -16632,      960,      365, 0x9944ae92
+0,     -15672,     -15672,      960,      362, 0x065ab62a
+0,     -14712,     -14712,      960,      361, 0x7f30ae00
+streams.stream.0.initial_padding=19512
+streams.stream.0.start_time="0.000000"
+decoded copy: 96000 bytes, decoded source: 96000 bytes
diff --git a/tests/ref/fate/ogg-copy-trim-opus-cut-preroll b/tests/ref/fate/ogg-copy-trim-opus-cut-preroll
new file mode 100644
index 0000000000..0a423d828e
--- /dev/null
+++ b/tests/ref/fate/ogg-copy-trim-opus-cut-preroll
@@ -0,0 +1,15 @@
+#extradata 0:       19, 0x38880454
+#tb 0: 1/48000
+#media_type 0: audio
+#codec_id 0: opus
+#sample_rate 0: 48000
+#channel_layout_name 0: stereo
+0,      -4152,      -4152,      960,      474, 0x770cec85, S=1, Skip Samples,       10, 0x02c00048
+0,      -3192,      -3192,      960,      163, 0x9f1655d7
+0,      -2232,      -2232,      960,      144, 0xd7764913
+0,      -1272,      -1272,      960,      152, 0x2c155282
+0,       -312,       -312,      960,      138, 0xd62641ed
+0,        648,        648,      960,      150, 0x070f46d0
+streams.stream.0.initial_padding=4152
+streams.stream.0.start_time="0.000000"
+decoded copy: 192000 bytes, decoded source: 192000 bytes
diff --git a/tests/ref/fate/ogg-copy-trim-opus-cut-preskip b/tests/ref/fate/ogg-copy-trim-opus-cut-preskip
index a40c225624..a0e77f3887 100644
--- a/tests/ref/fate/ogg-copy-trim-opus-cut-preskip
+++ b/tests/ref/fate/ogg-copy-trim-opus-cut-preskip
@@ -1,15 +1,15 @@
-#extradata 0:       19, 0x38100445
+#extradata 0:       19, 0x3a680490
 #tb 0: 1/48000
 #media_type 0: audio
 #codec_id 0: opus
 #sample_rate 0: 48000
 #channel_layout_name 0: stereo
-0,       -312,       -312,      960,      354, 0xa2a7b0c8, S=1, Skip Samples,       10, 0x02390039
-0,        648,        648,      960,      366, 0xf507c0ab
-0,       1608,       1608,      960,      359, 0x0379b6ca
-0,       2568,       2568,      960,      377, 0x7a62c054
-0,       3528,       3528,      960,      369, 0x08c1c043
-0,       4488,       4488,      960,      357, 0x689bab86
-streams.stream.0.initial_padding=312
-streams.stream.0.start_time="-0.980000"
-decoded copy: 380160 bytes, decoded source: 192000 bytes
+0,     -19512,     -19512,      960,      176, 0xc6b95e4e, S=1, Skip Samples,       10, 0x04dc0084
+0,     -18552,     -18552,      960,      170, 0x5325548c
+0,     -17592,     -17592,      960,      160, 0x49245032
+0,     -16632,     -16632,      960,      169, 0x055f5002
+0,     -15672,     -15672,      960,      171, 0xa4795904
+0,     -14712,     -14712,      960,      198, 0x3001631e
+streams.stream.0.initial_padding=19512
+streams.stream.0.start_time="0.000000"
+decoded copy: 192000 bytes, decoded source: 192000 bytes
diff --git a/tests/ref/fate/ogg-copy-trim-opus-end b/tests/ref/fate/ogg-copy-trim-opus-end
index 250733d06c..fe28383c21 100644
--- a/tests/ref/fate/ogg-copy-trim-opus-end
+++ b/tests/ref/fate/ogg-copy-trim-opus-end
@@ -11,5 +11,5 @@
 0,       3528,       3528,      960,      146, 0x633c4937
 0,       4488,       4488,      960,      153, 0x3d0b4f93
 streams.stream.0.initial_padding=312
-streams.stream.0.start_time="-0.000500"
+streams.stream.0.start_time="0.000000"
 decoded copy: 97804 bytes, decoded source: 97804 bytes
diff --git a/tests/ref/fate/ogg-copy-trim-opus-gap b/tests/ref/fate/ogg-copy-trim-opus-gap
new file mode 100644
index 0000000000..8bba5bf899
--- /dev/null
+++ b/tests/ref/fate/ogg-copy-trim-opus-gap
@@ -0,0 +1,3 @@
+frame|pts=0|nb_samples=960
+frame|pts=960|nb_samples=960
+stream|initial_padding=0|start_time=0.000000
diff --git a/tests/ref/fate/ogg-copy-trim-opus-gap-partial b/tests/ref/fate/ogg-copy-trim-opus-gap-partial
new file mode 100644
index 0000000000..43e9168954
--- /dev/null
+++ b/tests/ref/fate/ogg-copy-trim-opus-gap-partial
@@ -0,0 +1,9 @@
+frame|pts=0|nb_samples=648
+frame|pts=648|nb_samples=960
+frame|pts=1608|nb_samples=960
+frame|pts=2568|nb_samples=960
+frame|pts=3528|nb_samples=960
+frame|pts=4488|nb_samples=960
+frame|pts=5448|nb_samples=960
+frame|pts=6408|nb_samples=960
+stream|initial_padding=3192|start_time=0.000000
diff --git a/tests/ref/fate/ogg-copy-trim-opus-large-priming b/tests/ref/fate/ogg-copy-trim-opus-large-priming
index 58e0205eba..e6b25c2f25 100644
--- a/tests/ref/fate/ogg-copy-trim-opus-large-priming
+++ b/tests/ref/fate/ogg-copy-trim-opus-large-priming
@@ -1,15 +1,15 @@
-#extradata 0:       19, 0x48fd0655
+#extradata 0:       19, 0x462e0605
 #tb 0: 1/48000
 #media_type 0: audio
 #codec_id 0: opus
 #sample_rate 0: 48000
 #channel_layout_name 0: stereo
-0,     -65535,     -65535,      960,      443, 0xc3d7d97c, S=1, Skip Samples,       10, 0x12ed01fe
-0,     -64575,     -64575,      960,      235, 0xb58f6d2f
-0,     -63615,     -63615,      960,      345, 0x88bcac2b
-0,     -62655,     -62655,      960,      239, 0x6cf572c4
-0,     -61695,     -61695,      960,      246, 0xd8108289
-0,     -60735,     -60735,      960,      189, 0xfd0962e4
-streams.stream.0.initial_padding=65535
-streams.stream.0.start_time="-0.093021"
-decoded copy: 699108 bytes, decoded source: 681248 bytes
+0,     -65200,     -65200,      960,      189, 0xfd0962e4, S=1, Skip Samples,       10, 0x0fce01ae
+0,     -64240,     -64240,      960,      191, 0xdd5c5cb2
+0,     -63280,     -63280,      960,      193, 0xf21762cf
+0,     -62320,     -62320,      960,      192, 0x8c6160d5
+0,     -61360,     -61360,      960,      193, 0xf5e25fef
+0,     -60400,     -60400,      960,      190, 0xeb5c5b28
+streams.stream.0.initial_padding=65200
+streams.stream.0.start_time="0.000000"
+decoded copy: 681248 bytes, decoded source: 681248 bytes
diff --git a/tests/ref/fate/ogg-copy-trim-opus-repeated b/tests/ref/fate/ogg-copy-trim-opus-repeated
new file mode 100644
index 0000000000..d8fe9020bc
--- /dev/null
+++ b/tests/ref/fate/ogg-copy-trim-opus-repeated
@@ -0,0 +1,2 @@
+streams.stream.0.initial_padding=19200
+copy: same
diff --git a/tests/ref/fate/ogg-copy-trim-opus-written-headers b/tests/ref/fate/ogg-copy-trim-opus-written-headers
new file mode 100644
index 0000000000..b91c544061
--- /dev/null
+++ b/tests/ref/fate/ogg-copy-trim-opus-written-headers
@@ -0,0 +1 @@
+stream|initial_padding=4152|start_time=0.000000