move webrtc tunnels to relay/tunnel/rtc, unblock gomobile bind
This commit is contained in:
1 parent
799146771a
commit
ac5d890970
28 files changed
+173
-137
No files matched your search
@@ -0,0 +1,292 @@
|
||||
package rtc
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/kulikov0/headless-client/webrtc"
|
||||
"github.com/pion/datachannel"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
)
|
||||
|
||||
// Telemost chunk size
|
||||
const chunkSize = 994
|
||||
|
||||
type chunkBuf struct {
|
||||
chunks [][]byte
|
||||
count int
|
||||
size int
|
||||
}
|
||||
|
||||
type DCTunnel struct {
|
||||
dc *webrtc.DataChannel
|
||||
raw datachannel.ReadWriteCloser
|
||||
writeRaw datachannel.ReadWriteCloser
|
||||
logFn func(string, ...any)
|
||||
onData func([]byte)
|
||||
onClose func()
|
||||
obf *tunnel.TunnelObfuscator
|
||||
chunked bool
|
||||
readBuf int
|
||||
|
||||
recvBufs sync.Map
|
||||
sendMsgID uint32
|
||||
|
||||
recvBytes atomic.Uint64
|
||||
sendBytes atomic.Uint64
|
||||
recvMsgs atomic.Uint64
|
||||
sendMsgs atomic.Uint64
|
||||
}
|
||||
|
||||
func NewDCTunnel(dc *webrtc.DataChannel, obf *tunnel.TunnelObfuscator, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
t := &DCTunnel{dc: dc, obf: obf, readBuf: readBuf, logFn: logFn}
|
||||
|
||||
raw, err := dc.Detach()
|
||||
if err != nil {
|
||||
logFn("dctunnel: detach failed, using callback mode: %v", err)
|
||||
dc.OnMessage(func(msg webrtc.DataChannelMessage) {
|
||||
t.recvBytes.Add(uint64(len(msg.Data)))
|
||||
t.recvMsgs.Add(1)
|
||||
t.deliverMessage(msg.Data)
|
||||
})
|
||||
dc.OnClose(func() {
|
||||
if t.onClose != nil {
|
||||
t.onClose()
|
||||
}
|
||||
})
|
||||
return t
|
||||
}
|
||||
|
||||
t.raw = raw
|
||||
go t.readLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
func NewDCTunnelFromRaw(dc *webrtc.DataChannel, raw datachannel.ReadWriteCloser, obf *tunnel.TunnelObfuscator, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
t := &DCTunnel{dc: dc, raw: raw, obf: obf, readBuf: readBuf, logFn: logFn}
|
||||
go t.readLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
func NewChunkedDCTunnel(readRaw datachannel.ReadWriteCloser, writeDC *webrtc.DataChannel, obf *tunnel.TunnelObfuscator, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
writeRaw, err := writeDC.Detach()
|
||||
if err != nil {
|
||||
logFn("dctunnel: write DC detach failed: %v", err)
|
||||
return nil
|
||||
}
|
||||
t := &DCTunnel{raw: readRaw, writeRaw: writeRaw, obf: obf, readBuf: readBuf, logFn: logFn, chunked: true}
|
||||
go t.readLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
func NewChunkedDCTunnelFromRaw(readRaw, writeRaw datachannel.ReadWriteCloser, obf *tunnel.TunnelObfuscator, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
t := &DCTunnel{raw: readRaw, writeRaw: writeRaw, obf: obf, readBuf: readBuf, logFn: logFn, chunked: true}
|
||||
go t.readLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *DCTunnel) readLoop() {
|
||||
buf := make([]byte, t.readBuf)
|
||||
var stats dcStats
|
||||
for {
|
||||
n, isString, err := t.raw.ReadDataChannel(buf)
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
t.logFn("dctunnel: read error: %v", err)
|
||||
}
|
||||
if t.onClose != nil {
|
||||
t.onClose()
|
||||
}
|
||||
return
|
||||
}
|
||||
if isString {
|
||||
continue
|
||||
}
|
||||
t.recvBytes.Add(uint64(n))
|
||||
t.recvMsgs.Add(1)
|
||||
if t.chunked && n >= 6 {
|
||||
t.handleChunk(buf[:n])
|
||||
} else if n > 0 {
|
||||
t.deliverMessage(buf[:n])
|
||||
}
|
||||
if common.Debug {
|
||||
t.logStats(&stats)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *DCTunnel) handleChunk(data []byte) {
|
||||
id := uint16(data[0])<<8 | uint16(data[1])
|
||||
idx := int(uint16(data[2])<<8 | uint16(data[3]))
|
||||
total := int(uint16(data[4])<<8 | uint16(data[5]))
|
||||
payload := data[6:]
|
||||
|
||||
if total == 1 {
|
||||
cp := make([]byte, len(payload))
|
||||
copy(cp, payload)
|
||||
t.deliverMessage(cp)
|
||||
return
|
||||
}
|
||||
|
||||
val, _ := t.recvBufs.LoadOrStore(id, &chunkBuf{chunks: make([][]byte, total)})
|
||||
cb := val.(*chunkBuf)
|
||||
if idx < len(cb.chunks) && cb.chunks[idx] == nil {
|
||||
cp := make([]byte, len(payload))
|
||||
copy(cp, payload)
|
||||
cb.chunks[idx] = cp
|
||||
cb.count++
|
||||
cb.size += len(cp)
|
||||
}
|
||||
if cb.count == total {
|
||||
t.recvBufs.Delete(id)
|
||||
out := make([]byte, 0, cb.size)
|
||||
for _, c := range cb.chunks {
|
||||
out = append(out, c...)
|
||||
}
|
||||
t.deliverMessage(out)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *DCTunnel) deliverMessage(data []byte) {
|
||||
if len(data) == 0 {
|
||||
return
|
||||
}
|
||||
if t.obf != nil {
|
||||
pt, ok := t.obf.DecryptPayload(data)
|
||||
if !ok {
|
||||
if common.Debug {
|
||||
t.logFn("dctunnel: decrypt failed, dropping %d bytes", len(data))
|
||||
}
|
||||
return
|
||||
}
|
||||
data = pt
|
||||
}
|
||||
if t.onData != nil && len(data) > 0 {
|
||||
frame := make([]byte, 4+len(data))
|
||||
binary.BigEndian.PutUint32(frame[0:4], uint32(len(data)))
|
||||
copy(frame[4:], data)
|
||||
t.onData(frame)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *DCTunnel) sendChunked(data []byte) {
|
||||
w := t.writeRaw
|
||||
if w == nil {
|
||||
w = t.raw
|
||||
}
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
total := int(math.Ceil(float64(len(data)) / float64(chunkSize)))
|
||||
if total == 0 {
|
||||
total = 1
|
||||
}
|
||||
id := uint16(atomic.AddUint32(&t.sendMsgID, 1)) & 0xFFFF
|
||||
for i := 0; i < total; i++ {
|
||||
start := i * chunkSize
|
||||
end := start + chunkSize
|
||||
if end > len(data) {
|
||||
end = len(data)
|
||||
}
|
||||
p := data[start:end]
|
||||
f := make([]byte, 6+len(p))
|
||||
f[0] = byte(id >> 8)
|
||||
f[1] = byte(id & 0xFF)
|
||||
f[2] = byte(i >> 8)
|
||||
f[3] = byte(i & 0xFF)
|
||||
f[4] = byte(total >> 8)
|
||||
f[5] = byte(total & 0xFF)
|
||||
copy(f[6:], p)
|
||||
t.sendBytes.Add(uint64(len(f)))
|
||||
t.sendMsgs.Add(1)
|
||||
w.Write(f)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *DCTunnel) sendRaw(data []byte) {
|
||||
w := t.writeRaw
|
||||
if w == nil {
|
||||
w = t.raw
|
||||
}
|
||||
if w != nil {
|
||||
t.sendBytes.Add(uint64(len(data)))
|
||||
t.sendMsgs.Add(1)
|
||||
w.Write(data)
|
||||
return
|
||||
}
|
||||
if t.dc == nil || t.dc.ReadyState() != webrtc.DataChannelStateOpen {
|
||||
return
|
||||
}
|
||||
t.sendBytes.Add(uint64(len(data)))
|
||||
t.sendMsgs.Add(1)
|
||||
t.dc.Send(data)
|
||||
}
|
||||
|
||||
func (t *DCTunnel) SendData(data []byte) {
|
||||
tunnel.DecodeFrames(data, func(connID uint32, msgType byte, payload []byte) {
|
||||
buf := make([]byte, tunnel.WireHeaderLen+len(payload))
|
||||
binary.BigEndian.PutUint32(buf[0:4], connID)
|
||||
buf[4] = msgType
|
||||
copy(buf[tunnel.WireHeaderLen:], payload)
|
||||
wire := buf
|
||||
if t.obf != nil {
|
||||
wire = t.obf.EncryptPayload(buf)
|
||||
if wire == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if t.chunked {
|
||||
t.sendChunked(wire)
|
||||
} else {
|
||||
t.sendRaw(wire)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (t *DCTunnel) SetOnData(fn func([]byte)) { t.onData = fn }
|
||||
func (t *DCTunnel) OnData() func([]byte) { return t.onData }
|
||||
func (t *DCTunnel) SetOnClose(fn func()) { t.onClose = fn }
|
||||
func (t *DCTunnel) Reconfigure(fps, batch int) {}
|
||||
|
||||
type dcStats struct {
|
||||
last time.Time
|
||||
lastRecv uint64
|
||||
lastSend uint64
|
||||
lastRecvMsgs uint64
|
||||
lastSendMsgs uint64
|
||||
}
|
||||
|
||||
func (t *DCTunnel) logStats(s *dcStats) {
|
||||
recv := t.recvBytes.Load()
|
||||
send := t.sendBytes.Load()
|
||||
recvMsgs := t.recvMsgs.Load()
|
||||
sendMsgs := t.sendMsgs.Load()
|
||||
now := time.Now()
|
||||
elapsed := now.Sub(s.last)
|
||||
if s.last.IsZero() || elapsed < 2*time.Second {
|
||||
if s.last.IsZero() {
|
||||
s.last = now
|
||||
}
|
||||
return
|
||||
}
|
||||
secs := elapsed.Seconds()
|
||||
recvDelta := recv - s.lastRecv
|
||||
sendDelta := send - s.lastSend
|
||||
if recvDelta > 0 || sendDelta > 0 {
|
||||
fmt.Printf("DC-STATS: recv=%dKB/s(%dmsg) send=%dKB/s(%dmsg)\n",
|
||||
uint64(float64(recvDelta)/secs)/1024, uint64(float64(recvMsgs-s.lastRecvMsgs)/secs),
|
||||
uint64(float64(sendDelta)/secs)/1024, uint64(float64(sendMsgs-s.lastSendMsgs)/secs))
|
||||
}
|
||||
s.last = now
|
||||
s.lastRecv = recv
|
||||
s.lastSend = send
|
||||
s.lastRecvMsgs = recvMsgs
|
||||
s.lastSendMsgs = sendMsgs
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package rtc
|
||||
|
||||
import (
|
||||
"whitelist-bypass/relay/common"
|
||||
|
||||
"github.com/kulikov0/headless-client/webrtc"
|
||||
)
|
||||
|
||||
func DrainSenderRTCP(sender *webrtc.RTPSender) {
|
||||
if sender == nil {
|
||||
return
|
||||
}
|
||||
buf := make([]byte, 1500)
|
||||
for {
|
||||
if _, _, err := sender.Read(buf); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func DrainTrack(track *webrtc.TrackRemote) {
|
||||
if track == nil {
|
||||
return
|
||||
}
|
||||
buf := make([]byte, common.UDPBufSize)
|
||||
for {
|
||||
if _, _, err := track.Read(buf); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
package rtc
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
kcp "github.com/xtaci/kcp-go/v5"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
)
|
||||
|
||||
const (
|
||||
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 - tunnel.InterframeHdrLen - 24 - 16 - 1
|
||||
kcpReceiveBufSize = 128 * 1024
|
||||
kcpStatsEvery = 500
|
||||
|
||||
kcpWindowFloor = 64
|
||||
kcpWindowCeiling = 512
|
||||
kcpCarrierRTT = 250 * time.Millisecond
|
||||
kcpWaitSndFactor = 2
|
||||
kcpBackpressurePoll = 2 * time.Millisecond
|
||||
|
||||
kcpChannelReliable byte = 0x00
|
||||
kcpChannelRaw byte = 0x01
|
||||
|
||||
KCPCarrierQueueDepth = kcpWaitSndFactor * kcpWindowCeiling
|
||||
)
|
||||
|
||||
func computeKCPWindow(fps, batch int) int {
|
||||
rate := fps * batch
|
||||
if rate < 1 {
|
||||
rate = defaultVP8FPS * defaultVP8Batch
|
||||
}
|
||||
window := int(float64(rate) * kcpCarrierRTT.Seconds())
|
||||
if window < kcpWindowFloor {
|
||||
return kcpWindowFloor
|
||||
}
|
||||
if window > kcpWindowCeiling {
|
||||
return kcpWindowCeiling
|
||||
}
|
||||
return window
|
||||
}
|
||||
|
||||
type trackKCPSession struct {
|
||||
conv uint32
|
||||
vp8 *VP8DataTunnel
|
||||
parent *MultiTrackKCPTunnel
|
||||
kcpMu sync.Mutex
|
||||
kcp *kcp.KCP
|
||||
recvBuf []byte
|
||||
}
|
||||
|
||||
func newTrackKCPSession(parent *MultiTrackKCPTunnel, vp8 *VP8DataTunnel, conv uint32, window int) *trackKCPSession {
|
||||
session := &trackKCPSession{
|
||||
conv: conv,
|
||||
vp8: vp8,
|
||||
parent: parent,
|
||||
recvBuf: make([]byte, kcpReceiveBufSize),
|
||||
}
|
||||
session.kcp = kcp.NewKCP(conv, func(buf []byte, size int) {
|
||||
if size <= 0 {
|
||||
return
|
||||
}
|
||||
segment := make([]byte, size+1)
|
||||
segment[0] = kcpChannelReliable
|
||||
copy(segment[1:], buf[:size])
|
||||
parent.outputSegments.Add(1)
|
||||
if !session.vp8.TrySendData(segment) {
|
||||
parent.droppedSegments.Add(1)
|
||||
}
|
||||
})
|
||||
session.kcp.NoDelay(1, 10, 2, 1)
|
||||
session.kcp.WndSize(window, window)
|
||||
session.kcp.SetMtu(kcpSegmentMTU)
|
||||
return session
|
||||
}
|
||||
|
||||
func (s *trackKCPSession) setWindow(window int) {
|
||||
s.kcpMu.Lock()
|
||||
s.kcp.WndSize(window, window)
|
||||
s.kcpMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *trackKCPSession) send(frame []byte) {
|
||||
s.kcpMu.Lock()
|
||||
s.kcp.Send(frame)
|
||||
s.kcp.Update()
|
||||
s.kcpMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *trackKCPSession) input(segment []byte) [][]byte {
|
||||
s.kcpMu.Lock()
|
||||
s.kcp.Input(segment, kcp.IKCP_PACKET_REGULAR, true)
|
||||
var messages [][]byte
|
||||
for {
|
||||
size := s.kcp.PeekSize()
|
||||
if size <= 0 {
|
||||
break
|
||||
}
|
||||
if size > len(s.recvBuf) {
|
||||
s.recvBuf = make([]byte, size)
|
||||
}
|
||||
n := s.kcp.Recv(s.recvBuf)
|
||||
if n <= 0 {
|
||||
break
|
||||
}
|
||||
message := make([]byte, n)
|
||||
copy(message, s.recvBuf[:n])
|
||||
messages = append(messages, message)
|
||||
}
|
||||
s.kcpMu.Unlock()
|
||||
return messages
|
||||
}
|
||||
|
||||
func (s *trackKCPSession) update() {
|
||||
s.kcpMu.Lock()
|
||||
s.kcp.Update()
|
||||
s.kcpMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *trackKCPSession) waitSnd() int {
|
||||
s.kcpMu.Lock()
|
||||
pending := s.kcp.WaitSnd()
|
||||
s.kcpMu.Unlock()
|
||||
return pending
|
||||
}
|
||||
|
||||
type MultiTrackKCPTunnel struct {
|
||||
mt *MultiTrackTunnel
|
||||
logFn func(string, ...any)
|
||||
|
||||
mu sync.Mutex
|
||||
sessions []*trackKCPSession
|
||||
convMap map[uint32]*trackKCPSession
|
||||
connPin map[uint32]int
|
||||
onData func([]byte)
|
||||
onClose func()
|
||||
|
||||
stopCh chan struct{}
|
||||
stopOnce sync.Once
|
||||
nudge chan struct{}
|
||||
|
||||
currentWindow atomic.Int32
|
||||
|
||||
sentMessages atomic.Uint64
|
||||
deliveredMessages atomic.Uint64
|
||||
outputSegments atomic.Uint64
|
||||
inputSegments atomic.Uint64
|
||||
rawSent atomic.Uint64
|
||||
rawReceived atomic.Uint64
|
||||
droppedSegments atomic.Uint64
|
||||
}
|
||||
|
||||
func NewMultiTrackKCPTunnel(mt *MultiTrackTunnel, logFn func(string, ...any)) *MultiTrackKCPTunnel {
|
||||
t := &MultiTrackKCPTunnel{
|
||||
mt: mt,
|
||||
logFn: logFn,
|
||||
convMap: make(map[uint32]*trackKCPSession),
|
||||
connPin: make(map[uint32]int),
|
||||
stopCh: make(chan struct{}),
|
||||
nudge: make(chan struct{}, 1),
|
||||
}
|
||||
subs := mt.SubTunnels()
|
||||
window := kcpWindowFloor
|
||||
if len(subs) > 0 {
|
||||
window = computeKCPWindow(subs[0].FPS(), subs[0].Batch())
|
||||
}
|
||||
t.currentWindow.Store(int32(window))
|
||||
for i, sub := range subs {
|
||||
conv := uint32(kcpConvBase + i)
|
||||
session := newTrackKCPSession(t, sub, conv, window)
|
||||
t.sessions = append(t.sessions, session)
|
||||
t.convMap[conv] = session
|
||||
}
|
||||
if logFn != nil {
|
||||
logFn("kcptunnel: init tracks=%d window=%d queue=%d", len(subs), window, KCPCarrierQueueDepth)
|
||||
}
|
||||
mt.SetOnData(t.handleDecodedSegment)
|
||||
mt.SetOnClose(t.handleInnerClose)
|
||||
go t.updateLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) SendData(frame []byte) {
|
||||
if len(frame) < 9 {
|
||||
return
|
||||
}
|
||||
connID := binary.BigEndian.Uint32(frame[4:8])
|
||||
msgType := frame[8]
|
||||
|
||||
if msgType == tunnel.MsgUDP || msgType == tunnel.MsgUDPReply {
|
||||
t.sendRaw(connID, frame)
|
||||
return
|
||||
}
|
||||
t.wake()
|
||||
|
||||
t.mu.Lock()
|
||||
if len(t.sessions) == 0 {
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
index, pinned := t.connPin[connID]
|
||||
if !pinned || index >= len(t.sessions) {
|
||||
index = int(connID % uint32(len(t.sessions)))
|
||||
t.connPin[connID] = index
|
||||
}
|
||||
session := t.sessions[index]
|
||||
t.mu.Unlock()
|
||||
|
||||
if msgType == tunnel.MsgData {
|
||||
sndCap := int(t.currentWindow.Load()) * kcpWaitSndFactor
|
||||
for session.waitSnd() >= sndCap {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
return
|
||||
case <-time.After(kcpBackpressurePoll):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.sentMessages.Add(1)
|
||||
session.send(frame)
|
||||
|
||||
if msgType == tunnel.MsgClose {
|
||||
t.mu.Lock()
|
||||
delete(t.connPin, connID)
|
||||
t.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) sendRaw(connID uint32, frame []byte) {
|
||||
t.mu.Lock()
|
||||
if len(t.sessions) == 0 {
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
index := int(connID % uint32(len(t.sessions)))
|
||||
session := t.sessions[index]
|
||||
t.mu.Unlock()
|
||||
|
||||
segment := make([]byte, len(frame)+1)
|
||||
segment[0] = kcpChannelRaw
|
||||
copy(segment[1:], frame)
|
||||
t.rawSent.Add(1)
|
||||
session.vp8.TrySendData(segment)
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) InjectSegment(payload []byte) {
|
||||
t.handleDecodedSegment(payload)
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) handleDecodedSegment(payload []byte) {
|
||||
if len(payload) < 1 {
|
||||
return
|
||||
}
|
||||
channel := payload[0]
|
||||
body := payload[1:]
|
||||
|
||||
if channel == kcpChannelRaw {
|
||||
t.mu.Lock()
|
||||
callback := t.onData
|
||||
t.mu.Unlock()
|
||||
if callback == nil {
|
||||
return
|
||||
}
|
||||
t.rawReceived.Add(1)
|
||||
callback(body)
|
||||
return
|
||||
}
|
||||
|
||||
if len(body) < 4 {
|
||||
return
|
||||
}
|
||||
conv := binary.LittleEndian.Uint32(body[0:4])
|
||||
t.mu.Lock()
|
||||
session := t.convMap[conv]
|
||||
callback := t.onData
|
||||
t.mu.Unlock()
|
||||
if session == nil {
|
||||
return
|
||||
}
|
||||
t.inputSegments.Add(1)
|
||||
t.wake()
|
||||
messages := session.input(body)
|
||||
if callback == nil {
|
||||
return
|
||||
}
|
||||
for _, message := range messages {
|
||||
t.deliveredMessages.Add(1)
|
||||
callback(message)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) SetOnData(fn func([]byte)) {
|
||||
t.mu.Lock()
|
||||
t.onData = fn
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) SetOnClose(fn func()) {
|
||||
t.mu.Lock()
|
||||
t.onClose = fn
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) Reconfigure(fps, batch int) {
|
||||
t.mt.Reconfigure(fps, batch)
|
||||
window := computeKCPWindow(fps, batch)
|
||||
t.applyWindow(window)
|
||||
if t.logFn != nil {
|
||||
t.logFn("kcptunnel: reconfigure fps=%d batch=%d -> window=%d", fps, batch, window)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) applyWindow(window int) {
|
||||
t.currentWindow.Store(int32(window))
|
||||
t.mu.Lock()
|
||||
sessions := make([]*trackKCPSession, len(t.sessions))
|
||||
copy(sessions, t.sessions)
|
||||
t.mu.Unlock()
|
||||
for _, session := range sessions {
|
||||
session.setWindow(window)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) AddSession(sub *VP8DataTunnel) {
|
||||
window := int(t.currentWindow.Load())
|
||||
t.mu.Lock()
|
||||
conv := uint32(kcpConvBase + len(t.sessions))
|
||||
session := newTrackKCPSession(t, sub, conv, window)
|
||||
t.sessions = append(t.sessions, session)
|
||||
t.convMap[conv] = session
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) RemoveLastSession() {
|
||||
t.mu.Lock()
|
||||
if len(t.sessions) <= 1 {
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
last := t.sessions[len(t.sessions)-1]
|
||||
t.sessions = t.sessions[:len(t.sessions)-1]
|
||||
delete(t.convMap, last.conv)
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) Stop() {
|
||||
t.stopOnce.Do(func() { close(t.stopCh) })
|
||||
t.mt.Stop()
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) StopLayer() {
|
||||
t.stopOnce.Do(func() { close(t.stopCh) })
|
||||
}
|
||||
|
||||
func (t *MultiTrackKCPTunnel) handleInnerClose() {
|
||||
t.stopOnce.Do(func() { close(t.stopCh) })
|
||||
t.mu.Lock()
|
||||
callback := t.onClose
|
||||
t.mu.Unlock()
|
||||
if callback != nil {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
t.logFn("kcptunnel: sessions=%d window=%d sent=%d delivered=%d out_segs=%d in_segs=%d raw_out=%d raw_in=%d dropped=%d",
|
||||
len(sessions), t.currentWindow.Load(), t.sentMessages.Load(), t.deliveredMessages.Load(),
|
||||
t.outputSegments.Load(), t.inputSegments.Load(),
|
||||
t.rawSent.Load(), t.rawReceived.Load(), t.droppedSegments.Load())
|
||||
snmp := kcp.DefaultSnmp.Copy()
|
||||
t.logFn("kcptunnel: kcp_out=%d kcp_in=%d retrans=%d fastretrans=%d lost=%d repeat=%d",
|
||||
snmp.OutSegs, snmp.InSegs, snmp.RetransSegs, snmp.FastRetransSegs, snmp.LostSegs, snmp.RepeatSegs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package rtc
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type MultiTrackTunnel struct {
|
||||
tunnels []*VP8DataTunnel
|
||||
|
||||
mu sync.Mutex
|
||||
onData func([]byte)
|
||||
onClose func()
|
||||
onPeerRestart func()
|
||||
isClosed bool
|
||||
fps int
|
||||
batch int
|
||||
}
|
||||
|
||||
func NewMultiTrackTunnel(tunnels []*VP8DataTunnel) *MultiTrackTunnel {
|
||||
m := &MultiTrackTunnel{tunnels: tunnels}
|
||||
for i, tun := range tunnels {
|
||||
// Only the cam (index 0) carries the cascade-on-close semantics;
|
||||
// screenshare tracks close independently during partial shrink.
|
||||
m.wireSubTunnel(tun, i == 0)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) wireSubTunnel(tun *VP8DataTunnel, isCamera bool) {
|
||||
tun.SetOnData(func(data []byte) {
|
||||
m.mu.Lock()
|
||||
handler := m.onData
|
||||
m.mu.Unlock()
|
||||
if handler != nil {
|
||||
handler(data)
|
||||
}
|
||||
})
|
||||
if !isCamera {
|
||||
// Screenshare close is a partial shrink; it must not cascade-Stop
|
||||
// the cam writer or notify the parent that the whole tunnel died.
|
||||
return
|
||||
}
|
||||
tun.SetOnPeerRestart(func() {
|
||||
m.mu.Lock()
|
||||
handler := m.onPeerRestart
|
||||
m.mu.Unlock()
|
||||
if handler != nil {
|
||||
handler()
|
||||
}
|
||||
})
|
||||
tun.SetOnClose(func() {
|
||||
m.mu.Lock()
|
||||
if m.isClosed {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
m.isClosed = true
|
||||
closeHandler := m.onClose
|
||||
subTunnels := m.tunnels
|
||||
m.mu.Unlock()
|
||||
|
||||
for _, t := range subTunnels {
|
||||
t.Stop()
|
||||
}
|
||||
if closeHandler != nil {
|
||||
closeHandler()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) AddSubTunnel(tun *VP8DataTunnel) {
|
||||
m.mu.Lock()
|
||||
if m.isClosed {
|
||||
m.mu.Unlock()
|
||||
tun.Stop()
|
||||
return
|
||||
}
|
||||
m.tunnels = append(m.tunnels, tun)
|
||||
fps := m.fps
|
||||
batch := m.batch
|
||||
m.mu.Unlock()
|
||||
m.wireSubTunnel(tun, false)
|
||||
if fps > 0 && batch > 0 {
|
||||
tun.Start(fps, batch)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) RemoveLastSubTunnel() *VP8DataTunnel {
|
||||
m.mu.Lock()
|
||||
if len(m.tunnels) <= 1 {
|
||||
m.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
last := m.tunnels[len(m.tunnels)-1]
|
||||
m.tunnels = m.tunnels[:len(m.tunnels)-1]
|
||||
m.mu.Unlock()
|
||||
last.Stop()
|
||||
return last
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) SubTunnelCount() int {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return len(m.tunnels)
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) SendData(data []byte) {
|
||||
m.mu.Lock()
|
||||
tunnels := m.tunnels
|
||||
m.mu.Unlock()
|
||||
if len(tunnels) == 0 {
|
||||
return
|
||||
}
|
||||
var connID uint32
|
||||
if len(data) >= 8 {
|
||||
connID = binary.BigEndian.Uint32(data[4:8])
|
||||
}
|
||||
idx := connID % uint32(len(tunnels))
|
||||
tunnels[idx].SendData(data)
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) DeliverData(data []byte) {
|
||||
m.mu.Lock()
|
||||
handler := m.onData
|
||||
m.mu.Unlock()
|
||||
if handler != nil {
|
||||
handler(data)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) SubTunnels() []*VP8DataTunnel {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
subs := make([]*VP8DataTunnel, len(m.tunnels))
|
||||
copy(subs, m.tunnels)
|
||||
return subs
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) SetOnData(fn func([]byte)) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.onData = fn
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) SetOnClose(fn func()) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.onClose = fn
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) SetOnPeerRestart(fn func()) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.onPeerRestart = fn
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) Reconfigure(fps, batch int) {
|
||||
m.mu.Lock()
|
||||
m.fps = fps
|
||||
m.batch = batch
|
||||
tunnels := m.tunnels
|
||||
m.mu.Unlock()
|
||||
for _, tun := range tunnels {
|
||||
tun.Reconfigure(fps, batch)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) Start(fps, batch int) {
|
||||
m.mu.Lock()
|
||||
m.fps = fps
|
||||
m.batch = batch
|
||||
tunnels := m.tunnels
|
||||
m.mu.Unlock()
|
||||
for _, tun := range tunnels {
|
||||
tun.Start(fps, batch)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) Stop() {
|
||||
m.mu.Lock()
|
||||
if m.isClosed {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
m.isClosed = true
|
||||
tunnels := m.tunnels
|
||||
m.mu.Unlock()
|
||||
for _, tun := range tunnels {
|
||||
tun.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MultiTrackTunnel) HandleFrame(frame []byte) {
|
||||
m.mu.Lock()
|
||||
var first *VP8DataTunnel
|
||||
if len(m.tunnels) > 0 {
|
||||
first = m.tunnels[0]
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if first != nil {
|
||||
first.HandleFrame(frame)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package rtc
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
)
|
||||
|
||||
const (
|
||||
screenWriterFPS = 24
|
||||
screenWriterBatch = 30
|
||||
screenWriterMaxBytes = 60000
|
||||
screenWriterQueue = 256
|
||||
screenKeepalivePadMax = 48
|
||||
)
|
||||
|
||||
type ScreenWriter struct {
|
||||
obf *tunnel.TunnelObfuscator
|
||||
logFn func(string, ...any)
|
||||
label string
|
||||
|
||||
sendMu sync.Mutex
|
||||
send func([]byte) error
|
||||
|
||||
stopCh chan struct{}
|
||||
sendQueue chan []byte
|
||||
cfgChan chan struct{}
|
||||
stopOnce sync.Once
|
||||
running atomic.Bool
|
||||
|
||||
cfgMu sync.Mutex
|
||||
fps int
|
||||
batch int
|
||||
sent atomic.Uint64
|
||||
}
|
||||
|
||||
func NewScreenWriter(obf *tunnel.TunnelObfuscator, label string, logFn func(string, ...any)) *ScreenWriter {
|
||||
return &ScreenWriter{
|
||||
obf: obf,
|
||||
logFn: logFn,
|
||||
label: label,
|
||||
stopCh: make(chan struct{}),
|
||||
sendQueue: make(chan []byte, screenWriterQueue),
|
||||
cfgChan: make(chan struct{}, 1),
|
||||
fps: screenWriterFPS,
|
||||
batch: screenWriterBatch,
|
||||
}
|
||||
}
|
||||
|
||||
// SetSend installs the transport. Until it is set, frames are dropped.
|
||||
func (w *ScreenWriter) SetSend(fn func([]byte) error) {
|
||||
w.sendMu.Lock()
|
||||
w.send = fn
|
||||
w.sendMu.Unlock()
|
||||
}
|
||||
|
||||
func (w *ScreenWriter) SendData(data []byte) {
|
||||
if len(data) == 0 {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case w.sendQueue <- data:
|
||||
case <-w.stopCh:
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ScreenWriter) Reconfigure(fps, batch int) {
|
||||
if fps <= 0 && batch <= 0 {
|
||||
return
|
||||
}
|
||||
w.cfgMu.Lock()
|
||||
changed := false
|
||||
if fps > 0 && w.fps != fps {
|
||||
w.fps = fps
|
||||
changed = true
|
||||
}
|
||||
if batch > 0 && w.batch != batch {
|
||||
w.batch = batch
|
||||
changed = true
|
||||
}
|
||||
w.cfgMu.Unlock()
|
||||
if changed {
|
||||
select {
|
||||
case w.cfgChan <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ScreenWriter) interval() time.Duration {
|
||||
w.cfgMu.Lock()
|
||||
fps, batch := w.fps, w.batch
|
||||
w.cfgMu.Unlock()
|
||||
frame := time.Second / time.Duration(fps)
|
||||
sample := frame
|
||||
if batch > 1 {
|
||||
sample = frame / time.Duration(batch)
|
||||
}
|
||||
if sample <= 0 {
|
||||
sample = time.Millisecond
|
||||
}
|
||||
return sample
|
||||
}
|
||||
|
||||
func (w *ScreenWriter) nextKeepalive(sample time.Duration) (ticks, padLen int) {
|
||||
ticks = int(common.DurationInRange(keepaliveIdleMin, keepaliveIdleMax) / sample)
|
||||
if ticks < 1 {
|
||||
ticks = 1
|
||||
}
|
||||
return ticks, common.IntInRange(0, screenKeepalivePadMax)
|
||||
}
|
||||
|
||||
func (w *ScreenWriter) Start() {
|
||||
if !w.running.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
go w.writerLoop()
|
||||
}
|
||||
|
||||
func (w *ScreenWriter) Stop() {
|
||||
if !w.running.CompareAndSwap(true, false) {
|
||||
return
|
||||
}
|
||||
w.stopOnce.Do(func() { close(w.stopCh) })
|
||||
}
|
||||
|
||||
func (w *ScreenWriter) emit(msg []byte) {
|
||||
if msg == nil || len(msg) > screenWriterMaxBytes {
|
||||
return
|
||||
}
|
||||
w.sendMu.Lock()
|
||||
send := w.send
|
||||
w.sendMu.Unlock()
|
||||
if send == nil {
|
||||
return
|
||||
}
|
||||
if err := send(msg); err != nil {
|
||||
return
|
||||
}
|
||||
n := w.sent.Add(1)
|
||||
if common.Debug && (n <= 5 || n%500 == 0) {
|
||||
w.logFn("[%s] sent frame #%d size=%d", w.label, n, len(msg))
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ScreenWriter) writerLoop() {
|
||||
for {
|
||||
sample := w.interval()
|
||||
keepaliveEvery, keepalivePad := w.nextKeepalive(sample)
|
||||
ticker := time.NewTicker(sample)
|
||||
idle := 0
|
||||
reconfigure := false
|
||||
for !reconfigure {
|
||||
select {
|
||||
case <-w.stopCh:
|
||||
ticker.Stop()
|
||||
return
|
||||
case <-w.cfgChan:
|
||||
reconfigure = true
|
||||
case <-ticker.C:
|
||||
select {
|
||||
case data := <-w.sendQueue:
|
||||
w.emit(w.obf.EncodeData(data))
|
||||
idle = 0
|
||||
default:
|
||||
idle++
|
||||
if idle < keepaliveEvery {
|
||||
continue
|
||||
}
|
||||
idle = 0
|
||||
w.emit(w.obf.EncodeKeepalive(keepalivePad))
|
||||
keepaliveEvery, keepalivePad = w.nextKeepalive(sample)
|
||||
}
|
||||
}
|
||||
}
|
||||
ticker.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
type SymmetricScreenTunnel struct {
|
||||
cam *VP8DataTunnel
|
||||
screen *ScreenWriter
|
||||
obf *tunnel.TunnelObfuscator
|
||||
logFn func(string, ...any)
|
||||
screenReady func() bool
|
||||
|
||||
onDataMu sync.Mutex
|
||||
onData func([]byte)
|
||||
recv atomic.Uint64
|
||||
trackCount atomic.Int32
|
||||
}
|
||||
|
||||
func (s *SymmetricScreenTunnel) SetTrackCount(n int) {
|
||||
if n < 1 {
|
||||
n = 1
|
||||
}
|
||||
if n > 2 {
|
||||
n = 2 // VK has two channels: camera VP8 + screen DC
|
||||
}
|
||||
old := s.trackCount.Swap(int32(n))
|
||||
if int(old) != n {
|
||||
s.logFn("screen tunnel track count %d -> %d", old, n)
|
||||
}
|
||||
if n >= 2 {
|
||||
s.screen.Start()
|
||||
}
|
||||
}
|
||||
|
||||
func NewSymmetricScreenTunnel(cam *VP8DataTunnel, screen *ScreenWriter, obf *tunnel.TunnelObfuscator, screenReady func() bool, logFn func(string, ...any)) *SymmetricScreenTunnel {
|
||||
return &SymmetricScreenTunnel{cam: cam, screen: screen, obf: obf, screenReady: screenReady, logFn: logFn}
|
||||
}
|
||||
|
||||
func (s *SymmetricScreenTunnel) screenUp() bool {
|
||||
if s.screenReady == nil {
|
||||
return true
|
||||
}
|
||||
return s.screenReady()
|
||||
}
|
||||
|
||||
func (s *SymmetricScreenTunnel) SendData(data []byte) {
|
||||
var connID uint32
|
||||
if len(data) >= 8 {
|
||||
connID = binary.BigEndian.Uint32(data[4:8])
|
||||
}
|
||||
if connID == tunnel.ControlConnID {
|
||||
s.cam.SendData(data)
|
||||
return
|
||||
}
|
||||
tc := uint32(s.trackCount.Load())
|
||||
if tc < 1 {
|
||||
tc = 1
|
||||
}
|
||||
if connID%tc == 1 && s.screenUp() {
|
||||
s.screen.SendData(data)
|
||||
return
|
||||
}
|
||||
s.cam.SendData(data)
|
||||
}
|
||||
|
||||
func (s *SymmetricScreenTunnel) SetOnData(fn func([]byte)) {
|
||||
s.onDataMu.Lock()
|
||||
s.onData = fn
|
||||
s.onDataMu.Unlock()
|
||||
s.cam.SetOnData(fn)
|
||||
}
|
||||
|
||||
func (s *SymmetricScreenTunnel) SetOnClose(fn func()) { s.cam.SetOnClose(fn) }
|
||||
func (s *SymmetricScreenTunnel) Reconfigure(fps, batch int) {
|
||||
s.cam.Reconfigure(fps, batch)
|
||||
s.screen.Reconfigure(fps, batch)
|
||||
}
|
||||
|
||||
func (s *SymmetricScreenTunnel) Stop() {
|
||||
s.screen.Stop()
|
||||
s.cam.Stop()
|
||||
}
|
||||
|
||||
func (s *SymmetricScreenTunnel) HandleScreenFrame(frame []byte) {
|
||||
res := s.obf.Decode(frame)
|
||||
n := s.recv.Add(1)
|
||||
if common.Debug && (n <= 10 || n%500 == 0) {
|
||||
s.logFn("screen recv frame #%d in=%d hasFrame=%v keepalive=%v payload=%d", n, len(frame), res.HasFrame, res.Keepalive, len(res.Payload))
|
||||
}
|
||||
if !res.HasFrame || res.SelfEcho || res.Keepalive || len(res.Payload) == 0 {
|
||||
return
|
||||
}
|
||||
s.onDataMu.Lock()
|
||||
handler := s.onData
|
||||
s.onDataMu.Unlock()
|
||||
if handler != nil {
|
||||
handler(res.Payload)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
package rtc
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/kulikov0/headless-client/webrtc"
|
||||
"github.com/kulikov0/headless-client/webrtc/pkg/media"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultVP8FPS = 24
|
||||
defaultVP8Batch = 30
|
||||
keepaliveIdlePeriod = 100 * time.Millisecond
|
||||
keepaliveIdleMin = 60 * time.Millisecond
|
||||
keepaliveIdleMax = 200 * time.Millisecond
|
||||
keepalivePadMax = 176
|
||||
sendQueueDepth = 128
|
||||
|
||||
paceBatchFloorPercent = 80
|
||||
paceDriftMin = 5 * time.Second
|
||||
paceDriftMax = 20 * time.Second
|
||||
|
||||
idleSpinTicks = 40
|
||||
)
|
||||
|
||||
type VP8DataTunnel struct {
|
||||
track *webrtc.TrackLocalStaticSample
|
||||
logFn func(string, ...any)
|
||||
obf *tunnel.TunnelObfuscator
|
||||
stopCh chan struct{}
|
||||
sendQueue chan []byte
|
||||
cfgChan chan struct{}
|
||||
|
||||
stopOnce sync.Once
|
||||
running atomic.Bool
|
||||
|
||||
cfgMu sync.Mutex
|
||||
fps int
|
||||
batch int
|
||||
keepaliveMin time.Duration
|
||||
keepaliveMax time.Duration
|
||||
keepalivePadMax int
|
||||
|
||||
sentFrames atomic.Uint64
|
||||
recvFrames atomic.Uint64
|
||||
keepaliveFrames atomic.Uint64
|
||||
|
||||
OnData func([]byte)
|
||||
OnClose func()
|
||||
OnPeerRestart func()
|
||||
|
||||
WriteFrame func([]byte) error
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) SetOnData(fn func([]byte)) { t.OnData = fn }
|
||||
func (t *VP8DataTunnel) SetOnClose(fn func()) { t.OnClose = fn }
|
||||
func (t *VP8DataTunnel) SetOnPeerRestart(fn func()) { t.OnPeerRestart = fn }
|
||||
|
||||
func NewVP8DataTunnel(track *webrtc.TrackLocalStaticSample, obf *tunnel.TunnelObfuscator, logFn func(string, ...any)) *VP8DataTunnel {
|
||||
return NewVP8DataTunnelWithQueue(track, obf, logFn, sendQueueDepth)
|
||||
}
|
||||
|
||||
func NewVP8DataTunnelWithQueue(track *webrtc.TrackLocalStaticSample, obf *tunnel.TunnelObfuscator, logFn func(string, ...any), queueDepth int) *VP8DataTunnel {
|
||||
if queueDepth < sendQueueDepth {
|
||||
queueDepth = sendQueueDepth
|
||||
}
|
||||
return &VP8DataTunnel{
|
||||
track: track,
|
||||
obf: obf,
|
||||
logFn: logFn,
|
||||
stopCh: make(chan struct{}),
|
||||
sendQueue: make(chan []byte, queueDepth),
|
||||
cfgChan: make(chan struct{}, 1),
|
||||
fps: defaultVP8FPS,
|
||||
batch: defaultVP8Batch,
|
||||
keepaliveMin: keepaliveIdleMin,
|
||||
keepaliveMax: keepaliveIdleMax,
|
||||
keepalivePadMax: keepalivePadMax,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) nextKeepalive(sampleInterval time.Duration) (ticks, padLen int) {
|
||||
t.cfgMu.Lock()
|
||||
minPeriod, maxPeriod, padMax := t.keepaliveMin, t.keepaliveMax, t.keepalivePadMax
|
||||
t.cfgMu.Unlock()
|
||||
ticks = int(common.DurationInRange(minPeriod, maxPeriod) / sampleInterval)
|
||||
if ticks < 1 {
|
||||
ticks = 1
|
||||
}
|
||||
return ticks, common.IntInRange(0, padMax)
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) Reconfigure(fps, batch int) {
|
||||
if fps <= 0 && batch <= 0 {
|
||||
return
|
||||
}
|
||||
t.cfgMu.Lock()
|
||||
changed := false
|
||||
if fps > 0 && t.fps != fps {
|
||||
t.fps = fps
|
||||
changed = true
|
||||
}
|
||||
if batch > 0 && t.batch != batch {
|
||||
t.batch = batch
|
||||
changed = true
|
||||
}
|
||||
newFPS, newBatch := t.fps, t.batch
|
||||
t.cfgMu.Unlock()
|
||||
if !changed {
|
||||
return
|
||||
}
|
||||
t.logFn("vp8tunnel: reconfigure fps=%d batch=%d", newFPS, newBatch)
|
||||
select {
|
||||
case t.cfgChan <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) FPS() int {
|
||||
t.cfgMu.Lock()
|
||||
defer t.cfgMu.Unlock()
|
||||
return t.fps
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) Batch() int {
|
||||
t.cfgMu.Lock()
|
||||
defer t.cfgMu.Unlock()
|
||||
return t.batch
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) SendData(data []byte) {
|
||||
if len(data) == 0 {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case t.sendQueue <- data:
|
||||
case <-t.stopCh:
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) TrySendData(data []byte) bool {
|
||||
if len(data) == 0 {
|
||||
return true
|
||||
}
|
||||
select {
|
||||
case t.sendQueue <- data:
|
||||
return true
|
||||
case <-t.stopCh:
|
||||
return false
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) Start(fps, batch int) {
|
||||
t.cfgMu.Lock()
|
||||
if fps > 0 {
|
||||
t.fps = fps
|
||||
}
|
||||
if batch > 0 {
|
||||
t.batch = batch
|
||||
}
|
||||
t.cfgMu.Unlock()
|
||||
if !t.running.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
go t.writerLoop()
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) Stop() {
|
||||
if !t.running.CompareAndSwap(true, false) {
|
||||
return
|
||||
}
|
||||
t.stopOnce.Do(func() { close(t.stopCh) })
|
||||
if t.OnClose != nil {
|
||||
t.OnClose()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) currentRate() (fps, batch int) {
|
||||
t.cfgMu.Lock()
|
||||
defer t.cfgMu.Unlock()
|
||||
return t.fps, t.batch
|
||||
}
|
||||
|
||||
func sampleIntervalFor(fps, batch int) time.Duration {
|
||||
if fps < 1 {
|
||||
fps = 1
|
||||
}
|
||||
frameInterval := time.Second / time.Duration(fps)
|
||||
interval := frameInterval
|
||||
if batch > 1 {
|
||||
interval = frameInterval / time.Duration(batch)
|
||||
}
|
||||
if interval <= 0 {
|
||||
interval = time.Millisecond
|
||||
}
|
||||
return interval
|
||||
}
|
||||
|
||||
func pacedBatchFor(batch int) int {
|
||||
if batch <= 1 {
|
||||
return batch
|
||||
}
|
||||
floor := batch * paceBatchFloorPercent / 100
|
||||
if floor < 1 {
|
||||
floor = 1
|
||||
}
|
||||
return common.IntInRange(floor, batch)
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) writerLoop() {
|
||||
for {
|
||||
fps, batch := t.currentRate()
|
||||
pacedBatch := pacedBatchFor(batch)
|
||||
sampleInterval := sampleIntervalFor(fps, pacedBatch)
|
||||
keepaliveEvery, keepalivePad := t.nextKeepalive(sampleInterval)
|
||||
t.logFn("vp8tunnel: writer (re)started fps=%d batch=%d pacedBatch=%d sampleInterval=%s keepaliveEvery=%d",
|
||||
fps, batch, pacedBatch, sampleInterval, keepaliveEvery)
|
||||
|
||||
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 t.WriteFrame != nil {
|
||||
if err := t.WriteFrame(sample); err != nil {
|
||||
if common.Debug {
|
||||
t.logFn("vp8tunnel: WriteFrame error: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
} else 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:
|
||||
drift.Stop()
|
||||
idle.Stop()
|
||||
return
|
||||
case <-t.cfgChan:
|
||||
reconfigure = true
|
||||
case <-drift.C:
|
||||
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)
|
||||
idle.Reset(time.Duration(keepaliveEvery) * sampleInterval)
|
||||
}
|
||||
}
|
||||
ticker.Stop()
|
||||
drift.Stop()
|
||||
idle.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) HandleFrame(frame []byte) {
|
||||
res := t.obf.Decode(frame)
|
||||
if !res.HasFrame {
|
||||
return
|
||||
}
|
||||
if res.SelfEcho {
|
||||
return
|
||||
}
|
||||
if res.PeerRestart {
|
||||
t.logFn("vp8tunnel: peer restart detected, new epoch=0x%08x", res.PeerEpoch)
|
||||
if t.OnPeerRestart != nil {
|
||||
t.OnPeerRestart()
|
||||
}
|
||||
}
|
||||
if res.Keepalive || len(res.Payload) == 0 {
|
||||
return
|
||||
}
|
||||
n := t.recvFrames.Add(1)
|
||||
if common.Debug && (n <= 5 || n%500 == 0) {
|
||||
t.logFn("vp8tunnel: recv frame #%d size=%d", n, len(res.Payload))
|
||||
}
|
||||
if t.OnData != nil {
|
||||
t.OnData(res.Payload)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package rtc
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/kulikov0/headless-client/webrtc"
|
||||
"github.com/kulikov0/headless-client/webrtc/pkg/media"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
)
|
||||
|
||||
var legacyVP8Keyframe = []byte{
|
||||
16, 2, 0, 157, 1, 42, 2, 0, 2, 0, 2, 7, 8, 133, 133, 136,
|
||||
153, 132, 136, 11, 2, 0, 12, 13, 96, 0, 254, 252, 173, 16,
|
||||
}
|
||||
|
||||
var legacyVP8Interframe = []byte{
|
||||
177, 1, 0, 8, 17, 24, 0, 24, 0, 24, 88, 47, 244, 0, 8, 0, 0,
|
||||
}
|
||||
|
||||
const (
|
||||
legacyDataMarker byte = 0xCD
|
||||
legacyVP8InterLen = 17
|
||||
legacyDataHeaderLen = legacyVP8InterLen + 1 + 4
|
||||
legacyKeyframeEvery = 60
|
||||
)
|
||||
|
||||
type VP8LegacyTunnel struct {
|
||||
track *webrtc.TrackLocalStaticSample
|
||||
logFn func(string, ...any)
|
||||
stopCh chan struct{}
|
||||
sendQueue chan []byte
|
||||
cfgChan chan struct{}
|
||||
|
||||
stopOnce sync.Once
|
||||
running atomic.Bool
|
||||
|
||||
cfgMu sync.Mutex
|
||||
fps int
|
||||
batch int
|
||||
|
||||
sentFrames atomic.Uint64
|
||||
recvFrames atomic.Uint64
|
||||
|
||||
OnData func([]byte)
|
||||
OnClose func()
|
||||
}
|
||||
|
||||
func (t *VP8LegacyTunnel) SetOnData(fn func([]byte)) { t.OnData = fn }
|
||||
func (t *VP8LegacyTunnel) SetOnClose(fn func()) { t.OnClose = fn }
|
||||
|
||||
func NewVP8LegacyTunnel(track *webrtc.TrackLocalStaticSample, logFn func(string, ...any)) *VP8LegacyTunnel {
|
||||
return &VP8LegacyTunnel{
|
||||
track: track,
|
||||
logFn: logFn,
|
||||
stopCh: make(chan struct{}),
|
||||
sendQueue: make(chan []byte, sendQueueDepth),
|
||||
cfgChan: make(chan struct{}, 1),
|
||||
fps: defaultVP8FPS,
|
||||
batch: defaultVP8Batch,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8LegacyTunnel) SendData(data []byte) {
|
||||
if len(data) == 0 {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case t.sendQueue <- data:
|
||||
case <-t.stopCh:
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8LegacyTunnel) Reconfigure(fps, batch int) {
|
||||
if fps <= 0 && batch <= 0 {
|
||||
return
|
||||
}
|
||||
t.cfgMu.Lock()
|
||||
changed := false
|
||||
if fps > 0 && t.fps != fps {
|
||||
t.fps = fps
|
||||
changed = true
|
||||
}
|
||||
if batch > 0 && t.batch != batch {
|
||||
t.batch = batch
|
||||
changed = true
|
||||
}
|
||||
newFPS, newBatch := t.fps, t.batch
|
||||
t.cfgMu.Unlock()
|
||||
if !changed {
|
||||
return
|
||||
}
|
||||
t.logFn("vp8tunnel-legacy: reconfigure fps=%d batch=%d", newFPS, newBatch)
|
||||
select {
|
||||
case t.cfgChan <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8LegacyTunnel) Start(fps, batch int) {
|
||||
t.cfgMu.Lock()
|
||||
if fps > 0 {
|
||||
t.fps = fps
|
||||
}
|
||||
if batch > 0 {
|
||||
t.batch = batch
|
||||
}
|
||||
t.cfgMu.Unlock()
|
||||
if !t.running.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
go t.writerLoop()
|
||||
}
|
||||
|
||||
func (t *VP8LegacyTunnel) Stop() {
|
||||
if !t.running.CompareAndSwap(true, false) {
|
||||
return
|
||||
}
|
||||
t.stopOnce.Do(func() { close(t.stopCh) })
|
||||
if t.OnClose != nil {
|
||||
t.OnClose()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8LegacyTunnel) currentIntervals() (sampleInterval time.Duration, keepaliveEvery, fps, batch int) {
|
||||
t.cfgMu.Lock()
|
||||
fps = t.fps
|
||||
batch = t.batch
|
||||
t.cfgMu.Unlock()
|
||||
|
||||
frameInterval := time.Second / time.Duration(fps)
|
||||
sampleInterval = frameInterval
|
||||
if batch > 1 {
|
||||
sampleInterval = frameInterval / time.Duration(batch)
|
||||
}
|
||||
if sampleInterval <= 0 {
|
||||
sampleInterval = time.Millisecond
|
||||
}
|
||||
|
||||
keepaliveEvery = int(keepaliveIdlePeriod / sampleInterval)
|
||||
if keepaliveEvery < 1 {
|
||||
keepaliveEvery = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func encodeLegacyData(payload []byte) []byte {
|
||||
frame := make([]byte, legacyDataHeaderLen+len(payload))
|
||||
copy(frame, legacyVP8Interframe)
|
||||
frame[len(legacyVP8Interframe)] = legacyDataMarker
|
||||
binary.BigEndian.PutUint32(frame[len(legacyVP8Interframe)+1:], uint32(len(payload)))
|
||||
copy(frame[legacyDataHeaderLen:], payload)
|
||||
return frame
|
||||
}
|
||||
|
||||
func (t *VP8LegacyTunnel) writerLoop() {
|
||||
for {
|
||||
sampleInterval, keepaliveEvery, fps, batch := t.currentIntervals()
|
||||
t.logFn("vp8tunnel-legacy: writer (re)started fps=%d batch=%d sampleInterval=%s keepaliveEvery=%d",
|
||||
fps, batch, sampleInterval, keepaliveEvery)
|
||||
|
||||
ticker := time.NewTicker(sampleInterval)
|
||||
idleTicks := 0
|
||||
reconfigure := false
|
||||
|
||||
for !reconfigure {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
ticker.Stop()
|
||||
return
|
||||
case <-t.cfgChan:
|
||||
reconfigure = true
|
||||
case <-ticker.C:
|
||||
var sample []byte
|
||||
select {
|
||||
case data := <-t.sendQueue:
|
||||
sample = encodeLegacyData(data)
|
||||
idleTicks = 0
|
||||
default:
|
||||
idleTicks++
|
||||
if idleTicks < keepaliveEvery {
|
||||
continue
|
||||
}
|
||||
idleTicks = 0
|
||||
if (t.sentFrames.Load()+1)%legacyKeyframeEvery == 0 {
|
||||
sample = legacyVP8Keyframe
|
||||
} else {
|
||||
sample = legacyVP8Interframe
|
||||
}
|
||||
}
|
||||
if err := t.track.WriteSample(media.Sample{Data: sample, Duration: sampleInterval}); err != nil {
|
||||
if common.Debug {
|
||||
t.logFn("vp8tunnel-legacy: WriteSample error: %v", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
n := t.sentFrames.Add(1)
|
||||
if common.Debug && (n <= 5 || n%500 == 0) {
|
||||
t.logFn("vp8tunnel-legacy: sent frame #%d size=%d", n, len(sample))
|
||||
}
|
||||
}
|
||||
}
|
||||
ticker.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func extractLegacyPayload(frame []byte) []byte {
|
||||
if len(frame) < legacyDataHeaderLen {
|
||||
return nil
|
||||
}
|
||||
for i := range legacyVP8Interframe {
|
||||
if frame[i] != legacyVP8Interframe[i] {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if frame[len(legacyVP8Interframe)] != legacyDataMarker {
|
||||
return nil
|
||||
}
|
||||
payloadLen := binary.BigEndian.Uint32(frame[len(legacyVP8Interframe)+1 : legacyDataHeaderLen])
|
||||
if payloadLen == 0 || int(payloadLen) > len(frame)-legacyDataHeaderLen {
|
||||
return nil
|
||||
}
|
||||
return frame[legacyDataHeaderLen : legacyDataHeaderLen+int(payloadLen)]
|
||||
}
|
||||
|
||||
func (t *VP8LegacyTunnel) HandleFrame(frame []byte) {
|
||||
payload := extractLegacyPayload(frame)
|
||||
if payload == nil {
|
||||
return
|
||||
}
|
||||
n := t.recvFrames.Add(1)
|
||||
if common.Debug && (n <= 5 || n%500 == 0) {
|
||||
t.logFn("vp8tunnel-legacy: recv frame #%d size=%d", n, len(payload))
|
||||
}
|
||||
if t.OnData != nil {
|
||||
t.OnData(payload)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user