lksdk

package module
v1.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 25, 2024 License: Apache-2.0 Imports: 43 Imported by: 22

README

The LiveKit icon, the name of the repository and some sample code in the background.

LiveKit Go SDK

Use this SDK to manage LiveKit rooms and create access tokens from your Go backend.

Installation

go get github.com/livekit/server-sdk-go

Note: since v1.0 release, this package requires Go 1.18+ in order to build.

Token creation

import (
	"time"

	lksdk "github.com/livekit/server-sdk-go"
	"github.com/livekit/protocol/auth"
)

func getJoinToken(apiKey, apiSecret, room, identity string) (string, error) {
	at := auth.NewAccessToken(apiKey, apiSecret)
	grant := &auth.VideoGrant{
		RoomJoin: true,
		Room:     room,
	}
	at.AddGrant(grant).
		SetIdentity(identity).
		SetValidFor(time.Hour)

	return at.ToJWT()
}

RoomService API

RoomService gives you complete control over rooms and participants within them. It includes selective track subscriptions as well as moderation capabilities.

import (
	lksdk "github.com/livekit/server-sdk-go"
	livekit "github.com/livekit/protocol/livekit"
)

func main() {
	hostURL := "host-url"  // ex: https://project-123456.livekit.cloud
	apiKey := "api-key"
	apiSecret := "api-secret"

	roomName := "myroom"
	identity := "participantIdentity"

    roomClient := lksdk.NewRoomServiceClient(hostURL, apiKey, apiSecret)

    // create a new room
    room, _ := roomClient.CreateRoom(context.Background(), &livekit.CreateRoomRequest{
		Name: roomName,
	})

    // list rooms
    res, _ := roomClient.ListRooms(context.Background(), &livekit.ListRoomsRequest{})

    // terminate a room and cause participants to leave
    roomClient.DeleteRoom(context.Background(), &livekit.DeleteRoomRequest{
		Room: roomId,
	})

    // list participants in a room
    res, _ := roomClient.ListParticipants(context.Background(), &livekit.ListParticipantsRequest{
		Room: roomName,
	})

    // disconnect a participant from room
    roomClient.RemoveParticipant(context.Background(), &livekit.RoomParticipantIdentity{
		Room:     roomName,
		Identity: identity,
	})

    // mute/unmute participant's tracks
    roomClient.MutePublishedTrack(context.Background(), &livekit.MuteRoomTrackRequest{
		Room:     roomName,
		Identity: identity,
		TrackSid: "track_sid",
		Muted:    true,
	})
}

Interacting as a participant

The Participant SDK gives you access programmatic access as a client enabling you to publish and record audio/video/data to the room.

import (
  lksdk "github.com/livekit/server-sdk-go"
)

func main() {
  hostURL := "host-url"  // ex: https://project-123456.livekit.cloud
  apiKey := "api-key"
  apiSecret := "api-secret"
  roomName := "myroom"
  identity := "botuser"
  roomCB := &lksdk.RoomCallback{
	ParticipantCallback: lksdk.ParticipantCallback{
	  OnTrackSubscribed: trackSubscribed,
  	},
  }
  room, err := lksdk.ConnectToRoom(hostURL, lksdk.ConnectInfo{
  	APIKey:              apiKey,
  	APISecret:           apiSecret,
  	RoomName:            roomName,
  	ParticipantIdentity: identity,
  }, roomCB)
  if err != nil {
  	panic(err)
  }

  ...
  room.Disconnect()
}

func trackSubscribed(track *webrtc.TrackRemote, publication *lksdk.RemoteTrackPublication, rp *lksdk.RemoteParticipant) {

}

Publishing tracks to Room

With the Go SDK, you can publish existing files encoded in H.264, VP8, and Opus to the room.

First, you will need to encode media into the right format.

VP8 / Opus
ffmpeg -i <input.mp4> \
  -c:v libvpx -keyint_min 120 -qmax 50 -maxrate 2M -b:v 1M <output.ivf> \
  -c:a libopus -page_duration 20000 -vn <output.ogg>

The above encodes VP8 at average 1Mbps / max 2Mbps with a minimum keyframe interval of 120.

H.264 / Opus
ffmpeg -i <input.mp4> \
  -c:v libx264 -bsf:v h264_mp4toannexb -b:v 2M -profile baseline -pix_fmt yuv420p \
    -x264-params keyint=120 -max_delay 0 -bf 0 <output.h264> \
  -c:a libopus -page_duration 20000 -vn <output.ogg>

The above encodes H264 with CBS of 2Mbps with a minimum keyframe interval of 120.

Publish from file
file := "video.ivf"
videoWidth := 1920
videoHeight := 1080
track, err := lksdk.NewLocalFileTrack(file,
	// control FPS to ensure synchronization
	lksdk.ReaderTrackWithFrameDuration(33 * time.Millisecond),
	lksdk.ReaderTrackWithOnWriteComplete(func() { fmt.Println("track finished") }),
)
if err != nil {
    return err
}
if _, err = room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{
	Name: file,
	VideoWidth: videoWidth,
	VideoHeight: videoHeight,
}); err != nil {
    return err
}
Publish from io.ReadCloser implementation
// - `in` implements io.ReadCloser, such as buffer or file
// - `mime` has to be one of webrtc.MimeType...
track, err := lksdk.NewLocalReaderTrack(in, mime,
	lksdk.ReaderTrackWithFrameDuration(33 * time.Millisecond),
	lksdk.ReaderTrackWithOnWriteComplete(func() { fmt.Println("track finished") }),
)
if err != nil {
	return err
}
if _, err = room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{}); err != nil {
    return err
}

For a full working example, refer to join.go in livekit-cli.

Publish from other sources

