mirror of
https://github.com/livekit/livekit.git
synced 2026-12-04 08:58:09 +00:00
* Do not recover FlexFEC from RTX repaired packets A packet repaired from RTX takes its header from the RTX packet: libwebrtc adds a MID to retransmissions until the RTX SSRC is acknowledged, and sets abs-send-time and transport-cc at send time. The stored packet therefore differs from the media the publisher protected, so using it as a protected packet recovered the wrong length, failing with "invalid recovered packet size", or silently corrupted the recovered packet's header extensions when the length happened to match. Like libwebrtc's FlexfecReceiver, which skips packets recovered by RTX, mark RTX repaired sequence numbers and treat them as missing for FEC recovery. They are still forwarded and update NACK state as before. With a libwebrtc publisher at 10% upstream loss, every recovery attempt in a block containing a retransmitted packet failed; with retransmissions excluded recoveries succeed. * Move RTX repair tracking into BufferBase Keep the RTX repaired history, its lookup and the publisher sequence number extension in BufferBase, so every buffer built on it, such as the relay, can exclude RTX repaired packets from FlexFEC recovery the same way. The history is now cleared with the rest of the sequence number state when the stream restarts. Buffer only marks repaired packets from writeRTX. Packets recovered by FEC also enter with isRTX set, but they are exact reconstructions and stay usable, so marking is explicit rather than tied to that flag. * Keep RTX-repaired history safe with large packet caches The RTX repair history had 512 fixed slots. With a larger video packet cache, e.g. packet_buffer_size_video: 1500, two cached repairs could share a slot, the earlier mark was lost, and FlexFEC could recover from the altered retransmission. - Size the history from the video packet cache, at least 512 slots, and allocate it on the first repair. - When a later repair reuses a slot, the earlier packet counts as repaired: losing a recovery is better than corrupting one. - Do not mark a retransmission of a packet that is already cached. The bucket rejects it as a duplicate and keeps the exact packet, which stays usable for recovery. - Mark a repair before ingesting it and do not feed RTX repaired packets to the FEC decoder, as BufferBase now feeds ingested media to the decoder. * Generate downstream FlexFEC with per-track protection presets Generate FlexFEC-03 repairs for subscribed video tracks. Subscribers select none (default), low, medium or high through UpdateTrackSettings.fec; repairs require rtc.flexfec.downstream_enabled and negotiated flexfec-03 support. Generate repairs at each frame marker, splitting large frames into blocks of at most 48 packets, with upstream Q8 repair-count rounding and at least one repair per block. Reserve measured repair overhead during layer allocation and charge repair traffic to pacing, bandwidth estimation and metrics. Carry repair sequence state through the DownTrack GetState/SeedState handoff, apply subscriber settings from immutable snapshots, and preserve upstream FEC on shared sendrecv codec lists when downstream generation is disabled. This squashes the three commits of dc/feature/fec_down (38a67502,d269ac59,7b02897c) and rebases them onto master. Conflict resolution: - pacer.Packet keeps master's held-extension scratch next to the FEC field, and the DownTrack sets FEC on the pacer packet master now creates before adding extensions - DownTrackParams and subscriber config keep master's RTXBudget - configureSenderParams uses master's enableFlexFEC name - tests follow master: pion/transport v5 packetio, mid-less receivers skipped when restricting codecs, and settings compared by value since they are stored as merged snapshots Requires the UpdateTrackSettings.fec field from livekit/protocol#1794, which is not in the pinned protocol version yet. * Add end-to-end tests for downstream FlexFEC Publish a VP8 track through the SFU to a FlexFEC-capable subscriber, simulate downstream loss before the subscriber's receive buffer, and recover the dropped packets from the repairs actually sent, using the same FlexFEC-03 decoder as upstream recovery. RTX is dropped meanwhile so retransmissions cannot fill the gaps. The test checks that no repairs are sent before a preset is selected, that every preset recovers isolated losses bit-exactly, that presets change without renegotiation, and that a subscriber which declines flexfec-03 receives media but no repairs. Frames alternate between one and five packets, so repair counts match the Q8 rounding for both block sizes. The test client gains a subscriber RTP filter to simulate loss and accessors for the subscriber descriptions. The tests use their own ports so they can run next to a local server on the default ports. * Support downstream FEC protection modes Adopt the FECProtection message from livekit/protocol#1987: subscribers select a mode (disabled, adaptive, fixed, minimum) and a level (low, medium, high; unspecified is low) per track. As before, an update that omits fec keeps the previous setting. Unknown modes disable FEC and unknown levels are treated as unspecified. The modes follow libwebrtc's RtpParameters::fec_protection (webrtc-sdk/webrtc#329): - adaptive ports VCMNackFecMethod: the kFecRateTable lookup with a 10 second max-window loss filter, key frame boost, ConvertFECRate, NACK only delta frames below 20ms RTT, and BitRateTooLowForFec. Inputs are the subscriber's receiver reports, the sent bit and frame rates, and the forwarded layer's dimensions. - fixed uses the level for delta and key frames. - minimum uses the larger of the adaptive rate and the level. - the adaptive state is updated in every mode, so switching to adaptive or minimum starts from the current loss history, and a protection change keeps the group that is accumulating and protects it at the new rate. Key frames get their own protection factor, so pacer packets carry a key frame flag. Repairs are still generated per frame; multi-frame blocks (max_fec_frames) are not supported. The end-to-end tests report the simulated loss in receiver reports, since the test client sends none, and check that adaptive protection sends no repairs without loss and protects with loss, and that minimum protection matches its level without loss and rises with loss. Requires livekit/protocol#1987, which is not in the pinned protocol version yet. * Point protocol at livekit/protocol#1987 * Report loss before repair in receiver reports to publishers Receiver reports counted packets restored by RTX or recovered by FlexFEC as received, so as long as repairs kept up the reported fraction lost stayed at zero, even with 20% upstream loss. libwebrtc receivers exclude recovered packets from their receive statistics, and a publisher's loss-based protection depends on that: with no reported loss, FlexFEC backs off to almost no repairs. Packets that fill a loss through a repair are now counted separately, and receiver reports include them in the fraction and cumulative loss. Reordered packets that arrive on their own still cancel the loss. The fraction is also capped at 255, so a full loss no longer wraps to zero. With 20% simulated upstream loss from an Android publisher, the reported fraction lost goes from 0 to about 0.15, the FEC packets received over 30 seconds go from 64 to 204, and the packets recovered by FEC from 11 to 61. * Protect zeroed abs-send-time and TWCC in downstream FlexFEC The pacer encoded FEC after it had filled in abs-send-time and the transport-wide sequence number. libwebrtc generates FEC before its sender fills them in, and its FlexFEC receiver zeroes both in media packets before recovery. Packets recovered from SFU repairs therefore got wrong bytes in those extensions, and in the payload when the header lengths within a group differed, for example when only the first packet carried abs-capture-time. Zero both extensions after the media packet is written and before it is fed to the encoder. * Aggregate receiver report loss for adaptive FEC protection Adaptive and minimum protection fed the fraction lost of every reception report into the max-window loss filter. libwebrtc receivers can send a report with each NACK, so a report often covers only a few packets and its fraction lost is very noisy. With 10% random loss, single reports read up to 70%, and the filter kept the maximum. Derive loss from the cumulative counters instead and produce a sample only once it covers at least 20 expected packets, like libwebrtc's SendSideBandwidthEstimation::UpdatePacketsLost. The end-to-end tests now report cumulative loss and the extended highest sequence number in their receiver reports. * Report loss before repair only to FlexFEC publishers Counting repaired packets as lost in receiver reports applied to every publisher, so any publisher whose loss RTX repaired started to see that loss and its bandwidth estimate could back off sooner. Only FlexFEC protection needs loss before repair to choose its rate. Count repairs only for streams that negotiated flexfec-03, which requires FlexFEC to be enabled on the server. Other publishers keep receiving loss after repair, as before. * Keep the newest RTX repair mark of a history slot A late retransmission of an older packet that has aged out of the cache overwrote the slot of a newer repair sharing it. The newer repair, which carries the RTX packet's header, could then be used for FlexFEC recovery and corrupt the recovered packet. Keep the highest extended sequence number written to a slot until the stream restarts. isRTXRepairedLocked already treats an older packet in a slot with a newer mark as repaired. * Measure FEC overhead against all media The allocator scales the whole media bitrate by the measured repair overhead, but the overhead was measured against protected media only. With adaptive protection below 20 ms RTT only key frames are protected, so the ratio of key frame repairs to key frame media was applied to every frame, and the reservation could make the allocator lower the layer or pause the track although the bandwidth was sufficient. Count all non-padding media while any protection is active. * Keep the loss sample that closes a filter window The max-window loss filter, ported from libwebrtc, dropped the report that closes a one-second window when the window already had a maximum, so a loss spike arriving on the boundary never reached adaptive protection. Store the larger of the window's maximum and that sample. * Skip the encoder allocation check under the race detector CI runs the tests with -race and swaps sync.Mutex for go-deadlock, whose Lock allocates, so Encode allocated about once per call there. Check allocations only without the race detector, like the other allocation tests. * Bump protocol to v1.55.0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sfu: reserve measured FEC overhead only on the forwarded layer The measured repair overhead comes from the spatial layer being forwarded. On a low layer with one or two packets per frame it can be 60-100%, and applying it to every layer reserved the high layer at nearly twice its cost, so the allocator could stay on the low layer. Attribute measurements to the forwarded spatial layer, restarting them when forwarding starts, resumes or switches layers, and reserve the configured rate for the other layers. Also reallocate only when a reserved overhead moves by 5 points or more, or turns on or off, so that per-second measurements and adaptive protection do not re-run allocation on every receiver report. * buffer: gate upstream FlexFEC on an explicit flag A publisher PC registers flexfec-03 when only downstream FEC is enabled, because it can also carry subscriptions. Its buffers then got a FEC payload type, which reported loss before repair to the publisher and let the decoder start from the observed repair SSRC, although upstream FEC was disabled. Buffers now ignore the negotiated FlexFEC payload type unless the buffer factory enables upstream FlexFEC. * pacer: protect interceptor-written transport-cc as zeros in FEC With UseSendSideBWEInterceptor, Pion's TWCC header extension interceptor writes transport-cc during WriteRTP while the DownTrack leaves TransportWideExtID at zero. The extension was then protected with its non-zero value, which the receiver zeroes before recovery, so recovered packets got wrong bytes there. Pass the negotiated transport-cc ID to the pacer for FEC and zero it before encoding as well. * sfu: skip the FEC encoder while protection is disabled The encoder was attached whenever flexfec-03 was negotiated, including in the default disabled mode, so every forwarded packet took the encoder lock and updated the adaptive state without generating repairs. Pass the encoder to the pacer only while protection is enabled. Receiver reports still keep the loss history; adaptive protection measures media rates again once enabled. * sfu: account sent FEC repairs in the down track RTP stats Repairs were counted only in the aggregate Prometheus counter, so the down track's stats under-counted what the subscriber receives. Record them in the sender's FEC packet and byte counters, separate from media, and export the FEC counters in RTPStats for both directions. * rtc: merge subscriber FEC settings in one place The subscription merged and normalized settings, and the subscribed track merged and normalized them again, while the DownTrack mapped unknown modes and levels a third time. Merge only in the subscription, store the merged settings in the subscribed track as is, and leave unknown values to the DownTrack. * prometheus: resolve fixed-label FEC counters once RecordFECDownstream runs on the pacer path for every repair batch and looked up both counter vectors by label each time. * rtpstats: seed a sender without holding both locks Seed took the receiving sender's lock and then the source's, so two senders seeding from each other at the same time could deadlock. Copy the source's state under its own lock first, then apply the copy under the receiving sender's lock. * telemetry: count FlexFEC repairs in traffic totals Retransmissions and padding count towards node and participant traffic, but FEC repairs, which are also on the wire, did not. Add repairs sent and received to the node packet and byte totals, and to the packets and bytes of TrafficStats. Analytics streams are unchanged: AnalyticsStream has no FEC field. * sfu: read the FEC transport-cc ID atomically setRTPHeaderExtensions runs again when the stream allocator listener is set, which can happen while media is already forwarded, and WriteRTP read the ID without synchronization. Store it atomically once the extensions are processed. * telemetry: count only FEC repairs sent in node traffic Media recovered from FEC repairs is counted as received media, so adding the repairs received to node ingress counted recovered packets twice. Node traffic feeds room admission against limit.bytes_per_sec, so ingress must not be inflated. Keep repairs sent in node egress, where nothing is synthesized, and leave ingress as before. TrafficStats is derived from RTPStats without a direction, so it cannot tell repairs sent from repairs received; leave it without FEC. * rtc: add WebRTCConfig.SetFlexFEC for per-session FlexFEC settings * rtc: apply a session's upstream FlexFEC to its buffers SetFlexFEC changed what a session negotiates with its publisher, but the publisher's buffers still followed the node config: the room's buffer factory read it once. A session with upstream on and a node with it off negotiated flexfec-03, so the publisher sent repairs that its buffers ignored; the reverse turned on upstream recovery and loss reported before repair for a session that asked for neither. The session's buffer factory now follows the session's upstream setting, whichever of SetFlexFEC and SetBufferFactory comes first. Without a SetFlexFEC call it follows the node config, as before. The setting applies to buffers the factory creates afterwards, so SetFlexFEC is meant to be called while the session is set up, before any track is published. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Jules Testard <jules.testard@livekit.io> Co-authored-by: David Chen <chenosaurus@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
501 lines
17 KiB
Go
501 lines
17 KiB
Go
// 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 flexfec
|
|
|
|
import (
|
|
"math/rand/v2"
|
|
"sync"
|
|
"time"
|
|
|
|
pionflexfec "github.com/pion/interceptor/pkg/flexfec"
|
|
"github.com/pion/rtp"
|
|
"go.uber.org/atomic"
|
|
"go.uber.org/zap/zapcore"
|
|
|
|
"github.com/livekit/protocol/utils/mono"
|
|
)
|
|
|
|
const (
|
|
MaxProtectionPercent uint32 = 100
|
|
// MaxMediaPacketsPerGroup bounds memory and work for large frames. Like
|
|
// libwebrtc, use at most 48 media packets in a protection block.
|
|
MaxMediaPacketsPerGroup = 48
|
|
maxEncoderGroupAge = 200 * time.Millisecond
|
|
overheadUpdateInterval = time.Second
|
|
// Reserve all three FEC masks and up to 16 bytes of outer RTP extensions
|
|
// (AST/TWCC). A 48-packet group can require the third mask.
|
|
maxEncoderMediaPacketSize = maxMediaPacketSize - pionflexfec.BaseFec03HeaderSize - 12 - 16
|
|
)
|
|
|
|
// EncoderState preserves the repair sequence when a sender SSRC is reused.
|
|
// Partial media groups are never carried over to a new binding.
|
|
type EncoderState struct {
|
|
SSRC uint32
|
|
NextSequenceNumber uint16
|
|
}
|
|
|
|
func (s EncoderState) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
|
e.AddUint32("SSRC", s.SSRC)
|
|
e.AddUint16("NextSequenceNumber", s.NextSequenceNumber)
|
|
return nil
|
|
}
|
|
|
|
type encoderMediaGroup struct {
|
|
packets [MaxMediaPacketsPerGroup]rtp.Packet
|
|
storage [MaxMediaPacketsPerGroup]*[maxEncoderMediaPacketSize]byte
|
|
}
|
|
|
|
// Encoder batches final, outgoing video packets for Pion's FlexFEC-03 encoder.
|
|
// It owns reusable wire storage: the caller may recycle headers, extensions and
|
|
// payloads as soon as Encode returns. It does not delay media or start workers.
|
|
// Methods are safe to call from concurrent pass-through pacer writes.
|
|
type Encoder struct {
|
|
mu sync.Mutex
|
|
encoder *pionflexfec.FlexEncoder03
|
|
media *encoderMediaGroup
|
|
count int
|
|
startedAt int64
|
|
sequenceNumber uint16
|
|
ssrc uint32
|
|
closed bool
|
|
onSent func(packets int, bytes int)
|
|
|
|
protection Protection
|
|
// enabled mirrors protection.Mode != ProtectionDisabled for lock-free reads.
|
|
enabled atomic.Bool
|
|
// adaptive is updated in every mode, like libwebrtc runs its adaptive
|
|
// computation before applying a protection override, so that switching
|
|
// to adaptive or minimum protection starts from the current loss history.
|
|
adaptive *adaptiveState
|
|
// effective Q8 repair-to-media packet ratios for delta and key frames
|
|
deltaFactor uint8
|
|
keyFactor uint8
|
|
// whether the frame with frameTimestamp contains key frame packets
|
|
frameTimestamp uint32
|
|
frameKey bool
|
|
|
|
// overheadPercent is the larger of configuredPercent and measuredPercent;
|
|
// the atomics let the allocator read without contending with encoding.
|
|
overheadPercent atomic.Uint32
|
|
configuredOverhead atomic.Uint32
|
|
// measuredLayer is the forwarded spatial layer measuredPercent belongs to.
|
|
measuredLayer atomic.Int32
|
|
configuredPercent uint32
|
|
measuredPercent uint32
|
|
overheadUpdatedAt int64
|
|
sentMediaBytes uint64
|
|
sentRepairBytes uint64
|
|
}
|
|
|
|
func NewEncoder(payloadType uint8, ssrc uint32, onSent func(packets int, bytes int)) *Encoder {
|
|
e := &Encoder{
|
|
encoder: pionflexfec.NewFlexEncoder03(payloadType, ssrc),
|
|
sequenceNumber: uint16(rand.Uint32()),
|
|
ssrc: ssrc,
|
|
onSent: onSent,
|
|
adaptive: newAdaptiveState(mono.UnixNano()),
|
|
}
|
|
e.measuredLayer.Store(InvalidLayer)
|
|
return e
|
|
}
|
|
|
|
func (e *Encoder) GetState() EncoderState {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
return EncoderState{SSRC: e.ssrc, NextSequenceNumber: e.sequenceNumber}
|
|
}
|
|
|
|
// SeedState must be called before forwarding starts. Only reuse sequencing for
|
|
// the same repair SSRC; a new SSRC keeps its randomized initial sequence number.
|
|
func (e *Encoder) SeedState(state EncoderState) {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
if e.closed || state.SSRC == 0 || state.SSRC != e.ssrc {
|
|
return
|
|
}
|
|
e.sequenceNumber = state.NextSequenceNumber
|
|
e.count = 0
|
|
}
|
|
|
|
// Encode returns independently owned repairs at the end of a video frame (the
|
|
// RTP marker), splitting large frames at MaxMediaPacketsPerGroup. Timestamp
|
|
// changes discard an incomplete previous frame. Gaps, codec switches and stale
|
|
// groups also reset the block; Pion requires consecutive sequence numbers.
|
|
// Media is never delayed. No timer or worker is needed for sparse frames.
|
|
// keyFrame marks packets of key frames, which use the key frame protection
|
|
// factor; it is enough to mark one packet of each key frame.
|
|
// Call after the media write, including any interceptor header modifications.
|
|
func (e *Encoder) Encode(header *rtp.Header, payload []byte, keyFrame bool) []rtp.Packet {
|
|
return e.encode(mono.UnixNano(), header, payload, keyFrame)
|
|
}
|
|
|
|
func (e *Encoder) encode(now int64, header *rtp.Header, payload []byte, keyFrame bool) []rtp.Packet {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
if e.closed {
|
|
return nil
|
|
}
|
|
|
|
size := header.MarshalSize() + len(payload)
|
|
if header.Timestamp != e.frameTimestamp {
|
|
e.frameTimestamp = header.Timestamp
|
|
e.frameKey = false
|
|
}
|
|
e.frameKey = e.frameKey || keyFrame
|
|
e.adaptive.onMediaPacket(now, len(payload), header.Marker, e.frameKey)
|
|
factor := e.deltaFactor
|
|
if e.frameKey {
|
|
factor = e.keyFactor
|
|
}
|
|
if (e.deltaFactor != 0 || e.keyFactor != 0) && !header.Padding && len(payload) != 0 {
|
|
// Measure overhead against all media, protected or not: the allocator
|
|
// scales the whole media bitrate by it, and with key frame only
|
|
// protection most media is unprotected.
|
|
e.sentMediaBytes += uint64(size)
|
|
}
|
|
if factor == 0 || header.Padding || len(payload) == 0 || size > maxEncoderMediaPacketSize {
|
|
e.count = 0
|
|
return nil
|
|
}
|
|
if e.media == nil {
|
|
// Like the upstream recovery buffer, allocate packet storage only once
|
|
// it is needed. Negotiated tracks with the default "none" stay small.
|
|
e.media = &encoderMediaGroup{}
|
|
}
|
|
if e.count != 0 {
|
|
previous := &e.media.packets[e.count-1]
|
|
if header.SequenceNumber != previous.SequenceNumber+1 ||
|
|
header.SSRC != previous.SSRC || header.PayloadType != previous.PayloadType ||
|
|
header.Timestamp != previous.Timestamp ||
|
|
now-e.startedAt > int64(maxEncoderGroupAge) {
|
|
e.count = 0
|
|
}
|
|
}
|
|
if e.count == 0 {
|
|
e.startedAt = now
|
|
}
|
|
|
|
if e.media.storage[e.count] == nil {
|
|
// Retain only the packet buffers this stream has actually needed.
|
|
e.media.storage[e.count] = new([maxEncoderMediaPacketSize]byte)
|
|
}
|
|
raw := e.media.storage[e.count][:size]
|
|
n, err := header.MarshalTo(raw)
|
|
if err != nil {
|
|
e.count = 0
|
|
return nil
|
|
}
|
|
copy(raw[n:], payload)
|
|
if err = e.media.packets[e.count].Unmarshal(raw); err != nil {
|
|
e.count = 0
|
|
return nil
|
|
}
|
|
e.count++
|
|
if !header.Marker && e.count < MaxMediaPacketsPerGroup {
|
|
return nil
|
|
}
|
|
|
|
count := e.count
|
|
e.count = 0
|
|
// Match libwebrtc's ForwardErrorCorrection::NumFecPackets: round the Q8
|
|
// protection factor, with at least one repair for every protected block.
|
|
// In particular, a one-packet frame is protected immediately at every preset.
|
|
numRepair := max(uint32(1), (uint32(count)*uint32(factor)+128)>>8)
|
|
repair := e.encoder.EncodeFec(e.media.packets[:count], numRepair)
|
|
for i := range repair {
|
|
// Pion's encoder uses a constant timestamp and a fixed initial sequence number.
|
|
// Use this stream's media clock and a randomized, continuous repair sequence.
|
|
repair[i].Timestamp = header.Timestamp
|
|
repair[i].SequenceNumber = e.sequenceNumber
|
|
e.sequenceNumber++
|
|
}
|
|
return repair
|
|
}
|
|
|
|
// SetProtection updates the requested protection without changing the repair
|
|
// SSRC or sequence number. Like libwebrtc, a group that is already
|
|
// accumulating is kept and protected with the new rate when it completes, and
|
|
// the adaptive state keeps its history. Overhead measurements restart.
|
|
// Disabling stops encoding before any packet copies.
|
|
func (e *Encoder) SetProtection(protection Protection) {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
if protection.Mode < ProtectionDisabled || protection.Mode > ProtectionMinimum {
|
|
protection = Protection{}
|
|
}
|
|
if protection.Mode != ProtectionFixed && protection.Mode != ProtectionMinimum {
|
|
protection.Factor = 0
|
|
}
|
|
if e.protection == protection {
|
|
return
|
|
}
|
|
e.protection = protection
|
|
e.enabled.Store(protection.Mode != ProtectionDisabled)
|
|
e.resetMeasurementLocked()
|
|
e.setFactorsLocked(e.effectiveFactorsLocked())
|
|
}
|
|
|
|
// Enabled reports whether protection is requested, without taking the encoder
|
|
// lock. Callers may skip Encode while it is false: no repairs are generated,
|
|
// and receiver reports still keep the loss history for adaptive protection.
|
|
func (e *Encoder) Enabled() bool {
|
|
return e.enabled.Load()
|
|
}
|
|
|
|
func (e *Encoder) resetMeasurementLocked() {
|
|
e.measuredPercent = 0
|
|
e.overheadUpdatedAt = 0
|
|
e.sentMediaBytes = 0
|
|
e.sentRepairBytes = 0
|
|
}
|
|
|
|
// InvalidLayer marks a measurement that belongs to no forwarded layer.
|
|
const InvalidLayer = -1
|
|
|
|
// SetMeasurementLayer attributes overhead measurements to the forwarded
|
|
// spatial layer. Frames of different layers have different packet counts, so
|
|
// the repair overhead measured on one layer does not apply to another; a
|
|
// layer change restarts the measurement.
|
|
func (e *Encoder) SetMeasurementLayer(layer int32) {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
if e.measuredLayer.Load() == layer {
|
|
return
|
|
}
|
|
e.measuredLayer.Store(layer)
|
|
e.resetMeasurementLocked()
|
|
e.overheadPercent.Store(e.configuredPercent)
|
|
}
|
|
|
|
// SetProtectionPercent sets a fixed repair-to-media packet percentage; values
|
|
// above 100 are capped and zero disables encoding.
|
|
func (e *Encoder) SetProtectionPercent(percent uint32) {
|
|
if percent == 0 {
|
|
e.SetProtection(Protection{})
|
|
return
|
|
}
|
|
e.SetProtection(Protection{Mode: ProtectionFixed, Factor: ProtectionFactorFromPercent(percent)})
|
|
}
|
|
|
|
// NetworkStats are the receiver-side inputs of adaptive protection.
|
|
type NetworkStats struct {
|
|
// FractionLost is the Q8 loss fraction from an RTCP reception report.
|
|
FractionLost uint8
|
|
RTT time.Duration
|
|
// Width and Height of the forwarded video, zero when unknown.
|
|
Width uint32
|
|
Height uint32
|
|
}
|
|
|
|
// OnReceiverReport updates the adaptive state from a reception report of the
|
|
// protected media stream. It changes the effective rates only in adaptive and
|
|
// minimum modes, but is tracked in every mode.
|
|
func (e *Encoder) OnReceiverReport(stats NetworkStats) {
|
|
e.onReceiverReport(mono.UnixNano(), stats)
|
|
}
|
|
|
|
func (e *Encoder) onReceiverReport(now int64, stats NetworkStats) {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
if e.closed {
|
|
return
|
|
}
|
|
e.adaptive.update(now, stats)
|
|
e.setFactorsLocked(e.effectiveFactorsLocked())
|
|
}
|
|
|
|
// ProtectionFactors returns the effective Q8 repair-to-media packet ratios for
|
|
// delta and key frames.
|
|
func (e *Encoder) ProtectionFactors() (delta uint8, key uint8) {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
return e.deltaFactor, e.keyFactor
|
|
}
|
|
|
|
// effectiveFactorsLocked applies the requested mode on top of the adaptive
|
|
// factors, like libwebrtc's ApplyProtectionOverride.
|
|
func (e *Encoder) effectiveFactorsLocked() (uint8, uint8) {
|
|
switch e.protection.Mode {
|
|
case ProtectionFixed:
|
|
return e.protection.Factor, e.protection.Factor
|
|
case ProtectionAdaptive:
|
|
return e.adaptive.deltaFactor, e.adaptive.keyFactor
|
|
case ProtectionMinimum:
|
|
return max(e.adaptive.deltaFactor, e.protection.Factor), max(e.adaptive.keyFactor, e.protection.Factor)
|
|
default:
|
|
return 0, 0
|
|
}
|
|
}
|
|
|
|
func (e *Encoder) setFactorsLocked(delta uint8, key uint8) {
|
|
e.deltaFactor, e.keyFactor = delta, key
|
|
if delta == 0 && key == 0 {
|
|
// Nothing will be sent, so measurements would never refresh.
|
|
e.count = 0
|
|
e.resetMeasurementLocked()
|
|
}
|
|
// Reserve for delta frames; key frames are rare and are not reserved for.
|
|
e.configuredPercent = protectionFactorToPercent(delta)
|
|
e.configuredOverhead.Store(e.configuredPercent)
|
|
e.overheadPercent.Store(max(e.configuredPercent, e.measuredPercent))
|
|
}
|
|
|
|
// OverheadPercent reserves at least the configured rate, using measured RTP
|
|
// bytes when frame rounding or repair headers increase the actual overhead.
|
|
// The measurement belongs to one spatial layer; see Overhead.
|
|
// Reads by the allocator do not contend with encoding.
|
|
func (e *Encoder) OverheadPercent() uint32 {
|
|
return e.overheadPercent.Load()
|
|
}
|
|
|
|
// OverheadEstimate is the repair overhead to reserve per spatial layer.
|
|
type OverheadEstimate struct {
|
|
// ConfiguredPercent is the nominal repair-to-media rate of every layer.
|
|
ConfiguredPercent uint32
|
|
// LayerPercent applies to Layer instead, at least ConfiguredPercent and
|
|
// raised by the overhead measured while forwarding it.
|
|
LayerPercent uint32
|
|
Layer int32
|
|
}
|
|
|
|
// PercentForLayer returns the overhead to reserve for a spatial layer.
|
|
func (o OverheadEstimate) PercentForLayer(layer int32) uint32 {
|
|
if layer == o.Layer {
|
|
return o.LayerPercent
|
|
}
|
|
return o.ConfiguredPercent
|
|
}
|
|
|
|
// Overhead returns the current estimate without contending with encoding.
|
|
// Fields are read independently and may briefly mix two updates.
|
|
func (e *Encoder) Overhead() OverheadEstimate {
|
|
return OverheadEstimate{
|
|
ConfiguredPercent: e.configuredOverhead.Load(),
|
|
LayerPercent: e.overheadPercent.Load(),
|
|
Layer: e.measuredLayer.Load(),
|
|
}
|
|
}
|
|
|
|
// RecordSent accounts successful repairs, including headers for the allocator
|
|
// and payload bytes for the upstream-compatible telemetry callback. Refresh the
|
|
// estimate on the first repair and at most once per second thereafter.
|
|
// Callbacks run outside the encoder lock.
|
|
func (e *Encoder) RecordSent(packets int, payloadBytes int, rtpBytes int) {
|
|
if packets == 0 {
|
|
return
|
|
}
|
|
e.mu.Lock()
|
|
if !e.closed && e.protection.Mode != ProtectionDisabled {
|
|
e.sentRepairBytes += uint64(rtpBytes)
|
|
now := mono.UnixNano()
|
|
if e.sentMediaBytes != 0 && (e.overheadUpdatedAt == 0 || now-e.overheadUpdatedAt >= int64(overheadUpdateInterval)) {
|
|
e.measuredPercent = uint32((e.sentRepairBytes*100 + e.sentMediaBytes - 1) / e.sentMediaBytes)
|
|
e.overheadPercent.Store(max(e.configuredPercent, e.measuredPercent))
|
|
e.overheadUpdatedAt = now
|
|
e.sentMediaBytes = 0
|
|
e.sentRepairBytes = 0
|
|
}
|
|
}
|
|
e.mu.Unlock()
|
|
if e.onSent != nil {
|
|
e.onSent(packets, payloadBytes)
|
|
}
|
|
}
|
|
|
|
// Close prevents queued packets from generating repairs after unbind/close.
|
|
func (e *Encoder) Close() {
|
|
e.mu.Lock()
|
|
e.closed = true
|
|
e.count = 0
|
|
e.media = nil
|
|
e.encoder = nil
|
|
e.mu.Unlock()
|
|
}
|
|
|
|
// adaptiveState holds the inputs of libwebrtc's loss protection logic that
|
|
// the encoder measures itself: sent bit rate, frame rate and packets per frame.
|
|
type adaptiveState struct {
|
|
loss lossFilter
|
|
|
|
packetsPerFrame expFilter
|
|
packetsPerFrameKey expFilter
|
|
packetsPerFrameAt int64
|
|
packetsPerFrameKeyAt int64
|
|
frameBytes int
|
|
windowStart int64
|
|
windowBytes uint64
|
|
windowFrames uint64
|
|
bitrateKbps float64
|
|
frameRate float64
|
|
deltaFactor uint8
|
|
keyFactor uint8
|
|
}
|
|
|
|
// Use at least this window to measure the sent bit and frame rates.
|
|
const minRateWindow = 500 * time.Millisecond
|
|
|
|
func newAdaptiveState(now int64) *adaptiveState {
|
|
return &adaptiveState{
|
|
loss: newLossFilter(),
|
|
packetsPerFrame: newExpFilter(packetsPerFrameAlpha),
|
|
packetsPerFrameKey: newExpFilter(packetsPerFrameAlpha),
|
|
packetsPerFrameAt: now,
|
|
packetsPerFrameKeyAt: now,
|
|
windowStart: now,
|
|
}
|
|
}
|
|
|
|
func (a *adaptiveState) onMediaPacket(now int64, payloadSize int, marker bool, keyFrame bool) {
|
|
a.windowBytes += uint64(payloadSize)
|
|
a.frameBytes += payloadSize
|
|
if !marker {
|
|
return
|
|
}
|
|
a.windowFrames++
|
|
// Like FecControllerDefault::UpdateWithEncodedData, estimate packets from
|
|
// the frame size so that the key/delta ratio does not depend on packetization.
|
|
packets := float64(a.frameBytes) / adaptiveMaxPayloadSize
|
|
a.frameBytes = 0
|
|
if keyFrame {
|
|
a.packetsPerFrameKey.apply(float64(now-a.packetsPerFrameKeyAt)/1e6, packets)
|
|
a.packetsPerFrameKeyAt = now
|
|
} else {
|
|
a.packetsPerFrame.apply(float64(now-a.packetsPerFrameAt)/1e6, packets)
|
|
a.packetsPerFrameAt = now
|
|
}
|
|
}
|
|
|
|
func (a *adaptiveState) update(now int64, stats NetworkStats) {
|
|
if elapsed := now - a.windowStart; elapsed >= int64(minRateWindow) {
|
|
elapsedMs := float64(elapsed) / 1e6
|
|
// bits per millisecond is kbps
|
|
a.bitrateKbps = float64(a.windowBytes) * 8 / elapsedMs
|
|
a.frameRate = float64(a.windowFrames) * 1000 / elapsedMs
|
|
a.windowStart = now
|
|
a.windowBytes = 0
|
|
a.windowFrames = 0
|
|
}
|
|
a.deltaFactor, a.keyFactor = adaptiveProtectionFactors(adaptiveParams{
|
|
loss: a.loss.filteredLoss(now/1e6, stats.FractionLost),
|
|
rttMs: stats.RTT.Milliseconds(),
|
|
bitrateKbps: a.bitrateKbps,
|
|
frameRate: a.frameRate,
|
|
packetsPerFrame: a.packetsPerFrame.filtered,
|
|
packetsPerFrameKey: a.packetsPerFrameKey.filtered,
|
|
width: int(stats.Width),
|
|
height: int(stats.Height),
|
|
})
|
|
}
|