add bitrix support
This commit is contained in:
1 parent
747f8f2312
commit
5690cf58a9
62 files changed
+4098
-1053
No files matched your search
+156
-115
@@ -2,11 +2,9 @@ package livekit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -41,6 +39,7 @@ type Config struct {
|
||||
Token string
|
||||
Origin string
|
||||
UserAgent string
|
||||
Codec Codec
|
||||
LogFn func(string, ...any)
|
||||
SettingEngine *webrtc.SettingEngine
|
||||
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
@@ -54,6 +53,7 @@ type Client struct {
|
||||
token string
|
||||
origin string
|
||||
ua string
|
||||
codec Codec
|
||||
|
||||
settingEngine *webrtc.SettingEngine
|
||||
netDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
@@ -70,26 +70,34 @@ type Client struct {
|
||||
subMu sync.Mutex
|
||||
pubRemoteSet bool
|
||||
subRemoteSet bool
|
||||
pubPending []webrtc.ICECandidateInit
|
||||
subPending []webrtc.ICECandidateInit
|
||||
|
||||
closed atomic.Bool
|
||||
joined chan struct{}
|
||||
joinedOnce sync.Once
|
||||
closed atomic.Bool
|
||||
|
||||
OnReady func()
|
||||
OnTrack func(*webrtc.TrackRemote, *webrtc.RTPReceiver)
|
||||
OnDataChannel func(*webrtc.DataChannel)
|
||||
OnPubConnected func()
|
||||
OnParticipantUpdate func([]ParticipantInfo)
|
||||
OnReady func()
|
||||
OnTrack func(*webrtc.TrackRemote, *webrtc.RTPReceiver)
|
||||
OnDataChannel func(*webrtc.DataChannel)
|
||||
OnPubConnected func()
|
||||
OnSubConnected func()
|
||||
OnParticipantUpdate func([]ParticipantInfo)
|
||||
// OnRemoteCandidate fires once for every trickle ICE candidate
|
||||
// arriving from the SFU. Used by the Windows joiner to install
|
||||
// /32 bypass routes so the joiner's own media flows stay on the
|
||||
// physical NIC instead of recursing through the tunnel.
|
||||
OnRemoteCandidate func(target int, candidate webrtc.ICECandidateInit)
|
||||
OnRemoteCandidate func(target int, candidate webrtc.ICECandidateInit)
|
||||
// OnRemoteSDP fires when the SFU sends an SDP offer or answer.
|
||||
// The SDP itself can carry candidates inline; the Windows joiner
|
||||
// uses this to bypass them before any media starts flowing.
|
||||
OnRemoteSDP func(target int, sdpType, sdp string)
|
||||
OnRemoteSDP func(target int, sdpType, sdp string)
|
||||
}
|
||||
|
||||
func NewClient(cfg Config) *Client {
|
||||
func NewClient(cfg Config) (*Client, error) {
|
||||
if cfg.Codec == nil {
|
||||
return nil, fmt.Errorf("livekit: no codec")
|
||||
}
|
||||
logFn := cfg.LogFn
|
||||
if logFn == nil {
|
||||
logFn = func(string, ...any) {}
|
||||
@@ -100,35 +108,31 @@ func NewClient(cfg Config) *Client {
|
||||
token: cfg.Token,
|
||||
origin: cfg.Origin,
|
||||
ua: cfg.UserAgent,
|
||||
codec: cfg.Codec,
|
||||
settingEngine: cfg.SettingEngine,
|
||||
netDialContext: cfg.NetDialContext,
|
||||
resolveICEHost: cfg.ResolveICEHost,
|
||||
}
|
||||
joined: make(chan struct{}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Join() JoinResponse { return c.join }
|
||||
func (c *Client) Join() JoinResponse { return c.join }
|
||||
func (c *Client) PubPC() *webrtc.PeerConnection { return c.pubPC }
|
||||
func (c *Client) SubPC() *webrtc.PeerConnection { return c.subPC }
|
||||
func (c *Client) Joined() <-chan struct{} { return c.joined }
|
||||
|
||||
func (c *Client) Connect() error {
|
||||
u, err := url.Parse(c.wsURL)
|
||||
target, err := c.codec.DialURL(c.wsURL, c.token)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse url: %w", err)
|
||||
return err
|
||||
}
|
||||
u.Path = "/rtc"
|
||||
q := u.Query()
|
||||
q.Set("access_token", c.token)
|
||||
q.Set("protocol", ProtocolVersion)
|
||||
q.Set("sdk", SDKName)
|
||||
q.Set("version", SDKVersion)
|
||||
q.Set("auto_subscribe", "1")
|
||||
q.Set("adaptive_stream", "true")
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
headers := http.Header{}
|
||||
if c.ua != "" {
|
||||
headers.Set("User-Agent", c.ua)
|
||||
ua := c.ua
|
||||
if ua == "" {
|
||||
ua = common.UserAgent
|
||||
}
|
||||
headers.Set("User-Agent", ua)
|
||||
if c.origin != "" {
|
||||
headers.Set("Origin", c.origin)
|
||||
}
|
||||
@@ -137,51 +141,59 @@ func (c *Client) Connect() error {
|
||||
if c.netDialContext != nil {
|
||||
dialer.NetDialContext = c.netDialContext
|
||||
}
|
||||
conn, resp, err := dialer.Dial(u.String(), headers)
|
||||
conn, resp, err := dialer.Dial(target, headers)
|
||||
if err != nil {
|
||||
if resp != nil {
|
||||
return fmt.Errorf("ws dial: %w (status %d)", err, resp.StatusCode)
|
||||
return fmt.Errorf("ws dial: %w, status %d", err, resp.StatusCode)
|
||||
}
|
||||
return fmt.Errorf("ws dial: %w", err)
|
||||
}
|
||||
c.wsMu.Lock()
|
||||
c.ws = conn
|
||||
c.wsMu.Unlock()
|
||||
c.logFn("[lk] signaling connected")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) sendSignal(payload []byte) error {
|
||||
if payload == nil {
|
||||
return nil
|
||||
}
|
||||
c.wsMu.Lock()
|
||||
defer c.wsMu.Unlock()
|
||||
if c.ws == nil {
|
||||
return fmt.Errorf("ws not connected")
|
||||
}
|
||||
return c.ws.WriteMessage(websocket.BinaryMessage, payload)
|
||||
return c.ws.WriteMessage(c.codec.MessageType(), payload)
|
||||
}
|
||||
|
||||
func (c *Client) SendOffer(sdp string) error {
|
||||
return c.sendSignal(encSignalRequestOffer(sessionDescription{Type: "offer", SDP: sdp}))
|
||||
return c.sendSignal(c.codec.EncodeOffer(sdp))
|
||||
}
|
||||
|
||||
func (c *Client) SendAnswer(sdp string) error {
|
||||
return c.sendSignal(encSignalRequestAnswer(sessionDescription{Type: "answer", SDP: sdp}))
|
||||
return c.sendSignal(c.codec.EncodeAnswer(sdp))
|
||||
}
|
||||
|
||||
func (c *Client) SendTrickle(candidate webrtc.ICECandidateInit, target int) error {
|
||||
js, _ := json.Marshal(candidate)
|
||||
return c.sendSignal(encSignalRequestTrickle(trickleMsg{
|
||||
CandidateInit: string(js),
|
||||
Target: target,
|
||||
}))
|
||||
return c.sendSignal(c.codec.EncodeTrickle(candidate, target))
|
||||
}
|
||||
|
||||
func (c *Client) SendAddTrack(cid, name string, trackType, source int, width, height uint32) error {
|
||||
return c.sendSignal(encSignalRequestAddTrack(cid, name, trackType, source, width, height))
|
||||
return c.sendSignal(c.codec.EncodeAddTrack(AddTrackParams{
|
||||
CID: cid,
|
||||
Name: name,
|
||||
Type: trackType,
|
||||
Source: source,
|
||||
Width: width,
|
||||
Height: height,
|
||||
}))
|
||||
}
|
||||
|
||||
func (c *Client) SendLeave() error { return c.sendSignal(encSignalRequestLeave()) }
|
||||
func (c *Client) SendLeave() error { return c.sendSignal(c.codec.EncodeLeave()) }
|
||||
|
||||
func (c *Client) SendPing() error {
|
||||
return c.sendSignal(encSignalRequestPing(time.Now().UnixMilli()))
|
||||
return c.sendSignal(c.codec.EncodePing(time.Now().UnixMilli()))
|
||||
}
|
||||
|
||||
func (c *Client) Close() {
|
||||
@@ -190,13 +202,20 @@ func (c *Client) Close() {
|
||||
}
|
||||
c.wsMu.Lock()
|
||||
ws := c.ws
|
||||
c.ws = nil
|
||||
c.wsMu.Unlock()
|
||||
common.CloseWS(ws)
|
||||
if c.pubPC != nil {
|
||||
_ = c.pubPC.Close()
|
||||
c.pubMu.Lock()
|
||||
pubPC := c.pubPC
|
||||
c.pubMu.Unlock()
|
||||
c.subMu.Lock()
|
||||
subPC := c.subPC
|
||||
c.subMu.Unlock()
|
||||
if pubPC != nil {
|
||||
_ = pubPC.Close()
|
||||
}
|
||||
if c.subPC != nil {
|
||||
_ = c.subPC.Close()
|
||||
if subPC != nil {
|
||||
_ = subPC.Close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,8 +275,12 @@ func (c *Client) buildPeerConnections() error {
|
||||
return fmt.Errorf("create sub pc: %w", err)
|
||||
}
|
||||
|
||||
c.pubMu.Lock()
|
||||
c.pubPC = pubPC
|
||||
c.pubMu.Unlock()
|
||||
c.subMu.Lock()
|
||||
c.subPC = subPC
|
||||
c.subMu.Unlock()
|
||||
|
||||
pubPC.OnICECandidate(func(cand *webrtc.ICECandidate) {
|
||||
if cand == nil {
|
||||
@@ -284,6 +307,9 @@ func (c *Client) buildPeerConnections() error {
|
||||
})
|
||||
subPC.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
||||
c.logFn("[lk] sub PC state: %s", state.String())
|
||||
if state == webrtc.PeerConnectionStateConnected && c.OnSubConnected != nil {
|
||||
c.OnSubConnected()
|
||||
}
|
||||
})
|
||||
pubPC.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
|
||||
c.logFn("[lk] pub ICE state: %s", state.String())
|
||||
@@ -305,7 +331,7 @@ func (c *Client) buildPeerConnections() error {
|
||||
}
|
||||
})
|
||||
|
||||
c.logFn("[lk] PCs created (%d ICE servers)", len(c.join.ICEServers))
|
||||
c.logFn("[lk] PCs created, %d ICE servers", len(c.join.ICEServers))
|
||||
for i, s := range c.join.ICEServers {
|
||||
c.logFn("[lk] iceServer[%d]: urls=%v hasCred=%v", i, s.URLs, s.Username != "")
|
||||
}
|
||||
@@ -313,60 +339,51 @@ func (c *Client) buildPeerConnections() error {
|
||||
}
|
||||
|
||||
func (c *Client) handleSignal(data []byte) {
|
||||
sr, err := decSignalResponse(data)
|
||||
ev, err := c.codec.Decode(data)
|
||||
if err != nil {
|
||||
c.logFn("[lk] decode signal: %v", err)
|
||||
return
|
||||
}
|
||||
switch sr.Kind {
|
||||
case signalRespJoin:
|
||||
if sr.Join != nil {
|
||||
c.join = *sr.Join
|
||||
c.logFn("[lk] join: room=%s participant=%s subscriberPrimary=%v iceServers=%d pingTimeout=%ds pingInterval=%ds",
|
||||
c.join.RoomName, c.join.ParticipantID, c.join.SubscriberPrimary, len(c.join.ICEServers),
|
||||
c.join.PingTimeoutSec, c.join.PingIntervalSec)
|
||||
if err := c.buildPeerConnections(); err != nil {
|
||||
c.logFn("[lk] %v", err)
|
||||
return
|
||||
}
|
||||
if c.OnReady != nil {
|
||||
c.OnReady()
|
||||
}
|
||||
switch ev.Kind {
|
||||
case EventJoin:
|
||||
c.join = *ev.Join
|
||||
c.logFn("[lk] join: room=%s participant=%s subscriberPrimary=%v iceServers=%d pingTimeout=%ds pingInterval=%ds",
|
||||
c.join.RoomName, c.join.ParticipantID, c.join.SubscriberPrimary, len(c.join.ICEServers),
|
||||
c.join.PingTimeoutSec, c.join.PingIntervalSec)
|
||||
if err := c.buildPeerConnections(); err != nil {
|
||||
c.logFn("[lk] %v", err)
|
||||
return
|
||||
}
|
||||
case signalRespAnswer:
|
||||
c.logFn("[lk] <- pub answer (%d bytes)", len(sr.SDP.SDP))
|
||||
if sr.SDP != nil {
|
||||
c.applyPubAnswer(sr.SDP.SDP)
|
||||
c.joinedOnce.Do(func() { close(c.joined) })
|
||||
if c.OnReady != nil {
|
||||
c.OnReady()
|
||||
}
|
||||
case signalRespOffer:
|
||||
c.logFn("[lk] <- sub offer (%d bytes)", len(sr.SDP.SDP))
|
||||
if sr.SDP != nil {
|
||||
c.applySubOfferAndAnswer(sr.SDP.SDP)
|
||||
}
|
||||
case signalRespTrickle:
|
||||
if sr.Trickle != nil {
|
||||
c.logFn("[lk] <- trickle target=%d", sr.Trickle.Target)
|
||||
c.applyRemoteTrickle(*sr.Trickle)
|
||||
}
|
||||
case signalRespRefreshToken:
|
||||
if sr.Token != "" {
|
||||
c.token = sr.Token
|
||||
c.logFn("[lk] token refreshed")
|
||||
}
|
||||
case signalRespLeave:
|
||||
if sr.Leave != nil {
|
||||
case EventAnswer:
|
||||
c.logFn("[lk] pub answer received, %d bytes", len(ev.SDP))
|
||||
c.applyPubAnswer(ev.SDP)
|
||||
case EventOffer:
|
||||
c.logFn("[lk] sub offer received, %d bytes", len(ev.SDP))
|
||||
c.applySubOfferAndAnswer(ev.SDP)
|
||||
case EventTrickle:
|
||||
c.logFn("[lk] trickle target=%d", ev.Trickle.Target)
|
||||
c.applyRemoteTrickle(*ev.Trickle)
|
||||
case EventToken:
|
||||
c.token = ev.Token
|
||||
c.logFn("[lk] token refreshed")
|
||||
case EventLeave:
|
||||
if ev.Leave != nil {
|
||||
c.logFn("[lk] ignored leave reason=%s action=%s",
|
||||
DisconnectReasonName(sr.Leave.Reason), LeaveActionName(sr.Leave.Action))
|
||||
DisconnectReasonName(ev.Leave.Reason), LeaveActionName(ev.Leave.Action))
|
||||
} else {
|
||||
c.logFn("[lk] ignored leave")
|
||||
}
|
||||
case signalRespUpdate:
|
||||
if c.OnParticipantUpdate != nil && len(sr.Participants) > 0 {
|
||||
c.OnParticipantUpdate(sr.Participants)
|
||||
case EventUpdate:
|
||||
if c.OnParticipantUpdate != nil {
|
||||
c.OnParticipantUpdate(ev.Participants)
|
||||
}
|
||||
default:
|
||||
if common.Debug {
|
||||
c.logFn("[lk] <- signal kind=%d (%d bytes)", sr.Kind, len(data))
|
||||
c.logFn("[lk] unhandled signal, %d bytes", len(data))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -385,6 +402,7 @@ func (c *Client) applyPubAnswer(sdp string) {
|
||||
return
|
||||
}
|
||||
c.pubRemoteSet = true
|
||||
c.drainPendingLocked(c.pubPC, &c.pubPending)
|
||||
}
|
||||
|
||||
func (c *Client) applySubOfferAndAnswer(sdp string) {
|
||||
@@ -392,21 +410,26 @@ func (c *Client) applySubOfferAndAnswer(sdp string) {
|
||||
c.OnRemoteSDP(TargetSubscriber, "offer", sdp)
|
||||
}
|
||||
c.subMu.Lock()
|
||||
defer c.subMu.Unlock()
|
||||
if c.subPC == nil {
|
||||
c.subMu.Unlock()
|
||||
return
|
||||
}
|
||||
if err := c.subPC.SetRemoteDescription(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer, SDP: sdp}); err != nil {
|
||||
subPC := c.subPC
|
||||
if err := subPC.SetRemoteDescription(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer, SDP: sdp}); err != nil {
|
||||
c.subMu.Unlock()
|
||||
c.logFn("[lk] set sub remote offer: %v", err)
|
||||
return
|
||||
}
|
||||
c.subRemoteSet = true
|
||||
answer, err := c.subPC.CreateAnswer(nil)
|
||||
c.drainPendingLocked(subPC, &c.subPending)
|
||||
c.subMu.Unlock()
|
||||
|
||||
answer, err := subPC.CreateAnswer(nil)
|
||||
if err != nil {
|
||||
c.logFn("[lk] create sub answer: %v", err)
|
||||
return
|
||||
}
|
||||
if err := c.subPC.SetLocalDescription(answer); err != nil {
|
||||
if err := subPC.SetLocalDescription(answer); err != nil {
|
||||
c.logFn("[lk] set sub local answer: %v", err)
|
||||
return
|
||||
}
|
||||
@@ -415,44 +438,57 @@ func (c *Client) applySubOfferAndAnswer(sdp string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) applyRemoteTrickle(m trickleMsg) {
|
||||
if m.CandidateInit == "" {
|
||||
return
|
||||
}
|
||||
var ic webrtc.ICECandidateInit
|
||||
if err := json.Unmarshal([]byte(m.CandidateInit), &ic); err != nil {
|
||||
c.logFn("[lk] decode trickle candidate: %v", err)
|
||||
return
|
||||
func (c *Client) drainPendingLocked(pc *webrtc.PeerConnection, pending *[]webrtc.ICECandidateInit) {
|
||||
for _, ic := range *pending {
|
||||
if err := pc.AddICECandidate(ic); err != nil {
|
||||
c.logFn("[lk] add pending candidate: %v", err)
|
||||
}
|
||||
}
|
||||
*pending = nil
|
||||
}
|
||||
|
||||
func (c *Client) applyRemoteTrickle(m TrickleEvent) {
|
||||
if c.OnRemoteCandidate != nil {
|
||||
c.OnRemoteCandidate(m.Target, ic)
|
||||
c.OnRemoteCandidate(m.Target, m.Candidate)
|
||||
}
|
||||
switch m.Target {
|
||||
case TargetPublisher:
|
||||
c.pubMu.Lock()
|
||||
ready := c.pubRemoteSet
|
||||
c.pubMu.Unlock()
|
||||
if ready {
|
||||
_ = c.pubPC.AddICECandidate(ic)
|
||||
}
|
||||
case TargetSubscriber:
|
||||
c.subMu.Lock()
|
||||
ready := c.subRemoteSet
|
||||
c.subMu.Unlock()
|
||||
if ready {
|
||||
_ = c.subPC.AddICECandidate(ic)
|
||||
}
|
||||
mu := &c.subMu
|
||||
pc := &c.subPC
|
||||
ready := &c.subRemoteSet
|
||||
pending := &c.subPending
|
||||
if m.Target == TargetPublisher {
|
||||
mu = &c.pubMu
|
||||
pc = &c.pubPC
|
||||
ready = &c.pubRemoteSet
|
||||
pending = &c.pubPending
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if *pc == nil || !*ready {
|
||||
*pending = append(*pending, m.Candidate)
|
||||
return
|
||||
}
|
||||
if err := (*pc).AddICECandidate(m.Candidate); err != nil {
|
||||
c.logFn("[lk] add candidate: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) ReadLoop() error {
|
||||
defer c.Close()
|
||||
c.wsMu.Lock()
|
||||
ws := c.ws
|
||||
c.wsMu.Unlock()
|
||||
if ws == nil {
|
||||
return fmt.Errorf("ws not connected")
|
||||
}
|
||||
for {
|
||||
mt, data, err := c.ws.ReadMessage()
|
||||
mt, data, err := ws.ReadMessage()
|
||||
if err != nil {
|
||||
if c.closed.Load() {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if mt != websocket.BinaryMessage {
|
||||
if !c.codec.Accepts(mt) {
|
||||
continue
|
||||
}
|
||||
c.handleSignal(data)
|
||||
@@ -460,6 +496,11 @@ func (c *Client) ReadLoop() error {
|
||||
}
|
||||
|
||||
func (c *Client) PingLoop() {
|
||||
select {
|
||||
case <-c.joined:
|
||||
case <-time.After(30 * time.Second):
|
||||
return
|
||||
}
|
||||
period := PingPeriod
|
||||
if c.join.PingIntervalSec > 0 {
|
||||
period = time.Duration(c.join.PingIntervalSec) * time.Second
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
package livekit
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
const (
|
||||
EventOther = iota
|
||||
EventJoin
|
||||
EventAnswer
|
||||
EventOffer
|
||||
EventTrickle
|
||||
EventUpdate
|
||||
EventLeave
|
||||
EventToken
|
||||
)
|
||||
|
||||
type TrickleEvent struct {
|
||||
Candidate webrtc.ICECandidateInit
|
||||
Target int
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
Kind int
|
||||
Join *JoinResponse
|
||||
SDP string
|
||||
Trickle *TrickleEvent
|
||||
Participants []ParticipantInfo
|
||||
Token string
|
||||
Leave *LeaveInfo
|
||||
}
|
||||
|
||||
type AddTrackParams struct {
|
||||
CID string
|
||||
Name string
|
||||
Type int
|
||||
Source int
|
||||
Width uint32
|
||||
Height uint32
|
||||
}
|
||||
|
||||
type Codec interface {
|
||||
DialURL(serverURL, token string) (string, error)
|
||||
MessageType() int
|
||||
Accepts(messageType int) bool
|
||||
Decode(data []byte) (Event, error)
|
||||
EncodeOffer(sdp string) []byte
|
||||
EncodeAnswer(sdp string) []byte
|
||||
EncodeTrickle(candidate webrtc.ICECandidateInit, target int) []byte
|
||||
EncodeAddTrack(p AddTrackParams) []byte
|
||||
EncodePing(timestamp int64) []byte
|
||||
EncodeLeave() []byte
|
||||
}
|
||||
|
||||
type ProtoCodec struct{}
|
||||
|
||||
func (ProtoCodec) DialURL(serverURL, token string) (string, error) {
|
||||
u, err := url.Parse(serverURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse url: %w", err)
|
||||
}
|
||||
u.Path = "/rtc"
|
||||
q := u.Query()
|
||||
q.Set("access_token", token)
|
||||
q.Set("protocol", ProtocolVersion)
|
||||
q.Set("sdk", SDKName)
|
||||
q.Set("version", SDKVersion)
|
||||
q.Set("auto_subscribe", "1")
|
||||
q.Set("adaptive_stream", "true")
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
func (ProtoCodec) MessageType() int { return websocket.BinaryMessage }
|
||||
|
||||
func (ProtoCodec) Accepts(messageType int) bool { return messageType == websocket.BinaryMessage }
|
||||
|
||||
func (ProtoCodec) Decode(data []byte) (Event, error) {
|
||||
sr, err := decSignalResponse(data)
|
||||
if err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
var ev Event
|
||||
switch sr.Kind {
|
||||
case signalRespJoin:
|
||||
if sr.Join == nil {
|
||||
return ev, nil
|
||||
}
|
||||
ev.Kind = EventJoin
|
||||
ev.Join = sr.Join
|
||||
case signalRespAnswer:
|
||||
if sr.SDP == nil {
|
||||
return ev, nil
|
||||
}
|
||||
ev.Kind = EventAnswer
|
||||
ev.SDP = sr.SDP.SDP
|
||||
case signalRespOffer:
|
||||
if sr.SDP == nil {
|
||||
return ev, nil
|
||||
}
|
||||
ev.Kind = EventOffer
|
||||
ev.SDP = sr.SDP.SDP
|
||||
case signalRespTrickle:
|
||||
if sr.Trickle == nil || sr.Trickle.CandidateInit == "" {
|
||||
return ev, nil
|
||||
}
|
||||
var ic webrtc.ICECandidateInit
|
||||
if err := json.Unmarshal([]byte(sr.Trickle.CandidateInit), &ic); err != nil {
|
||||
return ev, fmt.Errorf("decode trickle candidate: %w", err)
|
||||
}
|
||||
ev.Kind = EventTrickle
|
||||
ev.Trickle = &TrickleEvent{Candidate: ic, Target: sr.Trickle.Target}
|
||||
case signalRespRefreshToken:
|
||||
if sr.Token == "" {
|
||||
return ev, nil
|
||||
}
|
||||
ev.Kind = EventToken
|
||||
ev.Token = sr.Token
|
||||
case signalRespLeave:
|
||||
ev.Kind = EventLeave
|
||||
ev.Leave = sr.Leave
|
||||
case signalRespUpdate:
|
||||
if len(sr.Participants) == 0 {
|
||||
return ev, nil
|
||||
}
|
||||
ev.Kind = EventUpdate
|
||||
ev.Participants = sr.Participants
|
||||
}
|
||||
return ev, nil
|
||||
}
|
||||
|
||||
func (ProtoCodec) EncodeOffer(sdp string) []byte {
|
||||
return encSignalRequestOffer(sessionDescription{Type: "offer", SDP: sdp})
|
||||
}
|
||||
|
||||
func (ProtoCodec) EncodeAnswer(sdp string) []byte {
|
||||
return encSignalRequestAnswer(sessionDescription{Type: "answer", SDP: sdp})
|
||||
}
|
||||
|
||||
func (ProtoCodec) EncodeTrickle(candidate webrtc.ICECandidateInit, target int) []byte {
|
||||
js, _ := json.Marshal(candidate)
|
||||
return encSignalRequestTrickle(trickleMsg{CandidateInit: string(js), Target: target})
|
||||
}
|
||||
|
||||
func (ProtoCodec) EncodeAddTrack(p AddTrackParams) []byte {
|
||||
return encSignalRequestAddTrack(p.CID, p.Name, p.Type, p.Source, p.Width, p.Height)
|
||||
}
|
||||
|
||||
func (ProtoCodec) EncodePing(timestamp int64) []byte {
|
||||
return encSignalRequestPing(timestamp)
|
||||
}
|
||||
|
||||
func (ProtoCodec) EncodeLeave() []byte { return encSignalRequestLeave() }
|
||||
|
||||
const (
|
||||
jsonTargetPublisher = "PUBLISHER"
|
||||
jsonTargetSubscriber = "SUBSCRIBER"
|
||||
)
|
||||
|
||||
type jsonSDP struct {
|
||||
SDP string `json:"sdp"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type jsonTrickle struct {
|
||||
CandidateInit string `json:"candidateInit"`
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
type jsonICEServer struct {
|
||||
URLs []string `json:"urls"`
|
||||
Username string `json:"username"`
|
||||
Credential string `json:"credential"`
|
||||
}
|
||||
|
||||
type jsonJoin struct {
|
||||
RoomID string `json:"roomId"`
|
||||
PingInterval int32 `json:"pingInterval"`
|
||||
ICEServers []jsonICEServer `json:"iceServers"`
|
||||
Local struct {
|
||||
SID string `json:"sid"`
|
||||
Name string `json:"name"`
|
||||
} `json:"localParticipant"`
|
||||
}
|
||||
|
||||
type jsonVideoLayer struct {
|
||||
Quality string `json:"quality"`
|
||||
Width uint32 `json:"width"`
|
||||
Height uint32 `json:"height"`
|
||||
}
|
||||
|
||||
type jsonAddTrack struct {
|
||||
CID string `json:"cid"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Source string `json:"source"`
|
||||
Width uint32 `json:"width"`
|
||||
Height uint32 `json:"height"`
|
||||
Layers []jsonVideoLayer `json:"layers"`
|
||||
}
|
||||
|
||||
type JSONCodec struct{}
|
||||
|
||||
func (JSONCodec) DialURL(serverURL, _ string) (string, error) { return serverURL, nil }
|
||||
|
||||
func (JSONCodec) MessageType() int { return websocket.TextMessage }
|
||||
|
||||
func (JSONCodec) Accepts(messageType int) bool {
|
||||
return messageType == websocket.TextMessage || messageType == websocket.BinaryMessage
|
||||
}
|
||||
|
||||
func (JSONCodec) Decode(data []byte) (Event, error) {
|
||||
var envelope map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &envelope); err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
var ev Event
|
||||
for kind, raw := range envelope {
|
||||
switch kind {
|
||||
case "joinResponse":
|
||||
var ji jsonJoin
|
||||
if err := json.Unmarshal(raw, &ji); err != nil {
|
||||
return ev, fmt.Errorf("joinResponse: %w", err)
|
||||
}
|
||||
join := JoinResponse{
|
||||
RoomName: ji.RoomID,
|
||||
ParticipantSID: ji.Local.SID,
|
||||
ParticipantID: ji.Local.Name,
|
||||
PingIntervalSec: ji.PingInterval,
|
||||
}
|
||||
for _, is := range ji.ICEServers {
|
||||
join.ICEServers = append(join.ICEServers, ICEServer{
|
||||
URLs: is.URLs,
|
||||
Username: is.Username,
|
||||
Credential: is.Credential,
|
||||
})
|
||||
}
|
||||
ev.Kind = EventJoin
|
||||
ev.Join = &join
|
||||
return ev, nil
|
||||
case "offer", "answer":
|
||||
var m jsonSDP
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return ev, fmt.Errorf("%s: %w", kind, err)
|
||||
}
|
||||
if kind == "offer" {
|
||||
ev.Kind = EventOffer
|
||||
} else {
|
||||
ev.Kind = EventAnswer
|
||||
}
|
||||
ev.SDP = m.SDP
|
||||
return ev, nil
|
||||
case "trickle":
|
||||
var m jsonTrickle
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return ev, fmt.Errorf("trickle: %w", err)
|
||||
}
|
||||
if m.CandidateInit == "" {
|
||||
return ev, nil
|
||||
}
|
||||
var ic webrtc.ICECandidateInit
|
||||
if err := json.Unmarshal([]byte(m.CandidateInit), &ic); err != nil {
|
||||
return ev, fmt.Errorf("decode trickle candidate: %w", err)
|
||||
}
|
||||
target := TargetPublisher
|
||||
if m.Target == jsonTargetSubscriber {
|
||||
target = TargetSubscriber
|
||||
}
|
||||
ev.Kind = EventTrickle
|
||||
ev.Trickle = &TrickleEvent{Candidate: ic, Target: target}
|
||||
return ev, nil
|
||||
}
|
||||
}
|
||||
return ev, nil
|
||||
}
|
||||
|
||||
func (JSONCodec) encode(envelope string, payload any) []byte {
|
||||
body, err := json.Marshal(map[string]any{envelope: payload})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func (c JSONCodec) EncodeOffer(sdp string) []byte {
|
||||
return c.encode("offer", jsonSDP{SDP: sdp, Type: "offer"})
|
||||
}
|
||||
|
||||
func (c JSONCodec) EncodeAnswer(sdp string) []byte {
|
||||
return c.encode("answer", jsonSDP{SDP: sdp, Type: "answer"})
|
||||
}
|
||||
|
||||
func (c JSONCodec) EncodeTrickle(candidate webrtc.ICECandidateInit, target int) []byte {
|
||||
js, err := json.Marshal(candidate)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
wire := jsonTrickle{CandidateInit: string(js), Target: jsonTargetPublisher}
|
||||
if target == TargetSubscriber {
|
||||
wire.Target = jsonTargetSubscriber
|
||||
}
|
||||
return c.encode("trickle", wire)
|
||||
}
|
||||
|
||||
func (c JSONCodec) EncodeAddTrack(p AddTrackParams) []byte {
|
||||
kind := "VIDEO"
|
||||
if p.Type == TrackTypeAudio {
|
||||
kind = "AUDIO"
|
||||
}
|
||||
source := "CAMERA"
|
||||
if p.Source == TrackSourceScreenShare {
|
||||
source = "SCREEN_SHARE"
|
||||
}
|
||||
return c.encode("addTrack", jsonAddTrack{
|
||||
CID: p.CID,
|
||||
Name: p.Name,
|
||||
Type: kind,
|
||||
Source: source,
|
||||
Width: p.Width,
|
||||
Height: p.Height,
|
||||
Layers: []jsonVideoLayer{{Quality: "HIGH", Width: p.Width, Height: p.Height}},
|
||||
})
|
||||
}
|
||||
|
||||
func (c JSONCodec) EncodePing(timestamp int64) []byte {
|
||||
return c.encode("pingReq", map[string]any{"timestamp": timestamp, "rtt": 0})
|
||||
}
|
||||
|
||||
func (JSONCodec) EncodeLeave() []byte { return nil }
|
||||
@@ -0,0 +1,52 @@
|
||||
package livekit
|
||||
|
||||
import (
|
||||
"github.com/pion/datachannel"
|
||||
)
|
||||
|
||||
type DataPacketWrapper struct {
|
||||
inner datachannel.ReadWriteCloser
|
||||
kind int
|
||||
}
|
||||
|
||||
func NewDataPacketWrapper(inner datachannel.ReadWriteCloser, kind int) *DataPacketWrapper {
|
||||
return &DataPacketWrapper{inner: inner, kind: kind}
|
||||
}
|
||||
|
||||
func (w *DataPacketWrapper) ReadDataChannel(p []byte) (int, bool, error) {
|
||||
buf := make([]byte, len(p))
|
||||
for {
|
||||
n, isString, err := w.inner.ReadDataChannel(buf)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if n == 0 {
|
||||
continue
|
||||
}
|
||||
payload, ok := DecodeDataPacketUser(buf[:n])
|
||||
if !ok || len(payload) == 0 {
|
||||
continue
|
||||
}
|
||||
copied := copy(p, payload)
|
||||
return copied, isString, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (w *DataPacketWrapper) WriteDataChannel(p []byte, isString bool) (int, error) {
|
||||
wire := EncodeDataPacketUser(p, w.kind)
|
||||
if _, err := w.inner.WriteDataChannel(wire, isString); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (w *DataPacketWrapper) Read(p []byte) (int, error) {
|
||||
n, _, err := w.ReadDataChannel(p)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (w *DataPacketWrapper) Write(p []byte) (int, error) {
|
||||
return w.WriteDataChannel(p, false)
|
||||
}
|
||||
|
||||
func (w *DataPacketWrapper) Close() error { return w.inner.Close() }
|
||||
+29
-29
@@ -3,26 +3,26 @@ package livekit
|
||||
import "fmt"
|
||||
|
||||
const (
|
||||
signalReqOffer = 1
|
||||
signalReqAnswer = 2
|
||||
signalReqTrickle = 3
|
||||
signalReqAddTrack = 4
|
||||
signalReqLeave = 8
|
||||
signalReqPingLegacy = 14
|
||||
signalReqPingReq = 16
|
||||
signalReqOffer = 1
|
||||
signalReqAnswer = 2
|
||||
signalReqTrickle = 3
|
||||
signalReqAddTrack = 4
|
||||
signalReqLeave = 8
|
||||
signalReqPingLegacy = 14
|
||||
signalReqPingReq = 16
|
||||
|
||||
signalRespJoin = 1
|
||||
signalRespAnswer = 2
|
||||
signalRespOffer = 3
|
||||
signalRespTrickle = 4
|
||||
signalRespUpdate = 5
|
||||
signalRespTrackPublished = 6
|
||||
signalRespLeave = 8
|
||||
signalRespRoomUpdate = 11
|
||||
signalRespRefreshToken = 16
|
||||
signalRespPongResp = 20
|
||||
signalRespRequestResponse = 22
|
||||
signalRespTrackSubscribed = 23
|
||||
signalRespJoin = 1
|
||||
signalRespAnswer = 2
|
||||
signalRespOffer = 3
|
||||
signalRespTrickle = 4
|
||||
signalRespUpdate = 5
|
||||
signalRespTrackPublished = 6
|
||||
signalRespLeave = 8
|
||||
signalRespRoomUpdate = 11
|
||||
signalRespRefreshToken = 16
|
||||
signalRespPongResp = 20
|
||||
signalRespRequestResponse = 22
|
||||
signalRespTrackSubscribed = 23
|
||||
|
||||
sdpFieldType = 1
|
||||
sdpFieldSDP = 2
|
||||
@@ -179,16 +179,16 @@ type iceServer struct {
|
||||
}
|
||||
|
||||
type joinResponse struct {
|
||||
RoomSID string
|
||||
RoomName string
|
||||
ParticipantSID string
|
||||
ParticipantID string
|
||||
ServerVersion string
|
||||
ServerRegion string
|
||||
ICEServers []iceServer
|
||||
SubscriberPrimary bool
|
||||
PingTimeoutSec int32
|
||||
PingIntervalSec int32
|
||||
RoomSID string
|
||||
RoomName string
|
||||
ParticipantSID string
|
||||
ParticipantID string
|
||||
ServerVersion string
|
||||
ServerRegion string
|
||||
ICEServers []iceServer
|
||||
SubscriberPrimary bool
|
||||
PingTimeoutSec int32
|
||||
PingIntervalSec int32
|
||||
}
|
||||
|
||||
type signalResponse struct {
|
||||
|
||||
Reference in new issue
Block a user