In order to publish from non-file sources, you will have to implement your own SampleProvider, that could provide frames of data with a NextSample method.

The SDK takes care of sending the samples to the room.

Using a pacer

With video publishing, keyframes can be an order of magnitude larger than delta frames. This size difference can cause a significant increase in bitrate when a keyframe is transmitted, leading to a surge in packet flow. Such spikes might result in packet loss at the forwarding layer. To maintain a consistent packet flow, you can enable the use of a pacer.

import "github.com/livekit/mediatransportutil/pkg/pacer"

// Control total output bitrate to 10Mbps with 1s max latency
pf := pacer.NewPacerFactory(
	pacer.LeakyBucketPacer,
	pacer.WithBitrate(10000000),
	pacer.WithMaxLatency(time.Second),
)

room, err := lksdk.ConnectToRoom(hostURL, lksdk.ConnectInfo{
    APIKey:              apiKey,
    APISecret:           apiSecret,
    RoomName:            roomName,
    ParticipantIdentity: identity,
}, &lksdk.RoomCallback{
    ParticipantCallback: lksdk.ParticipantCallback{
        OnTrackSubscribed: onTrackSubscribed,
    },
}, lksdk.WithPacer(pf))

Receiving webhooks

The Go SDK helps you to verify and decode webhook callbacks to ensure their authenticity. See webhooks guide for configuration.

import (
	"github.com/livekit/protocol/auth"
	"github.com/livekit/protocol/livekit"
	"github.com/livekit/protocol/webhook"
)

var authProvider = auth.NewSimpleKeyProvider(
	apiKey, apiSecret,
)

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
  // event is a livekit.WebhookEvent{} object
	event, err := webhook.ReceiveWebhookEvent(r, authProvider)
	if err != nil {
		// could not validate, handle error
		return
	}

	// consume WebhookEvent
}


LiveKit Ecosystem
Real-time SDKsReact Components · JavaScript · iOS/macOS · Android · Flutter · React Native · Rust · Python · Unity (web) · Unity (beta)
Server APIsNode.js · Golang · Ruby · Java/Kotlin · Python · Rust · PHP (community)
Agents FrameworksPython · Playground
ServicesLivekit server · Egress · Ingress · SIP
ResourcesDocs · Example apps · Cloud · Self-hosting · CLI

Documentation

Index

Constants

View Source
const PROTOCOL = 8
View Source
const (
	SimulateSpeakerUpdateInterval = 5
)
View Source
const Version = "1.1.8"

Variables

View Source
var (
	ErrURLNotProvided           = errors.New("URL was not provided")
	ErrConnectionTimeout        = errors.New("could not connect after timeout")
	ErrTrackPublishTimeout      = errors.New("timed out publishing track")
	ErrCannotDetermineMime      = errors.New("cannot determine mimetype from file extension")
	ErrUnsupportedFileType      = errors.New("ReaderSampleProvider does not support this mime type")
	ErrUnsupportedSimulcastKind = errors.New("simulcast is only supported for video")
	ErrInvalidSimulcastTrack    = errors.New("simulcast track was not initiated correctly")
	ErrCannotFindTrack          = errors.New("could not find the track")
	ErrInvalidParameter         = errors.New("invalid parameter")
	ErrCannotConnectSignal      = errors.New("could not establish signal connection")
	ErrCannotDialSignal         = errors.New("could not dial signal connection")
)

Functions

func FromProtoIceServers

func FromProtoIceServers(iceservers []*livekit.ICEServer) []webrtc.ICEServer

func FromProtoSessionDescription

func FromProtoSessionDescription(sd *livekit.SessionDescription) webrtc.SessionDescription

func FromProtoTrickle

func FromProtoTrickle(trickle *livekit.TrickleRequest) webrtc.ICECandidateInit

func ReaderTrackWithFrameDuration added in v0.10.1

func ReaderTrackWithFrameDuration(duration time.Duration) func(provider *ReaderSampleProvider)

func ReaderTrackWithMime added in v0.10.1

func ReaderTrackWithMime(mime string) func(provider *ReaderSampleProvider)

func ReaderTrackWithOnWriteComplete added in v0.10.1

func ReaderTrackWithOnWriteComplete(f func()) func(provider *ReaderSampleProvider)

func ReaderTrackWithRTCPHandler added in v0.10.5

func ReaderTrackWithRTCPHandler(f func(rtcp.Packet)) func(provider *ReaderSampleProvider)

func ReaderTrackWithSampleOptions added in v1.1.2

func ReaderTrackWithSampleOptions(opts ...LocalTrackOptions) func(provider *ReaderSampleProvider)

func SetLogger

func SetLogger(l protoLogger.Logger)

