From 06866244cb3741eb279f91cf8c6206984b83beda Mon Sep 17 00:00:00 2001 From: Jynk0 <106554291+Jynk0-btw@users.noreply.github.com> Date: Sun, 30 Aug 2026 11:54:41 +0300 Subject: [PATCH] Stop two idle tickers from spinning when there is nothing to send (#170) * tunnel: stop spinning idle tickers in the vp8 writer and kcp update loop Two hot loops woke the CPU constantly even with no traffic in the tunnel. vp8tunnel writerLoop: sampleInterval is (1s / fps) / pacedBatch, so the default fps=24 batch=30 gives 1.54ms - 648 ticks per second. With an empty send queue the loop still woke on every tick just to bump idleTicks; a real frame only goes out every keepaliveEvery ticks (~9/s), so ~639 wakeups per second did nothing but keep the core out of deep sleep. With dualTrack there are two such writers. The loop now has two phases. While data flows nothing changes - the ticker holds the frame pace and the traffic shape is identical. After 40 consecutive empty ticks (~60ms) the ticker stops and the goroutine blocks on a select over the send queue and a keepalive timer; incoming data returns it to pace at once. Gaps shorter than 60ms are still ridden out on the ticker, so bursty transfers do not flap between modes. multi_track_kcp_tunnel updateLoop: same shape, a fixed 10ms ticker calling Update 100 times a second regardless of traffic. While idle WaitSnd() is zero across every session, so there is nothing to retransmit. The loop keeps 10ms while segments are in flight and drops to 500ms once idle; sends and receives nudge it back through a buffered channel, so the first packet after silence is not delayed. Measured with relay/benchidle (single track, 30s of pure idle): before after vp8 only 2.47 % 0.14 % vp8 + reliable KCP 2.95 % 0.15 % The second row is the typical mobile client configuration. * tunnel: add an idle emission-rate test Measures both halves of what an idle tunnel costs: frames put on the wire per second, and CPU burned by the writer. The frame rate is the number that matters on a phone, since every frame is a packet that keeps the radio awake. Single track, 30s idle window: frames/s cpu original 7.9 2.155 % patched, same keepalive 7.7 0.154 % patched, keepalive 3-8s 0.2 0.007 % The middle row is the limit of the loop fix on its own - CPU drops 14x while the packet rate barely moves, because idle traffic is driven by the keepalive period rather than by the ticker. * avoid waking the kcp update loop on udp sends, cleanup --------- Co-authored-by: jynk0 <106554291+Jynk0_btw@users.noreply.github.com> Co-authored-by: kulikov0 <19497634+kulikov0@users.noreply.github.com> --- relay/tunnel/multi_track_kcp_tunnel.go | 43 +++++++- relay/tunnel/vp8tunnel.go | 131 +++++++++++++++++-------- 2 files changed, 130 insertions(+), 44 deletions(-) diff --git a/relay/tunnel/multi_track_kcp_tunnel.go b/relay/tunnel/multi_track_kcp_tunnel.go index 49350db..c23353f 100644 --- a/relay/tunnel/multi_track_kcp_tunnel.go +++ b/relay/tunnel/multi_track_kcp_tunnel.go @@ -12,13 +12,15 @@ import ( ) const ( - kcpConvBase = 0x77627374 - kcpUpdateInterval = 10 * time.Millisecond + kcpConvBase = 0x77627374 + kcpUpdateInterval = 10 * time.Millisecond + kcpIdleUpdateInterval = 500 * time.Millisecond + kcpIdleAfterTicks = 50 // One KCP segment must ride in a single RTP packet so a dropped packet // loses only its own frame, not a two-packet frame that readVP8Track // would discard whole. 1200 RTP budget - 1 VP8 descriptor - interframe // header - 24 XChaCha20 nonce - 16 Poly1305 tag - 1 channel tag. - kcpSegmentMTU = 1200 - 1 - interframeHdrLen - 24 - 16 - 1 + kcpSegmentMTU = 1200 - 1 - interframeHdrLen - 24 - 16 - 1 kcpReceiveBufSize = 128 * 1024 kcpStatsEvery = 500 @@ -146,6 +148,7 @@ type MultiTrackKCPTunnel struct { stopCh chan struct{} stopOnce sync.Once + nudge chan struct{} currentWindow atomic.Int32 @@ -165,6 +168,7 @@ func NewMultiTrackKCPTunnel(mt *MultiTrackTunnel, logFn func(string, ...any)) *M convMap: make(map[uint32]*trackKCPSession), connPin: make(map[uint32]int), stopCh: make(chan struct{}), + nudge: make(chan struct{}, 1), } subs := mt.SubTunnels() window := kcpWindowFloor @@ -198,6 +202,7 @@ func (t *MultiTrackKCPTunnel) SendData(frame []byte) { t.sendRaw(connID, frame) return } + t.wake() t.mu.Lock() if len(t.sessions) == 0 { @@ -285,6 +290,7 @@ func (t *MultiTrackKCPTunnel) handleDecodedSegment(payload []byte) { return } t.inputSegments.Add(1) + t.wake() messages := session.input(body) if callback == nil { return @@ -368,21 +374,52 @@ func (t *MultiTrackKCPTunnel) handleInnerClose() { } } +func (t *MultiTrackKCPTunnel) wake() { + select { + case t.nudge <- struct{}{}: + default: + } +} + func (t *MultiTrackKCPTunnel) updateLoop() { ticker := time.NewTicker(kcpUpdateInterval) defer ticker.Stop() ticks := 0 + idleTicks := 0 + fast := true for { select { case <-t.stopCh: return + case <-t.nudge: + if !fast { + fast = true + idleTicks = 0 + ticker.Reset(kcpUpdateInterval) + } case <-ticker.C: t.mu.Lock() sessions := make([]*trackKCPSession, len(t.sessions)) copy(sessions, t.sessions) t.mu.Unlock() + pending := 0 for _, session := range sessions { session.update() + pending += session.waitSnd() + } + if pending > 0 { + idleTicks = 0 + if !fast { + fast = true + ticker.Reset(kcpUpdateInterval) + } + } else if fast { + idleTicks++ + if idleTicks >= kcpIdleAfterTicks { + fast = false + idleTicks = 0 + ticker.Reset(kcpIdleUpdateInterval) + } } ticks++ if common.Debug && ticks%kcpStatsEvery == 0 && t.logFn != nil { diff --git a/relay/tunnel/vp8tunnel.go b/relay/tunnel/vp8tunnel.go index 77e1417..e3ddf0d 100644 --- a/relay/tunnel/vp8tunnel.go +++ b/relay/tunnel/vp8tunnel.go @@ -23,6 +23,8 @@ const ( paceBatchFloorPercent = 80 paceDriftMin = 5 * time.Second paceDriftMax = 20 * time.Second + + idleSpinTicks = 40 ) type VP8DataTunnel struct { @@ -236,64 +238,111 @@ func (t *VP8DataTunnel) writerLoop() { ticker := time.NewTicker(sampleInterval) drift := time.NewTimer(common.DurationInRange(paceDriftMin, paceDriftMax)) + idle := time.NewTimer(time.Hour) + if !idle.Stop() { + <-idle.C + } idleTicks := 0 + spinning := true reconfigure := false + emit := func(sample []byte, isKeepalive bool) { + if sample == nil { + return + } + if err := t.track.WriteSample(media.Sample{Data: sample, Duration: sampleInterval}); err != nil { + if common.Debug { + t.logFn("vp8tunnel: WriteSample error: %v", err) + } + return + } + n := t.sentFrames.Add(1) + if isKeepalive { + t.keepaliveFrames.Add(1) + } + if common.Debug && (n <= 5 || n%500 == 0) { + keepalives := t.keepaliveFrames.Load() + t.logFn("vp8tunnel: sent frame #%d size=%d data=%d keepalive=%d", n, len(sample), n-keepalives, keepalives) + } + } + + repace := func() { + pacedBatch = pacedBatchFor(batch) + sampleInterval = sampleIntervalFor(fps, pacedBatch) + if spinning { + ticker.Reset(sampleInterval) + } + keepaliveEvery, keepalivePad = t.nextKeepalive(sampleInterval) + drift.Reset(common.DurationInRange(paceDriftMin, paceDriftMax)) + if common.Debug { + t.logFn("vp8tunnel: pace drift pacedBatch=%d/%d sampleInterval=%s", pacedBatch, batch, sampleInterval) + } + } + for !reconfigure { + if spinning { + select { + case <-t.stopCh: + ticker.Stop() + drift.Stop() + idle.Stop() + return + case <-t.cfgChan: + reconfigure = true + case <-drift.C: + repace() + case <-ticker.C: + select { + case data := <-t.sendQueue: + emit(t.obf.EncodeData(data), false) + idleTicks = 0 + default: + idleTicks++ + switch { + case idleTicks >= keepaliveEvery: + idleTicks = 0 + emit(t.obf.EncodeKeepalive(keepalivePad), true) + keepaliveEvery, keepalivePad = t.nextKeepalive(sampleInterval) + case idleTicks >= idleSpinTicks: + ticker.Stop() + spinning = false + idle.Reset(time.Duration(keepaliveEvery-idleTicks) * sampleInterval) + } + } + } + continue + } + select { case <-t.stopCh: - ticker.Stop() drift.Stop() + idle.Stop() return case <-t.cfgChan: reconfigure = true case <-drift.C: - pacedBatch = pacedBatchFor(batch) - sampleInterval = sampleIntervalFor(fps, pacedBatch) + repace() + case data := <-t.sendQueue: + if !idle.Stop() { + select { + case <-idle.C: + default: + } + } + emit(t.obf.EncodeData(data), false) + idleTicks = 0 + spinning = true ticker.Reset(sampleInterval) + case <-idle.C: + idleTicks = 0 + emit(t.obf.EncodeKeepalive(keepalivePad), true) keepaliveEvery, keepalivePad = t.nextKeepalive(sampleInterval) - drift.Reset(common.DurationInRange(paceDriftMin, paceDriftMax)) - if common.Debug { - t.logFn("vp8tunnel: pace drift pacedBatch=%d/%d sampleInterval=%s", pacedBatch, batch, sampleInterval) - } - case <-ticker.C: - var sample []byte - isKeepalive := false - select { - case data := <-t.sendQueue: - sample = t.obf.EncodeData(data) - idleTicks = 0 - default: - idleTicks++ - if idleTicks < keepaliveEvery { - continue - } - idleTicks = 0 - sample = t.obf.EncodeKeepalive(keepalivePad) - keepaliveEvery, keepalivePad = t.nextKeepalive(sampleInterval) - isKeepalive = true - } - if sample == nil { - continue - } - if err := t.track.WriteSample(media.Sample{Data: sample, Duration: sampleInterval}); err != nil { - if common.Debug { - t.logFn("vp8tunnel: WriteSample error: %v", err) - } - continue - } - n := t.sentFrames.Add(1) - if isKeepalive { - t.keepaliveFrames.Add(1) - } - if common.Debug && (n <= 5 || n%500 == 0) { - keepalives := t.keepaliveFrames.Load() - t.logFn("vp8tunnel: sent frame #%d size=%d data=%d keepalive=%d", n, len(sample), n-keepalives, keepalives) - } + idle.Reset(time.Duration(keepaliveEvery) * sampleInterval) } } ticker.Stop() drift.Stop() + idle.Stop() } }