Batch subscriber updates to reduce noise (#703)

Improve scalability by batching subscriber updates on an interval.
When lots of subscribers join, the server ends up spending 20% CPU
sending each state change to everyone. There's a non-trivial amount of
overhead with each send operation.

For publishers, updates are sent right away.
This commit is contained in:
David Zhao
2022-05-20 22:54:02 -07:00
committed by GitHub
parent 8ef53037eb
commit cdf1724d80
4 changed files with 98 additions and 24 deletions
+5 -4
View File
@@ -8,7 +8,7 @@ import (
"github.com/livekit/livekit-server/pkg/rtc/types/typesfakes"
)
func newMockParticipant(identity livekit.ParticipantIdentity, protocol types.ProtocolVersion, hidden bool) *typesfakes.FakeLocalParticipant {
func newMockParticipant(identity livekit.ParticipantIdentity, protocol types.ProtocolVersion, hidden bool, publisher bool) *typesfakes.FakeLocalParticipant {
p := &typesfakes.FakeLocalParticipant{}
sid := utils.NewGuid(utils.ParticipantPrefix)
p.IDReturns(livekit.ParticipantID(sid))
@@ -20,9 +20,10 @@ func newMockParticipant(identity livekit.ParticipantIdentity, protocol types.Pro
p.CanPublishDataReturns(!hidden)
p.HiddenReturns(hidden)
p.ToProtoReturns(&livekit.ParticipantInfo{
Sid: sid,
Identity: string(identity),
State: livekit.ParticipantInfo_JOINED,
Sid: sid,
Identity: string(identity),
State: livekit.ParticipantInfo_JOINED,
IsPublisher: publisher,
})
p.SetMetadataStub = func(m string) {
+3
View File
@@ -328,6 +328,7 @@ func TestSubscriberAsPrimary(t *testing.T) {
type participantOpts struct {
permissions *livekit.ParticipantPermission
protocolVersion types.ProtocolVersion
publisher bool
}
func newParticipantForTestWithOpts(identity livekit.ParticipantIdentity, opts *participantOpts) *ParticipantImpl {
@@ -362,6 +363,8 @@ func newParticipantForTestWithOpts(identity livekit.ParticipantIdentity, opts *p
PLIThrottleConfig: conf.RTC.PLIThrottle,
Grants: grants,
})
p.isPublisher.Store(opts.publisher)
return p
}
+83 -13
View File
@@ -25,8 +25,14 @@ const (
DefaultEmptyTimeout = 5 * 60 // 5m
DefaultRoomDepartureGrace = 20
AudioLevelQuantization = 8 // ideally power of 2 to minimize float decimal
subscriberUpdateInterval = 3 * time.Second
)
type broadcastOptions struct {
skipSource bool
immediate bool
}
type Room struct {
lock sync.RWMutex
@@ -42,6 +48,10 @@ type Room struct {
participantOpts map[livekit.ParticipantIdentity]*ParticipantOptions
bufferFactory *buffer.Factory
// batch update participant info for non-publishers
batchedUpdates map[livekit.ParticipantIdentity]*livekit.ParticipantInfo
batchedUpdatesMu sync.Mutex
// time the first participant joined the room
joinedAt atomic.Int64
holds atomic.Int32
@@ -68,6 +78,7 @@ func NewRoom(room *livekit.Room, config WebRTCConfig, audioConfig *config.AudioC
participants: make(map[livekit.ParticipantIdentity]types.LocalParticipant),
participantOpts: make(map[livekit.ParticipantIdentity]*ParticipantOptions),
bufferFactory: buffer.NewBufferFactory(config.Receiver.PacketBufferSize),
batchedUpdates: make(map[livekit.ParticipantIdentity]*livekit.ParticipantInfo),
closed: make(chan struct{}),
}
if r.Room.EmptyTimeout == 0 {
@@ -79,6 +90,7 @@ func NewRoom(room *livekit.Room, config WebRTCConfig, audioConfig *config.AudioC
go r.audioUpdateWorker()
go r.connectionQualityWorker()
go r.subscriberBroadcastWorker()
return r
}
@@ -206,7 +218,7 @@ func (r *Room) Join(participant types.LocalParticipant, opts *ParticipantOptions
if r.onParticipantChanged != nil {
r.onParticipantChanged(participant)
}
r.broadcastParticipantState(p, true)
r.broadcastParticipantState(p, broadcastOptions{skipSource: true})
state := p.State()
if state == livekit.ParticipantInfo_ACTIVE {
@@ -361,7 +373,7 @@ func (r *Room) RemoveParticipant(identity livekit.ParticipantIdentity) {
if r.onParticipantChanged != nil {
r.onParticipantChanged(p)
}
r.broadcastParticipantState(p, true)
r.broadcastParticipantState(p, broadcastOptions{skipSource: true})
}
}
@@ -605,7 +617,7 @@ func (r *Room) autoSubscribe(participant types.LocalParticipant) bool {
// a ParticipantImpl in the room added a new remoteTrack, subscribe other participants to it
func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.MediaTrack) {
// publish participant update, since track state is changed
r.broadcastParticipantState(participant, true)
r.broadcastParticipantState(participant, broadcastOptions{skipSource: true})
r.lock.RLock()
defer r.lock.RUnlock()
@@ -643,14 +655,15 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.
func (r *Room) onTrackUpdated(p types.LocalParticipant, _ types.MediaTrack) {
// send track updates to everyone, especially if track was updated by admin
r.broadcastParticipantState(p, false)
r.broadcastParticipantState(p, broadcastOptions{})
if r.onParticipantChanged != nil {
r.onParticipantChanged(p)
}
}
func (r *Room) onParticipantUpdate(p types.LocalParticipant) {
r.broadcastParticipantState(p, false)
// immediately notify when permissions or metadata changed
r.broadcastParticipantState(p, broadcastOptions{immediate: true})
if r.onParticipantChanged != nil {
r.onParticipantChanged(p)
}
@@ -717,11 +730,12 @@ func (r *Room) subscribeToExistingTracks(p types.LocalParticipant) int {
}
// broadcast an update about participant p
func (r *Room) broadcastParticipantState(p types.LocalParticipant, skipSource bool) {
updates := ToProtoParticipants([]types.LocalParticipant{p})
func (r *Room) broadcastParticipantState(p types.LocalParticipant, opts broadcastOptions) {
pi := p.ToProto()
updates := []*livekit.ParticipantInfo{pi}
if p.Hidden() {
if !skipSource {
if !opts.skipSource {
// send update only to hidden participant
err := p.SendParticipantUpdate(updates)
if err != nil {
@@ -732,17 +746,27 @@ func (r *Room) broadcastParticipantState(p types.LocalParticipant, skipSource bo
return
}
participants := r.GetParticipants()
for _, op := range participants {
// skip itself && closed participants
if (skipSource && p.ID() == op.ID()) || op.State() == livekit.ParticipantInfo_DISCONNECTED {
if !pi.IsPublisher && !opts.immediate {
r.enqueueParticipantUpdate(pi)
return
} else {
r.clearParticipantUpdate(p.Identity())
}
r.sendParticipantUpdates(updates)
}
func (r *Room) sendParticipantUpdates(updates []*livekit.ParticipantInfo) {
for _, op := range r.GetParticipants() {
// skip closed participants
if op.State() == livekit.ParticipantInfo_DISCONNECTED {
continue
}
err := op.SendParticipantUpdate(updates)
if err != nil {
r.Logger.Errorw("could not send update to participant", err,
"participant", p.Identity(), "pID", p.ID())
"participant", op.Identity(), "pID", op.ID())
}
}
}
@@ -774,6 +798,52 @@ func (r *Room) sendSpeakerChanges(speakers []*livekit.SpeakerInfo) {
}
}
func (r *Room) enqueueParticipantUpdate(pi *livekit.ParticipantInfo) {
r.batchedUpdatesMu.Lock()
defer r.batchedUpdatesMu.Unlock()
identity := livekit.ParticipantIdentity(pi.Identity)
existing := r.batchedUpdates[identity]
if existing != nil && pi.Sid == existing.Sid && existing.Version > pi.Version {
return
}
r.batchedUpdates[identity] = pi
}
func (r *Room) clearParticipantUpdate(identity livekit.ParticipantIdentity) {
r.batchedUpdatesMu.Lock()
delete(r.batchedUpdates, identity)
r.batchedUpdatesMu.Unlock()
}
func (r *Room) subscriberBroadcastWorker() {
ticker := time.NewTicker(subscriberUpdateInterval)
defer ticker.Stop()
for !r.IsClosed() {
select {
case <-r.closed:
return
case <-ticker.C:
r.batchedUpdatesMu.Lock()
updatesMap := r.batchedUpdates
r.batchedUpdates = make(map[livekit.ParticipantIdentity]*livekit.ParticipantInfo)
r.batchedUpdatesMu.Unlock()
if len(updatesMap) == 0 {
continue
}
updates := make([]*livekit.ParticipantInfo, 0, len(updatesMap))
for _, pi := range updatesMap {
updates = append(updates, pi)
}
r.sendParticipantUpdates(updates)
}
}
}
func (r *Room) audioUpdateWorker() {
lastActiveMap := make(map[livekit.ParticipantID]*livekit.SpeakerInfo)
for {
+7 -7
View File
@@ -69,7 +69,7 @@ func TestJoinedState(t *testing.T) {
func TestRoomJoin(t *testing.T) {
t.Run("joining returns existing participant data", func(t *testing.T) {
rm := newRoomWithParticipants(t, testRoomOpts{num: numParticipants})
pNew := newMockParticipant("new", types.DefaultProtocol, false)
pNew := newMockParticipant("new", types.DefaultProtocol, false, false)
_ = rm.Join(pNew, nil, iceServersForRoom, "test")
@@ -84,7 +84,7 @@ func TestRoomJoin(t *testing.T) {
t.Run("subscribe to existing channels upon join", func(t *testing.T) {
numExisting := 3
rm := newRoomWithParticipants(t, testRoomOpts{num: numExisting})
p := newMockParticipant("new", types.DefaultProtocol, false)
p := newMockParticipant("new", types.DefaultProtocol, false, false)
err := rm.Join(p, &rtc.ParticipantOptions{AutoSubscribe: true}, iceServersForRoom, "")
require.NoError(t, err)
@@ -140,7 +140,7 @@ func TestRoomJoin(t *testing.T) {
t.Run("cannot exceed max participants", func(t *testing.T) {
rm := newRoomWithParticipants(t, testRoomOpts{num: 1})
rm.Room.MaxParticipants = 1
p := newMockParticipant("second", types.ProtocolVersion(0), false)
p := newMockParticipant("second", types.ProtocolVersion(0), false, false)
err := rm.Join(p, nil, iceServersForRoom, "")
require.Equal(t, rtc.ErrMaxParticipantsExceeded, err)
@@ -502,7 +502,7 @@ func TestHiddenParticipants(t *testing.T) {
rm := newRoomWithParticipants(t, testRoomOpts{num: 2, numHidden: 1})
defer rm.Close()
pNew := newMockParticipant("new", types.DefaultProtocol, false)
pNew := newMockParticipant("new", types.DefaultProtocol, false, false)
rm.Join(pNew, nil, iceServersForRoom, "testregion")
// expect new participant to get a JoinReply
@@ -516,7 +516,7 @@ func TestHiddenParticipants(t *testing.T) {
t.Run("hidden participant subscribes to tracks", func(t *testing.T) {
rm := newRoomWithParticipants(t, testRoomOpts{num: 2, numHidden: 1})
p := newMockParticipant("new", types.DefaultProtocol, false)
p := newMockParticipant("new", types.DefaultProtocol, false, true)
err := rm.Join(p, &rtc.ParticipantOptions{AutoSubscribe: true}, iceServersForRoom, "")
require.NoError(t, err)
@@ -574,11 +574,11 @@ func newRoomWithParticipants(t *testing.T, opts testRoomOpts) *rtc.Room {
)
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)
participant := newMockParticipant(identity, opts.protocol, i >= opts.num, true)
err := rm.Join(participant, &rtc.ParticipantOptions{AutoSubscribe: true}, iceServersForRoom, "")
require.NoError(t, err)
participant.StateReturns(livekit.ParticipantInfo_ACTIVE)
participant.IsReadyReturns(true)
require.NoError(t, err)
}
return rm
}