prevent estimated absolute timestamp from drifting too much (#5080)

This commit is contained in:
Alessandro Ros 2025-10-12 17:53:22 +02:00 committed by GitHub
parent 0cdae40fe3
commit a9d84103d0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 9 additions and 1 deletions

View file

@ -5,6 +5,10 @@ import (
"time" "time"
) )
const (
maxTimeDifference = 5 * time.Second
)
var timeNow = time.Now var timeNow = time.Now
func multiplyAndDivide(v, m, d time.Duration) time.Duration { func multiplyAndDivide(v, m, d time.Duration) time.Duration {
@ -35,7 +39,7 @@ func (e *Estimator) Estimate(pts int64) time.Time {
computed := e.refNTP.Add((multiplyAndDivide(time.Duration(pts-e.refPTS), time.Second, time.Duration(e.ClockRate)))) computed := e.refNTP.Add((multiplyAndDivide(time.Duration(pts-e.refPTS), time.Second, time.Duration(e.ClockRate))))
if computed.After(now) { if computed.After(now) || computed.Before(now.Add(-maxTimeDifference)) {
e.refNTP = now e.refNTP = now
e.refPTS = pts e.refPTS = pts
return now return now

View file

@ -29,4 +29,8 @@ func TestEstimator(t *testing.T) {
timeNow = func() time.Time { return time.Date(2003, 11, 4, 23, 15, 15, 0, time.UTC) } timeNow = func() time.Time { return time.Date(2003, 11, 4, 23, 15, 15, 0, time.UTC) }
ntp = e.Estimate(5 * 90000) ntp = e.Estimate(5 * 90000)
require.Equal(t, time.Date(2003, 11, 4, 23, 15, 10, 0, time.UTC), ntp) require.Equal(t, time.Date(2003, 11, 4, 23, 15, 10, 0, time.UTC), ntp)
timeNow = func() time.Time { return time.Date(2003, 11, 4, 23, 15, 20, 0, time.UTC) }
ntp = e.Estimate(6 * 90000)
require.Equal(t, time.Date(2003, 11, 4, 23, 15, 20, 0, time.UTC), ntp)
} }