VP8 pacing + traffic obfuscation in headless
This commit is contained in:
1 parent
deb1625617
commit
b48b0cb927
34 files changed
+936
-218
No files matched your search
+35
-20
@@ -30,8 +30,9 @@ type DCTunnel struct {
|
||||
logFn func(string, ...any)
|
||||
onData func([]byte)
|
||||
onClose func()
|
||||
chunked bool
|
||||
readBuf int
|
||||
obf *TunnelObfuscator
|
||||
chunked bool
|
||||
readBuf int
|
||||
|
||||
recvBufs sync.Map
|
||||
sendMsgID uint32
|
||||
@@ -42,21 +43,16 @@ type DCTunnel struct {
|
||||
sendMsgs atomic.Uint64
|
||||
}
|
||||
|
||||
func NewDCTunnel(dc *webrtc.DataChannel, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
t := &DCTunnel{dc: dc, readBuf: readBuf, logFn: logFn}
|
||||
func NewDCTunnel(dc *webrtc.DataChannel, obf *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) {
|
||||
if t.onData != nil {
|
||||
t.recvBytes.Add(uint64(len(msg.Data)))
|
||||
t.recvMsgs.Add(1)
|
||||
frame := make([]byte, 4+len(msg.Data))
|
||||
binary.BigEndian.PutUint32(frame[0:4], uint32(len(msg.Data)))
|
||||
copy(frame[4:], msg.Data)
|
||||
t.onData(frame)
|
||||
}
|
||||
t.recvBytes.Add(uint64(len(msg.Data)))
|
||||
t.recvMsgs.Add(1)
|
||||
t.deliverMessage(msg.Data)
|
||||
})
|
||||
dc.OnClose(func() {
|
||||
if t.onClose != nil {
|
||||
@@ -73,20 +69,20 @@ func NewDCTunnel(dc *webrtc.DataChannel, readBuf int, logFn func(string, ...any)
|
||||
return t
|
||||
}
|
||||
|
||||
func NewDCTunnelFromRaw(dc *webrtc.DataChannel, raw datachannel.ReadWriteCloser, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
t := &DCTunnel{dc: dc, raw: raw, readBuf: readBuf, logFn: logFn}
|
||||
func NewDCTunnelFromRaw(dc *webrtc.DataChannel, raw datachannel.ReadWriteCloser, obf *TunnelObfuscator, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
t := &DCTunnel{dc: dc, raw: raw, obf: obf, readBuf: readBuf, logFn: logFn}
|
||||
go t.readLoop()
|
||||
go t.statsLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
func NewChunkedDCTunnel(readRaw datachannel.ReadWriteCloser, writeDC *webrtc.DataChannel, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
func NewChunkedDCTunnel(readRaw datachannel.ReadWriteCloser, writeDC *webrtc.DataChannel, obf *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, readBuf: readBuf, logFn: logFn, chunked: true}
|
||||
t := &DCTunnel{raw: readRaw, writeRaw: writeRaw, obf: obf, readBuf: readBuf, logFn: logFn, chunked: true}
|
||||
go t.readLoop()
|
||||
go t.statsLoop()
|
||||
return t
|
||||
@@ -151,6 +147,17 @@ func (t *DCTunnel) handleChunk(data []byte) {
|
||||
}
|
||||
|
||||
func (t *DCTunnel) deliverMessage(data []byte) {
|
||||
if len(data) == 0 {
|
||||
return
|
||||
}
|
||||
if t.obf != nil {
|
||||
pt, ok := t.obf.DecryptPayload(data)
|
||||
if !ok {
|
||||
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)))
|
||||
@@ -218,16 +225,24 @@ func (t *DCTunnel) SendData(data []byte) {
|
||||
binary.BigEndian.PutUint32(buf[0:4], connID)
|
||||
buf[4] = msgType
|
||||
copy(buf[5:], payload)
|
||||
wire := buf
|
||||
if t.obf != nil {
|
||||
wire = t.obf.EncryptPayload(buf)
|
||||
if wire == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if t.chunked {
|
||||
t.sendChunked(buf)
|
||||
t.sendChunked(wire)
|
||||
} else {
|
||||
t.sendRaw(buf)
|
||||
t.sendRaw(wire)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (t *DCTunnel) SetOnData(fn func([]byte)) { t.onData = fn }
|
||||
func (t *DCTunnel) SetOnClose(fn func()) { t.onClose = fn }
|
||||
func (t *DCTunnel) SetOnData(fn func([]byte)) { t.onData = fn }
|
||||
func (t *DCTunnel) SetOnClose(fn func()) { t.onClose = fn }
|
||||
func (t *DCTunnel) Reconfigure(fps, batch int) {}
|
||||
|
||||
func (t *DCTunnel) statsLoop() {
|
||||
if !dcStatsEnabled {
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
)
|
||||
|
||||
var vp8Keepalive = []byte{
|
||||
0x30, 0x01, 0x00, 0x9d, 0x01, 0x2a, 0x10, 0x00,
|
||||
0x10, 0x00, 0x00, 0x47, 0x08, 0x85, 0x85, 0x88,
|
||||
0x99, 0x84, 0x88, 0xfc,
|
||||
}
|
||||
|
||||
const (
|
||||
vp8KeepaliveLen = 20
|
||||
epochOff = vp8KeepaliveLen
|
||||
epochHdrLen = vp8KeepaliveLen + 4
|
||||
)
|
||||
|
||||
var ErrEmptySecret = errors.New("tunnel: obfuscator requires a non-empty secret")
|
||||
|
||||
type DecodeResult struct {
|
||||
HasFrame bool
|
||||
Keepalive bool
|
||||
SelfEcho bool
|
||||
PeerRestart bool
|
||||
Payload []byte
|
||||
PeerEpoch uint32
|
||||
}
|
||||
|
||||
type TunnelObfuscator struct {
|
||||
aead cipher.AEAD
|
||||
localEpoch uint32
|
||||
|
||||
mu sync.Mutex
|
||||
peerEpoch uint32
|
||||
hasPeer bool
|
||||
}
|
||||
|
||||
func DeriveSecretFromJoinLink(joinLink string) []byte {
|
||||
token := extractJoinToken(joinLink)
|
||||
if token == "" {
|
||||
return nil
|
||||
}
|
||||
return []byte(token)
|
||||
}
|
||||
|
||||
func extractJoinToken(joinLink string) string {
|
||||
s := strings.TrimSpace(joinLink)
|
||||
s = strings.TrimRight(s, "/")
|
||||
if i := strings.IndexByte(s, '?'); i >= 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
if i := strings.IndexByte(s, '#'); i >= 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
if i := strings.LastIndexByte(s, '/'); i >= 0 {
|
||||
s = s[i+1:]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func NewTunnelObfuscator(secret []byte) (*TunnelObfuscator, error) {
|
||||
if len(secret) == 0 {
|
||||
return nil, ErrEmptySecret
|
||||
}
|
||||
keyHash := sha256.Sum256(secret)
|
||||
aead, err := chacha20poly1305.NewX(keyHash[:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var epochBytes [4]byte
|
||||
if _, err := rand.Read(epochBytes[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
epoch := binary.BigEndian.Uint32(epochBytes[:])
|
||||
if epoch == 0 {
|
||||
epoch = 1
|
||||
}
|
||||
return &TunnelObfuscator{aead: aead, localEpoch: epoch}, nil
|
||||
}
|
||||
|
||||
func (o *TunnelObfuscator) LocalEpoch() uint32 { return o.localEpoch }
|
||||
|
||||
func (o *TunnelObfuscator) header() []byte {
|
||||
hdr := make([]byte, epochHdrLen)
|
||||
copy(hdr, vp8Keepalive)
|
||||
binary.BigEndian.PutUint32(hdr[epochOff:], o.localEpoch)
|
||||
return hdr
|
||||
}
|
||||
|
||||
func (o *TunnelObfuscator) EncodeKeepalive() []byte {
|
||||
return o.header()
|
||||
}
|
||||
|
||||
func (o *TunnelObfuscator) EncodeData(payload []byte) []byte {
|
||||
hdr := o.header()
|
||||
nonce := make([]byte, o.aead.NonceSize())
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]byte, 0, len(hdr)+len(nonce)+len(payload)+o.aead.Overhead())
|
||||
out = append(out, hdr...)
|
||||
out = append(out, nonce...)
|
||||
out = o.aead.Seal(out, nonce, payload, nil)
|
||||
return out
|
||||
}
|
||||
|
||||
func (o *TunnelObfuscator) EncryptPayload(plaintext []byte) []byte {
|
||||
if o == nil {
|
||||
return plaintext
|
||||
}
|
||||
nonce := make([]byte, o.aead.NonceSize())
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]byte, 0, len(nonce)+len(plaintext)+o.aead.Overhead())
|
||||
out = append(out, nonce...)
|
||||
return o.aead.Seal(out, nonce, plaintext, nil)
|
||||
}
|
||||
|
||||
func (o *TunnelObfuscator) DecryptPayload(data []byte) ([]byte, bool) {
|
||||
if o == nil {
|
||||
return data, true
|
||||
}
|
||||
nonceSize := o.aead.NonceSize()
|
||||
if len(data) < nonceSize+o.aead.Overhead() {
|
||||
return nil, false
|
||||
}
|
||||
nonce := data[:nonceSize]
|
||||
ciphertext := data[nonceSize:]
|
||||
plaintext, err := o.aead.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return plaintext, true
|
||||
}
|
||||
|
||||
func (o *TunnelObfuscator) Decode(frame []byte) DecodeResult {
|
||||
if len(frame) < epochHdrLen {
|
||||
return DecodeResult{}
|
||||
}
|
||||
peerEpoch := binary.BigEndian.Uint32(frame[epochOff:epochHdrLen])
|
||||
if peerEpoch == o.localEpoch {
|
||||
return DecodeResult{HasFrame: true, SelfEcho: true, PeerEpoch: peerEpoch}
|
||||
}
|
||||
|
||||
res := DecodeResult{HasFrame: true, PeerEpoch: peerEpoch}
|
||||
o.mu.Lock()
|
||||
if !o.hasPeer {
|
||||
o.peerEpoch = peerEpoch
|
||||
o.hasPeer = true
|
||||
} else if o.peerEpoch != peerEpoch {
|
||||
o.peerEpoch = peerEpoch
|
||||
res.PeerRestart = true
|
||||
}
|
||||
o.mu.Unlock()
|
||||
|
||||
if len(frame) == epochHdrLen {
|
||||
res.Keepalive = true
|
||||
return res
|
||||
}
|
||||
|
||||
body := frame[epochHdrLen:]
|
||||
nonceSize := o.aead.NonceSize()
|
||||
if len(body) < nonceSize+o.aead.Overhead() {
|
||||
return DecodeResult{}
|
||||
}
|
||||
nonce := body[:nonceSize]
|
||||
ciphertext := body[nonceSize:]
|
||||
plaintext, err := o.aead.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return DecodeResult{}
|
||||
}
|
||||
res.Payload = plaintext
|
||||
return res
|
||||
}
|
||||
@@ -10,12 +10,44 @@ const (
|
||||
MsgClose byte = 0x05
|
||||
MsgUDP byte = 0x06
|
||||
MsgUDPReply byte = 0x07
|
||||
MsgConfig byte = 0x08
|
||||
)
|
||||
|
||||
const ControlConnID uint32 = 0
|
||||
|
||||
type DataTunnel interface {
|
||||
SendData(data []byte)
|
||||
SetOnData(fn func([]byte))
|
||||
SetOnClose(fn func())
|
||||
Reconfigure(fps, batch int)
|
||||
}
|
||||
|
||||
func EncodeVP8Config(fps, batch int) []byte {
|
||||
if fps < 1 {
|
||||
fps = 1
|
||||
}
|
||||
if batch < 1 {
|
||||
batch = 1
|
||||
}
|
||||
if fps > 0xFFFF {
|
||||
fps = 0xFFFF
|
||||
}
|
||||
if batch > 0xFFFF {
|
||||
batch = 0xFFFF
|
||||
}
|
||||
var payload [4]byte
|
||||
binary.BigEndian.PutUint16(payload[0:2], uint16(fps))
|
||||
binary.BigEndian.PutUint16(payload[2:4], uint16(batch))
|
||||
return EncodeFrame(ControlConnID, MsgConfig, payload[:])
|
||||
}
|
||||
|
||||
func DecodeVP8Config(payload []byte) (fps, batch int, ok bool) {
|
||||
if len(payload) < 4 {
|
||||
return 0, 0, false
|
||||
}
|
||||
fps = int(binary.BigEndian.Uint16(payload[0:2]))
|
||||
batch = int(binary.BigEndian.Uint16(payload[2:4]))
|
||||
return fps, batch, true
|
||||
}
|
||||
|
||||
func EncodeFrame(connID uint32, msgType byte, payload []byte) []byte {
|
||||
|
||||
@@ -78,6 +78,17 @@ func (rb *RelayBridge) send(connID uint32, msgType byte, payload []byte) {
|
||||
|
||||
func (rb *RelayBridge) handleTunnelData(data []byte) {
|
||||
DecodeFrames(data, func(connID uint32, msgType byte, payload []byte) {
|
||||
if connID == ControlConnID && msgType == MsgConfig {
|
||||
fps, batch, ok := DecodeVP8Config(payload)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if rb.mode == "creator" {
|
||||
rb.logFn("relay: peer requested vp8 pacing fps=%d batch=%d", fps, batch)
|
||||
rb.tunnel.Reconfigure(fps, batch)
|
||||
}
|
||||
return
|
||||
}
|
||||
switch rb.mode {
|
||||
case "joiner":
|
||||
rb.handleJoinerMessage(connID, msgType, payload)
|
||||
|
||||
+180
-106
@@ -1,7 +1,6 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -10,138 +9,213 @@ import (
|
||||
"github.com/pion/webrtc/v4/pkg/media"
|
||||
)
|
||||
|
||||
var vp8Keyframe = []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 vp8Interframe = []byte{
|
||||
177, 1, 0, 8, 17, 24, 0, 24, 0, 24, 88, 47, 244, 0, 8, 0, 0,
|
||||
}
|
||||
|
||||
const DataFrameMarker = 0xCD
|
||||
const dataHeaderLen = 17 + 1 + 4 // vp8Interframe + marker + uint32 length
|
||||
const (
|
||||
defaultVP8FPS = 24
|
||||
defaultVP8Batch = 30
|
||||
keepaliveIdlePeriod = 100 * time.Millisecond
|
||||
sendQueueDepth = 1024
|
||||
)
|
||||
|
||||
type VP8DataTunnel struct {
|
||||
track *webrtc.TrackLocalStaticSample
|
||||
mu sync.Mutex
|
||||
logFn func(string, ...any)
|
||||
frameCount uint64
|
||||
running bool
|
||||
stopCh chan struct{}
|
||||
sendQueue chan []byte
|
||||
OnData func([]byte)
|
||||
OnClose func()
|
||||
track *webrtc.TrackLocalStaticSample
|
||||
logFn func(string, ...any)
|
||||
obf *TunnelObfuscator
|
||||
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 *VP8DataTunnel) SetOnData(fn func([]byte)) { t.OnData = fn }
|
||||
func (t *VP8DataTunnel) SetOnClose(fn func()) { t.OnClose = fn }
|
||||
func (t *VP8DataTunnel) SetOnData(fn func([]byte)) { t.OnData = fn }
|
||||
func (t *VP8DataTunnel) SetOnClose(fn func()) { t.OnClose = fn }
|
||||
|
||||
func NewVP8DataTunnel(track *webrtc.TrackLocalStaticSample, logFn func(string, ...any)) *VP8DataTunnel {
|
||||
func NewVP8DataTunnel(track *webrtc.TrackLocalStaticSample, obf *TunnelObfuscator, logFn func(string, ...any)) *VP8DataTunnel {
|
||||
return &VP8DataTunnel{
|
||||
track: track,
|
||||
obf: obf,
|
||||
logFn: logFn,
|
||||
stopCh: make(chan struct{}),
|
||||
sendQueue: make(chan []byte, 256),
|
||||
sendQueue: make(chan []byte, sendQueueDepth),
|
||||
cfgChan: make(chan struct{}, 1),
|
||||
fps: defaultVP8FPS,
|
||||
batch: defaultVP8Batch,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) buildFrame(data []byte) []byte {
|
||||
t.frameCount++
|
||||
if len(data) == 0 {
|
||||
if t.frameCount%60 == 0 {
|
||||
return vp8Keyframe
|
||||
}
|
||||
return vp8Interframe
|
||||
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:
|
||||
}
|
||||
frame := make([]byte, dataHeaderLen+len(data))
|
||||
copy(frame, vp8Interframe)
|
||||
frame[len(vp8Interframe)] = DataFrameMarker
|
||||
binary.BigEndian.PutUint32(frame[len(vp8Interframe)+1:len(vp8Interframe)+5], uint32(len(data)))
|
||||
copy(frame[dataHeaderLen:], data)
|
||||
return frame
|
||||
}
|
||||
|
||||
var sendCount atomic.Uint64
|
||||
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) {
|
||||
n := sendCount.Add(1)
|
||||
if n <= 5 || n%100 == 0 {
|
||||
t.logFn("vp8tunnel: SendData #%d len=%d queueLen=%d", n, len(data), len(t.sendQueue))
|
||||
if len(data) == 0 {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case t.sendQueue <- data:
|
||||
case <-t.stopCh:
|
||||
}
|
||||
t.sendQueue <- data
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) Start(fps int) {
|
||||
t.running = true
|
||||
keepaliveInterval := time.Second / time.Duration(fps)
|
||||
lastSend := time.Now()
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(keepaliveInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
return
|
||||
case data := <-t.sendQueue:
|
||||
now := time.Now()
|
||||
elapsed := now.Sub(lastSend)
|
||||
// Most stable interval for burst mode, prevents congestion control
|
||||
minInterval := 1250 * time.Microsecond
|
||||
if elapsed < minInterval {
|
||||
time.Sleep(minInterval - elapsed)
|
||||
}
|
||||
frame := t.buildFrame(data)
|
||||
err := t.track.WriteSample(media.Sample{Data: frame, Duration: keepaliveInterval})
|
||||
lastSend = time.Now()
|
||||
if err != nil {
|
||||
t.logFn("vp8tunnel: WriteSample DATA error: %v (frame %d, %d bytes)", err, t.frameCount-1, len(frame))
|
||||
} else if t.frameCount <= 10 || t.frameCount%100 == 0 {
|
||||
t.logFn("vp8tunnel: WriteSample DATA ok frame=%d size=%d dataLen=%d first=0x%02x", t.frameCount-1, len(frame), len(data), frame[0])
|
||||
}
|
||||
if t.frameCount%60 == 0 {
|
||||
kf := t.buildFrame(nil)
|
||||
t.track.WriteSample(media.Sample{Data: kf, Duration: keepaliveInterval})
|
||||
}
|
||||
ticker.Reset(keepaliveInterval)
|
||||
case <-ticker.C:
|
||||
lastSend = time.Now()
|
||||
frame := t.buildFrame(nil)
|
||||
err := t.track.WriteSample(media.Sample{Data: frame, Duration: keepaliveInterval})
|
||||
if t.frameCount <= 3 || t.frameCount%500 == 0 {
|
||||
t.logFn("vp8tunnel: KEEPALIVE frame=%d first=0x%02x err=%v", t.frameCount-1, frame[0], err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
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 {
|
||||
close(t.stopCh)
|
||||
t.running = false
|
||||
if t.OnClose != nil {
|
||||
t.OnClose()
|
||||
}
|
||||
if !t.running.CompareAndSwap(true, false) {
|
||||
return
|
||||
}
|
||||
t.stopOnce.Do(func() { close(t.stopCh) })
|
||||
if t.OnClose != nil {
|
||||
t.OnClose()
|
||||
}
|
||||
}
|
||||
|
||||
func ExtractDataFromPayload(payload []byte) []byte {
|
||||
if len(payload) < dataHeaderLen {
|
||||
return nil
|
||||
func (t *VP8DataTunnel) 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)
|
||||
}
|
||||
for i := range vp8Interframe {
|
||||
if payload[i] != vp8Interframe[i] {
|
||||
return nil
|
||||
}
|
||||
if sampleInterval <= 0 {
|
||||
sampleInterval = time.Millisecond
|
||||
}
|
||||
if payload[len(vp8Interframe)] != DataFrameMarker {
|
||||
return nil
|
||||
|
||||
keepaliveEvery = int(keepaliveIdlePeriod / sampleInterval)
|
||||
if keepaliveEvery < 1 {
|
||||
keepaliveEvery = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) writerLoop() {
|
||||
for {
|
||||
sampleInterval, keepaliveEvery, fps, batch := t.currentIntervals()
|
||||
t.logFn("vp8tunnel: 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 = t.obf.EncodeData(data)
|
||||
idleTicks = 0
|
||||
default:
|
||||
idleTicks++
|
||||
if idleTicks < keepaliveEvery {
|
||||
continue
|
||||
}
|
||||
idleTicks = 0
|
||||
sample = t.obf.EncodeKeepalive()
|
||||
}
|
||||
if sample == nil {
|
||||
continue
|
||||
}
|
||||
if err := t.track.WriteSample(media.Sample{Data: sample, Duration: sampleInterval}); err != nil {
|
||||
t.logFn("vp8tunnel: WriteSample error: %v", err)
|
||||
continue
|
||||
}
|
||||
n := t.sentFrames.Add(1)
|
||||
if n <= 5 || n%500 == 0 {
|
||||
t.logFn("vp8tunnel: sent frame #%d size=%d", n, len(sample))
|
||||
}
|
||||
}
|
||||
}
|
||||
ticker.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 res.Keepalive || len(res.Payload) == 0 {
|
||||
return
|
||||
}
|
||||
n := t.recvFrames.Add(1)
|
||||
if 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)
|
||||
}
|
||||
dataLen := binary.BigEndian.Uint32(payload[len(vp8Interframe)+1 : len(vp8Interframe)+5])
|
||||
if dataLen == 0 || int(dataLen) > len(payload)-dataHeaderLen {
|
||||
return nil
|
||||
}
|
||||
return payload[dataHeaderLen : dataHeaderLen+int(dataLen)]
|
||||
}
|
||||
Reference in new issue
Block a user