Commit 6896213fe7 for ffmpeg
commit 6896213fe7e6ca506b61c6826300ff99eb9587c1
Author: Romain Beauxis <romain.beauxis@gmail.com>
Date: Fri Nov 27 08:02:37 2026 -0600
avformat/demux: let demuxers apply the end trim with the packet length
The end trim takes the decoded length of a packet from the codec frame
size, or from the packet duration. A codec with a variable packet
length has no frame size, and a container trimming the stream by
shortening the last duration then leaves nothing to discard.
A demuxer that reads the decoded length from the packet can pass it
instead, while the packet keeps the container duration.
diff --git a/libavformat/demux.c b/libavformat/demux.c
index 4a63dab259..4bc3be6c7a 100644
--- a/libavformat/demux.c
+++ b/libavformat/demux.c
@@ -1243,6 +1243,27 @@ static int end_trim_padding(AVStream *st, const AVPacket *pkt, int64_t min_durat
return FFMIN(end_sample - sti->first_discard_sample, duration);
}
+int ff_end_trim_packet(AVStream *st, AVPacket *pkt, int64_t samples)
+{
+ int discard = end_trim_padding(st, pkt, samples);
+ size_t size;
+ uint8_t *side;
+
+ if (!discard || pkt->duration <= 0)
+ return 0;
+
+ side = av_packet_get_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, &size);
+ if (side && size >= 10) {
+ discard = FFMAX(discard, AV_RL32(side + 4));
+ } else {
+ 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;
+}
+
/**
* Parse a packet, add all split parts to parse_queue.
*
diff --git a/libavformat/demux.h b/libavformat/demux.h
index 146c702494..e0f140ec03 100644
--- a/libavformat/demux.h
+++ b/libavformat/demux.h
@@ -421,4 +421,16 @@ int ff_itunes_parse_smpb(const char *value, int64_t *priming,
int ff_buffer_packet(AVFormatContext *s, AVPacket *pkt);
+/**
+ * Apply the end trim of the stream to a packet whose decoded length the
+ * demuxer read from its payload, for a codec without a fixed frame size.
+ * The packet keeps its container duration, which a trimmed last packet
+ * shortens below its decoded length.
+ *
+ * @param samples decoded length of the packet, in samples at the stream
+ * sample rate
+ * @return 0 or AVERROR(ENOMEM)
+ */
+int ff_end_trim_packet(AVStream *st, AVPacket *pkt, int64_t samples);
+
#endif /* AVFORMAT_DEMUX_H */