PR #26202 opened by Romain Beauxis (toots)
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26202
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26202.patch

Opus in ISOBMFF trims a packet by giving its sample a duration shorter than 
what the packet decodes to. The mov demuxer ignored this, so the trimmed 
samples were decoded. Our own muxer writes such files with `-use_editlist 0`: 
21 ms of audio decodes to 37.5 ms.

The demuxer now reads the packet's length from its TOC and exports the 
difference as discard padding. That parsing already existed as three copies 
(ogg, rtp, matroskaenc), so it moves to a shared inline helper in 
`libavcodec/opus/opus.h`, which also rejects packets breaking RFC 6716 3.2.5.

Encrypted packets are left alone. When an edit list ends inside the same 
packet, the trim stops at whichever end comes first, and on track clocks 
coarser than 48 kHz a shortfall under one tick is treated as rounding.

The new `fate-mov-mp4-opus-trim` test is added first with the current behavior, 
and its reference changes with the fix.


>From 8b873f16c677fb25cbc4108fc746b27c698e3d9e Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Thu, 19 Nov 2026 07:56:41 -0600
Subject: [PATCH 1/4] tests/fate/mov: add a test for the end trim of Opus in
 MP4

Without an edit list, the muxer shortens the last sample to 168 out of
960. The demuxer does not discard the 792 trimmed samples.
---
 tests/fate/mov.mak               |  6 ++++++
 tests/ref/fate/mov-mp4-opus-trim | 10 ++++++++++
 2 files changed, 16 insertions(+)
 create mode 100644 tests/ref/fate/mov-mp4-opus-trim

diff --git a/tests/fate/mov.mak b/tests/fate/mov.mak
index a603ca94dec..9bc8fae391f 100644
--- a/tests/fate/mov.mak
+++ b/tests/fate/mov.mak
@@ -208,6 +208,12 @@ fate-mov-t35-cdsc-track: CMD = run 
ffprobe$(PROGSSUF)$(EXESUF) -show_entries str
 
 fate-mov-t35-rndr-track: CMD = run ffprobe$(PROGSSUF)$(EXESUF) -show_entries 
stream_group=index,id,nb_streams,type:stream_group_stream=index,id,codec_name,codec_type,codec_tag_string,extradata_size
 $(TARGET_SAMPLES)/mov/mov-t35-rndr-track.mp4
 
+# Without an edit list, the end of an Opus stream is trimmed by shortening the
+# last sample, here from 960 to 168.
+FATE_MOV_FFMPEG-$(call TRANSCODE, OPUS, MP4 WAV, ANULLSRC_FILTER 
ARESAMPLE_FILTER) += fate-mov-mp4-opus-trim
+fate-mov-mp4-opus-trim: tests/data/asynth-44100-2.wav
+fate-mov-mp4-opus-trim: CMD = transcode wav tests/data/asynth-44100-2.wav mp4 
"-filter_complex anullsrc=r=48000:cl=stereo:d=0.021[a] -map [a] -c:a opus 
-strict -2 -use_editlist 0" "-c copy"
+
 FATE_MOV_FFMPEG_FFPROBE_SAMPLES-$(call REMUX, MP4 MOV, OGG_DEMUXER 
VORBIS_DECODER) \
                           += fate-mov-mp4-chapters
 fate-mov-mp4-chapters: CMD = transcode ogg 
$(TARGET_SAMPLES)/vorbis/vorbis_chapter_extension_demo.ogg mp4 "-c copy" "-c 
copy -t 0.1" "-show_chapters"
diff --git a/tests/ref/fate/mov-mp4-opus-trim b/tests/ref/fate/mov-mp4-opus-trim
new file mode 100644
index 00000000000..de48b1ec423
--- /dev/null
+++ b/tests/ref/fate/mov-mp4-opus-trim
@@ -0,0 +1,10 @@
+a51e04975a80d74a5d887ed4f288de10 *tests/data/fate/mov-mp4-opus-trim.mp4
+671 tests/data/fate/mov-mp4-opus-trim.mp4
+#extradata 0:       19, 0x3c4604cf
+#tb 0: 1/48000
+#media_type 0: audio
+#codec_id 0: opus
+#sample_rate 0: 48000
+#channel_layout_name 0: stereo
+0,          0,          0,      960,        3, 0x05f002f9
+0,        960,        960,      168,        3, 0x05f002f9
-- 
2.54.1