SetLogger overrides default logger. To use a [logr](https://github.com/go-logr/logr) compatible logger, pass in SetLogger(logger.LogRLogger(logRLogger))

func ToHttpURL added in v0.10.0

func ToHttpURL(url string) string

func ToProtoSessionDescription

func ToProtoSessionDescription(sd webrtc.SessionDescription) *livekit.SessionDescription

func ToProtoTrickle

func ToProtoTrickle(candidateInit webrtc.ICECandidateInit, target livekit.SignalTarget) *livekit.TrickleRequest

func ToWebsocketURL added in v0.10.0

func ToWebsocketURL(url string) string

Types

type AudioSampleProvider added in v0.7.0

type AudioSampleProvider interface {
	SampleProvider
	CurrentAudioLevel() uint8
}

type BaseSampleProvider added in v0.9.0

type BaseSampleProvider struct {
}

BaseSampleProvider provides empty implementations for OnBind and OnUnbind

func (*BaseSampleProvider) Close added in v1.0.11

func (p *BaseSampleProvider) Close() error

func (*BaseSampleProvider) OnBind added in v0.9.0

func (p *BaseSampleProvider) OnBind() error

func (*BaseSampleProvider) OnUnbind added in v0.9.0

func (p *BaseSampleProvider) OnUnbind() error

type ConnectInfo

type ConnectInfo struct {
	APIKey              string
	APISecret           string
	RoomName            string
	ParticipantName     string
	ParticipantIdentity string
	ParticipantKind     ParticipantKind
	ParticipantMetadata string
}

type ConnectOption added in v0.6.1

type ConnectOption func(*ConnectParams)

func WithAutoSubscribe added in v0.6.1

func WithAutoSubscribe(val bool) ConnectOption

func WithPacer added in v1.1.2

func WithPacer(pacer pacer.Factory) ConnectOption

func WithRetransmitBufferSize added in v1.1.1

func WithRetransmitBufferSize(val uint16) ConnectOption

Retransmit buffer size to reponse to nack request, must be one of: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768

type ConnectParams added in v0.6.1

type ConnectParams struct {
	AutoSubscribe bool
	Reconnect     bool
	Callback      *RoomCallback

	RetransmitBufferSize uint16

	Pacer pacer.Factory
}

type EgressClient added in v0.9.0

type EgressClient struct {
	// contains filtered or unexported fields
}

func NewEgressClient added in v0.9.0

func NewEgressClient(url string, apiKey string, secretKey string) *EgressClient

func (*EgressClient) ListEgress added in v0.9.0

func (*EgressClient) StartParticipantEgress added in v1.1.0

func (c *EgressClient) StartParticipantEgress(ctx context.Context, req *livekit.ParticipantEgressRequest) (*livekit.EgressInfo, error)

func (*EgressClient) StartRoomCompositeEgress added in v0.9.3

func (c *EgressClient) StartRoomCompositeEgress(ctx context.Context, req *livekit.RoomCompositeEgressRequest) (*livekit.EgressInfo, error)

func (*EgressClient) StartTrackCompositeEgress added in v0.10.0

func (c *EgressClient) StartTrackCompositeEgress(ctx context.Context, req *livekit.TrackCompositeEgressRequest) (*livekit.EgressInfo, error)

func (*EgressClient) StartTrackEgress added in v0.10.0

func (c *EgressClient) StartTrackEgress(ctx context.Context, req *livekit.TrackEgressRequest) (*livekit.EgressInfo, error)

func (*EgressClient) StartWebEgress added in v1.0.5

func (c *EgressClient) StartWebEgress(ctx context.Context, req *livekit.WebEgressRequest) (*livekit.EgressInfo, error)

func (*EgressClient) StopEgress added in v0.9.0

func (*EgressClient) UpdateLayout added in v0.9.0

func (*EgressClient) UpdateStream added in v0.9.0

type IngressClient added in v0.10.5

type IngressClient struct {
	// contains filtered or unexported fields
}

func NewIngressClient added in v0.10.5

func NewIngressClient(url string, apiKey string, secretKey string) *IngressClient

func (*IngressClient) CreateIngress added in v0.10.5

func (*IngressClient) DeleteIngress added in v0.10.5

func (*IngressClient) ListIngress added in v0.10.5

func (*IngressClient) UpdateIngress added in v0.10.5

type LocalParticipant

type LocalParticipant struct {
	// contains filtered or unexported fields
}

func (*LocalParticipant) AudioLevel

func (p *LocalParticipant) AudioLevel() float32

func (*LocalParticipant) GetPublisherPeerConnection added in v0.9.0

func (p *LocalParticipant) GetPublisherPeerConnection() *webrtc.PeerConnection

GetPublisherPeerConnection is a power-user API that gives access to the underlying publisher peer connection local tracks are published to server via this PeerConnection

func (*LocalParticipant) GetSubscriberPeerConnection added in v0.9.0

func (p *LocalParticipant) GetSubscriberPeerConnection() *webrtc.PeerConnection

GetSubscriberPeerConnection is a power-user API that gives access to the underlying subscriber peer connection subscribed tracks are received using this PeerConnection

func (*LocalParticipant) GetTrack added in v0.8.0

func (p *LocalParticipant) GetTrack(source livekit.TrackSource) TrackPublication

func (*LocalParticipant) Identity

func (p *LocalParticipant) Identity() string

func (*LocalParticipant) IsCameraEnabled added in v0.8.0

func (p *LocalParticipant) IsCameraEnabled() bool

func (*LocalParticipant) IsMicrophoneEnabled added in v0.8.0

func (p *LocalParticipant) IsMicrophoneEnabled() bool

func (*LocalParticipant) IsScreenShareEnabled added in v0.8.0

func (p *LocalParticipant) IsScreenShareEnabled() bool

func (*LocalParticipant) IsSpeaking

func (p *LocalParticipant) IsSpeaking() bool

func (*LocalParticipant) Kind added in v1.1.8

func (p *LocalParticipant) Kind() livekit.ParticipantInfo_Kind

func (*LocalParticipant) Metadata added in v0.5.13

func (p *LocalParticipant) Metadata() string

func (*LocalParticipant) Name added in v0.8.2

func (p *LocalParticipant) Name() string

func (*LocalParticipant) Permissions added in v1.1.8

func (p *LocalParticipant) Permissions() *livekit.ParticipantPermission

func (*LocalParticipant) PublishData added in v0.5.12

func (p *LocalParticipant) PublishData(
	data []byte,
	kind livekit.DataPacket_Kind,
	destinationSids []string,
) error

func (*LocalParticipant) PublishDataPacket added in v1.1.0

func (p *LocalParticipant) PublishDataPacket(userPacket *livekit.UserPacket, kind livekit.DataPacket_Kind) error

func (*LocalParticipant) PublishSimulcastTrack added in v0.9.0

func (p *LocalParticipant) PublishSimulcastTrack(tracks []*LocalTrack, opts *TrackPublicationOptions) (*LocalTrackPublication, error)

PublishSimulcastTrack publishes up to three layers to the server

func (*LocalParticipant) PublishTrack

func (p *LocalParticipant) PublishTrack(track webrtc.TrackLocal, opts *TrackPublicationOptions) (*LocalTrackPublication, error)

func (*LocalParticipant) SID

func (p *LocalParticipant) SID() string

func (*LocalParticipant) SetMetadata added in v1.0.10

func (p *LocalParticipant) SetMetadata(metadata string)

SetMetadata sets the metadata of the current participant. updates will be performed only if the participant has canUpdateOwnMetadata grant

func (*LocalParticipant) SetName added in v1.0.10

func (p *LocalParticipant) SetName(name string)

SetName sets the name of the current participant. updates will be performed only if the participant has canUpdateOwnMetadata grant

func (*LocalParticipant) Tracks

func (p *LocalParticipant) Tracks() []TrackPublication

func (*LocalParticipant) UnpublishTrack added in v0.7.0

func (p *LocalParticipant) UnpublishTrack(sid string) error

type LocalSampleTrack

type LocalSampleTrack = LocalTrack

type LocalSampleTrackOptions added in v0.9.0

type LocalSampleTrackOptions = LocalTrackOptions

type LocalTrack added in v1.1.6

type LocalTrack struct {
	// contains filtered or unexported fields
}

LocalTrack is a local track that simplifies writing samples. It handles timing and publishing of things, so as long as a SampleProvider is provided, the class takes care of publishing tracks at the right frequency This extends webrtc.TrackLocalStaticSample, and adds the ability to write RTP extensions

func NewLocalFileTrack added in v0.7.0

func NewLocalFileTrack(file string, options ...ReaderSampleProviderOption) (*LocalTrack, error)

NewLocalFileTrack creates an *os.File reader for NewLocalReaderTrack

func NewLocalReaderTrack added in v0.10.1

func NewLocalReaderTrack(in io.ReadCloser, mime string, options ...ReaderSampleProviderOption) (*LocalTrack, error)

NewLocalReaderTrack uses io.ReadCloser interface to adapt to various ingress types - mime: has to be one of webrtc.MimeType... (e.g. webrtc.MimeTypeOpus)

func NewLocalSampleTrack

func NewLocalSampleTrack(c webrtc.RTPCodecCapability, opts ...LocalTrackOptions) (*LocalTrack, error)

func NewLocalTrack added in v1.1.6

func NewLocalTrack(c webrtc.RTPCodecCapability, opts ...LocalTrackOptions) (*LocalTrack, error)

func (*LocalTrack) Bind added in v1.1.6

func (s *LocalTrack) Bind(t webrtc.TrackLocalContext) (webrtc.RTPCodecParameters, error)

Bind is an interface for TrackLocal, not for external consumption

func (*LocalTrack) Close added in v1.1.6

func (s *LocalTrack) Close() error

func (*LocalTrack) Codec added in v1.1.6

func (s *LocalTrack) Codec() webrtc.RTPCodecCapability

Codec gets the Codec of the track

func (*LocalTrack) ID added in v1.1.6

func (s *LocalTrack) ID() string

ID is the unique identifier for this Track. This should be unique for the stream, but doesn't have to globally unique. A common example would be 'audio' or 'video' and StreamID would be 'desktop' or 'webcam'

func (*LocalTrack) IsBound added in v1.1.6

func (s *LocalTrack) IsBound() bool

func (*LocalTrack) Kind added in v1.1.6

func (s *LocalTrack) Kind() webrtc.RTPCodecType

Kind controls if this TrackLocal is audio or video

func (*LocalTrack) OnBind added in v1.1.6

func (s *LocalTrack) OnBind(f func())

OnBind sets a callback to be called when the track has been negotiated for publishing and bound to a peer connection

func (*LocalTrack) OnUnbind added in v1.1.6

func (s *LocalTrack) OnUnbind(f func())

OnUnbind sets a callback to be called after the track is removed from a peer connection

func (*LocalTrack) RID added in v1.1.6

func (s *LocalTrack) RID() string

RID is the RTP stream identifier.

func (*LocalTrack) SetTransceiver added in v1.1.6

func (s *LocalTrack) SetTransceiver(transceiver *webrtc.RTPTransceiver)

func (*LocalTrack) StartWrite added in v1.1.6

func (s *LocalTrack) StartWrite(provider SampleProvider, onComplete func()) error

func (*LocalTrack) StreamID added in v1.1.6

func (s *LocalTrack) StreamID() string

StreamID is the group this track belongs too. This must be unique

func (*LocalTrack) Unbind added in v1.1.6

func (s *LocalTrack) Unbind(t webrtc.TrackLocalContext) error

Unbind is an interface for TrackLocal, not for external consumption

func (*LocalTrack) WriteRTP added in v1.1.6

func (s *LocalTrack) WriteRTP(p *rtp.Packet, opts *SampleWriteOptions) error

func (*LocalTrack) WriteSample added in v1.1.6

func (s *LocalTrack) WriteSample(sample media.Sample, opts *SampleWriteOptions) error

type LocalTrackOptions added in v1.1.6

type LocalTrackOptions func(s *LocalTrack)

func WithRTCPHandler added in v0.9.0

func WithRTCPHandler(cb func(rtcp.Packet)) LocalTrackOptions

func WithSimulcast added in v0.9.0

func WithSimulcast(simulcastID string, layer *livekit.VideoLayer) LocalTrackOptions

WithSimulcast marks the current track for simulcasting. In order to use simulcast, simulcastID must be identical across all layers

type LocalTrackPublication

type LocalTrackPublication struct {
	// contains filtered or unexported fields
}

func NewLocalTrackPublication added in v0.10.3

func NewLocalTrackPublication(kind TrackKind, track Track, opts TrackPublicationOptions, client *SignalClient) *LocalTrackPublication

func (*LocalTrackPublication) CloseTrack added in v1.0.11

func (p *LocalTrackPublication) CloseTrack()

func (*LocalTrackPublication) GetSimulcastTrack added in v0.9.0

func (p *LocalTrackPublication) GetSimulcastTrack(quality livekit.VideoQuality) *LocalTrack

func (*LocalTrackPublication) IsMuted

func (p *LocalTrackPublication) IsMuted() bool

func (*LocalTrackPublication) IsSubscribed

func (p *LocalTrackPublication) IsSubscribed() bool

func (*LocalTrackPublication) Kind

func (p *LocalTrackPublication) Kind() TrackKind

func (*LocalTrackPublication) MimeType added in v0.8.2

func (p *LocalTrackPublication) MimeType() string

func (*LocalTrackPublication) Name

func (p *LocalTrackPublication) Name() string

func (*LocalTrackPublication) PublicationOptions added in v1.0.11

func (p *LocalTrackPublication) PublicationOptions() TrackPublicationOptions

func (*LocalTrackPublication) SID

func (p *LocalTrackPublication) SID() string

func (*LocalTrackPublication) SetMuted

func (p *LocalTrackPublication) SetMuted(muted bool)

func (*LocalTrackPublication) Source added in v0.8.0

func (p *LocalTrackPublication) Source() livekit.TrackSource

func (*LocalTrackPublication) Track

func (p *LocalTrackPublication) Track() Track

func (*LocalTrackPublication) TrackInfo added in v0.10.2

func (p *LocalTrackPublication) TrackInfo() *livekit.TrackInfo

func (*LocalTrackPublication) TrackLocal

func (p *LocalTrackPublication) TrackLocal() webrtc.TrackLocal

type LocalTrackWithClose added in v1.0.11

type LocalTrackWithClose interface {
	webrtc.TrackLocal
	Close() error
}

type NullSampleProvider

type NullSampleProvider struct {
	BaseSampleProvider
	BytesPerSample uint32
	SampleDuration time.Duration
}

NullSampleProvider is a media provider that provides null packets, it could meet a certain bitrate, if desired

func NewNullSampleProvider

func NewNullSampleProvider(bitrate uint32) *NullSampleProvider

func (*NullSampleProvider) NextSample

func (p *NullSampleProvider) NextSample(ctx context.Context) (media.Sample, error)

type PCTransport

type PCTransport struct {
	OnOffer func(description webrtc.SessionDescription)
	// contains filtered or unexported fields
}

PCTransport is a wrapper around PeerConnection, with some helper methods

func NewPCTransport

func NewPCTransport(params PCTransportParams) (*PCTransport, error)

func (*PCTransport) AddICECandidate

func (t *PCTransport) AddICECandidate(candidate webrtc.ICECandidateInit) error

func (*PCTransport) Close

func (t *PCTransport) Close() error

func (*PCTransport) GetSelectedCandidatePair added in v1.0.15

func (t *PCTransport) GetSelectedCandidatePair() (*webrtc.ICECandidatePair, error)

func (*PCTransport) IsConnected

func (t *PCTransport) IsConnected() bool

func (*PCTransport) Negotiate added in v0.7.0

func (t *PCTransport) Negotiate()

func (*PCTransport) OnRemoteDescriptionSettled added in v0.10.5

func (t *PCTransport) OnRemoteDescriptionSettled(f func() error)

func (*PCTransport) PeerConnection

func (t *PCTransport) PeerConnection() *webrtc.PeerConnection

func (*PCTransport) SetRTT added in v1.0.0

func (t *PCTransport) SetRTT(rtt uint32)

func (*PCTransport) SetRemoteDescription

func (t *PCTransport) SetRemoteDescription(sd webrtc.SessionDescription) error

type PCTransportParams added in v1.1.1

type PCTransportParams struct {
	Configuration webrtc.Configuration

	RetransmitBufferSize uint16
	Pacer                pacer.Factory
	OnRTTUpdate          func(rtt uint32)
}

type PLIWriter added in v0.9.0

type PLIWriter func(webrtc.SSRC)

type Participant

type Participant interface {
	SID() string
	Identity() string
	Name() string
	Kind() livekit.ParticipantInfo_Kind
	IsSpeaking() bool
	AudioLevel() float32
	Tracks() []TrackPublication
	IsCameraEnabled() bool
	IsMicrophoneEnabled() bool
	IsScreenShareEnabled() bool
	Metadata() string
	GetTrack(source livekit.TrackSource) TrackPublication
	Permissions() *livekit.ParticipantPermission
	// contains filtered or unexported methods
}

type ParticipantCallback

type ParticipantCallback struct {
	// for all participants
	OnTrackMuted               func(pub TrackPublication, p Participant)
	OnTrackUnmuted             func(pub TrackPublication, p Participant)
	OnMetadataChanged          func(oldMetadata string, p Participant)
	OnIsSpeakingChanged        func(p Participant)
	OnConnectionQualityChanged func(update *livekit.ConnectionQualityInfo, p Participant)

	// for remote participants
	OnTrackSubscribed         func(track *webrtc.TrackRemote, publication *RemoteTrackPublication, rp *RemoteParticipant)
	OnTrackUnsubscribed       func(track *webrtc.TrackRemote, publication *RemoteTrackPublication, rp *RemoteParticipant)
	OnTrackSubscriptionFailed func(sid string, rp *RemoteParticipant)
	OnTrackPublished          func(publication *RemoteTrackPublication, rp *RemoteParticipant)
	OnTrackUnpublished        func(publication *RemoteTrackPublication, rp *RemoteParticipant)
	OnDataReceived            func(data []byte, rp *RemoteParticipant)
}

func NewParticipantCallback

func NewParticipantCallback() *ParticipantCallback

func (*ParticipantCallback) Merge added in v0.10.3

func (cb *ParticipantCallback) Merge(other *ParticipantCallback)

type ParticipantKind added in v1.1.5

type ParticipantKind int

type PubCallback

type PubCallback func(pub TrackPublication, participant *RemoteParticipant)

type RTCEngine

type RTCEngine struct {
	JoinTimeout time.Duration

	// callbacks
	OnDisconnected          func()
	OnMediaTrack            func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver)
	OnParticipantUpdate     func([]*livekit.ParticipantInfo)
	OnActiveSpeakersChanged func([]*livekit.SpeakerInfo)
	OnSpeakersChanged       func([]*livekit.SpeakerInfo)
	OnDataReceived          func(userPacket *livekit.UserPacket)
	OnConnectionQuality     func([]*livekit.ConnectionQualityInfo)
	OnRoomUpdate            func(room *livekit.Room)
	OnRestarting            func()
	OnRestarted             func(*livekit.JoinResponse)
	OnResuming              func()
	OnResumed               func()
	// contains filtered or unexported fields
}

