diff --git a/pkg/sfu/bwe/sendsidebwe/congestion_detector.go b/pkg/sfu/bwe/sendsidebwe/congestion_detector.go index 0151a295..23bcc36e 100644 --- a/pkg/sfu/bwe/sendsidebwe/congestion_detector.go +++ b/pkg/sfu/bwe/sendsidebwe/congestion_detector.go @@ -68,8 +68,8 @@ type ProbeSignalConfig struct { JQRMinDelay time.Duration `yaml:"jqr_min_delay,omitempty"` DQRMaxDelay time.Duration `yaml:"dqr_max_delay,omitempty"` - WeightedLoss WeightedLossConfig `yaml:"weighted_loss,omitempty"` - CongestionMinLoss float64 `yaml:"congestion_min_loss,omitempty"` + WeightedLoss WeightedLossConfig `yaml:"weighted_loss,omitempty"` + CongestionMinWeightedLoss float64 `yaml:"congestion_min_weighted_loss,omitempty"` } func (p ProbeSignalConfig) IsValid(pci ccutils.ProbeClusterInfo) bool { @@ -87,7 +87,7 @@ func (p ProbeSignalConfig) ProbeSignal(ppg *probePacketGroup) (ccutils.ProbeSign return ccutils.ProbeSignalCongesting, ts.AcknowledgedBitrate() } - if ts.WeightedLoss() > p.CongestionMinLoss { + if ts.WeightedLoss() > p.CongestionMinWeightedLoss { return ccutils.ProbeSignalCongesting, ts.AcknowledgedBitrate() } @@ -106,8 +106,8 @@ var ( JQRMinDelay: 15 * time.Millisecond, DQRMaxDelay: 5 * time.Millisecond, - WeightedLoss: defaultWeightedLossConfig, - CongestionMinLoss: 0.25, + WeightedLoss: defaultWeightedLossConfig, + CongestionMinWeightedLoss: 0.25, } ) @@ -335,8 +335,8 @@ type CongestionDetectorConfig struct { JQRMinDelay time.Duration `yaml:"jqr_min_delay,omitempty"` DQRMaxDelay time.Duration `yaml:"dqr_max_delay,omitempty"` - WeightedLoss WeightedLossConfig `yaml:"weighted_loss,omitempty"` - CongestionMinLoss float64 `yaml:"congestion_min_loss,omitempty"` + WeightedLoss WeightedLossConfig `yaml:"weighted_loss,omitempty"` + CongestionMinWeightedLoss float64 `yaml:"congestion_min_weighted_loss,omitempty"` QueuingDelayEarlyWarning CongestionSignalConfig `yaml:"queuing_delay_early_warning,omitempty"` LossEarlyWarning CongestionSignalConfig `yaml:"loss_early_warning,omitempty"` @@ -377,8 +377,8 @@ var ( JQRMinDelay: 15 * time.Millisecond, DQRMaxDelay: 5 * time.Millisecond, - WeightedLoss: defaultWeightedLossConfig, - CongestionMinLoss: 0.25, + WeightedLoss: defaultWeightedLossConfig, + CongestionMinWeightedLoss: 0.25, QueuingDelayEarlyWarning: defaultQueuingDelayEarlyWarningCongestionSignalConfig, LossEarlyWarning: defaultLossEarlyWarningCongestionSignalConfig, @@ -731,7 +731,7 @@ func (c *congestionDetector) isCongestionSignalTriggered() (bool, string, bool, c.params.Config.LossEarlyWarning, c.params.Config.LossCongested, c.params.Config.WeightedLoss, - c.params.Config.CongestionMinLoss, + c.params.Config.CongestionMinWeightedLoss, c.params.Logger, ) @@ -760,11 +760,13 @@ func (c *congestionDetector) isCongestionSignalTriggered() (bool, string, bool, if earlyWarningTriggered { earlyWarningReason = "queuing-delay" oldestContributingGroup = qdMeasurement.EarlyWarningGroupIdx() + c.params.Logger.Debugw("send side bwe: early warning queuing-delay", "qd", qdMeasurement) } else { earlyWarningTriggered = lossMeasurement.IsEarlyWarningTriggered() if earlyWarningTriggered { earlyWarningReason = "loss" oldestContributingGroup = lossMeasurement.EarlyWarningGroupIdx() + c.params.Logger.Debugw("send side bwe: early warning loss", "loss", lossMeasurement) } } @@ -773,11 +775,13 @@ func (c *congestionDetector) isCongestionSignalTriggered() (bool, string, bool, if congestedTriggered { congestedReason = "queuing-delay" oldestContributingGroup = qdMeasurement.CongestedGroupIdx() + c.params.Logger.Debugw("send side bwe: congested queuing-delay", "qd", qdMeasurement) } else { congestedTriggered = lossMeasurement.IsCongestedTriggered() if congestedTriggered { congestedReason = "loss" oldestContributingGroup = lossMeasurement.CongestedGroupIdx() + c.params.Logger.Debugw("send side bwe: congested loss", "loss", lossMeasurement) } } @@ -793,7 +797,7 @@ func (c *congestionDetector) congestionDetectionStateMachine() (bool, bwe.Conges switch state { case bwe.CongestionStateNone: - if congestedTriggered { + if congestedTriggered && !earlyWarningTriggered { c.params.Logger.Warnw("send side bwe: invalid congested state transition", nil, "from", state, "reason", congestedReason) } if earlyWarningTriggered { @@ -810,7 +814,7 @@ func (c *congestionDetector) congestionDetectionStateMachine() (bool, bwe.Conges } case bwe.CongestionStateEarlyWarningHangover: - if congestedTriggered { + if congestedTriggered && !earlyWarningTriggered { c.params.Logger.Warnw("send side bwe: invalid congested state transition", nil, "from", state, "reason", congestedReason) } if earlyWarningTriggered { @@ -826,7 +830,7 @@ func (c *congestionDetector) congestionDetectionStateMachine() (bool, bwe.Conges } case bwe.CongestionStateCongestedHangover: - if congestedTriggered { + if congestedTriggered && !earlyWarningTriggered { c.params.Logger.Warnw("send side bwe: invalid congested state transition", nil, "from", state, "reason", congestedReason) } if earlyWarningTriggered { diff --git a/pkg/sfu/bwe/sendsidebwe/packet_tracker.go b/pkg/sfu/bwe/sendsidebwe/packet_tracker.go index 17acbd48..a41e50fe 100644 --- a/pkg/sfu/bwe/sendsidebwe/packet_tracker.go +++ b/pkg/sfu/bwe/sendsidebwe/packet_tracker.go @@ -112,7 +112,7 @@ func (p *packetTracker) RecordPacketIndicationFromRemote(sn uint16, recvTime int } if recvTime == 0 { - // maybe lost OR already receied but reported lost in a later report + // maybe lost OR already received but reported lost in a later report piRecv = *pi return } diff --git a/pkg/sfu/ccutils/prober.go b/pkg/sfu/ccutils/prober.go index 5e7e31eb..210a4b0c 100644 --- a/pkg/sfu/ccutils/prober.go +++ b/pkg/sfu/ccutils/prober.go @@ -195,6 +195,15 @@ func (p *Prober) AddCluster(mode ProbeClusterMode, pcg ProbeClusterGoal) ProbeCl return cluster.Info() } +func (p *Prober) ProbesSent(bytesSent int) { + cluster := p.getFrontCluster() + if cluster == nil { + return + } + + cluster.ProbesSent(bytesSent) +} + func (p *Prober) ClusterDone(info ProbeClusterInfo) { cluster := p.getFrontCluster() if cluster == nil { @@ -293,7 +302,11 @@ type ProbeClusterId uint32 const ( ProbeClusterIdInvalid ProbeClusterId = 0 - cBytesPerProbe = 1100 // padding only packets are 255 bytes max + 20 byte header = 4 packets per probe + // padding only packets are 255 bytes max + 20 byte header = 4 packets per probe, + // when not using padding only packets, this is a min and actual sent could be higher + cBytesPerProbe = 1100 + cSleepDuration = 20 * time.Millisecond + cSleepDurationMin = 10 * time.Millisecond ) // ----------------------------------- @@ -395,6 +408,19 @@ func (p ProbeClusterInfo) MarshalLogObject(e zapcore.ObjectEncoder) error { // --------------------------------------------------------------------------- +type bucket struct { + expectedElapsedDuration time.Duration + expectedProbeBytesSent int +} + +func (b bucket) MarshalLogObject(e zapcore.ObjectEncoder) error { + e.AddDuration("expectedElapsedDuration", b.expectedElapsedDuration) + e.AddInt("expectedProbesBytesSent", b.expectedProbeBytesSent) + return nil +} + +// --------------------------------------------------------------------------- + type Cluster struct { lock sync.RWMutex @@ -402,9 +428,13 @@ type Cluster struct { mode ProbeClusterMode listener ProberListener - probeSleeps []time.Duration - probeIdx int + baseSleepDuration time.Duration + buckets []bucket + bucketIdx int + probeBytesSent int + + startTime time.Time isComplete bool } @@ -423,29 +453,56 @@ func newCluster(id ProbeClusterId, mode ProbeClusterMode, pcg ProbeClusterGoal, } func (c *Cluster) initProbes() { - numProbeBytes := int(math.Round(float64(c.info.Goal.DesiredBps-c.info.Goal.ExpectedUsageBps)*c.info.Goal.Duration.Seconds()/8 + 0.5)) - numProbes := (numProbeBytes + cBytesPerProbe - 1) / cBytesPerProbe - if numProbes < 1 { - numProbes = 1 - } - - c.probeSleeps = make([]time.Duration, numProbes) - switch c.mode { - case ProbeClusterModeUniform: - interval := c.info.Goal.Duration / time.Duration(numProbes) - for i := 0; i < numProbes; i++ { - c.probeSleeps[i] = interval - } - - case ProbeClusterModeLinearChirp: - numIntervals := numProbes * (numProbes + 1) / 2 - interval := c.info.Goal.Duration / time.Duration(numIntervals) - for i := 0; i < numProbes; i++ { - c.probeSleeps[i] = time.Duration(numProbes-i) * interval - } - } - c.info.Goal.DesiredBytes = int(math.Round(float64(c.info.Goal.DesiredBps)*c.info.Goal.Duration.Seconds()/8 + 0.5)) + + numBuckets := int(math.Round(c.info.Goal.Duration.Seconds()/cSleepDuration.Seconds() + 0.5)) + if numBuckets < 1 { + numBuckets = 1 + } + numIntervals := numBuckets + + // for linear chirp, group intervals with decreasing duration, i.e. incraasing bitrate, + // by aiming to send same number of bytes in each interval, as intervals get shorter, the bitrate is higher + if c.mode == ProbeClusterModeLinearChirp { + sum := 0 + i := 1 + for { + sum += i + if sum >= numBuckets { + break + } + i++ + } + numBuckets = i + numIntervals = sum + } + + c.baseSleepDuration = c.info.Goal.Duration / time.Duration(numIntervals) + if c.baseSleepDuration < cSleepDurationMin { + c.baseSleepDuration = cSleepDurationMin + } + + numIntervals = int(math.Round(c.info.Goal.Duration.Seconds()/c.baseSleepDuration.Seconds() + 0.5)) + desiredProbeBytesPerInterval := int(math.Round(((c.info.Goal.Duration.Seconds()*float64(c.info.Goal.DesiredBps-c.info.Goal.ExpectedUsageBps)/8)+float64(numIntervals)-1)/float64(numIntervals) + 0.5)) + + c.buckets = make([]bucket, numBuckets) + for i := 0; i < numBuckets; i++ { + switch c.mode { + case ProbeClusterModeUniform: + c.buckets[i] = bucket{ + expectedElapsedDuration: c.baseSleepDuration, + } + + case ProbeClusterModeLinearChirp: + c.buckets[i] = bucket{ + expectedElapsedDuration: time.Duration(numBuckets-i) * c.baseSleepDuration, + } + } + if i > 0 { + c.buckets[i].expectedElapsedDuration += c.buckets[i-1].expectedElapsedDuration + } + c.buckets[i].expectedProbeBytesSent = (i + 1) * desiredProbeBytesPerInterval + } } func (c *Cluster) Start() { @@ -465,6 +522,13 @@ func (c *Cluster) Info() ProbeClusterInfo { return c.info } +func (c *Cluster) ProbesSent(bytesSent int) { + c.lock.Lock() + defer c.lock.Unlock() + + c.probeBytesSent += bytesSent +} + func (c *Cluster) MarkCompleted(result ProbeClusterResult) { c.lock.Lock() defer c.lock.Unlock() @@ -480,28 +544,45 @@ func (c *Cluster) Process() time.Duration { return 0 } - sleepDuration := c.probeSleeps[c.probeIdx%len(c.probeSleeps)] - c.probeIdx++ - if c.probeIdx >= len(c.probeSleeps) { - // when overflowing, back off to ensure probe finishes, but not overshoot too much - sleepDuration *= time.Duration(c.probeIdx/len(c.probeSleeps) + 1) + bytesToSend := 0 + if c.startTime.IsZero() { + c.startTime = mono.Now() + bytesToSend = cBytesPerProbe + } else { + sinceStart := time.Since(c.startTime) + if sinceStart > c.buckets[c.bucketIdx].expectedElapsedDuration { + c.bucketIdx++ + overflow := false + if c.bucketIdx >= len(c.buckets) { + // when overflowing, repeat the last bucket + c.bucketIdx = len(c.buckets) - 1 + overflow = true + } + if c.buckets[c.bucketIdx].expectedProbeBytesSent > c.probeBytesSent || overflow { + bytesToSend = max(cBytesPerProbe, c.buckets[c.bucketIdx].expectedProbeBytesSent-c.probeBytesSent) + } + } } c.lock.Unlock() - if c.listener != nil { - c.listener.OnSendProbe(cBytesPerProbe) + if bytesToSend != 0 && c.listener != nil { + c.listener.OnSendProbe(bytesToSend) } - return sleepDuration + return cSleepDurationMin } func (c *Cluster) MarshalLogObject(e zapcore.ObjectEncoder) error { if c != nil { e.AddString("mode", c.mode.String()) e.AddObject("info", c.info) - e.AddInt("numProbes", len(c.probeSleeps)) - e.AddArray("probeSleeps", logger.DurationSlice(c.probeSleeps)) - e.AddInt("probeIdx", c.probeIdx) + e.AddDuration("baseSleepDuration", c.baseSleepDuration) + e.AddInt("numBuckets", len(c.buckets)) + e.AddArray("buckets", logger.ObjectSlice(c.buckets)) + e.AddInt("bucketIdx", c.bucketIdx) + e.AddInt("probeBytesSent", c.probeBytesSent) + e.AddTime("startTime", c.startTime) + e.AddDuration("elapsed", time.Since(c.startTime)) e.AddBool("isComplete", c.isComplete) } return nil diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index 5dc79024..d5797639 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -191,6 +191,32 @@ type DownTrackStreamAllocatorListener interface { IsSubscribeMutable(dt *DownTrack) bool } +// ------------------------------------------------------------------- + +type bindState int + +const ( + bindStateUnbound bindState = iota + // downtrack negotiated, but waiting for receiver to be ready to start forwarding + bindStateWaitForReceiverReady + // downtrack is bound and ready to forward + bindStateBound +) + +func (bs bindState) String() string { + switch bs { + case bindStateUnbound: + return "unbound" + case bindStateWaitForReceiverReady: + return "waitForReceiverReady" + case bindStateBound: + return "bound" + } + return "unknown" +} + +// ------------------------------------------------------------------- + type ReceiverReportListener func(dt *DownTrack, report *rtcp.ReceiverReport) type DowntrackParams struct { @@ -304,28 +330,6 @@ type DownTrack struct { createdAt int64 } -type bindState int - -const ( - bindStateUnbound bindState = iota - // downtrack negotiated, but waiting for receiver to be ready to start forwarding - bindStateWaitForReceiverReady - // downtrack is bound and ready to forward - bindStateBound -) - -func (bs bindState) String() string { - switch bs { - case bindStateUnbound: - return "unbound" - case bindStateWaitForReceiverReady: - return "waitForReceiverReady" - case bindStateBound: - return "bound" - } - return "unknown" -} - // NewDownTrack returns a DownTrack. func NewDownTrack(params DowntrackParams) (*DownTrack, error) { codecs := params.Codecs @@ -522,11 +526,13 @@ func (d *DownTrack) Bind(t webrtc.TrackLocalContext) (webrtc.RTPCodecParameters, }) d.rtcpReader = rr } - if rr := d.params.BufferFactory.GetOrNew(packetio.RTCPBufferPacket, d.ssrcRTX).(*buffer.RTCPReader); rr != nil { - rr.OnPacket(func(pkt []byte) { - d.handleRTCP(pkt) - }) - d.rtcpReaderRTX = rr + if d.ssrcRTX != 0 { + if rr := d.params.BufferFactory.GetOrNew(packetio.RTCPBufferPacket, d.ssrcRTX).(*buffer.RTCPReader); rr != nil { + rr.OnPacket(func(pkt []byte) { + d.handleRTCP(pkt) + }) + d.rtcpReaderRTX = rr + } } d.sequencer = newSequencer(d.params.MaxTrack, d.kind == webrtc.RTPCodecTypeVideo, d.params.Logger) @@ -691,6 +697,10 @@ func (d *DownTrack) SSRC() uint32 { return d.ssrc } +func (d *DownTrack) SSRCRTX() uint32 { + return d.ssrcRTX +} + func (d *DownTrack) Stop() error { if tr := d.transceiver.Load(); tr != nil { return tr.Stop() @@ -1781,7 +1791,7 @@ func (d *DownTrack) handleRTCP(bytes []byte) { } case *rtcp.TransportLayerCC: - if p.MediaSSRC == d.ssrc || p.MediaSSRC == d.ssrcRTX { + if p.MediaSSRC == d.ssrc || (d.ssrcRTX != 0 && p.MediaSSRC == d.ssrcRTX) { if sal := d.getStreamAllocatorListener(); sal != nil { sal.OnTransportCCFeedback(d, p) } @@ -1848,6 +1858,100 @@ func (d *DownTrack) SetActivePaddingOnMuteUpTrack() { d.activePaddingOnMuteUpTrack.Store(true) } +func (d *DownTrack) retransmitPacket(epm *extPacketMeta, sourcePkt []byte, isProbe bool) (int, error) { + var pkt rtp.Packet + if err := pkt.Unmarshal(sourcePkt); err != nil { + d.params.Logger.Errorw("could not unmarshal rtp packet to send via RTX", err) + return 0, err + } + hdr := &rtp.Header{ + Version: pkt.Header.Version, + Padding: pkt.Header.Padding, + Marker: epm.marker, + PayloadType: d.getTranslatedPayloadType(pkt.Header.PayloadType), + SequenceNumber: epm.targetSeqNo, + Timestamp: epm.timestamp, + SSRC: d.ssrc, + } + rtxOffset := 0 + if d.payloadTypeRTX != 0 && d.ssrcRTX != 0 { + rtxOffset = 2 + + hdr.PayloadType = d.payloadTypeRTX + hdr.SequenceNumber = uint16(d.rtxSequenceNumber.Inc()) + hdr.SSRC = d.ssrcRTX + } + + if d.dependencyDescriptorExtID != 0 { + var ddBytes []byte + if len(epm.ddBytesSlice) != 0 { + ddBytes = epm.ddBytesSlice + } else { + ddBytes = epm.ddBytes[:epm.ddBytesSize] + } + if len(ddBytes) != 0 { + hdr.SetExtension(uint8(d.dependencyDescriptorExtID), ddBytes) + } + } + if d.absCaptureTimeExtID != 0 && len(epm.actBytes) != 0 { + hdr.SetExtension(uint8(d.absCaptureTimeExtID), epm.actBytes) + } + d.addDummyExtensions(hdr) + + poolEntity := PacketFactory.Get().(*[]byte) + payload := *poolEntity + if rtxOffset != 0 { + // write OSN (Original Sequence Number) + binary.BigEndian.PutUint16(payload[0:2], epm.targetSeqNo) + } + if len(epm.codecBytesSlice) != 0 { + n := copy(payload[rtxOffset:], epm.codecBytesSlice) + m := copy(payload[rtxOffset+n:], pkt.Payload[epm.numCodecBytesIn:]) + payload = payload[:rtxOffset+n+m] + } else { + copy(payload[rtxOffset:], epm.codecBytes[:epm.numCodecBytesOut]) + copy(payload[rtxOffset+int(epm.numCodecBytesOut):], pkt.Payload[epm.numCodecBytesIn:]) + payload = payload[:rtxOffset+int(epm.numCodecBytesOut)+len(pkt.Payload)-int(epm.numCodecBytesIn)] + } + + headerSize := hdr.MarshalSize() + var ( + payloadSize, paddingSize int + isOutOfOrder bool + ) + if isProbe { + // although not padding only packets, marking it as padding for accounting as padding is used to signify probing, + // also not marking them as out-of-order although sequence numbers in packets are out-of-order because of re-sending packets + payloadSize, paddingSize, isOutOfOrder = 0, len(payload), false + } else { + payloadSize, paddingSize, isOutOfOrder = len(payload), 0, true + } + d.rtpStats.Update( + mono.UnixNano(), + epm.extSequenceNumber, + epm.extTimestamp, + hdr.Marker, + headerSize, + payloadSize, + paddingSize, + isOutOfOrder, + ) + d.pacer.Enqueue(&pacer.Packet{ + Header: hdr, + HeaderSize: headerSize, + Payload: payload, + ProbeClusterId: ccutils.ProbeClusterId(d.probeClusterId.Load()), + IsProbe: isProbe, + IsRTX: !isProbe, + AbsSendTimeExtID: uint8(d.absSendTimeExtID), + TransportWideExtID: uint8(d.transportWideExtID), + WriteStream: d.writeStream, + Pool: PacketFactory, + PoolEntity: poolEntity, + }) + return headerSize + len(payload), nil +} + func (d *DownTrack) retransmitPackets(nacks []uint16) { if d.sequencer == nil { return @@ -1889,84 +1993,7 @@ func (d *DownTrack) retransmitPackets(nacks []uint16) { numRepeatedNACKs++ } - var pkt rtp.Packet - if err = pkt.Unmarshal(pktBuff[:n]); err != nil { - d.params.Logger.Errorw("could not unmarshal rtp packet in retransmit", err) - continue - } - hdr := &rtp.Header{ - Version: pkt.Header.Version, - Padding: pkt.Header.Padding, - Marker: epm.marker, - PayloadType: d.getTranslatedPayloadType(pkt.Header.PayloadType), - SequenceNumber: epm.targetSeqNo, - Timestamp: epm.timestamp, - SSRC: d.ssrc, - } - rtxOffset := 0 - if d.payloadTypeRTX != 0 && d.ssrcRTX != 0 { - rtxOffset = 2 - - hdr.PayloadType = d.payloadTypeRTX - hdr.SequenceNumber = uint16(d.rtxSequenceNumber.Inc()) - hdr.SSRC = d.ssrcRTX - } - - if d.dependencyDescriptorExtID != 0 { - var ddBytes []byte - if len(epm.ddBytesSlice) != 0 { - ddBytes = epm.ddBytesSlice - } else { - ddBytes = epm.ddBytes[:epm.ddBytesSize] - } - if len(ddBytes) != 0 { - hdr.SetExtension(uint8(d.dependencyDescriptorExtID), ddBytes) - } - } - if d.absCaptureTimeExtID != 0 && len(epm.actBytes) != 0 { - hdr.SetExtension(uint8(d.absCaptureTimeExtID), epm.actBytes) - } - d.addDummyExtensions(hdr) - - poolEntity := PacketFactory.Get().(*[]byte) - payload := *poolEntity - if rtxOffset != 0 { - // write OSN (Original Sequence Number) - binary.BigEndian.PutUint16(payload[0:2], epm.targetSeqNo) - } - if len(epm.codecBytesSlice) != 0 { - n := copy(payload[rtxOffset:], epm.codecBytesSlice) - m := copy(payload[rtxOffset+n:], pkt.Payload[epm.numCodecBytesIn:]) - payload = payload[:rtxOffset+n+m] - } else { - copy(payload[rtxOffset:], epm.codecBytes[:epm.numCodecBytesOut]) - copy(payload[rtxOffset+int(epm.numCodecBytesOut):], pkt.Payload[epm.numCodecBytesIn:]) - payload = payload[:rtxOffset+int(epm.numCodecBytesOut)+len(pkt.Payload)-int(epm.numCodecBytesIn)] - } - - headerSize := hdr.MarshalSize() - d.rtpStats.Update( - mono.UnixNano(), - epm.extSequenceNumber, - epm.extTimestamp, - hdr.Marker, - headerSize, - len(payload), - 0, - true, - ) - d.pacer.Enqueue(&pacer.Packet{ - Header: hdr, - HeaderSize: headerSize, - Payload: payload, - ProbeClusterId: ccutils.ProbeClusterId(d.probeClusterId.Load()), - IsRTX: true, - AbsSendTimeExtID: uint8(d.absSendTimeExtID), - TransportWideExtID: uint8(d.transportWideExtID), - WriteStream: d.writeStream, - Pool: PacketFactory, - PoolEntity: poolEntity, - }) + d.retransmitPacket(&epm, pktBuff[:n], false) } d.totalRepeatedNACKs.Add(numRepeatedNACKs) @@ -1974,6 +2001,102 @@ func (d *DownTrack) retransmitPackets(nacks []uint16) { d.rtpStats.UpdateNackProcessed(nackAcks, nackMisses, numRepeatedNACKs) } +func (d *DownTrack) WriteProbePackets(bytesToSend int, usePadding bool) int { + if d.ssrcRTX == 0 { + return d.WritePaddingRTP(bytesToSend, false, false) + } + + if !d.writable.Load() || + !d.rtpStats.IsActive() || + (d.absSendTimeExtID == 0 && d.transportWideExtID == 0) || + d.rtpStats.LastReceiverReportTime().IsZero() || + d.sequencer == nil { + return 0 + } + + bytesSent := 0 + + if usePadding { + num := (bytesToSend + RTPPaddingMaxPayloadSize + RTPPaddingEstimatedHeaderSize - 1) / (RTPPaddingMaxPayloadSize + RTPPaddingEstimatedHeaderSize) + if num == 0 { + return 0 + } + + for i := 0; i < num; i++ { + hdr := &rtp.Header{ + Version: 2, + Padding: true, + Marker: false, + PayloadType: d.payloadTypeRTX, + SequenceNumber: uint16(d.rtxSequenceNumber.Inc()), + Timestamp: 0, + SSRC: d.ssrcRTX, + } + d.addDummyExtensions(hdr) + + payload := make([]byte, RTPPaddingMaxPayloadSize) + // last byte of padding has padding size including that byte + payload[RTPPaddingMaxPayloadSize-1] = byte(RTPPaddingMaxPayloadSize) + + hdrSize := hdr.MarshalSize() + payloadSize := len(payload) + /* RTX-TODO + d.rtpStats.Update( + mono.UnixNano(), + snts[i].extSequenceNumber, + snts[i].extTimestamp, + hdr.Marker, + hdrSize, + 0, + payloadSize, + false, + ) + */ + d.pacer.Enqueue(&pacer.Packet{ + Header: hdr, + HeaderSize: hdrSize, + Payload: payload, + ProbeClusterId: ccutils.ProbeClusterId(d.probeClusterId.Load()), + IsProbe: true, + AbsSendTimeExtID: uint8(d.absSendTimeExtID), + TransportWideExtID: uint8(d.transportWideExtID), + WriteStream: d.writeStream, + }) + + bytesSent += hdrSize + payloadSize + } + } else { + src := PacketFactory.Get().(*[]byte) + defer PacketFactory.Put(src) + + endExtHighestSequenceNumber := d.rtpStats.ExtHighestSequenceNumber() + startExtHighestSequenceNumber := endExtHighestSequenceNumber - 5 + for esn := startExtHighestSequenceNumber; esn <= endExtHighestSequenceNumber; esn++ { + epm := d.sequencer.lookupExtPacketMeta(esn) + if epm == nil { + continue + } + + pktBuff := *src + n, err := d.params.Receiver.ReadRTP(pktBuff, uint8(epm.layer), epm.sourceSeqNo) + if err != nil { + if err == io.EOF { + break + } + continue + } + + sent, _ := d.retransmitPacket(epm, pktBuff[:n], true) + bytesSent += sent + if bytesSent >= bytesToSend { + break + } + } + } + + return bytesSent +} + func (d *DownTrack) addDummyExtensions(hdr *rtp.Header) { // add dummy extensions (actual ones will be filed by pacer) to get header size if d.absSendTimeExtID != 0 { diff --git a/pkg/sfu/sequencer.go b/pkg/sfu/sequencer.go index 5222741f..5ba788b9 100644 --- a/pkg/sfu/sequencer.go +++ b/pkg/sfu/sequencer.go @@ -30,18 +30,6 @@ const ( maxAck = 3 ) -func btoi(b bool) int { - if b { - return 1 - } - - return 0 -} - -func itob(i int) bool { - return i != 0 -} - type packetMeta struct { // Original extended sequence number from stream. // The original extended sequence number is used to find the original @@ -80,22 +68,37 @@ type packetMeta struct { actBytes []byte } +func (pm packetMeta) MarshalLogObject(e zapcore.ObjectEncoder) error { + e.AddUint64("sourceSeqNo", pm.sourceSeqNo) + e.AddUint16("targetSeqNo", pm.targetSeqNo) + e.AddInt8("layer", pm.layer) + e.AddUint8("nacked", pm.nacked) + e.AddUint8("numCodecBytesIn", pm.numCodecBytesIn) + if len(pm.codecBytesSlice) != 0 { + e.AddInt("codecBytesSlice", len(pm.codecBytesSlice)) + } else { + e.AddUint8("numCodecBytesOut", pm.numCodecBytesOut) + } + if len(pm.ddBytesSlice) != 0 { + e.AddInt("ddBytesSlice", len(pm.ddBytesSlice)) + } else { + e.AddUint8("ddBytesSize", pm.ddBytesSize) + } + if len(pm.actBytes) != 0 { + e.AddInt("actBytes", len(pm.actBytes)) + } + return nil +} + type extPacketMeta struct { packetMeta extSequenceNumber uint64 extTimestamp uint64 } -func (epm *extPacketMeta) MarshalLogObject(e zapcore.ObjectEncoder) error { - if epm == nil { - return nil - } - - e.AddUint64("sourceSeqNo", epm.sourceSeqNo) - e.AddUint16("targetSeqNo", epm.targetSeqNo) +func (epm extPacketMeta) MarshalLogObject(e zapcore.ObjectEncoder) error { + e.AddObject("packetMeta", epm.packetMeta) e.AddUint64("extSequenceNumber", epm.extSequenceNumber) - e.AddInt8("layer", epm.layer) - e.AddUint8("nacked", epm.nacked) return nil } @@ -271,20 +274,20 @@ func (s *sequencer) pushPadding(extStartSNInclusive uint64, extEndSNInclusive ui } // if exclusion range is before what has already been sequenced, invalidate exclusion range slots - for sn := extStartSNInclusive; sn != extEndSNInclusive+1; sn++ { - diff := int64(sn - s.extHighestSN) + for esn := extStartSNInclusive; esn != extEndSNInclusive+1; esn++ { + diff := int64(esn - s.extHighestSN) if diff >= 0 || diff < -int64(s.size) { // too old OR too new (too new should not happen, just be safe) continue } - snOffset, err := s.snRangeMap.GetValue(sn) + snOffset, err := s.snRangeMap.GetValue(esn) if err != nil { - s.logger.Errorw("could not get sequence number offset", err, "sn", sn) + s.logger.Errorw("could not get sequence number offset", err, "sn", esn) continue } - slot := (sn - snOffset) % uint64(s.size) + slot := (esn - snOffset) % uint64(s.size) s.invalidateSlot(int(slot)) } return @@ -371,6 +374,52 @@ func (s *sequencer) getExtPacketMetas(seqNo []uint16) []extPacketMeta { return extPacketMetas } +func (s *sequencer) lookupExtPacketMeta(extSN uint64) *extPacketMeta { + s.Lock() + defer s.Unlock() + + if !s.initialized { + return nil + } + + snOffset := uint64(0) + var err error + if s.snRangeMap != nil { + snOffset, err = s.snRangeMap.GetValue(extSN) + if err != nil { + return nil + } + } + + extSNAdjusted := extSN - snOffset + extHighestSNAdjusted := s.extHighestSN - s.snOffset + if extHighestSNAdjusted-extSNAdjusted >= uint64(s.size) { + // too old + return nil + } + + slot := extSNAdjusted % uint64(s.size) + meta := &s.meta[slot] + if s.isInvalidSlot(int(slot)) { + // invalid slot access could happen if padding packets exclusion range could not be recorded + return nil + } + + extTS := uint64(meta.timestamp) + (s.extHighestTS & 0xFFFF_FFFF_0000_0000) + if meta.timestamp > uint32(s.extHighestTS) { + extTS -= (1 << 32) + } + epm := extPacketMeta{ + packetMeta: *meta, + extSequenceNumber: extSN, + extTimestamp: extTS, + } + epm.codecBytesSlice = append([]byte{}, meta.codecBytesSlice...) + epm.ddBytesSlice = append([]byte{}, meta.ddBytesSlice...) + epm.actBytes = append([]byte{}, meta.actBytes...) + return &epm +} + func (s *sequencer) getRefTime(at int64) uint32 { return uint32((at - s.startTime) / 1e6) } diff --git a/pkg/sfu/streamallocator/streamallocator.go b/pkg/sfu/streamallocator/streamallocator.go index bc92744d..72b750ad 100644 --- a/pkg/sfu/streamallocator/streamallocator.go +++ b/pkg/sfu/streamallocator/streamallocator.go @@ -372,10 +372,12 @@ func (s *StreamAllocator) OnREMB(downTrack *sfu.DownTrack, remb *rtcp.ReceiverEs return } - track := s.videoTracks[livekit.TrackID(downTrack.ID())] downTrackSSRC := uint32(0) + downTrackSSRCRTX := uint32(0) + track := s.videoTracks[livekit.TrackID(downTrack.ID())] if track != nil { downTrackSSRC = track.DownTrack().SSRC() + downTrackSSRCRTX = track.DownTrack().SSRCRTX() } found := false @@ -393,13 +395,22 @@ func (s *StreamAllocator) OnREMB(downTrack *sfu.DownTrack, remb *rtcp.ReceiverEs } // try to lock to track which is sending this update - if downTrackSSRC != 0 { - for _, ssrc := range remb.SSRCs { - if ssrc == downTrackSSRC { - s.rembTrackingSSRC = downTrackSSRC - found = true - break - } + downTrackSSRC := track.DownTrack().SSRC() + downTrackSSRCRTX := track.DownTrack().SSRCRTX() + for _, ssrc := range remb.SSRCs { + if ssrc == 0 { + continue + } + + if ssrc == downTrackSSRC { + s.rembTrackingSSRC = downTrackSSRC + found = true + break + } + if ssrc == downTrackSSRCRTX { + s.rembTrackingSSRC = downTrackSSRCRTX + found = true + break } } @@ -408,7 +419,7 @@ func (s *StreamAllocator) OnREMB(downTrack *sfu.DownTrack, remb *rtcp.ReceiverEs } } - if s.rembTrackingSSRC == 0 || s.rembTrackingSSRC != downTrackSSRC { + if s.rembTrackingSSRC == 0 || (s.rembTrackingSSRC != downTrackSSRC && s.rembTrackingSSRC != downTrackSSRCRTX) { s.videoTracksMu.Unlock() return } @@ -727,13 +738,15 @@ func (s *StreamAllocator) handleSignalSendProbe(event Event) { bytesSent := 0 for _, track := range s.getTracks() { - sent := track.WritePaddingRTP(bytesToSend) + sent := track.WriteProbePackets(bytesToSend) bytesSent += sent bytesToSend -= sent if bytesToSend <= 0 { break } } + + s.prober.ProbesSent(bytesSent) } func (s *StreamAllocator) handleSignalPacerProbeObserverClusterComplete(event Event) { diff --git a/pkg/sfu/streamallocator/track.go b/pkg/sfu/streamallocator/track.go index 6f2af870..1c28e9b8 100644 --- a/pkg/sfu/streamallocator/track.go +++ b/pkg/sfu/streamallocator/track.go @@ -134,6 +134,10 @@ func (t *Track) WritePaddingRTP(bytesToSend int) int { return t.downTrack.WritePaddingRTP(bytesToSend, false, false) } +func (t *Track) WriteProbePackets(bytesToSend int) int { + return t.downTrack.WriteProbePackets(bytesToSend, true) +} + func (t *Track) AllocateOptimal(allowOvershoot bool, hold bool) sfu.VideoAllocation { return t.downTrack.AllocateOptimal(allowOvershoot, hold) }