Removed cli, mux cleanup, docs update
This commit is contained in:
@@ -1,605 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/pion/rtcp"
|
||||
"github.com/pion/rtp"
|
||||
"github.com/pion/webrtc/v3"
|
||||
"github.com/thoas/go-funk"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/logger"
|
||||
"github.com/livekit/livekit-server/pkg/rtc"
|
||||
livekit "github.com/livekit/livekit-server/proto"
|
||||
"github.com/livekit/protocol/utils"
|
||||
)
|
||||
|
||||
type RTCClient struct {
|
||||
id string
|
||||
conn *websocket.Conn
|
||||
publisher *rtc.PCTransport
|
||||
subscriber *rtc.PCTransport
|
||||
// sid => track
|
||||
localTracks map[string]webrtc.TrackLocal
|
||||
lock sync.Mutex
|
||||
wsLock sync.Mutex
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
connected utils.AtomicFlag
|
||||
iceConnected utils.AtomicFlag
|
||||
me *webrtc.MediaEngine // optional, populated only when receiving tracks
|
||||
subscribedTracks map[string][]*webrtc.TrackRemote
|
||||
localParticipant *livekit.ParticipantInfo
|
||||
remoteParticipants map[string]*livekit.ParticipantInfo
|
||||
|
||||
// tracks waiting to be acked, cid => trackInfo
|
||||
pendingPublishedTracks map[string]*livekit.TrackInfo
|
||||
|
||||
pendingTrackWriters []*TrackWriter
|
||||
OnConnected func()
|
||||
|
||||
// map of track Id and last packet
|
||||
lastPackets map[string]*rtp.Packet
|
||||
bytesReceived map[string]uint64
|
||||
}
|
||||
|
||||
var (
|
||||
// minimal settings only with stun server
|
||||
rtcConf = webrtc.Configuration{
|
||||
ICEServers: []webrtc.ICEServer{
|
||||
{
|
||||
URLs: []string{"stun:stun.l.google.com:19302"},
|
||||
},
|
||||
},
|
||||
}
|
||||
extMimeMapping = map[string]string{
|
||||
".ivf": webrtc.MimeTypeVP8,
|
||||
".h264": webrtc.MimeTypeH264,
|
||||
".ogg": webrtc.MimeTypeOpus,
|
||||
}
|
||||
)
|
||||
|
||||
func NewWebSocketConn(host, token string) (*websocket.Conn, error) {
|
||||
u, err := url.Parse(host + "/rtc")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
requestHeader := make(http.Header)
|
||||
SetAuthorizationToken(requestHeader, token)
|
||||
conn, _, err := websocket.DefaultDialer.Dial(u.String(), requestHeader)
|
||||
return conn, err
|
||||
}
|
||||
|
||||
func SetAuthorizationToken(header http.Header, token string) {
|
||||
header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
|
||||
func NewRTCClient(conn *websocket.Conn) (*RTCClient, error) {
|
||||
var err error
|
||||
|
||||
c := &RTCClient{
|
||||
conn: conn,
|
||||
localTracks: make(map[string]webrtc.TrackLocal),
|
||||
pendingPublishedTracks: make(map[string]*livekit.TrackInfo),
|
||||
subscribedTracks: make(map[string][]*webrtc.TrackRemote),
|
||||
remoteParticipants: make(map[string]*livekit.ParticipantInfo),
|
||||
me: &webrtc.MediaEngine{},
|
||||
lastPackets: make(map[string]*rtp.Packet),
|
||||
bytesReceived: make(map[string]uint64),
|
||||
}
|
||||
c.ctx, c.cancel = context.WithCancel(context.Background())
|
||||
|
||||
conf := rtc.WebRTCConfig{
|
||||
Configuration: rtcConf,
|
||||
}
|
||||
c.publisher, err = rtc.NewPCTransport(livekit.SignalTarget_PUBLISHER, &conf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// intentionally use publisher transport to have codecs pre-registered
|
||||
c.subscriber, err = rtc.NewPCTransport(livekit.SignalTarget_PUBLISHER, &conf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.publisher.PeerConnection().OnICECandidate(func(ic *webrtc.ICECandidate) {
|
||||
if ic == nil {
|
||||
return
|
||||
}
|
||||
c.SendIceCandidate(ic, livekit.SignalTarget_PUBLISHER)
|
||||
})
|
||||
c.subscriber.PeerConnection().OnICECandidate(func(ic *webrtc.ICECandidate) {
|
||||
if ic == nil {
|
||||
return
|
||||
}
|
||||
c.SendIceCandidate(ic, livekit.SignalTarget_SUBSCRIBER)
|
||||
})
|
||||
|
||||
c.subscriber.PeerConnection().OnTrack(func(track *webrtc.TrackRemote, rtpReceiver *webrtc.RTPReceiver) {
|
||||
go c.processTrack(track)
|
||||
})
|
||||
c.subscriber.PeerConnection().OnDataChannel(func(channel *webrtc.DataChannel) {
|
||||
})
|
||||
|
||||
c.publisher.OnOffer(c.onOffer)
|
||||
|
||||
c.publisher.PeerConnection().OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
|
||||
logger.Debugw("ICE state has changed", "state", connectionState.String(),
|
||||
"participant", c.localParticipant.Identity)
|
||||
if connectionState == webrtc.ICEConnectionStateConnected {
|
||||
// flush peers
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
for _, tw := range c.pendingTrackWriters {
|
||||
if err := tw.Start(); err != nil {
|
||||
logger.Debugw("track writer error", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
initialConnect := !c.iceConnected.Get()
|
||||
c.pendingTrackWriters = nil
|
||||
c.iceConnected.TrySet(true)
|
||||
|
||||
if initialConnect && c.OnConnected != nil {
|
||||
go c.OnConnected()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *RTCClient) ID() string {
|
||||
return c.id
|
||||
}
|
||||
|
||||
// create an offer for the server
|
||||
func (c *RTCClient) Run() error {
|
||||
c.conn.SetCloseHandler(func(code int, text string) error {
|
||||
// when closed, stop connection
|
||||
logger.Infow("connection closed", "code", code, "text", text)
|
||||
c.Stop()
|
||||
return nil
|
||||
})
|
||||
|
||||
// create a data channel, in order to work
|
||||
_, err := c.publisher.PeerConnection().CreateDataChannel("_private", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// run the session
|
||||
for {
|
||||
res, err := c.ReadResponse()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch msg := res.Message.(type) {
|
||||
case *livekit.SignalResponse_Join:
|
||||
c.localParticipant = msg.Join.Participant
|
||||
c.id = msg.Join.Participant.Sid
|
||||
|
||||
c.lock.Lock()
|
||||
for _, p := range msg.Join.OtherParticipants {
|
||||
c.remoteParticipants[p.Sid] = p
|
||||
}
|
||||
c.lock.Unlock()
|
||||
|
||||
logger.Debugw("join accepted, sending offer..", "participant", msg.Join.Participant.Identity)
|
||||
logger.Debugw("other participants", "count", len(msg.Join.OtherParticipants))
|
||||
|
||||
// Create an offer to send to the other process
|
||||
offer, err := c.publisher.PeerConnection().CreateOffer(nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Debugw("created offer",
|
||||
"participant", c.localParticipant.Identity,
|
||||
//"sdp", offer.SDP,
|
||||
)
|
||||
|
||||
// Sets the LocalDescription, and starts our UDP listeners
|
||||
// Note: this will start the gathering of ICE candidates
|
||||
if err = c.publisher.PeerConnection().SetLocalDescription(offer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// send the offer to remote
|
||||
req := &livekit.SignalRequest{
|
||||
Message: &livekit.SignalRequest_Offer{
|
||||
Offer: rtc.ToProtoSessionDescription(offer),
|
||||
},
|
||||
}
|
||||
if err = c.SendRequest(req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer c.Stop()
|
||||
case *livekit.SignalResponse_Answer:
|
||||
//logger.Debugw("received server answer",
|
||||
// "participant", c.localParticipant.Identity,
|
||||
// "answer", msg.Answer.Sdp)
|
||||
c.handleAnswer(rtc.FromProtoSessionDescription(msg.Answer))
|
||||
case *livekit.SignalResponse_Offer:
|
||||
//logger.Debugw("received server offer",
|
||||
// "participant", c.localParticipant.Identity,
|
||||
// "sdp", msg.Offer.Sdp)
|
||||
desc := rtc.FromProtoSessionDescription(msg.Offer)
|
||||
if err := c.handleOffer(desc); err != nil {
|
||||
return err
|
||||
}
|
||||
case *livekit.SignalResponse_Trickle:
|
||||
candidateInit, err := rtc.FromProtoTrickle(msg.Trickle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if msg.Trickle.Target == livekit.SignalTarget_PUBLISHER {
|
||||
err = c.publisher.AddICECandidate(candidateInit)
|
||||
} else {
|
||||
err = c.subscriber.AddICECandidate(candidateInit)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case *livekit.SignalResponse_Update:
|
||||
participants := make(map[string]*livekit.ParticipantInfo)
|
||||
for _, p := range msg.Update.Participants {
|
||||
if p.State != livekit.ParticipantInfo_DISCONNECTED {
|
||||
participants[p.Sid] = p
|
||||
}
|
||||
}
|
||||
c.lock.Lock()
|
||||
c.remoteParticipants = participants
|
||||
c.lock.Unlock()
|
||||
|
||||
case *livekit.SignalResponse_TrackPublished:
|
||||
logger.Debugw("track published", "track", msg.TrackPublished.Track.Name, "participant", c.localParticipant.Sid,
|
||||
"cid", msg.TrackPublished.Cid, "trackSid", msg.TrackPublished.Track.Sid)
|
||||
c.lock.Lock()
|
||||
c.pendingPublishedTracks[msg.TrackPublished.Cid] = msg.TrackPublished.Track
|
||||
c.lock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
if err != io.EOF {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *RTCClient) WaitUntilConnected() error {
|
||||
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
id := c.ID()
|
||||
if c.localParticipant != nil {
|
||||
id = c.localParticipant.Identity
|
||||
}
|
||||
return fmt.Errorf("%s could not connect after timeout", id)
|
||||
case <-time.After(10 * time.Millisecond):
|
||||
if c.iceConnected.Get() {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *RTCClient) ReadResponse() (*livekit.SignalResponse, error) {
|
||||
for {
|
||||
// handle special messages and pass on the rest
|
||||
messageType, payload, err := c.conn.ReadMessage()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if c.ctx.Err() != nil {
|
||||
return nil, c.ctx.Err()
|
||||
}
|
||||
|
||||
msg := &livekit.SignalResponse{}
|
||||
switch messageType {
|
||||
case websocket.PingMessage:
|
||||
c.conn.WriteMessage(websocket.PongMessage, nil)
|
||||
continue
|
||||
case websocket.BinaryMessage:
|
||||
// protobuf encoded
|
||||
err := proto.Unmarshal(payload, msg)
|
||||
return msg, err
|
||||
case websocket.TextMessage:
|
||||
// json encoded, also write back JSON
|
||||
err := protojson.Unmarshal(payload, msg)
|
||||
return msg, err
|
||||
default:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: this function is not thread safe, need to cleanup
|
||||
func (c *RTCClient) SubscribedTracks() map[string][]*webrtc.TrackRemote {
|
||||
// create a copy of this
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
tracks := make(map[string][]*webrtc.TrackRemote, len(c.subscribedTracks))
|
||||
for key, val := range c.subscribedTracks {
|
||||
tracks[key] = val
|
||||
}
|
||||
return tracks
|
||||
}
|
||||
|
||||
func (c *RTCClient) RemoteParticipants() []*livekit.ParticipantInfo {
|
||||
return funk.Values(c.remoteParticipants).([]*livekit.ParticipantInfo)
|
||||
}
|
||||
|
||||
func (c *RTCClient) Stop() {
|
||||
_ = c.SendRequest(&livekit.SignalRequest{
|
||||
Message: &livekit.SignalRequest_Leave{
|
||||
Leave: &livekit.LeaveRequest{},
|
||||
},
|
||||
})
|
||||
c.connected.TrySet(false)
|
||||
c.iceConnected.TrySet(false)
|
||||
c.conn.Close()
|
||||
c.publisher.Close()
|
||||
c.subscriber.Close()
|
||||
c.cancel()
|
||||
}
|
||||
|
||||
func (c *RTCClient) SendRequest(msg *livekit.SignalRequest) error {
|
||||
payload, err := protojson.Marshal(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.wsLock.Lock()
|
||||
defer c.wsLock.Unlock()
|
||||
return c.conn.WriteMessage(websocket.TextMessage, payload)
|
||||
}
|
||||
|
||||
func (c *RTCClient) SendIceCandidate(ic *webrtc.ICECandidate, target livekit.SignalTarget) error {
|
||||
trickle := rtc.ToProtoTrickle(ic.ToJSON())
|
||||
trickle.Target = target
|
||||
return c.SendRequest(&livekit.SignalRequest{
|
||||
Message: &livekit.SignalRequest_Trickle{
|
||||
Trickle: trickle,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c *RTCClient) AddTrack(track *webrtc.TrackLocalStaticSample, path string) (writer *TrackWriter, err error) {
|
||||
trackType := livekit.TrackType_AUDIO
|
||||
if track.Kind() == webrtc.RTPCodecTypeVideo {
|
||||
trackType = livekit.TrackType_VIDEO
|
||||
}
|
||||
|
||||
if err = c.SendAddTrack(track.ID(), track.StreamID(), trackType); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// wait till track published message is received
|
||||
timeout := time.After(5 * time.Second)
|
||||
var ti *livekit.TrackInfo
|
||||
for {
|
||||
select {
|
||||
case <-timeout:
|
||||
return nil, errors.New("could not publish track after timeout")
|
||||
default:
|
||||
c.lock.Lock()
|
||||
ti = c.pendingPublishedTracks[track.ID()]
|
||||
c.lock.Unlock()
|
||||
if ti != nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if ti != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
c.localTracks[ti.Sid] = track
|
||||
|
||||
if _, err = c.publisher.PeerConnection().AddTrack(track); err != nil {
|
||||
return
|
||||
}
|
||||
c.publisher.Negotiate()
|
||||
writer = NewTrackWriter(c.ctx, track, path)
|
||||
|
||||
// write tracks only after ICE connectivity
|
||||
if c.iceConnected.Get() {
|
||||
err = writer.Start()
|
||||
} else {
|
||||
c.pendingTrackWriters = append(c.pendingTrackWriters, writer)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (c *RTCClient) AddStaticTrack(mime string, id string, label string) (writer *TrackWriter, err error) {
|
||||
track, err := webrtc.NewTrackLocalStaticSample(webrtc.RTPCodecCapability{MimeType: mime}, id, label)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return c.AddTrack(track, "")
|
||||
}
|
||||
|
||||
func (c *RTCClient) AddFileTrack(path string, id string, label string) (writer *TrackWriter, err error) {
|
||||
// determine file mime
|
||||
mime, ok := extMimeMapping[filepath.Ext(path)]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s has an unsupported extension", filepath.Base(path))
|
||||
}
|
||||
|
||||
logger.Debugw("adding file track",
|
||||
"mime", mime,
|
||||
)
|
||||
|
||||
track, err := webrtc.NewTrackLocalStaticSample(
|
||||
webrtc.RTPCodecCapability{MimeType: mime},
|
||||
id,
|
||||
label,
|
||||
)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return c.AddTrack(track, path)
|
||||
}
|
||||
|
||||
// send AddTrack command to server to initiate server-side negotiation
|
||||
func (c *RTCClient) SendAddTrack(cid string, name string, trackType livekit.TrackType) error {
|
||||
return c.SendRequest(&livekit.SignalRequest{
|
||||
Message: &livekit.SignalRequest_AddTrack{
|
||||
AddTrack: &livekit.AddTrackRequest{
|
||||
Cid: cid,
|
||||
Name: name,
|
||||
Type: trackType,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// handles a server initiated offer, handle on subscriber PC
|
||||
func (c *RTCClient) handleOffer(desc webrtc.SessionDescription) error {
|
||||
if err := c.subscriber.SetRemoteDescription(desc); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// if we received an offer, we'd have to answer
|
||||
answer, err := c.subscriber.PeerConnection().CreateAnswer(nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := c.subscriber.PeerConnection().SetLocalDescription(answer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// send remote an answer
|
||||
logger.Debugw("sending subscriber answer",
|
||||
"participant", c.localParticipant.Identity,
|
||||
//"sdp", answer,
|
||||
)
|
||||
return c.SendRequest(&livekit.SignalRequest{
|
||||
Message: &livekit.SignalRequest_Answer{
|
||||
Answer: rtc.ToProtoSessionDescription(answer),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// the client handles answer on the publisher PC
|
||||
func (c *RTCClient) handleAnswer(desc webrtc.SessionDescription) error {
|
||||
logger.Debugw("handling server answer", "participant", c.localParticipant.Identity)
|
||||
// remote answered the offer, establish connection
|
||||
err := c.publisher.SetRemoteDescription(desc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !c.connected.TrySet(true) {
|
||||
// already connected
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *RTCClient) onOffer(offer webrtc.SessionDescription) {
|
||||
if c.localParticipant != nil {
|
||||
logger.Debugw("starting negotiation", "participant", c.localParticipant.Identity)
|
||||
}
|
||||
_ = c.SendRequest(&livekit.SignalRequest{
|
||||
Message: &livekit.SignalRequest_Offer{
|
||||
Offer: rtc.ToProtoSessionDescription(offer),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c *RTCClient) processTrack(track *webrtc.TrackRemote) {
|
||||
lastUpdate := time.Time{}
|
||||
pId := track.StreamID()
|
||||
trackId := track.ID()
|
||||
c.lock.Lock()
|
||||
c.subscribedTracks[pId] = append(c.subscribedTracks[pId], track)
|
||||
c.lock.Unlock()
|
||||
|
||||
logger.Debugw("client added track", "participant", c.localParticipant.Identity,
|
||||
"source", pId,
|
||||
"track", trackId,
|
||||
)
|
||||
|
||||
defer func() {
|
||||
c.lock.Lock()
|
||||
c.subscribedTracks[pId] = funk.Without(c.subscribedTracks[pId], track).([]*webrtc.TrackRemote)
|
||||
c.lock.Unlock()
|
||||
}()
|
||||
|
||||
numBytes := 0
|
||||
for {
|
||||
pkt, _, err := track.ReadRTP()
|
||||
if c.ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
if rtc.IsEOF(err) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
logger.Debugw("error reading RTP", "err", err)
|
||||
continue
|
||||
}
|
||||
c.lock.Lock()
|
||||
c.lastPackets[pId] = pkt
|
||||
c.bytesReceived[pId] += uint64(pkt.MarshalSize())
|
||||
c.lock.Unlock()
|
||||
numBytes += pkt.MarshalSize()
|
||||
if time.Now().Sub(lastUpdate) > 30*time.Second {
|
||||
logger.Debugw("consumed from participant",
|
||||
"track", trackId, "participant", pId,
|
||||
"size", numBytes)
|
||||
lastUpdate = time.Now()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *RTCClient) BytesReceived() uint64 {
|
||||
var total uint64
|
||||
c.lock.Lock()
|
||||
for _, size := range c.bytesReceived {
|
||||
total += size
|
||||
}
|
||||
c.lock.Unlock()
|
||||
return total
|
||||
}
|
||||
|
||||
func (c *RTCClient) SendNacks(count int) {
|
||||
var packets []rtcp.Packet
|
||||
c.lock.Lock()
|
||||
for _, pkt := range c.lastPackets {
|
||||
seqs := make([]uint16, 0, count)
|
||||
for i := 0; i < count; i++ {
|
||||
seqs = append(seqs, pkt.SequenceNumber-uint16(i))
|
||||
}
|
||||
packets = append(packets, &rtcp.TransportLayerNack{
|
||||
MediaSSRC: pkt.SSRC,
|
||||
Nacks: rtcp.NackPairsFromSequenceNumbers(seqs),
|
||||
})
|
||||
}
|
||||
c.lock.Unlock()
|
||||
|
||||
c.subscriber.PeerConnection().WriteRTCP(packets)
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/pion/webrtc/v3"
|
||||
"github.com/pion/webrtc/v3/pkg/media"
|
||||
"github.com/pion/webrtc/v3/pkg/media/h264reader"
|
||||
"github.com/pion/webrtc/v3/pkg/media/ivfreader"
|
||||
"github.com/pion/webrtc/v3/pkg/media/oggreader"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/logger"
|
||||
)
|
||||
|
||||
// Writes a file to an RTP track.
|
||||
// makes it easier to debug and create RTP streams
|
||||
type TrackWriter struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
track *webrtc.TrackLocalStaticSample
|
||||
filePath string
|
||||
mime string
|
||||
done chan bool
|
||||
|
||||
ogg *oggreader.OggReader
|
||||
ivfheader *ivfreader.IVFFileHeader
|
||||
ivf *ivfreader.IVFReader
|
||||
h264 *h264reader.H264Reader
|
||||
}
|
||||
|
||||
func NewTrackWriter(ctx context.Context, track *webrtc.TrackLocalStaticSample, filePath string) *TrackWriter {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
return &TrackWriter{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
track: track,
|
||||
filePath: filePath,
|
||||
mime: track.Codec().MimeType,
|
||||
done: make(chan bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (w *TrackWriter) Start() error {
|
||||
if w.filePath == "" {
|
||||
go w.writeNull()
|
||||
return nil
|
||||
}
|
||||
|
||||
file, err := os.Open(w.filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Infow("starting track writer",
|
||||
"track", w.track.ID(),
|
||||
"mime", w.mime)
|
||||
switch w.mime {
|
||||
case webrtc.MimeTypeOpus:
|
||||
w.ogg, _, err = oggreader.NewWith(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
go w.writeOgg()
|
||||
case webrtc.MimeTypeVP8:
|
||||
w.ivf, w.ivfheader, err = ivfreader.NewWith(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
go w.writeVP8()
|
||||
case webrtc.MimeTypeH264:
|
||||
w.h264, err = h264reader.NewReader(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
go w.writeH264()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *TrackWriter) Stop() {
|
||||
w.cancel()
|
||||
}
|
||||
|
||||
func (w *TrackWriter) writeNull() {
|
||||
defer w.onWriteComplete()
|
||||
sample := media.Sample{Data: []byte{0x0, 0xff, 0xff, 0xff, 0xff}, Duration: 30 * time.Millisecond}
|
||||
for {
|
||||
select {
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
w.track.WriteSample(sample)
|
||||
case <-w.ctx.Done():
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *TrackWriter) writeOgg() {
|
||||
// Keep track of last granule, the difference is the amount of samples in the buffer
|
||||
var lastGranule uint64
|
||||
for {
|
||||
if w.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
pageData, pageHeader, err := w.ogg.ParseNextPage()
|
||||
if err == io.EOF {
|
||||
logger.Infow("all audio samples parsed and sent")
|
||||
w.onWriteComplete()
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Errorw("could not parse ogg page", "err", err)
|
||||
return
|
||||
}
|
||||
|
||||
// The amount of samples is the difference between the last and current timestamp
|
||||
sampleCount := float64(pageHeader.GranulePosition - lastGranule)
|
||||
lastGranule = pageHeader.GranulePosition
|
||||
sampleDuration := time.Duration((sampleCount/48000)*1000) * time.Millisecond
|
||||
|
||||
if err = w.track.WriteSample(media.Sample{Data: pageData, Duration: sampleDuration}); err != nil {
|
||||
logger.Errorw("could not write sample", "err", err)
|
||||
return
|
||||
}
|
||||
|
||||
time.Sleep(sampleDuration)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *TrackWriter) writeVP8() {
|
||||
// Send our video file frame at a time. Pace our sending so we send it at the same speed it should be played back as.
|
||||
// This isn't required since the video is timestamped, but we will such much higher loss if we send all at once.
|
||||
sleepTime := time.Millisecond * time.Duration((float32(w.ivfheader.TimebaseNumerator)/float32(w.ivfheader.TimebaseDenominator))*1000)
|
||||
for {
|
||||
if w.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
frame, _, err := w.ivf.ParseNextFrame()
|
||||
if err == io.EOF {
|
||||
logger.Infow("all video frames parsed and sent")
|
||||
w.onWriteComplete()
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Errorw("could not parse VP8 frame", "err", err)
|
||||
return
|
||||
}
|
||||
|
||||
time.Sleep(sleepTime)
|
||||
if err = w.track.WriteSample(media.Sample{Data: frame, Duration: time.Second}); err != nil {
|
||||
logger.Errorw("could not write sample", "err", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *TrackWriter) writeH264() {
|
||||
// TODO: this is harder
|
||||
}
|
||||
|
||||
func (w *TrackWriter) onWriteComplete() {
|
||||
|
||||
}
|
||||
@@ -1,247 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/twitchtv/twirp"
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"github.com/livekit/livekit-server/cmd/cli/client"
|
||||
"github.com/livekit/livekit-server/pkg/logger"
|
||||
livekit "github.com/livekit/livekit-server/proto"
|
||||
"github.com/livekit/protocol/auth"
|
||||
)
|
||||
|
||||
var (
|
||||
RoomCommands = []*cli.Command{
|
||||
{
|
||||
Name: "create-room",
|
||||
Before: createClient,
|
||||
Action: createRoom,
|
||||
Flags: []cli.Flag{
|
||||
roomHostFlag,
|
||||
&cli.StringFlag{
|
||||
Name: "name",
|
||||
Usage: "name of the room",
|
||||
Required: true,
|
||||
},
|
||||
apiKeyFlag,
|
||||
secretFlag,
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "list-rooms",
|
||||
Before: createClient,
|
||||
Action: listRooms,
|
||||
Flags: []cli.Flag{
|
||||
roomHostFlag,
|
||||
apiKeyFlag,
|
||||
secretFlag,
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "delete-room",
|
||||
Before: createClient,
|
||||
Action: deleteRoom,
|
||||
Flags: []cli.Flag{
|
||||
roomFlag,
|
||||
roomHostFlag,
|
||||
apiKeyFlag,
|
||||
secretFlag,
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "list-participants",
|
||||
Before: createClient,
|
||||
Action: listParticipants,
|
||||
Flags: []cli.Flag{
|
||||
roomFlag,
|
||||
roomHostFlag,
|
||||
apiKeyFlag,
|
||||
secretFlag,
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "get-participant",
|
||||
Before: createClient,
|
||||
Action: getParticipant,
|
||||
Flags: []cli.Flag{
|
||||
roomFlag,
|
||||
identityFlag,
|
||||
roomHostFlag,
|
||||
apiKeyFlag,
|
||||
secretFlag,
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "remove-participant",
|
||||
Before: createClient,
|
||||
Action: removeParticipant,
|
||||
Flags: []cli.Flag{
|
||||
roomFlag,
|
||||
identityFlag,
|
||||
roomHostFlag,
|
||||
apiKeyFlag,
|
||||
secretFlag,
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "mute-track",
|
||||
Before: createClient,
|
||||
Action: muteTrack,
|
||||
Flags: []cli.Flag{
|
||||
roomFlag,
|
||||
identityFlag,
|
||||
&cli.StringFlag{
|
||||
Name: "track",
|
||||
Usage: "track sid to mute",
|
||||
Required: true,
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "muted",
|
||||
Usage: "set to true to mute, false to unmute",
|
||||
},
|
||||
roomHostFlag,
|
||||
apiKeyFlag,
|
||||
secretFlag,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
roomClient livekit.RoomService
|
||||
)
|
||||
|
||||
func createClient(c *cli.Context) error {
|
||||
host := c.String("host")
|
||||
roomClient = livekit.NewRoomServiceJSONClient(host, &http.Client{})
|
||||
return nil
|
||||
}
|
||||
|
||||
func createRoom(c *cli.Context) error {
|
||||
ctx := contextWithAccessToken(c, &auth.VideoGrant{RoomCreate: true})
|
||||
room, err := roomClient.CreateRoom(ctx, &livekit.CreateRoomRequest{
|
||||
Name: c.String("name"),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
PrintJSON(room)
|
||||
return nil
|
||||
}
|
||||
|
||||
func listRooms(c *cli.Context) error {
|
||||
ctx := contextWithAccessToken(c, &auth.VideoGrant{RoomList: true})
|
||||
res, err := roomClient.ListRooms(ctx, &livekit.ListRoomsRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, rm := range res.Rooms {
|
||||
fmt.Printf("%s\t%s\n", rm.Sid, rm.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func deleteRoom(c *cli.Context) error {
|
||||
ctx := contextWithAccessToken(c, &auth.VideoGrant{RoomCreate: true})
|
||||
roomId := c.String("room")
|
||||
_, err := roomClient.DeleteRoom(ctx, &livekit.DeleteRoomRequest{
|
||||
Room: roomId,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("deleted room", roomId)
|
||||
return nil
|
||||
}
|
||||
|
||||
func listParticipants(c *cli.Context) error {
|
||||
roomName := c.String("room")
|
||||
ctx := contextWithAccessToken(c, &auth.VideoGrant{RoomAdmin: true, Room: roomName})
|
||||
res, err := roomClient.ListParticipants(ctx, &livekit.ListParticipantsRequest{
|
||||
Room: roomName,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, p := range res.Participants {
|
||||
fmt.Printf("%s (%s)\t tracks: %d\n", p.Identity, p.State.String(), len(p.Tracks))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getParticipant(c *cli.Context) error {
|
||||
roomName := c.String("room")
|
||||
identity := c.String("identity")
|
||||
ctx := contextWithAccessToken(c, &auth.VideoGrant{RoomAdmin: true, Room: roomName})
|
||||
res, err := roomClient.GetParticipant(ctx, &livekit.RoomParticipantIdentity{
|
||||
Room: roomName,
|
||||
Identity: identity,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
PrintJSON(res)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeParticipant(c *cli.Context) error {
|
||||
roomName := c.String("room")
|
||||
identity := c.String("identity")
|
||||
ctx := contextWithAccessToken(c, &auth.VideoGrant{RoomAdmin: true, Room: roomName})
|
||||
_, err := roomClient.RemoveParticipant(ctx, &livekit.RoomParticipantIdentity{
|
||||
Room: roomName,
|
||||
Identity: identity,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("successfully removed participant", identity)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func muteTrack(c *cli.Context) error {
|
||||
roomName := c.String("room")
|
||||
identity := c.String("identity")
|
||||
trackSid := c.String("track")
|
||||
ctx := contextWithAccessToken(c, &auth.VideoGrant{RoomAdmin: true, Room: roomName})
|
||||
_, err := roomClient.MutePublishedTrack(ctx, &livekit.MuteRoomTrackRequest{
|
||||
Room: roomName,
|
||||
Identity: identity,
|
||||
TrackSid: trackSid,
|
||||
Muted: c.Bool("muted"),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("muted track", trackSid)
|
||||
return nil
|
||||
}
|
||||
|
||||
func contextWithAccessToken(c *cli.Context, grant *auth.VideoGrant) context.Context {
|
||||
ctx := context.Background()
|
||||
token, err := accessToken(c, grant, "").ToJWT()
|
||||
if err != nil {
|
||||
logger.Errorw("Could not get access token", "err", err)
|
||||
}
|
||||
if token != "" {
|
||||
header := make(http.Header)
|
||||
client.SetAuthorizationToken(header, token)
|
||||
if tctx, err := twirp.WithHTTPRequestHeaders(ctx, header); err == nil {
|
||||
logger.Debugw("requesting with token")
|
||||
ctx = tctx
|
||||
} else {
|
||||
logger.Errorw("Error setting Twirp auth header", "err", err)
|
||||
}
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"github.com/livekit/livekit-server/cmd/cli/client"
|
||||
"github.com/livekit/livekit-server/pkg/logger"
|
||||
"github.com/livekit/protocol/auth"
|
||||
)
|
||||
|
||||
var (
|
||||
RTCCommands = []*cli.Command{
|
||||
{
|
||||
Name: "join",
|
||||
Action: joinRoom,
|
||||
Flags: []cli.Flag{
|
||||
rtcHostFlag,
|
||||
&cli.StringFlag{
|
||||
Name: "token",
|
||||
Usage: "access token, not required in dev mode. if passed in, ignores --api-key, --api-secret, and --identity",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "identity",
|
||||
Usage: "identity of the participant, required if token isn't passed in",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "audio",
|
||||
Usage: "an ogg file to publish upon connection",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "video",
|
||||
Usage: "an ivf file to publish upon connection",
|
||||
},
|
||||
apiKeyFlag,
|
||||
secretFlag,
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
func joinRoom(c *cli.Context) error {
|
||||
identity := c.String("identity")
|
||||
roomId := c.String("room")
|
||||
token := c.String("token")
|
||||
|
||||
// generate access token if needed
|
||||
if token == "" {
|
||||
// require roomId & name to be passed in
|
||||
if roomId == "" {
|
||||
return fmt.Errorf("--room is required")
|
||||
}
|
||||
if identity == "" {
|
||||
return fmt.Errorf("--identity is required")
|
||||
}
|
||||
// token may be nil in dev mode
|
||||
var err error
|
||||
token, err = accessToken(c, &auth.VideoGrant{
|
||||
RoomJoin: true,
|
||||
Room: roomId,
|
||||
}, identity).ToJWT()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
host := c.String("host")
|
||||
logger.Infow("connecting to Websocket signal", "host", host)
|
||||
conn, err := client.NewWebSocketConn(host, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
rc, err := client.NewRTCClient(conn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
handleSignals(rc)
|
||||
|
||||
// add tracks if needed
|
||||
audioFile := c.String("audio")
|
||||
videoFile := c.String("video")
|
||||
rc.OnConnected = func() {
|
||||
// add after connection, since we need proper publish track APIs
|
||||
if audioFile != "" {
|
||||
rc.AddFileTrack(audioFile, "audio", filepath.Base(audioFile))
|
||||
}
|
||||
if videoFile != "" {
|
||||
rc.AddFileTrack(videoFile, "video", filepath.Base(videoFile))
|
||||
}
|
||||
}
|
||||
|
||||
return rc.Run()
|
||||
}
|
||||
|
||||
func handleSignals(rc *client.RTCClient) {
|
||||
// signal to stop client
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
|
||||
|
||||
go func() {
|
||||
sig := <-sigChan
|
||||
logger.Infow("exit requested, shutting down", "signal", sig)
|
||||
rc.Stop()
|
||||
}()
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"github.com/livekit/protocol/auth"
|
||||
)
|
||||
|
||||
var (
|
||||
TokenCommands = []*cli.Command{
|
||||
{
|
||||
Name: "create-token",
|
||||
Usage: "create token for Room APIs",
|
||||
Action: createToken,
|
||||
Flags: []cli.Flag{
|
||||
apiKeyFlag,
|
||||
secretFlag,
|
||||
&cli.BoolFlag{
|
||||
Name: "join",
|
||||
Usage: "enable token to be used to join a room",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "create",
|
||||
Usage: "enable token to be used to create rooms",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "admin",
|
||||
Usage: "enable token to be used to manage a room",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "participant",
|
||||
Aliases: []string{"p"},
|
||||
Usage: "unique name of the participant, used with --join",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "room",
|
||||
Aliases: []string{"r"},
|
||||
Usage: "name of the room to join, empty to allow joining all rooms",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "metadata",
|
||||
Usage: "JSON metadata to encode in the token, will be passed to participant",
|
||||
},
|
||||
devFlag,
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
func createToken(c *cli.Context) error {
|
||||
if !c.IsSet("api-key") || !c.IsSet("api-secret") {
|
||||
return fmt.Errorf("api-key and api-secret are required")
|
||||
}
|
||||
p := c.String("participant") // required only for join
|
||||
room := c.String("room")
|
||||
metadata := c.String("metadata")
|
||||
|
||||
grant := &auth.VideoGrant{}
|
||||
if c.Bool("create") {
|
||||
grant.RoomCreate = true
|
||||
}
|
||||
if c.Bool("join") {
|
||||
grant.RoomJoin = true
|
||||
grant.Room = room
|
||||
if p == "" {
|
||||
return fmt.Errorf("participant name is required")
|
||||
}
|
||||
}
|
||||
if c.Bool("admin") {
|
||||
grant.RoomAdmin = true
|
||||
grant.Room = room
|
||||
}
|
||||
|
||||
if !grant.RoomJoin && !grant.RoomCreate && !grant.RoomAdmin {
|
||||
return fmt.Errorf("one of --join, --create, or --admin is required")
|
||||
}
|
||||
|
||||
at := accessToken(c, grant, p)
|
||||
|
||||
if metadata != "" {
|
||||
at.SetMetadata(metadata)
|
||||
}
|
||||
|
||||
token, err := at.ToJWT()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("access token: ", token)
|
||||
return nil
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"github.com/livekit/protocol/auth"
|
||||
)
|
||||
|
||||
var (
|
||||
roomFlag = &cli.StringFlag{
|
||||
Name: "room",
|
||||
Usage: "name or id of the room",
|
||||
Required: true,
|
||||
}
|
||||
roomHostFlag = &cli.StringFlag{
|
||||
Name: "host",
|
||||
Value: "http://localhost:7880",
|
||||
}
|
||||
rtcHostFlag = &cli.StringFlag{
|
||||
Name: "host",
|
||||
Value: "ws://localhost:7880",
|
||||
}
|
||||
apiKeyFlag = &cli.StringFlag{
|
||||
Name: "api-key",
|
||||
EnvVars: []string{"LIVEKIT_API_KEY"},
|
||||
Required: true,
|
||||
}
|
||||
secretFlag = &cli.StringFlag{
|
||||
Name: "api-secret",
|
||||
EnvVars: []string{"LIVEKIT_API_SECRET"},
|
||||
Required: true,
|
||||
}
|
||||
identityFlag = &cli.StringFlag{
|
||||
Name: "identity",
|
||||
Usage: "identity of participant",
|
||||
Required: true,
|
||||
}
|
||||
devFlag = &cli.BoolFlag{
|
||||
Name: "dev",
|
||||
Usage: "enables dev mode, longer expiration for tokens",
|
||||
}
|
||||
)
|
||||
|
||||
func PrintJSON(obj interface{}) {
|
||||
txt, _ := json.MarshalIndent(obj, "", " ")
|
||||
fmt.Println(string(txt))
|
||||
}
|
||||
|
||||
func ExpandUser(p string) string {
|
||||
if strings.HasPrefix(p, "~") {
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, p[1:])
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
func accessToken(c *cli.Context, grant *auth.VideoGrant, identity string) *auth.AccessToken {
|
||||
apiKey := c.String("api-key")
|
||||
apiSecret := c.String("api-secret")
|
||||
if apiKey == "" && apiSecret == "" {
|
||||
// not provided, don't sign request
|
||||
return nil
|
||||
}
|
||||
|
||||
isDev := c.Bool("dev")
|
||||
|
||||
at := auth.NewAccessToken(apiKey, apiSecret).
|
||||
AddGrant(grant).
|
||||
SetIdentity(identity)
|
||||
if isDev {
|
||||
fmt.Println("creating dev token")
|
||||
at.SetValidFor(time.Hour * 24 * 30)
|
||||
}
|
||||
return at
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"github.com/livekit/livekit-server/cmd/cli/commands"
|
||||
"github.com/livekit/livekit-server/pkg/logger"
|
||||
)
|
||||
|
||||
// command line util that tests server
|
||||
func main() {
|
||||
app := &cli.App{
|
||||
Name: "livekit-cli",
|
||||
}
|
||||
|
||||
app.Commands = append(app.Commands, commands.RoomCommands...)
|
||||
app.Commands = append(app.Commands, commands.RTCCommands...)
|
||||
app.Commands = append(app.Commands, commands.TokenCommands...)
|
||||
|
||||
logger.InitDevelopment("")
|
||||
if err := app.Run(os.Args); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/livekit/protocol/auth"
|
||||
"github.com/livekit/protocol/utils"
|
||||
"github.com/urfave/cli/v2"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func generateKeys(c *cli.Context) error {
|
||||
apiKey := utils.NewGuid(utils.APIKeyPrefix)
|
||||
secret := utils.RandomSecret()
|
||||
fmt.Println("API Key: ", apiKey)
|
||||
fmt.Println("Secret Key: ", secret)
|
||||
return nil
|
||||
}
|
||||
|
||||
func printPorts(c *cli.Context) error {
|
||||
conf, err := getConfig(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
udpPorts := make([]string, 0)
|
||||
tcpPorts := make([]string, 0)
|
||||
|
||||
tcpPorts = append(tcpPorts, fmt.Sprintf("%d - HTTP service", conf.Port))
|
||||
if conf.RTC.TCPPort != 0 {
|
||||
tcpPorts = append(tcpPorts, fmt.Sprintf("%d - ICE/TCP", conf.RTC.TCPPort))
|
||||
}
|
||||
if conf.RTC.UDPPort != 0 {
|
||||
udpPorts = append(udpPorts, fmt.Sprintf("%d - ICE/UDP", conf.RTC.UDPPort))
|
||||
} else {
|
||||
udpPorts = append(udpPorts, fmt.Sprintf("%d-%d - ICE/UDP range", conf.RTC.ICEPortRangeStart, conf.RTC.ICEPortRangeEnd))
|
||||
}
|
||||
|
||||
if conf.TURN.Enabled {
|
||||
udpPorts = append(udpPorts, fmt.Sprintf("%d-%d", conf.TURN.PortRangeStart, conf.TURN.PortRangeEnd))
|
||||
udpPorts = append(udpPorts, strconv.Itoa(conf.TURN.TCPPort))
|
||||
tcpPorts = append(tcpPorts, strconv.Itoa(conf.TURN.TCPPort))
|
||||
}
|
||||
|
||||
fmt.Println("TCP Ports")
|
||||
for _, p := range tcpPorts {
|
||||
fmt.Println(p)
|
||||
}
|
||||
|
||||
fmt.Println("UDP Ports")
|
||||
for _, p := range udpPorts {
|
||||
fmt.Println(p)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createToken(c *cli.Context) error {
|
||||
room := c.String("room")
|
||||
identity := c.String("identity")
|
||||
|
||||
conf, err := getConfig(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// use the first API key from config
|
||||
if len(conf.Keys) == 0 {
|
||||
// try to load from file
|
||||
if _, err := os.Stat(conf.KeyFile); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.Open(conf.KeyFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
}()
|
||||
decoder := yaml.NewDecoder(f)
|
||||
if err = decoder.Decode(conf.Keys); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(conf.Keys) == 0 {
|
||||
return fmt.Errorf("keys are not configured")
|
||||
}
|
||||
}
|
||||
|
||||
var apiKey string
|
||||
var apiSecret string
|
||||
for k, v := range conf.Keys {
|
||||
apiKey = k
|
||||
apiSecret = v
|
||||
break
|
||||
}
|
||||
|
||||
grant := &auth.VideoGrant{
|
||||
RoomJoin: true,
|
||||
Room: room,
|
||||
}
|
||||
at := auth.NewAccessToken(apiKey, apiSecret).
|
||||
AddGrant(grant).
|
||||
SetIdentity(identity).
|
||||
SetValidFor(30 * 24 * time.Hour)
|
||||
|
||||
token, err := at.ToJWT()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("Token:", token)
|
||||
|
||||
return nil
|
||||
}
|
||||
+38
-56
@@ -9,7 +9,6 @@ import (
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"runtime/pprof"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -23,7 +22,6 @@ import (
|
||||
"github.com/livekit/livekit-server/pkg/service"
|
||||
"github.com/livekit/livekit-server/version"
|
||||
"github.com/livekit/protocol/auth"
|
||||
"github.com/livekit/protocol/utils"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -83,6 +81,23 @@ func main() {
|
||||
Usage: "print ports that server is configured to use",
|
||||
Action: printPorts,
|
||||
},
|
||||
{
|
||||
Name: "create-join-token",
|
||||
Usage: "create a room join token for development use",
|
||||
Action: createToken,
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "room",
|
||||
Usage: "name of room to join",
|
||||
Required: true,
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "identity",
|
||||
Usage: "identity of participant that holds the token",
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Version: version.Version,
|
||||
}
|
||||
@@ -92,26 +107,34 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
func getConfig(c *cli.Context) (*config.Config, error) {
|
||||
confString, err := getConfigString(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
conf, err := config.NewConfig(confString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = conf.UpdateFromCLI(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return conf, nil
|
||||
}
|
||||
|
||||
func startServer(c *cli.Context) error {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
cpuProfile := c.String("cpuprofile")
|
||||
memProfile := c.String("memprofile")
|
||||
|
||||
confString, err := getConfigString(c)
|
||||
conf, err := getConfig(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
conf, err := config.NewConfig(confString)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = conf.UpdateFromCLI(c); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if conf.Development {
|
||||
logger.InitDevelopment(conf.LogLevel)
|
||||
} else {
|
||||
@@ -216,7 +239,9 @@ func createKeyProvider(conf *config.Config) (auth.KeyProvider, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
}()
|
||||
return auth.NewFileBasedKeyProviderFromReader(f)
|
||||
}
|
||||
|
||||
@@ -241,46 +266,3 @@ func getConfigString(c *cli.Context) (string, error) {
|
||||
}
|
||||
return configBody, nil
|
||||
}
|
||||
|
||||
func generateKeys(c *cli.Context) error {
|
||||
apiKey := utils.NewGuid(utils.APIKeyPrefix)
|
||||
secret := utils.RandomSecret()
|
||||
fmt.Println("API Key: ", apiKey)
|
||||
fmt.Println("Secret Key: ", secret)
|
||||
return nil
|
||||
}
|
||||
|
||||
func printPorts(c *cli.Context) error {
|
||||
confString, err := getConfigString(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
conf, err := config.NewConfig(confString)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
udpPorts := make([]string, 0)
|
||||
tcpPorts := make([]string, 0)
|
||||
|
||||
tcpPorts = append(tcpPorts, strconv.Itoa(int(conf.Port)))
|
||||
udpPorts = append(udpPorts, fmt.Sprintf("%d-%d", conf.RTC.ICEPortRangeStart, conf.RTC.ICEPortRangeEnd))
|
||||
|
||||
if conf.TURN.Enabled {
|
||||
udpPorts = append(udpPorts, fmt.Sprintf("%d-%d", conf.TURN.PortRangeStart, conf.TURN.PortRangeEnd))
|
||||
udpPorts = append(udpPorts, strconv.Itoa(conf.TURN.TCPPort))
|
||||
tcpPorts = append(tcpPorts, strconv.Itoa(conf.TURN.TCPPort))
|
||||
}
|
||||
|
||||
fmt.Println("TCP Ports")
|
||||
for _, p := range tcpPorts {
|
||||
fmt.Println(p)
|
||||
}
|
||||
|
||||
fmt.Println("UDP Ports")
|
||||
for _, p := range udpPorts {
|
||||
fmt.Println(p)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user