Don't drop message if calculate duration is too small (#3442)

* Don't drop message if calculate duration is too small

* fix test
This commit is contained in:
cnderrauber
2025-02-18 14:41:41 +08:00
committed by GitHub
parent b3da3ff2cb
commit b2a54729f5
6 changed files with 23 additions and 11 deletions
+7 -3
View File
@@ -50,6 +50,10 @@ func (c *BitrateCalculator) AddBytes(bytes int, bufferedAmout int, ts time.Time)
defer c.lock.Unlock()
bytes -= bufferedAmout - c.lastBufferedAmount
if bytes < 0 {
// it is possible that internal buffering (non-data like DCEP packet from webrtc) caused bytes to be negative
bytes = 0
}
c.lastBufferedAmount = bufferedAmout
if ts.Sub(c.active.start) >= c.windowDuration {
c.windows.PushBack(c.active)
@@ -76,15 +80,15 @@ func (c *BitrateCalculator) AddBytes(bytes int, bufferedAmout int, ts time.Time)
}
func (c *BitrateCalculator) Bitrate(ts time.Time) int {
func (c *BitrateCalculator) Bitrate(ts time.Time) (int, bool) {
c.lock.Lock()
defer c.lock.Unlock()
duration := ts.Sub(c.start)
if duration < c.windowDuration {
duration = c.windowDuration
return 0, false
}
return c.bytes * 8 * 1000 / int(duration.Milliseconds())
return c.bytes * 8 * 1000 / int(duration.Milliseconds()), true
}
type bitrateWindow struct {
+9 -2
View File
@@ -15,15 +15,22 @@ func TestBitrateCalculator(t *testing.T) {
c.AddBytes(100, 0, t0)
// bytes buffered
c.AddBytes(100, 100, t0.Add(50*time.Millisecond))
bitrate, ok := c.Bitrate(t0.Add(50 * time.Millisecond))
require.Equal(t, 0, bitrate)
require.False(t, ok)
// 50 bytes sent (50 bytes buffer flushed)
c.AddBytes(100, 50, t0.Add(time.Second))
// 250 bytes sent in 1 second
require.Equal(t, 2000, c.Bitrate(t0.Add(time.Second)))
bitrate, ok = c.Bitrate(t0.Add(time.Second))
require.Equal(t, 2000, bitrate)
require.True(t, ok)
// silence for long time
t1 := t0.Add(2 * BitrateDuration)
// 150 bytes sent (50 bytes buffer flushed)
c.AddBytes(100, 0, t1)
require.Equal(t, 1200, c.Bitrate(t1.Add(time.Second)))
bitrate, ok = c.Bitrate(t1.Add(time.Second))
require.Equal(t, 1200, bitrate)
require.True(t, ok)
}
+1 -1
View File
@@ -64,7 +64,7 @@ func (w *DataChannelWriter[T]) Write(p []byte) (n int, err error) {
w.rate.AddBytes(n, int(w.bufferGetter.BufferedAmount()), now)
// retry if the write timed out on a non-slow receiver
if errors.Is(err, context.DeadlineExceeded) {
if bitrate := w.rate.Bitrate(now); bitrate >= w.slowThreshold {
if bitrate, ok := w.rate.Bitrate(now); !ok || bitrate >= w.slowThreshold {
continue
} else {
err = fmt.Errorf("%w: bitrate %d, threshold %d", ErrDataDroppedBySlowReader, bitrate, w.slowThreshold)