Compare commits
10
Commits
9a6c187afd
...
44b791ad50
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
44b791ad50 | ||
|
|
c2339b2b85 | ||
|
|
edb19c9e8f | ||
|
|
7ef0cd014e | ||
|
|
2fab31691b | ||
|
|
aa08becc6a | ||
|
|
ad54223d1b | ||
|
|
2d9bf12581 | ||
|
|
d91b16238a | ||
|
|
6ed445bad1 |
@@ -117,6 +117,16 @@ rtc:
|
||||
# # in the unlikely event of highly congested networks, SFU may choose to pause some tracks
|
||||
# # in order to allow others to stream smoothly. You can disable this behavior here
|
||||
# allow_pause: true
|
||||
# # use send-side bandwidth estimation instead of relying on receiver reports, default false
|
||||
# use_send_side_bwe: false
|
||||
# # how egress is paced when use_send_side_bwe is enabled. one of:
|
||||
# # no-queue - hand packets to a send worker that drains them without rate
|
||||
# # limiting, so the sender never blocks on a write (default)
|
||||
# # pass-through - send each packet inline on the calling goroutine
|
||||
# # leaky-bucket - accepted, but not currently wired to the bandwidth estimate; it
|
||||
# # logs a warning and falls back to no-queue. see livekit/livekit#4724
|
||||
# # an unrecognized value is rejected at startup.
|
||||
# send_side_bwe_pacer: no-queue
|
||||
# # allows automatic connection fallback to TCP and TURN/TLS (if configured) when UDP has been unstable, default true
|
||||
# allow_tcp_fallback: true
|
||||
# # signaling RTT (in milliseconds) below which ICE/TCP is attempted on a UDP failure; at or above it,
|
||||
|
||||
+37
-5
@@ -220,6 +220,22 @@ type CongestionControlConfig struct {
|
||||
SendSideBWE sendsidebwe.SendSideBWEConfig `yaml:"send_side_bwe,omitempty"`
|
||||
}
|
||||
|
||||
// Validate reports configuration that would otherwise be ignored at runtime.
|
||||
func (c CongestionControlConfig) Validate() error {
|
||||
switch pacer.PacerBehavior(c.SendSideBWEPacer) {
|
||||
case "", pacer.PacerBehaviorPassThrough, pacer.PacerBehaviorNoQueue, pacer.PacerBehaviorLeakybucket:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf(
|
||||
"invalid send_side_bwe_pacer %q, must be one of %q, %q, %q",
|
||||
c.SendSideBWEPacer,
|
||||
pacer.PacerBehaviorPassThrough,
|
||||
pacer.PacerBehaviorNoQueue,
|
||||
pacer.PacerBehaviorLeakybucket,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
type PlayoutDelayConfig struct {
|
||||
Enabled bool `yaml:"enabled,omitempty"`
|
||||
Min int `yaml:"min,omitempty"`
|
||||
@@ -399,8 +415,20 @@ func (l LimitConfig) CheckAttributesSize(attributes map[string]string) bool {
|
||||
return uint32(total) <= l.MaxAttributesSize
|
||||
}
|
||||
|
||||
func (l LimitConfig) CheckDataBlobKeyLength(key string) bool {
|
||||
return l.MaxDataBlobKeyLength == 0 || len(key) <= l.MaxDataBlobKeyLength
|
||||
// DataBlobKeyLength returns the length of the identifying content of a data blob key.
|
||||
// The text form of the key message is not used, as it adds field names and quotes.
|
||||
func DataBlobKeyLength(key *livekit.DataBlobKey) int {
|
||||
switch k := key.GetKey().(type) {
|
||||
case *livekit.DataBlobKey_Generic:
|
||||
return len(k.Generic)
|
||||
case *livekit.DataBlobKey_SchemaId:
|
||||
return len(k.SchemaId.GetName()) + len(k.SchemaId.GetEncoding().GetCustom())
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (l LimitConfig) CheckDataBlobKeyLength(key *livekit.DataBlobKey) bool {
|
||||
return l.MaxDataBlobKeyLength == 0 || DataBlobKeyLength(key) <= l.MaxDataBlobKeyLength
|
||||
}
|
||||
|
||||
func (l LimitConfig) CheckDataTrackCustomEncodingLength(identifier string) bool {
|
||||
@@ -430,7 +458,7 @@ func (l LimitConfig) CheckDataBlobsSize(dataBlobs []*livekit.DataBlob) bool {
|
||||
|
||||
total := 0
|
||||
for _, dataBlob := range dataBlobs {
|
||||
total += len(dataBlob.GetKey().String()) + len(dataBlob.Contents)
|
||||
total += DataBlobKeyLength(dataBlob.GetKey()) + len(dataBlob.Contents)
|
||||
}
|
||||
return uint32(total) <= l.MaxDataBlobSize
|
||||
}
|
||||
@@ -442,9 +470,9 @@ func (l LimitConfig) CanAddDataBlob(dataBlobs []*livekit.DataBlob, toAdd *liveki
|
||||
|
||||
total := 0
|
||||
for _, dataBlob := range dataBlobs {
|
||||
total += len(dataBlob.Key.String()) + len(dataBlob.Contents)
|
||||
total += DataBlobKeyLength(dataBlob.GetKey()) + len(dataBlob.Contents)
|
||||
}
|
||||
return uint32(total+len(toAdd.GetKey().String())+len(toAdd.Contents)) <= l.MaxDataBlobSize
|
||||
return uint32(total+DataBlobKeyLength(toAdd.GetKey())+len(toAdd.Contents)) <= l.MaxDataBlobSize
|
||||
}
|
||||
|
||||
// ---------------------------------
|
||||
@@ -659,6 +687,10 @@ func NewConfig(confString string, strictMode bool, c *cli.Command, baseFlags []c
|
||||
return nil, fmt.Errorf("could not validate RTC config: %v", err)
|
||||
}
|
||||
|
||||
if err := conf.RTC.CongestionControl.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("could not validate congestion control config: %v", err)
|
||||
}
|
||||
|
||||
conf.NormalizeTURNTTLs()
|
||||
|
||||
// expand env vars in filenames
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/urfave/cli/v3"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/config/configtest"
|
||||
"github.com/livekit/livekit-server/pkg/sfu/pacer"
|
||||
)
|
||||
|
||||
func TestConfig_UnmarshalKeys(t *testing.T) {
|
||||
@@ -182,6 +183,40 @@ func TestNewConfigNormalizesTURNTTL(t *testing.T) {
|
||||
require.Equal(t, DefaultTURNTTLSeconds, conf.TURN.TTLSeconds)
|
||||
}
|
||||
|
||||
func TestNewConfigValidatesSendSideBWEPacer(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
pacer string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "unset keeps the default", pacer: "", wantErr: false},
|
||||
{name: "pass-through", pacer: string(pacer.PacerBehaviorPassThrough), wantErr: false},
|
||||
{name: "no-queue", pacer: string(pacer.PacerBehaviorNoQueue), wantErr: false},
|
||||
{name: "leaky-bucket", pacer: string(pacer.PacerBehaviorLeakybucket), wantErr: false},
|
||||
{name: "typo is rejected", pacer: "leakybucket", wantErr: true},
|
||||
{name: "unknown value is rejected", pacer: "not-a-pacer", wantErr: true},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
content := "rtc:\n congestion_control:\n send_side_bwe_pacer: " + tc.pacer
|
||||
conf, err := NewConfig(content, true, nil, nil)
|
||||
if tc.wantErr {
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), tc.pacer)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
if tc.pacer == "" {
|
||||
require.Equal(t, string(pacer.PacerBehaviorNoQueue), conf.RTC.CongestionControl.SendSideBWEPacer)
|
||||
return
|
||||
}
|
||||
require.Equal(t, tc.pacer, conf.RTC.CongestionControl.SendSideBWEPacer)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func writeSecretFile(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "secret")
|
||||
|
||||
@@ -162,6 +162,10 @@ func isCodecEnabledWithFmtp(codecs []*livekit.Codec, cap webrtc.RTPCodecCapabili
|
||||
|
||||
func selectAlternativeVideoCodec(enabledCodecs []*livekit.Codec) string {
|
||||
for _, c := range enabledCodecs {
|
||||
// RTX and FEC are not real codecs, skip them
|
||||
if mime.IsMimeTypeStringRTX(c.Mime) || mime.IsMimeTypeStringFlexFEC03(c.Mime) {
|
||||
continue
|
||||
}
|
||||
if mime.IsMimeTypeStringVideo(c.Mime) {
|
||||
return c.Mime
|
||||
}
|
||||
|
||||
@@ -73,6 +73,23 @@ func TestIsCodecEnabled(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestSelectAlternativeVideoCodec(t *testing.T) {
|
||||
// RTX and FEC have the video/ prefix but are not real codecs. The fallback must skip them.
|
||||
t.Run("skips rtx and fec, picks real codec", func(t *testing.T) {
|
||||
enabled := []*livekit.Codec{
|
||||
{Mime: mime.MimeTypeRTX.String()},
|
||||
{Mime: mime.MimeTypeFlexFEC03.String()},
|
||||
{Mime: mime.MimeTypeH264.String()},
|
||||
}
|
||||
require.Equal(t, mime.MimeTypeH264.String(), selectAlternativeVideoCodec(enabled))
|
||||
})
|
||||
|
||||
t.Run("falls back to vp8 when only rtx is enabled", func(t *testing.T) {
|
||||
enabled := []*livekit.Codec{{Mime: mime.MimeTypeRTX.String()}}
|
||||
require.Equal(t, mime.MimeTypeVP8.String(), selectAlternativeVideoCodec(enabled))
|
||||
})
|
||||
}
|
||||
|
||||
type offeredCodec struct {
|
||||
payloadType webrtc.PayloadType
|
||||
name string
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
package rtc
|
||||
|
||||
import (
|
||||
"github.com/livekit/livekit-server/pkg/config"
|
||||
"github.com/livekit/livekit-server/pkg/rtc/types"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/logger"
|
||||
@@ -31,7 +32,7 @@ func (p *ParticipantImpl) HandleStoreDataBlobRequest(req *livekit.StoreDataBlobR
|
||||
return
|
||||
}
|
||||
|
||||
if req.Blob == nil || req.Blob.Key == nil || len(req.Blob.Key.String()) == 0 || !p.params.LimitConfig.CheckDataBlobKeyLength(req.Blob.Key.String()) {
|
||||
if req.Blob == nil || req.Blob.Key == nil || config.DataBlobKeyLength(req.Blob.Key) == 0 || !p.params.LimitConfig.CheckDataBlobKeyLength(req.Blob.Key) {
|
||||
p.pubLogger.Warnw("data blob is invalid", nil, "req", logger.Proto(req))
|
||||
p.sendRequestResponse(&livekit.RequestResponse{
|
||||
RequestId: req.RequestId,
|
||||
|
||||
@@ -124,6 +124,61 @@ func TestHandleStoreDataBlobRequest(t *testing.T) {
|
||||
require.Equal(t, livekit.RequestResponse_INVALID_REQUEST, rr.Reason)
|
||||
})
|
||||
|
||||
t.Run("returns INVALID_REQUEST when generic key is empty", func(t *testing.T) {
|
||||
p := newParticipantWithDataBlob(t, true, 0, 0)
|
||||
sink := p.params.Sink.(*routingfakes.FakeMessageSink)
|
||||
|
||||
p.HandleStoreDataBlobRequest(&livekit.StoreDataBlobRequest{
|
||||
Blob: &livekit.DataBlob{
|
||||
Key: genericKey(""),
|
||||
Contents: []byte("def"),
|
||||
},
|
||||
})
|
||||
|
||||
require.Equal(t, 1, sink.WriteMessageCallCount())
|
||||
rr := lastRequestResponse(t, sink, 0)
|
||||
require.Equal(t, livekit.RequestResponse_INVALID_REQUEST, rr.Reason)
|
||||
require.Empty(t, p.dataBlob.GetAll())
|
||||
})
|
||||
|
||||
t.Run("accepts a key exactly at the length limit", func(t *testing.T) {
|
||||
p := newParticipantWithDataBlob(t, true, 5, 0)
|
||||
sink := p.params.Sink.(*routingfakes.FakeMessageSink)
|
||||
|
||||
key := genericKey("abcde")
|
||||
p.HandleStoreDataBlobRequest(&livekit.StoreDataBlobRequest{
|
||||
Blob: &livekit.DataBlob{
|
||||
Key: key,
|
||||
Contents: []byte("def"),
|
||||
},
|
||||
})
|
||||
|
||||
require.Equal(t, 1, sink.WriteMessageCallCount())
|
||||
msg := sink.WriteMessageArgsForCall(0).(*livekit.SignalResponse)
|
||||
_, ok := msg.Message.(*livekit.SignalResponse_StoreDataBlobResponse)
|
||||
require.True(t, ok, "expected SignalResponse_StoreDataBlobResponse, got %T", msg.Message)
|
||||
require.NotNil(t, p.dataBlob.Get(key))
|
||||
})
|
||||
|
||||
t.Run("counts only key and contents bytes against the size limit", func(t *testing.T) {
|
||||
p := newParticipantWithDataBlob(t, true, 0, 9)
|
||||
sink := p.params.Sink.(*routingfakes.FakeMessageSink)
|
||||
|
||||
key := genericKey("abc")
|
||||
p.HandleStoreDataBlobRequest(&livekit.StoreDataBlobRequest{
|
||||
Blob: &livekit.DataBlob{
|
||||
Key: key,
|
||||
Contents: []byte("defghi"),
|
||||
},
|
||||
})
|
||||
|
||||
require.Equal(t, 1, sink.WriteMessageCallCount())
|
||||
msg := sink.WriteMessageArgsForCall(0).(*livekit.SignalResponse)
|
||||
_, ok := msg.Message.(*livekit.SignalResponse_StoreDataBlobResponse)
|
||||
require.True(t, ok, "expected SignalResponse_StoreDataBlobResponse, got %T", msg.Message)
|
||||
require.NotNil(t, p.dataBlob.Get(key))
|
||||
})
|
||||
|
||||
t.Run("returns INVALID_REQUEST when contents is empty", func(t *testing.T) {
|
||||
p := newParticipantWithDataBlob(t, true, 0, 0)
|
||||
sink := p.params.Sink.(*routingfakes.FakeMessageSink)
|
||||
|
||||
@@ -79,6 +79,38 @@ func TestIsReady(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Disabling a codec can leave the publish list with only RTX and FEC. The
|
||||
// fallback must still pick a real codec, or the track registers as RTX and
|
||||
// subscribers see a blank tile.
|
||||
func TestPublishCodecFallbackSkipsRTX(t *testing.T) {
|
||||
h264 := &livekit.Codec{Mime: mime.MimeTypeH264.String()}
|
||||
rtx := &livekit.Codec{Mime: mime.MimeTypeRTX.String()}
|
||||
|
||||
newParticipant := func() *ParticipantImpl {
|
||||
return &ParticipantImpl{params: ParticipantParams{Logger: logger.GetLogger()}}
|
||||
}
|
||||
|
||||
t.Run("h264 enabled, rtx is last and not chosen", func(t *testing.T) {
|
||||
p := newParticipant()
|
||||
p.setupEnabledCodecs([]*livekit.Codec{h264, rtx}, nil, nil)
|
||||
|
||||
require.Equal(t, mime.MimeTypeH264.String(), selectAlternativeVideoCodec(p.enabledPublishCodecs))
|
||||
})
|
||||
|
||||
t.Run("h264 disabled leaves rtx only, fallback avoids rtx", func(t *testing.T) {
|
||||
p := newParticipant()
|
||||
disabled := &livekit.DisabledCodecs{Publish: []*livekit.Codec{{Mime: mime.MimeTypeH264.String()}}}
|
||||
p.setupEnabledCodecs([]*livekit.Codec{h264, rtx}, nil, disabled)
|
||||
|
||||
require.Len(t, p.enabledPublishCodecs, 1)
|
||||
require.True(t, mime.IsMimeTypeStringRTX(p.enabledPublishCodecs[0].Mime))
|
||||
|
||||
alt := selectAlternativeVideoCodec(p.enabledPublishCodecs)
|
||||
require.False(t, mime.IsMimeTypeStringRTX(alt), "fallback must not be rtx, got %q", alt)
|
||||
require.Equal(t, mime.MimeTypeVP8.String(), alt)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSupportsMoving(t *testing.T) {
|
||||
t.Run("current protocol version", func(t *testing.T) {
|
||||
p := newParticipantForTestWithOpts("test", &participantOpts{protocolVersion: types.CurrentProtocol})
|
||||
|
||||
@@ -906,6 +906,7 @@ func newRoomWithParticipants(t *testing.T, opts testRoomOpts) *Room {
|
||||
telemetry.NewTelemetryService(n, &telemetryfakes.FakeAnalyticsService{}),
|
||||
nil, nil, nil,
|
||||
)
|
||||
t.Cleanup(func() { rm.Close(types.RoomCloseReasonUnknown) })
|
||||
for i := 0; i < opts.num+opts.numHidden; i++ {
|
||||
identity := livekit.ParticipantIdentity(fmt.Sprintf("p%d", i))
|
||||
participant := NewMockParticipant(identity, opts.protocol, i >= opts.num, true, rm.LocalParticipantListener())
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/rtc/types"
|
||||
"github.com/livekit/livekit-server/pkg/rtc/types/typesfakes"
|
||||
"github.com/livekit/livekit-server/pkg/sfu/connectionquality"
|
||||
)
|
||||
|
||||
func NewMockParticipant(
|
||||
@@ -54,6 +55,11 @@ func NewMockParticipant(
|
||||
State: livekit.ParticipantInfo_JOINED,
|
||||
IsPublisher: publisher,
|
||||
}, utils.TimedVersion(0))
|
||||
p.GetConnectionQualityReturns(&livekit.ConnectionQualityInfo{
|
||||
ParticipantSid: sid,
|
||||
Quality: livekit.ConnectionQuality_EXCELLENT,
|
||||
Score: connectionquality.MaxMOS,
|
||||
})
|
||||
|
||||
p.SetMetadataCalls(func(m string) {
|
||||
participantListener.OnParticipantUpdate(p)
|
||||
|
||||
+14
-1
@@ -582,12 +582,25 @@ func NewPCTransport(params TransportParams) (*PCTransport, error) {
|
||||
Config: params.CongestionControlConfig.SendSideBWE,
|
||||
Logger: params.Logger,
|
||||
})
|
||||
switch pacer.PacerBehavior(params.CongestionControlConfig.SendSideBWEPacer) {
|
||||
switch behavior := pacer.PacerBehavior(params.CongestionControlConfig.SendSideBWEPacer); behavior {
|
||||
case pacer.PacerBehaviorPassThrough:
|
||||
t.pacer = pacer.NewPassThrough(params.Logger, t.bwe)
|
||||
case pacer.PacerBehaviorNoQueue:
|
||||
t.pacer = pacer.NewNoQueue(params.Logger, t.bwe)
|
||||
default:
|
||||
// leaky-bucket lands here: it is a recognized value, but LeakyBucket paces
|
||||
// to a bitrate set through Pacer.SetBitrate and nothing drives that from
|
||||
// the bandwidth estimate, so it would pace at a fixed rate and ignore
|
||||
// congestion. Unknown values are rejected by CongestionControlConfig.
|
||||
// Validate, so they only reach here from callers building TransportParams
|
||||
// directly.
|
||||
if behavior != "" {
|
||||
params.Logger.Warnw(
|
||||
"send side BWE pacer unavailable, falling back", nil,
|
||||
"pacerBehavior", behavior,
|
||||
"fallback", pacer.PacerBehaviorNoQueue,
|
||||
)
|
||||
}
|
||||
t.pacer = pacer.NewNoQueue(params.Logger, t.bwe)
|
||||
}
|
||||
} else {
|
||||
|
||||
+19
-10
@@ -60,8 +60,8 @@ func TestMissingAnswerDuringICERestart(t *testing.T) {
|
||||
handleICEExchange(t, transportA, transportB, handlerA, handlerB)
|
||||
|
||||
connectTransports(t, transportA, transportB, handlerA, handlerB, false, 1, 1)
|
||||
require.Equal(t, webrtc.ICEConnectionStateConnected, transportA.pc.ICEConnectionState())
|
||||
require.Equal(t, webrtc.ICEConnectionStateConnected, transportB.pc.ICEConnectionState())
|
||||
require.True(t, iceConnected(transportA.pc))
|
||||
require.True(t, iceConnected(transportB.pc))
|
||||
|
||||
var negotiationState atomic.Value
|
||||
transportA.OnNegotiationStateChanged(func(state transport.NegotiationState) {
|
||||
@@ -82,8 +82,8 @@ func TestMissingAnswerDuringICERestart(t *testing.T) {
|
||||
}, 10*time.Second, time.Millisecond*10, "transportA offer not received")
|
||||
|
||||
connectTransports(t, transportA, transportB, handlerA, handlerB, true, 1, 1)
|
||||
require.Equal(t, webrtc.ICEConnectionStateConnected, transportA.pc.ICEConnectionState())
|
||||
require.Equal(t, webrtc.ICEConnectionStateConnected, transportB.pc.ICEConnectionState())
|
||||
require.True(t, iceConnected(transportA.pc))
|
||||
require.True(t, iceConnected(transportB.pc))
|
||||
|
||||
transportA.Close()
|
||||
transportB.Close()
|
||||
@@ -270,8 +270,8 @@ func TestFirstOfferMissedDuringICERestart(t *testing.T) {
|
||||
|
||||
// ensure we are connected
|
||||
require.Eventually(t, func() bool {
|
||||
return transportA.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected &&
|
||||
transportB.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected &&
|
||||
return iceConnected(transportA.pc) &&
|
||||
iceConnected(transportB.pc) &&
|
||||
offerCount.Load() == 2
|
||||
}, testutils.ConnectTimeout, 10*time.Millisecond, "transport did not connect")
|
||||
|
||||
@@ -347,8 +347,8 @@ func TestFirstAnswerMissedDuringICERestart(t *testing.T) {
|
||||
|
||||
// ensure we are connected
|
||||
require.Eventually(t, func() bool {
|
||||
return transportA.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected &&
|
||||
transportB.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected &&
|
||||
return iceConnected(transportA.pc) &&
|
||||
iceConnected(transportB.pc) &&
|
||||
offerCount.Load() == 2
|
||||
}, testutils.ConnectTimeout, 10*time.Millisecond, "transport did not connect")
|
||||
|
||||
@@ -518,6 +518,15 @@ func TestFilteringCandidates(t *testing.T) {
|
||||
transport.Close()
|
||||
}
|
||||
|
||||
// iceConnected reports whether a peer connection's ICE has established. The
|
||||
// controlling agent (the offerer) advances Connected -> Completed once its
|
||||
// connectivity checks finish, so asserting exactly Connected races the poll
|
||||
// against that transition; both states mean the transport is up.
|
||||
func iceConnected(pc *webrtc.PeerConnection) bool {
|
||||
s := pc.ICEConnectionState()
|
||||
return s == webrtc.ICEConnectionStateConnected || s == webrtc.ICEConnectionStateCompleted
|
||||
}
|
||||
|
||||
func handleICEExchange(t *testing.T, a, b *PCTransport, ah, bh *transportfakes.FakeHandler) {
|
||||
ah.OnICECandidateCalls(func(candidate *webrtc.ICECandidate, target livekit.SignalTarget) error {
|
||||
if candidate == nil {
|
||||
@@ -563,7 +572,7 @@ func connectTransports(t *testing.T, offerer, answerer *PCTransport, offererHand
|
||||
}, 10*time.Second, time.Millisecond*10, fmt.Sprintf("offer count mismatch, expected: %d, actual: %d", expectedOfferCount, offerCount.Load()))
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
return offerer.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected
|
||||
return iceConnected(offerer.pc)
|
||||
}, 10*time.Second, time.Millisecond*10, "offerer did not become connected")
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
@@ -571,7 +580,7 @@ func connectTransports(t *testing.T, offerer, answerer *PCTransport, offererHand
|
||||
}, 10*time.Second, time.Millisecond*10, fmt.Sprintf("answer count mismatch, expected: %d, actual: %d", expectedAnswerCount, answerCount.Load()))
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
return answerer.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected
|
||||
return iceConnected(answerer.pc)
|
||||
}, 10*time.Second, time.Millisecond*10, "answerer did not become connected")
|
||||
|
||||
transportsConnected := untilTransportsConnected(offererHandler, answererHandler)
|
||||
|
||||
@@ -81,7 +81,9 @@ type IngressStore interface {
|
||||
type RoomAllocator interface {
|
||||
AutoCreateEnabled(ctx context.Context) bool
|
||||
SelectRoomNode(ctx context.Context, roomName livekit.RoomName, nodeID livekit.NodeID) error
|
||||
CreateRoom(ctx context.Context, req *livekit.CreateRoomRequest, isExplicit bool) (*livekit.Room, *livekit.RoomInternal, bool, error)
|
||||
// CreateRoom also returns the request with its room preset applied,
|
||||
// or req unchanged when the implementation does not resolve presets
|
||||
CreateRoom(ctx context.Context, req *livekit.CreateRoomRequest, isExplicit bool) (*livekit.Room, *livekit.RoomInternal, *livekit.CreateRoomRequest, bool, error)
|
||||
ValidateCreateRoom(ctx context.Context, roomName livekit.RoomName) error
|
||||
}
|
||||
|
||||
|
||||
@@ -113,7 +113,7 @@ func (s *IOInfoService) EvaluateSIPDispatchRules(ctx context.Context, req *rpc.E
|
||||
if e := (*sip.ErrNoDispatchMatched)(nil); errors.As(err, &e) {
|
||||
return &rpc.EvaluateSIPDispatchRulesResponse{
|
||||
SipTrunkId: trunkID,
|
||||
Result: rpc.SIPDispatchResult_DROP,
|
||||
Result: rpc.SIPDispatchResult_REJECT,
|
||||
}, nil
|
||||
}
|
||||
return nil, err
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/service"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/rpc"
|
||||
"github.com/livekit/psrpc/pkg/bus/redisbus"
|
||||
)
|
||||
|
||||
@@ -121,3 +122,18 @@ func TestSIPRuleSelect(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSIPDispatchNoRuleRejects(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, rs := ioStoreDocker(t)
|
||||
require.NoError(t, rs.StoreSIPInboundTrunk(ctx, &livekit.SIPInboundTrunkInfo{SipTrunkId: "A", Numbers: []string{"+1000"}}))
|
||||
|
||||
for number, trunk := range map[string]string{"+1000": "A", "+2000": ""} {
|
||||
resp, err := s.EvaluateSIPDispatchRules(ctx, &rpc.EvaluateSIPDispatchRulesRequest{
|
||||
Call: &rpc.SIPCall{SourceIp: "1.1.1.1", From: &livekit.SIPUri{User: "+3000"}, To: &livekit.SIPUri{User: number}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, rpc.SIPDispatchResult_REJECT, resp.Result, number)
|
||||
require.Equal(t, trunk, resp.SipTrunkId)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,10 +59,10 @@ func (r *StandardRoomAllocator) AutoCreateEnabled(context.Context) bool {
|
||||
|
||||
// CreateRoom creates a new room from a request and allocates it to a node to handle
|
||||
// it'll also monitor its state, and cleans it up when appropriate
|
||||
func (r *StandardRoomAllocator) CreateRoom(ctx context.Context, req *livekit.CreateRoomRequest, isExplicit bool) (*livekit.Room, *livekit.RoomInternal, bool, error) {
|
||||
func (r *StandardRoomAllocator) CreateRoom(ctx context.Context, req *livekit.CreateRoomRequest, isExplicit bool) (*livekit.Room, *livekit.RoomInternal, *livekit.CreateRoomRequest, bool, error) {
|
||||
token, err := r.roomStore.LockRoom(ctx, livekit.RoomName(req.Name), 5*time.Second)
|
||||
if err != nil {
|
||||
return nil, nil, false, err
|
||||
return nil, nil, nil, false, err
|
||||
}
|
||||
defer func() {
|
||||
_ = r.roomStore.UnlockRoom(ctx, livekit.RoomName(req.Name), token)
|
||||
@@ -84,12 +84,12 @@ func (r *StandardRoomAllocator) CreateRoom(ctx context.Context, req *livekit.Cre
|
||||
internal = &livekit.RoomInternal{}
|
||||
applyDefaultRoomConfig(rm, internal, &r.config.Room)
|
||||
} else if err != nil {
|
||||
return nil, nil, false, err
|
||||
return nil, nil, nil, false, err
|
||||
}
|
||||
|
||||
req, err = r.applyNamedRoomConfiguration(req)
|
||||
if err != nil {
|
||||
return nil, nil, false, err
|
||||
return nil, nil, nil, false, err
|
||||
}
|
||||
|
||||
if req.EmptyTimeout > 0 {
|
||||
@@ -127,10 +127,10 @@ func (r *StandardRoomAllocator) CreateRoom(ctx context.Context, req *livekit.Cre
|
||||
}
|
||||
|
||||
if err = r.roomStore.StoreRoom(ctx, rm, internal); err != nil {
|
||||
return nil, nil, false, err
|
||||
return nil, nil, nil, false, err
|
||||
}
|
||||
|
||||
return rm, internal, created, nil
|
||||
return rm, internal, req, created, nil
|
||||
}
|
||||
|
||||
func (r *StandardRoomAllocator) SelectRoomNode(ctx context.Context, roomName livekit.RoomName, nodeID livekit.NodeID) error {
|
||||
|
||||
@@ -39,12 +39,44 @@ func TestCreateRoom(t *testing.T) {
|
||||
|
||||
ra, conf := newTestRoomAllocator(t, conf, node.Clone())
|
||||
|
||||
room, _, _, err := ra.CreateRoom(context.Background(), &livekit.CreateRoomRequest{Name: "myroom"}, true)
|
||||
room, _, _, _, err := ra.CreateRoom(context.Background(), &livekit.CreateRoomRequest{Name: "myroom"}, true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, conf.Room.EmptyTimeout, room.EmptyTimeout)
|
||||
require.Equal(t, conf.Room.DepartureTimeout, room.DepartureTimeout)
|
||||
require.NotEmpty(t, room.EnabledCodecs)
|
||||
})
|
||||
|
||||
t.Run("return the request with the room preset applied", func(t *testing.T) {
|
||||
conf, err := config.NewConfig(`
|
||||
room:
|
||||
room_configurations:
|
||||
record:
|
||||
egress:
|
||||
room:
|
||||
layout: grid
|
||||
`, true, nil, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
node, err := routing.NewLocalNode(conf)
|
||||
require.NoError(t, err)
|
||||
|
||||
ra, conf := newTestRoomAllocator(t, conf, node.Clone())
|
||||
|
||||
// without a preset, the request itself is returned
|
||||
req := &livekit.CreateRoomRequest{Name: "myroom"}
|
||||
_, _, applied, _, err := ra.CreateRoom(context.Background(), req, true)
|
||||
require.NoError(t, err)
|
||||
require.Same(t, req, applied)
|
||||
|
||||
// with a preset, a copy with the preset applied is returned,
|
||||
// leaving both the request and the preset unchanged
|
||||
req = &livekit.CreateRoomRequest{Name: "myroom", RoomPreset: "record"}
|
||||
_, _, applied, _, err = ra.CreateRoom(context.Background(), req, true)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, req.Egress)
|
||||
require.Equal(t, "grid", applied.GetEgress().GetRoom().GetLayout())
|
||||
require.NotSame(t, conf.Room.RoomConfigurations["record"].Egress.Room, applied.Egress.Room)
|
||||
})
|
||||
}
|
||||
|
||||
func SelectRoomNode(t *testing.T) {
|
||||
|
||||
@@ -656,7 +656,9 @@ func (r *RoomManager) getOrCreateRoom(ctx context.Context, createRoom *livekit.C
|
||||
}
|
||||
|
||||
// create new room, get details first
|
||||
ri, internal, created, err := r.roomAllocator.CreateRoom(ctx, createRoom, true)
|
||||
// createRoom is reassigned to the request with the room preset applied, so that a room
|
||||
// composite egress from the preset, which RoomInternal has no field for, is started
|
||||
ri, internal, createRoom, created, err := r.roomAllocator.CreateRoom(ctx, createRoom, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -733,6 +735,11 @@ func (r *RoomManager) getOrCreateRoom(ctx context.Context, createRoom *livekit.C
|
||||
prometheus.RoomStarted()
|
||||
|
||||
if created && createRoom.GetEgress().GetRoom() != nil {
|
||||
if r.egressLauncher == nil {
|
||||
newRoom.Release()
|
||||
return nil, ErrEgressNotConnected
|
||||
}
|
||||
|
||||
// ensure room name matches
|
||||
createRoom.Egress.Room.RoomName = createRoom.Name
|
||||
_, err = r.egressLauncher.StartEgress(ctx, &rpc.StartEgressRequest{
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
// Copyright 2026 LiveKit, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package service_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/livekit/mediatransportutil/pkg/rtcconfig"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/rpc"
|
||||
"github.com/livekit/protocol/utils"
|
||||
"github.com/livekit/psrpc"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/config"
|
||||
"github.com/livekit/livekit-server/pkg/routing"
|
||||
"github.com/livekit/livekit-server/pkg/routing/routingfakes"
|
||||
"github.com/livekit/livekit-server/pkg/rtc"
|
||||
"github.com/livekit/livekit-server/pkg/service"
|
||||
"github.com/livekit/livekit-server/pkg/telemetry/telemetryfakes"
|
||||
)
|
||||
|
||||
// fakeEgressLauncher records the egress start requests it receives.
|
||||
type fakeEgressLauncher struct {
|
||||
mu sync.Mutex
|
||||
started []*rpc.StartEgressRequest
|
||||
}
|
||||
|
||||
func (f *fakeEgressLauncher) StartEgress(_ context.Context, req *rpc.StartEgressRequest) (*livekit.EgressInfo, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.started = append(f.started, req)
|
||||
return &livekit.EgressInfo{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeEgressLauncher) StopEgress(context.Context, *livekit.StopEgressRequest) (*livekit.EgressInfo, error) {
|
||||
return &livekit.EgressInfo{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeEgressLauncher) roomCompositeRoomNames() []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
var names []string
|
||||
for _, req := range f.started {
|
||||
if rc := req.GetRoomComposite(); rc != nil {
|
||||
names = append(names, rc.RoomName)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func newTestRoomManager(t *testing.T, conf *config.Config, egressLauncher rtc.EgressLauncher) *service.RoomManager {
|
||||
// no fixed RTC ports, so that the test does not bind the defaults
|
||||
conf.RTC.TCPPort = 0
|
||||
conf.RTC.UDPPort = rtcconfig.PortRange{}
|
||||
|
||||
node, err := routing.NewLocalNode(conf)
|
||||
require.NoError(t, err)
|
||||
router := &routingfakes.FakeRouter{}
|
||||
router.GetNodeForRoomReturns(node.Clone(), nil)
|
||||
|
||||
store := service.NewLocalStore()
|
||||
ra, err := service.NewRoomAllocator(conf, router, store)
|
||||
require.NoError(t, err)
|
||||
|
||||
rm, err := service.NewLocalRoomManager(
|
||||
conf,
|
||||
store,
|
||||
node,
|
||||
router,
|
||||
ra,
|
||||
&telemetryfakes.FakeTelemetryService{},
|
||||
nil,
|
||||
store,
|
||||
egressLauncher,
|
||||
utils.NewDefaultTimedVersionGenerator(),
|
||||
nil,
|
||||
psrpc.NewLocalMessageBus(),
|
||||
nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(rm.Stop)
|
||||
return rm
|
||||
}
|
||||
|
||||
func TestRoomCompositeEgressOnCreateRoom(t *testing.T) {
|
||||
t.Run("from request", func(t *testing.T) {
|
||||
conf, err := config.NewConfig("", true, nil, nil)
|
||||
require.NoError(t, err)
|
||||
launcher := &fakeEgressLauncher{}
|
||||
rm := newTestRoomManager(t, conf, launcher)
|
||||
|
||||
_, err = rm.CreateRoom(context.Background(), &livekit.CreateRoomRequest{
|
||||
Name: "room-a",
|
||||
Egress: &livekit.RoomEgress{
|
||||
Room: &livekit.RoomCompositeEgressRequest{
|
||||
Layout: "grid",
|
||||
FileOutputs: []*livekit.EncodedFileOutput{{Filepath: "recordings/{room_name}.mp4"}},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"room-a"}, launcher.roomCompositeRoomNames())
|
||||
})
|
||||
|
||||
t.Run("from room preset", func(t *testing.T) {
|
||||
conf, err := config.NewConfig(roomPresetConfig, true, nil, nil)
|
||||
require.NoError(t, err)
|
||||
launcher := &fakeEgressLauncher{}
|
||||
rm := newTestRoomManager(t, conf, launcher)
|
||||
|
||||
for _, name := range []string{"room-a", "room-b"} {
|
||||
_, err = rm.CreateRoom(context.Background(), &livekit.CreateRoomRequest{
|
||||
Name: name,
|
||||
RoomPreset: "record",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// each room records itself, and the preset is left as configured
|
||||
require.Equal(t, []string{"room-a", "room-b"}, launcher.roomCompositeRoomNames())
|
||||
require.Empty(t, conf.Room.RoomConfigurations["record"].GetEgress().GetRoom().GetRoomName())
|
||||
})
|
||||
|
||||
t.Run("from room preset when a session starts", func(t *testing.T) {
|
||||
conf, err := config.NewConfig(roomPresetConfig, true, nil, nil)
|
||||
require.NoError(t, err)
|
||||
launcher := &fakeEgressLauncher{}
|
||||
rm := newTestRoomManager(t, conf, launcher)
|
||||
|
||||
// the join and WHIP paths create the room through StartSession, with the
|
||||
// token's room preset; without an identity only the room is created
|
||||
err = rm.StartSession(context.Background(), routing.ParticipantInit{
|
||||
CreateRoom: &livekit.CreateRoomRequest{
|
||||
Name: "room-a",
|
||||
RoomPreset: "record",
|
||||
},
|
||||
}, nil, nil, false)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"room-a"}, launcher.roomCompositeRoomNames())
|
||||
})
|
||||
|
||||
t.Run("from room preset without an egress launcher", func(t *testing.T) {
|
||||
conf, err := config.NewConfig(roomPresetConfig, true, nil, nil)
|
||||
require.NoError(t, err)
|
||||
rm := newTestRoomManager(t, conf, nil)
|
||||
|
||||
_, err = rm.CreateRoom(context.Background(), &livekit.CreateRoomRequest{
|
||||
Name: "room-a",
|
||||
RoomPreset: "record",
|
||||
})
|
||||
require.ErrorIs(t, err, service.ErrEgressNotConnected)
|
||||
})
|
||||
}
|
||||
|
||||
const roomPresetConfig = `
|
||||
room:
|
||||
room_configurations:
|
||||
record:
|
||||
egress:
|
||||
room:
|
||||
layout: grid
|
||||
file_outputs:
|
||||
- filepath: recordings/{room_name}.mp4
|
||||
`
|
||||
@@ -21,7 +21,7 @@ type FakeRoomAllocator struct {
|
||||
autoCreateEnabledReturnsOnCall map[int]struct {
|
||||
result1 bool
|
||||
}
|
||||
CreateRoomStub func(context.Context, *livekit.CreateRoomRequest, bool) (*livekit.Room, *livekit.RoomInternal, bool, error)
|
||||
CreateRoomStub func(context.Context, *livekit.CreateRoomRequest, bool) (*livekit.Room, *livekit.RoomInternal, *livekit.CreateRoomRequest, bool, error)
|
||||
createRoomMutex sync.RWMutex
|
||||
createRoomArgsForCall []struct {
|
||||
arg1 context.Context
|
||||
@@ -31,14 +31,16 @@ type FakeRoomAllocator struct {
|
||||
createRoomReturns struct {
|
||||
result1 *livekit.Room
|
||||
result2 *livekit.RoomInternal
|
||||
result3 bool
|
||||
result4 error
|
||||
result3 *livekit.CreateRoomRequest
|
||||
result4 bool
|
||||
result5 error
|
||||
}
|
||||
createRoomReturnsOnCall map[int]struct {
|
||||
result1 *livekit.Room
|
||||
result2 *livekit.RoomInternal
|
||||
result3 bool
|
||||
result4 error
|
||||
result3 *livekit.CreateRoomRequest
|
||||
result4 bool
|
||||
result5 error
|
||||
}
|
||||
SelectRoomNodeStub func(context.Context, livekit.RoomName, livekit.NodeID) error
|
||||
selectRoomNodeMutex sync.RWMutex
|
||||
@@ -130,7 +132,7 @@ func (fake *FakeRoomAllocator) AutoCreateEnabledReturnsOnCall(i int, result1 boo
|
||||
}{result1}
|
||||
}
|
||||
|
||||
func (fake *FakeRoomAllocator) CreateRoom(arg1 context.Context, arg2 *livekit.CreateRoomRequest, arg3 bool) (*livekit.Room, *livekit.RoomInternal, bool, error) {
|
||||
func (fake *FakeRoomAllocator) CreateRoom(arg1 context.Context, arg2 *livekit.CreateRoomRequest, arg3 bool) (*livekit.Room, *livekit.RoomInternal, *livekit.CreateRoomRequest, bool, error) {
|
||||
fake.createRoomMutex.Lock()
|
||||
ret, specificReturn := fake.createRoomReturnsOnCall[len(fake.createRoomArgsForCall)]
|
||||
fake.createRoomArgsForCall = append(fake.createRoomArgsForCall, struct {
|
||||
@@ -146,9 +148,9 @@ func (fake *FakeRoomAllocator) CreateRoom(arg1 context.Context, arg2 *livekit.Cr
|
||||
return stub(arg1, arg2, arg3)
|
||||
}
|
||||
if specificReturn {
|
||||
return ret.result1, ret.result2, ret.result3, ret.result4
|
||||
return ret.result1, ret.result2, ret.result3, ret.result4, ret.result5
|
||||
}
|
||||
return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3, fakeReturns.result4
|
||||
return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3, fakeReturns.result4, fakeReturns.result5
|
||||
}
|
||||
|
||||
func (fake *FakeRoomAllocator) CreateRoomCallCount() int {
|
||||
@@ -157,7 +159,7 @@ func (fake *FakeRoomAllocator) CreateRoomCallCount() int {
|
||||
return len(fake.createRoomArgsForCall)
|
||||
}
|
||||
|
||||
func (fake *FakeRoomAllocator) CreateRoomCalls(stub func(context.Context, *livekit.CreateRoomRequest, bool) (*livekit.Room, *livekit.RoomInternal, bool, error)) {
|
||||
func (fake *FakeRoomAllocator) CreateRoomCalls(stub func(context.Context, *livekit.CreateRoomRequest, bool) (*livekit.Room, *livekit.RoomInternal, *livekit.CreateRoomRequest, bool, error)) {
|
||||
fake.createRoomMutex.Lock()
|
||||
defer fake.createRoomMutex.Unlock()
|
||||
fake.CreateRoomStub = stub
|
||||
@@ -170,19 +172,20 @@ func (fake *FakeRoomAllocator) CreateRoomArgsForCall(i int) (context.Context, *l
|
||||
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
|
||||
}
|
||||
|
||||
func (fake *FakeRoomAllocator) CreateRoomReturns(result1 *livekit.Room, result2 *livekit.RoomInternal, result3 bool, result4 error) {
|
||||
func (fake *FakeRoomAllocator) CreateRoomReturns(result1 *livekit.Room, result2 *livekit.RoomInternal, result3 *livekit.CreateRoomRequest, result4 bool, result5 error) {
|
||||
fake.createRoomMutex.Lock()
|
||||
defer fake.createRoomMutex.Unlock()
|
||||
fake.CreateRoomStub = nil
|
||||
fake.createRoomReturns = struct {
|
||||
result1 *livekit.Room
|
||||
result2 *livekit.RoomInternal
|
||||
result3 bool
|
||||
result4 error
|
||||
}{result1, result2, result3, result4}
|
||||
result3 *livekit.CreateRoomRequest
|
||||
result4 bool
|
||||
result5 error
|
||||
}{result1, result2, result3, result4, result5}
|
||||
}
|
||||
|
||||
func (fake *FakeRoomAllocator) CreateRoomReturnsOnCall(i int, result1 *livekit.Room, result2 *livekit.RoomInternal, result3 bool, result4 error) {
|
||||
func (fake *FakeRoomAllocator) CreateRoomReturnsOnCall(i int, result1 *livekit.Room, result2 *livekit.RoomInternal, result3 *livekit.CreateRoomRequest, result4 bool, result5 error) {
|
||||
fake.createRoomMutex.Lock()
|
||||
defer fake.createRoomMutex.Unlock()
|
||||
fake.CreateRoomStub = nil
|
||||
@@ -190,16 +193,18 @@ func (fake *FakeRoomAllocator) CreateRoomReturnsOnCall(i int, result1 *livekit.R
|
||||
fake.createRoomReturnsOnCall = make(map[int]struct {
|
||||
result1 *livekit.Room
|
||||
result2 *livekit.RoomInternal
|
||||
result3 bool
|
||||
result4 error
|
||||
result3 *livekit.CreateRoomRequest
|
||||
result4 bool
|
||||
result5 error
|
||||
})
|
||||
}
|
||||
fake.createRoomReturnsOnCall[i] = struct {
|
||||
result1 *livekit.Room
|
||||
result2 *livekit.RoomInternal
|
||||
result3 bool
|
||||
result4 error
|
||||
}{result1, result2, result3, result4}
|
||||
result3 *livekit.CreateRoomRequest
|
||||
result4 bool
|
||||
result5 error
|
||||
}{result1, result2, result3, result4, result5}
|
||||
}
|
||||
|
||||
func (fake *FakeRoomAllocator) SelectRoomNode(arg1 context.Context, arg2 livekit.RoomName, arg3 livekit.NodeID) error {
|
||||
|
||||
@@ -68,13 +68,14 @@ func (s *DataStats) ToProtoActive() *livekit.RTPStats {
|
||||
if duration > s.params.WindowDuration.Nanoseconds() {
|
||||
return &livekit.RTPStats{}
|
||||
}
|
||||
seconds := float64(duration) / 1e9
|
||||
|
||||
return &livekit.RTPStats{
|
||||
StartTime: timestamppb.New(time.Unix(s.windowStart/1e9, s.windowStart%1e9)),
|
||||
EndTime: timestamppb.New(time.Unix(0, now)),
|
||||
Duration: float64(duration / 1e9),
|
||||
Duration: seconds,
|
||||
Bytes: uint64(s.windowBytes),
|
||||
Bitrate: float64(s.windowBytes) * 8 / float64(duration) / 1e9,
|
||||
Bitrate: float64(s.windowBytes) * 8 / seconds,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,3 +51,16 @@ func TestDataStats(t *testing.T) {
|
||||
require.EqualValues(t, 100, r.Bytes)
|
||||
require.NotZero(t, r.Bitrate)
|
||||
}
|
||||
|
||||
func TestDataStatsActiveBitrateAndDuration(t *testing.T) {
|
||||
stats := NewDataStats(DataStatsParam{WindowDuration: 10 * time.Second})
|
||||
|
||||
// 1000 bytes over a 1.5 second window is 8000 bits / 1.5 s
|
||||
stats.windowStart = time.Now().Add(-1500 * time.Millisecond).UnixNano()
|
||||
stats.windowBytes = 1000
|
||||
|
||||
r := stats.ToProtoActive()
|
||||
require.EqualValues(t, 1000, r.Bytes)
|
||||
require.InDelta(t, 1.5, r.Duration, 0.1)
|
||||
require.InDelta(t, 8000/1.5, r.Bitrate, 0.1*8000/1.5)
|
||||
}
|
||||
|
||||
+24
-16
@@ -1079,9 +1079,28 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) int32 {
|
||||
SSRC: d.ssrc,
|
||||
})
|
||||
|
||||
pacerPacket := pacer.PacketFactory.Get().(*pacer.Packet)
|
||||
*pacerPacket = pacer.Packet{
|
||||
Header: hdr,
|
||||
HeaderPool: RTPHeaderFactory,
|
||||
Payload: payload,
|
||||
ProbeClusterId: ccutils.ProbeClusterId(d.probeClusterId.Load()),
|
||||
AbsSendTimeExtID: uint8(d.absSendTimeExtID),
|
||||
TransportWideExtID: uint8(d.transportWideExtID),
|
||||
WriteStream: d.writeStream,
|
||||
Pool: PacketFactory,
|
||||
PoolEntity: poolEntity,
|
||||
}
|
||||
|
||||
// add extensions
|
||||
if d.dependencyDescriptorExtID != 0 && tp.ddBytes != nil {
|
||||
hdr.SetExtension(uint8(d.dependencyDescriptorExtID), tp.ddBytes)
|
||||
//
|
||||
// the header refers to the descriptor until the pacer marshals it, so hold it in the pacer packet, which one send owns
|
||||
ddBytes := tp.ddBytesSpill
|
||||
if inline := tp.ddInline(); ddBytes == nil && len(inline) != 0 {
|
||||
ddBytes = pacerPacket.HoldExtension(inline)
|
||||
}
|
||||
if d.dependencyDescriptorExtID != 0 && len(ddBytes) != 0 {
|
||||
hdr.SetExtension(uint8(d.dependencyDescriptorExtID), ddBytes)
|
||||
}
|
||||
if d.playoutDelayExtID != 0 && d.playoutDelay != nil {
|
||||
if val := d.playoutDelay.GetDelayExtension(hdr.SequenceNumber); val != nil {
|
||||
@@ -1128,6 +1147,7 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) int32 {
|
||||
}
|
||||
d.addDummyExtensions(hdr)
|
||||
|
||||
// the sequencer copies the descriptor, which has to happen before Enqueue frees the scratch
|
||||
if d.sequencer != nil {
|
||||
d.sequencer.push(
|
||||
extPkt.Arrival,
|
||||
@@ -1138,13 +1158,14 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) int32 {
|
||||
int8(layer),
|
||||
payload[:len(codecBytes)],
|
||||
tp.incomingHeaderSize,
|
||||
tp.ddBytes,
|
||||
ddBytes,
|
||||
actBytes,
|
||||
trailerStripped,
|
||||
)
|
||||
}
|
||||
|
||||
headerSize := hdr.MarshalSize()
|
||||
pacerPacket.HeaderSize = headerSize
|
||||
d.rtpStats.Update(
|
||||
extPkt.Arrival,
|
||||
tp.rtp.extSequenceNumber,
|
||||
@@ -1155,19 +1176,6 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) int32 {
|
||||
0,
|
||||
extPkt.IsOutOfOrder,
|
||||
)
|
||||
pacerPacket := pacer.PacketFactory.Get().(*pacer.Packet)
|
||||
*pacerPacket = pacer.Packet{
|
||||
Header: hdr,
|
||||
HeaderPool: RTPHeaderFactory,
|
||||
HeaderSize: headerSize,
|
||||
Payload: payload,
|
||||
ProbeClusterId: ccutils.ProbeClusterId(d.probeClusterId.Load()),
|
||||
AbsSendTimeExtID: uint8(d.absSendTimeExtID),
|
||||
TransportWideExtID: uint8(d.transportWideExtID),
|
||||
WriteStream: d.writeStream,
|
||||
Pool: PacketFactory,
|
||||
PoolEntity: poolEntity,
|
||||
}
|
||||
d.pacer.Enqueue(pacerPacket)
|
||||
|
||||
if extPkt.IsKeyFrame {
|
||||
|
||||
+11
-2
@@ -199,7 +199,9 @@ type TranslationParams struct {
|
||||
isResuming bool
|
||||
isSwitching bool
|
||||
rtp TranslationParamsRTP
|
||||
ddBytes []byte
|
||||
ddBytes [dd.MaxInlineExtensionSize]byte
|
||||
ddBytesLen int
|
||||
ddBytesSpill []byte
|
||||
incomingHeaderSize int
|
||||
codecBytes [codecmunger.MaxHeaderSize]byte
|
||||
codecBytesLen int
|
||||
@@ -213,6 +215,13 @@ func (tp *TranslationParams) codecHeader() []byte {
|
||||
return tp.codecBytes[:tp.codecBytesLen]
|
||||
}
|
||||
|
||||
// ddInline returns the dependency descriptor extension held inline. It points
|
||||
// into tp, so it has to be copied before it is attached to anything that
|
||||
// outlives the write.
|
||||
func (tp *TranslationParams) ddInline() []byte {
|
||||
return tp.ddBytes[:tp.ddBytesLen]
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
type refInfo struct {
|
||||
@@ -2190,7 +2199,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
|
||||
}
|
||||
tp.isResuming = result.IsResuming
|
||||
tp.isSwitching = result.IsSwitching
|
||||
tp.ddBytes = result.DependencyDescriptorExtension
|
||||
tp.ddBytes, tp.ddBytesLen, tp.ddBytesSpill = result.DDBytes, result.DDBytesLen, result.DDBytesSpill
|
||||
tp.marker = result.RTPMarker
|
||||
tp.isEndOfLayerFrame = f.isEndOfLayerFrame(extPkt)
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/buffer"
|
||||
"github.com/livekit/livekit-server/pkg/sfu/codecmunger"
|
||||
"github.com/livekit/livekit-server/pkg/sfu/pacer"
|
||||
dd "github.com/livekit/livekit-server/pkg/sfu/rtpextension/dependencydescriptor"
|
||||
"github.com/livekit/livekit-server/pkg/sfu/testutils"
|
||||
)
|
||||
@@ -2261,3 +2262,13 @@ func codecHeaderOf(b []byte) [codecmunger.MaxHeaderSize]byte {
|
||||
copy(hdr[:], b)
|
||||
return hdr
|
||||
}
|
||||
|
||||
// WriteRTP holds the dependency descriptor in pacer scratch sized to pion's one
|
||||
// byte extension profile payload cap, which has to be the inline size
|
||||
// TranslationParams carries, or descriptors would take the heap copy fallback
|
||||
func TestPacerScratchFitsInlineDependencyDescriptor(t *testing.T) {
|
||||
p := &pacer.Packet{}
|
||||
|
||||
require.Len(t, p.HoldExtension(make([]byte, dd.MaxInlineExtensionSize)), dd.MaxInlineExtensionSize)
|
||||
require.Nil(t, p.HoldExtension(make([]byte, dd.MaxInlineExtensionSize+1)))
|
||||
}
|
||||
|
||||
+122
-61
@@ -1,7 +1,7 @@
|
||||
package sfu
|
||||
|
||||
import (
|
||||
"math"
|
||||
"math/bits"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -13,6 +13,12 @@ import (
|
||||
const (
|
||||
cHighForwardingLatency = 20 * time.Millisecond
|
||||
cSkewFactor = 10
|
||||
|
||||
// forwardLatencyPercentile is the transit quantile reported as the node's
|
||||
// forwarding latency and read by the overload controller. p90 tracks a broad
|
||||
// slowdown but ignores the sparse tail (a few packets stalled on goroutine
|
||||
// scheduling), which shedding cannot fix.
|
||||
forwardLatencyPercentile = 0.90
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -94,32 +100,86 @@ func (b *forwardSampleBuffer) takeDropped() uint64 {
|
||||
return b.dropped.Swap(0)
|
||||
}
|
||||
|
||||
// forwardSummary is a mergeable summary of forwarding transit over an interval.
|
||||
// The sum of squares is kept in microseconds so it does not overflow int64.
|
||||
type forwardSummary struct {
|
||||
count int64
|
||||
sumUs int64
|
||||
sumSqUs int64
|
||||
minNs int64
|
||||
maxNs int64
|
||||
// forwardSummary is a mergeable histogram of forwarding transit over an
|
||||
// interval. Each power-of-two octave [2^e, 2^(e+1)) us is split into
|
||||
// forwardHistSub linear sub-buckets, and each bucket keeps the observed
|
||||
// [min, max] of the samples in it. A percentile interpolates within the
|
||||
// crossing bucket's observed range rather than its nominal edges, so the
|
||||
// estimate never leaves the samples and is exact when a bucket's samples
|
||||
// cluster -- which keeps it accurate near an overload threshold that falls
|
||||
// mid-bucket, without needing threshold-aware boundaries. Two summaries merge
|
||||
// by adding their buckets, so the percentile covers the whole report window,
|
||||
// and a few stalled packets (e.g. from goroutine scheduling latency) cannot
|
||||
// drag it the way a mean does.
|
||||
const (
|
||||
forwardHistSub = 8 // linear sub-buckets per octave
|
||||
forwardHistOctaves = 27 // up to 2^27 us (~134 s)
|
||||
forwardHistBuckets = forwardHistOctaves * forwardHistSub // 216
|
||||
)
|
||||
|
||||
// bucketStat is one bucket: how many samples fell in it and their observed
|
||||
// transit range in nanoseconds.
|
||||
type bucketStat struct {
|
||||
count int64
|
||||
minNs int64
|
||||
maxNs int64
|
||||
}
|
||||
|
||||
func (s forwardSummary) addSample(transitNs int64) forwardSummary {
|
||||
us := transitNs / 1000
|
||||
if s.count == 0 {
|
||||
return forwardSummary{count: 1, sumUs: us, sumSqUs: us * us, minNs: transitNs, maxNs: transitNs}
|
||||
func (b *bucketStat) add(transitNs int64) {
|
||||
if b.count == 0 {
|
||||
b.minNs, b.maxNs = transitNs, transitNs
|
||||
} else {
|
||||
b.minNs = min(b.minNs, transitNs)
|
||||
b.maxNs = max(b.maxNs, transitNs)
|
||||
}
|
||||
b.count++
|
||||
}
|
||||
|
||||
func (b *bucketStat) mergeIn(o bucketStat) {
|
||||
if o.count == 0 {
|
||||
return
|
||||
}
|
||||
if b.count == 0 {
|
||||
*b = o
|
||||
return
|
||||
}
|
||||
b.count += o.count
|
||||
b.minNs = min(b.minNs, o.minNs)
|
||||
b.maxNs = max(b.maxNs, o.maxNs)
|
||||
}
|
||||
|
||||
type forwardSummary struct {
|
||||
count int64
|
||||
minNs int64
|
||||
maxNs int64
|
||||
buckets [forwardHistBuckets]bucketStat
|
||||
}
|
||||
|
||||
// forwardBucket returns the bucket index for a transit in nanoseconds: the
|
||||
// octave floor(log2(us)) times forwardHistSub, plus the linear sub-bucket
|
||||
// within the octave.
|
||||
func forwardBucket(transitNs int64) int {
|
||||
us := transitNs / 1000
|
||||
if us <= 0 {
|
||||
return 0
|
||||
}
|
||||
e := bits.Len64(uint64(us)) - 1 // floor(log2(us)), us >= 1 so e >= 0
|
||||
if e >= forwardHistOctaves {
|
||||
return forwardHistBuckets - 1
|
||||
}
|
||||
octave := int64(1) << e
|
||||
return e*forwardHistSub + int((us-octave)*forwardHistSub/octave)
|
||||
}
|
||||
|
||||
func (s *forwardSummary) addSample(transitNs int64) {
|
||||
if s.count == 0 {
|
||||
s.minNs, s.maxNs = transitNs, transitNs
|
||||
} else {
|
||||
s.minNs = min(s.minNs, transitNs)
|
||||
s.maxNs = max(s.maxNs, transitNs)
|
||||
}
|
||||
s.count++
|
||||
s.sumUs += us
|
||||
s.sumSqUs += us * us
|
||||
if transitNs < s.minNs {
|
||||
s.minNs = transitNs
|
||||
}
|
||||
if transitNs > s.maxNs {
|
||||
s.maxNs = transitNs
|
||||
}
|
||||
return s
|
||||
s.buckets[forwardBucket(transitNs)].add(transitNs)
|
||||
}
|
||||
|
||||
func (s forwardSummary) merge(o forwardSummary) forwardSummary {
|
||||
@@ -129,35 +189,36 @@ func (s forwardSummary) merge(o forwardSummary) forwardSummary {
|
||||
if s.count == 0 {
|
||||
return o
|
||||
}
|
||||
return forwardSummary{
|
||||
count: s.count + o.count,
|
||||
sumUs: s.sumUs + o.sumUs,
|
||||
sumSqUs: s.sumSqUs + o.sumSqUs,
|
||||
minNs: min(s.minNs, o.minNs),
|
||||
maxNs: max(s.maxNs, o.maxNs),
|
||||
s.count += o.count
|
||||
s.minNs = min(s.minNs, o.minNs)
|
||||
s.maxNs = max(s.maxNs, o.maxNs)
|
||||
for i := range s.buckets {
|
||||
s.buckets[i].mergeIn(o.buckets[i])
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (s forwardSummary) meanStdDev() (mean, stdDev time.Duration) {
|
||||
// percentile returns the p-quantile (0..1) of transit, interpolated within the
|
||||
// observed [min, max] of the bucket the quantile falls in.
|
||||
func (s forwardSummary) percentile(p float64) time.Duration {
|
||||
if s.count == 0 {
|
||||
return 0, 0
|
||||
return 0
|
||||
}
|
||||
|
||||
meanUs := float64(s.sumUs) / float64(s.count)
|
||||
mean = time.Duration(meanUs * float64(time.Microsecond))
|
||||
if s.count < 2 {
|
||||
return mean, 0
|
||||
target := p * float64(s.count)
|
||||
var cum float64
|
||||
for i := range s.buckets {
|
||||
b := s.buckets[i]
|
||||
c := float64(b.count)
|
||||
if c == 0 {
|
||||
continue
|
||||
}
|
||||
if cum+c >= target {
|
||||
lo, hi := float64(b.minNs), float64(b.maxNs)
|
||||
return time.Duration(lo + (hi-lo)*(target-cum)/c)
|
||||
}
|
||||
cum += c
|
||||
}
|
||||
|
||||
// sample variance (divisor count-1)
|
||||
m2 := float64(s.sumSqUs) - float64(s.sumUs)*meanUs
|
||||
varUs2 := m2 / float64(s.count-1)
|
||||
if varUs2 < 0 {
|
||||
// floating point rounding can push a (near-zero) variance slightly negative
|
||||
varUs2 = 0
|
||||
}
|
||||
stdDev = time.Duration(math.Sqrt(varUs2) * float64(time.Microsecond))
|
||||
return mean, stdDev
|
||||
return time.Duration(s.maxNs)
|
||||
}
|
||||
|
||||
type ForwardStats struct {
|
||||
@@ -231,12 +292,12 @@ func (s *ForwardStats) run() {
|
||||
|
||||
// flush drains the buffered samples, observes each into the Prometheus
|
||||
// histogram, and folds the interval summary into the window ring used for the
|
||||
// latency/jitter gauges.
|
||||
// latency gauge.
|
||||
func (s *ForwardStats) flush() {
|
||||
var summ forwardSummary
|
||||
s.samples.drain(func(transitNs int64) {
|
||||
prometheus.RecordForwardLatencySample(transitNs)
|
||||
summ = summ.addSample(transitNs)
|
||||
summ.addSample(transitNs)
|
||||
})
|
||||
|
||||
s.lock.Lock()
|
||||
@@ -274,33 +335,33 @@ func (s *ForwardStats) summarize(window time.Duration) forwardSummary {
|
||||
return w
|
||||
}
|
||||
|
||||
// GetStats returns the mean latency and jitter (std dev) of the forwarding
|
||||
// transit over the most recent duration. The duration is rounded up to a whole
|
||||
// number of summary intervals (the smallest bucket span that covers it). A
|
||||
// duration <= 0, or one that meets/exceeds the report window, covers the full
|
||||
// window.
|
||||
func (s *ForwardStats) GetStats(duration time.Duration) (time.Duration, time.Duration) {
|
||||
return s.summarize(duration).meanStdDev()
|
||||
// GetStats returns the reported forwarding-latency percentile
|
||||
// (forwardLatencyPercentile) over the most recent duration. The duration is
|
||||
// rounded up to a whole number of summary intervals (the smallest bucket span
|
||||
// that covers it). A duration <= 0, or one that meets/exceeds the report window,
|
||||
// covers the full window.
|
||||
func (s *ForwardStats) GetStats(duration time.Duration) time.Duration {
|
||||
return s.summarize(duration).percentile(forwardLatencyPercentile)
|
||||
}
|
||||
|
||||
func (s *ForwardStats) report() {
|
||||
w := s.summarize(0)
|
||||
|
||||
latency, jitter := w.meanStdDev()
|
||||
p90 := w.percentile(forwardLatencyPercentile)
|
||||
if dropped := s.samples.takeDropped(); dropped > 0 {
|
||||
logger.Warnw("forward stats sample buffer overflow", nil, "dropped", dropped)
|
||||
}
|
||||
if w.count > 0 && jitter > latency*cSkewFactor {
|
||||
// a max far above p90 means a few packets stalled (e.g. goroutine scheduling
|
||||
// latency) rather than a broad forwarding slowdown; p90 rides through it.
|
||||
if w.count > 0 && w.maxNs > p90.Nanoseconds()*cSkewFactor {
|
||||
logger.Infow(
|
||||
"high jitter in forwarding path",
|
||||
"high spread in forwarding path",
|
||||
"lowest", time.Duration(w.minNs),
|
||||
"highest", time.Duration(w.maxNs),
|
||||
"count", w.count,
|
||||
"latency", latency,
|
||||
"jitter", jitter,
|
||||
"p90", p90,
|
||||
)
|
||||
}
|
||||
|
||||
prometheus.RecordForwardJitter(uint32(jitter.Nanoseconds()))
|
||||
prometheus.RecordForwardLatency(uint32(latency.Nanoseconds()))
|
||||
prometheus.RecordForwardLatency(uint32(p90.Nanoseconds()))
|
||||
}
|
||||
|
||||
@@ -24,28 +24,39 @@ func initPrometheus(t *testing.T) {
|
||||
// forwardSummary
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// bucketSum totals a summary's per-bucket counts, independent of the bucketing
|
||||
// scheme, so tests can assert samples landed without hard-coding bucket indices.
|
||||
func bucketSum(s forwardSummary) int64 {
|
||||
var n int64
|
||||
for _, b := range s.buckets {
|
||||
n += b.count
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestForwardSummary_AddSample(t *testing.T) {
|
||||
var s forwardSummary
|
||||
|
||||
// empty summary
|
||||
require.Equal(t, int64(0), s.count)
|
||||
|
||||
// microsecond-aligned transits so the /1000 truncation is exact
|
||||
s = s.addSample(3000) // 3us
|
||||
s = s.addSample(1000) // 1us
|
||||
s = s.addSample(2000) // 2us
|
||||
s.addSample(3000) // 3us
|
||||
s.addSample(1000) // 1us
|
||||
s.addSample(2000) // 2us
|
||||
|
||||
require.Equal(t, int64(3), s.count)
|
||||
require.Equal(t, int64(1+2+3), s.sumUs)
|
||||
require.Equal(t, int64(1+4+9), s.sumSqUs)
|
||||
require.Equal(t, int64(1000), s.minNs)
|
||||
require.Equal(t, int64(3000), s.maxNs)
|
||||
require.Equal(t, s.count, bucketSum(s)) // every sample landed in a bucket
|
||||
}
|
||||
|
||||
func TestForwardSummary_Merge(t *testing.T) {
|
||||
var empty forwardSummary
|
||||
a := forwardSummary{}.addSample(1000).addSample(2000)
|
||||
b := forwardSummary{}.addSample(5000).addSample(3000)
|
||||
var a, b forwardSummary
|
||||
a.addSample(1000)
|
||||
a.addSample(2000)
|
||||
b.addSample(5000)
|
||||
b.addSample(3000)
|
||||
|
||||
// merging with empty is identity, in both directions
|
||||
require.Equal(t, a, a.merge(empty))
|
||||
@@ -53,34 +64,72 @@ func TestForwardSummary_Merge(t *testing.T) {
|
||||
|
||||
m := a.merge(b)
|
||||
require.Equal(t, int64(4), m.count)
|
||||
require.Equal(t, a.sumUs+b.sumUs, m.sumUs)
|
||||
require.Equal(t, a.sumSqUs+b.sumSqUs, m.sumSqUs)
|
||||
require.Equal(t, int64(1000), m.minNs)
|
||||
require.Equal(t, int64(5000), m.maxNs)
|
||||
// merge sums the per-bucket counts
|
||||
require.Equal(t, bucketSum(a)+bucketSum(b), bucketSum(m))
|
||||
require.Equal(t, m.count, bucketSum(m))
|
||||
}
|
||||
|
||||
func TestForwardSummary_MeanStdDev(t *testing.T) {
|
||||
func TestForwardSummary_Percentile(t *testing.T) {
|
||||
// empty -> zero
|
||||
mean, stdDev := forwardSummary{}.meanStdDev()
|
||||
require.Zero(t, mean)
|
||||
require.Zero(t, stdDev)
|
||||
require.Zero(t, forwardSummary{}.percentile(0.5))
|
||||
|
||||
// single sample -> mean set, stddev zero (needs >= 2 for variance)
|
||||
mean, stdDev = forwardSummary{}.addSample(4000).meanStdDev()
|
||||
require.Equal(t, 4*time.Microsecond, mean)
|
||||
require.Zero(t, stdDev)
|
||||
// half the samples fast (1us), half a slow tail (100us). A percentile is not
|
||||
// dragged toward the tail the way the mean is -- why the reported metric is
|
||||
// p90, not the mean.
|
||||
var s forwardSummary
|
||||
for i := 0; i < 5; i++ {
|
||||
s.addSample(1000) // 1us
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
s.addSample(100_000) // 100us
|
||||
}
|
||||
require.Equal(t, int64(10), s.count)
|
||||
|
||||
// identical samples -> zero variance
|
||||
s := forwardSummary{}.addSample(2000).addSample(2000).addSample(2000)
|
||||
mean, stdDev = s.meanStdDev()
|
||||
require.Equal(t, 2*time.Microsecond, mean)
|
||||
require.Zero(t, stdDev)
|
||||
// p50 lands in the fast cluster, unmoved by the 100us tail.
|
||||
require.Equal(t, 1*time.Microsecond, s.percentile(0.5))
|
||||
// p90 crosses into the slow cluster.
|
||||
require.Equal(t, 100*time.Microsecond, s.percentile(0.9))
|
||||
|
||||
// known dataset [1us, 2us, 3us]: mean 2us, sample variance 1us^2 -> stddev 1us
|
||||
s = forwardSummary{}.addSample(1000).addSample(2000).addSample(3000)
|
||||
mean, stdDev = s.meanStdDev()
|
||||
require.Equal(t, 2*time.Microsecond, mean)
|
||||
require.InDelta(t, float64(time.Microsecond), float64(stdDev), float64(50*time.Nanosecond))
|
||||
// a single sample reports exactly its latency, not the top edge of its bucket
|
||||
// (nominal-edge interpolation would report the bucket's upper reach instead).
|
||||
var single forwardSummary
|
||||
single.addSample(int64(20 * time.Millisecond))
|
||||
require.Equal(t, 20*time.Millisecond, single.percentile(0.9))
|
||||
|
||||
// identical samples share a bucket but must not invent intra-bucket spread.
|
||||
var u forwardSummary
|
||||
for i := 0; i < 8; i++ {
|
||||
u.addSample(int64(2 * time.Millisecond))
|
||||
}
|
||||
require.Equal(t, 2*time.Millisecond, u.percentile(0.5))
|
||||
require.Equal(t, 2*time.Millisecond, u.percentile(0.99))
|
||||
}
|
||||
|
||||
func TestForwardSummary_ThresholdResolution(t *testing.T) {
|
||||
// Nodes whose p90 packets cluster near a 300us overload threshold.
|
||||
// Interpolating within each bucket's observed range reports a tight tail
|
||||
// exactly, so each cluster lands on the correct side of 300us.
|
||||
build := func(tailUs int64) forwardSummary {
|
||||
var s forwardSummary
|
||||
for i := 0; i < 850; i++ {
|
||||
s.addSample(50 * int64(time.Microsecond))
|
||||
}
|
||||
for i := 0; i < 150; i++ {
|
||||
s.addSample(tailUs * int64(time.Microsecond))
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
require.Less(t, build(265).percentile(0.9), 300*time.Microsecond) // below -> no trip
|
||||
require.Greater(t, build(310).percentile(0.9), 300*time.Microsecond) // just above -> trips
|
||||
require.Greater(t, build(500).percentile(0.9), 300*time.Microsecond) // well above -> trips
|
||||
|
||||
// a tight tail is reported exactly, regardless of where it sits in the bucket.
|
||||
require.Equal(t, 265*time.Microsecond, build(265).percentile(0.9))
|
||||
require.Equal(t, 310*time.Microsecond, build(310).percentile(0.9))
|
||||
require.Equal(t, 500*time.Microsecond, build(500).percentile(0.9))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -284,29 +333,25 @@ func TestForwardStats_GetStats(t *testing.T) {
|
||||
// 5 buckets, each covering one 100ms summary interval.
|
||||
s := &ForwardStats{ring: make([]forwardSummary, 5), summaryInterval: 100 * time.Millisecond}
|
||||
|
||||
// fold five 100ms buckets, one sample each: 1ms, 2ms, 3ms, 4ms, 5ms.
|
||||
for i := 1; i <= 5; i++ {
|
||||
// fold five 100ms buckets, one sample each, descending 5ms..1ms so trailing
|
||||
// windows have distinct maxima.
|
||||
for i := 5; i >= 1; i-- {
|
||||
s.Update(0, int64(i)*int64(time.Millisecond))
|
||||
s.flush()
|
||||
}
|
||||
require.Equal(t, 5, s.ringLen)
|
||||
|
||||
// a duration <= 0 covers the whole window: mean of 1..5ms == 3ms.
|
||||
latency, jitter := s.GetStats(0)
|
||||
require.InDelta(t, float64(3*time.Millisecond), float64(latency), float64(50*time.Microsecond))
|
||||
require.Greater(t, jitter, time.Duration(0))
|
||||
// whole window {1..5ms}: p90 clamps to the observed max, 5ms.
|
||||
require.Equal(t, 5*time.Millisecond, s.GetStats(0))
|
||||
require.Equal(t, 5*time.Millisecond, s.GetStats(time.Second))
|
||||
|
||||
// a duration meeting/exceeding the window also covers it.
|
||||
fullLatency, _ := s.GetStats(time.Second)
|
||||
require.InDelta(t, float64(3*time.Millisecond), float64(fullLatency), float64(50*time.Microsecond))
|
||||
// ~200ms covers only the two most recent buckets {2ms, 1ms}: a lower window
|
||||
// than the full one, and above the single most-recent bucket.
|
||||
require.Less(t, s.GetStats(200*time.Millisecond), 3*time.Millisecond)
|
||||
require.Greater(t, s.GetStats(200*time.Millisecond), s.GetStats(time.Nanosecond))
|
||||
|
||||
// ~200ms rounds up to the two most recent buckets (4ms, 5ms): mean == 4.5ms.
|
||||
shortLatency, _ := s.GetStats(200 * time.Millisecond)
|
||||
require.InDelta(t, float64(4500*time.Microsecond), float64(shortLatency), float64(50*time.Microsecond))
|
||||
|
||||
// a sub-interval duration still yields at least the most recent bucket (5ms).
|
||||
lastLatency, _ := s.GetStats(time.Nanosecond)
|
||||
require.InDelta(t, float64(5*time.Millisecond), float64(lastLatency), float64(50*time.Microsecond))
|
||||
// a sub-interval yields only the most recent bucket, ~1ms.
|
||||
require.Equal(t, 1*time.Millisecond, s.GetStats(time.Nanosecond))
|
||||
}
|
||||
|
||||
func TestForwardStats_Lifecycle(t *testing.T) {
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
package pacer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
@@ -24,6 +25,7 @@ import (
|
||||
"github.com/livekit/protocol/logger"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/bwe"
|
||||
dd "github.com/livekit/livekit-server/pkg/sfu/rtpextension/dependencydescriptor"
|
||||
"github.com/livekit/livekit-server/pkg/sfu/utils"
|
||||
)
|
||||
|
||||
@@ -85,3 +87,23 @@ func TestSendPacketHeaderExtensionsNoAlloc(t *testing.T) {
|
||||
require.Equal(t, 0.0, allocs, "allocations per SendPacket")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHoldExtension(t *testing.T) {
|
||||
p := &Packet{}
|
||||
|
||||
ext := []byte{1, 2, 3}
|
||||
held := p.HoldExtension(ext)
|
||||
require.Equal(t, ext, held)
|
||||
require.Same(t, &p.extBuf[0], &held[0], "the extension has to be held in the packet's scratch")
|
||||
|
||||
ext[0] = 9
|
||||
require.EqualValues(t, 1, held[0], "the held copy has to be independent of the caller's slice")
|
||||
|
||||
// exactly the one byte extension profile payload cap
|
||||
exact := bytes.Repeat([]byte{7}, dd.MaxInlineExtensionSize)
|
||||
held = p.HoldExtension(exact)
|
||||
require.Equal(t, exact, held)
|
||||
|
||||
// one byte more does not fit
|
||||
require.Nil(t, p.HoldExtension(bytes.Repeat([]byte{7}, dd.MaxInlineExtensionSize+1)))
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/ccutils"
|
||||
dd "github.com/livekit/livekit-server/pkg/sfu/rtpextension/dependencydescriptor"
|
||||
"github.com/pion/rtp"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
@@ -59,6 +60,15 @@ type Packet struct {
|
||||
// the Packet is owned by one send until SendPacket returns
|
||||
absSendTimeBuf [3]byte
|
||||
twccBuf [2]byte
|
||||
extBuf [dd.MaxInlineExtensionSize]byte
|
||||
}
|
||||
|
||||
// HoldExtension copies ext into scratch the header can point at until SendPacket returns, nil if it does not fit
|
||||
func (p *Packet) HoldExtension(ext []byte) []byte {
|
||||
if len(ext) > len(p.extBuf) {
|
||||
return nil
|
||||
}
|
||||
return p.extBuf[:copy(p.extBuf[:], ext)]
|
||||
}
|
||||
|
||||
type Pacer interface {
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
package dependencydescriptor
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
@@ -23,6 +24,10 @@ import (
|
||||
// DependencyDescriptorExtension is a extension payload format in
|
||||
// https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension
|
||||
|
||||
// ErrBufferTooSmall is returned by MarshalTo when the caller's storage cannot
|
||||
// hold the marshaled extension.
|
||||
var ErrBufferTooSmall = errors.New("dependency descriptor buffer too small")
|
||||
|
||||
func formatBitmask(b *uint32) string {
|
||||
if b == nil {
|
||||
return "-"
|
||||
@@ -42,18 +47,48 @@ func (d *DependencyDescriptorExtension) Marshal() ([]byte, error) {
|
||||
}
|
||||
|
||||
func (d *DependencyDescriptorExtension) MarshalWithActiveChains(activeChains uint32) ([]byte, error) {
|
||||
writer, err := NewDependencyDescriptorWriter(nil, d.Structure, activeChains, d.Descriptor)
|
||||
writer, size, err := d.newWriter(activeChains)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buf := make([]byte, int(math.Ceil(float64(writer.ValueSizeBits())/8)))
|
||||
writer.ResetBuf(buf)
|
||||
if err = writer.Write(); err != nil {
|
||||
|
||||
buf := make([]byte, size)
|
||||
writer = writer.withBuf(buf)
|
||||
if err := writer.Write(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// MarshalTo marshals into caller owned storage and returns the number of bytes
|
||||
// written, or ErrBufferTooSmall, leaving buf untouched, if the extension does not fit.
|
||||
func (d *DependencyDescriptorExtension) MarshalTo(buf []byte) (int, error) {
|
||||
writer, size, err := d.newWriter(^uint32(0))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(buf) < size {
|
||||
// bare sentinel, key frames take this path and formatting an error there would allocate
|
||||
return 0, ErrBufferTooSmall
|
||||
}
|
||||
|
||||
writer = writer.withBuf(buf[:size])
|
||||
if err := writer.Write(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return size, nil
|
||||
}
|
||||
|
||||
// newWriter returns a writer for the extension, by value so that it stays on the
|
||||
// caller's stack, along with the number of bytes the marshaled extension needs.
|
||||
func (d *DependencyDescriptorExtension) newWriter(activeChains uint32) (DependencyDescriptorWriter, int, error) {
|
||||
writer := newDependencyDescriptorWriter(nil, d.Structure, activeChains, d.Descriptor)
|
||||
if err := writer.findBestTemplate(); err != nil {
|
||||
return writer, 0, err
|
||||
}
|
||||
return writer, int(math.Ceil(float64(writer.ValueSizeBits()) / 8)), nil
|
||||
}
|
||||
|
||||
func (d *DependencyDescriptorExtension) Unmarshal(buf []byte) (int, error) {
|
||||
reader := NewDependencyDescriptorReader(buf, d.Structure, d.Descriptor)
|
||||
return reader.Parse()
|
||||
@@ -67,6 +102,9 @@ const (
|
||||
MaxDecodeTargets = 32
|
||||
MaxTemplates = 64
|
||||
|
||||
// MaxInlineExtensionSize is the inline storage the forwarding path and the pacer reserve for a marshaled extension, pion's one byte profile cap
|
||||
MaxInlineExtensionSize = 16
|
||||
|
||||
AllChainsAreActive = uint32(0)
|
||||
|
||||
ExtensionURI = "https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"
|
||||
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
// Copyright 2026 LiveKit, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package dependencydescriptor
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/utils"
|
||||
)
|
||||
|
||||
// dependencyDescriptorMarshalFixture is a dependency descriptor captured from
|
||||
// traffic. The fixture helper decodes its attached structure once, then returns
|
||||
// a regular per-packet descriptor that references that structure.
|
||||
const dependencyDescriptorMarshalFixture = "c1017280081485214eafffaaaa863cf0430c10c302afc0aaa0063c00430010c002a000a80006000040001d954926e082b04a0941b820ac1282503157f974000ca864330e222222eca8655304224230eca877530077004200ef008601df010d"
|
||||
|
||||
func newDependencyDescriptorMarshalFixture(tb testing.TB) *DependencyDescriptorExtension {
|
||||
tb.Helper()
|
||||
|
||||
buf, err := hex.DecodeString(dependencyDescriptorMarshalFixture)
|
||||
require.NoError(tb, err)
|
||||
|
||||
descriptor := DependencyDescriptor{}
|
||||
parser := DependencyDescriptorExtension{Descriptor: &descriptor}
|
||||
_, err = parser.Unmarshal(buf)
|
||||
require.NoError(tb, err)
|
||||
require.NotNil(tb, descriptor.AttachedStructure, "fixture did not contain a dependency structure")
|
||||
|
||||
structure := descriptor.AttachedStructure
|
||||
descriptor.AttachedStructure = nil
|
||||
descriptor.ActiveDecodeTargetsBitmask = nil
|
||||
|
||||
return &DependencyDescriptorExtension{
|
||||
Descriptor: &descriptor,
|
||||
Structure: structure,
|
||||
}
|
||||
}
|
||||
|
||||
func checkDependencyDescriptorMarshal(tb testing.TB, buf []byte, structure *FrameDependencyStructure, frameNumber uint16) {
|
||||
tb.Helper()
|
||||
|
||||
require.NotEmpty(tb, buf, "marshal returned an empty dependency descriptor")
|
||||
|
||||
decoded := DependencyDescriptor{}
|
||||
parser := DependencyDescriptorExtension{
|
||||
Descriptor: &decoded,
|
||||
Structure: structure,
|
||||
}
|
||||
_, err := parser.Unmarshal(buf)
|
||||
require.NoError(tb, err)
|
||||
require.Equal(tb, frameNumber, decoded.FrameNumber)
|
||||
}
|
||||
|
||||
func TestDependencyDescriptorMarshalRoundTrip(t *testing.T) {
|
||||
extension := newDependencyDescriptorMarshalFixture(t)
|
||||
|
||||
first, err := extension.Marshal()
|
||||
require.NoError(t, err)
|
||||
firstCopy := append([]byte(nil), first...)
|
||||
checkDependencyDescriptorMarshal(t, first, extension.Structure, extension.Descriptor.FrameNumber)
|
||||
|
||||
extension.Descriptor.FrameNumber++
|
||||
second, err := extension.Marshal()
|
||||
require.NoError(t, err)
|
||||
checkDependencyDescriptorMarshal(t, second, extension.Structure, extension.Descriptor.FrameNumber)
|
||||
|
||||
require.Equal(t, firstCopy, first, "a later marshal modified a previously returned buffer")
|
||||
require.NotEqual(t, first, second, "different frame numbers produced identical descriptors")
|
||||
}
|
||||
|
||||
func TestDependencyDescriptorMarshalTo(t *testing.T) {
|
||||
extension := newDependencyDescriptorMarshalFixture(t)
|
||||
|
||||
// every template of the fixture structure, i. e. the per-packet descriptors
|
||||
// the forwarding path marshals, has to match Marshal byte for byte and fit
|
||||
// the inline size the forwarding path reserves
|
||||
for i, template := range extension.Structure.Templates {
|
||||
extension.Descriptor.FrameDependencies = template
|
||||
extension.Descriptor.FrameNumber = uint16(i)
|
||||
|
||||
want, err := extension.Marshal()
|
||||
require.NoError(t, err)
|
||||
require.LessOrEqual(t, len(want), MaxInlineExtensionSize)
|
||||
|
||||
var scratch [MaxInlineExtensionSize]byte
|
||||
n, err := extension.MarshalTo(scratch[:])
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, scratch[:n])
|
||||
checkDependencyDescriptorMarshal(t, scratch[:n], extension.Structure, uint16(i))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDependencyDescriptorMarshalToBufferTooSmall(t *testing.T) {
|
||||
extension := newDependencyDescriptorMarshalFixture(t)
|
||||
|
||||
want, err := extension.Marshal()
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = extension.MarshalTo(make([]byte, len(want)-1))
|
||||
require.ErrorIs(t, err, ErrBufferTooSmall)
|
||||
|
||||
n, err := extension.MarshalTo(make([]byte, len(want)))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, len(want), n)
|
||||
|
||||
// a descriptor carrying the full dependency structure does not fit inline
|
||||
extension.Descriptor.AttachedStructure = extension.Structure
|
||||
_, err = extension.MarshalTo(make([]byte, MaxInlineExtensionSize))
|
||||
require.ErrorIs(t, err, ErrBufferTooSmall)
|
||||
|
||||
keyFrame, err := extension.Marshal()
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, len(keyFrame), MaxInlineExtensionSize)
|
||||
}
|
||||
|
||||
// TestDependencyDescriptorMarshalToLargerDescriptors covers the 8 to 16 byte
|
||||
// band, where the active decode targets bitmask and custom frame dependencies
|
||||
// land and where the sequencer's own inline copy already spills.
|
||||
func TestDependencyDescriptorMarshalToLargerDescriptors(t *testing.T) {
|
||||
extension := newDependencyDescriptorMarshalFixture(t)
|
||||
bitmask := uint32(0x1ff)
|
||||
|
||||
// the widest per-packet descriptor of the fixture, with the bitmask attached
|
||||
widest := 0
|
||||
for _, template := range extension.Structure.Templates {
|
||||
extension.Descriptor.FrameDependencies = template
|
||||
extension.Descriptor.ActiveDecodeTargetsBitmask = &bitmask
|
||||
|
||||
want, err := extension.Marshal()
|
||||
require.NoError(t, err)
|
||||
widest = max(widest, len(want))
|
||||
|
||||
var scratch [MaxInlineExtensionSize]byte
|
||||
n, err := extension.MarshalTo(scratch[:])
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, scratch[:n])
|
||||
}
|
||||
require.GreaterOrEqual(t, widest, 8)
|
||||
|
||||
// custom frame diffs and chain diffs, i. e. a frame that matches no template
|
||||
custom := extension.Structure.Templates[0].Clone()
|
||||
custom.FrameDiffs = []int{1, 300, 4000}
|
||||
for i := range custom.ChainDiffs {
|
||||
custom.ChainDiffs[i] = 200 + i
|
||||
}
|
||||
extension.Descriptor.FrameDependencies = custom
|
||||
extension.Descriptor.ActiveDecodeTargetsBitmask = nil
|
||||
|
||||
want, err := extension.Marshal()
|
||||
require.NoError(t, err)
|
||||
require.GreaterOrEqual(t, len(want), 8)
|
||||
require.LessOrEqual(t, len(want), MaxInlineExtensionSize)
|
||||
|
||||
var scratch [MaxInlineExtensionSize]byte
|
||||
n, err := extension.MarshalTo(scratch[:])
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, scratch[:n])
|
||||
checkDependencyDescriptorMarshal(t, scratch[:n], extension.Structure, extension.Descriptor.FrameNumber)
|
||||
}
|
||||
|
||||
func TestDependencyDescriptorMarshalAllocs(t *testing.T) {
|
||||
if utils.RaceEnabled {
|
||||
// the race detector perturbs allocation counts, see #4874
|
||||
t.Skip("allocation count is not meaningful under the race detector")
|
||||
}
|
||||
|
||||
extension := newDependencyDescriptorMarshalFixture(t)
|
||||
|
||||
var (
|
||||
scratch [MaxInlineExtensionSize]byte
|
||||
n int
|
||||
err error
|
||||
)
|
||||
allocs := testing.AllocsPerRun(100, func() {
|
||||
n, err = extension.MarshalTo(scratch[:])
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotZero(t, n)
|
||||
require.Zero(t, allocs, "a per-packet descriptor has to marshal without allocating")
|
||||
|
||||
// a key frame descriptor carries the full dependency structure, does not fit
|
||||
// the inline scratch and spills to exactly one allocation, the Marshal slice
|
||||
extension.Descriptor.AttachedStructure = extension.Structure
|
||||
|
||||
var buf []byte
|
||||
allocs = testing.AllocsPerRun(100, func() {
|
||||
if n, err = extension.MarshalTo(scratch[:]); err != nil {
|
||||
buf, err = extension.Marshal()
|
||||
}
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, len(buf), MaxInlineExtensionSize)
|
||||
require.Equal(t, float64(1), allocs, "the spill path has to allocate only the Marshal slice")
|
||||
}
|
||||
|
||||
func BenchmarkDependencyDescriptorMarshal(b *testing.B) {
|
||||
extension := newDependencyDescriptorMarshalFixture(b)
|
||||
frameNumber := extension.Descriptor.FrameNumber
|
||||
|
||||
b.ReportAllocs()
|
||||
var buf []byte
|
||||
for b.Loop() {
|
||||
extension.Descriptor.FrameNumber = frameNumber
|
||||
frameNumber++
|
||||
|
||||
var err error
|
||||
buf, err = extension.Marshal()
|
||||
require.NoError(b, err)
|
||||
}
|
||||
|
||||
checkDependencyDescriptorMarshal(b, buf, extension.Structure, frameNumber-1)
|
||||
}
|
||||
|
||||
func BenchmarkDependencyDescriptorMarshalTo(b *testing.B) {
|
||||
extension := newDependencyDescriptorMarshalFixture(b)
|
||||
frameNumber := extension.Descriptor.FrameNumber
|
||||
|
||||
b.ReportAllocs()
|
||||
var (
|
||||
scratch [MaxInlineExtensionSize]byte
|
||||
n int
|
||||
)
|
||||
for b.Loop() {
|
||||
extension.Descriptor.FrameNumber = frameNumber
|
||||
frameNumber++
|
||||
|
||||
var err error
|
||||
n, err = extension.MarshalTo(scratch[:])
|
||||
require.NoError(b, err)
|
||||
}
|
||||
|
||||
checkDependencyDescriptorMarshal(b, scratch[:n], extension.Structure, frameNumber-1)
|
||||
}
|
||||
@@ -33,23 +33,28 @@ type DependencyDescriptorWriter struct {
|
||||
descriptor *DependencyDescriptor
|
||||
structure *FrameDependencyStructure
|
||||
activeChains uint32
|
||||
writer *BitStreamWriter
|
||||
writer BitStreamWriter
|
||||
bestTemplate TemplateMatch
|
||||
}
|
||||
|
||||
func NewDependencyDescriptorWriter(buf []byte, structure *FrameDependencyStructure, activeChains uint32, descriptor *DependencyDescriptor) (*DependencyDescriptorWriter, error) {
|
||||
writer := NewBitStreamWriter(buf)
|
||||
w := &DependencyDescriptorWriter{
|
||||
func newDependencyDescriptorWriter(buf []byte, structure *FrameDependencyStructure, activeChains uint32, descriptor *DependencyDescriptor) DependencyDescriptorWriter {
|
||||
return DependencyDescriptorWriter{
|
||||
descriptor: descriptor,
|
||||
structure: structure,
|
||||
activeChains: activeChains,
|
||||
writer: writer,
|
||||
writer: BitStreamWriter{buf: buf},
|
||||
}
|
||||
return w, w.findBestTemplate()
|
||||
}
|
||||
|
||||
func (w *DependencyDescriptorWriter) ResetBuf(buf []byte) {
|
||||
w.writer = NewBitStreamWriter(buf)
|
||||
func NewDependencyDescriptorWriter(buf []byte, structure *FrameDependencyStructure, activeChains uint32, descriptor *DependencyDescriptor) (*DependencyDescriptorWriter, error) {
|
||||
w := newDependencyDescriptorWriter(buf, structure, activeChains, descriptor)
|
||||
return &w, w.findBestTemplate()
|
||||
}
|
||||
|
||||
// withBuf returns a copy of the writer that writes into buf, value receiver so a caller owned buffer does not escape
|
||||
func (w DependencyDescriptorWriter) withBuf(buf []byte) DependencyDescriptorWriter {
|
||||
w.writer = BitStreamWriter{buf: buf}
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *DependencyDescriptorWriter) Write() error {
|
||||
|
||||
@@ -46,6 +46,10 @@ type DependencyDescriptor struct {
|
||||
decodeTargets []*DecodeTarget
|
||||
fnWrapper FrameNumberWrapper
|
||||
|
||||
// per packet copy of the descriptor when the frame number or the active
|
||||
// decode targets are rewritten, owned here so it does not allocate
|
||||
ddClone dede.DependencyDescriptor
|
||||
|
||||
restartGeneration int
|
||||
}
|
||||
|
||||
@@ -322,8 +326,8 @@ func (d *DependencyDescriptor) Select(extPkt *buffer.ExtPacket, _layer int32) (r
|
||||
unWrapFn := uint16(d.fnWrapper.UpdateAndGet(extFrameNum, ddwdt.StructureUpdated))
|
||||
var ddClone *dede.DependencyDescriptor
|
||||
if unWrapFn != dd.FrameNumber {
|
||||
clone := *dd
|
||||
ddClone = &clone
|
||||
d.ddClone = *dd
|
||||
ddClone = &d.ddClone
|
||||
ddClone.FrameNumber = unWrapFn
|
||||
ddExtension.Descriptor = ddClone
|
||||
}
|
||||
@@ -333,8 +337,8 @@ func (d *DependencyDescriptor) Select(extPkt *buffer.ExtPacket, _layer int32) (r
|
||||
if ddClone == nil {
|
||||
// clone and override activebitmask
|
||||
// DD-TODO: if the packet that contains the bitmask is acknowledged by RR, then we don't need it until it changed.
|
||||
clone := *dd
|
||||
ddClone = &clone
|
||||
d.ddClone = *dd
|
||||
ddClone = &d.ddClone
|
||||
ddExtension.Descriptor = ddClone
|
||||
}
|
||||
ddClone.ActiveDecodeTargetsBitmask = d.activeDecodeTargetsBitmask
|
||||
@@ -355,11 +359,9 @@ func (d *DependencyDescriptor) Select(extPkt *buffer.ExtPacket, _layer int32) (r
|
||||
"stack", string(debug.Stack()))
|
||||
}
|
||||
}()
|
||||
bytes, err := ddExtension.Marshal()
|
||||
if err != nil {
|
||||
if err := result.marshalDependencyDescriptorExtension(ddExtension); err != nil {
|
||||
d.logger.Warnw("error marshalling dependency descriptor extension", err)
|
||||
} else {
|
||||
result.DependencyDescriptorExtension = bytes
|
||||
ddMarshaled = true
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
package videolayerselector
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
@@ -23,6 +24,7 @@ import (
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/buffer"
|
||||
dd "github.com/livekit/livekit-server/pkg/sfu/rtpextension/dependencydescriptor"
|
||||
"github.com/livekit/livekit-server/pkg/sfu/utils"
|
||||
"github.com/livekit/protocol/logger"
|
||||
)
|
||||
|
||||
@@ -409,3 +411,71 @@ func createDDFrames(maxLayer buffer.VideoLayer, startFrameNumber uint16) []*buff
|
||||
|
||||
return frames
|
||||
}
|
||||
|
||||
// same capture as the dependency descriptor package's marshal fixture, an L3T3
|
||||
// key frame descriptor with the full dependency structure attached
|
||||
const dependencyDescriptorFixture = "c1017280081485214eafffaaaa863cf0430c10c302afc0aaa0063c00430010c002a000a80006000040001d954926e082b04a0941b820ac1282503157f974000ca864330e222222eca8655304224230eca877530077004200ef008601df010d"
|
||||
|
||||
func TestVideoLayerSelectorResultDependencyDescriptor(t *testing.T) {
|
||||
raw, err := hex.DecodeString(dependencyDescriptorFixture)
|
||||
require.NoError(t, err)
|
||||
|
||||
descriptor := dd.DependencyDescriptor{}
|
||||
_, err = (&dd.DependencyDescriptorExtension{Descriptor: &descriptor}).Unmarshal(raw)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, descriptor.AttachedStructure)
|
||||
structure := descriptor.AttachedStructure
|
||||
|
||||
// a key frame descriptor carries the full structure and spills to the heap
|
||||
keyFrame := VideoLayerSelectorResult{}
|
||||
require.NoError(t, keyFrame.marshalDependencyDescriptorExtension(&dd.DependencyDescriptorExtension{
|
||||
Descriptor: &descriptor,
|
||||
Structure: structure,
|
||||
}))
|
||||
require.Zero(t, keyFrame.DDBytesLen)
|
||||
require.Greater(t, len(keyFrame.DDBytesSpill), dd.MaxInlineExtensionSize)
|
||||
|
||||
// a per-packet descriptor is held inline, byte for byte what Marshal returns
|
||||
perPacket := descriptor
|
||||
perPacket.AttachedStructure = nil
|
||||
perPacket.ActiveDecodeTargetsBitmask = nil
|
||||
ddExtension := &dd.DependencyDescriptorExtension{Descriptor: &perPacket, Structure: structure}
|
||||
|
||||
result := VideoLayerSelectorResult{}
|
||||
require.NoError(t, result.marshalDependencyDescriptorExtension(ddExtension))
|
||||
require.Nil(t, result.DDBytesSpill)
|
||||
require.NotZero(t, result.DDBytesLen)
|
||||
require.LessOrEqual(t, result.DDBytesLen, dd.MaxInlineExtensionSize)
|
||||
|
||||
want, err := ddExtension.Marshal()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, result.DDBytes[:result.DDBytesLen])
|
||||
}
|
||||
|
||||
func TestDependencyDescriptorSelectAllocations(t *testing.T) {
|
||||
for _, rewriteFrameNumber := range []bool{false, true} {
|
||||
selector := NewDependencyDescriptor(logger.GetLogger())
|
||||
selector.SetTarget(buffer.VideoLayer{Spatial: 0, Temporal: 0})
|
||||
selector.SetRequestSpatial(0)
|
||||
frames := createDDFrames(buffer.VideoLayer{Spatial: 0, Temporal: 0}, 100)
|
||||
require.True(t, selector.Select(frames[0], 0).IsSelected)
|
||||
require.NotNil(t, selector.activeDecodeTargetsBitmask)
|
||||
if rewriteFrameNumber {
|
||||
selector.fnWrapper.offset = 6000
|
||||
}
|
||||
packet := frames[1]
|
||||
packet.DependencyDescriptor.ExtFrameNum--
|
||||
packet.DependencyDescriptor.Descriptor.FrameNumber--
|
||||
|
||||
selected := true
|
||||
allocs := testing.AllocsPerRun(1000, func() {
|
||||
packet.DependencyDescriptor.ExtFrameNum++
|
||||
packet.DependencyDescriptor.Descriptor.FrameNumber++
|
||||
selected = selected && selector.Select(packet, 0).IsSelected
|
||||
})
|
||||
require.True(t, selected)
|
||||
if !utils.RaceEnabled {
|
||||
require.Equal(t, 0.0, allocs, "allocations per selected packet, rewriteFrameNumber=%v", rewriteFrameNumber)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,18 +15,43 @@
|
||||
package videolayerselector
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/buffer"
|
||||
dd "github.com/livekit/livekit-server/pkg/sfu/rtpextension/dependencydescriptor"
|
||||
"github.com/livekit/livekit-server/pkg/sfu/videolayerselector/temporallayerselector"
|
||||
"github.com/livekit/protocol/logger"
|
||||
)
|
||||
|
||||
type VideoLayerSelectorResult struct {
|
||||
IsSelected bool
|
||||
IsRelevant bool
|
||||
IsSwitching bool
|
||||
IsResuming bool
|
||||
RTPMarker bool
|
||||
DependencyDescriptorExtension []byte
|
||||
IsSelected bool
|
||||
IsRelevant bool
|
||||
IsSwitching bool
|
||||
IsResuming bool
|
||||
RTPMarker bool
|
||||
|
||||
// marshaled dependency descriptor extension, held inline when it fits and
|
||||
// spilled to the heap when it does not, the way the sequencer keeps its copy
|
||||
DDBytes [dd.MaxInlineExtensionSize]byte
|
||||
DDBytesLen int
|
||||
DDBytesSpill []byte
|
||||
}
|
||||
|
||||
// marshalDependencyDescriptorExtension marshals ddExtension into the result,
|
||||
// inline if it fits and on the heap otherwise.
|
||||
func (v *VideoLayerSelectorResult) marshalDependencyDescriptorExtension(ddExtension *dd.DependencyDescriptorExtension) error {
|
||||
ddBytesLen, err := ddExtension.MarshalTo(v.DDBytes[:])
|
||||
if err == nil {
|
||||
v.DDBytesLen = ddBytesLen
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, dd.ErrBufferTooSmall) {
|
||||
return err
|
||||
}
|
||||
|
||||
// descriptors carrying the full dependency structure do not fit inline
|
||||
v.DDBytesSpill, err = ddExtension.Marshal()
|
||||
return err
|
||||
}
|
||||
|
||||
type VideoLayerSelector interface {
|
||||
|
||||
@@ -174,7 +174,6 @@ func GetNodeStats(nodeStartedAt int64, prevStats []*livekit.NodeStats, rateInter
|
||||
ParticipantRtcCanceled: participantRTCCanceled.Load(),
|
||||
ParticipantRtcActive: participantRTCActive.Load(),
|
||||
ForwardLatency: forwardLatency.Load(),
|
||||
ForwardJitter: forwardJitter.Load(),
|
||||
NumCpus: uint32(cpuStats.NumCPU()), // this will round down to the nearest integer
|
||||
CpuLoad: float32(cpuStats.GetCPULoad()),
|
||||
MemoryTotal: memTotal,
|
||||
|
||||
@@ -51,7 +51,6 @@ var (
|
||||
participantRTCCanceled atomic.Uint64
|
||||
participantRTCActive atomic.Uint64
|
||||
forwardLatency atomic.Uint32
|
||||
forwardJitter atomic.Uint32
|
||||
|
||||
promPacketLabels = []string{"direction", "transmission", "country"}
|
||||
promPacketTotal *prometheus.CounterVec
|
||||
@@ -70,7 +69,6 @@ var (
|
||||
promParticipantJoin *prometheus.CounterVec
|
||||
promConnections *prometheus.GaugeVec
|
||||
promForwardLatency prometheus.Gauge
|
||||
promForwardJitter prometheus.Gauge
|
||||
promForwardLatencyHist prometheus.Histogram
|
||||
)
|
||||
|
||||
@@ -164,12 +162,6 @@ func initPacketStats(nodeID string, nodeType livekit.NodeType) {
|
||||
Name: "latency",
|
||||
ConstLabels: prometheus.Labels{"node_id": nodeID, "node_type": nodeType.String()},
|
||||
})
|
||||
promForwardJitter = prometheus.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: livekitNamespace,
|
||||
Subsystem: "forward",
|
||||
Name: "jitter",
|
||||
ConstLabels: prometheus.Labels{"node_id": nodeID, "node_type": nodeType.String()},
|
||||
})
|
||||
promForwardLatencyHist = prometheus.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: livekitNamespace,
|
||||
Subsystem: "forward_latency",
|
||||
@@ -204,7 +196,6 @@ func initPacketStats(nodeID string, nodeType livekit.NodeType) {
|
||||
prometheus.MustRegister(promParticipantJoin)
|
||||
prometheus.MustRegister(promConnections)
|
||||
prometheus.MustRegister(promForwardLatency)
|
||||
prometheus.MustRegister(promForwardJitter)
|
||||
prometheus.MustRegister(promForwardLatencyHist)
|
||||
}
|
||||
|
||||
@@ -380,12 +371,7 @@ func RecordForwardLatencySample(forwardLatency int64) {
|
||||
promForwardLatencyHist.Observe(float64(forwardLatency))
|
||||
}
|
||||
|
||||
func RecordForwardLatency(longTermLatencyAvg uint32) {
|
||||
forwardLatency.Store(longTermLatencyAvg)
|
||||
promForwardLatency.Set(float64(longTermLatencyAvg))
|
||||
}
|
||||
|
||||
func RecordForwardJitter(longTermJitterAvg uint32) {
|
||||
forwardJitter.Store(longTermJitterAvg)
|
||||
promForwardJitter.Set(float64(longTermJitterAvg))
|
||||
func RecordForwardLatency(p90 uint32) {
|
||||
forwardLatency.Store(p90)
|
||||
promForwardLatency.Set(float64(p90))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user