Replace sleep with sync.Cond to reduce jitter (#2603)

This commit is contained in:
cnderrauber
2024-03-29 17:24:31 +08:00
committed by GitHub
parent 95df9737a6
commit 0a35e59ebd
+7 -4
View File
@@ -69,6 +69,7 @@ type ExtPacket struct {
// Buffer contains all packets // Buffer contains all packets
type Buffer struct { type Buffer struct {
sync.RWMutex sync.RWMutex
readCond *sync.Cond
bucket *bucket.Bucket bucket *bucket.Bucket
nacker *nack.NackQueue nacker *nack.NackQueue
maxVideoPkts int maxVideoPkts int
@@ -144,6 +145,7 @@ func NewBuffer(ssrc uint32, maxVideoPkts, maxAudioPkts int) *Buffer {
pliThrottle: int64(500 * time.Millisecond), pliThrottle: int64(500 * time.Millisecond),
logger: l.WithComponent(sutils.ComponentPub).WithComponent(sutils.ComponentSFU), logger: l.WithComponent(sutils.ComponentPub).WithComponent(sutils.ComponentSFU),
} }
b.readCond = sync.NewCond(&b.RWMutex)
b.extPackets.SetMinCapacity(7) b.extPackets.SetMinCapacity(7)
return b return b
} }
@@ -324,6 +326,7 @@ func (b *Buffer) Write(pkt []byte) (n int, err error) {
b.payloadType = rtpPacket.PayloadType b.payloadType = rtpPacket.PayloadType
b.calc(pkt, &rtpPacket, time.Now(), false) b.calc(pkt, &rtpPacket, time.Now(), false)
b.Unlock() b.Unlock()
b.readCond.Signal()
return return
} }
@@ -398,24 +401,23 @@ func (b *Buffer) Read(buff []byte) (n int, err error) {
} }
func (b *Buffer) ReadExtended(buf []byte) (*ExtPacket, error) { func (b *Buffer) ReadExtended(buf []byte) (*ExtPacket, error) {
b.Lock()
for { for {
if b.closed.Load() { if b.closed.Load() {
b.Unlock()
return nil, io.EOF return nil, io.EOF
} }
b.Lock()
if b.extPackets.Len() > 0 { if b.extPackets.Len() > 0 {
ep := b.extPackets.PopFront() ep := b.extPackets.PopFront()
ep = b.patchExtPacket(ep, buf) ep = b.patchExtPacket(ep, buf)
if ep == nil { if ep == nil {
b.Unlock()
continue continue
} }
b.Unlock() b.Unlock()
return ep, nil return ep, nil
} }
b.Unlock() b.readCond.Wait()
time.Sleep(10 * time.Millisecond)
} }
} }
@@ -437,6 +439,7 @@ func (b *Buffer) Close() error {
} }
} }
b.readCond.Broadcast()
if b.onClose != nil { if b.onClose != nil {
b.onClose() b.onClose()
} }