func NewRTCEngine

func NewRTCEngine() *RTCEngine

func (*RTCEngine) Close

func (e *RTCEngine) Close()

func (*RTCEngine) GetDataChannel added in v0.10.5

func (e *RTCEngine) GetDataChannel(kind livekit.DataPacket_Kind) *webrtc.DataChannel

func (*RTCEngine) GetDataChannelSub added in v0.10.5

func (e *RTCEngine) GetDataChannelSub(kind livekit.DataPacket_Kind) *webrtc.DataChannel

func (*RTCEngine) IsConnected

func (e *RTCEngine) IsConnected() bool

func (*RTCEngine) Join

func (e *RTCEngine) Join(url string, token string, params *ConnectParams) (*livekit.JoinResponse, error)

func (*RTCEngine) TrackPublishedChan

func (e *RTCEngine) TrackPublishedChan() <-chan *livekit.TrackPublishedResponse

type ReaderSampleProvider added in v0.10.1

type ReaderSampleProvider struct {
	// Configuration
	Mime            string
	FrameDuration   time.Duration
	OnWriteComplete func()
	AudioLevel      uint8
	// contains filtered or unexported fields
}

ReaderSampleProvider provides samples by reading from an io.ReadCloser implementation

func (*ReaderSampleProvider) Close added in v1.0.11

