Documentation
¶
Overview ¶
Package tunnel implements PoC #2A's framing layer: arbitrary []byte payloads ride inside what the SFU sees as VP8 video frames. One logical message == one media.Sample == one VP8 "frame" (1+ RTP packets sharing a timestamp, last packet has marker=1).
On the wire (after Pion's VP8 payload descriptor):
+--+--+--+--+--+--+--+--+--+--+--+--+--... ----+
|magic 'G' 'T'|ver |flg| msgID | ...payload (length bytes)
|0x47 0x54 |0x01| | BE uint32 | |
+--+--+--+--+--+--+--+--+--+--+--+--+--... ----+
0 1 2 3 4 5 6 7 8 ... 11+length
Index ¶
- Constants
- Variables
- func EncodeFrame(msgID uint32, flags Flags, payload []byte) []byte
- func StripVP8Descriptor(payload []byte) ([]byte, bool)
- type DecodedFrame
- type Dispatcher
- type Flags
- type FrameAssembler
- type ReceivedFrame
- type Receiver
- type Sender
- type StreamManager
- type TunnelPacketConn
- func (c *TunnelPacketConn) Close() error
- func (c *TunnelPacketConn) Deliver(payload []byte) bool
- func (c *TunnelPacketConn) LocalAddr() net.Addr
- func (c *TunnelPacketConn) ReadFrom(p []byte) (int, net.Addr, error)
- func (c *TunnelPacketConn) SetDeadline(t time.Time) error
- func (c *TunnelPacketConn) SetReadDeadline(t time.Time) error
- func (c *TunnelPacketConn) SetWriteDeadline(t time.Time) error
- func (c *TunnelPacketConn) WriteTo(p []byte, _ net.Addr) (int, error)
Constants ¶
const ( // MagicByte0 / MagicByte1 spell "GT" — they distinguish our frames from // genuine VP8 video that other (browser) participants in the same room // may publish. Receivers drop anything without this prefix silently. MagicByte0 byte = 0x47 // 'G' MagicByte1 byte = 0x54 // 'T' // Version is bumped on any wire-incompatible change to the header. Version byte = 0x01 // HeaderSize is the fixed-length header before payload bytes. HeaderSize = 12 // MaxPayloadSize caps a single frame to 10 MiB. Realistically we send // up to ~100 KB during PoC #2A T3, but the cap stops a malformed length // field from triggering huge allocations on the receive side. MaxPayloadSize = 10 * 1024 * 1024 )
const ( DefaultBatchSize = 6144 DefaultBatchInterval = 2 * time.Millisecond DefaultPacingInterval = 500 * time.Microsecond DefaultKeepaliveInterval = 40 * time.Millisecond // ~25fps when active DefaultIdleKeepaliveInterval = 1000 * time.Millisecond // 1fps when idle DefaultIdleAfter = 10 * time.Second // switch to idle after this much silence )
const VP8KeyframeHeaderLen = 10
VP8KeyframeHeaderLen is the fixed prefix length (10).
Variables ¶
var ( ErrShortFrame = errors.New("tunnel: frame shorter than header") ErrBadMagic = errors.New("tunnel: magic bytes mismatch (likely real video)") ErrBadVersion = errors.New("tunnel: unknown frame version") ErrLengthMismatch = errors.New("tunnel: declared length != actual payload size") ErrPayloadTooBig = errors.New("tunnel: declared length exceeds MaxPayloadSize") )
ErrShortFrame, ErrBadMagic, ErrBadVersion, ErrLengthMismatch are all non-fatal: receivers should drop the offending frame and keep going.
var VP8KeyframeHeader = []byte{
0x10, 0x02, 0x00,
0x9d, 0x01, 0x2a,
0x40, 0x01,
0xf0, 0x00,
}
VP8KeyframeHeader is a 10-byte fake VP8 frame header prepended to every outbound tunnel frame so the SFU's keyframe-gated forwarder treats each Sample as a key frame and forwards it. Pion's VP8Payloader doesn't peek inside the payload, and goloom's SFU only inspects the first few bytes to classify frames.
Layout (RFC 6386 §9.1):
byte 0: 0x10 — frame tag bits: key_frame=0 (LSB), version=0,
show_frame=1, first_part_size_low=0
byte 1: 0x02 — first_part_size_mid
byte 2: 0x00 — first_part_size_high
byte 3-5: 0x9d 0x01 0x2a — start code (mandatory for keyframes)
byte 6-7: 0x40 0x01 — width = 0x140 = 320
byte 8-9: 0xf0 0x00 — height = 0x0f0 = 240
Receivers MUST skip these 10 bytes (after stripping Pion's RTP payload descriptor) before parsing the tunnel header.
Functions ¶
func EncodeFrame ¶
EncodeFrame builds one wire-format frame from a payload. msgID is the sender-monotonic sequence number, flags carries protocol bits.
func StripVP8Descriptor ¶
StripVP8Descriptor removes the VP8 RTP payload descriptor (RFC 7741 §4.2) from the front of an RTP packet payload and returns the remaining VP8 payload bytes. ok=false means the input is malformed (truncated descriptor).
Descriptor layout:
byte 0: |X|R|N|S|R| PID(3) | mandatory byte 1: |I|L|T|K| RSV(4) | present iff X=1 byte 2..: PictureID present iff I=1; 1 byte (M=0) or 2 bytes (M=1, MSB has M flag set) +1: TL0PICIDX present iff L=1 +1: TID/Y/KEYIDX present iff T=1 OR K=1 (single byte combines both)
We don't validate the inner VP8 payload (Pion's Sample Builder would, but we never feed our payload to a VP8 decoder — the SFU forwards bytes verbatim). All we care about is computing the correct prefix length to strip so the caller sees pure VP8 video bytes (which in our case are our tunnel frame bytes).
Types ¶
type DecodedFrame ¶
type DecodedFrame struct {
MsgID uint32
Flags Flags
Payload []byte // alias into the input buffer; copy if you need to outlive it
}
DecodedFrame is what DecodeFrame returns on success.
func DecodeFrame ¶
func DecodeFrame(buf []byte) (DecodedFrame, error)
DecodeFrame validates a complete frame and returns the parsed view. The returned Payload aliases the input slice — callers that buffer it must copy.
type Dispatcher ¶
type Dispatcher struct {
KCPConn *TunnelPacketConn
Handshake chan<- ReceivedFrame
Legacy chan<- ReceivedFrame // ping/pong/test frames
DroppedKCP uint64
DroppedOther uint64
}
Dispatcher reads from a merged ReceivedFrame channel and routes frames to the appropriate consumer based on flags:
- FlagKCP → TunnelPacketConn.Deliver (KCP transport datagrams)
- FlagHandshake/FlagHandshakeAck → handshake channel
- FlagPing/FlagPong → legacy test channel
Run blocks until ctx is done or the input channel closes.
func (*Dispatcher) Run ¶
func (d *Dispatcher) Run(ctx context.Context, in <-chan ReceivedFrame, lg *log.Logger)
type Flags ¶
type Flags uint8
Flags occupies one byte. Multiple flags can be combined.
const ( FlagTest Flags = 1 << 0 // test-phase traffic (vs WG in future) FlagHandshake Flags = 1 << 1 // HELLO frame, payload = our participantId FlagHandshakeAck Flags = 1 << 2 // HELLO_ACK frame, payload = our participantId FlagPing Flags = 1 << 3 // initiator → echoer; payload[:4]=ping msgID, then data FlagPong Flags = 1 << 4 // echoer → initiator; payload echoed verbatim FlagKCP Flags = 1 << 5 // KCP reliable transport datagram )
type FrameAssembler ¶
type FrameAssembler struct {
// PartialDrops counts how many times we threw away a partial frame
// because a new timestamp arrived before the marker. Useful for telemetry.
PartialDrops uint64
// contains filtered or unexported fields
}
FrameAssembler reassembles one logical frame from the stream of per-RTP-packet payloads that share a single RTP timestamp. The last RTP packet of a frame has its marker bit set; that's our signal to flush.
Behaviour summary:
- First call sets currentTS and arms.
- Subsequent calls with the same timestamp append.
- A different timestamp before marker means the previous frame was lost mid-flight; we drop the partial buffer and start fresh on the new TS.
- A call with marker=true returns the concatenated payload and disarms.
Not safe for concurrent use; expected to be called from a single per-track read loop.
func (*FrameAssembler) Add ¶
Add ingests one RTP packet's stripped payload. Returns (frame, true) when a complete frame is ready, otherwise (nil, false).
The caller must pass an already-VP8-descriptor-stripped payload slice. The slice is copied internally because Pion reuses the underlying buffer across ReadRTP calls.
func (*FrameAssembler) Reset ¶
func (a *FrameAssembler) Reset()
Reset clears any partial state. Call when the underlying RTP stream resets (e.g. SSRC change or after teardown).
type ReceivedFrame ¶
type Receiver ¶
type Receiver struct {
RTPPackets atomic.Uint64
StripErrs atomic.Uint64
BadMagic atomic.Uint64
DecodeErrs atomic.Uint64
FramesPushed atomic.Uint64
HeaderTooShort atomic.Uint64
HeaderBadStart atomic.Uint64
// contains filtered or unexported fields
}
func NewReceiver ¶
func (*Receiver) Frames ¶
func (r *Receiver) Frames() <-chan ReceivedFrame
type Sender ¶
type Sender struct {
FrameDuration time.Duration
VP8Prefix []byte
VP8Wrap bool
BatchSize int
BatchInterval time.Duration
PacingInterval time.Duration
KeepaliveInterval time.Duration
// IdleKeepaliveInterval is the keepalive cadence used when no real
// tunnel data has been sent for IdleAfter. Defaults to ~1fps —
// enough to keep the SFU's track-active heuristics happy while
// dropping our battery footprint by ~25× compared to the active
// 25fps cadence. Set to 0 to disable idle-mode entirely.
IdleKeepaliveInterval time.Duration
IdleAfter time.Duration
TxSamples atomic.Uint64
TxBytes atomic.Uint64
TxBatches atomic.Uint64
// contains filtered or unexported fields
}
Sender turns Send([]byte) calls into VP8-shaped media samples.
Three throughput optimizations over a naive one-Send-per-WriteSample:
Batching: concatenate up to BatchSize bytes (or up to BatchInterval time) of frames into a single VP8 sample. Cuts per-RTP-packet overhead and gets us under the SFU's per-packet rate cap.
Pacing: enforce a minimum gap (PacingInterval) between two WriteSample calls so REMB/TWCC doesn't throttle us.
Keepalive: when the batch is empty for KeepaliveInterval, send a real VP8 interframe to keep the SFU's track-active timers happy (without it the SFU eventually stops forwarding the slot).
Tuning is informed by the call-gate measurements: pacing 500µs + batching 6KB/2ms got their tunnel from 6 Mbit/s to ~50 Mbit/s sustained, which appears to be Telemost's per-track bandwidth cap.
func NewSender ¶
func NewSender(track *webrtc.TrackLocalStaticSample) *Sender
func (*Sender) Close ¶
func (s *Sender) Close()
Close stops the background goroutines, flushing whatever is buffered. Idempotent.
func (*Sender) PeekNextID ¶
type StreamManager ¶
type StreamManager struct {
PacketConn *TunnelPacketConn
KCPConn net.Conn // the single KCP session (as net.Conn)
KCPSession *kcp.UDPSession
Mux *yamux.Session
Logger *log.Logger
IsServer bool
}
StreamManager holds the full reliable-stream stack:
TunnelPacketConn → KCP (reliable, ordered bytes) → yamux (multiplexed streams)
The initiator calls Listen/Accept; the echoer calls Dial/Open.
func NewStreamManager ¶
func NewStreamManager(pc *TunnelPacketConn, isServer bool, lg *log.Logger) (*StreamManager, error)
NewStreamManager creates the full KCP+yamux stack over the given TunnelPacketConn. isServer should be true for the initiator (screen-sharer) who accepts yamux streams, false for the echoer who opens them.
func (*StreamManager) AcceptStream ¶
func (sm *StreamManager) AcceptStream() (net.Conn, error)
AcceptStream blocks until a peer opens a new yamux stream. Server-side only.
func (*StreamManager) Close ¶
func (sm *StreamManager) Close() error
Close tears down yamux, KCP, and the underlying PacketConn.
func (*StreamManager) OpenStream ¶
func (sm *StreamManager) OpenStream() (net.Conn, error)
OpenStream opens a new yamux stream to the peer. Client-side.
type TunnelPacketConn ¶
type TunnelPacketConn struct {
// contains filtered or unexported fields
}
TunnelPacketConn adapts a Sender + incoming frame channel into a net.PacketConn that KCP can read/write through. KCP sees this as a UDP-like socket; under the hood every WriteTo becomes a tunnel frame with FlagKCP, and every ReadFrom pulls from the dispatcher's channel.
func NewPacketConn ¶
func NewPacketConn(sender *Sender, bufSize int) *TunnelPacketConn
NewPacketConn returns a PacketConn backed by sender for writes and in for reads. The caller must feed KCP-flagged frame payloads into in (see Dispatcher). bufSize controls backpressure on the read side.
func (*TunnelPacketConn) Close ¶
func (c *TunnelPacketConn) Close() error
func (*TunnelPacketConn) Deliver ¶
func (c *TunnelPacketConn) Deliver(payload []byte) bool
Deliver pushes a raw KCP payload (already stripped of the tunnel header) into the read buffer. Called by the dispatcher. Returns false if closed.
func (*TunnelPacketConn) LocalAddr ¶
func (c *TunnelPacketConn) LocalAddr() net.Addr
func (*TunnelPacketConn) ReadFrom ¶
ReadFrom blocks until a KCP datagram arrives or the deadline expires. The addr is a fixed dummy — KCP doesn't use it for anything meaningful since we have exactly one peer per PacketConn.
func (*TunnelPacketConn) SetDeadline ¶
func (c *TunnelPacketConn) SetDeadline(t time.Time) error
func (*TunnelPacketConn) SetReadDeadline ¶
func (c *TunnelPacketConn) SetReadDeadline(t time.Time) error
func (*TunnelPacketConn) SetWriteDeadline ¶
func (c *TunnelPacketConn) SetWriteDeadline(t time.Time) error