update core to 0.0.5 (#1540)

* update core

* sort imports

* fix typos

* redundant types
This commit is contained in:
David Colburn
2023-03-22 16:53:23 -07:00
committed by GitHub
parent 0ea88e4025
commit 191a9e8014
41 changed files with 272 additions and 263 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ require (
github.com/dustin/go-humanize v1.0.1 github.com/dustin/go-humanize v1.0.1
github.com/elliotchance/orderedmap/v2 v2.2.0 github.com/elliotchance/orderedmap/v2 v2.2.0
github.com/florianl/go-tc v0.4.2 github.com/florianl/go-tc v0.4.2
github.com/frostbyte73/core v0.0.4 github.com/frostbyte73/core v0.0.5
github.com/gammazero/deque v0.1.0 github.com/gammazero/deque v0.1.0
github.com/gammazero/workerpool v1.1.2 github.com/gammazero/workerpool v1.1.2
github.com/google/wire v0.5.0 github.com/google/wire v0.5.0
+2 -2
View File
@@ -87,8 +87,8 @@ github.com/florianl/go-tc v0.4.2 h1:jan5zcOWCLhA9SRBHZhQ0SSAq7cmDUagiRPngAi5AOQ=
github.com/florianl/go-tc v0.4.2/go.mod h1:2W1jSMFryiYlpQigr4ZpSSpE9XNze+bW7cTsCXWbMwo= github.com/florianl/go-tc v0.4.2/go.mod h1:2W1jSMFryiYlpQigr4ZpSSpE9XNze+bW7cTsCXWbMwo=
github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k= github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k=
github.com/frankban/quicktest v1.14.0/go.mod h1:NeW+ay9A/U67EYXNFA1nPE8e/tnQv/09mUdL/ijj8og= github.com/frankban/quicktest v1.14.0/go.mod h1:NeW+ay9A/U67EYXNFA1nPE8e/tnQv/09mUdL/ijj8og=
github.com/frostbyte73/core v0.0.4 h1:CwwoYfKPdNSO/QbOOMWMRSYoNW14ov4XHnt094AuMX8= github.com/frostbyte73/core v0.0.5 h1:+oHjXDyQyQzEx04mtmmafYP07n7EToKpUGafWbNVQ9I=
github.com/frostbyte73/core v0.0.4/go.mod h1:mqHHSVFS5DE6kSdhU1/s9Mm0YCnLB8Ou2DD/eX1Zbr4= github.com/frostbyte73/core v0.0.5/go.mod h1:mqHHSVFS5DE6kSdhU1/s9Mm0YCnLB8Ou2DD/eX1Zbr4=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/gammazero/deque v0.1.0 h1:f9LnNmq66VDeuAlSAapemq/U7hJ2jpIWa4c09q8Dlik= github.com/gammazero/deque v0.1.0 h1:f9LnNmq66VDeuAlSAapemq/U7hJ2jpIWa4c09q8Dlik=
+13 -13
View File
@@ -314,30 +314,30 @@ func NewConfig(confString string, strictMode bool, c *cli.Context, baseFlags []c
2: 1 * time.Second, 2: 1 * time.Second,
}, },
PacketTracker: map[int32]StreamTrackerPacketConfig{ PacketTracker: map[int32]StreamTrackerPacketConfig{
0: StreamTrackerPacketConfig{ 0: {
SamplesRequired: 1, SamplesRequired: 1,
CyclesRequired: 4, CyclesRequired: 4,
CycleDuration: 500 * time.Millisecond, CycleDuration: 500 * time.Millisecond,
}, },
1: StreamTrackerPacketConfig{ 1: {
SamplesRequired: 5, SamplesRequired: 5,
CyclesRequired: 20, CyclesRequired: 20,
CycleDuration: 500 * time.Millisecond, CycleDuration: 500 * time.Millisecond,
}, },
2: StreamTrackerPacketConfig{ 2: {
SamplesRequired: 5, SamplesRequired: 5,
CyclesRequired: 20, CyclesRequired: 20,
CycleDuration: 500 * time.Millisecond, CycleDuration: 500 * time.Millisecond,
}, },
}, },
FrameTracker: map[int32]StreamTrackerFrameConfig{ FrameTracker: map[int32]StreamTrackerFrameConfig{
0: StreamTrackerFrameConfig{ 0: {
MinFPS: 5.0, MinFPS: 5.0,
}, },
1: StreamTrackerFrameConfig{ 1: {
MinFPS: 5.0, MinFPS: 5.0,
}, },
2: StreamTrackerFrameConfig{ 2: {
MinFPS: 5.0, MinFPS: 5.0,
}, },
}, },
@@ -350,30 +350,30 @@ func NewConfig(confString string, strictMode bool, c *cli.Context, baseFlags []c
2: 4 * time.Second, 2: 4 * time.Second,
}, },
PacketTracker: map[int32]StreamTrackerPacketConfig{ PacketTracker: map[int32]StreamTrackerPacketConfig{
0: StreamTrackerPacketConfig{ 0: {
SamplesRequired: 1, SamplesRequired: 1,
CyclesRequired: 1, CyclesRequired: 1,
CycleDuration: 2 * time.Second, CycleDuration: 2 * time.Second,
}, },
1: StreamTrackerPacketConfig{ 1: {
SamplesRequired: 1, SamplesRequired: 1,
CyclesRequired: 1, CyclesRequired: 1,
CycleDuration: 2 * time.Second, CycleDuration: 2 * time.Second,
}, },
2: StreamTrackerPacketConfig{ 2: {
SamplesRequired: 1, SamplesRequired: 1,
CyclesRequired: 1, CyclesRequired: 1,
CycleDuration: 2 * time.Second, CycleDuration: 2 * time.Second,
}, },
}, },
FrameTracker: map[int32]StreamTrackerFrameConfig{ FrameTracker: map[int32]StreamTrackerFrameConfig{
0: StreamTrackerFrameConfig{ 0: {
MinFPS: 0.5, MinFPS: 0.5,
}, },
1: StreamTrackerFrameConfig{ 1: {
MinFPS: 0.5, MinFPS: 0.5,
}, },
2: StreamTrackerFrameConfig{ 2: {
MinFPS: 0.5, MinFPS: 0.5,
}, },
}, },
@@ -576,7 +576,7 @@ func (conf *Config) ValidateKeys() error {
func GenerateCLIFlags(existingFlags []cli.Flag, hidden bool) ([]cli.Flag, error) { func GenerateCLIFlags(existingFlags []cli.Flag, hidden bool) ([]cli.Flag, error) {
blankConfig := &Config{} blankConfig := &Config{}
flags := []cli.Flag{} flags := make([]cli.Flag, 0)
for name, value := range blankConfig.ToCLIFlagNames(existingFlags) { for name, value := range blankConfig.ToCLIFlagNames(existingFlags) {
kind := value.Kind() kind := value.Kind()
if kind == reflect.Ptr { if kind == reflect.Ptr {
+2 -1
View File
@@ -3,8 +3,9 @@ package routing
import ( import (
"testing" "testing"
"github.com/livekit/protocol/livekit"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/livekit/protocol/livekit"
) )
func TestUtils_ParticipantKey(t *testing.T) { func TestUtils_ParticipantKey(t *testing.T) {
+3 -3
View File
@@ -340,7 +340,7 @@ func getNAT1to1IPsForConf(conf *config.Config, ipFilter func(net.IP) bool) ([]st
}(ip) }(ip)
} }
var firstResloved bool var firstResolved bool
natMapping := make(map[string]string) natMapping := make(map[string]string)
timeout := time.NewTimer(5 * time.Second) timeout := time.NewTimer(5 * time.Second)
defer timeout.Stop() defer timeout.Stop()
@@ -349,8 +349,8 @@ done:
for { for {
select { select {
case mapping := <-addrCh: case mapping := <-addrCh:
if !firstResloved { if !firstResolved {
firstResloved = true firstResolved = true
timeout.Reset(1 * time.Second) timeout.Reset(1 * time.Second)
} }
if local, ok := natMapping[mapping.externalIP]; ok { if local, ok := natMapping[mapping.externalIP]; ok {
+1 -1
View File
@@ -88,7 +88,7 @@ func (d *DynacastManager) Close() {
} }
} }
// THere are situations like track unmute or streaming from a sifferent node // THere are situations like track unmute or streaming from a different node
// where subscribed quality needs to sent to the provider immediately. // where subscribed quality needs to sent to the provider immediately.
// This bypasses any debouncing and forces a subscribed quality update // This bypasses any debouncing and forces a subscribed quality update
// with immediate effect. // with immediate effect.
+3 -2
View File
@@ -6,10 +6,11 @@ import (
"testing" "testing"
"time" "time"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/protocol/livekit"
"github.com/pion/webrtc/v3" "github.com/pion/webrtc/v3"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/protocol/livekit"
) )
func TestSubscribedMaxQuality(t *testing.T) { func TestSubscribedMaxQuality(t *testing.T) {
+1 -1
View File
@@ -54,7 +54,7 @@ func (m mediaTrackReceiverState) String() string {
} }
} }
//----------------------------------------------------- // -----------------------------------------------------
type simulcastReceiver struct { type simulcastReceiver struct {
sfu.TrackReceiver sfu.TrackReceiver
+4 -4
View File
@@ -687,7 +687,7 @@ func (p *ParticipantImpl) IsClosed() bool {
return p.isClosed.Load() return p.isClosed.Load()
} }
// Negotiate subscriber SDP with client, if force is true, will cencel pending // Negotiate subscriber SDP with client, if force is true, will cancel pending
// negotiate task and negotiate immediately // negotiate task and negotiate immediately
func (p *ParticipantImpl) Negotiate(force bool) { func (p *ParticipantImpl) Negotiate(force bool) {
if p.MigrateState() != types.MigrateStateInit { if p.MigrateState() != types.MigrateStateInit {
@@ -1363,7 +1363,7 @@ func (p *ParticipantImpl) onStreamStateChange(update *sfu.StreamStateUpdate) err
}) })
} }
func (p *ParticipantImpl) onSubscribedMaxQualityChange(trackID livekit.TrackID, subscribedQualities []*livekit.SubscribedCodec, maxSubscribedQualites []types.SubscribedCodecQuality) error { func (p *ParticipantImpl) onSubscribedMaxQualityChange(trackID livekit.TrackID, subscribedQualities []*livekit.SubscribedCodec, maxSubscribedQualities []types.SubscribedCodecQuality) error {
if p.params.DisableDynacast { if p.params.DisableDynacast {
return nil return nil
} }
@@ -1394,7 +1394,7 @@ func (p *ParticipantImpl) onSubscribedMaxQualityChange(trackID livekit.TrackID,
} }
} }
for _, maxSubscribedQuality := range maxSubscribedQualites { for _, maxSubscribedQuality := range maxSubscribedQualities {
ti := &livekit.TrackInfo{ ti := &livekit.TrackInfo{
Sid: string(trackID), Sid: string(trackID),
Type: livekit.TrackType_VIDEO, Type: livekit.TrackType_VIDEO,
@@ -1417,7 +1417,7 @@ func (p *ParticipantImpl) onSubscribedMaxQualityChange(trackID livekit.TrackID,
"sending max subscribed quality", "sending max subscribed quality",
"trackID", trackID, "trackID", trackID,
"qualities", subscribedQualities, "qualities", subscribedQualities,
"max", maxSubscribedQualites, "max", maxSubscribedQualities,
) )
return p.writeMessage(&livekit.SignalResponse{ return p.writeMessage(&livekit.SignalResponse{
Message: &livekit.SignalResponse_SubscribedQualityUpdate{ Message: &livekit.SignalResponse_SubscribedQualityUpdate{
+1 -1
View File
@@ -361,7 +361,7 @@ func TestSetStableTrackID(t *testing.T) {
} }
func TestDisableCodecs(t *testing.T) { func TestDisableCodecs(t *testing.T) {
participant := newParticipantForTestWithOpts(livekit.ParticipantIdentity("123"), &participantOpts{ participant := newParticipantForTestWithOpts("123", &participantOpts{
publisher: false, publisher: false,
clientConf: &livekit.ClientConfiguration{ clientConf: &livekit.ClientConfiguration{
DisabledCodecs: &livekit.DisabledCodecs{ DisabledCodecs: &livekit.DisabledCodecs{
+6 -6
View File
@@ -1162,11 +1162,11 @@ func BroadcastDataPacketForRoom(r types.Room, source types.LocalParticipant, dp
var dpData []byte var dpData []byte
participants := r.GetLocalParticipants() participants := r.GetLocalParticipants()
cap := len(dest) capacity := len(dest)
if cap == 0 { if capacity == 0 {
cap = len(participants) capacity = len(participants)
} }
destParticpants := make([]types.LocalParticipant, 0, cap) destParticipants := make([]types.LocalParticipant, 0, capacity)
for _, op := range participants { for _, op := range participants {
if op.State() != livekit.ParticipantInfo_ACTIVE { if op.State() != livekit.ParticipantInfo_ACTIVE {
@@ -1195,10 +1195,10 @@ func BroadcastDataPacketForRoom(r types.Room, source types.LocalParticipant, dp
return return
} }
} }
destParticpants = append(destParticpants, op) destParticipants = append(destParticipants, op)
} }
utils.ParallelExec(destParticpants, dataForwardLoadBalanceThreshold, 1, func(op types.LocalParticipant) { utils.ParallelExec(destParticipants, dataForwardLoadBalanceThreshold, 1, func(op types.LocalParticipant) {
err := op.SendDataPacket(dp, dpData) err := op.SendDataPacket(dp, dpData)
if err != nil && !errors.Is(err, io.ErrClosedPipe) { if err != nil && !errors.Is(err, io.ErrClosedPipe) {
op.GetLogger().Infow("send data packet error", "error", err) op.GetLogger().Infow("send data packet error", "error", err)
+4 -4
View File
@@ -1263,7 +1263,7 @@ func (t *PCTransport) initPCWithPreviousAnswer(previousAnswer webrtc.SessionDesc
} }
tr.SetMid(mid) tr.SetMid(mid)
// save mid -> senders for migration resue // save mid -> senders for migration reuse
sender := tr.Sender() sender := tr.Sender()
senders[mid] = sender senders[mid] = sender
@@ -1294,7 +1294,7 @@ func (t *PCTransport) SetPreviousSdp(offer, answer *webrtc.SessionDescription) {
} }
return return
} else if offer != nil { } else if offer != nil {
// in migration case, can't reuse tranceiver before negotiated except track subscribed at previous node // in migration case, can't reuse transceiver before negotiated except track subscribed at previous node
t.canReuseTransceiver = false t.canReuseTransceiver = false
if err := t.parseTrackMid(*offer, senders); err != nil { if err := t.parseTrackMid(*offer, senders); err != nil {
t.params.Logger.Errorw("parse previous offer failed", err, "offer", offer.SDP) t.params.Logger.Errorw("parse previous offer failed", err, "offer", offer.SDP)
@@ -1318,12 +1318,12 @@ func (t *PCTransport) parseTrackMid(offer webrtc.SessionDescription, senders map
} }
if split := strings.Split(msid, " "); len(split) == 2 { if split := strings.Split(msid, " "); len(split) == 2 {
trackid := split[1] trackID := split[1]
mid := lksdp.GetMidValue(m) mid := lksdp.GetMidValue(m)
if mid == "" { if mid == "" {
return ErrMidNotFound return ErrMidNotFound
} }
t.previousTrackDescription[trackid] = &trackDescription{ t.previousTrackDescription[trackID] = &trackDescription{
mid: mid, mid: mid,
sender: senders[mid], sender: senders[mid],
} }
+1 -1
View File
@@ -246,7 +246,7 @@ func TestFirstAnswerMissedDuringICERestart(t *testing.T) {
// exchange ICE // exchange ICE
handleICEExchange(t, transportA, transportB) handleICEExchange(t, transportA, transportB)
// first anwser missed // first answer missed
var firstAnswerReceived atomic.Bool var firstAnswerReceived atomic.Bool
transportB.OnAnswer(func(sd webrtc.SessionDescription) error { transportB.OnAnswer(func(sd webrtc.SessionDescription) error {
if firstAnswerReceived.Load() { if firstAnswerReceived.Load() {
+2 -2
View File
@@ -363,7 +363,7 @@ func (t *TransportManager) GetUnmatchMediaForOffer(offer webrtc.SessionDescripti
answer := lastAnswer.(webrtc.SessionDescription) answer := lastAnswer.(webrtc.SessionDescription)
parsedAnswer, err1 := answer.Unmarshal() parsedAnswer, err1 := answer.Unmarshal()
if err1 != nil { if err1 != nil {
// should not happend // should not happen
t.params.Logger.Errorw("failed to parse last answer", err) t.params.Logger.Errorw("failed to parse last answer", err)
return return
} }
@@ -572,7 +572,7 @@ func (t *TransportManager) handleConnectionFailed(isShortLived bool) {
} }
// //
// Checking only `PreferenceSubcriber` field although any connection failure (PUBLISHER OR SUBSCRIBER) will // Checking only `PreferenceSubscriber` field although any connection failure (PUBLISHER OR SUBSCRIBER) will
// flow through here. // flow through here.
// //
// As both transports are switched to the same type on any failure, checking just subscriber should be fine. // As both transports are switched to the same type on any failure, checking just subscriber should be fine.
+1 -1
View File
@@ -118,7 +118,7 @@ func (s *IOInfoService) loadIngressFromInfoRequest(req *rpc.GetIngressInfoReques
} else if req.StreamKey != "" { } else if req.StreamKey != "" {
info, err = s.is.LoadIngressFromStreamKey(context.Background(), req.StreamKey) info, err = s.is.LoadIngressFromStreamKey(context.Background(), req.StreamKey)
} else { } else {
err = errors.New("request needs to specity either IngressId or StreamKey") err = errors.New("request needs to specify either IngressId or StreamKey")
} }
return info, err return info, err
} }
-1
View File
@@ -30,7 +30,6 @@ const (
EgressKey = "egress" EgressKey = "egress"
EndedEgressKey = "ended_egress" EndedEgressKey = "ended_egress"
RoomEgressPrefix = "egress:room:" RoomEgressPrefix = "egress:room:"
DeprecatedRoomEgressPrefix = "room_egress:"
// IngressKey is a hash of ingressID => ingress info // IngressKey is a hash of ingressID => ingress info
IngressKey = "ingress" IngressKey = "ingress"
+5 -5
View File
@@ -92,7 +92,7 @@ type Buffer struct {
// logger // logger
logger logger.Logger logger logger.Logger
// depencency descriptor // dependency descriptor
ddExt uint8 ddExt uint8
ddParser *DependencyDescriptorParser ddParser *DependencyDescriptorParser
maxLayerChangedCB func(int32, int32) maxLayerChangedCB func(int32, int32)
@@ -436,15 +436,15 @@ func (b *Buffer) patchExtPacket(ep *ExtPacket, buf []byte) *ExtPacket {
ep.RawPacket = buf[:n] ep.RawPacket = buf[:n]
// patch RTP packet to point payload to new buffer // patch RTP packet to point payload to new buffer
rtp := *ep.Packet pkt := *ep.Packet
payloadStart := ep.Packet.Header.MarshalSize() payloadStart := ep.Packet.Header.MarshalSize()
payloadEnd := payloadStart + len(ep.Packet.Payload) payloadEnd := payloadStart + len(ep.Packet.Payload)
if payloadEnd > n { if payloadEnd > n {
b.logger.Warnw("unexpected marshal size", nil, "max", n, "need", payloadEnd) b.logger.Warnw("unexpected marshal size", nil, "max", n, "need", payloadEnd)
return nil return nil
} }
rtp.Payload = buf[payloadStart:payloadEnd] pkt.Payload = buf[payloadStart:payloadEnd]
ep.Packet = &rtp ep.Packet = &pkt
return ep return ep
} }
@@ -755,7 +755,7 @@ func (b *Buffer) GetAudioLevel() (float64, bool) {
} }
// TODO : now we rely on stream tracker for layer change, dependency still // TODO : now we rely on stream tracker for layer change, dependency still
// work for that too. Do we keep it unchange or use both methods? // work for that too. Do we keep it unchanged or use both methods?
func (b *Buffer) OnMaxLayerChanged(fn func(int32, int32)) { func (b *Buffer) OnMaxLayerChanged(fn func(int32, int32)) {
b.maxLayerChangedCB = fn b.maxLayerChangedCB = fn
} }
+2 -1
View File
@@ -6,11 +6,12 @@ import (
"testing" "testing"
"time" "time"
"github.com/livekit/mediatransportutil/pkg/nack"
"github.com/pion/rtcp" "github.com/pion/rtcp"
"github.com/pion/rtp" "github.com/pion/rtp"
"github.com/pion/webrtc/v3" "github.com/pion/webrtc/v3"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/livekit/mediatransportutil/pkg/nack"
) )
var vp8Codec = webrtc.RTPCodecParameters{ var vp8Codec = webrtc.RTPCodecParameters{
+2 -1
View File
@@ -4,9 +4,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/livekit/protocol/livekit"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"github.com/livekit/protocol/livekit"
) )
func TestDataStats(t *testing.T) { func TestDataStats(t *testing.T) {
+1 -1
View File
@@ -115,7 +115,7 @@ func (f *FrameRateCalculatorVP8) RecvPacket(ep *ExtPacket) bool {
func (f *FrameRateCalculatorVP8) calc() bool { func (f *FrameRateCalculatorVP8) calc() bool {
var rateCounter int var rateCounter int
for currentTemporal := int32(0); currentTemporal <= int32(DefaultMaxLayerTemporal); currentTemporal++ { for currentTemporal := int32(0); currentTemporal <= DefaultMaxLayerTemporal; currentTemporal++ {
if f.frameRates[currentTemporal] > 0 { if f.frameRates[currentTemporal] > 0 {
rateCounter++ rateCounter++
continue continue
+2 -2
View File
@@ -147,7 +147,7 @@ func TestFpsVP8(t *testing.T) {
testCase := c testCase := c
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
fps := testCase.fps fps := testCase.fps
frames := [][]*testFrameInfo{} frames := make([][]*testFrameInfo, 0)
vp8calcs := make([]*FrameRateCalculatorVP8, len(fps)) vp8calcs := make([]*FrameRateCalculatorVP8, len(fps))
for i := range vp8calcs { for i := range vp8calcs {
vp8calcs[i] = NewFrameRateCalculatorVP8(90000, logger.GetLogger()) vp8calcs[i] = NewFrameRateCalculatorVP8(90000, logger.GetLogger())
@@ -178,7 +178,7 @@ func TestFpsVP8(t *testing.T) {
} }
t.Run("packet lost and duplicate", func(t *testing.T) { t.Run("packet lost and duplicate", func(t *testing.T) {
fps := [][]float32{{7.5, 15}, {7.5, 15}, {15, 30}} fps := [][]float32{{7.5, 15}, {7.5, 15}, {15, 30}}
frames := [][]*testFrameInfo{} frames := make([][]*testFrameInfo, 0)
vp8calcs := make([]*FrameRateCalculatorVP8, len(fps)) vp8calcs := make([]*FrameRateCalculatorVP8, len(fps))
for i := range vp8calcs { for i := range vp8calcs {
vp8calcs[i] = NewFrameRateCalculatorVP8(90000, logger.GetLogger()) vp8calcs[i] = NewFrameRateCalculatorVP8(90000, logger.GetLogger())
+2 -2
View File
@@ -801,7 +801,7 @@ func (r *RTPStats) SnapshotRtcpReceptionReport(ssrc uint32, proxyFracLost uint8,
packetsLost := uint32(0) packetsLost := uint32(0)
if r.params.IsReceiverReportDriven { if r.params.IsReceiverReportDriven {
// receiver report drvien should not be set for streams that need to generate reception report, but including code here for consistency // receiver report driven should not be set for streams that need to generate reception report, but including code here for consistency
packetsLost = now.packetsLostOverridden - then.packetsLostOverridden packetsLost = now.packetsLostOverridden - then.packetsLostOverridden
if int32(packetsLost) < 0 { if int32(packetsLost) < 0 {
packetsLost = 0 packetsLost = 0
@@ -825,7 +825,7 @@ func (r *RTPStats) SnapshotRtcpReceptionReport(ssrc uint32, proxyFracLost uint8,
jitter := r.jitter jitter := r.jitter
if r.params.IsReceiverReportDriven { if r.params.IsReceiverReportDriven {
// receiver report drvien should not be set for streams that need to generate reception report, but including code here for consistency // receiver report driven should not be set for streams that need to generate reception report, but including code here for consistency
jitter = r.jitterOverridden jitter = r.jitterOverridden
} }
+2 -2
View File
@@ -84,7 +84,7 @@ func RidToSpatialLayer(rid string, trackInfo *livekit.TrackInfo) int32 {
logger.Warnw("unexpected rid f with only two qualities, low and high", nil) logger.Warnw("unexpected rid f with only two qualities, low and high", nil)
return 1 return 1
case lp[livekit.VideoQuality_MEDIUM] && lp[livekit.VideoQuality_HIGH]: case lp[livekit.VideoQuality_MEDIUM] && lp[livekit.VideoQuality_HIGH]:
logger.Warnw("unexpected rid f with only two qualities, medum and high", nil) logger.Warnw("unexpected rid f with only two qualities, medium and high", nil)
return 1 return 1
default: default:
@@ -156,7 +156,7 @@ func SpatialLayerToRid(layer int32, trackInfo *livekit.TrackInfo) string {
logger.Warnw("unexpected layer 2 with only two qualities, low and high", nil) logger.Warnw("unexpected layer 2 with only two qualities, low and high", nil)
return HalfResolution return HalfResolution
case lp[livekit.VideoQuality_MEDIUM] && lp[livekit.VideoQuality_HIGH]: case lp[livekit.VideoQuality_MEDIUM] && lp[livekit.VideoQuality_HIGH]:
logger.Warnw("unexpected layer 2 with only two qualities, medum and high", nil) logger.Warnw("unexpected layer 2 with only two qualities, medium and high", nil)
return HalfResolution return HalfResolution
default: default:
+101 -100
View File
@@ -3,8 +3,9 @@ package buffer
import ( import (
"testing" "testing"
"github.com/livekit/protocol/livekit"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/livekit/protocol/livekit"
) )
func TestRidConversion(t *testing.T) { func TestRidConversion(t *testing.T) {
@@ -21,123 +22,123 @@ func TestRidConversion(t *testing.T) {
"no track info", "no track info",
nil, nil,
map[string]RidAndLayer{ map[string]RidAndLayer{
"": RidAndLayer{rid: QuarterResolution, layer: 0}, "": {rid: QuarterResolution, layer: 0},
QuarterResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, QuarterResolution: {rid: QuarterResolution, layer: 0},
HalfResolution: RidAndLayer{rid: HalfResolution, layer: 1}, HalfResolution: {rid: HalfResolution, layer: 1},
FullResolution: RidAndLayer{rid: FullResolution, layer: 2}, FullResolution: {rid: FullResolution, layer: 2},
}, },
}, },
{ {
"no layers", "no layers",
&livekit.TrackInfo{}, &livekit.TrackInfo{},
map[string]RidAndLayer{ map[string]RidAndLayer{
"": RidAndLayer{rid: QuarterResolution, layer: 0}, "": {rid: QuarterResolution, layer: 0},
QuarterResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, QuarterResolution: {rid: QuarterResolution, layer: 0},
HalfResolution: RidAndLayer{rid: HalfResolution, layer: 1}, HalfResolution: {rid: HalfResolution, layer: 1},
FullResolution: RidAndLayer{rid: FullResolution, layer: 2}, FullResolution: {rid: FullResolution, layer: 2},
}, },
}, },
{ {
"single layer, low", "single layer, low",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
}, },
}, },
map[string]RidAndLayer{ map[string]RidAndLayer{
"": RidAndLayer{rid: QuarterResolution, layer: 0}, "": {rid: QuarterResolution, layer: 0},
QuarterResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, QuarterResolution: {rid: QuarterResolution, layer: 0},
HalfResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, HalfResolution: {rid: QuarterResolution, layer: 0},
FullResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, FullResolution: {rid: QuarterResolution, layer: 0},
}, },
}, },
{ {
"single layer, medium", "single layer, medium",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
}, },
}, },
map[string]RidAndLayer{ map[string]RidAndLayer{
"": RidAndLayer{rid: QuarterResolution, layer: 0}, "": {rid: QuarterResolution, layer: 0},
QuarterResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, QuarterResolution: {rid: QuarterResolution, layer: 0},
HalfResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, HalfResolution: {rid: QuarterResolution, layer: 0},
FullResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, FullResolution: {rid: QuarterResolution, layer: 0},
}, },
}, },
{ {
"single layer, high", "single layer, high",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[string]RidAndLayer{ map[string]RidAndLayer{
"": RidAndLayer{rid: QuarterResolution, layer: 0}, "": {rid: QuarterResolution, layer: 0},
QuarterResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, QuarterResolution: {rid: QuarterResolution, layer: 0},
HalfResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, HalfResolution: {rid: QuarterResolution, layer: 0},
FullResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, FullResolution: {rid: QuarterResolution, layer: 0},
}, },
}, },
{ {
"two layers, low and medium", "two layers, low and medium",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
}, },
}, },
map[string]RidAndLayer{ map[string]RidAndLayer{
"": RidAndLayer{rid: QuarterResolution, layer: 0}, "": {rid: QuarterResolution, layer: 0},
QuarterResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, QuarterResolution: {rid: QuarterResolution, layer: 0},
HalfResolution: RidAndLayer{rid: HalfResolution, layer: 1}, HalfResolution: {rid: HalfResolution, layer: 1},
FullResolution: RidAndLayer{rid: HalfResolution, layer: 1}, FullResolution: {rid: HalfResolution, layer: 1},
}, },
}, },
{ {
"two layers, low and high", "two layers, low and high",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[string]RidAndLayer{ map[string]RidAndLayer{
"": RidAndLayer{rid: QuarterResolution, layer: 0}, "": {rid: QuarterResolution, layer: 0},
QuarterResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, QuarterResolution: {rid: QuarterResolution, layer: 0},
HalfResolution: RidAndLayer{rid: HalfResolution, layer: 1}, HalfResolution: {rid: HalfResolution, layer: 1},
FullResolution: RidAndLayer{rid: HalfResolution, layer: 1}, FullResolution: {rid: HalfResolution, layer: 1},
}, },
}, },
{ {
"two layers, medium and high", "two layers, medium and high",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[string]RidAndLayer{ map[string]RidAndLayer{
"": RidAndLayer{rid: QuarterResolution, layer: 0}, "": {rid: QuarterResolution, layer: 0},
QuarterResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, QuarterResolution: {rid: QuarterResolution, layer: 0},
HalfResolution: RidAndLayer{rid: HalfResolution, layer: 1}, HalfResolution: {rid: HalfResolution, layer: 1},
FullResolution: RidAndLayer{rid: HalfResolution, layer: 1}, FullResolution: {rid: HalfResolution, layer: 1},
}, },
}, },
{ {
"three layers", "three layers",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[string]RidAndLayer{ map[string]RidAndLayer{
"": RidAndLayer{rid: QuarterResolution, layer: 0}, "": {rid: QuarterResolution, layer: 0},
QuarterResolution: RidAndLayer{rid: QuarterResolution, layer: 0}, QuarterResolution: {rid: QuarterResolution, layer: 0},
HalfResolution: RidAndLayer{rid: HalfResolution, layer: 1}, HalfResolution: {rid: HalfResolution, layer: 1},
FullResolution: RidAndLayer{rid: FullResolution, layer: 2}, FullResolution: {rid: FullResolution, layer: 2},
}, },
}, },
} }
@@ -169,114 +170,114 @@ func TestQualityConversion(t *testing.T) {
"no track info", "no track info",
nil, nil,
map[livekit.VideoQuality]QualityAndLayer{ map[livekit.VideoQuality]QualityAndLayer{
livekit.VideoQuality_LOW: QualityAndLayer{quality: livekit.VideoQuality_LOW, layer: 0}, livekit.VideoQuality_LOW: {quality: livekit.VideoQuality_LOW, layer: 0},
livekit.VideoQuality_MEDIUM: QualityAndLayer{quality: livekit.VideoQuality_MEDIUM, layer: 1}, livekit.VideoQuality_MEDIUM: {quality: livekit.VideoQuality_MEDIUM, layer: 1},
livekit.VideoQuality_HIGH: QualityAndLayer{quality: livekit.VideoQuality_HIGH, layer: 2}, livekit.VideoQuality_HIGH: {quality: livekit.VideoQuality_HIGH, layer: 2},
}, },
}, },
{ {
"no layers", "no layers",
&livekit.TrackInfo{}, &livekit.TrackInfo{},
map[livekit.VideoQuality]QualityAndLayer{ map[livekit.VideoQuality]QualityAndLayer{
livekit.VideoQuality_LOW: QualityAndLayer{quality: livekit.VideoQuality_LOW, layer: 0}, livekit.VideoQuality_LOW: {quality: livekit.VideoQuality_LOW, layer: 0},
livekit.VideoQuality_MEDIUM: QualityAndLayer{quality: livekit.VideoQuality_MEDIUM, layer: 1}, livekit.VideoQuality_MEDIUM: {quality: livekit.VideoQuality_MEDIUM, layer: 1},
livekit.VideoQuality_HIGH: QualityAndLayer{quality: livekit.VideoQuality_HIGH, layer: 2}, livekit.VideoQuality_HIGH: {quality: livekit.VideoQuality_HIGH, layer: 2},
}, },
}, },
{ {
"single layer, low", "single layer, low",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
}, },
}, },
map[livekit.VideoQuality]QualityAndLayer{ map[livekit.VideoQuality]QualityAndLayer{
livekit.VideoQuality_LOW: QualityAndLayer{quality: livekit.VideoQuality_LOW, layer: 0}, livekit.VideoQuality_LOW: {quality: livekit.VideoQuality_LOW, layer: 0},
livekit.VideoQuality_MEDIUM: QualityAndLayer{quality: livekit.VideoQuality_LOW, layer: 0}, livekit.VideoQuality_MEDIUM: {quality: livekit.VideoQuality_LOW, layer: 0},
livekit.VideoQuality_HIGH: QualityAndLayer{quality: livekit.VideoQuality_LOW, layer: 0}, livekit.VideoQuality_HIGH: {quality: livekit.VideoQuality_LOW, layer: 0},
}, },
}, },
{ {
"single layer, medium", "single layer, medium",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
}, },
}, },
map[livekit.VideoQuality]QualityAndLayer{ map[livekit.VideoQuality]QualityAndLayer{
livekit.VideoQuality_LOW: QualityAndLayer{quality: livekit.VideoQuality_MEDIUM, layer: 0}, livekit.VideoQuality_LOW: {quality: livekit.VideoQuality_MEDIUM, layer: 0},
livekit.VideoQuality_MEDIUM: QualityAndLayer{quality: livekit.VideoQuality_MEDIUM, layer: 0}, livekit.VideoQuality_MEDIUM: {quality: livekit.VideoQuality_MEDIUM, layer: 0},
livekit.VideoQuality_HIGH: QualityAndLayer{quality: livekit.VideoQuality_MEDIUM, layer: 0}, livekit.VideoQuality_HIGH: {quality: livekit.VideoQuality_MEDIUM, layer: 0},
}, },
}, },
{ {
"single layer, high", "single layer, high",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[livekit.VideoQuality]QualityAndLayer{ map[livekit.VideoQuality]QualityAndLayer{
livekit.VideoQuality_LOW: QualityAndLayer{quality: livekit.VideoQuality_HIGH, layer: 0}, livekit.VideoQuality_LOW: {quality: livekit.VideoQuality_HIGH, layer: 0},
livekit.VideoQuality_MEDIUM: QualityAndLayer{quality: livekit.VideoQuality_HIGH, layer: 0}, livekit.VideoQuality_MEDIUM: {quality: livekit.VideoQuality_HIGH, layer: 0},
livekit.VideoQuality_HIGH: QualityAndLayer{quality: livekit.VideoQuality_HIGH, layer: 0}, livekit.VideoQuality_HIGH: {quality: livekit.VideoQuality_HIGH, layer: 0},
}, },
}, },
{ {
"two layers, low and medium", "two layers, low and medium",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
}, },
}, },
map[livekit.VideoQuality]QualityAndLayer{ map[livekit.VideoQuality]QualityAndLayer{
livekit.VideoQuality_LOW: QualityAndLayer{quality: livekit.VideoQuality_LOW, layer: 0}, livekit.VideoQuality_LOW: {quality: livekit.VideoQuality_LOW, layer: 0},
livekit.VideoQuality_MEDIUM: QualityAndLayer{quality: livekit.VideoQuality_MEDIUM, layer: 1}, livekit.VideoQuality_MEDIUM: {quality: livekit.VideoQuality_MEDIUM, layer: 1},
livekit.VideoQuality_HIGH: QualityAndLayer{quality: livekit.VideoQuality_MEDIUM, layer: 1}, livekit.VideoQuality_HIGH: {quality: livekit.VideoQuality_MEDIUM, layer: 1},
}, },
}, },
{ {
"two layers, low and high", "two layers, low and high",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[livekit.VideoQuality]QualityAndLayer{ map[livekit.VideoQuality]QualityAndLayer{
livekit.VideoQuality_LOW: QualityAndLayer{quality: livekit.VideoQuality_LOW, layer: 0}, livekit.VideoQuality_LOW: {quality: livekit.VideoQuality_LOW, layer: 0},
livekit.VideoQuality_MEDIUM: QualityAndLayer{quality: livekit.VideoQuality_HIGH, layer: 1}, livekit.VideoQuality_MEDIUM: {quality: livekit.VideoQuality_HIGH, layer: 1},
livekit.VideoQuality_HIGH: QualityAndLayer{quality: livekit.VideoQuality_HIGH, layer: 1}, livekit.VideoQuality_HIGH: {quality: livekit.VideoQuality_HIGH, layer: 1},
}, },
}, },
{ {
"two layers, medium and high", "two layers, medium and high",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[livekit.VideoQuality]QualityAndLayer{ map[livekit.VideoQuality]QualityAndLayer{
livekit.VideoQuality_LOW: QualityAndLayer{quality: livekit.VideoQuality_MEDIUM, layer: 0}, livekit.VideoQuality_LOW: {quality: livekit.VideoQuality_MEDIUM, layer: 0},
livekit.VideoQuality_MEDIUM: QualityAndLayer{quality: livekit.VideoQuality_MEDIUM, layer: 0}, livekit.VideoQuality_MEDIUM: {quality: livekit.VideoQuality_MEDIUM, layer: 0},
livekit.VideoQuality_HIGH: QualityAndLayer{quality: livekit.VideoQuality_HIGH, layer: 1}, livekit.VideoQuality_HIGH: {quality: livekit.VideoQuality_HIGH, layer: 1},
}, },
}, },
{ {
"three layers", "three layers",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[livekit.VideoQuality]QualityAndLayer{ map[livekit.VideoQuality]QualityAndLayer{
livekit.VideoQuality_LOW: QualityAndLayer{quality: livekit.VideoQuality_LOW, layer: 0}, livekit.VideoQuality_LOW: {quality: livekit.VideoQuality_LOW, layer: 0},
livekit.VideoQuality_MEDIUM: QualityAndLayer{quality: livekit.VideoQuality_MEDIUM, layer: 1}, livekit.VideoQuality_MEDIUM: {quality: livekit.VideoQuality_MEDIUM, layer: 1},
livekit.VideoQuality_HIGH: QualityAndLayer{quality: livekit.VideoQuality_HIGH, layer: 2}, livekit.VideoQuality_HIGH: {quality: livekit.VideoQuality_HIGH, layer: 2},
}, },
}, },
} }
@@ -322,7 +323,7 @@ func TestVideoQualityToRidConversion(t *testing.T) {
"single layer, low", "single layer, low",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
}, },
}, },
map[livekit.VideoQuality]string{ map[livekit.VideoQuality]string{
@@ -335,7 +336,7 @@ func TestVideoQualityToRidConversion(t *testing.T) {
"single layer, medium", "single layer, medium",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
}, },
}, },
map[livekit.VideoQuality]string{ map[livekit.VideoQuality]string{
@@ -348,7 +349,7 @@ func TestVideoQualityToRidConversion(t *testing.T) {
"single layer, high", "single layer, high",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[livekit.VideoQuality]string{ map[livekit.VideoQuality]string{
@@ -361,8 +362,8 @@ func TestVideoQualityToRidConversion(t *testing.T) {
"two layers, low and medium", "two layers, low and medium",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
}, },
}, },
map[livekit.VideoQuality]string{ map[livekit.VideoQuality]string{
@@ -375,8 +376,8 @@ func TestVideoQualityToRidConversion(t *testing.T) {
"two layers, low and high", "two layers, low and high",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[livekit.VideoQuality]string{ map[livekit.VideoQuality]string{
@@ -389,8 +390,8 @@ func TestVideoQualityToRidConversion(t *testing.T) {
"two layers, medium and high", "two layers, medium and high",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[livekit.VideoQuality]string{ map[livekit.VideoQuality]string{
@@ -403,9 +404,9 @@ func TestVideoQualityToRidConversion(t *testing.T) {
"three layers", "three layers",
&livekit.TrackInfo{ &livekit.TrackInfo{
Layers: []*livekit.VideoLayer{ Layers: []*livekit.VideoLayer{
&livekit.VideoLayer{Quality: livekit.VideoQuality_LOW}, {Quality: livekit.VideoQuality_LOW},
&livekit.VideoLayer{Quality: livekit.VideoQuality_MEDIUM}, {Quality: livekit.VideoQuality_MEDIUM},
&livekit.VideoLayer{Quality: livekit.VideoQuality_HIGH}, {Quality: livekit.VideoQuality_HIGH},
}, },
}, },
map[livekit.VideoQuality]string{ map[livekit.VideoQuality]string{
+8 -6
View File
@@ -6,13 +6,12 @@ import (
"time" "time"
"github.com/frostbyte73/core" "github.com/frostbyte73/core"
"github.com/pion/webrtc/v3"
"go.uber.org/atomic" "go.uber.org/atomic"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger" "github.com/livekit/protocol/logger"
"github.com/pion/webrtc/v3"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
) )
const ( const (
@@ -227,13 +226,14 @@ func (cs *ConnectionStats) updateStatsWorker() {
tk := time.NewTicker(interval) tk := time.NewTicker(interval)
defer tk.Stop() defer tk.Stop()
done := cs.done.Watch()
for { for {
select { select {
case <-cs.done.Watch(): case <-done:
return return
case <-tk.C: case <-tk.C:
if cs.done.IsClosed() { if cs.done.IsBroken() {
return return
} }
@@ -247,13 +247,15 @@ func (cs *ConnectionStats) updateStatsWorker() {
// how much weight to give to packet loss rate when calculating score. // how much weight to give to packet loss rate when calculating score.
// It is codec dependent. // It is codec dependent.
// For audio: // For audio:
//
// o Opus without FEC or RED suffers the most through packet loss, hence has the highest weight // o Opus without FEC or RED suffers the most through packet loss, hence has the highest weight
// o RED with two packet redundancy can absorb two out of every three packets lost, so packet loss is not as detrimental and therefore lower weight // o RED with two packet redundancy can absorb two out of every three packets lost, so packet loss is not as detrimental and therefore lower weight
// //
// For video: // For video:
//
// o No in-built codec repair available, hence same for all codecs // o No in-built codec repair available, hence same for all codecs
func getPacketLossWeight(mimeType string, isFecEnabled bool) float64 { func getPacketLossWeight(mimeType string, isFecEnabled bool) float64 {
plw := float64(0.0) var plw float64
switch { switch {
case strings.EqualFold(mimeType, webrtc.MimeTypeOpus): case strings.EqualFold(mimeType, webrtc.MimeTypeOpus):
// 2.5%: fall to GOOD, 7.5%: fall to POOR // 2.5%: fall to GOOD, 7.5%: fall to POOR
@@ -5,10 +5,11 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/livekit/livekit-server/pkg/sfu/buffer" "github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger" "github.com/livekit/protocol/logger"
"github.com/stretchr/testify/require"
) )
func newConnectionStats(mimeType string, isFECEnabled bool, isDependentRTT bool, isDependentJitter bool) *ConnectionStats { func newConnectionStats(mimeType string, isFECEnabled bool, isDependentRTT bool, isDependentJitter bool) *ConnectionStats {
@@ -38,7 +39,7 @@ func TestConnectionQuality(t *testing.T) {
// best conditions (no loss, jitter/rtt = 0) - quality should stay EXCELLENT // best conditions (no loss, jitter/rtt = 0) - quality should stay EXCELLENT
streams := map[uint32]*buffer.StreamStatsWithLayers{ streams := map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -54,7 +55,7 @@ func TestConnectionQuality(t *testing.T) {
// introduce loss and the score should drop - 12% loss for Opus -> POOR // introduce loss and the score should drop - 12% loss for Opus -> POOR
now = now.Add(duration) now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -73,7 +74,7 @@ func TestConnectionQuality(t *testing.T) {
// bound so that climbing back does not take too long even under excellent conditions. // bound so that climbing back does not take too long even under excellent conditions.
now = now.Add(duration) now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -89,7 +90,7 @@ func TestConnectionQuality(t *testing.T) {
// should stay at GOOD if conditions continue to be good // should stay at GOOD if conditions continue to be good
now = now.Add(duration) now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -105,7 +106,7 @@ func TestConnectionQuality(t *testing.T) {
// should climb up to EXCELLENT if conditions continue to be good // should climb up to EXCELLENT if conditions continue to be good
now = now.Add(duration) now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -121,7 +122,7 @@ func TestConnectionQuality(t *testing.T) {
// introduce loss and the score should drop - 5% loss for Opus -> GOOD // introduce loss and the score should drop - 5% loss for Opus -> GOOD
now = now.Add(duration) now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -138,7 +139,7 @@ func TestConnectionQuality(t *testing.T) {
// should stay at GOOD quality for another iteration even if the conditions improve // should stay at GOOD quality for another iteration even if the conditions improve
now = now.Add(duration) now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -154,7 +155,7 @@ func TestConnectionQuality(t *testing.T) {
// should climb up to EXCELLENT if conditions continue to be good // should climb up to EXCELLENT if conditions continue to be good
now = now.Add(duration) now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -170,7 +171,7 @@ func TestConnectionQuality(t *testing.T) {
// mute when quality is POOR should return quality to EXCELLENT // mute when quality is POOR should return quality to EXCELLENT
now = now.Add(duration) now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -195,7 +196,7 @@ func TestConnectionQuality(t *testing.T) {
cs.UpdateMute(false, now.Add(3*time.Second)) cs.UpdateMute(false, now.Add(3*time.Second))
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -211,7 +212,7 @@ func TestConnectionQuality(t *testing.T) {
// next update with no packets should knock quality down // next update with no packets should knock quality down
now = now.Add(duration) now = now.Add(duration)
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -232,7 +233,7 @@ func TestConnectionQuality(t *testing.T) {
// with lesser number of packet (simulating DTX). // with lesser number of packet (simulating DTX).
// even higher loss (like 10%) should only knock down quality to GOOD, typically would be POOR at that loss rate // even higher loss (like 10%) should only knock down quality to GOOD, typically would be POOR at that loss rate
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -254,7 +255,7 @@ func TestConnectionQuality(t *testing.T) {
// RTT and jitter can knock quality down. // RTT and jitter can knock quality down.
// at 2% loss, quality should stay at EXCELLENT purely based on loss, but with added RTT/jitter, should drop to GOOD // at 2% loss, quality should stay at EXCELLENT purely based on loss, but with added RTT/jitter, should drop to GOOD
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -280,7 +281,7 @@ func TestConnectionQuality(t *testing.T) {
cs.AddBitrateTransition(2_000_000, now.Add(2*time.Second)) cs.AddBitrateTransition(2_000_000, now.Add(2*time.Second))
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -306,7 +307,7 @@ func TestConnectionQuality(t *testing.T) {
cs.AddBitrateTransition(2_000_000, now.Add(2*time.Second)) cs.AddBitrateTransition(2_000_000, now.Add(2*time.Second))
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -331,7 +332,7 @@ func TestConnectionQuality(t *testing.T) {
cs.AddBitrateTransition(2_000_000, now.Add(2*time.Second)) cs.AddBitrateTransition(2_000_000, now.Add(2*time.Second))
streams = map[uint32]*buffer.StreamStatsWithLayers{ streams = map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -356,9 +357,9 @@ func TestConnectionQuality(t *testing.T) {
// RTT does not knock quality down because it is dependent and hence not taken into account // RTT does not knock quality down because it is dependent and hence not taken into account
// at 2% loss, quality should stay at EXCELLENT purely based on loss. With high RTT (700 ms) // at 2% loss, quality should stay at EXCELLENT purely based on loss. With high RTT (700 ms)
// quality should drop to GOOD if RTT were taken into consieration // quality should drop to GOOD if RTT were taken into consideration
streams := map[uint32]*buffer.StreamStatsWithLayers{ streams := map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -384,9 +385,9 @@ func TestConnectionQuality(t *testing.T) {
// Jitter does not knock quality down because it is dependent and hence not taken into account // Jitter does not knock quality down because it is dependent and hence not taken into account
// at 2% loss, quality should stay at EXCELLENT purely based on loss. With high jitter (200 ms) // at 2% loss, quality should stay at EXCELLENT purely based on loss. With high jitter (200 ms)
// quality should drop to GOOD if jitter were taken into consieration // quality should drop to GOOD if jitter were taken into consideration
streams := map[uint32]*buffer.StreamStatsWithLayers{ streams := map[uint32]*buffer.StreamStatsWithLayers{
1: &buffer.StreamStatsWithLayers{ 1: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -548,7 +549,7 @@ func TestConnectionQuality(t *testing.T) {
for _, eq := range tc.expectedQualities { for _, eq := range tc.expectedQualities {
streams := map[uint32]*buffer.StreamStatsWithLayers{ streams := map[uint32]*buffer.StreamStatsWithLayers{
123: &buffer.StreamStatsWithLayers{ 123: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -644,7 +645,7 @@ func TestConnectionQuality(t *testing.T) {
} }
streams := map[uint32]*buffer.StreamStatsWithLayers{ streams := map[uint32]*buffer.StreamStatsWithLayers{
123: &buffer.StreamStatsWithLayers{ 123: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
@@ -731,7 +732,7 @@ func TestConnectionQuality(t *testing.T) {
} }
streams := map[uint32]*buffer.StreamStatsWithLayers{ streams := map[uint32]*buffer.StreamStatsWithLayers{
123: &buffer.StreamStatsWithLayers{ 123: {
RTPStats: &buffer.RTPDeltaInfo{ RTPStats: &buffer.RTPDeltaInfo{
StartTime: now, StartTime: now,
Duration: duration, Duration: duration,
+10 -10
View File
@@ -63,7 +63,7 @@ func (w *windowStat) calculatePacketScore(plw float64, isDependentRTT bool, isDe
actualLost = 0 actualLost = 0
} }
lossEffect := float64(0.0) var lossEffect float64
if w.packetsExpected > 0 { if w.packetsExpected > 0 {
lossEffect = float64(actualLost) * 100.0 / float64(w.packetsExpected) lossEffect = float64(actualLost) * 100.0 / float64(w.packetsExpected)
} }
@@ -83,7 +83,7 @@ func (w *windowStat) calculateBitrateScore(expectedBitrate int64) float64 {
return maxScore return maxScore
} }
score := float64(0.0) var score float64
if w.bytes != 0 { if w.bytes != 0 {
// using the ratio of expectedBitrate / actualBitrate // using the ratio of expectedBitrate / actualBitrate
// the quality inflection points are approximately // the quality inflection points are approximately
@@ -369,7 +369,7 @@ func (q *qualityScorer) getExpectedBitsAndUpdateTransitions(at time.Time) int64
} }
var startedAt time.Time var startedAt time.Time
totalBits := float64(0.0) var totalBits float64
for idx := 0; idx < len(q.bitrateTransitions)-1; idx++ { for idx := 0; idx < len(q.bitrateTransitions)-1; idx++ {
bt := &q.bitrateTransitions[idx] bt := &q.bitrateTransitions[idx]
btNext := &q.bitrateTransitions[idx+1] btNext := &q.bitrateTransitions[idx+1]
@@ -391,8 +391,8 @@ func (q *qualityScorer) getExpectedBitsAndUpdateTransitions(at time.Time) int64
} }
totalBits += at.Sub(startedAt).Seconds() * float64(bt.bitrate) totalBits += at.Sub(startedAt).Seconds() * float64(bt.bitrate)
// set up last bit rate as the startig bit rate for next analysis window // set up last bit rate as the starting bit rate for next analysis window
q.bitrateTransitions = []bitrateTransition{bitrateTransition{ q.bitrateTransitions = []bitrateTransition{{
startedAt: at, startedAt: at,
bitrate: bt.bitrate, bitrate: bt.bitrate,
}} }}
@@ -406,7 +406,7 @@ func (q *qualityScorer) getExpectedDistanceAndUpdateTransitions(at time.Time) fl
} }
var startedAt time.Time var startedAt time.Time
totalDistance := float64(0.0) var totalDistance float64
totalDuration := time.Duration(0) totalDuration := time.Duration(0)
for idx := 0; idx < len(q.layerTransitions)-1; idx++ { for idx := 0; idx < len(q.layerTransitions)-1; idx++ {
lt := &q.layerTransitions[idx] lt := &q.layerTransitions[idx]
@@ -425,7 +425,7 @@ func (q *qualityScorer) getExpectedDistanceAndUpdateTransitions(at time.Time) fl
// negative distances are overshoot, that does not compensate for shortfalls, so use optimal, i. e. 0 distance when overshooting // negative distances are overshoot, that does not compensate for shortfalls, so use optimal, i. e. 0 distance when overshooting
dist = 0.0 dist = 0.0
} }
totalDistance += dur.Seconds() * float64(dist) totalDistance += dur.Seconds() * dist
} }
// last transition // last transition
@@ -442,10 +442,10 @@ func (q *qualityScorer) getExpectedDistanceAndUpdateTransitions(at time.Time) fl
if dist < 0.0 { if dist < 0.0 {
dist = 0.0 dist = 0.0
} }
totalDistance += dur.Seconds() * float64(dist) totalDistance += dur.Seconds() * dist
// set up last distance as the startig distance for next analysis window // set up last distance as the starting distance for next analysis window
q.layerTransitions = []layerTransition{layerTransition{ q.layerTransitions = []layerTransition{{
startedAt: at, startedAt: at,
distance: lt.distance, distance: lt.distance,
}} }}
+13 -13
View File
@@ -8,15 +8,15 @@ import (
type BitStreamReader struct { type BitStreamReader struct {
buf []byte buf []byte
pos int pos int
remaingBits int remainingBits int
} }
func NewBitStreamReader(buf []byte) *BitStreamReader { func NewBitStreamReader(buf []byte) *BitStreamReader {
return &BitStreamReader{buf: buf, remaingBits: len(buf) * 8} return &BitStreamReader{buf: buf, remainingBits: len(buf) * 8}
} }
func (b *BitStreamReader) RemaningBits() int { func (b *BitStreamReader) RemainingBits() int {
return b.remaingBits return b.remainingBits
} }
// Reads `bits` from the bitstream. `bits` must be in range [0, 64]. // Reads `bits` from the bitstream. `bits` must be in range [0, 64].
@@ -27,17 +27,17 @@ func (b *BitStreamReader) ReadBits(bits int) (uint64, error) {
return 0, errors.New("invalid number of bits, expected 0-64") return 0, errors.New("invalid number of bits, expected 0-64")
} }
if b.remaingBits < bits { if b.remainingBits < bits {
b.remaingBits -= bits b.remainingBits -= bits
return 0, io.EOF return 0, io.EOF
} }
remainingBitsInFirstByte := b.remaingBits % 8 remainingBitsInFirstByte := b.remainingBits % 8
b.remaingBits -= bits b.remainingBits -= bits
if bits < remainingBitsInFirstByte { if bits < remainingBitsInFirstByte {
// Reading fewer bits than what's left in the current byte, just // Reading fewer bits than what's left in the current byte, just
// return the portion of this byte that is needed. // return the portion of this byte that is needed.
offset := (remainingBitsInFirstByte - bits) offset := remainingBitsInFirstByte - bits
return uint64((b.buf[b.pos] >> offset) & ((1 << bits) - 1)), nil return uint64((b.buf[b.pos] >> offset) & ((1 << bits) - 1)), nil
} }
var result uint64 var result uint64
@@ -69,11 +69,11 @@ func (b *BitStreamReader) ReadBool() (bool, error) {
} }
func (b *BitStreamReader) Ok() bool { func (b *BitStreamReader) Ok() bool {
return b.remaingBits >= 0 return b.remainingBits >= 0
} }
func (b *BitStreamReader) Invalidate() { func (b *BitStreamReader) Invalidate() {
b.remaingBits = -1 b.remainingBits = -1
} }
// Reads value in range [0, `num_values` - 1]. // Reads value in range [0, `num_values` - 1].
@@ -107,8 +107,8 @@ func (b *BitStreamReader) ReadNonSymmetric(numValues uint32) (uint32, error) {
return uint32((val << 1) + bit - uint64(numMinBitsValues)), nil return uint32((val << 1) + bit - uint64(numMinBitsValues)), nil
} }
func (b *BitStreamReader) ReadedBytes() int { func (b *BitStreamReader) BytesRead() int {
if b.remaingBits%8 > 0 { if b.remainingBits%8 > 0 {
return b.pos + 1 return b.pos + 1
} }
return b.pos return b.pos
@@ -27,7 +27,7 @@ func (w *BitStreamWriter) WriteBits(val uint64, bitCount int) error {
totalBits := bitCount totalBits := bitCount
// push bits to the highest bits of uint64 // push bits to the highest bits of uint64
val <<= (64 - bitCount) val <<= 64 - bitCount
buf := w.buf[w.pos:] buf := w.buf[w.pos:]
@@ -86,7 +86,7 @@ type DecodeTargetIndication int
const ( const (
DecodeTargetNotPresent DecodeTargetIndication = iota // DecodeTargetInfo symbol '-' DecodeTargetNotPresent DecodeTargetIndication = iota // DecodeTargetInfo symbol '-'
DecodeTargetDiscadable // DecodeTargetInfo symbol 'D' DecodeTargetDiscardable // DecodeTargetInfo symbol 'D'
DecodeTargetSwitch // DecodeTargetInfo symbol 'S' DecodeTargetSwitch // DecodeTargetInfo symbol 'S'
DecodeTargetRequired // DecodeTargetInfo symbol 'R' DecodeTargetRequired // DecodeTargetInfo symbol 'R'
) )
@@ -95,7 +95,7 @@ func (i DecodeTargetIndication) String() string {
switch i { switch i {
case DecodeTargetNotPresent: case DecodeTargetNotPresent:
return "-" return "-"
case DecodeTargetDiscadable: case DecodeTargetDiscardable:
return "D" return "D"
case DecodeTargetSwitch: case DecodeTargetSwitch:
return "S" return "S"
@@ -35,7 +35,7 @@ func TestDependencyDescriptorUnmarshal(t *testing.T) {
} }
var ddVal DependencyDescriptor var ddVal DependencyDescriptor
var d DependencyDescriptorExtension = DependencyDescriptorExtension{ var d = DependencyDescriptorExtension{
Structure: structure, Structure: structure,
Descriptor: &ddVal, Descriptor: &ddVal,
} }
@@ -59,7 +59,7 @@ func (r *DependencyDescriptorReader) Parse() (int, error) {
if err != nil { if err != nil {
return 0, err return 0, err
} }
return r.buffer.ReadedBytes(), nil return r.buffer.BytesRead(), nil
} }
func (r *DependencyDescriptorReader) readMandatoryFields() error { func (r *DependencyDescriptorReader) readMandatoryFields() error {
@@ -47,7 +47,7 @@ func (w *DependencyDescriptorWriter) Write() error {
return err return err
} }
if w.hasExtenedFields() { if w.hasExtendedFields() {
if err := w.writeExtendedFields(); err != nil { if err := w.writeExtendedFields(); err != nil {
return err return err
} }
@@ -57,15 +57,15 @@ func (w *DependencyDescriptorWriter) Write() error {
} }
} }
remaingBits := w.writer.RemainingBits() remainingBits := w.writer.RemainingBits()
// Zero remaining memory to avoid leaving it uninitialized. // Zero remaining memory to avoid leaving it uninitialized.
if remaingBits%64 != 0 { if remainingBits%64 != 0 {
if err := w.writeBits(0, remaingBits%64); err != nil { if err := w.writeBits(0, remainingBits%64); err != nil {
return err return err
} }
} }
for i := 0; i < remaingBits/64; i++ { for i := 0; i < remainingBits/64; i++ {
if err := w.writeBits(0, 64); err != nil { if err := w.writeBits(0, 64); err != nil {
return err return err
} }
@@ -101,10 +101,10 @@ func (w *DependencyDescriptorWriter) findBestTemplate() error {
} }
// Search if there any better template that have small extra size. // Search if there any better template that have small extra size.
w.bestTemplate = w.caculateMatch(firstSameLayerIdx, firstSameLayer) w.bestTemplate = w.calculateMatch(firstSameLayerIdx, firstSameLayer)
for i := firstSameLayerIdx + 1; i <= lastSameLayerIdx; i++ { for i := firstSameLayerIdx + 1; i <= lastSameLayerIdx; i++ {
t := w.structure.Templates[i] t := w.structure.Templates[i]
match := w.caculateMatch(i, t) match := w.calculateMatch(i, t)
if match.ExtraSizeBits < w.bestTemplate.ExtraSizeBits { if match.ExtraSizeBits < w.bestTemplate.ExtraSizeBits {
w.bestTemplate = match w.bestTemplate = match
} }
@@ -127,7 +127,7 @@ func (w *DependencyDescriptorWriter) findBestTemplate() error {
// return true // return true
// } // }
func (w *DependencyDescriptorWriter) caculateMatch(idx int, template *FrameDependencyTemplate) TemplateMatch { func (w *DependencyDescriptorWriter) calculateMatch(idx int, template *FrameDependencyTemplate) TemplateMatch {
var result TemplateMatch var result TemplateMatch
result.TemplateIdx = idx result.TemplateIdx = idx
result.NeedCustomFdiffs = w.descriptor.FrameDependencies.FrameDiffs != nil && !reflect.DeepEqual(w.descriptor.FrameDependencies.FrameDiffs, template.FrameDiffs) result.NeedCustomFdiffs = w.descriptor.FrameDependencies.FrameDiffs != nil && !reflect.DeepEqual(w.descriptor.FrameDependencies.FrameDiffs, template.FrameDiffs)
@@ -191,13 +191,13 @@ func (w *DependencyDescriptorWriter) writeBool(val bool) error {
} }
func (w *DependencyDescriptorWriter) writeBits(val uint64, bitCount int) error { func (w *DependencyDescriptorWriter) writeBits(val uint64, bitCount int) error {
if err := w.writer.WriteBits(uint64(val), bitCount); err != nil { if err := w.writer.WriteBits(val, bitCount); err != nil {
return err return err
} }
return nil return nil
} }
func (w *DependencyDescriptorWriter) hasExtenedFields() bool { func (w *DependencyDescriptorWriter) hasExtendedFields() bool {
return w.bestTemplate.ExtraSizeBits > 0 || w.descriptor.AttachedStructure != nil || w.descriptor.ActiveDecodeTargetsBitmask != nil return w.bestTemplate.ExtraSizeBits > 0 || w.descriptor.AttachedStructure != nil || w.descriptor.ActiveDecodeTargetsBitmask != nil
} }
@@ -448,7 +448,7 @@ const mandatoryFieldSize = 1 + 1 + 6 + 16
func (w *DependencyDescriptorWriter) ValueSizeBits() int { func (w *DependencyDescriptorWriter) ValueSizeBits() int {
valueSizeBits := mandatoryFieldSize + w.bestTemplate.ExtraSizeBits valueSizeBits := mandatoryFieldSize + w.bestTemplate.ExtraSizeBits
if w.hasExtenedFields() { if w.hasExtendedFields() {
valueSizeBits += 5 valueSizeBits += 5
if w.descriptor.AttachedStructure != nil { if w.descriptor.AttachedStructure != nil {
valueSizeBits += w.structureSizeBits() valueSizeBits += w.structureSizeBits()
+3 -3
View File
@@ -143,7 +143,7 @@ type DownTrackStreamAllocatorListener interface {
// subscribed max video layer changed // subscribed max video layer changed
OnSubscribedLayersChanged(dt *DownTrack, layers VideoLayers) OnSubscribedLayersChanged(dt *DownTrack, layers VideoLayers)
// target video layer reaached // target video layer reached
OnTargetLayerReached(dt *DownTrack) OnTargetLayerReached(dt *DownTrack)
// packet(s) sent // packet(s) sent
@@ -760,7 +760,7 @@ func (d *DownTrack) handleMute(muted bool, isPub bool, changed bool, maxLayers V
// 2. down track(s) notifying max layer // 2. down track(s) notifying max layer
// 3. out-of-band notification about max layer sent back to the publisher // 3. out-of-band notification about max layer sent back to the publisher
// 4. publisher starts layer(s) // 4. publisher starts layer(s)
// Ideally, on publisher mute, whatever layers were active reamin active and // Ideally, on publisher mute, whatever layers were active remain active and
// can be restarted by publisher immediately on unmute. // can be restarted by publisher immediately on unmute.
// //
// Note that while publisher mute is active, subscriber changes can also happen // Note that while publisher mute is active, subscriber changes can also happen
@@ -1503,7 +1503,7 @@ func (d *DownTrack) writeRTPHeaderExtensions(hdr *rtp.Header, extraExtensions ..
hdr.Extensions = []rtp.Extension{} hdr.Extensions = []rtp.Extension{}
for _, ext := range extraExtensions { for _, ext := range extraExtensions {
hdr.SetExtension(uint8(ext.id), ext.payload) hdr.SetExtension(ext.id, ext.payload)
} }
if d.absSendTimeID != 0 { if d.absSendTimeID != 0 {
+3 -3
View File
@@ -518,7 +518,7 @@ func TestForwarderProvisionalAllocate(t *testing.T) {
} }
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
bandwidthRequested: bitrates[1][3], bandwidthRequested: bitrates[1][3],
bandwidthDelta: bitrates[1][3] - 1, // 1 is the last allocation bandwith requested bandwidthDelta: bitrates[1][3] - 1, // 1 is the last allocation bandwidth requested
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
requestLayerSpatial: expectedTargetLayers.Spatial, requestLayerSpatial: expectedTargetLayers.Spatial,
@@ -562,7 +562,7 @@ func TestForwarderProvisionalAllocate(t *testing.T) {
expectedResult = VideoAllocation{ expectedResult = VideoAllocation{
pauseReason: VideoPauseReasonFeedDry, pauseReason: VideoPauseReasonFeedDry,
bandwidthRequested: bitrates[0][2], bandwidthRequested: bitrates[0][2],
bandwidthDelta: bitrates[0][2] - 8, // 8 is the last allocation bandwith requested bandwidthDelta: bitrates[0][2] - 8, // 8 is the last allocation bandwidth requested
bitrates: bitrates, bitrates: bitrates,
targetLayers: expectedTargetLayers, targetLayers: expectedTargetLayers,
requestLayerSpatial: expectedTargetLayers.Spatial, requestLayerSpatial: expectedTargetLayers.Spatial,
@@ -787,7 +787,7 @@ func TestForwarderProvisionalAllocateGetCooperativeTransition(t *testing.T) {
require.Equal(t, expectedLayers, f.TargetLayers()) require.Equal(t, expectedLayers, f.TargetLayers())
// //
// Test continuting at current layers when feed is dry // Test continuing at current layers when feed is dry
// //
bitrates = Bitrates{ bitrates = Bitrates{
{0, 0, 0, 0}, {0, 0, 0, 0},
+2 -1
View File
@@ -5,8 +5,9 @@ import (
"sync" "sync"
"time" "time"
"github.com/livekit/protocol/logger"
"go.uber.org/atomic" "go.uber.org/atomic"
"github.com/livekit/protocol/logger"
) )
// ------------------------------------------------------------ // ------------------------------------------------------------
+1 -1
View File
@@ -151,7 +151,7 @@ func (s *StreamTrackerFrame) updateEstimatedFrameRate() float64 {
s.oldestTS = s.newestTS s.oldestTS = s.newestTS
s.numFrames = 1 s.numFrames = 1
factor := float64(1.0) factor := 1.0
switch { switch {
case s.estimatedFrameRate < frameRate: case s.estimatedFrameRate < frameRate:
// slow increase, prevents shortening eval interval too quickly on frame rate going up // slow increase, prevents shortening eval interval too quickly on frame rate going up
+1
View File
@@ -7,6 +7,7 @@ import (
"time" "time"
"github.com/frostbyte73/core" "github.com/frostbyte73/core"
"github.com/livekit/livekit-server/pkg/config" "github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/sfu/buffer" "github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/livekit-server/pkg/sfu/streamtracker" "github.com/livekit/livekit-server/pkg/sfu/streamtracker"
+8 -8
View File
@@ -78,7 +78,7 @@ func (s *DDVideoLayerSelector) Select(expPkt *buffer.ExtPacket, tp *TranslationP
} }
if currentTarget < 0 { if currentTarget < 0 {
// s.logger.Debugw(fmt.Sprintf("drop packet for no target found, deocdeTargets %v, selected layer %v, s:%d, t:%d", // s.logger.Debugw(fmt.Sprintf("drop packet for no target found, decodeTargets %v, selected layer %v, s:%d, t:%d",
// s.decodeTargetLayer, s.layer, expPkt.DependencyDescriptor.FrameDependencies.SpatialId, expPkt.DependencyDescriptor.FrameDependencies.TemporalId)) // s.decodeTargetLayer, s.layer, expPkt.DependencyDescriptor.FrameDependencies.SpatialId, expPkt.DependencyDescriptor.FrameDependencies.TemporalId))
// no active decode target, forward all packets // no active decode target, forward all packets
return false return false
@@ -178,25 +178,25 @@ func (s *DDVideoLayerSelector) updateDependencyStructure(structure *dd.FrameDepe
// DD-TODO : use generic wrapper when updated to go 1.18 // DD-TODO : use generic wrapper when updated to go 1.18
type Uint16Wrapper struct { type Uint16Wrapper struct {
last_value *uint16 lastValue *uint16
lastUnwrapped int32 lastUnwrapped int32
} }
func (w *Uint16Wrapper) Unwrap(value uint16) int32 { func (w *Uint16Wrapper) Unwrap(value uint16) int32 {
if w.last_value == nil { if w.lastValue == nil {
w.last_value = &value w.lastValue = &value
w.lastUnwrapped = int32(value) w.lastUnwrapped = int32(value)
return int32(*w.last_value) return int32(*w.lastValue)
} }
diff := value - *w.last_value diff := value - *w.lastValue
w.lastUnwrapped += int32(diff) w.lastUnwrapped += int32(diff)
if diff == 0x8000 && value < *w.last_value { if diff == 0x8000 && value < *w.lastValue {
w.lastUnwrapped -= 0x10000 w.lastUnwrapped -= 0x10000
} else if diff > 0x8000 { } else if diff > 0x8000 {
w.lastUnwrapped -= 0x10000 w.lastUnwrapped -= 0x10000
} }
*w.last_value = value *w.lastValue = value
return w.lastUnwrapped return w.lastUnwrapped
} }
+8 -8
View File
@@ -53,31 +53,31 @@ func (s *BytesTrackStats) Report() {
s.report(true) s.report(true)
} }
func (p *BytesTrackStats) report(force bool) { func (s *BytesTrackStats) report(force bool) {
now := time.Now() now := time.Now()
if !force { if !force {
lr := p.lastStatsReport.Load().(*time.Time) lr := s.lastStatsReport.Load().(*time.Time)
if time.Since(*lr) < statsReportInterval { if time.Since(*lr) < statsReportInterval {
return return
} }
if !p.lastStatsReport.CompareAndSwap(lr, &now) { if !s.lastStatsReport.CompareAndSwap(lr, &now) {
return return
} }
} else { } else {
p.lastStatsReport.Store(&now) s.lastStatsReport.Store(&now)
} }
if recv := p.recv.Swap(0); recv > 0 { if recv := s.recv.Swap(0); recv > 0 {
p.telemetry.TrackStats(StatsKeyForData(livekit.StreamType_UPSTREAM, p.pID, p.trackID), &livekit.AnalyticsStat{ s.telemetry.TrackStats(StatsKeyForData(livekit.StreamType_UPSTREAM, s.pID, s.trackID), &livekit.AnalyticsStat{
Streams: []*livekit.AnalyticsStream{ Streams: []*livekit.AnalyticsStream{
{PrimaryBytes: recv}, {PrimaryBytes: recv},
}, },
}) })
} }
if send := p.send.Swap(0); send > 0 { if send := s.send.Swap(0); send > 0 {
p.telemetry.TrackStats(StatsKeyForData(livekit.StreamType_DOWNSTREAM, p.pID, p.trackID), &livekit.AnalyticsStat{ s.telemetry.TrackStats(StatsKeyForData(livekit.StreamType_DOWNSTREAM, s.pID, s.trackID), &livekit.AnalyticsStat{
Streams: []*livekit.AnalyticsStream{ Streams: []*livekit.AnalyticsStream{
{PrimaryBytes: send}, {PrimaryBytes: send},
}, },
+1 -1
View File
@@ -630,7 +630,7 @@ func (c *RTCClient) ensurePublisherConnected() error {
} }
} }
func (c *RTCClient) handleDataMessage(kind livekit.DataPacket_Kind, data []byte) { func (c *RTCClient) handleDataMessage(_ livekit.DataPacket_Kind, data []byte) {
dp := &livekit.DataPacket{} dp := &livekit.DataPacket{}
err := proto.Unmarshal(data, dp) err := proto.Unmarshal(data, dp)
if err != nil { if err != nil {