Move callbacks out of messageRouter (#269)

* move callbacks out of messageRouter

* OCD

* more OCD

* fix forwarder test

* even more OCD

* maximum OCD

* package name collision, copy lock by value
This commit is contained in:
David Colburn
2021-12-17 13:19:23 -08:00
committed by GitHub
parent a06edd885e
commit faa870de3d
82 changed files with 315 additions and 527 deletions
-24
View File
@@ -25,30 +25,6 @@ func (a *atomicUint8) get() uint8 {
return uint8(atomic.LoadUint32((*uint32)(a)))
}
type atomicUint16 uint32
func (a *atomicUint16) set(value uint16) {
atomic.StoreUint32((*uint32)(a), uint32(value))
}
func (a *atomicUint16) get() uint16 {
return uint16(atomic.LoadUint32((*uint32)(a)))
}
func (a *atomicUint16) add(value uint16) {
atomic.AddUint32((*uint32)(a), uint32(value))
}
type atomicInt32 int32
func (a *atomicInt32) set(value int32) {
atomic.StoreInt32((*int32)(a), value)
}
func (a *atomicInt32) get() int32 {
return atomic.LoadInt32((*int32)(a))
}
type atomicUint32 uint32
func (a *atomicUint32) set(value uint32) {
+4 -4
View File
@@ -49,7 +49,7 @@ func Test_queue(t *testing.T) {
buf, err := p.Marshal()
assert.NoError(t, err)
assert.NotPanics(t, func() {
q.AddPacket(buf, p.SequenceNumber, true)
_, _ = q.AddPacket(buf, p.SequenceNumber, true)
})
}
var expectedSN uint16
@@ -70,7 +70,7 @@ func Test_queue(t *testing.T) {
buf, err := np2.Marshal()
assert.NoError(t, err)
expectedSN = 8
q.AddPacket(buf, 8, false)
_, _ = q.AddPacket(buf, 8, false)
i, err = q.GetPacket(buff, expectedSN)
assert.NoError(t, err)
err = np.Unmarshal(buff[:i])
@@ -109,7 +109,7 @@ func Test_queue_edges(t *testing.T) {
buf, err := p.Marshal()
assert.NoError(t, err)
assert.NotPanics(t, func() {
q.AddPacket(buf, p.SequenceNumber, true)
_, _ = q.AddPacket(buf, p.SequenceNumber, true)
})
})
}
@@ -130,7 +130,7 @@ func Test_queue_edges(t *testing.T) {
}
buf, err := np2.Marshal()
assert.NoError(t, err)
q.AddPacket(buf, np2.SequenceNumber, false)
_, _ = q.AddPacket(buf, np2.SequenceNumber, false)
i, err = q.GetPacket(buff, expectedSN+1)
assert.NoError(t, err)
err = np.Unmarshal(buff[:i])
+5 -7
View File
@@ -17,13 +17,11 @@ import (
)
const (
MaxSN = 1 << 16
ReportDelta = 1e9
)
// Logger is an implementation of logr.Logger. If is not provided - will be turned off.
var Logger logr.Logger = logr.Discard()
var Logger = logr.Discard()
type pendingPackets struct {
arrivalTime int64
@@ -36,7 +34,7 @@ type ExtPacket struct {
Packet rtp.Packet
Payload interface{}
KeyFrame bool
//audio level for voice, l&0x80 == 0 means audio level not present
// audio level for voice, l&0x80 == 0 means audio level not present
AudioLevel uint8
RawPacket []byte
}
@@ -183,7 +181,7 @@ func (b *Buffer) Bind(params webrtc.RTPParameters, codec webrtc.RTPCodecCapabili
b.logger.V(1).Info("NewBuffer", "MaxBitRate", o.MaxBitRate)
}
// Write adds a RTP Packet, out of order, new packet may be arrived later
// Write adds an RTP Packet, out of order, new packet may be arrived later
func (b *Buffer) Write(pkt []byte) (n int, err error) {
b.Lock()
defer b.Unlock()
@@ -416,7 +414,7 @@ func (b *Buffer) calc(pkt []byte, arrivalTime int64) {
bitrates = make([]int64, len(b.bitrateHelper))
}
for i := 0; i < len(b.bitrateHelper); i++ {
br := (8 * b.bitrateHelper[i] * int64(ReportDelta)) / int64(diff)
br := (8 * b.bitrateHelper[i] * int64(ReportDelta)) / diff
bitrates[i] = br
b.bitrateHelper[i] = 0
}
@@ -681,7 +679,7 @@ func (s *SeqWrapHandler) Unwrap(seq uint16) (uint32, bool) {
if delta > 0 && (int32(s.maxSeqNo)+delta-0x10000) >= 0 {
// wrap backwards, should not less than 0 in this case:
// at start time, received seq 1, set s.maxSeqNo =1 ,
// then a out of order seq 65534 coming, we can't unwrap
// then an out of order seq 65534 coming, we can't unwrap
// the seq to -2
delta -= 0x10000
}
+4 -36
View File
@@ -6,44 +6,12 @@ import (
"time"
"github.com/pion/rtcp"
"github.com/pion/rtp"
"github.com/pion/webrtc/v3"
"github.com/stretchr/testify/assert"
)
func CreateTestPacket(pktStamp *SequenceNumberAndTimeStamp) *rtp.Packet {
if pktStamp == nil {
return &rtp.Packet{
Header: rtp.Header{},
Payload: []byte{1, 2, 3},
}
}
return &rtp.Packet{
Header: rtp.Header{
SequenceNumber: pktStamp.SequenceNumber,
Timestamp: pktStamp.Timestamp,
},
Payload: []byte{1, 2, 3},
}
}
type SequenceNumberAndTimeStamp struct {
SequenceNumber uint16
Timestamp uint32
}
func CreateTestListPackets(snsAndTSs []SequenceNumberAndTimeStamp) (packetList []*rtp.Packet) {
for _, item := range snsAndTSs {
item := item
packetList = append(packetList, CreateTestPacket(&item))
}
return packetList
}
var vp8Codec webrtc.RTPCodecParameters = webrtc.RTPCodecParameters{
var vp8Codec = webrtc.RTPCodecParameters{
RTPCodecCapability: webrtc.RTPCodecCapability{
MimeType: "video/vp8",
ClockRate: 90000,
@@ -54,7 +22,7 @@ var vp8Codec webrtc.RTPCodecParameters = webrtc.RTPCodecParameters{
PayloadType: 96,
}
var opusCodec webrtc.RTPCodecParameters = webrtc.RTPCodecParameters{
var opusCodec = webrtc.RTPCodecParameters{
RTPCodecCapability: webrtc.RTPCodecCapability{
MimeType: "audio/opus",
ClockRate: 48000,
@@ -233,7 +201,7 @@ func TestNewBuffer(t *testing.T) {
for _, p := range TestPackets {
buf, _ := p.Marshal()
buff.Write(buf)
_, _ = buff.Write(buf)
}
// assert.Equal(t, 6, buff.PacketQueue.size)
assert.Equal(t, uint32(1<<16), buff.seqHdlr.Cycles())
@@ -292,7 +260,7 @@ func TestSeqWrapHandler(t *testing.T) {
assert.Equal(t, uint32(1), s.MaxSeqNo())
type caseInfo struct {
seqs []uint32 //{seq1, seq2, unwrap of seq2}
seqs []uint32 // {seq1, seq2, unwrap of seq2}
newer bool // seq2 is newer than seq1
}
// test normal case, name -> {seq1, seq2, unwrap of seq2}
+20 -20
View File
@@ -70,7 +70,7 @@ type VP8 struct {
}
// Unmarshal parses the passed byte slice and stores the result in the VP8 this method is called upon
func (p *VP8) Unmarshal(payload []byte) error {
func (v *VP8) Unmarshal(payload []byte) error {
if payload == nil {
return errNilPacket
}
@@ -82,7 +82,7 @@ func (p *VP8) Unmarshal(payload []byte) error {
}
idx := 0
p.FirstByte = payload[idx]
v.FirstByte = payload[idx]
S := payload[idx]&0x10 > 0
// Check for extended bit control
if payload[idx]&0x80 > 0 {
@@ -103,7 +103,7 @@ func (p *VP8) Unmarshal(payload []byte) error {
if payloadLen < idx+1 {
return errShortPacket
}
p.PictureIDPresent = 1
v.PictureIDPresent = 1
pid := payload[idx] & 0x7f
// Check if m is 1, then Picture ID is 15 bits
if payload[idx]&0x80 > 0 {
@@ -111,10 +111,10 @@ func (p *VP8) Unmarshal(payload []byte) error {
if payloadLen < idx+1 {
return errShortPacket
}
p.MBit = true
p.PictureID = binary.BigEndian.Uint16([]byte{pid, payload[idx]})
v.MBit = true
v.PictureID = binary.BigEndian.Uint16([]byte{pid, payload[idx]})
} else {
p.PictureID = uint16(pid)
v.PictureID = uint16(pid)
}
}
// Check if TL0PICIDX is present
@@ -123,12 +123,12 @@ func (p *VP8) Unmarshal(payload []byte) error {
if payloadLen < idx+1 {
return errShortPacket
}
p.TL0PICIDXPresent = 1
v.TL0PICIDXPresent = 1
if int(idx) >= payloadLen {
if idx >= payloadLen {
return errShortPacket
}
p.TL0PICIDX = payload[idx]
v.TL0PICIDX = payload[idx]
}
if T || K {
idx++
@@ -136,13 +136,13 @@ func (p *VP8) Unmarshal(payload []byte) error {
return errShortPacket
}
if T {
p.TIDPresent = 1
p.TID = (payload[idx] & 0xc0) >> 6
p.Y = (payload[idx] & 0x20) >> 5
v.TIDPresent = 1
v.TID = (payload[idx] & 0xc0) >> 6
v.Y = (payload[idx] & 0x20) >> 5
}
if K {
p.KEYIDXPresent = 1
p.KEYIDX = payload[idx] & 0x1f
v.KEYIDXPresent = 1
v.KEYIDX = payload[idx] & 0x1f
}
}
if idx >= payloadLen {
@@ -153,16 +153,16 @@ func (p *VP8) Unmarshal(payload []byte) error {
return errShortPacket
}
// Check is packet is a keyframe by looking at P bit in vp8 payload
p.IsKeyFrame = payload[idx]&0x01 == 0 && S
v.IsKeyFrame = payload[idx]&0x01 == 0 && S
} else {
idx++
if payloadLen < idx+1 {
return errShortPacket
}
// Check is packet is a keyframe by looking at P bit in vp8 payload
p.IsKeyFrame = payload[idx]&0x01 == 0 && S
v.IsKeyFrame = payload[idx]&0x01 == 0 && S
}
p.HeaderSize = idx
v.HeaderSize = idx
return nil
}
@@ -189,16 +189,16 @@ func (v *VP8) MarshalTo(buf []byte) error {
}
}
if v.TL0PICIDXPresent == 1 {
buf[idx] = byte(v.TL0PICIDX)
buf[idx] = v.TL0PICIDX
idx++
}
if v.TIDPresent == 1 || v.KEYIDXPresent == 1 {
buf[idx] = 0
if v.TIDPresent == 1 {
buf[idx] = byte(v.TID<<6) | byte(v.Y<<5)
buf[idx] = v.TID<<6 | v.Y<<5
}
if v.KEYIDXPresent == 1 {
buf[idx] |= byte(v.KEYIDX & 0x1f)
buf[idx] |= v.KEYIDX & 0x1f
}
idx++
}
+1 -1
View File
@@ -8,7 +8,7 @@ import (
type RTCPReader struct {
ssrc uint32
closed atomicBool
onPacket atomic.Value //func([]byte)
onPacket atomic.Value // func([]byte)
onClose func()
}
+4 -5
View File
@@ -19,7 +19,7 @@ import (
"github.com/livekit/livekit-server/pkg/sfu/buffer"
)
// TrackSender defines a interface send media to remote peer
// TrackSender defines an interface send media to remote peer
type TrackSender interface {
UptrackLayersChange(availableLayers []uint16)
WriteRTP(p *buffer.ExtPacket, layer int32) error
@@ -45,7 +45,6 @@ var (
ErrNotVP8 = errors.New("not VP8")
ErrOutOfOrderVP8PictureIdCacheMiss = errors.New("out-of-order VP8 picture id not found in cache")
ErrFilteredVP8TemporalLayer = errors.New("filtered VP8 temporal layer")
ErrNoRequiredBuff = errors.New("buff size if less than required")
)
var (
@@ -156,7 +155,7 @@ func NewDownTrack(c webrtc.RTPCodecCapability, r TrackReceiver, bf *buffer.Facto
// Bind is called by the PeerConnection after negotiation is complete
// This asserts that the code requested is supported by the remote peer.
// If so it setups all the state (SSRC and PayloadType) to have a call
// If so it sets up all the state (SSRC and PayloadType) to have a call
func (d *DownTrack) Bind(t webrtc.TrackLocalContext) (webrtc.RTPCodecParameters, error) {
parameters := webrtc.RTPCodecParameters{RTPCodecCapability: d.codec}
if codec, err := codecParametersFuzzySearch(parameters, t.CodecParameters()); err == nil {
@@ -227,7 +226,7 @@ func (d *DownTrack) SetTransceiver(transceiver *webrtc.RTPTransceiver) {
d.transceiver = transceiver
}
// WriteRTP writes a RTP Packet to the DownTrack
// WriteRTP writes an RTP Packet to the DownTrack
func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) error {
var pool *[]byte
defer func() {
@@ -420,7 +419,7 @@ func (d *DownTrack) Close() {
// Idea here is to send blank 1x1 key frames to flush the decoder buffer at the remote end.
// Otherwise, with transceiver re-use last frame from previous stream is held in the
// display buffer and there could be a brief moment where the previous stream is displayed.
d.writeBlankFrameRTP()
_ = d.writeBlankFrameRTP()
d.closeOnce.Do(func() {
Logger.V(1).Info("Closing sender", "peer_id", d.peerID, "kind", d.kind)
-7
View File
@@ -1,8 +1 @@
package sfu
import "errors"
var (
ErrSpatialNotSupported = errors.New("current track does not support simulcast/SVC")
ErrSpatialLayerNotFound = errors.New("the requested layer does not exist")
)
+2 -14
View File
@@ -26,13 +26,6 @@ const (
ForwardingStatusOptimal
)
type LayerDirection int
const (
LayerDirectionLowToHigh LayerDirection = iota
LayerDirectionHighToLow
)
type VideoStreamingChange int
const (
@@ -154,11 +147,6 @@ var (
temporal: -1,
}
MinLayers = VideoLayers{
spatial: 0,
temporal: 0,
}
DefaultMaxLayers = VideoLayers{
spatial: DefaultMaxLayerSpatial,
temporal: DefaultMaxLayerTemporal,
@@ -539,7 +527,7 @@ func (f *Forwarder) ProvisionalAllocateGetCooperativeTransition() VideoTransitio
// 4. If not currently streaming, find the minimum layers that can unpause the stream.
//
// To summarize, co-operative streaming means
// - Try to keep tracks streaming, i. e. no pauses even if not at optimal layers
// - Try to keep tracks streaming, i.e. no pauses even if not at optimal layers
// - Do not make an upgrade as it could affect other tracks
//
f.lock.Lock()
@@ -1097,7 +1085,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
// this will take client subscription as the winning vote and
// continue to stream current spatial layer till switch point.
// That could lead to congesting the channel.
// LK-TODO: Improve the above case, i. e. distinguish server
// LK-TODO: Improve the above case, i.e. distinguish server
// applied restriction from client requested restriction.
//
tp.shouldDrop = true
+12 -13
View File
@@ -4,12 +4,11 @@ import (
"reflect"
"testing"
"github.com/pion/webrtc/v3"
"github.com/stretchr/testify/require"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/livekit-server/pkg/sfu/testutils"
"github.com/pion/webrtc/v3"
"github.com/stretchr/testify/require"
)
func disable(f *Forwarder) {
@@ -180,7 +179,7 @@ func TestForwarderAllocate(t *testing.T) {
require.Equal(t, expectedResult, result)
require.Equal(t, expectedResult, f.lastAllocation)
// awaiting measurement, i. e. bitrates are not available, but layers available
// awaiting measurement, i.e. bitrates are not available, but layers available
f.lastAllocation.state = VideoAllocationStateNone
disable(f)
f.UptrackLayersChange([]uint16{0})
@@ -494,7 +493,7 @@ func TestForwarderFinalizeAllocate(t *testing.T) {
bandwidthRequested: 0,
bandwidthDelta: 0,
availableLayers: nil,
bitrates: [3][4]int64{},
bitrates: Bitrates{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
targetLayers: InvalidLayers,
distanceToDesired: 0,
}
@@ -653,7 +652,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
require.Equal(t, expectedResult, f.lastAllocation)
require.False(t, boosted)
// move from (0, 0) -> (0, 1), i. e. a higher temporal layer is available in the same spatial layer
// move from (0, 0) -> (0, 1), i.e. a higher temporal layer is available in the same spatial layer
expectedTargetLayers := VideoLayers{
spatial: 0,
temporal: 1,
@@ -674,7 +673,7 @@ func TestForwarderAllocateNextHigher(t *testing.T) {
require.Equal(t, expectedTargetLayers, f.TargetLayers())
require.True(t, boosted)
// move from (0, 1) -> (1, 0), i. e. a higher spatial layer is available
// move from (0, 1) -> (1, 0), i.e. a higher spatial layer is available
f.currentLayers.temporal = 1
expectedTargetLayers = VideoLayers{
spatial: 1,
@@ -1399,7 +1398,7 @@ func TestForwardGetSnTsForPadding(t *testing.T) {
f.currentLayers = InvalidLayers
// send it through so that forwarder locks onto stream
f.GetTranslationParams(extPkt, 0)
_, _ = f.GetTranslationParams(extPkt, 0)
// pause stream and get padding, it should still work
disable(f)
@@ -1411,7 +1410,7 @@ func TestForwardGetSnTsForPadding(t *testing.T) {
numPadding := 5
clockRate := uint32(0)
frameRate := uint32(5)
var sntsExpected []SnTs = make([]SnTs, numPadding)
var sntsExpected = make([]SnTs, numPadding)
for i := 0; i < numPadding; i++ {
sntsExpected[i] = SnTs{
sequenceNumber: 23333 + uint16(i) + 1,
@@ -1467,7 +1466,7 @@ func TestForwardGetSnTsForBlankFrames(t *testing.T) {
f.currentLayers = InvalidLayers
// send it through so that forwarder locks onto stream
f.GetTranslationParams(extPkt, 0)
_, _ = f.GetTranslationParams(extPkt, 0)
// should get back frame end needed as the last packet did not have RTP marker set
snts, frameEndNeeded, err := f.GetSnTsForBlankFrames()
@@ -1478,7 +1477,7 @@ func TestForwardGetSnTsForBlankFrames(t *testing.T) {
numPadding := RTPBlankFramesMax + 1
clockRate := testutils.TestVP8Codec.ClockRate
frameRate := uint32(30)
var sntsExpected []SnTs = make([]SnTs, numPadding)
var sntsExpected = make([]SnTs, numPadding)
for i := 0; i < numPadding; i++ {
sntsExpected[i] = SnTs{
sequenceNumber: 23333 + uint16(i) + 1,
@@ -1538,7 +1537,7 @@ func TestForwardGetPaddingVP8(t *testing.T) {
f.currentLayers = InvalidLayers
// send it through so that forwarder locks onto stream
f.GetTranslationParams(extPkt, 0)
_, _ = f.GetTranslationParams(extPkt, 0)
// getting padding with frame end needed, should repeat the last picture id
expectedVP8 := buffer.VP8{
-18
View File
@@ -4,7 +4,6 @@ import (
"strings"
"time"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/pion/webrtc/v3"
)
@@ -41,23 +40,6 @@ func codecParametersFuzzySearch(needle webrtc.RTPCodecParameters, haystack []web
return webrtc.RTPCodecParameters{}, webrtc.ErrCodecNotFound
}
func ntpToMillisSinceEpoch(ntp uint64) uint64 {
// ntp time since epoch calculate fractional ntp as milliseconds
// (lower 32 bits stored as 1/2^32 seconds) and add
// ntp seconds (stored in higher 32 bits) as milliseconds
return (((ntp & 0xFFFFFFFF) * 1000) >> 32) + ((ntp >> 32) * 1000)
}
func fastForwardTimestampAmount(newestTimestamp uint32, referenceTimestamp uint32) uint32 {
if buffer.IsTimestampWrapAround(newestTimestamp, referenceTimestamp) {
return uint32(uint64(newestTimestamp) + 0x100000000 - uint64(referenceTimestamp))
}
if newestTimestamp < referenceTimestamp {
return 0
}
return newestTimestamp - referenceTimestamp
}
func (t ntpTime) Duration() time.Duration {
sec := (t >> 32) * 1e9
frac := (t & 0xffffffff) * 1e9
+4 -5
View File
@@ -1,7 +1,7 @@
//
// Design of Prober
//
// Probing is to used to check for existence of excess channel capacity.
// Probing is used to to check for existence of excess channel capacity.
// This is especially useful in the downstream direction of SFU.
// SFU forwards audio/video streams from one or more publishers to
// all the subscribers. But, the downstream channel of a subscriber
@@ -75,7 +75,7 @@
//
// A further assumption is that if there are multiple publishers for
// a subscriber peer connection, all the publishers are not pacing
// in sync, i. e. each publisher's pacer is completely independent
// in sync, i.e. each publisher's pacer is completely independent
// and SFU will be receiving the media packets with a good spread and
// not clumped together.
//
@@ -112,7 +112,6 @@ import (
"time"
"github.com/gammazero/deque"
"github.com/livekit/protocol/logger"
)
@@ -262,7 +261,7 @@ func (p *Prober) run() {
}
}
//---------------------------------
// ---------------------------------
type Cluster struct {
// LK-TODO-START
@@ -290,7 +289,7 @@ func NewCluster(desiredRateBps int, expectedRateBps int, minDuration time.Durati
expectedBytes := int((int64(expectedRateBps)*minDurationMs/time.Second.Milliseconds() + 7) / 8)
// pace based on sending approximately 1000 bytes per probe
numProbes := int((desiredBytes - expectedBytes + 999) / 1000)
numProbes := (desiredBytes - expectedBytes + 999) / 1000
sleepDurationMicroSeconds := int(float64(minDurationMs*1000)/float64(numProbes) + 0.5)
c := &Cluster{
desiredBytes: desiredBytes,
+2 -2
View File
@@ -18,7 +18,7 @@ import (
type Bitrates [DefaultMaxLayerSpatial + 1][DefaultMaxLayerTemporal + 1]int64
// TrackReceiver defines a interface receive media from remote peer
// TrackReceiver defines an interface receive media from remote peer
type TrackReceiver interface {
TrackID() string
StreamID() string
@@ -31,7 +31,7 @@ type TrackReceiver interface {
Codec() webrtc.RTPCodecCapability
}
// Receiver defines a interface for a track receivers
// Receiver defines an interface for a track receivers
type Receiver interface {
TrackID() string
StreamID() string
+3 -3
View File
@@ -121,7 +121,7 @@ func (r *RTPMunger) UpdateAndGetSnTs(extPkt *buffer.ExtPacket) (*TranslationPara
// if padding only packet, can be dropped and sequence number adjusted
// as it is contiguous and in order. That means this is the highest
// incoming sequence number and it is a good point to adjust
// incoming sequence number, and it is a good point to adjust
// sequence number offset.
if len(extPkt.Packet.Payload) == 0 {
r.highestIncomingSN = extPkt.Packet.SequenceNumber
@@ -134,10 +134,10 @@ func (r *RTPMunger) UpdateAndGetSnTs(extPkt *buffer.ExtPacket) (*TranslationPara
}
// in-order incoming packet, may or may not be contiguous.
// In the case of loss (i. e. incoming sequence number is not contiguous),
// In the case of loss (i.e. incoming sequence number is not contiguous),
// forward even if it is a padding only packet. With temporal scalability,
// it is unclear if the current packet should be dropped if it is not
// contiguous. Hence forward anything that is not contiguous.
// contiguous. Hence, forward anything that is not contiguous.
// Reference: http://www.rtcbits.com/2017/04/howto-implement-temporal-scalability.html
mungedSN := extPkt.Packet.SequenceNumber - r.snOffset
mungedTS := extPkt.Packet.Timestamp - r.tsOffset
+3 -3
View File
@@ -4,9 +4,9 @@ import (
"reflect"
"testing"
"github.com/livekit/livekit-server/pkg/sfu/testutils"
"github.com/stretchr/testify/require"
"github.com/livekit/livekit-server/pkg/sfu/testutils"
)
func TestSetLastSnTs(t *testing.T) {
@@ -314,7 +314,7 @@ func TestUpdateAndGetPaddingSnTs(t *testing.T) {
numPadding := 10
clockRate := uint32(10)
frameRate := uint32(5)
var sntsExpected []SnTs = make([]SnTs, numPadding)
var sntsExpected = make([]SnTs, numPadding)
for i := 0; i < numPadding; i++ {
sntsExpected[i] = SnTs{
sequenceNumber: 23333 + uint16(i) + 1,
+2 -2
View File
@@ -5,9 +5,9 @@ import (
"testing"
"time"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/stretchr/testify/require"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
)
func Test_sequencer(t *testing.T) {
+1 -1
View File
@@ -7,7 +7,7 @@ import (
)
// Logger is an implementation of logr.Logger. If is not provided - will be turned off.
var Logger logr.Logger = logr.Discard()
var Logger = logr.Discard()
var (
PacketFactory *sync.Pool
+30 -31
View File
@@ -8,7 +8,6 @@ import (
"time"
"github.com/livekit/protocol/logger"
"github.com/pion/rtcp"
"github.com/pion/webrtc/v3"
)
@@ -18,25 +17,25 @@ const (
EstimateEpsilon = 2000 // 2 kbps
GratuitousProbeHeadroomBps = 1 * 1000 * 1000 // if headroom > 1 Mbps, don't probe
GratuitousProbePct = 10
GratuitousProbeMinBps = 100 * 1000 // 100 kbps
GratuitousProbeMaxBps = 300 * 1000 // 300 kbps
GratuitousProbeMinDurationMs = 500 * time.Millisecond
GratuitousProbeMaxDurationMs = 600 * time.Millisecond
GratuitousProbeHeadroomBps = 1 * 1000 * 1000 // if headroom > 1 Mbps, don't probe
GratuitousProbePct = 10
GratuitousProbeMinBps = 100 * 1000 // 100 kbps
GratuitousProbeMaxBps = 300 * 1000 // 300 kbps
GratuitousProbeMinDuration = 500 * time.Millisecond
GratuitousProbeMaxDuration = 600 * time.Millisecond
AudioLossWeight = 0.75
VideoLossWeight = 0.25
// LK-TODO-START
// These constants will definitely require more tweaking.
// In fact, simple time tresholded rules most proably will not be enough.
// In fact, simple time threshold rules most probably will not be enough.
// LK-TODO-END
EstimateCommitMs = 2 * 1000 * time.Millisecond // 2 seconds
ProbeWaitMs = 8 * 1000 * time.Millisecond // 8 seconds
BoostWaitMs = 5 * 1000 * time.Millisecond // 5 seconds
GratuitousProbeWaitMs = 8 * 1000 * time.Millisecond // 8 seconds
GratuitousProbeMoreWaitMs = 5 * 1000 * time.Millisecond // 5 seconds
EstimateCommit = 2 * 1000 * time.Millisecond // 2 seconds
ProbeWait = 8 * 1000 * time.Millisecond // 8 seconds
BoostWait = 5 * 1000 * time.Millisecond // 5 seconds
GratuitousProbeWait = 8 * 1000 * time.Millisecond // 8 seconds
GratuitousProbeMoreWait = 5 * 1000 * time.Millisecond // 5 seconds
)
type State int
@@ -200,7 +199,7 @@ func (s *StreamAllocator) RemoveTrack(downTrack *DownTrack) {
func (s *StreamAllocator) initializeEstimate() {
s.committedChannelCapacity = ChannelCapacityInfinity
s.lastCommitTime = time.Now().Add(-EstimateCommitMs)
s.lastCommitTime = time.Now().Add(-EstimateCommit)
s.receivedEstimate = ChannelCapacityInfinity
s.lastEstimateDecreaseTime = time.Now()
@@ -406,7 +405,7 @@ func (s *StreamAllocator) handleSignalEstimate(event *Event) {
//
// A couple of things to keep in mind
// - REMB reports could be sent gratuitously as a way of providing
// periodic feedback, i. e. even if the estimated capacity does not
// periodic feedback, i.e. even if the estimated capacity does not
// change, there could be REMB packets on the wire. Those gratuitous
// REMBs should not trigger anything bad.
// - As each down track will issue this callback for the same REMB packet
@@ -594,14 +593,14 @@ func (s *StreamAllocator) maybeCommitEstimate() (isDecreasing bool) {
if math.Abs(float64(s.receivedEstimate)-float64(s.prevReceivedEstimate)) > EstimateEpsilon {
// too large a change, wait for estimate to settle.
// Unless estimate has been oscillating for too long.
if time.Since(s.lastCommitTime) < EstimateCommitMs {
if time.Since(s.lastCommitTime) < EstimateCommit {
return
}
}
// don't commit too often even if the change is small.
// Small changes will also get picked up during periodic check.
if time.Since(s.lastCommitTime) < EstimateCommitMs {
if time.Since(s.lastCommitTime) < EstimateCommit {
return
}
@@ -664,7 +663,7 @@ func (s *StreamAllocator) allocateTrack(track *Track) {
return
// LK-TODO-START
// Should use the bits given back to start any paused track.
// Note layer downgrade may actually have positive delta (i. e. consume more bits)
// Note layer downgrade may actually have positive delta (i.e. consume more bits)
// because of when the measurement is done. Watch for that.
// LK-TODO-END
}
@@ -728,7 +727,7 @@ func (s *StreamAllocator) allocateAllTracks() {
//
// Goals:
// 1. Stream as many tracks as possible, i. e. no pauses.
// 1. Stream as many tracks as possible, i.e. no pauses.
// 2. Try to give fair allocation to all track.
//
// Start with the lowest layers and give each track a chance at that layer and keep going up.
@@ -905,9 +904,9 @@ func (s *StreamAllocator) isTimeToBoost() bool {
// Checking against last estimate boost prevents multiple artificial boosts
// in situations where multiple tracks become available in a short span.
if !s.lastBoostTime.IsZero() {
return time.Since(s.lastBoostTime) > BoostWaitMs
return time.Since(s.lastBoostTime) > BoostWait
} else {
return time.Since(s.lastEstimateDecreaseTime) > ProbeWaitMs
return time.Since(s.lastEstimateDecreaseTime) > ProbeWait
}
}
@@ -916,12 +915,12 @@ func (s *StreamAllocator) resetBoost() {
}
func (s *StreamAllocator) maybeGratuitousProbe() bool {
if time.Since(s.lastEstimateDecreaseTime) < GratuitousProbeWaitMs || len(s.managedVideoTracksSorted) == 0 {
if time.Since(s.lastEstimateDecreaseTime) < GratuitousProbeWait || len(s.managedVideoTracksSorted) == 0 {
return false
}
// don't gratuitously probe too often
if time.Since(s.lastGratuitousProbeTime) < GratuitousProbeMoreWaitMs {
if time.Since(s.lastGratuitousProbeTime) < GratuitousProbeMoreWait {
return false
}
@@ -944,8 +943,8 @@ func (s *StreamAllocator) maybeGratuitousProbe() bool {
s.prober.AddCluster(
int(s.receivedEstimate+probeRateBps),
int(expectedRateBps),
GratuitousProbeMinDurationMs,
GratuitousProbeMaxDurationMs,
GratuitousProbeMinDuration,
GratuitousProbeMaxDuration,
)
s.lastGratuitousProbeTime = time.Now()
@@ -957,7 +956,7 @@ func (s *StreamAllocator) resetGratuitousProbe() {
s.lastGratuitousProbeTime = time.Now()
}
//------------------------------------------------
// ------------------------------------------------
type StreamState int
@@ -1001,7 +1000,7 @@ func (s *StreamStateUpdate) Empty() bool {
return len(s.StreamStates) == 0
}
//------------------------------------------------
// ------------------------------------------------
type Track struct {
downTrack *DownTrack
@@ -1116,7 +1115,7 @@ func (t *Track) DistanceToDesired() int32 {
return t.downTrack.DistanceToDesired()
}
//------------------------------------------------
// ------------------------------------------------
type TrackSorter []*Track
@@ -1136,7 +1135,7 @@ func (t TrackSorter) Less(i, j int) bool {
return t[i].maxLayers.temporal > t[j].maxLayers.temporal
}
//------------------------------------------------
// ------------------------------------------------
type MaxDistanceSorter []*Track
@@ -1152,7 +1151,7 @@ func (m MaxDistanceSorter) Less(i, j int) bool {
return m[i].DistanceToDesired() > m[j].DistanceToDesired()
}
//------------------------------------------------
// ------------------------------------------------
type MinDistanceSorter []*Track
@@ -1168,4 +1167,4 @@ func (m MinDistanceSorter) Less(i, j int) bool {
return m[i].DistanceToDesired() < m[j].DistanceToDesired()
}
//------------------------------------------------
// ------------------------------------------------
+3 -3
View File
@@ -4,9 +4,9 @@ import (
"testing"
"time"
"github.com/livekit/livekit-server/pkg/testutils"
"github.com/stretchr/testify/require"
"github.com/livekit/livekit-server/pkg/testutils"
)
func TestStreamTracker(t *testing.T) {
@@ -44,7 +44,7 @@ func TestStreamTracker(t *testing.T) {
})
require.Equal(t, StreamStatusActive, tracker.Status())
// run a single interation
// run a single iteration
tracker.detectChanges()
require.Equal(t, StreamStatusStopped, tracker.Status())
require.True(t, callbackCalled.get())
+7 -7
View File
@@ -1,13 +1,13 @@
package testutils
import (
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/pion/rtp"
"github.com/pion/webrtc/v3"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
)
//-----------------------------------------------------------
// -----------------------------------------------------------
type TestExtPacketParams struct {
SetMarker bool
@@ -23,7 +23,7 @@ type TestExtPacketParams struct {
ArrivalTime int64
}
//-----------------------------------------------------------
// -----------------------------------------------------------
func GetTestExtPacket(params *TestExtPacketParams) (*buffer.ExtPacket, error) {
packet := rtp.Packet{
@@ -56,7 +56,7 @@ func GetTestExtPacket(params *TestExtPacketParams) (*buffer.ExtPacket, error) {
return ep, nil
}
//--------------------------------------
// --------------------------------------
func GetTestExtPacketVP8(params *TestExtPacketParams, vp8 *buffer.VP8) (*buffer.ExtPacket, error) {
ep, err := GetTestExtPacket(params)
@@ -69,7 +69,7 @@ func GetTestExtPacketVP8(params *TestExtPacketParams, vp8 *buffer.VP8) (*buffer.
return ep, nil
}
//--------------------------------------
// --------------------------------------
var TestVP8Codec = webrtc.RTPCodecCapability{
MimeType: "video/vp8",
@@ -81,4 +81,4 @@ var TestOpusCodec = webrtc.RTPCodecCapability{
ClockRate: 48000,
}
//--------------------------------------
// --------------------------------------
+2 -2
View File
@@ -185,7 +185,7 @@ func (v *VP8Munger) UpdateAndGet(extPkt *buffer.ExtPacket, ordering SequenceNumb
}
// in-order incoming sequence number, may or may not be contiguous.
// In the case of loss (i. e. incoming sequence number is not contiguous),
// In the case of loss (i.e. incoming sequence number is not contiguous),
// forward even if it is a filtered layer. With temporal scalability,
// it is unclear if the current packet should be dropped if it is not
// contiguous. Hence forward anything that is not contiguous.
@@ -286,7 +286,7 @@ func (v *VP8Munger) PictureIdOffset(extPictureId int32) (int32, bool) {
return value.(int32), ok
}
//-----------------------------
// -----------------------------
//
// VP8PictureIdWrapHandler
+2 -2
View File
@@ -4,10 +4,10 @@ import (
"reflect"
"testing"
"github.com/stretchr/testify/require"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/livekit-server/pkg/sfu/testutils"
"github.com/stretchr/testify/require"
)
func compare(expected *VP8Munger, actual *VP8Munger) bool {