WHIP support. (#3692)

* WHIP support.

WHIP like signalling with added support for data channels.

* clean up

* Paul feedback

* deps
This commit is contained in:
Raja Subramanian
2025-06-03 08:23:37 -07:00
committed by GitHub
parent e4f7d81bdd
commit 1b760393bc
11 changed files with 856 additions and 100 deletions
+28 -24
View File
@@ -99,7 +99,7 @@ type Room struct {
protoRoom *livekit.Room
internal *livekit.RoomInternal
protoProxy *utils.ProtoProxy[*livekit.Room]
Logger logger.Logger
logger logger.Logger
config WebRTCConfig
audioConfig *sfu.AudioConfig
@@ -241,7 +241,7 @@ func NewRoom(
r := &Room{
protoRoom: utils.CloneProto(room),
internal: internal,
Logger: LoggerWithRoom(
logger: LoggerWithRoom(
logger.GetLogger().WithComponent(sutils.ComponentRoom),
livekit.RoomName(room.Name),
livekit.RoomID(room.Sid),
@@ -294,6 +294,10 @@ func NewRoom(
return r
}
func (r *Room) Logger() logger.Logger {
return r.logger
}
func (r *Room) ToProto() *livekit.Room {
return r.protoProxy.Get()
}
@@ -527,7 +531,7 @@ func (r *Room) Join(participant types.LocalParticipant, requestSource routing.Me
r.launchTargetAgents(maps.Values(r.agentDispatches), participant, livekit.JobType_JT_PARTICIPANT)
r.Logger.Debugw("new participant joined",
r.logger.Debugw("new participant joined",
"pID", participant.ID(),
"participant", participant.Identity(),
"clientInfo", logger.Proto(participant.GetClientInfo()),
@@ -728,7 +732,7 @@ func (r *Room) RemoveParticipant(identity livekit.ParticipantIdentity, pID livek
go func() {
_, err := r.agentClient.TerminateJob(context.Background(), agentJob.Id, rpc.JobTerminateReason_AGENT_LEFT_ROOM)
if err != nil {
r.Logger.Infow("failed sending TerminateJob RPC", "error", err, "jobID", agentJob.Id, "participant", identity)
r.logger.Infow("failed sending TerminateJob RPC", "error", err, "jobID", agentJob.Id, "participant", identity)
}
}()
}
@@ -914,7 +918,7 @@ func (r *Room) CloseIfEmpty() {
if elapsed >= int64(timeout) {
r.Close(types.ParticipantCloseReasonRoomClosed)
r.Logger.Infow("closing idle room", "reason", reason)
r.logger.Infow("closing idle room", "reason", reason)
}
}
@@ -930,7 +934,7 @@ func (r *Room) Close(reason types.ParticipantCloseReason) {
close(r.closed)
r.lock.Unlock()
r.Logger.Infow("closing room")
r.logger.Infow("closing room")
for _, p := range r.GetParticipants() {
_ = p.Close(true, reason, false)
}
@@ -971,7 +975,7 @@ func (r *Room) sendRoomUpdate() {
err := p.SendRoomUpdate(roomInfo)
if err != nil {
r.Logger.Warnw("failed to send room update", err, "participant", p.Identity())
r.logger.Warnw("failed to send room update", err, "participant", p.Identity())
}
}
}
@@ -1049,7 +1053,7 @@ func (r *Room) DeleteAgentDispatch(dispatchID string) (*livekit.AgentDispatch, e
if agentJob != nil {
err := agentJob.waitForParticipantLeaving()
if err == ErrJobShutdownTimeout {
r.Logger.Infow("Agent Worker did not disconnect after 3s")
r.logger.Infow("Agent Worker did not disconnect after 3s")
}
}
r.RemoveParticipant(p.Identity(), p.ID(), types.ParticipantCloseReasonServiceRequestRemoveParticipant)
@@ -1071,7 +1075,7 @@ func (r *Room) OnRoomUpdated(f func()) {
func (r *Room) SimulateScenario(participant types.LocalParticipant, simulateScenario *livekit.SimulateScenario) error {
switch scenario := simulateScenario.Scenario.(type) {
case *livekit.SimulateScenario_SpeakerUpdate:
r.Logger.Infow("simulating speaker update", "participant", participant.Identity(), "duration", scenario.SpeakerUpdate)
r.logger.Infow("simulating speaker update", "participant", participant.Identity(), "duration", scenario.SpeakerUpdate)
go func() {
<-time.After(time.Duration(scenario.SpeakerUpdate) * time.Second)
r.sendSpeakerChanges([]*livekit.SpeakerInfo{{
@@ -1086,33 +1090,33 @@ func (r *Room) SimulateScenario(participant types.LocalParticipant, simulateScen
Level: 0.9,
}})
case *livekit.SimulateScenario_Migration:
r.Logger.Infow("simulating migration", "participant", participant.Identity())
r.logger.Infow("simulating migration", "participant", participant.Identity())
// drop participant without necessarily cleaning up
if err := participant.Close(false, types.ParticipantCloseReasonSimulateMigration, true); err != nil {
return err
}
case *livekit.SimulateScenario_NodeFailure:
r.Logger.Infow("simulating node failure", "participant", participant.Identity())
r.logger.Infow("simulating node failure", "participant", participant.Identity())
// drop participant without necessarily cleaning up
if err := participant.Close(false, types.ParticipantCloseReasonSimulateNodeFailure, true); err != nil {
return err
}
case *livekit.SimulateScenario_ServerLeave:
r.Logger.Infow("simulating server leave", "participant", participant.Identity())
r.logger.Infow("simulating server leave", "participant", participant.Identity())
if err := participant.Close(true, types.ParticipantCloseReasonSimulateServerLeave, false); err != nil {
return err
}
case *livekit.SimulateScenario_SwitchCandidateProtocol:
r.Logger.Infow("simulating switch candidate protocol", "participant", participant.Identity())
r.logger.Infow("simulating switch candidate protocol", "participant", participant.Identity())
participant.ICERestart(&livekit.ICEConfig{
PreferenceSubscriber: livekit.ICECandidateType(scenario.SwitchCandidateProtocol),
PreferencePublisher: livekit.ICECandidateType(scenario.SwitchCandidateProtocol),
})
case *livekit.SimulateScenario_SubscriberBandwidth:
if scenario.SubscriberBandwidth > 0 {
r.Logger.Infow("simulating subscriber bandwidth start", "participant", participant.Identity(), "bandwidth", scenario.SubscriberBandwidth)
r.logger.Infow("simulating subscriber bandwidth start", "participant", participant.Identity(), "bandwidth", scenario.SubscriberBandwidth)
} else {
r.Logger.Infow("simulating subscriber bandwidth end", "participant", participant.Identity())
r.logger.Infow("simulating subscriber bandwidth end", "participant", participant.Identity())
}
participant.SetSubscriberChannelCapacity(scenario.SubscriberBandwidth)
case *livekit.SimulateScenario_DisconnectSignalOnResume:
@@ -1189,7 +1193,7 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.
continue
}
r.Logger.Debugw("subscribing to new track",
r.logger.Debugw("subscribing to new track",
"participant", existingParticipant.Identity(),
"pID", existingParticipant.ID(),
"publisher", participant.Identity(),
@@ -1227,7 +1231,7 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.
r.Name(),
r.ID(),
); err != nil {
r.Logger.Errorw("failed to launch participant egress", err)
r.logger.Errorw("failed to launch participant egress", err)
}
}()
}
@@ -1243,7 +1247,7 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.
r.Name(),
r.ID(),
); err != nil {
r.Logger.Errorw("failed to launch track egress", err)
r.logger.Errorw("failed to launch track egress", err)
}
}()
}
@@ -1277,15 +1281,15 @@ func (r *Room) onParticipantUpdate(p types.LocalParticipant) {
}
func (r *Room) onDataPacket(source types.LocalParticipant, kind livekit.DataPacket_Kind, dp *livekit.DataPacket) {
BroadcastDataPacketForRoom(r, source, kind, dp, r.Logger)
BroadcastDataPacketForRoom(r, source, kind, dp, r.logger)
}
func (r *Room) onDataMessage(source types.LocalParticipant, data []byte) {
BroadcastDataMessageForRoom(r, source, data, r.Logger)
BroadcastDataMessageForRoom(r, source, data, r.logger)
}
func (r *Room) onMetrics(source types.Participant, dp *livekit.DataPacket) {
BroadcastMetricsForRoom(r, source, dp, r.Logger)
BroadcastMetricsForRoom(r, source, dp, r.logger)
}
func (r *Room) subscribeToExistingTracks(p types.LocalParticipant) {
@@ -1310,7 +1314,7 @@ func (r *Room) subscribeToExistingTracks(p types.LocalParticipant) {
}
}
if len(trackIDs) > 0 {
r.Logger.Debugw("subscribed participant to existing tracks", "trackID", trackIDs)
r.logger.Debugw("subscribed participant to existing tracks", "trackID", trackIDs)
}
}
@@ -1520,7 +1524,7 @@ func (r *Room) connectionQualityWorker() {
continue
}
if err := op.SendConnectionQualityUpdate(update); err != nil {
r.Logger.Warnw("could not send connection quality update", err,
r.logger.Warnw("could not send connection quality update", err,
"participant", op.Identity())
}
}
@@ -1670,7 +1674,7 @@ func (r *Room) createAgentDispatchesFromRoomAgent() {
for _, ag := range roomDisp {
_, err := r.createAgentDispatchFromParams(ag.AgentName, ag.Metadata)
if err != nil {
r.Logger.Warnw("failed storing room dispatch", err)
r.logger.Warnw("failed storing room dispatch", err)
}
}
}
-1
View File
@@ -1064,7 +1064,6 @@ func (t *PCTransport) CreateReadableDataChannel(label string, dci *webrtc.DataCh
buffer := make([]byte, dataChannelBufferSize)
for {
n, _, err := rawDC.ReadDataChannel(buffer)
t.params.Logger.Infow("RAJA read data", "data", string(buffer[:n])) // REMVOE
if err != nil {
if !errors.Is(err, io.EOF) && !strings.Contains(err.Error(), "state=Closed") {
t.params.Logger.Warnw("error reading data channel", err, "label", dc.Label())
+37 -13
View File
@@ -70,6 +70,7 @@ type RoomManager struct {
router routing.Router
roomAllocator RoomAllocator
roomManagerServer rpc.TypedRoomManagerServer
rtcRestServer rpc.RTCRestServer[livekit.NodeID]
roomStore ObjectStore
telemetry telemetry.TelemetryService
clientConfManager clientconfiguration.ClientConfigurationManager
@@ -82,9 +83,10 @@ type RoomManager struct {
rooms map[livekit.RoomName]*rtc.Room
roomServers utils.MultitonService[rpc.RoomTopic]
agentDispatchServers utils.MultitonService[rpc.RoomTopic]
participantServers utils.MultitonService[rpc.ParticipantTopic]
roomServers utils.MultitonService[rpc.RoomTopic]
agentDispatchServers utils.MultitonService[rpc.RoomTopic]
participantServers utils.MultitonService[rpc.ParticipantTopic]
rtcRestParticipantServers utils.MultitonService[rpc.ParticipantTopic]
iceConfigCache *sutils.IceConfigCache[iceConfigCacheKey]
@@ -151,6 +153,14 @@ func NewLocalRoomManager(
return nil, err
}
r.rtcRestServer, err = rpc.NewRTCRestServer[livekit.NodeID](rtcRestService{r}, bus, rpc.WithDefaultServerOptions(conf.PSRPC, logger.GetLogger()))
if err != nil {
return nil, err
}
if err := r.rtcRestServer.RegisterAllCommonTopics(currentNode.NodeID()); err != nil {
return nil, err
}
return r, nil
}
@@ -222,9 +232,11 @@ func (r *RoomManager) Stop() {
}
r.roomManagerServer.Kill()
r.rtcRestServer.Kill()
r.roomServers.Kill()
r.agentDispatchServers.Kill()
r.participantServers.Kill()
r.rtcRestParticipantServers.Kill()
if r.rtcConfig != nil {
if r.rtcConfig.UDPMux != nil {
@@ -480,16 +492,28 @@ func (r *RoomManager) StartSession(
return err
}
var participantServerClosers utils.Closers
participantTopic := rpc.FormatParticipantTopic(room.Name(), participant.Identity())
participantServer := must.Get(rpc.NewTypedParticipantServer(r, r.bus))
killParticipantServer := r.participantServers.Replace(participantTopic, participantServer)
participantServerClosers = append(participantServerClosers, utils.CloseFunc(r.participantServers.Replace(participantTopic, participantServer)))
if err := participantServer.RegisterAllParticipantTopics(participantTopic); err != nil {
killParticipantServer()
participantServerClosers.Close()
pLogger.Errorw("could not join register participant topic", err)
_ = participant.Close(true, types.ParticipantCloseReasonMessageBusFailed, false)
return err
}
if useOneShotSignallingMode {
rtcRestParticipantServer := must.Get(rpc.NewTypedRTCRestParticipantServer(rtcRestParticipantService{r}, r.bus))
participantServerClosers = append(participantServerClosers, utils.CloseFunc(r.rtcRestParticipantServers.Replace(participantTopic, rtcRestParticipantServer)))
if err := rtcRestParticipantServer.RegisterAllCommonTopics(participantTopic); err != nil {
participantServerClosers.Close()
pLogger.Errorw("could not join register participant topic for rtc rest participant server", err)
_ = participant.Close(true, types.ParticipantCloseReasonMessageBusFailed, false)
return err
}
}
if err = r.roomStore.StoreParticipant(ctx, room.Name(), participant.ToProto()); err != nil {
pLogger.Errorw("could not store participant", err)
}
@@ -509,7 +533,7 @@ func (r *RoomManager) StartSession(
clientMeta := &livekit.AnalyticsClientMeta{Region: r.currentNode.Region(), Node: string(r.currentNode.NodeID())}
r.telemetry.ParticipantJoined(ctx, protoRoom, participant.ToProto(), pi.Client, clientMeta, true)
participant.OnClose(func(p types.LocalParticipant) {
killParticipantServer()
participantServerClosers.Close()
if err := r.roomStore.DeleteParticipant(ctx, room.Name(), p.Identity()); err != nil {
pLogger.Errorw("could not delete participant", err)
@@ -594,22 +618,22 @@ func (r *RoomManager) getOrCreateRoom(ctx context.Context, createRoom *livekit.C
r.telemetry.RoomEnded(ctx, roomInfo)
prometheus.RoomEnded(time.Unix(roomInfo.CreationTime, 0))
if err := r.deleteRoom(ctx, roomName); err != nil {
newRoom.Logger.Errorw("could not delete room", err)
newRoom.Logger().Errorw("could not delete room", err)
}
newRoom.Logger.Infow("room closed")
newRoom.Logger().Infow("room closed")
})
newRoom.OnRoomUpdated(func() {
if err := r.roomStore.StoreRoom(ctx, newRoom.ToProto(), newRoom.Internal()); err != nil {
newRoom.Logger.Errorw("could not handle metadata update", err)
newRoom.Logger().Errorw("could not handle metadata update", err)
}
})
newRoom.OnParticipantChanged(func(p types.LocalParticipant) {
if !p.IsDisconnected() {
if err := r.roomStore.StoreParticipant(ctx, roomName, p.ToProto()); err != nil {
newRoom.Logger.Errorw("could not handle participant change", err)
newRoom.Logger().Errorw("could not handle participant change", err)
}
}
})
@@ -787,7 +811,7 @@ func (r *RoomManager) DeleteRoom(ctx context.Context, req *livekit.DeleteRoomReq
return nil, err
}
} else {
room.Logger.Infow("deleting room")
room.Logger().Infow("deleting room")
room.Close(types.ParticipantCloseReasonServiceRequestDeleteRoom)
}
return &livekit.DeleteRoomResponse{}, nil
@@ -815,7 +839,7 @@ func (r *RoomManager) SendData(ctx context.Context, req *livekit.SendDataRequest
return nil, ErrRoomNotFound
}
room.Logger.Debugw("api send data", "size", len(req.Data))
room.Logger().Debugw("api send data", "size", len(req.Data))
room.SendDataPacket(&livekit.DataPacket{
Kind: req.Kind,
DestinationIdentities: req.DestinationIdentities,
@@ -838,7 +862,7 @@ func (r *RoomManager) UpdateRoomMetadata(ctx context.Context, req *livekit.Updat
return nil, ErrRoomNotFound
}
room.Logger.Debugw("updating room")
room.Logger().Debugw("updating room")
done := room.SetMetadata(req.Metadata)
// wait till the update is applied
<-done
+189
View File
@@ -0,0 +1,189 @@
package service
import (
"context"
"fmt"
"time"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/rpc"
"github.com/livekit/psrpc"
"github.com/pion/webrtc/v4"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/emptypb"
)
type rtcRestService struct {
*RoomManager
}
func (s rtcRestService) Create(ctx context.Context, req *rpc.RTCRestCreateRequest) (*rpc.RTCRestCreateResponse, error) {
pi, err := routing.ParticipantInitFromStartSession(req.StartSession, s.RoomManager.currentNode.Region())
if err != nil {
logger.Errorw("rtcRest service: could not create participant init", err)
return nil, err
}
prometheus.IncrementParticipantRtcInit(1)
if err = s.RoomManager.StartSession(
ctx,
*pi,
routing.NewNullMessageSource(livekit.ConnectionID(req.StartSession.ConnectionId)), // no requestSource
routing.NewNullMessageSink(livekit.ConnectionID(req.StartSession.ConnectionId)), // no responseSink
true, // useOneShotSignallingMode
); err != nil {
logger.Errorw("rtcRest service: could not start session", err)
return nil, err
}
room := s.RoomManager.GetRoom(ctx, livekit.RoomName(req.StartSession.RoomName))
if room == nil {
logger.Errorw("rtcRest service: could not find room", nil, "room", req.StartSession.RoomName)
return nil, ErrRoomNotFound
}
lp := room.GetParticipant(pi.Identity)
if lp == nil {
room.Logger().Errorw("rtcRest service: could not find local participant", nil, "participant", pi.Identity)
return nil, ErrParticipantNotFound
}
if err := lp.HandleOffer(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer, SDP: req.OfferSdp}); err != nil {
lp.GetLogger().Errorw("rtcRest service: could not handle offer", err)
return nil, err
}
// wait for subscriptions to resolve
eg, _ := errgroup.WithContext(ctx)
for publisherIdentity, trackList := range req.SubscribedParticipantTracks {
for _, trackName := range trackList.TrackNames {
eg.Go(func() error {
for {
if lp.IsTrackNameSubscribed(livekit.ParticipantIdentity(publisherIdentity), trackName) {
return nil
}
time.Sleep(50 * time.Millisecond)
}
})
}
}
err = eg.Wait()
if err != nil {
lp.GetLogger().Errorw("rtcRest service: could not subscribe to tracks", err)
return nil, err
}
answer, err := lp.GetAnswer()
if err != nil {
lp.GetLogger().Errorw("rtcRest service: could not get answer", err)
return nil, err
}
iceSessionID, err := lp.GetPublisherICESessionUfrag()
if err != nil {
lp.GetLogger().Errorw("rtcRest service: could not get ICE session ID", err)
return nil, err
}
var iceServers []*livekit.ICEServer
apiKey, _, err := s.RoomManager.getFirstKeyPair()
if err != nil {
iceServers = s.RoomManager.iceServersForParticipant(
apiKey,
lp,
false,
)
}
return &rpc.RTCRestCreateResponse{
AnswerSdp: answer.SDP,
ParticipantId: string(lp.ID()),
IceServers: iceServers,
IceSessionId: iceSessionID,
}, nil
}
type rtcRestParticipantService struct {
*RoomManager
}
func (r rtcRestParticipantService) ICETrickle(ctx context.Context, req *rpc.RTCRestParticipantICETrickleRequest) (*emptypb.Empty, error) {
room := r.RoomManager.GetRoom(ctx, livekit.RoomName(req.Room))
if room == nil {
return nil, ErrRoomNotFound
}
lp := room.GetParticipantByID(livekit.ParticipantID(req.ParticipantId))
if lp == nil {
return nil, ErrParticipantNotFound
}
iceSessionID, err := lp.GetPublisherICESessionUfrag()
if err != nil {
lp.GetLogger().Warnw("rtcRestParticipant service ice-trickle: could not get ICE session ufrag", err)
return nil, psrpc.NewError(psrpc.Internal, err)
}
if req.IceSessionId != iceSessionID {
return nil, psrpc.NewError(
psrpc.FailedPrecondition,
fmt.Errorf("ice session mismatch, expected: %s, got: %s", iceSessionID, req.IceSessionId),
)
}
if err := lp.HandleICETrickleSDPFragment(req.SdpFragment); err != nil {
return nil, psrpc.NewError(psrpc.InvalidArgument, err)
}
return &emptypb.Empty{}, nil
}
func (r rtcRestParticipantService) ICERestart(ctx context.Context, req *rpc.RTCRestParticipantICERestartRequest) (*rpc.RTCRestParticipantICERestartResponse, error) {
room := r.RoomManager.GetRoom(ctx, livekit.RoomName(req.Room))
if room == nil {
return nil, ErrRoomNotFound
}
lp := room.GetParticipantByID(livekit.ParticipantID(req.ParticipantId))
if lp == nil {
return nil, ErrParticipantNotFound
}
sdpFragment, err := lp.HandleICERestartSDPFragment(req.SdpFragment)
if err != nil {
return nil, psrpc.NewError(psrpc.InvalidArgument, err)
}
iceSessionID, err := lp.GetPublisherICESessionUfrag()
if err != nil {
lp.GetLogger().Warnw("rtcRestParticipant service ice-restart: could not get ICE session ufrag", err)
return nil, psrpc.NewError(psrpc.Internal, err)
}
return &rpc.RTCRestParticipantICERestartResponse{
IceSessionId: iceSessionID,
SdpFragment: sdpFragment,
}, nil
}
func (r rtcRestParticipantService) DeleteSession(ctx context.Context, req *rpc.RTCRestParticipantDeleteSessionRequest) (*emptypb.Empty, error) {
room := r.RoomManager.GetRoom(ctx, livekit.RoomName(req.Room))
if room == nil {
return nil, ErrRoomNotFound
}
lp := room.GetParticipantByID(livekit.ParticipantID(req.ParticipantId))
if lp != nil {
room.RemoveParticipant(
lp.Identity(),
lp.ID(),
types.ParticipantCloseReasonClientRequestLeave,
)
}
return &emptypb.Empty{}, nil
}
+527
View File
@@ -0,0 +1,527 @@
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package service
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/pkg/rtc/types"
sutils "github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/rpc"
"github.com/livekit/protocol/utils/guid"
"github.com/livekit/psrpc"
"github.com/pion/webrtc/v4"
"github.com/tomnomnom/linkheader"
)
const (
cParticipantPath = "/whip/v1"
cParticipantIDPath = "/whip/v1/{participant_id}"
)
type RTCRestService struct {
http.Handler
config *config.Config
router routing.Router
roomAllocator RoomAllocator
client rpc.RTCRestClient[livekit.NodeID]
topicFormatter rpc.TopicFormatter
participantClient rpc.TypedRTCRestParticipantClient
}
func NewRTCRestService(
config *config.Config,
router routing.Router,
roomAllocator RoomAllocator,
clientParams rpc.ClientParams,
topicFormatter rpc.TopicFormatter,
participantClient rpc.TypedRTCRestParticipantClient,
) (*RTCRestService, error) {
client, err := rpc.NewRTCRestClient[livekit.NodeID](clientParams.Args())
if err != nil {
return nil, err
}
return &RTCRestService{
config: config,
router: router,
roomAllocator: roomAllocator,
client: client,
topicFormatter: topicFormatter,
participantClient: participantClient,
}, nil
}
func (s *RTCRestService) SetupRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET "+cParticipantPath, s.handleGet)
mux.HandleFunc("OPTIONS "+cParticipantPath, s.handleOptions)
mux.HandleFunc("POST "+cParticipantPath, s.handleCreate)
mux.HandleFunc("GET "+cParticipantIDPath, s.handleParticipantGet)
mux.HandleFunc("PATCH "+cParticipantIDPath, s.handleParticipantPatch)
mux.HandleFunc("DELETE "+cParticipantIDPath, s.handleParticipantDelete)
}
func (s *RTCRestService) handleGet(w http.ResponseWriter, r *http.Request) {
// https:/www.rfc-editor.org/rfc/rfc9725.html#name-http-usage
w.WriteHeader(http.StatusNoContent)
}
func (s *RTCRestService) handleOptions(w http.ResponseWriter, r *http.Request) {
logger.Infow("RAJA got here to options", "req", r) // REMOVE
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Access-Control-Allow-Methods", "PATCH, OPTIONS, GET, POST, DELETE")
w.Header().Set("Access-Control-Expose-Headers", "*")
w.WriteHeader(http.StatusOK)
// According to https://www.rfc-editor.org/rfc/rfc9725.html#name-stun-turn-server-configurat,
// ICE servers can be returned in OPTIONS response, but not recommended.
//
// Supporting that here is tricky. This would have to get region settings like the
// session CREATE POST request and send a request to get ICE servers from a
// region + media node that is selected. The issue is that a subsequent POST,
// although unlikely, may end up in a different region. Media node in one region and
// TURN in another region, although shuttling media across regions, should still work.
// But, as this is not a recommended way, not supporting it.
}
type createRequest struct {
RoomName livekit.RoomName
ParticipantInit routing.ParticipantInit
ClientIP string
OfferSDP string
SubscribedParticipantTrackNames map[string][]string
}
func (s *RTCRestService) validateCreate(r *http.Request) (*createRequest, int, error) {
claims := GetGrants(r.Context())
if claims == nil || claims.Video == nil {
return nil, http.StatusUnauthorized, rtc.ErrPermissionDenied
}
if err := EnsureCreatePermission(r.Context()); err != nil {
return nil, http.StatusUnauthorized, err
}
roomName, err := EnsureJoinPermission(r.Context())
if err != nil {
return nil, http.StatusUnauthorized, err
}
if roomName == "" {
return nil, http.StatusUnauthorized, errors.New("room name cannot be empty")
}
if limit := s.config.Limit.MaxRoomNameLength; limit > 0 && len(roomName) > limit {
return nil, http.StatusBadRequest, fmt.Errorf("%w: max length %d", ErrRoomNameExceedsLimits, limit)
}
if claims.Identity == "" {
return nil, http.StatusBadRequest, ErrIdentityEmpty
}
if limit := s.config.Limit.MaxParticipantIdentityLength; limit > 0 && len(claims.Identity) > limit {
return nil, http.StatusBadRequest, fmt.Errorf("%w: max length %d", ErrParticipantIdentityExceedsLimits, limit)
}
var clientInfo struct {
ClientIP string `json:"clientIp"`
SubscribedParticipantTrackNames map[string][]string `json:"subscribedParticipantTrackNames"`
}
clientInfoHeader := r.Header.Get("X-LiveKit-ClientInfo")
if clientInfoHeader != "" {
if err := json.NewDecoder(strings.NewReader(clientInfoHeader)).Decode(&clientInfo); err != nil {
return nil, http.StatusBadRequest, fmt.Errorf("malformed json in client info header: %s", err)
}
}
offerSDPBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, http.StatusBadRequest, fmt.Errorf("body does not have SDP offer: %s", err)
}
offerSDP := string(offerSDPBytes)
sd := &webrtc.SessionDescription{
Type: webrtc.SDPTypeOffer,
SDP: offerSDP,
}
_, err = sd.Unmarshal()
if err != nil {
return nil, http.StatusBadRequest, fmt.Errorf("malformed SDP offer: %s", err)
}
pi := routing.ParticipantInit{
Identity: livekit.ParticipantIdentity(claims.Identity),
Name: livekit.ParticipantName(claims.Name),
AutoSubscribe: true,
Client: &livekit.ClientInfo{
Protocol: types.CurrentProtocol,
},
Grants: claims,
CreateRoom: &livekit.CreateRoomRequest{
Name: string(roomName),
RoomPreset: claims.RoomPreset,
},
AdaptiveStream: false,
DisableICELite: true,
}
SetRoomConfiguration(pi.CreateRoom, claims.GetRoomConfiguration())
return &createRequest{
roomName,
pi,
clientInfo.ClientIP,
offerSDP,
clientInfo.SubscribedParticipantTrackNames,
}, http.StatusOK, nil
}
func (s *RTCRestService) handleCreate(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-type") != "application/sdp" {
handleError("Create", w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type")))
return
}
w.Header().Add("Content-type", "application/sdp")
req, status, err := s.validateCreate(r)
if err != nil {
handleError("Create", w, r, status, err)
return
}
if err := s.roomAllocator.SelectRoomNode(r.Context(), req.RoomName, ""); err != nil {
handleError("Create", w, r, http.StatusInternalServerError, err)
return
}
rtcNode, err := s.router.GetNodeForRoom(r.Context(), req.RoomName)
if err != nil {
handleError("Create", w, r, http.StatusInternalServerError, err)
return
}
connID := livekit.ConnectionID(guid.New("CO_"))
starSession, err := req.ParticipantInit.ToStartSession(req.RoomName, connID)
if err != nil {
handleError("Create", w, r, http.StatusInternalServerError, err)
return
}
subscribedParticipantTracks := map[string]*rpc.RTCRestCreateRequest_TrackList{}
for identity, trackNames := range req.SubscribedParticipantTrackNames {
subscribedParticipantTracks[identity] = &rpc.RTCRestCreateRequest_TrackList{
TrackNames: trackNames,
}
}
res, err := s.client.Create(r.Context(), livekit.NodeID(rtcNode.Id), &rpc.RTCRestCreateRequest{
OfferSdp: req.OfferSDP,
StartSession: starSession,
SubscribedParticipantTracks: subscribedParticipantTracks,
})
if err != nil {
handleError("Create", w, r, http.StatusServiceUnavailable, err)
return
}
// created resource sent in Location header:
// https://www.rfc-editor.org/rfc/rfc9725.html#name-ingest-session-setup
// using relative location
w.Header().Add("Location", fmt.Sprintf("%s/%s", cParticipantPath, res.ParticipantId))
// ICE servers as Link header(s):
// https://www.rfc-editor.org/rfc/rfc9725.html#name-stun-turn-server-configurat
var iceServerLinks []*linkheader.Link
for _, iceServer := range res.IceServers {
for _, iceURL := range iceServer.Urls {
iceServerLink := &linkheader.Link{
URL: url.PathEscape(iceURL),
Rel: "ice-server",
Params: map[string]string{},
}
if iceServer.Username != "" {
iceServerLink.Params["username"] = iceServer.Username
}
if iceServer.Credential != "" {
iceServerLink.Params["credential"] = iceServer.Credential
}
iceServerLinks = append(iceServerLinks, iceServerLink)
}
}
for _, iceServerLink := range iceServerLinks {
w.Header().Add("Link", iceServerLink.String())
}
// To support ICE Trickle/Restart, HTTP PATCH should have an ETag
// send ICE session ID (ICE ufrag is used as ID) in ETag header
// https://www.rfc-editor.org/rfc/rfc9725.html#name-http-patch-request-usage
if res.IceSessionId != "" {
w.Header().Add("ETag", res.IceSessionId)
}
// 201 Status Created
w.WriteHeader(http.StatusCreated)
// SDP answer in the response body
w.Write([]byte(res.AnswerSdp))
sutils.GetLogger(r.Context()).Infow(
"API RTCRest.Create",
"connID", connID,
"participant", req.ParticipantInit.Identity,
"room", req.RoomName,
"status", http.StatusCreated,
"response", logger.Proto(res),
)
return
}
func (s *RTCRestService) handleParticipantGet(w http.ResponseWriter, r *http.Request) {
// https:/www.rfc-editor.org/rfc/rfc9725.html#name-http-usage
w.WriteHeader(http.StatusNoContent)
}
func (s *RTCRestService) iceTrickle(
w http.ResponseWriter,
r *http.Request,
roomName livekit.RoomName,
participantIdentity livekit.ParticipantIdentity,
pID livekit.ParticipantID,
iceSessionID string,
sdpFragment string,
) {
_, err := s.participantClient.ICETrickle(
r.Context(),
s.topicFormatter.ParticipantTopic(r.Context(), roomName, participantIdentity),
&rpc.RTCRestParticipantICETrickleRequest{
Room: string(roomName),
ParticipantIdentity: string(participantIdentity),
ParticipantId: string(pID),
IceSessionId: iceSessionID,
SdpFragment: sdpFragment,
},
)
if err != nil {
var pe psrpc.Error
if errors.As(err, &pe) {
switch pe.Code() {
case psrpc.NotFound:
handleError("Patch", w, r, http.StatusNotFound, errors.New(pe.Error()))
case psrpc.InvalidArgument:
switch pe.Error() {
case rtc.ErrInvalidSDPFragment.Error(), rtc.ErrMidMismatch.Error(), rtc.ErrICECredentialMismatch.Error():
handleError("Patch", w, r, http.StatusBadRequest, errors.New(pe.Error()))
default:
handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
}
default:
handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
}
} else {
handleError("Patch", w, r, http.StatusInternalServerError, nil)
}
return
}
sutils.GetLogger(r.Context()).Infow(
"API RTCRest.Patch",
"method", "ice-trickle",
"room", roomName,
"participant", participantIdentity,
"pID", pID,
"sdpFragment", sdpFragment,
"status", http.StatusNoContent,
)
w.WriteHeader(http.StatusNoContent)
}
func (s *RTCRestService) iceRestart(
w http.ResponseWriter,
r *http.Request,
roomName livekit.RoomName,
participantIdentity livekit.ParticipantIdentity,
pID livekit.ParticipantID,
sdpFragment string,
) {
res, err := s.participantClient.ICERestart(
r.Context(),
s.topicFormatter.ParticipantTopic(r.Context(), roomName, participantIdentity),
&rpc.RTCRestParticipantICERestartRequest{
Room: string(roomName),
ParticipantIdentity: string(participantIdentity),
ParticipantId: string(pID),
SdpFragment: sdpFragment,
},
)
if err != nil {
var pe psrpc.Error
if errors.As(err, &pe) {
switch pe.Code() {
case psrpc.NotFound:
handleError("Patch", w, r, http.StatusNotFound, errors.New(pe.Error()))
case psrpc.InvalidArgument:
switch pe.Error() {
case rtc.ErrInvalidSDPFragment.Error():
handleError("Patch", w, r, http.StatusBadRequest, errors.New(pe.Error()))
default:
handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
}
default:
handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
}
} else {
handleError("Patch", w, r, http.StatusInternalServerError, nil)
}
return
}
sutils.GetLogger(r.Context()).Infow(
"API RTCRest.Patch",
"method", "ice-restart",
"room", roomName,
"participant", participantIdentity,
"pID", pID,
"sdpFragment", sdpFragment,
"status", http.StatusNoContent,
"res", logger.Proto(res),
)
if res.IceSessionId != "" {
w.Header().Add("ETag", res.IceSessionId)
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(res.SdpFragment))
}
func (s *RTCRestService) handleParticipantPatch(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-type") != "application/trickle-ice-sdpfrag" {
handleError("Patch", w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type")))
return
}
w.Header().Add("Content-type", "application/trickle-ice-sdpfrag")
// https://www.rfc-editor.org/rfc/rfc9725.html#name-http-patch-request-usage
ifMatch := r.Header.Get("If-Match")
if ifMatch == "" {
handleError("Patch", w, r, http.StatusPreconditionRequired, errors.New("missing entity tag"))
return
}
claims := GetGrants(r.Context())
if claims == nil || claims.Video == nil {
handleError("Patch", w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied)
return
}
roomName, err := EnsureJoinPermission(r.Context())
if err != nil {
handleError("Patch", w, r, http.StatusUnauthorized, err)
return
}
if roomName == "" {
handleError("Patch", w, r, http.StatusUnauthorized, errors.New("room name cannot be empty"))
return
}
if claims.Identity == "" {
handleError("Patch", w, r, http.StatusUnauthorized, errors.New("participant identity cannot be empty"))
return
}
pID := livekit.ParticipantID(r.PathValue("participant_id"))
if pID == "" {
handleError("Patch", w, r, http.StatusUnauthorized, errors.New("participant ID cannot be empty"))
return
}
sdpFragmentBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
handleError("Patch", w, r, http.StatusBadRequest, fmt.Errorf("body does not have SDP fragment: %s", err))
}
sdpFragment := string(sdpFragmentBytes)
if ifMatch == "*" {
s.iceRestart(w, r, roomName, livekit.ParticipantIdentity(claims.Identity), pID, sdpFragment)
} else {
s.iceTrickle(w, r, roomName, livekit.ParticipantIdentity(claims.Identity), pID, ifMatch, sdpFragment)
}
}
func (s *RTCRestService) handleParticipantDelete(w http.ResponseWriter, r *http.Request) {
claims := GetGrants(r.Context())
if claims == nil || claims.Video == nil {
handleError("Delete", w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied)
return
}
roomName, err := EnsureJoinPermission(r.Context())
if err != nil {
handleError("Delete", w, r, http.StatusUnauthorized, err)
return
}
if roomName == "" {
handleError("Delete", w, r, http.StatusUnauthorized, errors.New("room name cannot be empty"))
return
}
if claims.Identity == "" {
handleError("Delete", w, r, http.StatusUnauthorized, errors.New("participant identity cannot be empty"))
return
}
_, err = s.participantClient.DeleteSession(
r.Context(),
s.topicFormatter.ParticipantTopic(r.Context(), roomName, livekit.ParticipantIdentity(claims.Identity)),
&rpc.RTCRestParticipantDeleteSessionRequest{
Room: string(roomName),
ParticipantIdentity: claims.Identity,
ParticipantId: r.PathValue("participant_id"),
},
)
if err != nil {
handleError("Delete", w, r, http.StatusNotFound, err)
return
}
sutils.GetLogger(r.Context()).Infow(
"API RTCRest.Delete",
"participant", claims.Identity,
"pID", r.PathValue("participant_id"),
"room", roomName,
"status", http.StatusOK,
)
w.WriteHeader(http.StatusOK)
}
func handleError(method string, w http.ResponseWriter, r *http.Request, status int, err error) {
sutils.GetLogger(r.Context()).Warnw(
fmt.Sprintf("API RTCRest.%s", method), err,
"status", status,
)
w.WriteHeader(status)
json.NewEncoder(w).Encode(struct {
Error string `json:"error"`
}{
Error: err.Error(),
})
}
-6
View File
@@ -45,9 +45,7 @@ import (
type RTCService struct {
router routing.MessageRouter
roomAllocator RoomAllocator
store ServiceStore
upgrader websocket.Upgrader
currentNode routing.LocalNode
config *config.Config
isDev bool
limits config.LimitConfig
@@ -61,16 +59,12 @@ type RTCService struct {
func NewRTCService(
conf *config.Config,
ra RoomAllocator,
store ServiceStore,
router routing.MessageRouter,
currentNode routing.LocalNode,
telemetry telemetry.TelemetryService,
) *RTCService {
s := &RTCService{
router: router,
roomAllocator: ra,
store: store,
currentNode: currentNode,
config: conf,
isDev: conf.Development,
limits: conf.Limit,
+27 -21
View File
@@ -46,20 +46,21 @@ import (
)
type LivekitServer struct {
config *config.Config
ioService *IOInfoService
rtcService *RTCService
agentService *AgentService
httpServer *http.Server
promServer *http.Server
router routing.Router
roomManager *RoomManager
signalServer *SignalServer
turnServer *turn.Server
currentNode routing.LocalNode
running atomic.Bool
doneChan chan struct{}
closedChan chan struct{}
config *config.Config
ioService *IOInfoService
rtcService *RTCService
rtcRestService *RTCRestService
agentService *AgentService
httpServer *http.Server
promServer *http.Server
router routing.Router
roomManager *RoomManager
signalServer *SignalServer
turnServer *turn.Server
currentNode routing.LocalNode
running atomic.Bool
doneChan chan struct{}
closedChan chan struct{}
}
func NewLivekitServer(conf *config.Config,
@@ -70,6 +71,7 @@ func NewLivekitServer(conf *config.Config,
sipService *SIPService,
ioService *IOInfoService,
rtcService *RTCService,
rtcRestService *RTCRestService,
agentService *AgentService,
keyProvider auth.KeyProvider,
router routing.Router,
@@ -79,13 +81,14 @@ func NewLivekitServer(conf *config.Config,
currentNode routing.LocalNode,
) (s *LivekitServer, err error) {
s = &LivekitServer{
config: conf,
ioService: ioService,
rtcService: rtcService,
agentService: agentService,
router: router,
roomManager: roomManager,
signalServer: signalServer,
config: conf,
ioService: ioService,
rtcService: rtcService,
rtcRestService: rtcRestService,
agentService: agentService,
router: router,
roomManager: roomManager,
signalServer: signalServer,
// turn server starts automatically
turnServer: turnServer,
currentNode: currentNode,
@@ -100,7 +103,9 @@ func NewLivekitServer(conf *config.Config,
AllowOriginFunc: func(origin string) bool {
return true
},
AllowedMethods: []string{"OPTIONS", "HEAD", "GET", "POST", "PATCH", "DELETE"},
AllowedHeaders: []string{"*"},
ExposedHeaders: []string{"*"},
// allow preflight to be cached for a day
MaxAge: 86400,
}),
@@ -140,6 +145,7 @@ func NewLivekitServer(conf *config.Config,
xtwirp.RegisterServer(mux, sipServer)
mux.Handle("/rtc", rtcService)
rtcService.SetupRoutes(mux)
rtcRestService.SetupRoutes(mux)
mux.Handle("/agent", agentService)
mux.HandleFunc("/", s.defaultHandler)
+2
View File
@@ -79,6 +79,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
NewRoomAllocator,
NewRoomService,
NewRTCService,
NewRTCRestService,
NewAgentService,
NewAgentDispatchService,
agent.NewAgentClient,
@@ -94,6 +95,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
rpc.NewTopicFormatter,
rpc.NewTypedRoomClient,
rpc.NewTypedParticipantClient,
rpc.NewTypedRTCRestParticipantClient,
rpc.NewTypedAgentDispatchInternalClient,
NewLocalRoomManager,
NewTURNAuthHandler,
+10 -2
View File
@@ -120,7 +120,15 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
return nil, err
}
sipService := NewSIPService(sipConfig, nodeID, messageBus, sipClient, sipStore, roomService, telemetryService)
rtcService := NewRTCService(conf, roomAllocator, objectStore, router, currentNode, telemetryService)
rtcService := NewRTCService(conf, roomAllocator, router, telemetryService)
rtcRestParticipantClient, err := rpc.NewTypedRTCRestParticipantClient(clientParams)
if err != nil {
return nil, err
}
serviceRTCRestService, err := NewRTCRestService(conf, router, roomAllocator, clientParams, topicFormatter, rtcRestParticipantClient)
if err != nil {
return nil, err
}
agentService, err := NewAgentService(conf, currentNode, messageBus, keyProvider)
if err != nil {
return nil, err
@@ -147,7 +155,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
if err != nil {
return nil, err
}
livekitServer, err := NewLivekitServer(conf, roomService, agentDispatchService, egressService, ingressService, sipService, ioInfoService, rtcService, agentService, keyProvider, router, roomManager, signalServer, server, currentNode)
livekitServer, err := NewLivekitServer(conf, roomService, agentDispatchService, egressService, ingressService, sipService, ioInfoService, rtcService, serviceRTCRestService, agentService, keyProvider, router, roomManager, signalServer, server, currentNode)
if err != nil {
return nil, err
}