>From 5741d79334623e2a6666a999884cf0c255c74aca Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Thu, 19 Nov 2026 08:01:56 -0600
Subject: [PATCH 2/4] avcodec/opus: add ff_opus_packet_duration()

Parse the duration of an Opus packet from its TOC, for the demuxers and
muxers that each carry a copy of it.
---
 libavcodec/opus/opus.h | 42 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)

diff --git a/libavcodec/opus/opus.h b/libavcodec/opus/opus.h
index 9b1693329e2..d7cb80d26df 100644
--- a/libavcodec/opus/opus.h
+++ b/libavcodec/opus/opus.h
@@ -25,6 +25,9 @@
 
 #include <stdint.h>
 
+#include "libavutil/error.h"
+#include "libavutil/macros.h"
+
 #define OPUS_MAX_FRAME_SIZE          1275
 #define OPUS_MAX_FRAMES                48
 #define OPUS_MAX_PACKET_DUR          5760
@@ -56,4 +59,43 @@ enum OpusBandwidth {
     OPUS_BANDWITH_NB
 };
 
+/**
+ * Get the duration of an Opus packet from its TOC.
+ *
+ * @param buf  packet data
+ * @param size packet size in bytes
+ * @return the duration in samples at 48 kHz, or AVERROR_INVALIDDATA if the
+ *         packet is truncated or breaks the limits of RFC 6716 3.2.5
+ */
+static inline int ff_opus_packet_duration(const uint8_t *buf, int size)
+{
+    int config, frame_duration, frame_count;
+
+    if (size < 1)
+        return AVERROR_INVALIDDATA;
+
+    config         = buf[0] >> 3;
+    frame_duration = config < 12 ? FFMAX(480, 960 * (config & 3)) :
+                     config < 16 ? 480 << (config & 1) :
+                                   120 << (config & 3);
+
+    switch (buf[0] & 3) {
+    case 0:
+        frame_count = 1;
+        break;
+    case 3:
+        if (size < 2)
+            return AVERROR_INVALIDDATA;
+        frame_count = buf[1] & 0x3F;
+        break;
+    default:
+        frame_count = 2;
+    }
+
+    if (!frame_count || frame_duration * frame_count > OPUS_MAX_PACKET_DUR)
+        return AVERROR_INVALIDDATA;
+
+    return frame_duration * frame_count;
+}
+
 #endif /* AVCODEC_OPUS_OPUS_H */
-- 
2.54.1


>From 0df8a926cd51fcf514e9ceb1c7c2f3a1036381e9 Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Thu, 19 Nov 2026 08:02:24 -0600
Subject: [PATCH 3/4] avformat: use ff_opus_packet_duration()

Drop the three local copies, and the frame duration table matroskaenc
pulled from libavcodec for its own.
---
 libavcodec/opus/Makefile              |  3 ---
 libavformat/Makefile                  |  2 --
 libavformat/matroskaenc.c             | 32 ++-------------------------
 libavformat/ogg/mapping/opus.c        | 27 ++++------------------
 libavformat/opus_frame_duration_tab.c | 19 ----------------
 libavformat/rtpdec_opus.c             | 23 ++-----------------
 6 files changed, 8 insertions(+), 98 deletions(-)
 delete mode 100644 libavformat/opus_frame_duration_tab.c

diff --git a/libavcodec/opus/Makefile b/libavcodec/opus/Makefile
index 49ce7fb7673..92b082242b3 100644
--- a/libavcodec/opus/Makefile
+++ b/libavcodec/opus/Makefile
@@ -27,6 +27,3 @@ OBJS-$(CONFIG_OPUS_ENCODER) +=  \
     opus/pvq.o                  \
     opus/rc.o                   \
     opus/tab.o                  \
-
-STLIBOBJS-$(CONFIG_MATROSKA_MUXER)   += opus/frame_duration_tab.o
-STLIBOBJS-$(CONFIG_WEBM_MUXER)       += opus/frame_duration_tab.o
diff --git a/libavformat/Makefile b/libavformat/Makefile
index 0da209b17ed..de390074371 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -756,7 +756,6 @@ SHLIBOBJS-$(CONFIG_IMAGE_JPEGXL_PIPE_DEMUXER)    += 
jpegxl_parse.o
 SHLIBOBJS-$(CONFIG_JNI)                  += ffjni.o
 SHLIBOBJS-$(CONFIG_JPEGXL_ANIM_DEMUXER)  += jpegxl_parse.o
 SHLIBOBJS-$(CONFIG_MATROSKA_DEMUXER)     += mpeg4audio_sample_rates.o