func (p *ReaderSampleProvider) Close() error

func (*ReaderSampleProvider) CurrentAudioLevel added in v0.10.1

func (p *ReaderSampleProvider) CurrentAudioLevel() uint8

func (*ReaderSampleProvider) NextSample added in v0.10.1

func (p *ReaderSampleProvider) NextSample(ctx context.Context) (media.Sample, error)

func (*ReaderSampleProvider) OnBind added in v0.10.1

func (p *ReaderSampleProvider) OnBind() error

func (*ReaderSampleProvider) OnUnbind added in v0.10.1

func (p *ReaderSampleProvider) OnUnbind() error

type ReaderSampleProviderOption added in v0.10.1

type ReaderSampleProviderOption func(*ReaderSampleProvider)

type RemoteParticipant

type RemoteParticipant struct {
	// contains filtered or unexported fields
}

func (*RemoteParticipant) AudioLevel

func (p *RemoteParticipant) AudioLevel() float32

func (*RemoteParticipant) GetTrack added in v0.8.0

func (p *RemoteParticipant) GetTrack(source livekit.TrackSource) TrackPublication

func (*RemoteParticipant) Identity

func (p *RemoteParticipant) Identity() string

func (*RemoteParticipant) IsCameraEnabled added in v0.8.0

func (p *RemoteParticipant) IsCameraEnabled() bool

