v0.1.5
This commit is contained in:
1 parent
61ef2aa2bd
commit
e8da07179a
32 files changed
+3633
-161
No files matched your search
@@ -14,6 +14,23 @@ require (
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/schema v1.4.1 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/pion/datachannel v1.6.0 // indirect
|
||||
github.com/pion/dtls/v3 v3.1.2 // indirect
|
||||
github.com/pion/ice/v4 v4.2.1 // indirect
|
||||
github.com/pion/interceptor v0.1.44 // indirect
|
||||
github.com/pion/logging v0.2.4 // indirect
|
||||
github.com/pion/mdns/v2 v2.1.0 // indirect
|
||||
github.com/pion/randutil v0.1.0 // indirect
|
||||
github.com/pion/rtcp v1.2.16 // indirect
|
||||
github.com/pion/rtp v1.10.1 // indirect
|
||||
github.com/pion/sctp v1.9.2 // indirect
|
||||
github.com/pion/sdp/v3 v3.0.18 // indirect
|
||||
github.com/pion/srtp/v3 v3.0.10 // indirect
|
||||
github.com/pion/stun/v3 v3.1.1 // indirect
|
||||
github.com/pion/transport/v4 v4.0.1 // indirect
|
||||
github.com/pion/turn/v4 v4.1.4 // indirect
|
||||
github.com/pion/webrtc/v4 v4.2.9 // indirect
|
||||
github.com/wlynxg/anet v0.0.5 // indirect
|
||||
github.com/xjasonlyu/tun2socks/v2 v2.6.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.uber.org/automaxprocs v1.6.0 // indirect
|
||||
@@ -32,3 +49,5 @@ require (
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
gvisor.dev/gvisor v0.0.0-20250523182742-eede7a881b20 // indirect
|
||||
)
|
||||
|
||||
|
||||
@@ -20,6 +20,40 @@ github.com/gorilla/schema v1.4.1 h1:jUg5hUjCSDZpNGLuXQOgIWGdlgrIdYvgQ0wZtdK1M3E=
|
||||
github.com/gorilla/schema v1.4.1/go.mod h1:Dg5SSm5PV60mhF2NFaTV1xuYYj8tV8NOPRo4FggUMnM=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/pion/datachannel v1.6.0 h1:XecBlj+cvsxhAMZWFfFcPyUaDZtd7IJvrXqlXD/53i0=
|
||||
github.com/pion/datachannel v1.6.0/go.mod h1:ur+wzYF8mWdC+Mkis5Thosk+u/VOL287apDNEbFpsIk=
|
||||
github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc=
|
||||
github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo=
|
||||
github.com/pion/ice/v4 v4.2.1 h1:XPRYXaLiFq3LFDG7a7bMrmr3mFr27G/gtXN3v/TVfxY=
|
||||
github.com/pion/ice/v4 v4.2.1/go.mod h1:2quLV1S5v1tAx3VvAJaH//KGitRXvo4RKlX6D3tnN+c=
|
||||
github.com/pion/interceptor v0.1.44 h1:sNlZwM8dWXU9JQAkJh8xrarC0Etn8Oolcniukmuy0/I=
|
||||
github.com/pion/interceptor v0.1.44/go.mod h1:4atVlBkcgXuUP+ykQF0qOCGU2j7pQzX2ofvPRFsY5RY=
|
||||
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
|
||||
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
|
||||
github.com/pion/mdns/v2 v2.1.0 h1:3IJ9+Xio6tWYjhN6WwuY142P/1jA0D5ERaIqawg/fOY=
|
||||
github.com/pion/mdns/v2 v2.1.0/go.mod h1:pcez23GdynwcfRU1977qKU0mDxSeucttSHbCSfFOd9A=
|
||||
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
|
||||
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
|
||||
github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo=
|
||||
github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo=
|
||||
github.com/pion/rtp v1.10.1 h1:xP1prZcCTUuhO2c83XtxyOHJteISg6o8iPsE2acaMtA=
|
||||
github.com/pion/rtp v1.10.1/go.mod h1:rF5nS1GqbR7H/TCpKwylzeq6yDM+MM6k+On5EgeThEM=
|
||||
github.com/pion/sctp v1.9.2 h1:HxsOzEV9pWoeggv7T5kewVkstFNcGvhMPx0GvUOUQXo=
|
||||
github.com/pion/sctp v1.9.2/go.mod h1:OTOlsQ5EDQ6mQ0z4MUGXt2CgQmKyafBEXhUVqLRB6G8=
|
||||
github.com/pion/sdp/v3 v3.0.18 h1:l0bAXazKHpepazVdp+tPYnrsy9dfh7ZbT8DxesH5ZnI=
|
||||
github.com/pion/sdp/v3 v3.0.18/go.mod h1:ZREGo6A9ZygQ9XkqAj5xYCQtQpif0i6Pa81HOiAdqQ8=
|
||||
github.com/pion/srtp/v3 v3.0.10 h1:tFirkpBb3XccP5VEXLi50GqXhv5SKPxqrdlhDCJlZrQ=
|
||||
github.com/pion/srtp/v3 v3.0.10/go.mod h1:3mOTIB0cq9qlbn59V4ozvv9ClW/BSEbRp4cY0VtaR7M=
|
||||
github.com/pion/stun/v3 v3.1.1 h1:CkQxveJ4xGQjulGSROXbXq94TAWu8gIX2dT+ePhUkqw=
|
||||
github.com/pion/stun/v3 v3.1.1/go.mod h1:qC1DfmcCTQjl9PBaMa5wSn3x9IPmKxSdcCsxBcDBndM=
|
||||
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
|
||||
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
|
||||
github.com/pion/turn/v4 v4.1.4 h1:EU11yMXKIsK43FhcUnjLlrhE4nboHZq+TXBIi3QpcxQ=
|
||||
github.com/pion/turn/v4 v4.1.4/go.mod h1:ES1DXVFKnOhuDkqn9hn5VJlSWmZPaRJLyBXoOeO/BmQ=
|
||||
github.com/pion/webrtc/v4 v4.2.9 h1:DZIh1HAhPIL3RvwEDFsmL5hfPSLEpxsQk9/Jir2vkJE=
|
||||
github.com/pion/webrtc/v4 v4.2.9/go.mod h1:9EmLZve0H76eTzf8v2FmchZ6tcBXtDgpfTEu+drW6SY=
|
||||
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
|
||||
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
||||
github.com/xjasonlyu/tun2socks/v2 v2.6.0 h1:gI9saJT3XgH4e6v9jBuHRLwK7l3aN9YFWec/SsDTDx4=
|
||||
github.com/xjasonlyu/tun2socks/v2 v2.6.0/go.mod h1:35AwqxIxnMkfBfT0UJ1Lku7PZm2ZiZJ8sxHyp0gt1yw=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
|
||||
+48
-1
@@ -4,9 +4,11 @@ import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"whitelist-bypass/relay/mobile"
|
||||
"whitelist-bypass/relay/pion"
|
||||
)
|
||||
|
||||
type stdLogger struct{}
|
||||
@@ -19,6 +21,7 @@ func main() {
|
||||
mode := flag.String("mode", "", "joiner or creator")
|
||||
wsPort := flag.Int("ws-port", 9000, "WebSocket port for browser connection")
|
||||
socksPort := flag.Int("socks-port", 1080, "SOCKS5 proxy port (joiner mode only)")
|
||||
flag.String("local-ip", "", "local IP address (unused, passed via hook)")
|
||||
flag.Parse()
|
||||
|
||||
if *mode == "" {
|
||||
@@ -33,8 +36,52 @@ func main() {
|
||||
log.Fatal(mobile.StartJoiner(*wsPort, *socksPort, cb))
|
||||
case "creator":
|
||||
log.Fatal(mobile.StartCreator(*wsPort, cb))
|
||||
case "vk-video-joiner":
|
||||
c := pion.NewVKClient(log.Printf)
|
||||
c.OnConnected = func(tunnel *pion.VP8DataTunnel) {
|
||||
rb := pion.NewRelayBridge(tunnel, "joiner", log.Printf)
|
||||
rb.MarkReady()
|
||||
go rb.ListenSOCKS(fmt.Sprintf("127.0.0.1:%d", *socksPort))
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/signaling", c.HandleSignaling)
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", *wsPort)
|
||||
log.Printf("vk-video-joiner: signaling on %s, SOCKS5 on :%d", addr, *socksPort)
|
||||
log.Fatal(http.ListenAndServe(addr, mux))
|
||||
case "vk-video-creator":
|
||||
c := pion.NewVKClient(log.Printf)
|
||||
c.OnConnected = func(tunnel *pion.VP8DataTunnel) {
|
||||
pion.NewRelayBridge(tunnel, "creator", log.Printf)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/signaling", c.HandleSignaling)
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", *wsPort)
|
||||
log.Printf("vk-video-creator: signaling on %s", addr)
|
||||
log.Fatal(http.ListenAndServe(addr, mux))
|
||||
case "telemost-video-joiner":
|
||||
c := pion.NewTelemostClient(log.Printf)
|
||||
c.OnConnected = func(tunnel *pion.VP8DataTunnel) {
|
||||
rb := pion.NewRelayBridge(tunnel, "joiner", log.Printf)
|
||||
rb.MarkReady()
|
||||
go rb.ListenSOCKS(fmt.Sprintf("127.0.0.1:%d", *socksPort))
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/signaling", c.HandleSignaling)
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", *wsPort)
|
||||
log.Printf("telemost-video-joiner: signaling on %s, SOCKS5 on :%d", addr, *socksPort)
|
||||
log.Fatal(http.ListenAndServe(addr, mux))
|
||||
case "telemost-video-creator":
|
||||
c := pion.NewTelemostClient(log.Printf)
|
||||
c.OnConnected = func(tunnel *pion.VP8DataTunnel) {
|
||||
pion.NewRelayBridge(tunnel, "creator", log.Printf)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/signaling", c.HandleSignaling)
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", *wsPort)
|
||||
log.Printf("telemost-video-creator: signaling on %s", addr)
|
||||
log.Fatal(http.ListenAndServe(addr, mux))
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "Unknown mode: %s (use joiner or creator)\n", *mode)
|
||||
fmt.Fprintf(os.Stderr, "Unknown mode: %s\n", *mode)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package pion
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"github.com/pion/transport/v4"
|
||||
)
|
||||
|
||||
// AndroidNet implements transport.Net without netlink interface enumeration
|
||||
type AndroidNet struct {
|
||||
LocalIP string
|
||||
}
|
||||
|
||||
func (n *AndroidNet) ListenPacket(network string, address string) (net.PacketConn, error) {
|
||||
return net.ListenPacket(network, address)
|
||||
}
|
||||
|
||||
func (n *AndroidNet) ListenUDP(network string, locAddr *net.UDPAddr) (transport.UDPConn, error) {
|
||||
return net.ListenUDP(network, locAddr)
|
||||
}
|
||||
|
||||
type wrappedTCPListener struct {
|
||||
*net.TCPListener
|
||||
}
|
||||
|
||||
func (w *wrappedTCPListener) AcceptTCP() (transport.TCPConn, error) {
|
||||
return w.TCPListener.AcceptTCP()
|
||||
}
|
||||
|
||||
func (n *AndroidNet) ListenTCP(network string, laddr *net.TCPAddr) (transport.TCPListener, error) {
|
||||
l, err := net.ListenTCP(network, laddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &wrappedTCPListener{l}, nil
|
||||
}
|
||||
|
||||
func (n *AndroidNet) Dial(network, address string) (net.Conn, error) {
|
||||
return net.Dial(network, address)
|
||||
}
|
||||
|
||||
func (n *AndroidNet) DialUDP(network string, laddr, raddr *net.UDPAddr) (transport.UDPConn, error) {
|
||||
return net.DialUDP(network, laddr, raddr)
|
||||
}
|
||||
|
||||
func (n *AndroidNet) DialTCP(network string, laddr, raddr *net.TCPAddr) (transport.TCPConn, error) {
|
||||
return net.DialTCP(network, laddr, raddr)
|
||||
}
|
||||
|
||||
func (n *AndroidNet) ResolveIPAddr(network, address string) (*net.IPAddr, error) {
|
||||
return net.ResolveIPAddr(network, address)
|
||||
}
|
||||
|
||||
func (n *AndroidNet) ResolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
||||
return net.ResolveUDPAddr(network, address)
|
||||
}
|
||||
|
||||
func (n *AndroidNet) ResolveTCPAddr(network, address string) (*net.TCPAddr, error) {
|
||||
return net.ResolveTCPAddr(network, address)
|
||||
}
|
||||
|
||||
func (n *AndroidNet) Interfaces() ([]*transport.Interface, error) {
|
||||
ifaces, err := net.Interfaces()
|
||||
if err == nil && len(ifaces) > 0 {
|
||||
result := make([]*transport.Interface, len(ifaces))
|
||||
for i := range ifaces {
|
||||
ifc := transport.NewInterface(ifaces[i])
|
||||
addrs, addrErr := ifaces[i].Addrs()
|
||||
if addrErr == nil {
|
||||
for _, addr := range addrs {
|
||||
ifc.AddAddress(addr)
|
||||
}
|
||||
}
|
||||
result[i] = ifc
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
return n.scanSysNet()
|
||||
}
|
||||
|
||||
func (n *AndroidNet) scanSysNet() ([]*transport.Interface, error) {
|
||||
if n.LocalIP == "" {
|
||||
return []*transport.Interface{
|
||||
{Interface: net.Interface{Index: 1, MTU: 1500, Name: "lo", Flags: net.FlagUp | net.FlagLoopback}},
|
||||
}, nil
|
||||
}
|
||||
ip := net.ParseIP(n.LocalIP)
|
||||
if ip == nil {
|
||||
return []*transport.Interface{
|
||||
{Interface: net.Interface{Index: 1, MTU: 1500, Name: "lo", Flags: net.FlagUp | net.FlagLoopback}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
iface := net.Interface{
|
||||
Index: 1,
|
||||
MTU: 1500,
|
||||
Name: "rmnet0",
|
||||
Flags: net.FlagUp | net.FlagMulticast,
|
||||
HardwareAddr: net.HardwareAddr{0, 0, 0, 0, 0, 0},
|
||||
}
|
||||
|
||||
ones := 32
|
||||
if ip.To4() == nil {
|
||||
ones = 128
|
||||
}
|
||||
ti := transport.NewInterface(iface)
|
||||
ti.AddAddress(&net.IPNet{IP: ip, Mask: net.CIDRMask(ones, ones)})
|
||||
|
||||
return []*transport.Interface{ti}, nil
|
||||
}
|
||||
|
||||
func (n *AndroidNet) InterfaceByIndex(index int) (*transport.Interface, error) {
|
||||
ifaces, err := n.Interfaces()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, iface := range ifaces {
|
||||
if iface.Index == index {
|
||||
return iface, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("interface index %d not found", index)
|
||||
}
|
||||
|
||||
func (n *AndroidNet) InterfaceByName(name string) (*transport.Interface, error) {
|
||||
ifaces, err := n.Interfaces()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, iface := range ifaces {
|
||||
if iface.Name == name {
|
||||
return iface, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("interface %s not found", name)
|
||||
}
|
||||
|
||||
func (n *AndroidNet) CreateDialer(dialer *net.Dialer) transport.Dialer {
|
||||
return dialer
|
||||
}
|
||||
|
||||
func (n *AndroidNet) CreateListenConfig(lc *net.ListenConfig) transport.ListenConfig {
|
||||
return lc
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package pion
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
type SignalingMessage struct {
|
||||
Type string `json:"type"`
|
||||
Data json.RawMessage `json:"data,omitempty"`
|
||||
ID int `json:"id,omitempty"`
|
||||
Role string `json:"role,omitempty"`
|
||||
}
|
||||
|
||||
type ICEServerConfig struct {
|
||||
URLs []string `json:"urls"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Credential string `json:"credential,omitempty"`
|
||||
}
|
||||
|
||||
type SDPMessage struct {
|
||||
Type string `json:"type"`
|
||||
SDP string `json:"sdp"`
|
||||
}
|
||||
|
||||
type ICECandidateMessage struct {
|
||||
Candidate string `json:"candidate"`
|
||||
SDPMid string `json:"sdpMid"`
|
||||
SDPMLineIndex uint16 `json:"sdpMLineIndex"`
|
||||
}
|
||||
|
||||
var WsUpgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
}
|
||||
|
||||
func ParseICEServers(data json.RawMessage) ([]webrtc.ICEServer, error) {
|
||||
var servers []ICEServerConfig
|
||||
if err := json.Unmarshal(data, &servers); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
iceServers := make([]webrtc.ICEServer, len(servers))
|
||||
for i, s := range servers {
|
||||
iceServers[i] = webrtc.ICEServer{
|
||||
URLs: s.URLs, Username: s.Username, Credential: s.Credential,
|
||||
}
|
||||
}
|
||||
return iceServers, nil
|
||||
}
|
||||
|
||||
func NewPionAPI(localIP string) *webrtc.API {
|
||||
se := webrtc.SettingEngine{}
|
||||
se.SetNet(&AndroidNet{LocalIP: localIP})
|
||||
return webrtc.NewAPI(webrtc.WithSettingEngine(se))
|
||||
}
|
||||
|
||||
type WSHelper struct {
|
||||
wsConn *websocket.Conn
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (h *WSHelper) SetConn(ws *websocket.Conn) {
|
||||
h.mu.Lock()
|
||||
h.wsConn = ws
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
func (h *WSHelper) SendToHook(msgType string, data any) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.wsConn == nil {
|
||||
return
|
||||
}
|
||||
dataBytes, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
msg := SignalingMessage{Type: msgType, Data: dataBytes}
|
||||
msgBytes, _ := json.Marshal(msg)
|
||||
h.wsConn.WriteMessage(websocket.TextMessage, msgBytes)
|
||||
}
|
||||
|
||||
func (h *WSHelper) SendToHookWithRole(msgType string, data any, role string) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.wsConn == nil {
|
||||
return
|
||||
}
|
||||
dataBytes, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
msg := SignalingMessage{Type: msgType, Data: dataBytes, Role: role}
|
||||
msgBytes, _ := json.Marshal(msg)
|
||||
h.wsConn.WriteMessage(websocket.TextMessage, msgBytes)
|
||||
}
|
||||
|
||||
func (h *WSHelper) SendResponse(id int, data any) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.wsConn == nil {
|
||||
return
|
||||
}
|
||||
dataBytes, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
msg := SignalingMessage{Type: "response", Data: dataBytes, ID: id}
|
||||
msgBytes, _ := json.Marshal(msg)
|
||||
h.wsConn.WriteMessage(websocket.TextMessage, msgBytes)
|
||||
}
|
||||
|
||||
func (h *WSHelper) ReadMessages(handler func([]byte), onDisconnect func()) {
|
||||
for {
|
||||
_, msg, err := h.wsConn.ReadMessage()
|
||||
if err != nil {
|
||||
onDisconnect()
|
||||
return
|
||||
}
|
||||
handler(msg)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
package pion
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
msgConnect byte = 0x01
|
||||
msgConnectOK byte = 0x02
|
||||
msgConnectErr byte = 0x03
|
||||
msgData byte = 0x04
|
||||
msgClose byte = 0x05
|
||||
msgUDP byte = 0x06
|
||||
msgUDPReply byte = 0x07
|
||||
)
|
||||
|
||||
func encodeFrame(connID uint32, msgType byte, payload []byte) []byte {
|
||||
buf := make([]byte, 4+5+len(payload))
|
||||
binary.BigEndian.PutUint32(buf[0:4], uint32(5+len(payload)))
|
||||
binary.BigEndian.PutUint32(buf[4:8], connID)
|
||||
buf[8] = msgType
|
||||
copy(buf[9:], payload)
|
||||
return buf
|
||||
}
|
||||
|
||||
func decodeFrames(data []byte, cb func(connID uint32, msgType byte, payload []byte)) {
|
||||
for len(data) >= 4 {
|
||||
frameLen := int(binary.BigEndian.Uint32(data[0:4]))
|
||||
if frameLen < 5 || 4+frameLen > len(data) {
|
||||
return
|
||||
}
|
||||
connID := binary.BigEndian.Uint32(data[4:8])
|
||||
msgType := data[8]
|
||||
payload := data[9 : 4+frameLen]
|
||||
cb(connID, msgType, payload)
|
||||
data = data[4+frameLen:]
|
||||
}
|
||||
}
|
||||
|
||||
type udpClient struct {
|
||||
udpConn *net.UDPConn
|
||||
clientAddr *net.UDPAddr
|
||||
socksHdr []byte
|
||||
}
|
||||
|
||||
type RelayBridge struct {
|
||||
tunnel *VP8DataTunnel
|
||||
conns sync.Map
|
||||
udpClients sync.Map
|
||||
nextID atomic.Uint32
|
||||
logFn func(string, ...any)
|
||||
mode string
|
||||
ready chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func NewRelayBridge(tunnel *VP8DataTunnel, mode string, logFn func(string, ...any)) *RelayBridge {
|
||||
rb := &RelayBridge{
|
||||
tunnel: tunnel,
|
||||
logFn: logFn,
|
||||
mode: mode,
|
||||
ready: make(chan struct{}),
|
||||
}
|
||||
tunnel.onData = rb.handleTunnelData
|
||||
tunnel.onClose = rb.closeAll
|
||||
return rb
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) closeAll() {
|
||||
rb.logFn("relay: closing all connections")
|
||||
rb.conns.Range(func(key, value any) bool {
|
||||
switch v := value.(type) {
|
||||
case net.Conn:
|
||||
v.Close()
|
||||
case *socksConn:
|
||||
v.conn.Close()
|
||||
}
|
||||
rb.conns.Delete(key)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) MarkReady() {
|
||||
rb.once.Do(func() { close(rb.ready) })
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) send(connID uint32, msgType byte, payload []byte) {
|
||||
frame := encodeFrame(connID, msgType, payload)
|
||||
rb.tunnel.SendData(frame)
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleTunnelData(data []byte) {
|
||||
decodeFrames(data, func(connID uint32, msgType byte, payload []byte) {
|
||||
switch rb.mode {
|
||||
case "joiner":
|
||||
rb.handleJoinerMessage(connID, msgType, payload)
|
||||
case "creator":
|
||||
rb.handleCreatorMessage(connID, msgType, payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Joiner: receives ConnectOK/Data/Close from creator
|
||||
func (rb *RelayBridge) handleJoinerMessage(connID uint32, msgType byte, payload []byte) {
|
||||
if msgType == msgUDPReply {
|
||||
uval, ok := rb.udpClients.Load(connID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
uc := uval.(*udpClient)
|
||||
reply := make([]byte, len(uc.socksHdr)+len(payload))
|
||||
copy(reply, uc.socksHdr)
|
||||
copy(reply[len(uc.socksHdr):], payload)
|
||||
uc.udpConn.WriteToUDP(reply, uc.clientAddr)
|
||||
rb.udpClients.Delete(connID)
|
||||
return
|
||||
}
|
||||
val, ok := rb.conns.Load(connID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
sc := val.(*socksConn)
|
||||
switch msgType {
|
||||
case msgConnectOK:
|
||||
sc.rdy <- nil
|
||||
case msgConnectErr:
|
||||
sc.rdy <- fmt.Errorf("%s", payload)
|
||||
case msgData:
|
||||
sc.conn.Write(payload)
|
||||
case msgClose:
|
||||
sc.conn.Close()
|
||||
rb.conns.Delete(connID)
|
||||
}
|
||||
}
|
||||
|
||||
// Creator: receives Connect/Data/Close from joiner
|
||||
func (rb *RelayBridge) handleCreatorMessage(connID uint32, msgType byte, payload []byte) {
|
||||
switch msgType {
|
||||
case msgConnect:
|
||||
go rb.connectTCP(connID, string(payload))
|
||||
case msgUDP:
|
||||
go rb.handleUDP(connID, payload)
|
||||
case msgData:
|
||||
val, ok := rb.conns.Load(connID)
|
||||
if ok {
|
||||
val.(net.Conn).Write(payload)
|
||||
}
|
||||
case msgClose:
|
||||
val, ok := rb.conns.LoadAndDelete(connID)
|
||||
if ok {
|
||||
val.(net.Conn).Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleUDP(connID uint32, payload []byte) {
|
||||
if len(payload) < 2 {
|
||||
return
|
||||
}
|
||||
addrLen := int(payload[0])
|
||||
if len(payload) < 1+addrLen {
|
||||
return
|
||||
}
|
||||
addr := string(payload[1 : 1+addrLen])
|
||||
data := payload[1+addrLen:]
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
conn, err := net.DialUDP("udp", nil, udpAddr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
conn.Write(data)
|
||||
buf := make([]byte, 4096)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rb.send(connID, msgUDPReply, buf[:n])
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) connectTCP(connID uint32, addr string) {
|
||||
rb.logFn("relay: CONNECT %d -> %s", connID, addr)
|
||||
conn, err := net.DialTimeout("tcp", addr, 10e9)
|
||||
if err != nil {
|
||||
rb.logFn("relay: CONNECT %d failed: %v", connID, err)
|
||||
rb.send(connID, msgConnectErr, []byte(err.Error()))
|
||||
return
|
||||
}
|
||||
rb.conns.Store(connID, conn)
|
||||
rb.send(connID, msgConnectOK, nil)
|
||||
rb.logFn("relay: CONNECTED %d -> %s", connID, addr)
|
||||
|
||||
buf := make([]byte, 900)
|
||||
for {
|
||||
n, err := conn.Read(buf)
|
||||
if n > 0 {
|
||||
rb.send(connID, msgData, buf[:n])
|
||||
}
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
rb.logFn("relay: conn %d read error: %v", connID, err)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
rb.send(connID, msgClose, nil)
|
||||
rb.conns.Delete(connID)
|
||||
}
|
||||
|
||||
// SOCKS5 proxy for joiner mode
|
||||
type socksConn struct {
|
||||
id uint32
|
||||
conn net.Conn
|
||||
rb *RelayBridge
|
||||
rdy chan error
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) ListenSOCKS(addr string) error {
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rb.logFn("relay: SOCKS5 on %s", addr)
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
rb.logFn("relay: accept error: %v", err)
|
||||
continue
|
||||
}
|
||||
go rb.handleSOCKS(conn)
|
||||
}
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleSOCKS(conn net.Conn) {
|
||||
<-rb.ready
|
||||
buf := make([]byte, 258)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil || n < 2 || buf[0] != 0x05 {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
conn.Write([]byte{0x05, 0x00})
|
||||
n, err = conn.Read(buf)
|
||||
if err != nil || n < 7 || buf[0] != 0x05 {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
cmd := buf[1]
|
||||
if cmd == 0x03 {
|
||||
rb.handleUDPAssociate(conn)
|
||||
return
|
||||
}
|
||||
if cmd != 0x01 {
|
||||
conn.Write([]byte{0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
var host string
|
||||
switch buf[3] {
|
||||
case 0x01:
|
||||
if n < 10 {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
host = fmt.Sprintf("%d.%d.%d.%d:%d", buf[4], buf[5], buf[6], buf[7],
|
||||
binary.BigEndian.Uint16(buf[8:10]))
|
||||
case 0x03:
|
||||
dlen := int(buf[4])
|
||||
if n < 5+dlen+2 {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
host = fmt.Sprintf("%s:%d", string(buf[5:5+dlen]),
|
||||
binary.BigEndian.Uint16(buf[5+dlen:7+dlen]))
|
||||
case 0x04:
|
||||
if n < 22 {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
ip := net.IP(buf[4:20])
|
||||
host = fmt.Sprintf("[%s]:%d", ip.String(),
|
||||
binary.BigEndian.Uint16(buf[20:22]))
|
||||
default:
|
||||
conn.Write([]byte{0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
id := rb.nextID.Add(1)
|
||||
sc := &socksConn{id: id, conn: conn, rb: rb, rdy: make(chan error, 1)}
|
||||
rb.conns.Store(id, sc)
|
||||
rb.logFn("relay: SOCKS CONNECT %d -> %s", id, host)
|
||||
rb.send(id, msgConnect, []byte(host))
|
||||
|
||||
if err := <-sc.rdy; err != nil {
|
||||
rb.logFn("relay: SOCKS CONNECT %d failed: %v", id, err)
|
||||
conn.Write([]byte{0x05, 0x05, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
conn.Close()
|
||||
rb.conns.Delete(id)
|
||||
return
|
||||
}
|
||||
conn.Write([]byte{0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
rb.logFn("relay: SOCKS CONNECTED %d -> %s", id, host)
|
||||
|
||||
go func() {
|
||||
readBuf := make([]byte, 900)
|
||||
for {
|
||||
rn, rerr := conn.Read(readBuf)
|
||||
if rn > 0 {
|
||||
rb.send(id, msgData, readBuf[:rn])
|
||||
}
|
||||
if rerr != nil {
|
||||
rb.send(id, msgClose, nil)
|
||||
rb.conns.Delete(id)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleUDPAssociate(tcpConn net.Conn) {
|
||||
udpAddr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:0")
|
||||
udpConn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
tcpConn.Write([]byte{0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
tcpConn.Close()
|
||||
return
|
||||
}
|
||||
localAddr := udpConn.LocalAddr().(*net.UDPAddr)
|
||||
reply := []byte{0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0}
|
||||
binary.BigEndian.PutUint16(reply[8:10], uint16(localAddr.Port))
|
||||
tcpConn.Write(reply)
|
||||
|
||||
go func() {
|
||||
buf := make([]byte, 1)
|
||||
tcpConn.Read(buf)
|
||||
udpConn.Close()
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer udpConn.Close()
|
||||
defer tcpConn.Close()
|
||||
buf := make([]byte, 4096)
|
||||
for {
|
||||
n, addr, err := udpConn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if n < 10 {
|
||||
continue
|
||||
}
|
||||
frag := buf[2]
|
||||
if frag != 0 {
|
||||
continue
|
||||
}
|
||||
atyp := buf[3]
|
||||
var dstAddr string
|
||||
var headerLen int
|
||||
switch atyp {
|
||||
case 0x01:
|
||||
if n < 10 {
|
||||
continue
|
||||
}
|
||||
dstAddr = fmt.Sprintf("%d.%d.%d.%d:%d", buf[4], buf[5], buf[6], buf[7],
|
||||
binary.BigEndian.Uint16(buf[8:10]))
|
||||
headerLen = 10
|
||||
case 0x03:
|
||||
dlen := int(buf[4])
|
||||
if n < 5+dlen+2 {
|
||||
continue
|
||||
}
|
||||
dstAddr = fmt.Sprintf("%s:%d", string(buf[5:5+dlen]),
|
||||
binary.BigEndian.Uint16(buf[5+dlen:7+dlen]))
|
||||
headerLen = 5 + dlen + 2
|
||||
case 0x04:
|
||||
if n < 22 {
|
||||
continue
|
||||
}
|
||||
ip := net.IP(buf[4:20])
|
||||
dstAddr = fmt.Sprintf("[%s]:%d", ip.String(),
|
||||
binary.BigEndian.Uint16(buf[20:22]))
|
||||
headerLen = 22
|
||||
default:
|
||||
continue
|
||||
}
|
||||
id := rb.nextID.Add(1)
|
||||
payload := make([]byte, len(dstAddr)+1+n-headerLen)
|
||||
payload[0] = byte(len(dstAddr))
|
||||
copy(payload[1:], dstAddr)
|
||||
copy(payload[1+len(dstAddr):], buf[headerLen:n])
|
||||
rb.udpClients.Store(id, &udpClient{udpConn: udpConn, clientAddr: addr, socksHdr: buf[:headerLen]})
|
||||
rb.send(id, msgUDP, payload)
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package pion
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pion/rtp"
|
||||
"github.com/pion/rtp/codecs"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
type tmPCState struct {
|
||||
pc *webrtc.PeerConnection
|
||||
remoteSet bool
|
||||
pending []webrtc.ICECandidateInit
|
||||
}
|
||||
|
||||
type TelemostClient struct {
|
||||
WSHelper
|
||||
pcs map[string]*tmPCState
|
||||
pcMu sync.Mutex
|
||||
sampleTrack *webrtc.TrackLocalStaticSample
|
||||
tunnel *VP8DataTunnel
|
||||
logFn func(string, ...any)
|
||||
LocalIP string
|
||||
ipReady chan struct{}
|
||||
ipOnce sync.Once
|
||||
OnConnected func(*VP8DataTunnel)
|
||||
}
|
||||
|
||||
func NewTelemostClient(logFn func(string, ...any)) *TelemostClient {
|
||||
if logFn == nil {
|
||||
logFn = log.Printf
|
||||
}
|
||||
return &TelemostClient{
|
||||
logFn: logFn,
|
||||
pcs: make(map[string]*tmPCState),
|
||||
ipReady: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *TelemostClient) HandleSignaling(w http.ResponseWriter, r *http.Request) {
|
||||
ws, err := WsUpgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
c.logFn("telemost: ws upgrade error: %v", err)
|
||||
return
|
||||
}
|
||||
c.SetConn(ws)
|
||||
c.logFn("telemost: signaling connected")
|
||||
c.ReadMessages(c.handleMessage, c.cleanup)
|
||||
}
|
||||
|
||||
func (c *TelemostClient) handleMessage(raw []byte) {
|
||||
var msg SignalingMessage
|
||||
if err := json.Unmarshal(raw, &msg); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
role := msg.Role
|
||||
if role == "" {
|
||||
role = "pub"
|
||||
}
|
||||
|
||||
switch msg.Type {
|
||||
case "local-ip":
|
||||
var ip string
|
||||
json.Unmarshal(msg.Data, &ip)
|
||||
c.LocalIP = ip
|
||||
c.logFn("telemost: local IP set to %s", ip)
|
||||
c.ipOnce.Do(func() { close(c.ipReady) })
|
||||
case "ice-servers":
|
||||
go c.handleICEServers(msg.Data, role)
|
||||
case "create-offer":
|
||||
go c.waitAndDo(role, func() { c.handleCreateOffer(msg.ID, role) })
|
||||
case "create-answer":
|
||||
go c.waitAndDo(role, func() { c.handleCreateAnswer(msg.ID, role) })
|
||||
case "set-local-description":
|
||||
case "set-remote-description":
|
||||
go c.waitAndDo(role, func() { c.handleSetRemoteDescription(msg.Data, msg.ID, role) })
|
||||
case "add-ice-candidate":
|
||||
c.handleICECandidate(msg.Data, role)
|
||||
case "add-track", "create-data-channel":
|
||||
case "close":
|
||||
c.cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *TelemostClient) waitAndDo(role string, fn func()) {
|
||||
for i := 0; i < 50; i++ {
|
||||
c.pcMu.Lock()
|
||||
ps := c.pcs[role]
|
||||
c.pcMu.Unlock()
|
||||
if ps != nil && ps.pc != nil {
|
||||
fn()
|
||||
return
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
c.logFn("telemost [%s]: timeout waiting for PC", role)
|
||||
}
|
||||
|
||||
func (c *TelemostClient) handleICEServers(data json.RawMessage, role string) {
|
||||
c.pcMu.Lock()
|
||||
if ps, ok := c.pcs[role]; ok && ps.pc != nil {
|
||||
c.pcMu.Unlock()
|
||||
return
|
||||
}
|
||||
c.pcMu.Unlock()
|
||||
|
||||
if c.LocalIP == "" {
|
||||
select {
|
||||
case <-c.ipReady:
|
||||
case <-time.After(3 * time.Second):
|
||||
c.logFn("telemost: no local IP received")
|
||||
}
|
||||
}
|
||||
|
||||
iceServers, err := ParseICEServers(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
config := webrtc.Configuration{
|
||||
ICEServers: iceServers,
|
||||
ICETransportPolicy: webrtc.ICETransportPolicyRelay,
|
||||
}
|
||||
|
||||
pc, err := NewPionAPI(c.LocalIP).NewPeerConnection(config)
|
||||
if err != nil {
|
||||
c.logFn("telemost [%s]: failed to create PC: %v", role, err)
|
||||
return
|
||||
}
|
||||
|
||||
ps := &tmPCState{pc: pc}
|
||||
c.pcMu.Lock()
|
||||
if existing, ok := c.pcs[role]; ok && existing.pc != nil {
|
||||
c.pcMu.Unlock()
|
||||
pc.Close()
|
||||
return
|
||||
}
|
||||
c.pcs[role] = ps
|
||||
c.pcMu.Unlock()
|
||||
|
||||
if role == "pub" {
|
||||
sampleTrack, _ := webrtc.NewTrackLocalStaticSample(
|
||||
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8},
|
||||
"video", "tunnel-video",
|
||||
)
|
||||
c.sampleTrack = sampleTrack
|
||||
audioTrack, _ := webrtc.NewTrackLocalStaticRTP(
|
||||
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus},
|
||||
"audio", "tunnel-audio",
|
||||
)
|
||||
audioSender, audioErr := pc.AddTrack(audioTrack)
|
||||
videoSender, videoErr := pc.AddTrack(sampleTrack)
|
||||
c.logFn("telemost [pub]: AddTrack audio: sender=%v err=%v", audioSender != nil, audioErr)
|
||||
c.logFn("telemost [pub]: AddTrack video: sender=%v err=%v", videoSender != nil, videoErr)
|
||||
c.logFn("telemost [pub]: senders count: %d", len(pc.GetSenders()))
|
||||
|
||||
}
|
||||
|
||||
pc.OnICECandidate(func(cand *webrtc.ICECandidate) {
|
||||
if cand == nil {
|
||||
c.logFn("telemost [%s]: ICE gathering complete", role)
|
||||
return
|
||||
}
|
||||
c.logFn("telemost [%s]: ICE candidate: type=%s protocol=%s address=%s", role, cand.Typ.String(), cand.Protocol.String(), cand.Address)
|
||||
c.SendToHookWithRole("ice-candidate", cand.ToJSON(), role)
|
||||
})
|
||||
|
||||
pc.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
||||
c.logFn("telemost [%s]: connection state: %s", role, state.String())
|
||||
c.SendToHook("connection-state", state.String())
|
||||
if state == webrtc.PeerConnectionStateConnected && role == "pub" && c.tunnel == nil {
|
||||
c.logFn("telemost: === CONNECTED - starting VP8 tunnel ===")
|
||||
c.logFn("telemost: sampleTrack id=%s kind=%s", c.sampleTrack.ID(), c.sampleTrack.Kind().String())
|
||||
c.logFn("telemost: pub senders=%d receivers=%d", len(pc.GetSenders()), len(pc.GetReceivers()))
|
||||
c.tunnel = NewVP8DataTunnel(c.sampleTrack, c.logFn)
|
||||
c.tunnel.Start(25)
|
||||
if c.OnConnected != nil {
|
||||
c.OnConnected(c.tunnel)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
pc.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
|
||||
c.logFn("telemost [%s]: remote track: %s", role, track.Codec().MimeType)
|
||||
c.SendToHook("remote-track", map[string]string{"kind": track.Kind().String()})
|
||||
go c.readTrack(track)
|
||||
})
|
||||
|
||||
c.logFn("telemost [%s]: PC created (%d ICE servers)", role, len(iceServers))
|
||||
}
|
||||
|
||||
func (c *TelemostClient) handleCreateOffer(id int, role string) {
|
||||
c.pcMu.Lock()
|
||||
ps := c.pcs[role]
|
||||
c.pcMu.Unlock()
|
||||
if ps == nil || ps.pc == nil {
|
||||
return
|
||||
}
|
||||
offer, err := ps.pc.CreateOffer(nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ps.pc.SetLocalDescription(offer)
|
||||
c.logFn("telemost [%s]: created offer, senders=%d signalingState=%s", role, len(ps.pc.GetSenders()), ps.pc.SignalingState().String())
|
||||
c.SendResponse(id, SDPMessage{Type: offer.Type.String(), SDP: offer.SDP})
|
||||
}
|
||||
|
||||
func (c *TelemostClient) handleCreateAnswer(id int, role string) {
|
||||
c.pcMu.Lock()
|
||||
ps := c.pcs[role]
|
||||
c.pcMu.Unlock()
|
||||
if ps == nil || ps.pc == nil {
|
||||
return
|
||||
}
|
||||
answer, err := ps.pc.CreateAnswer(nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ps.pc.SetLocalDescription(answer)
|
||||
c.logFn("telemost [%s]: created answer, senders=%d signalingState=%s", role, len(ps.pc.GetSenders()), ps.pc.SignalingState().String())
|
||||
c.SendResponse(id, SDPMessage{Type: answer.Type.String(), SDP: answer.SDP})
|
||||
}
|
||||
|
||||
func (c *TelemostClient) handleSetRemoteDescription(data json.RawMessage, id int, role string) {
|
||||
var sdpMsg SDPMessage
|
||||
if err := json.Unmarshal(data, &sdpMsg); err != nil {
|
||||
return
|
||||
}
|
||||
c.pcMu.Lock()
|
||||
ps := c.pcs[role]
|
||||
c.pcMu.Unlock()
|
||||
if ps == nil || ps.pc == nil {
|
||||
return
|
||||
}
|
||||
var sdpType webrtc.SDPType
|
||||
if sdpMsg.Type == "offer" {
|
||||
sdpType = webrtc.SDPTypeOffer
|
||||
} else {
|
||||
sdpType = webrtc.SDPTypeAnswer
|
||||
}
|
||||
if err := ps.pc.SetRemoteDescription(webrtc.SessionDescription{Type: sdpType, SDP: sdpMsg.SDP}); err != nil {
|
||||
c.logFn("telemost [%s]: setRemoteDescription error: %v", role, err)
|
||||
return
|
||||
}
|
||||
c.logFn("telemost [%s]: set remote description: %s, signalingState=%s, senders=%d", role, sdpMsg.Type, ps.pc.SignalingState().String(), len(ps.pc.GetSenders()))
|
||||
ps.remoteSet = true
|
||||
for _, cand := range ps.pending {
|
||||
ps.pc.AddICECandidate(cand)
|
||||
}
|
||||
ps.pending = nil
|
||||
if id > 0 {
|
||||
c.SendResponse(id, "ok")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *TelemostClient) handleICECandidate(data json.RawMessage, role string) {
|
||||
var cand ICECandidateMessage
|
||||
if err := json.Unmarshal(data, &cand); err != nil {
|
||||
return
|
||||
}
|
||||
c.pcMu.Lock()
|
||||
ps := c.pcs[role]
|
||||
c.pcMu.Unlock()
|
||||
if ps == nil || ps.pc == nil {
|
||||
return
|
||||
}
|
||||
init := webrtc.ICECandidateInit{
|
||||
Candidate: cand.Candidate, SDPMid: &cand.SDPMid, SDPMLineIndex: &cand.SDPMLineIndex,
|
||||
}
|
||||
if !ps.remoteSet {
|
||||
ps.pending = append(ps.pending, init)
|
||||
return
|
||||
}
|
||||
ps.pc.AddICECandidate(init)
|
||||
}
|
||||
|
||||
func (c *TelemostClient) readTrack(track *webrtc.TrackRemote) {
|
||||
if track.Codec().MimeType != webrtc.MimeTypeVP8 {
|
||||
buf := make([]byte, 4096)
|
||||
for {
|
||||
if _, _, err := track.Read(buf); err != nil {
|
||||
c.logFn("telemost: readTrack (%s) error: %v", track.Codec().MimeType, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var vp8Pkt codecs.VP8Packet
|
||||
var frameBuf []byte
|
||||
dataCount := 0
|
||||
recvCount := 0
|
||||
buf := make([]byte, 65536)
|
||||
for {
|
||||
n, _, err := track.Read(buf)
|
||||
if err != nil {
|
||||
c.logFn("telemost: readTrack error: %v", err)
|
||||
return
|
||||
}
|
||||
pkt := &rtp.Packet{}
|
||||
if pkt.Unmarshal(buf[:n]) != nil {
|
||||
continue
|
||||
}
|
||||
vp8Payload, err := vp8Pkt.Unmarshal(pkt.Payload)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if vp8Pkt.S == 1 {
|
||||
frameBuf = frameBuf[:0]
|
||||
}
|
||||
frameBuf = append(frameBuf, vp8Payload...)
|
||||
if pkt.Marker {
|
||||
recvCount++
|
||||
if recvCount <= 3 || recvCount%25 == 0 {
|
||||
if len(frameBuf) > 0 {
|
||||
c.logFn("telemost: recv frame #%d %d bytes, first=0x%02x", recvCount, len(frameBuf), frameBuf[0])
|
||||
}
|
||||
}
|
||||
data := ExtractDataFromPayload(frameBuf)
|
||||
if data != nil {
|
||||
dataCount++
|
||||
if dataCount <= 5 || dataCount%100 == 0 {
|
||||
c.logFn("telemost: TUNNEL DATA #%d: %d bytes", dataCount, len(data))
|
||||
}
|
||||
if c.tunnel != nil && c.tunnel.onData != nil {
|
||||
c.tunnel.onData(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *TelemostClient) cleanup() {
|
||||
if c.tunnel != nil {
|
||||
c.tunnel.Stop()
|
||||
c.tunnel = nil
|
||||
}
|
||||
c.pcMu.Lock()
|
||||
for role, ps := range c.pcs {
|
||||
if ps.pc != nil {
|
||||
ps.pc.Close()
|
||||
}
|
||||
delete(c.pcs, role)
|
||||
}
|
||||
c.pcMu.Unlock()
|
||||
c.logFn("telemost: cleaned up")
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package pion
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/pion/rtp"
|
||||
"github.com/pion/rtp/codecs"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
type VKClient struct {
|
||||
WSHelper
|
||||
pc *webrtc.PeerConnection
|
||||
sampleTrack *webrtc.TrackLocalStaticSample
|
||||
tunnel *VP8DataTunnel
|
||||
logFn func(string, ...any)
|
||||
remoteSet bool
|
||||
pending []webrtc.ICECandidateInit
|
||||
OnConnected func(*VP8DataTunnel)
|
||||
}
|
||||
|
||||
func NewVKClient(logFn func(string, ...any)) *VKClient {
|
||||
if logFn == nil {
|
||||
logFn = log.Printf
|
||||
}
|
||||
return &VKClient{logFn: logFn}
|
||||
}
|
||||
|
||||
func (c *VKClient) HandleSignaling(w http.ResponseWriter, r *http.Request) {
|
||||
ws, err := WsUpgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
c.logFn("vk: ws upgrade error: %v", err)
|
||||
return
|
||||
}
|
||||
c.SetConn(ws)
|
||||
c.logFn("vk: signaling connected")
|
||||
c.ReadMessages(c.handleMessage, c.cleanup)
|
||||
}
|
||||
|
||||
func (c *VKClient) handleMessage(raw []byte) {
|
||||
var msg SignalingMessage
|
||||
if err := json.Unmarshal(raw, &msg); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
switch msg.Type {
|
||||
case "ice-servers":
|
||||
c.handleICEServers(msg.Data)
|
||||
case "create-offer":
|
||||
c.handleCreateOffer(msg.ID)
|
||||
case "create-answer":
|
||||
c.handleCreateAnswer(msg.ID)
|
||||
case "set-local-description":
|
||||
case "set-remote-description":
|
||||
c.handleSetRemoteDescription(msg.Data, msg.ID)
|
||||
case "add-ice-candidate", "remote-ice-candidate":
|
||||
c.handleICECandidate(msg.Data)
|
||||
case "add-track", "create-data-channel":
|
||||
case "close":
|
||||
c.cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *VKClient) handleICEServers(data json.RawMessage) {
|
||||
if c.pc != nil {
|
||||
return
|
||||
}
|
||||
iceServers, err := ParseICEServers(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
config := webrtc.Configuration{
|
||||
ICEServers: iceServers,
|
||||
ICETransportPolicy: webrtc.ICETransportPolicyRelay,
|
||||
}
|
||||
|
||||
se := webrtc.SettingEngine{}
|
||||
se.SetNet(&AndroidNet{})
|
||||
se.SetInterfaceFilter(func(iface string) bool { return false })
|
||||
api := webrtc.NewAPI(webrtc.WithSettingEngine(se))
|
||||
pc, err := api.NewPeerConnection(config)
|
||||
if err != nil {
|
||||
c.logFn("vk: failed to create PC: %v", err)
|
||||
return
|
||||
}
|
||||
c.pc = pc
|
||||
|
||||
sampleTrack, _ := webrtc.NewTrackLocalStaticSample(
|
||||
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8},
|
||||
"video", "tunnel-video",
|
||||
)
|
||||
c.sampleTrack = sampleTrack
|
||||
|
||||
audioTrack, _ := webrtc.NewTrackLocalStaticRTP(
|
||||
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus},
|
||||
"audio", "tunnel-audio",
|
||||
)
|
||||
|
||||
audioSender, audioErr := pc.AddTrack(audioTrack)
|
||||
videoSender, videoErr := pc.AddTrack(sampleTrack)
|
||||
c.logFn("vk: AddTrack audio: sender=%v err=%v", audioSender != nil, audioErr)
|
||||
c.logFn("vk: AddTrack video: sender=%v err=%v", videoSender != nil, videoErr)
|
||||
c.logFn("vk: senders count: %d", len(pc.GetSenders()))
|
||||
|
||||
pc.OnICECandidate(func(cand *webrtc.ICECandidate) {
|
||||
if cand == nil {
|
||||
c.logFn("vk: ICE gathering complete (nil candidate)")
|
||||
return
|
||||
}
|
||||
c.logFn("vk: ICE candidate: type=%s protocol=%s address=%s", cand.Typ.String(), cand.Protocol.String(), cand.Address)
|
||||
c.SendToHook("ice-candidate", cand.ToJSON())
|
||||
})
|
||||
|
||||
pc.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
||||
c.logFn("vk: connection state: %s", state.String())
|
||||
c.SendToHook("connection-state", state.String())
|
||||
if state == webrtc.PeerConnectionStateConnected && c.tunnel == nil {
|
||||
c.logFn("vk: === CONNECTED - starting VP8 tunnel ===")
|
||||
c.logFn("vk: sampleTrack id=%s kind=%s", sampleTrack.ID(), sampleTrack.Kind().String())
|
||||
c.logFn("vk: PC senders=%d receivers=%d signalingState=%s", len(pc.GetSenders()), len(pc.GetReceivers()), pc.SignalingState().String())
|
||||
c.tunnel = NewVP8DataTunnel(sampleTrack, c.logFn)
|
||||
c.tunnel.Start(25)
|
||||
if c.OnConnected != nil {
|
||||
c.OnConnected(c.tunnel)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
pc.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
|
||||
c.logFn("vk: remote track: %s", track.Codec().MimeType)
|
||||
c.SendToHook("remote-track", map[string]string{"kind": track.Kind().String()})
|
||||
go c.readTrack(track)
|
||||
})
|
||||
|
||||
c.logFn("vk: PC created (%d ICE servers)", len(iceServers))
|
||||
}
|
||||
|
||||
func (c *VKClient) handleCreateOffer(id int) {
|
||||
if c.pc == nil {
|
||||
return
|
||||
}
|
||||
offer, err := c.pc.CreateOffer(nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.pc.SetLocalDescription(offer)
|
||||
c.logFn("vk: created offer, senders=%d signalingState=%s", len(c.pc.GetSenders()), c.pc.SignalingState().String())
|
||||
c.SendResponse(id, SDPMessage{Type: offer.Type.String(), SDP: offer.SDP})
|
||||
}
|
||||
|
||||
func (c *VKClient) handleCreateAnswer(id int) {
|
||||
if c.pc == nil {
|
||||
return
|
||||
}
|
||||
answer, err := c.pc.CreateAnswer(nil)
|
||||
if err != nil {
|
||||
c.logFn("vk: createAnswer error: %v", err)
|
||||
return
|
||||
}
|
||||
c.pc.SetLocalDescription(answer)
|
||||
c.logFn("vk: created answer, senders=%d signalingState=%s", len(c.pc.GetSenders()), c.pc.SignalingState().String())
|
||||
c.SendResponse(id, SDPMessage{Type: answer.Type.String(), SDP: answer.SDP})
|
||||
}
|
||||
|
||||
func (c *VKClient) handleSetRemoteDescription(data json.RawMessage, id int) {
|
||||
var sdpMsg SDPMessage
|
||||
if err := json.Unmarshal(data, &sdpMsg); err != nil || c.pc == nil {
|
||||
return
|
||||
}
|
||||
var sdpType webrtc.SDPType
|
||||
if sdpMsg.Type == "offer" {
|
||||
sdpType = webrtc.SDPTypeOffer
|
||||
} else {
|
||||
sdpType = webrtc.SDPTypeAnswer
|
||||
}
|
||||
if err := c.pc.SetRemoteDescription(webrtc.SessionDescription{Type: sdpType, SDP: sdpMsg.SDP}); err != nil {
|
||||
c.logFn("vk: setRemoteDescription error: %v", err)
|
||||
return
|
||||
}
|
||||
c.logFn("vk: set remote description: %s, signalingState=%s, senders=%d", sdpMsg.Type, c.pc.SignalingState().String(), len(c.pc.GetSenders()))
|
||||
for i, s := range c.pc.GetSenders() {
|
||||
if s.Track() != nil {
|
||||
c.logFn("vk: sender[%d]: kind=%s id=%s", i, s.Track().Kind().String(), s.Track().ID())
|
||||
} else {
|
||||
c.logFn("vk: sender[%d]: track=nil", i)
|
||||
}
|
||||
}
|
||||
c.remoteSet = true
|
||||
for _, cand := range c.pending {
|
||||
c.pc.AddICECandidate(cand)
|
||||
}
|
||||
c.pending = nil
|
||||
if id > 0 {
|
||||
c.SendResponse(id, "ok")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *VKClient) handleICECandidate(data json.RawMessage) {
|
||||
var cand ICECandidateMessage
|
||||
if err := json.Unmarshal(data, &cand); err != nil || c.pc == nil {
|
||||
return
|
||||
}
|
||||
init := webrtc.ICECandidateInit{
|
||||
Candidate: cand.Candidate, SDPMid: &cand.SDPMid, SDPMLineIndex: &cand.SDPMLineIndex,
|
||||
}
|
||||
if !c.remoteSet {
|
||||
c.pending = append(c.pending, init)
|
||||
return
|
||||
}
|
||||
c.pc.AddICECandidate(init)
|
||||
}
|
||||
|
||||
func (c *VKClient) readTrack(track *webrtc.TrackRemote) {
|
||||
if track.Codec().MimeType != webrtc.MimeTypeVP8 {
|
||||
buf := make([]byte, 4096)
|
||||
for {
|
||||
if _, _, err := track.Read(buf); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var vp8Pkt codecs.VP8Packet
|
||||
var frameBuf []byte
|
||||
dataCount := 0
|
||||
recvCount := 0
|
||||
buf := make([]byte, 65536)
|
||||
for {
|
||||
n, _, err := track.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
pkt := &rtp.Packet{}
|
||||
if pkt.Unmarshal(buf[:n]) != nil {
|
||||
continue
|
||||
}
|
||||
vp8Payload, err := vp8Pkt.Unmarshal(pkt.Payload)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if vp8Pkt.S == 1 {
|
||||
frameBuf = frameBuf[:0]
|
||||
}
|
||||
frameBuf = append(frameBuf, vp8Payload...)
|
||||
if pkt.Marker {
|
||||
recvCount++
|
||||
if recvCount <= 3 || recvCount%25 == 0 {
|
||||
if len(frameBuf) > 0 {
|
||||
c.logFn("vk: recv frame #%d %d bytes, first=0x%02x", recvCount, len(frameBuf), frameBuf[0])
|
||||
}
|
||||
}
|
||||
data := ExtractDataFromPayload(frameBuf)
|
||||
if data != nil {
|
||||
dataCount++
|
||||
if dataCount <= 5 || dataCount%100 == 0 {
|
||||
c.logFn("vk: TUNNEL DATA #%d: %d bytes", dataCount, len(data))
|
||||
}
|
||||
if c.tunnel != nil && c.tunnel.onData != nil {
|
||||
c.tunnel.onData(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *VKClient) cleanup() {
|
||||
if c.tunnel != nil {
|
||||
c.tunnel.Stop()
|
||||
c.tunnel = nil
|
||||
}
|
||||
if c.pc != nil {
|
||||
c.pc.Close()
|
||||
c.pc = nil
|
||||
}
|
||||
c.logFn("vk: cleaned up")
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package pion
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pion/webrtc/v4"
|
||||
"github.com/pion/webrtc/v4/pkg/media"
|
||||
)
|
||||
|
||||
// Real VP8 frames
|
||||
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,
|
||||
}
|
||||
|
||||
// VP8DataTunnel handles sending and receiving data through VP8 video samples
|
||||
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()
|
||||
throttle bool
|
||||
}
|
||||
|
||||
func NewVP8DataTunnel(track *webrtc.TrackLocalStaticSample, logFn func(string, ...any)) *VP8DataTunnel {
|
||||
return &VP8DataTunnel{
|
||||
track: track,
|
||||
logFn: logFn,
|
||||
stopCh: make(chan struct{}),
|
||||
sendQueue: make(chan []byte, 256),
|
||||
}
|
||||
}
|
||||
|
||||
// Data frame marker - first byte 0xFF distinguishes from VP8 (keyframe bit0=0, inter bit0=1)
|
||||
const dataFrameMarker = 0xFF
|
||||
|
||||
// buildFrame creates a VP8 frame or a data frame
|
||||
func (t *VP8DataTunnel) buildFrame(data []byte) []byte {
|
||||
t.frameCount++
|
||||
|
||||
if len(data) == 0 {
|
||||
// Keepalive - send valid VP8 keyframe every 60 frames (~2.4s)
|
||||
if t.frameCount%60 == 0 {
|
||||
return vp8Keyframe
|
||||
}
|
||||
return vp8Interframe
|
||||
}
|
||||
|
||||
// Data frame: [0xFF][4-byte length][payload]
|
||||
frame := make([]byte, 1+4+len(data))
|
||||
frame[0] = dataFrameMarker
|
||||
binary.BigEndian.PutUint32(frame[1:5], uint32(len(data)))
|
||||
copy(frame[5:], data)
|
||||
return frame
|
||||
}
|
||||
|
||||
// SendData queues tunnel data to be sent in the next VP8 frame
|
||||
var sendCount uint64
|
||||
|
||||
func (t *VP8DataTunnel) SendData(data []byte) {
|
||||
sendCount++
|
||||
if sendCount <= 5 || sendCount%100 == 0 {
|
||||
t.logFn("vp8tunnel: SendData #%d len=%d queueLen=%d", sendCount, len(data), len(t.sendQueue))
|
||||
}
|
||||
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)
|
||||
minInterval := 5 * time.Millisecond
|
||||
if elapsed < minInterval {
|
||||
time.Sleep(minInterval - elapsed)
|
||||
}
|
||||
lastSend = time.Now()
|
||||
frame := t.buildFrame(data)
|
||||
err := t.track.WriteSample(media.Sample{Data: frame, Duration: keepaliveInterval})
|
||||
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%250 == 0 {
|
||||
t.logFn("vp8tunnel: KEEPALIVE frame=%d first=0x%02x err=%v", t.frameCount-1, frame[0], err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) SetThrottle(on bool) {
|
||||
t.throttle = on
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) Stop() {
|
||||
if t.running {
|
||||
close(t.stopCh)
|
||||
t.running = false
|
||||
if t.onClose != nil {
|
||||
t.onClose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ExtractDataFromPayload extracts tunnel data from reassembled VP8 frame
|
||||
// The payload has VP8 RTP payload descriptor stripped by the depacketizer
|
||||
// First byte: 0xFF = data frame, anything else = valid VP8 (keepalive)
|
||||
func ExtractDataFromPayload(payload []byte) []byte {
|
||||
if len(payload) < 5 {
|
||||
return nil
|
||||
}
|
||||
if payload[0] != dataFrameMarker {
|
||||
return nil // valid VP8 keepalive frame, skip
|
||||
}
|
||||
dataLen := binary.BigEndian.Uint32(payload[1:5])
|
||||
if dataLen == 0 || int(dataLen) > len(payload)-5 {
|
||||
return nil
|
||||
}
|
||||
return payload[5 : 5+dataLen]
|
||||
}
|
||||
BIN
Binary file not shown.
Reference in new issue
Block a user