-SHLIBOBJS-$(CONFIG_MATROSKA_MUXER)       += opus_frame_duration_tab.o
 SHLIBOBJS-$(CONFIG_MOV_DEMUXER)          += ac3_channel_layout_tab.o
 SHLIBOBJS-$(CONFIG_MOV_MUXER)            += mpegaudiotabs.o
 SHLIBOBJS-$(CONFIG_MP3_MUXER)            += mpegaudiotabs.o
@@ -767,7 +766,6 @@ SHLIBOBJS-$(CONFIG_RTPDEC)               += jpegtables.o
 SHLIBOBJS-$(CONFIG_RTP_MUXER)            += golomb_tab.o jpegtables.o \
                                             mpeg4audio_sample_rates.o
 SHLIBOBJS-$(CONFIG_SPDIF_MUXER)          += dca_sample_rate_tab.o
-SHLIBOBJS-$(CONFIG_WEBM_MUXER)           += opus_frame_duration_tab.o
 
 # libavdevice dependencies
 
diff --git a/libavformat/matroskaenc.c b/libavformat/matroskaenc.c
index f08fee0c9aa..c0e51c7a9e5 100644
--- a/libavformat/matroskaenc.c
+++ b/libavformat/matroskaenc.c
@@ -70,7 +70,7 @@
 #include "libavcodec/itut35.h"
 #include "libavcodec/xiph.h"
 #include "libavcodec/mpeg4audio.h"
-#include "libavcodec/opus/tab.h"
+#include "libavcodec/opus/opus.h"
 
 /* Level 1 elements we create a SeekHead entry for:
  * Info, Tracks, Chapters, Attachments, Tags (potentially twice) and Cues */