func (*RemoteParticipant) IsMicrophoneEnabled added in v0.8.0

func (p *RemoteParticipant) IsMicrophoneEnabled() bool

func (*RemoteParticipant) IsScreenShareEnabled added in v0.8.0

func (p *RemoteParticipant) IsScreenShareEnabled() bool

func (*RemoteParticipant) IsSpeaking

func (p *RemoteParticipant) IsSpeaking() bool

func (*RemoteParticipant) Kind added in v1.1.8

func (p *RemoteParticipant) Kind() livekit.ParticipantInfo_Kind

func (*RemoteParticipant) Metadata added in v0.5.13

func (p *RemoteParticipant) Metadata() string

func (*RemoteParticipant) Name added in v0.8.2

func (p *RemoteParticipant) Name() string

func (*RemoteParticipant) Permissions added in v1.1.8

func (p *RemoteParticipant) Permissions() *livekit.ParticipantPermission

func (*RemoteParticipant) SID

func (p *RemoteParticipant) SID() string

func (*RemoteParticipant) Tracks

func (p *RemoteParticipant) Tracks() []TrackPublication

func (*RemoteParticipant) WritePLI added in v0.9.0

func (p *RemoteParticipant) WritePLI(ssrc webrtc.SSRC)

type RemoteTrackPublication

type RemoteTrackPublication struct {
	// contains filtered or unexported fields
}

func (*RemoteTrackPublication) IsEnabled added in v0.9.0

func (p *RemoteTrackPublication) IsEnabled() bool

func (*RemoteTrackPublication) IsMuted

func (p *RemoteTrackPublication) IsMuted() bool

func (*RemoteTrackPublication) IsSubscribed

