Commit c07887f606 for ffmpeg
commit c07887f60697f43f5d53e89011e8a14e8cb33410
Author: Romain Beauxis <romain.beauxis@gmail.com>
Date: Mon Nov 23 08:46:18 2026 -0500
avformat/demux: keep full packets that round down in the end trim
On a track clock coarser than the sample rate, the duration of a full
last packet can round down below its decoded length, and its timestamp
can round up. The end trim then discards samples that the track does
not leave out.
Only trim when the decoded length, rounded down to the track clock, is
longer than what is left before the trim.
diff --git a/libavformat/demux.c b/libavformat/demux.c
index b5755f18ce..4a63dab259 100644
--- a/libavformat/demux.c
+++ b/libavformat/demux.c
@@ -1198,6 +1198,12 @@ static int64_t ts_to_samples(AVStream *st, int64_t ts)
return av_rescale(ts, st->time_base.num * st->codecpar->sample_rate, st->time_base.den);
}
+static int64_t samples_to_ts(AVStream *st, int64_t samples, enum AVRounding rnd)
+{
+ return av_rescale_rnd(samples, st->time_base.den,
+ st->time_base.num * st->codecpar->sample_rate, rnd);
+}
+
/**
* Samples of a packet past the end trim of the stream.
*
@@ -1209,7 +1215,8 @@ static int end_trim_padding(AVStream *st, const AVPacket *pkt, int64_t min_durat
const FFStream *sti = ffstream(st);
int64_t pts = pkt->pts, duration, sample, end_sample;
- if (!sti->first_discard_sample || pts == AV_NOPTS_VALUE)
+ if (!sti->first_discard_sample || pts == AV_NOPTS_VALUE ||
+ st->codecpar->sample_rate <= 0)
return 0;
duration = FFMAX(min_duration, ts_to_samples(st, pkt->duration));
@@ -1220,6 +1227,19 @@ static int end_trim_padding(AVStream *st, const AVPacket *pkt, int64_t min_durat
end_sample = av_sat_add64(sample, duration);
if (end_sample < sti->first_discard_sample || sample >= sti->last_discard_sample)
return 0;
+ // On a coarse clock, a full packet can round down to the ticks left.
+ if ((int64_t)st->time_base.num * st->codecpar->sample_rate > st->time_base.den &&
+ sti->first_discard_sample > sample) {
+ int64_t samples_left = sti->first_discard_sample - sample;
+ int64_t ticks_left = samples_to_ts(st, samples_left, AV_ROUND_NEAR_INF);
+ if (samples_to_ts(st, duration, AV_ROUND_DOWN) <= ticks_left) {
+ // An edit ending inside the packet's own duration is a cut, not
+ // rounding. Measure it from the decoded length, which stts rounds.
+ if (pkt->duration > ticks_left && min_duration > samples_left)
+ return min_duration - samples_left;
+ return 0;
+ }
+ }
return FFMIN(end_sample - sti->first_discard_sample, duration);
}