@@ -283,34 +283,6 @@ typedef struct MatroskaMuxContext {
 /** Seek preroll value for opus */
 #define OPUS_SEEK_PREROLL 80000000
 
-/**
- * Returns the duration of an Opus packet in samples.
- */
-static int parse_opus_packet_duration(const uint8_t *buf, int buf_size)
-{
-    int code   = buf[0] & 0x3;
-    int config = buf[0] >> 3;
-    int frame_count;
-
-    switch (code) {
-    default:
-        av_unreachable("code is in 0..3");
-    case 0:
-        frame_count = 1;
-        break;
-    case 1:
-    case 2:
-        frame_count = 2;
-        break;
-    case 3:
-        if (buf_size <= 1)
-            return AVERROR_INVALIDDATA;
-        frame_count = buf[1] & 0x3F;
-        break;
-    }
-    return frame_count * ff_opus_frame_duration[config];
-}
-
 static int ebml_id_size(uint32_t id)
 {
     return (av_log2(id) + 7U) / 8;
@@ -2900,7 +2872,7 @@ static int mkv_write_block(void *logctx, 
MatroskaMuxContext *mkv,
         duration != track->default_duration_low))
         ebml_writer_add_uint(&writer, MATROSKA_ID_BLOCKDURATION, duration);
     else if (par->codec_id == AV_CODEC_ID_OPUS) {
-        ret = parse_opus_packet_duration(pkt->data, pkt->size);
+        ret = ff_opus_packet_duration(pkt->data, pkt->size);
         if (ret >= 0) {
             /* If the packet's duration is inconsistent with the coded 
duration,
              * add an explicit duration element. */
diff --git a/libavformat/ogg/mapping/opus.c b/libavformat/ogg/mapping/opus.c
index c9fca879934..071c12c3523 100644
--- a/libavformat/ogg/mapping/opus.c
+++ b/libavformat/ogg/mapping/opus.c
@@ -23,6 +23,7 @@
 
 #include "libavutil/intreadwrite.h"
 #include "libavutil/mem.h"
+#include "libavcodec/opus/opus.h"
 #include "libavformat/avformat.h"
 #include "libavformat/internal.h"
 #include "libavformat/ogg/mapping.h"
@@ -110,26 +111,6 @@ static int opus_header(AVFormatContext *avf, int idx)
     return 0;
 }
 
-static int opus_duration(uint8_t *src, int size)
-{
-    unsigned nb_frames  = 1;
-    unsigned toc        = src[0];
-    unsigned toc_config = toc >> 3;
-    unsigned toc_count  = toc & 3;
-    unsigned frame_size = toc_config < 12 ? FFMAX(480, 960 * (toc_config & 3)) 
:
-                          toc_config < 16 ? 480 << (toc_config & 1) :
-                                            120 << (toc_config & 3);
-    if (toc_count == 3) {
-        if (size<2)
-            return AVERROR_INVALIDDATA;
-        nb_frames = src[1] & 0x3F;
-    } else if (toc_count) {
-        nb_frames = 2;
-    }
-
-    return frame_size * nb_frames;
-}
-
 static int opus_packet(AVFormatContext *avf, int idx)
 {
     struct ogg *ogg              = avf->priv_data;
@@ -179,7 +160,7 @@ static int opus_packet(AVFormatContext *avf, int idx)
 
         duration = 0;
         seg = os->segp;
-        d = opus_duration(last_pkt, os->psize);
+        d = ff_opus_packet_duration(last_pkt, os->psize);
         if (d < 0) {
             os->pflags |= AV_PKT_FLAG_CORRUPT;
             return 0;
@@ -189,7 +170,7 @@ static int opus_packet(AVFormatContext *avf, int idx)
         for (; seg < os->nsegs; seg++) {
             next_pkt += os->segments[seg];
             if (os->segments[seg] < 255 && next_pkt != last_pkt) {
-                d = opus_duration(last_pkt, next_pkt - last_pkt);
+                d = ff_opus_packet_duration(last_pkt, next_pkt - last_pkt);
                 if (d > 0)
                     duration += d;
                 last_pkt = next_pkt;
@@ -199,7 +180,7 @@ static int opus_packet(AVFormatContext *avf, int idx)
         os->lastdts                 = os->granule - duration;
     }
 
-    if ((ret = opus_duration(packet, os->psize)) < 0)
+    if ((ret = ff_opus_packet_duration(packet, os->psize)) < 0)
         return ret;
 
     os->pduration = ret;
diff --git a/libavformat/opus_frame_duration_tab.c 
b/libavformat/opus_frame_duration_tab.c
deleted file mode 100644
index d06fb20a298..00000000000
--- a/libavformat/opus_frame_duration_tab.c
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include "libavcodec/opus/frame_duration_tab.c"
diff --git a/libavformat/rtpdec_opus.c b/libavformat/rtpdec_opus.c
index 1eeef3c4b6a..858cea03468 100644
--- a/libavformat/rtpdec_opus.c
+++ b/libavformat/rtpdec_opus.c
@@ -23,29 +23,10 @@
 #include "libavcodec/bytestream.h"
 #include "libavutil/mem.h"
 #include "libavutil/avstring.h"
+#include "libavcodec/opus/opus.h"
 #include "rtpdec_formats.h"
 #include "internal.h"
 
-static int opus_duration(const uint8_t *src, int size)
-{
-    unsigned nb_frames  = 1;
-    unsigned toc        = src[0];
-    unsigned toc_config = toc >> 3;
-    unsigned toc_count  = toc & 3;
-    unsigned frame_size = toc_config < 12 ? FFMAX(480, 960 * (toc_config & 3)) 
:
-                          toc_config < 16 ? 480 << (toc_config & 1) :
-                                            120 << (toc_config & 3);
-    if (toc_count == 3) {
-        if (size<2)
-            return AVERROR_INVALIDDATA;
-        nb_frames = src[1] & 0x3F;
-    } else if (toc_count) {
-        nb_frames = 2;
-    }
-
-    return frame_size * nb_frames;
-}
-
 static int opus_write_extradata(AVCodecParameters *codecpar)
 {
     uint8_t *bs;
@@ -105,7 +86,7 @@ static int opus_parse_packet(AVFormatContext *ctx, 
PayloadContext *data,
     memcpy(pkt->data, buf, len);
     pkt->stream_index = st->index;
 
-    duration = opus_duration(buf, len);
+    duration = ff_opus_packet_duration(buf, len);
     if (duration != AVERROR_INVALIDDATA) {
         pkt->duration = duration;
     }
-- 
2.54.1


>From 9ae1521bba75860b8420d0b2b676761cae6c2460 Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Thu, 19 Nov 2026 07:57:11 -0600
Subject: [PATCH 4/4] avformat/mov: discard the trimmed samples of an Opus
 packet

Opus in ISOBMFF trims a packet by shortening its sample duration. Parse
the packet length from its TOC and export the difference as discard
padding.
---
 libavformat/mov.c                | 42 +++++++++++++++++++++++++++++++-
 tests/ref/fate/mov-mp4-opus-trim |  2 +-
 2 files changed, 42 insertions(+), 2 deletions(-)

diff --git a/libavformat/mov.c b/libavformat/mov.c
index 85936bf8252..87592728f78 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -60,6 +60,7 @@
 #include "libavcodec/mpegaudiodata.h"
 #include "libavcodec/mpegaudiodecheader.h"
 #include "libavcodec/mlp_parse.h"
+#include "libavcodec/opus/opus.h"
 #include "avformat.h"
 #include "internal.h"
 #include "avio_internal.h"
@@ -12897,6 +12898,45 @@ static int get_eia608_packet(AVIOContext *pb, AVPacket 
*pkt, int src_size)
     return ret;
 }
 
+/**
+ * Discard what an Opus packet decodes past the end of its sample, or of the
+ * edit list when that comes first.
+ */
+static int mov_opus_trim(AVStream *st, AVPacket *pkt)
+{
+    const AVRational opus_tb = { 1, 48000 };
+    const FFStream *sti = ffstream(st);
+    int64_t start, end, discard;
+    int samples;
+    uint8_t *side;
+
+    if (st->codecpar->codec_id != AV_CODEC_ID_OPUS ||
+        pkt->pts == AV_NOPTS_VALUE || pkt->duration <= 0 ||
+        av_packet_get_side_data(pkt, AV_PKT_DATA_ENCRYPTION_INFO, NULL))
+        return 0;
+
+    samples = ff_opus_packet_duration(pkt->data, pkt->size);
+    if (samples <= 0)
+        return 0;
+
+    start = av_rescale_q(pkt->pts, st->time_base, opus_tb);
+    end   = start + av_rescale_q(pkt->duration, st->time_base, opus_tb);
+    if (sti->first_discard_sample && st->codecpar->sample_rate > 0)
+        end = FFMIN(end, FFMAX(start, av_rescale(sti->first_discard_sample, 
48000,
+                                                 st->codecpar->sample_rate)));
+    discard = start + samples - end;
+
+    // A track clock coarser than 48 kHz rounds the sample durations.
+    if (discard < av_rescale_q_rnd(1, st->time_base, opus_tb, AV_ROUND_UP))
+        return 0;
+
+    side = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
+    if (!side)
+        return AVERROR(ENOMEM);
+    AV_WL32(side + 4, discard);
+    return 0;
+}
+
 static int mov_finalize_packet(AVFormatContext *s, AVStream *st, AVIndexEntry 
*sample,
                                 int64_t current_index, AVPacket *pkt)
 {
@@ -13159,7 +13199,7 @@ static int mov_read_packet(AVFormatContext *s, AVPacket 
*pkt)
         return ret;
     }
 
-    return 0;
+    return mov_opus_trim(st, pkt);
 }
 
 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t 
timestamp)
diff --git a/tests/ref/fate/mov-mp4-opus-trim b/tests/ref/fate/mov-mp4-opus-trim
index de48b1ec423..736b113a4df 100644
--- a/tests/ref/fate/mov-mp4-opus-trim
+++ b/tests/ref/fate/mov-mp4-opus-trim
@@ -7,4 +7,4 @@ a51e04975a80d74a5d887ed4f288de10 
*tests/data/fate/mov-mp4-opus-trim.mp4
 #sample_rate 0: 48000
 #channel_layout_name 0: stereo
 0,          0,          0,      960,        3, 0x05f002f9
-0,        960,        960,      168,        3, 0x05f002f9
+0,        960,        960,      168,        3, 0x05f002f9, S=1, Skip Samples,  
     10, 0x009f001b
-- 
2.54.1

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

Reply via email to