func (p *RemoteTrackPublication) IsSubscribed() bool

func (*RemoteTrackPublication) Kind

func (p *RemoteTrackPublication) Kind() TrackKind

func (*RemoteTrackPublication) MimeType added in v0.8.2

func (p *RemoteTrackPublication) MimeType() string

func (*RemoteTrackPublication) Name

func (p *RemoteTrackPublication) Name() string

func (*RemoteTrackPublication) OnRTCP added in v0.9.0

func (p *RemoteTrackPublication) OnRTCP(cb func(rtcp.Packet))

func (*RemoteTrackPublication) Receiver

func (p *RemoteTrackPublication) Receiver() *webrtc.RTPReceiver

func (*RemoteTrackPublication) SID

func (p *RemoteTrackPublication) SID() string

func (*RemoteTrackPublication) SetEnabled added in v0.9.0

func (p *RemoteTrackPublication) SetEnabled(enabled bool)

func (*RemoteTrackPublication) SetSubscribed added in v0.9.0

func (p *RemoteTrackPublication) SetSubscribed(subscribed bool) error

func (*RemoteTrackPublication) SetVideoDimensions added in v0.9.0

func (p *RemoteTrackPublication) SetVideoDimensions(width uint32, height uint32)

func (*RemoteTrackPublication) Source added in v0.8.0

func (p *RemoteTrackPublication) Source() livekit.TrackSource

func (*RemoteTrackPublication) Track

func (p *RemoteTrackPublication) Track() Track

func (*RemoteTrackPublication) TrackInfo added in v0.10.2

func (p *RemoteTrackPublication) TrackInfo() *livekit.TrackInfo

func (*RemoteTrackPublication) TrackRemote

func (p *RemoteTrackPublication) TrackRemote() *webrtc.TrackRemote

type Room

type Room struct {
	LocalParticipant *LocalParticipant
	// contains filtered or unexported fields
}

func ConnectToRoom

func ConnectToRoom(url string, info ConnectInfo, callback *RoomCallback, opts ...ConnectOption) (*Room, error)

ConnectToRoom creates and joins the room

func ConnectToRoomWithToken

func ConnectToRoomWithToken(url, token string, callback *RoomCallback, opts ...ConnectOption) (*Room, error)

ConnectToRoomWithToken creates and joins the room

func CreateRoom added in v0.9.0

func CreateRoom(callback *RoomCallback) *Room

CreateRoom can be used to update callbacks before calling Join

func (*Room) ActiveSpeakers

func (r *Room) ActiveSpeakers() []Participant

func (*Room) Disconnect

func (r *Room) Disconnect()

func (*Room) GetParticipant

func (r *Room) GetParticipant(sid string) *RemoteParticipant

func (*Room) GetParticipants

func (r *Room) GetParticipants() []*RemoteParticipant

func (*Room) Join added in v0.9.0

func (r *Room) Join(url string, info ConnectInfo, opts ...ConnectOption) error

Join - joins the room as with default permissions

func (*Room) JoinWithToken added in v0.9.0

func (r *Room) JoinWithToken(url, token string, opts ...ConnectOption) error

JoinWithToken - customize participant options by generating your own token

func (*Room) Metadata added in v0.8.0

func (r *Room) Metadata() string

func (*Room) Name

func (r *Room) Name() string

func (*Room) SID

func (r *Room) SID() string

func (*Room) ServerInfo added in v1.0.0

func (r *Room) ServerInfo() *livekit.ServerInfo

func (*Room) Simulate added in v0.10.2

func (r *Room) Simulate(scenario SimulateScenario)

type RoomCallback

type RoomCallback struct {
	OnDisconnected            func()
	OnParticipantConnected    func(*RemoteParticipant)
	OnParticipantDisconnected func(*RemoteParticipant)
	OnActiveSpeakersChanged   func([]Participant)
	OnRoomMetadataChanged     func(metadata string)
	OnReconnecting            func()
	OnReconnected             func()

	// participant events are sent to the room as well
	ParticipantCallback
}

func NewRoomCallback

func NewRoomCallback() *RoomCallback

func (*RoomCallback) Merge added in v0.10.3

func (cb *RoomCallback) Merge(other *RoomCallback)

type RoomServiceClient

type RoomServiceClient struct {
	// contains filtered or unexported fields
}

func NewRoomServiceClient

func NewRoomServiceClient(url string, apiKey string, secretKey string) *RoomServiceClient

func (*RoomServiceClient) CreateRoom

func (*RoomServiceClient) CreateToken

func (c *RoomServiceClient) CreateToken() *auth.AccessToken

func (*RoomServiceClient) DeleteRoom

func (*RoomServiceClient) GetParticipant

func (*RoomServiceClient) ListParticipants

func (*RoomServiceClient) ListRooms

func (*RoomServiceClient) MutePublishedTrack

func (*RoomServiceClient) RemoveParticipant

func (*RoomServiceClient) SendData added in v0.7.1

func (*RoomServiceClient) UpdateParticipant

func (*RoomServiceClient) UpdateRoomMetadata added in v0.8.0

func (c *RoomServiceClient) UpdateRoomMetadata(ctx context.Context, req *livekit.UpdateRoomMetadataRequest) (*livekit.Room, error)

type SIPClient added in v1.1.4

type SIPClient struct {
	// contains filtered or unexported fields
}

func NewSIPClient added in v1.1.4

func NewSIPClient(url string, apiKey string, secretKey string) *SIPClient

func (*SIPClient) CreateSIPDispatchRule added in v1.1.4

func (*SIPClient) CreateSIPParticipant added in v1.1.4

func (*SIPClient) CreateSIPTrunk added in v1.1.4

func (*SIPClient) DeleteSIPDispatchRule added in v1.1.4

func (*SIPClient) DeleteSIPTrunk added in v1.1.4

func (*SIPClient) ListSIPDispatchRule added in v1.1.4

func (*SIPClient) ListSIPTrunk added in v1.1.4

type SampleProvider

type SampleProvider interface {
	NextSample(context.Context) (media.Sample, error)
	OnBind() error
	OnUnbind() error
	Close() error
}

type SampleWriteOptions added in v0.7.0

type SampleWriteOptions struct {
	AudioLevel *uint8
}

type SignalClient

type SignalClient struct {
	OnClose                 func()
	OnAnswer                func(sd webrtc.SessionDescription)
	OnOffer                 func(sd webrtc.SessionDescription)
	OnTrickle               func(init webrtc.ICECandidateInit, target livekit.SignalTarget)
	OnParticipantUpdate     func([]*livekit.ParticipantInfo)
	OnLocalTrackPublished   func(response *livekit.TrackPublishedResponse)
	OnSpeakersChanged       func([]*livekit.SpeakerInfo)
	OnConnectionQuality     func([]*livekit.ConnectionQualityInfo)
	OnRoomUpdate            func(room *livekit.Room)
	OnTrackRemoteMuted      func(request *livekit.MuteTrackRequest)
	OnLocalTrackUnpublished func(response *livekit.TrackUnpublishedResponse)
	OnTokenRefresh          func(refreshToken string)
	OnLeave                 func(*livekit.LeaveRequest)
	// contains filtered or unexported fields
}

func NewSignalClient

func NewSignalClient() *SignalClient

func (*SignalClient) Close

func (c *SignalClient) Close()

func (*SignalClient) IsStarted added in v0.10.2

func (c *SignalClient) IsStarted() bool

func (*SignalClient) Join

func (c *SignalClient) Join(urlPrefix string, token string, params *ConnectParams) (*livekit.JoinResponse, error)

func (*SignalClient) SendAnswer

func (c *SignalClient) SendAnswer(sd webrtc.SessionDescription) error

func (*SignalClient) SendICECandidate

func (c *SignalClient) SendICECandidate(candidate webrtc.ICECandidateInit, target livekit.SignalTarget) error

func (*SignalClient) SendLeave

func (c *SignalClient) SendLeave() error

func (*SignalClient) SendMuteTrack

func (c *SignalClient) SendMuteTrack(sid string, muted bool) error

func (*SignalClient) SendOffer

func (c *SignalClient) SendOffer(sd webrtc.SessionDescription) error

func (*SignalClient) SendRequest

func (c *SignalClient) SendRequest(req *livekit.SignalRequest) error

func (*SignalClient) SendSyncState added in v0.10.2

func (c *SignalClient) SendSyncState(state *livekit.SyncState) error

func (*SignalClient) SendUpdateParticipantMetadata added in v1.0.10

func (c *SignalClient) SendUpdateParticipantMetadata(metadata *livekit.UpdateParticipantMetadata) error

func (*SignalClient) SendUpdateTrackSettings added in v0.9.0

func (c *SignalClient) SendUpdateTrackSettings(settings *livekit.UpdateTrackSettings) error

func (*SignalClient) Start added in v0.10.1

func (c *SignalClient) Start()

type SimulateScenario added in v0.10.2

type SimulateScenario int
const (
	SimulateSignalReconnect SimulateScenario = iota
	SimulateForceTCP
	SimulateForceTLS
	SimulateSpeakerUpdate
	SimulateMigration
	SimulateServerLeave
	SimulateNodeFailure
)

type SimulcastTrack added in v0.9.0

type SimulcastTrack struct {
	// contains filtered or unexported fields
}

func NewSimulcastTrack added in v0.9.0

func NewSimulcastTrack(trackLocal webrtc.TrackLocal, videoLayer *livekit.VideoLayer) *SimulcastTrack

func (*SimulcastTrack) Quality added in v0.9.0

func (t *SimulcastTrack) Quality() livekit.VideoQuality

func (*SimulcastTrack) TrackLocal added in v0.9.0

func (t *SimulcastTrack) TrackLocal() webrtc.TrackLocal

func (*SimulcastTrack) VideoLayer added in v0.9.0

func (t *SimulcastTrack) VideoLayer() *livekit.VideoLayer

type Track

type Track interface {
	ID() string
}

type TrackKind

type TrackKind string
const (
	TrackKindVideo TrackKind = "video"
	TrackKindAudio TrackKind = "audio"
)

func KindFromRTPType

func KindFromRTPType(rt webrtc.RTPCodecType) TrackKind

func (TrackKind) ProtoType

func (k TrackKind) ProtoType() livekit.TrackType

func (TrackKind) RTPType

func (k TrackKind) RTPType() webrtc.RTPCodecType

func (TrackKind) String

func (k TrackKind) String() string

type TrackPubCallback

type TrackPubCallback func(track Track, pub TrackPublication, participant *RemoteParticipant)

type TrackPublication

type TrackPublication interface {
	Name() string
	SID() string
	Source() livekit.TrackSource
	Kind() TrackKind
	MimeType() string
	IsMuted() bool
	IsSubscribed() bool
	TrackInfo() *livekit.TrackInfo
	// Track is either a webrtc.TrackLocal or webrtc.TrackRemote
	Track() Track
	// contains filtered or unexported methods
}

type TrackPublicationOptions

type TrackPublicationOptions struct {
	Name   string
	Source livekit.TrackSource
	// Set dimensions for video
	VideoWidth  int
	VideoHeight int
	// Opus only
	DisableDTX bool
	Stereo     bool
}

Directories

Path Synopsis
examples
pkg
samplebuilder
Package samplebuilder builds media frames from RTP packets.
Package samplebuilder builds media frames from RTP packets.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL