lksdk

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2025 License: Apache-2.0 Imports: 62 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	MEDIA_ROUTER_SDK_SALT                = "LKFrameEncryptionKey"
	MEDIA_ROUTER_IV_LENGTH               = 12
	MEDIA_ROUTER_PBKDF_ITERATIONS        = 100000
	MEDIA_ROUTER_KEY_SIZE_BYTES          = 16
	MEDIA_ROUTER_HKDF_INFO_BYTES         = 128
	MEDIA_ROUTER_UNENCRYPTED_AUDIO_BYTES = 1
)
View Source
const (
	MaxMessageBytes = 256
	MaxDataBytes    = 15360 // 15KiB

	// Maximum payload size for RPC requests and responses. If a payload exceeds this size,
	// the RPC call will fail with a RpcRequestPayloadTooLarge(1402) or RpcResponsePayloadTooLarge(1504) error.
	MaxPayloadBytes = 15360 // 15KiB
)
View Source
const PROTOCOL = 16
View Source
const (
	// default max chunk size for streams
	STREAM_CHUNK_SIZE = 15_000
)
View Source
const (
	SimulateSpeakerUpdateInterval = 5
)
View Source
const Version = "2.9.2"

Variables

View Source
var (
	ErrIncorrectKeyLength    = errors.New("incorrect key length for encryption/decryption")
	ErrUnableGenerateIV      = errors.New("unable to generate iv for encryption")
	ErrIncorrectIVLength     = errors.New("incorrect iv length")
	ErrIncorrectSecretLength = errors.New("input secret provided to derivation function cannot be empty or nil")
	ErrIncorrectSaltLength   = errors.New("input salt provided to derivation function cannot be empty or nil")
	ErrBlockCipherRequired   = errors.New("input block cipher cannot be nil")
)
View Source
var (
	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")
	ErrInvalidMessageType       = signalling.ErrInvalidMessageType
	ErrInvalidParameter         = signalling.ErrInvalidParameter
	ErrNoPeerConnection         = errors.New("peer connection not established")
	ErrAborted                  = errors.New("operation was aborted")
)

Functions

func ChatMessage

func ChatMessage(ts time.Time, text string) *media_router.ChatMessage

ChatMessage creates a chat message that can be sent via WebRTC.

func DecryptGCMAudioSample

func DecryptGCMAudioSample(sample, key, sifTrailer []byte) ([]byte, error)

Take audio sample (body of RTP) encrypted by Vibtree client SDK, extract IV and decrypt using provided key If sample matches sifTrailer, it's considered to be a non-encrypted Server Injected Frame and nil is returned Use DecryptGCMAudioSampleCustomCipher with cached aes cipher block for better (30%) performance

func DecryptGCMAudioSampleCustomCipher

func DecryptGCMAudioSampleCustomCipher(sample, sifTrailer []byte, cipherBlock cipher.Block) ([]byte, error)

Take audio sample (body of RTP) encrypted by Vibtree client SDK, extract IV and decrypt using provided cipherBlock If sample matches sifTrailer, it's considered to be a non-encrypted Server Injected Frame and nil is returned Encrypted sample format based on Vibtree client SDK ---------+-------------------------+---------+---- payload |IV...(length = IV_LENGTH)|IV_LENGTH|KID| ---------+-------------------------+---------+---- First byte of audio frame is not encrypted and only authenticated payload - variable bytes IV - variable bytes (equal to IV_LENGTH bytes) IV_LENGTH - 1 byte KID (Key ID) - 1 byte - ignored here, key is provided as parameter to function

func DeriveKeyFromBytes

func DeriveKeyFromBytes(secret []byte) ([]byte, error)

func DeriveKeyFromBytesCustomSalt

func DeriveKeyFromBytesCustomSalt(secret []byte, salt string) ([]byte, error)

func DeriveKeyFromString

func DeriveKeyFromString(password string) ([]byte, error)

func DeriveKeyFromStringCustomSalt

func DeriveKeyFromStringCustomSalt(password, salt string) ([]byte, error)

func EncryptGCMAudioSample

func EncryptGCMAudioSample(sample, key []byte, kid uint8) ([]byte, error)

Take audio sample (body of RTP) and encrypts it using AES-GCM 128bit with provided key Use EncryptGCMAudioSampleCustomCipher with cached aes cipher block for better (20%) performance

func EncryptGCMAudioSampleCustomCipher

func EncryptGCMAudioSampleCustomCipher(sample []byte, kid uint8, cipherBlock cipher.Block) ([]byte, error)

Take audio sample (body of RTP) and encrypts it using AES-GCM 128bit with provided cipher block Encrypted sample format based on Vibtree client sdk ---------+-------------------------+---------+---- payload |IV...(length = IV_LENGTH)|IV_LENGTH|KID| ---------+-------------------------+---------+---- First byte of audio frame is not encrypted and only authenticated payload - variable bytes IV - variable bytes (equal to IV_LENGTH bytes) - 12 random bytes IV_LENGTH - 1 byte - 12 bytes fixed KID (Key ID) - 1 byte - taken from "kid" parameter

func ReaderTrackWithFrameDuration

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

func ReaderTrackWithMime

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

func ReaderTrackWithOnWriteComplete

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

func ReaderTrackWithRTCPHandler

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

func ReaderTrackWithSampleOptions

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

func SIPStatusFrom

func SIPStatusFrom(err error) *media_router.SIPStatus

SIPStatusFrom unwraps an error and returns associated SIP call status, if any.

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))

Types

type AgentClient

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

func NewAgentClient

func NewAgentClient(url string, apiKey string, apiSecret string, opts ...twirp.ClientOption) (*AgentClient, error)

func (*AgentClient) CreateAgent

func (c *AgentClient) CreateAgent(ctx context.Context, req *media_router.CreateAgentRequest) (*media_router.CreateAgentResponse, error)

func (*AgentClient) DeleteAgent

func (c *AgentClient) DeleteAgent(ctx context.Context, req *media_router.DeleteAgentRequest) (*media_router.DeleteAgentResponse, error)

func (*AgentClient) DeployAgent

func (c *AgentClient) DeployAgent(ctx context.Context, req *media_router.DeployAgentRequest) (*media_router.DeployAgentResponse, error)

func (*AgentClient) GetClientSettings

func (c *AgentClient) GetClientSettings(ctx context.Context, req *media_router.ClientSettingsRequest) (*media_router.ClientSettingsResponse, error)

func (*AgentClient) ListAgentSecrets

func (c *AgentClient) ListAgentSecrets(ctx context.Context, req *media_router.ListAgentSecretsRequest) (*media_router.ListAgentSecretsResponse, error)

func (*AgentClient) ListAgentVersions

func (c *AgentClient) ListAgentVersions(ctx context.Context, req *media_router.ListAgentVersionsRequest) (*media_router.ListAgentVersionsResponse, error)

func (*AgentClient) ListAgents

func (c *AgentClient) ListAgents(ctx context.Context, req *media_router.ListAgentsRequest) (*media_router.ListAgentsResponse, error)

func (*AgentClient) RestartAgent

func (c *AgentClient) RestartAgent(ctx context.Context, req *media_router.RestartAgentRequest) (*media_router.RestartAgentResponse, error)

func (*AgentClient) RollbackAgent

func (c *AgentClient) RollbackAgent(ctx context.Context, req *media_router.RollbackAgentRequest) (*media_router.RollbackAgentResponse, error)

func (*AgentClient) UpdateAgent

func (c *AgentClient) UpdateAgent(ctx context.Context, req *media_router.UpdateAgentRequest) (*media_router.UpdateAgentResponse, error)

func (*AgentClient) UpdateAgentSecrets

func (c *AgentClient) UpdateAgentSecrets(ctx context.Context, req *media_router.UpdateAgentSecretsRequest) (*media_router.UpdateAgentSecretsResponse, error)

type AgentDispatchClient

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

func NewAgentDispatchServiceClient

func NewAgentDispatchServiceClient(url string, apiKey string, secretKey string, opts ...twirp.ClientOption) *AgentDispatchClient

func (*AgentDispatchClient) CreateDispatch

func (c *AgentDispatchClient) CreateDispatch(ctx context.Context, req *media_router.CreateAgentDispatchRequest) (*media_router.AgentDispatch, error)

func (*AgentDispatchClient) DeleteDispatch

func (c *AgentDispatchClient) DeleteDispatch(ctx context.Context, req *media_router.DeleteAgentDispatchRequest) (*media_router.AgentDispatch, error)

func (*AgentDispatchClient) ListDispatch

func (c *AgentDispatchClient) ListDispatch(ctx context.Context, req *media_router.ListAgentDispatchRequest) (*media_router.ListAgentDispatchResponse, error)

type AudioSampleProvider

type AudioSampleProvider interface {
	SampleProvider
	CurrentAudioLevel() uint8
}

type BaseSampleProvider

type BaseSampleProvider struct {
}

BaseSampleProvider provides empty implementations for OnBind and OnUnbind

func (*BaseSampleProvider) Close

func (p *BaseSampleProvider) Close() error

func (*BaseSampleProvider) OnBind

func (p *BaseSampleProvider) OnBind() error

func (*BaseSampleProvider) OnUnbind

func (p *BaseSampleProvider) OnUnbind() error

type ByteStreamHandler

type ByteStreamHandler func(reader *ByteStreamReader, participantIdentity string)

ByteStreamHandler is a function that will be called when a byte stream is received. It will be called with the stream reader and the participant identity that sent the stream.

type ByteStreamInfo

type ByteStreamInfo struct {
	Name *string
	// contains filtered or unexported fields
}

Info for byte streams

  • Id is the id of the stream
  • MimeType is the mime type of the stream, determined for SendFile if not provided
  • Topic is the topic of the stream
  • Timestamp is the timestamp of sending the stream
  • Size is the total size of the stream, if provided
  • Attributes are any additional attributes of the stream
  • Name is the name of the file or stream, if provided

type ByteStreamReader

type ByteStreamReader struct {
	Info ByteStreamInfo
	// contains filtered or unexported fields
}

func NewByteStreamReader

func NewByteStreamReader(info ByteStreamInfo, totalChunkCount *uint64) *ByteStreamReader

func (ByteStreamReader) OnProgress

func (r ByteStreamReader) OnProgress(onProgress *func(progress float64))

OnProgress sets the callback function that will be called when the stream is being read only called if TotalSize of the stream is set

func (ByteStreamReader) Read

func (r ByteStreamReader) Read(bytes []byte) (int, error)

Read reads the next len(p) bytes from the stream or until the stream buffer is drained. The return value is the number of bytes read. If the buffer has no data to return, it will wait for a write to the stream or return io.EOF if the stream is closed.

func (*ByteStreamReader) ReadAll

func (r *ByteStreamReader) ReadAll() []byte

ReadAll reads all the data from the stream and returns it as a byte slice. This will block until the stream is closed.

func (ByteStreamReader) ReadByte

func (r ByteStreamReader) ReadByte() (byte, error)

ReadByte reads and returns the next byte from the buffer. If no byte is available, it will wait for a write to the stream or return io.EOF if the stream is closed.

func (ByteStreamReader) ReadBytes

func (r ByteStreamReader) ReadBytes(delim byte) ([]byte, error)

ReadBytes reads until the first occurrence of delim in the input, returning a slice containing the data up to and including the delimiter. If ReadBytes encounters an error before finding a delimiter, it returns the data read before EOF, but does not return EOF until the stream is closed. ReadBytes returns err != nil if and only if the returned data does not end in delim.

type ByteStreamWriter

type ByteStreamWriter struct {
	Info ByteStreamInfo
	// contains filtered or unexported fields
}

ByteStreamWriter is a writer type for byte streams

func (ByteStreamWriter) Close

func (w ByteStreamWriter) Close()

Close the stream, this will send a stream trailer to notify the receiver that the stream is closed

func (ByteStreamWriter) Write

func (w ByteStreamWriter) Write(data T, onDone *func())

Write data to the stream, data can be a byte slice or a string depending on the type of the stream writer onDone is a callback function that will be called when the data provided is written to the stream

type ConnectInfo

type ConnectInfo struct {
	APIKey                string
	APISecret             string
	RoomName              string
	ParticipantName       string
	ParticipantIdentity   string
	ParticipantKind       ParticipantKind
	ParticipantMetadata   string
	ParticipantAttributes map[string]string
}

type ConnectOption

type ConnectOption func(*signalling.ConnectParams)

func WithAutoSubscribe

func WithAutoSubscribe(val bool) ConnectOption

func WithDisableRegionDiscovery

func WithDisableRegionDiscovery() ConnectOption

func WithExtraAttributes

func WithExtraAttributes(attrs map[string]string) ConnectOption

func WithICETransportPolicy

func WithICETransportPolicy(iceTransportPolicy webrtc.ICETransportPolicy) ConnectOption

func WithInterceptors

func WithInterceptors(interceptors []interceptor.Factory) ConnectOption

func WithMetadata

func WithMetadata(metadata string) ConnectOption

func WithPacer

func WithPacer(pacer pacer.Factory) ConnectOption

WithPacer enables the use of a pacer on this connection A pacer helps to smooth out video packet rate to avoid overwhelming downstream. Learn more at: https://chromium.googlesource.com/external/webrtc/+/master/modules/pacing/g3doc/index.md

func WithRetransmitBufferSize

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 ConnectionState

type ConnectionState string
const (
	ConnectionStateConnected    ConnectionState = "connected"
	ConnectionStateReconnecting ConnectionState = "reconnecting"
	ConnectionStateDisconnected ConnectionState = "disconnected"
)

type DataPacket

type DataPacket interface {
	ToProto() *media_router.DataPacket
}

type DataPublishOption

type DataPublishOption func(*dataPublishOptions)

func WithDataPublishDestination

func WithDataPublishDestination(identities []string) DataPublishOption

func WithDataPublishReliable

func WithDataPublishReliable(reliable bool) DataPublishOption

func WithDataPublishTopic

func WithDataPublishTopic(topic string) DataPublishOption

type DataReceiveParams

type DataReceiveParams struct {
	Sender         *RemoteParticipant
	SenderIdentity string
	Topic          string // Deprecated: Use UserDataPacket.Topic
}

type DisconnectionReason

type DisconnectionReason string
const (
	LeaveRequested     DisconnectionReason = "leave requested by user"
	UserUnavailable    DisconnectionReason = "remote user unavailable"
	RejectedByUser     DisconnectionReason = "rejected by remote user"
	Failed             DisconnectionReason = "connection to room failed"
	RoomClosed         DisconnectionReason = "room closed"
	ParticipantRemoved DisconnectionReason = "removed by server"
	DuplicateIdentity  DisconnectionReason = "duplicate identity"
	OtherReason        DisconnectionReason = "other reasons"
)

type EgressClient

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

func NewEgressClient

func NewEgressClient(url string, apiKey string, secretKey string, opts ...twirp.ClientOption) *EgressClient

func (*EgressClient) ListEgress

func (*EgressClient) StartParticipantEgress

func (*EgressClient) StartRoomCompositeEgress

func (*EgressClient) StartTrackCompositeEgress

func (*EgressClient) StartTrackEgress

func (*EgressClient) StartWebEgress

func (*EgressClient) StopEgress

func (*EgressClient) UpdateLayout

func (*EgressClient) UpdateStream

type IngressClient

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

func NewIngressClient

func NewIngressClient(url string, apiKey string, secretKey string, opts ...twirp.ClientOption) *IngressClient

func (*IngressClient) CreateIngress

func (*IngressClient) DeleteIngress

func (*IngressClient) UpdateIngress

type LocalParticipant

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

func (*LocalParticipant) Attributes

func (p *LocalParticipant) Attributes() map[string]string

func (*LocalParticipant) AudioLevel

func (p *LocalParticipant) AudioLevel() float32

func (*LocalParticipant) GetPublisherPeerConnection

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

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) GetTrackPublication

func (p *LocalParticipant) GetTrackPublication(source media_router.TrackSource) TrackPublication

func (*LocalParticipant) HandleIncomingRpcAck

func (p *LocalParticipant) HandleIncomingRpcAck(requestId string)

func (*LocalParticipant) HandleIncomingRpcResponse

func (p *LocalParticipant) HandleIncomingRpcResponse(requestId string, payload *string, error *RpcError)

func (*LocalParticipant) Identity

func (p *LocalParticipant) Identity() string

func (*LocalParticipant) IsCameraEnabled

func (p *LocalParticipant) IsCameraEnabled() bool

func (*LocalParticipant) IsMicrophoneEnabled

func (p *LocalParticipant) IsMicrophoneEnabled() bool

func (*LocalParticipant) IsScreenShareAudioEnabled

func (p *LocalParticipant) IsScreenShareAudioEnabled() bool

func (*LocalParticipant) IsScreenShareEnabled

func (p *LocalParticipant) IsScreenShareEnabled() bool

func (*LocalParticipant) IsSpeaking

func (p *LocalParticipant) IsSpeaking() bool

func (*LocalParticipant) Kind

func (p *LocalParticipant) Kind() ParticipantKind

func (*LocalParticipant) Metadata

func (p *LocalParticipant) Metadata() string

func (*LocalParticipant) Name

func (p *LocalParticipant) Name() string

func (*LocalParticipant) PerformRpc

func (p *LocalParticipant) PerformRpc(params PerformRpcParams) (*string, error)

Initiate an RPC call to a remote participant

  • @param params - For parameters for initiating the RPC call, see PerformRpcParams
  • @returns A string payload or an error

func (*LocalParticipant) Permissions

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

func (*LocalParticipant) PublishData deprecated

func (p *LocalParticipant) PublishData(payload []byte, opts ...DataPublishOption) error

PublishData sends custom user data via WebRTC data channel.

By default, the message can be received by all participants in a room, see WithDataPublishDestination for choosing specific participants.

Messages are sent via a LOSSY channel by default, see WithDataPublishReliable for sending reliable data.

Deprecated: Use PublishDataPacket with UserData instead.

func (*LocalParticipant) PublishDataPacket

func (p *LocalParticipant) PublishDataPacket(pck DataPacket, opts ...DataPublishOption) error

PublishDataPacket sends a packet via a WebRTC data channel. UserData can be used for sending custom user data.

By default, the message can be received by all participants in a room, see WithDataPublishDestination for choosing specific participants.

Messages are sent via UDP and offer no delivery guarantees, see WithDataPublishReliable for sending data reliably (with retries).

func (*LocalParticipant) PublishSimulcastTrack

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

PublishSimulcastTrack publishes up to three layers to the server

func (*LocalParticipant) PublishTrack

func (*LocalParticipant) SID

func (p *LocalParticipant) SID() string

func (*LocalParticipant) SendFile

func (p *LocalParticipant) SendFile(filePath string, options StreamBytesOptions) (*ByteStreamInfo, error)

SendFile sends a file to the remote participant as a byte stream with the provided options. It will return a ByteStreamInfo that can be used to get metadata about the stream. Error is returned if the file cannot be read.

func (*LocalParticipant) SendText

func (p *LocalParticipant) SendText(text string, options StreamTextOptions) *TextStreamInfo

SendText creates a new text stream writer with the provided options. It will return a TextStreamInfo that can be used to get metadata about the stream.

func (*LocalParticipant) SetAttributes

func (p *LocalParticipant) SetAttributes(attrs map[string]string)

SetAttributes sets the KV attributes of the current participant. To remove an attribute, set it to empty value. Updates will be performed only if the participant has canUpdateOwnMetadata grant.

func (*LocalParticipant) SetMetadata

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

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) SetSubscriptionPermission

func (p *LocalParticipant) SetSubscriptionPermission(sp *media_router.SubscriptionPermission)

Control who can subscribe to LocalParticipant's published tracks.

By default, all participants can subscribe. This allows fine-grained control over who is able to subscribe at a participant and track level.

Note: if access is given at a track-level (i.e. both `AllParticipants` and `TrackPermission.AllTracks` are false), any newer published tracks will not grant permissions to any participants and will require a subsequent permissions update to allow subscription.

func (*LocalParticipant) StreamBytes

func (p *LocalParticipant) StreamBytes(options StreamBytesOptions) *ByteStreamWriter

StreamBytes creates a new byte stream writer with the provided options.

func (*LocalParticipant) StreamText

func (p *LocalParticipant) StreamText(options StreamTextOptions) *TextStreamWriter

StreamText creates a new text stream writer with the provided options.

func (*LocalParticipant) TrackPublications

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

func (*LocalParticipant) UnpublishTrack

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

type LocalSampleTrack

type LocalSampleTrack = LocalTrack

type LocalSampleTrackOptions

type LocalSampleTrackOptions = LocalTrackOptions

type LocalTrack

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

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

NewLocalFileTrack creates an *os.File reader for NewLocalReaderTrack

func NewLocalReaderTrack

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

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

func (*LocalTrack) Bind

Bind is an interface for TrackLocal, not for external consumption

func (*LocalTrack) Close

func (s *LocalTrack) Close() error

func (*LocalTrack) Codec

Codec gets the Codec of the track

func (*LocalTrack) ID

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

func (s *LocalTrack) IsBound() bool

func (*LocalTrack) Kind

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

Kind controls if this TrackLocal is audio or video

func (*LocalTrack) OnBind

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

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

func (s *LocalTrack) RID() string

RID is the RTP stream identifier.

func (*LocalTrack) SSRC

func (s *LocalTrack) SSRC() webrtc.SSRC

func (*LocalTrack) SetLogger

func (s *LocalTrack) SetLogger(l protoLogger.Logger)

SetLogger overrides default logger.

func (*LocalTrack) SetTransceiver

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

func (*LocalTrack) StartWrite

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

func (*LocalTrack) StreamID

func (s *LocalTrack) StreamID() string

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

func (*LocalTrack) Unbind

Unbind is an interface for TrackLocal, not for external consumption

func (*LocalTrack) WriteRTP

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

func (*LocalTrack) WriteSample

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

type LocalTrackOptions

type LocalTrackOptions func(s *LocalTrack)

func WithRTCPHandler

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

func WithSimulcast

func WithSimulcast(simulcastID string, layer *media_router.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

func NewLocalTrackPublication(kind TrackKind, track Track, opts TrackPublicationOptions, engine *RTCEngine) *LocalTrackPublication

func (*LocalTrackPublication) CloseTrack

func (p *LocalTrackPublication) CloseTrack()

func (*LocalTrackPublication) GetSimulcastTrack

func (p *LocalTrackPublication) GetSimulcastTrack(quality media_router.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

func (p *LocalTrackPublication) MimeType() string

func (*LocalTrackPublication) Name

func (p *LocalTrackPublication) Name() string

func (*LocalTrackPublication) PublicationOptions

func (p *LocalTrackPublication) PublicationOptions() TrackPublicationOptions

func (*LocalTrackPublication) SID

func (p *LocalTrackPublication) SID() string

func (*LocalTrackPublication) SetMuted

func (p *LocalTrackPublication) SetMuted(muted bool)

func (*LocalTrackPublication) SimulateDisconnection

func (p *LocalTrackPublication) SimulateDisconnection(duration time.Duration)

func (*LocalTrackPublication) Source

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

func (*LocalTrackPublication) Track

func (p *LocalTrackPublication) Track() Track

func (*LocalTrackPublication) TrackInfo

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

func (*LocalTrackPublication) TrackLocal

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

type LocalTrackWithClose

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

type MuteFunc

type MuteFunc func(muted bool) 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) GetLocalOffer

func (t *PCTransport) GetLocalOffer() (webrtc.SessionDescription, error)

func (*PCTransport) GetSelectedCandidatePair

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

func (*PCTransport) IsConnected

func (t *PCTransport) IsConnected() bool

func (*PCTransport) Negotiate

func (t *PCTransport) Negotiate()

func (*PCTransport) OnRemoteDescriptionSettled

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

func (*PCTransport) PeerConnection

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

func (*PCTransport) SetConfiguration

func (t *PCTransport) SetConfiguration(config webrtc.Configuration) error

func (*PCTransport) SetLocalOffer

func (t *PCTransport) SetLocalOffer(offer webrtc.SessionDescription)

func (*PCTransport) SetLogger

func (t *PCTransport) SetLogger(l protoLogger.Logger)

SetLogger overrides default logger.

func (*PCTransport) SetRTT

func (t *PCTransport) SetRTT(rtt uint32)

func (*PCTransport) SetRemoteDescription

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

type PCTransportParams

type PCTransportParams struct {
	Configuration webrtc.Configuration

	RetransmitBufferSize uint16
	Pacer                pacer.Factory
	Interceptors         []interceptor.Factory
	OnRTTUpdate          func(rtt uint32)
	IsSender             bool
}

type PLIWriter

type PLIWriter func(webrtc.SSRC)

type Participant

type Participant interface {
	SID() string
	Identity() string
	Name() string
	Kind() ParticipantKind
	IsSpeaking() bool
	AudioLevel() float32
	TrackPublications() []TrackPublication
	IsCameraEnabled() bool
	IsMicrophoneEnabled() bool
	IsScreenShareEnabled() bool
	IsScreenShareAudioEnabled() bool
	Metadata() string
	Attributes() map[string]string
	GetTrackPublication(source media_router.TrackSource) TrackPublication
	Permissions() *media_router.ParticipantPermission
	// contains filtered or unexported methods
}

type ParticipantAttributesChangedFunc

type ParticipantAttributesChangedFunc func(changed map[string]string, p Participant)

ParticipantAttributesChangedFunc is callback for Participant attribute change event. The function is called with an already updated participant state and the map of changes attributes. Deleted attributes will have empty string value in the changed map.

type ParticipantCallback

type ParticipantCallback struct {
	// for local participant
	OnLocalTrackPublished   func(publication *LocalTrackPublication, lp *LocalParticipant)
	OnLocalTrackUnpublished func(publication *LocalTrackPublication, lp *LocalParticipant)

	// for all participants
	OnTrackMuted               func(pub TrackPublication, p Participant)
	OnTrackUnmuted             func(pub TrackPublication, p Participant)
	OnMetadataChanged          func(oldMetadata string, p Participant)
	OnAttributesChanged        ParticipantAttributesChangedFunc
	OnIsSpeakingChanged        func(p Participant)
	OnConnectionQualityChanged func(update *media_router.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, params DataReceiveParams) // Deprecated: Use OnDataPacket instead
	OnDataPacket              func(data DataPacket, params DataReceiveParams)
	OnTranscriptionReceived   func(transcriptionSegments []*TranscriptionSegment, p Participant, publication TrackPublication)
}

func NewParticipantCallback

func NewParticipantCallback() *ParticipantCallback

func (*ParticipantCallback) Merge

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

type ParticipantKind

type ParticipantKind int

type PerformRpcParams

type PerformRpcParams struct {
	// The identity of the destination participant
	DestinationIdentity string
	// The name of the method to call
	Method string
	// The method payload
	Payload string
	// Timeout for receiving a response after initial connection. Default: 10000ms
	ResponseTimeout *time.Duration
}

Parameters for initiating an RPC call

type Private

type Private[T any] struct {
	// contains filtered or unexported fields
}

func MakePrivate

func MakePrivate[T any](v T) Private[T]

type PubCallback

type PubCallback func(pub TrackPublication, participant *RemoteParticipant)

type RTCEngine

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

func NewRTCEngine

func NewRTCEngine(
	engineHandler engineHandler,
	getLocalParticipantSID func() string,
) *RTCEngine

func (*RTCEngine) Close

func (e *RTCEngine) Close()

func (*RTCEngine) GetDataChannel

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

func (*RTCEngine) GetDataChannelSub

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

func (*RTCEngine) IsConnected

func (e *RTCEngine) IsConnected() bool

func (*RTCEngine) JoinContext

func (e *RTCEngine) JoinContext(
	ctx context.Context,
	url string,
	token string,
	connectParams *signalling.ConnectParams,
) (bool, error)

func (*RTCEngine) OnAnswer

func (e *RTCEngine) OnAnswer(sd webrtc.SessionDescription, answerId uint32)

func (*RTCEngine) OnClose

func (e *RTCEngine) OnClose(onClose func())

func (*RTCEngine) OnConnectionQuality

func (e *RTCEngine) OnConnectionQuality(cqi []*media_router.ConnectionQualityInfo)

func (*RTCEngine) OnJoinResponse

func (e *RTCEngine) OnJoinResponse(res *media_router.JoinResponse) error

signalling.SignalProcessor implementation

func (*RTCEngine) OnLeave

func (e *RTCEngine) OnLeave(leave *media_router.LeaveRequest)

func (*RTCEngine) OnLocalTrackPublished

func (e *RTCEngine) OnLocalTrackPublished(res *media_router.TrackPublishedResponse)

func (*RTCEngine) OnLocalTrackSubscribed

func (e *RTCEngine) OnLocalTrackSubscribed(trackSubscribed *media_router.TrackSubscribed)

func (*RTCEngine) OnLocalTrackUnpublished

func (e *RTCEngine) OnLocalTrackUnpublished(res *media_router.TrackUnpublishedResponse)

func (*RTCEngine) OnOffer

func (e *RTCEngine) OnOffer(sd webrtc.SessionDescription, offerId uint32)

func (*RTCEngine) OnParticipantUpdate

func (e *RTCEngine) OnParticipantUpdate(info []*media_router.ParticipantInfo)

func (*RTCEngine) OnReconnectResponse

func (e *RTCEngine) OnReconnectResponse(res *media_router.ReconnectResponse) error

func (*RTCEngine) OnRoomMoved

func (e *RTCEngine) OnRoomMoved(moved *media_router.RoomMovedResponse)

func (*RTCEngine) OnRoomUpdate

func (e *RTCEngine) OnRoomUpdate(room *media_router.Room)

func (*RTCEngine) OnSpeakersChanged

func (e *RTCEngine) OnSpeakersChanged(si []*media_router.SpeakerInfo)

func (*RTCEngine) OnSubscribedQualityUpdate

func (e *RTCEngine) OnSubscribedQualityUpdate(subscribedQualityUpdate *media_router.SubscribedQualityUpdate)

func (*RTCEngine) OnTokenRefresh

func (e *RTCEngine) OnTokenRefresh(refreshToken string)

func (*RTCEngine) OnTrackRemoteMuted

func (e *RTCEngine) OnTrackRemoteMuted(request *media_router.MuteTrackRequest)

func (*RTCEngine) OnTransportClose

func (e *RTCEngine) OnTransportClose()

signalling.SignalTransportHandler implementation

func (*RTCEngine) OnTrickle

func (e *RTCEngine) OnTrickle(init webrtc.ICECandidateInit, target media_router.SignalTarget)

func (*RTCEngine) Publisher

func (e *RTCEngine) Publisher() (*PCTransport, bool)

func (*RTCEngine) RegisterTrackPublishedListener

func (e *RTCEngine) RegisterTrackPublishedListener(cid string, c chan *media_router.TrackPublishedResponse)

func (*RTCEngine) SendAddTrack

func (e *RTCEngine) SendAddTrack(addTrack *media_router.AddTrackRequest) error

func (*RTCEngine) SendLeaveWithReason

func (e *RTCEngine) SendLeaveWithReason(reason media_router.DisconnectReason) error

func (*RTCEngine) SendMuteTrack

func (e *RTCEngine) SendMuteTrack(sid string, muted bool) error

func (*RTCEngine) SendSubscriptionPermission

func (e *RTCEngine) SendSubscriptionPermission(subscriptionPermission *media_router.SubscriptionPermission) error

func (*RTCEngine) SendSyncState

func (e *RTCEngine) SendSyncState(syncState *media_router.SyncState) error

func (*RTCEngine) SendUpdateParticipantMetadata

func (e *RTCEngine) SendUpdateParticipantMetadata(metadata *media_router.UpdateParticipantMetadata) error

func (*RTCEngine) SendUpdateSubscription

func (e *RTCEngine) SendUpdateSubscription(updateSubscription *media_router.UpdateSubscription) error

func (*RTCEngine) SendUpdateTrackSettings

func (e *RTCEngine) SendUpdateTrackSettings(settings *media_router.UpdateTrackSettings) error

func (*RTCEngine) SetLogger

func (e *RTCEngine) SetLogger(l protoLogger.Logger)

SetLogger overrides default logger.

func (*RTCEngine) Simulate

func (e *RTCEngine) Simulate(scenario SimulateScenario)

func (*RTCEngine) Subscriber

func (e *RTCEngine) Subscriber() (*PCTransport, bool)

func (*RTCEngine) UnregisterTrackPublishedListener

func (e *RTCEngine) UnregisterTrackPublishedListener(cid string)

type ReaderSampleProvider

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

func (p *ReaderSampleProvider) Close() error

func (*ReaderSampleProvider) CurrentAudioLevel

func (p *ReaderSampleProvider) CurrentAudioLevel() uint8

func (*ReaderSampleProvider) NextSample

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

func (*ReaderSampleProvider) OnBind

func (p *ReaderSampleProvider) OnBind() error

func (*ReaderSampleProvider) OnUnbind

func (p *ReaderSampleProvider) OnUnbind() error

type ReaderSampleProviderOption

type ReaderSampleProviderOption func(*ReaderSampleProvider)

type RemoteParticipant

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

func (*RemoteParticipant) Attributes

func (p *RemoteParticipant) Attributes() map[string]string

func (*RemoteParticipant) AudioLevel

func (p *RemoteParticipant) AudioLevel() float32

func (*RemoteParticipant) GetTrackPublication

func (p *RemoteParticipant) GetTrackPublication(source media_router.TrackSource) TrackPublication

func (*RemoteParticipant) Identity

func (p *RemoteParticipant) Identity() string

func (*RemoteParticipant) IsCameraEnabled

func (p *RemoteParticipant) IsCameraEnabled() bool

func (*RemoteParticipant) IsMicrophoneEnabled

func (p *RemoteParticipant) IsMicrophoneEnabled() bool

func (*RemoteParticipant) IsScreenShareAudioEnabled

func (p *RemoteParticipant) IsScreenShareAudioEnabled() bool

func (*RemoteParticipant) IsScreenShareEnabled

func (p *RemoteParticipant) IsScreenShareEnabled() bool

func (*RemoteParticipant) IsSpeaking

func (p *RemoteParticipant) IsSpeaking() bool

func (*RemoteParticipant) Kind

func (p *RemoteParticipant) Kind() ParticipantKind

func (*RemoteParticipant) Metadata

func (p *RemoteParticipant) Metadata() string

func (*RemoteParticipant) Name

func (p *RemoteParticipant) Name() string

func (*RemoteParticipant) Permissions

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

func (*RemoteParticipant) SID

func (p *RemoteParticipant) SID() string

func (*RemoteParticipant) TrackPublications

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

func (*RemoteParticipant) WritePLI

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

type RemoteTrackPublication

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

func (*RemoteTrackPublication) IsEnabled

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

func (p *RemoteTrackPublication) MimeType() string

func (*RemoteTrackPublication) Name

func (p *RemoteTrackPublication) Name() string

func (*RemoteTrackPublication) OnRTCP

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

func (p *RemoteTrackPublication) SetEnabled(enabled bool)

func (*RemoteTrackPublication) SetSubscribed

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

func (*RemoteTrackPublication) SetVideoDimensions

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

func (*RemoteTrackPublication) SetVideoQuality

func (p *RemoteTrackPublication) SetVideoQuality(quality media_router.VideoQuality) error

func (*RemoteTrackPublication) Source

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

func (*RemoteTrackPublication) Track

func (p *RemoteTrackPublication) Track() Track

func (*RemoteTrackPublication) TrackInfo

func (p *RemoteTrackPublication) TrackInfo() *media_router.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 NewRoom

func NewRoom(callback *RoomCallback) *Room

NewRoom can be used to update callbacks before calling Join

func (*Room) ActiveSpeakers

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

func (*Room) ConnectionState

func (r *Room) ConnectionState() ConnectionState

func (*Room) Disconnect

func (r *Room) Disconnect()

func (*Room) DisconnectWithReason

func (r *Room) DisconnectWithReason(reason media_router.DisconnectReason)

func (*Room) GetParticipantByIdentity

func (r *Room) GetParticipantByIdentity(identity string) *RemoteParticipant

func (*Room) GetParticipantBySID

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

func (*Room) GetRemoteParticipants

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

func (*Room) Join

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

Join - joins the room as with default permissions

func (*Room) JoinWithToken

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

JoinWithToken - customize participant options by generating your own token

func (*Room) Metadata

func (r *Room) Metadata() string

func (*Room) Name

func (r *Room) Name() string

func (*Room) OnConnectionQuality

func (n *Room) OnConnectionQuality([]*media_router.ConnectionQualityInfo)

func (*Room) OnConnectionQualityUpdate

func (r *Room) OnConnectionQualityUpdate(updates []*media_router.ConnectionQualityInfo)

func (*Room) OnDataPacket

func (r *Room) OnDataPacket(identity string, dataPacket DataPacket)

func (*Room) OnDisconnect

func (r *Room) OnDisconnect(reason DisconnectionReason)

func (*Room) OnDisconnected

func (n *Room) OnDisconnected(reason DisconnectionReason)

func (*Room) OnLocalTrackSubscribed

func (r *Room) OnLocalTrackSubscribed(trackSubscribed *media_router.TrackSubscribed)

func (*Room) OnLocalTrackUnpublished

func (r *Room) OnLocalTrackUnpublished(msg *media_router.TrackUnpublishedResponse)

func (*Room) OnMediaTrack

func (r *Room) OnMediaTrack(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver)

engineHandler implementation

func (*Room) OnParticipantDisconnect

func (r *Room) OnParticipantDisconnect(rp *RemoteParticipant)

func (*Room) OnParticipantUpdate

func (r *Room) OnParticipantUpdate(participants []*media_router.ParticipantInfo)

func (*Room) OnRestarted

func (r *Room) OnRestarted(
	room *media_router.Room,
	participant *media_router.ParticipantInfo,
	otherParticipants []*media_router.ParticipantInfo,
)

func (*Room) OnRestarting

func (r *Room) OnRestarting()

func (*Room) OnResumed

func (r *Room) OnResumed()

func (*Room) OnResuming

func (r *Room) OnResuming()

func (*Room) OnRoomJoined

func (r *Room) OnRoomJoined(
	room *media_router.Room,
	participant *media_router.ParticipantInfo,
	otherParticipants []*media_router.ParticipantInfo,
	serverInfo *media_router.ServerInfo,
	sifTrailer []byte,
)

func (*Room) OnRoomMoved

func (r *Room) OnRoomMoved(moved *media_router.RoomMovedResponse)

func (*Room) OnRoomUpdate

func (r *Room) OnRoomUpdate(room *media_router.Room)

func (*Room) OnRpcAck

func (r *Room) OnRpcAck(requestId string)

func (*Room) OnRpcRequest

func (r *Room) OnRpcRequest(callerIdentity, requestId, method, payload string, responseTimeout time.Duration, version uint32)

func (*Room) OnRpcResponse

func (r *Room) OnRpcResponse(requestId string, payload *string, error *RpcError)

func (*Room) OnSignalClientConnected

func (n *Room) OnSignalClientConnected(*media_router.JoinResponse)

func (*Room) OnSpeakersChange

func (r *Room) OnSpeakersChange(speakerUpdates []*media_router.SpeakerInfo)

func (*Room) OnSpeakersChanged

func (n *Room) OnSpeakersChanged([]*media_router.SpeakerInfo)

func (*Room) OnStreamChunk

func (r *Room) OnStreamChunk(streamChunk *media_router.DataStream_Chunk)

func (*Room) OnStreamHeader

func (r *Room) OnStreamHeader(streamHeader *media_router.DataStream_Header, participantIdentity string)

func (*Room) OnStreamTrailer

func (r *Room) OnStreamTrailer(streamTrailer *media_router.DataStream_Trailer)

func (*Room) OnSubscribedQualityUpdate

func (r *Room) OnSubscribedQualityUpdate(subscribedQualityUpdate *media_router.SubscribedQualityUpdate)

func (*Room) OnTrackRemoteMuted

func (r *Room) OnTrackRemoteMuted(msg *media_router.MuteTrackRequest)

func (*Room) OnTranscription

func (n *Room) OnTranscription(*media_router.Transcription)

func (*Room) OnTranscriptionReceived

func (r *Room) OnTranscriptionReceived(transcription *media_router.Transcription)

func (*Room) PrepareConnection

func (r *Room) PrepareConnection(url, token string) error

PrepareConnection - with Vibtree, determine the best edge data center for the current client to connect to

func (*Room) RegisterByteStreamHandler

func (r *Room) RegisterByteStreamHandler(topic string, handler ByteStreamHandler) error

Registers a handler for a byte stream. It will be called when a byte stream is received for the given topic. The handler will be called with the stream reader and the participant identity that sent the stream.

func (*Room) RegisterRpcMethod

func (r *Room) RegisterRpcMethod(method string, handler RpcHandlerFunc) error

Establishes the participant as a receiver for calls of the specified RPC method. Will overwrite any existing callback for the same method.

  • @param method - The name of the indicated RPC method
  • @param handler - Will be invoked when an RPC request for this method is received
  • @returns A promise that resolves when the method is successfully registered

Example:

room.LocalParticipant?.registerRpcMethod(
	"greet",
	func (data: RpcInvocationData) => {
		fmt.Println("Received greeting from ", data.callerIdentity, "with payload ", data.payload)
		return "Hello, " + data.callerIdentity + "!";
	}
);

The handler should return either a string or an error. If unable to respond within `responseTimeout`, the request will result in an error on the caller's side.

You may throw errors of type `RpcError` with a string `message` in the handler, and they will be received on the caller's side with the message intact. Other errors thrown in your handler will not be transmitted as-is, and will instead arrive to the caller as `1500` ("Application Error").

func (*Room) RegisterTextStreamHandler

func (r *Room) RegisterTextStreamHandler(topic string, handler TextStreamHandler) error

Registers a handler for a text stream. It will be called when a text stream is received for the given topic. The handler will be called with the stream reader and the participant identity that sent the stream.

func (*Room) SID

func (r *Room) SID() string

func (*Room) ServerInfo

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

func (*Room) SetLogger

func (r *Room) SetLogger(l protoLogger.Logger)

SetLogger overrides default logger.

func (*Room) SifTrailer

func (r *Room) SifTrailer() []byte

func (*Room) Simulate

func (r *Room) Simulate(scenario SimulateScenario)

func (*Room) UnregisterByteStreamHandler

func (r *Room) UnregisterByteStreamHandler(topic string)

Unregisters a handler for a byte stream.

func (*Room) UnregisterRpcMethod

func (r *Room) UnregisterRpcMethod(method string)

Unregisters a previously registered RPC method.

  • @param method - The name of the RPC method to unregister

func (*Room) UnregisterTextStreamHandler

func (r *Room) UnregisterTextStreamHandler(topic string)

Unregisters a handler for a text stream.

type RoomCallback

type RoomCallback struct {
	OnDisconnected            func()
	OnDisconnectedWithReason  func(reason DisconnectionReason)
	OnParticipantConnected    func(*RemoteParticipant)
	OnParticipantDisconnected func(*RemoteParticipant)
	OnActiveSpeakersChanged   func([]Participant)
	OnRoomMetadataChanged     func(metadata string)
	OnRoomMoved               func(roomName string, token string)
	OnReconnecting            func()
	OnReconnected             func()
	OnLocalTrackSubscribed    func(publication *LocalTrackPublication, lp *LocalParticipant)

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

ExampleRoomCallback demonstrates usage of RoomCallback to handle various room events

package main

import (
	"fmt"

	media_router "github.com/vibtreeofficial/protocol/media-router"
	lksdk "github.com/vibtreeofficial/server-sdk-go/v2"
)

func main() {
	// Create a new callback handler
	cb := lksdk.NewRoomCallback()

	// Handle data packets received from other participants
	cb.OnDataPacket = func(data lksdk.DataPacket, params lksdk.DataReceiveParams) {
		// handle DTMF
		switch val := data.(type) {
		case *media_router.SipDTMF:
			fmt.Printf("Received DTMF from %s: %s (%d)\n", params.SenderIdentity, val.Digit, val.Code)
		case *lksdk.UserDataPacket:
			fmt.Printf("Received user data from %s: %s\n", params.SenderIdentity, string(val.Payload))
		}
	}

	// Handle participant metadata changes
	cb.OnAttributesChanged = func(changed map[string]string, p lksdk.Participant) {
		fmt.Printf("Participant %s attributes changed: %v\n", p.Identity(), changed)
	}

	// Handle when current participant becomes disconnected
	cb.OnDisconnectedWithReason = func(reason lksdk.DisconnectionReason) {
		fmt.Printf("Disconnected from room: %s\n", reason)
	}

	// Create a new room with the callback
	room := lksdk.NewRoom(cb)
	room.JoinWithToken("wss://myproject.media-router.cloud", "my-token")
}

func NewRoomCallback

func NewRoomCallback() *RoomCallback

func (*RoomCallback) Merge

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, opts ...twirp.ClientOption) *RoomServiceClient

func (*RoomServiceClient) CreateRoom

func (*RoomServiceClient) CreateToken

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

func (*RoomServiceClient) DeleteRoom

func (*RoomServiceClient) ForwardParticipant

Forward a participant's track(s) to another room. Requires `roomAdmin` and `destinationRoom`. The forwarding will stop when the participant leaves the room or `RemoveParticipant` has been called in the destination room. A participant can be forwarded to multiple rooms. The destination room will be created if it does not exist.

func (*RoomServiceClient) GetParticipant

func (*RoomServiceClient) ListRooms

func (*RoomServiceClient) MoveParticipant

Move a connected participant to a different room. Requires `roomAdmin` and `destinationRoom`. The participant will be removed from the current room and added to the destination room. From other observers' perspective, the participant would've disconnected from the previous room and joined the new one.

func (*RoomServiceClient) MutePublishedTrack

func (*RoomServiceClient) SendData

func (*RoomServiceClient) UpdateParticipant

func (*RoomServiceClient) UpdateRoomMetadata

type RpcError

type RpcError struct {
	Code    RpcErrorCode
	Message string
	Data    *string
}

Specialized error handling for RPC methods.

Instances of this type, when thrown in a method handler, will have their `message` serialized and sent across the wire. The sender will receive an equivalent error on the other side.

Built-in types are included but developers may use any string, with a max length of 256 bytes.

func NewRpcError

func NewRpcError(code RpcErrorCode, message string, data *string) *RpcError

Creates an error object with the given code and message, plus an optional data payload.

If thrown in an RPC method handler, the error will be sent back to the caller.

Error codes 1001-1999 are reserved for built-in errors.

Maximum message length is 256 bytes, and maximum data payload length is 15KiB. If a payload exceeds these limits, it will be truncated.

func (*RpcError) Error

func (e *RpcError) Error() string

type RpcErrorCode

type RpcErrorCode uint32
const (
	RpcApplicationError RpcErrorCode = 1500 + iota
	RpcConnectionTimeout
	RpcResponseTimeout
	RpcRecipientDisconnected
	RpcResponsePayloadTooLarge
	RpcSendFailed
)
const (
	RpcUnsupportedMethod RpcErrorCode = 1400 + iota
	RpcRecipientNotFound
	RpcRequestPayloadTooLarge
	RpcUnsupportedServer
	RpcUnsupportedVersion
)

type RpcHandlerFunc

type RpcHandlerFunc func(data RpcInvocationData) (string, error)

type RpcInvocationData

type RpcInvocationData struct {
	// The unique request ID. Will match at both sides of the call, useful for debugging or logging.
	RequestID string
	// The unique participant identity of the caller.
	CallerIdentity string
	// The payload of the request. User-definable format, could be JSON for example.
	Payload string
	// The maximum time the caller will wait for a response.
	ResponseTimeout time.Duration
}

Data passed to method handler for incoming RPC invocations

type SIPClient

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

func NewSIPClient

func NewSIPClient(url string, apiKey string, secretKey string, opts ...twirp.ClientOption) *SIPClient

NewSIPClient creates a Vibtree SIP client.

func (*SIPClient) CreateSIPDispatchRule

func (s *SIPClient) CreateSIPDispatchRule(ctx context.Context, in *media_router.CreateSIPDispatchRuleRequest) (*media_router.SIPDispatchRuleInfo, error)

CreateSIPDispatchRule creates SIP Dispatch Rules.

func (*SIPClient) CreateSIPInboundTrunk

func (s *SIPClient) CreateSIPInboundTrunk(ctx context.Context, in *media_router.CreateSIPInboundTrunkRequest) (*media_router.SIPInboundTrunkInfo, error)

CreateSIPInboundTrunk creates a new SIP Trunk for accepting inbound calls to Vibtree.

func (*SIPClient) CreateSIPOutboundTrunk

func (s *SIPClient) CreateSIPOutboundTrunk(ctx context.Context, in *media_router.CreateSIPOutboundTrunkRequest) (*media_router.SIPOutboundTrunkInfo, error)

CreateSIPOutboundTrunk creates a new SIP Trunk for making outbound calls from Vibtree.

func (*SIPClient) CreateSIPParticipant

func (s *SIPClient) CreateSIPParticipant(ctx context.Context, in *media_router.CreateSIPParticipantRequest) (*media_router.SIPParticipantInfo, error)

CreateSIPParticipant creates SIP Participant by making an outbound call.

func (*SIPClient) DeleteSIPDispatchRule

func (s *SIPClient) DeleteSIPDispatchRule(ctx context.Context, in *media_router.DeleteSIPDispatchRuleRequest) (*media_router.SIPDispatchRuleInfo, error)

DeleteSIPDispatchRule deletes SIP Dispatch Rule given an ID.

func (*SIPClient) DeleteSIPTrunk

func (s *SIPClient) DeleteSIPTrunk(ctx context.Context, in *media_router.DeleteSIPTrunkRequest) (*media_router.SIPTrunkInfo, error)

DeleteSIPTrunk deletes SIP Trunk given an ID.

func (*SIPClient) GetSIPDispatchRulesByIDs

func (s *SIPClient) GetSIPDispatchRulesByIDs(ctx context.Context, ids []string) ([]*media_router.SIPDispatchRuleInfo, error)

GetSIPDispatchRulesByIDs gets SIP Dispatch Rules by ID. Returned slice is in the same order as the IDs. Missing IDs will have nil in the corresponding position.

func (*SIPClient) GetSIPInboundTrunksByIDs

func (s *SIPClient) GetSIPInboundTrunksByIDs(ctx context.Context, ids []string) ([]*media_router.SIPInboundTrunkInfo, error)

GetSIPInboundTrunksByIDs gets SIP Inbound Trunks by ID. Returned slice is in the same order as the IDs. Missing IDs will have nil in the corresponding position.

func (*SIPClient) GetSIPOutboundTrunksByIDs

func (s *SIPClient) GetSIPOutboundTrunksByIDs(ctx context.Context, ids []string) ([]*media_router.SIPOutboundTrunkInfo, error)

GetSIPOutboundTrunksByIDs gets SIP Outbound Trunks by ID. Returned slice is in the same order as the IDs. Missing IDs will have nil in the corresponding position.

func (*SIPClient) ListSIPDispatchRule

func (s *SIPClient) ListSIPDispatchRule(ctx context.Context, in *media_router.ListSIPDispatchRuleRequest) (*media_router.ListSIPDispatchRuleResponse, error)

ListSIPDispatchRule lists SIP Dispatch Rules.

func (*SIPClient) ListSIPInboundTrunk

func (s *SIPClient) ListSIPInboundTrunk(ctx context.Context, in *media_router.ListSIPInboundTrunkRequest) (*media_router.ListSIPInboundTrunkResponse, error)

ListSIPInboundTrunk lists SIP Trunks accepting inbound calls.

func (*SIPClient) ListSIPOutboundTrunk

func (s *SIPClient) ListSIPOutboundTrunk(ctx context.Context, in *media_router.ListSIPOutboundTrunkRequest) (*media_router.ListSIPOutboundTrunkResponse, error)

ListSIPOutboundTrunk lists SIP Trunks for making outbound calls.

func (*SIPClient) ListSIPTrunk deprecated

func (s *SIPClient) ListSIPTrunk(ctx context.Context, in *media_router.ListSIPTrunkRequest) (*media_router.ListSIPTrunkResponse, error)

ListSIPTrunk lists SIP Trunks.

Deprecated: Use ListSIPInboundTrunk or ListSIPOutboundTrunk

func (*SIPClient) TransferSIPParticipant

func (s *SIPClient) TransferSIPParticipant(ctx context.Context, in *media_router.TransferSIPParticipantRequest) (*emptypb.Empty, error)

TransferSIPParticipant transfer an existing SIP participant to an outside SIP endpoint.

func (*SIPClient) UpdateSIPDispatchRule

func (s *SIPClient) UpdateSIPDispatchRule(ctx context.Context, in *media_router.UpdateSIPDispatchRuleRequest) (*media_router.SIPDispatchRuleInfo, error)

UpdateSIPDispatchRule updates an existing SIP Dispatch Rule.

func (*SIPClient) UpdateSIPInboundTrunk

func (s *SIPClient) UpdateSIPInboundTrunk(ctx context.Context, in *media_router.UpdateSIPInboundTrunkRequest) (*media_router.SIPInboundTrunkInfo, error)

UpdateSIPInboundTrunk updates an existing SIP Inbound Trunk.

func (*SIPClient) UpdateSIPOutboundTrunk

func (s *SIPClient) UpdateSIPOutboundTrunk(ctx context.Context, in *media_router.UpdateSIPOutboundTrunkRequest) (*media_router.SIPOutboundTrunkInfo, error)

UpdateSIPOutboundTrunk updates an existing SIP Outbound Trunk.

type SampleProvider

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

type SampleWriteOptions

type SampleWriteOptions struct {
	AudioLevel *uint8
}

type SimulateScenario

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

type SimulcastTrack

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

func NewSimulcastTrack

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

func (*SimulcastTrack) Quality

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

func (*SimulcastTrack) TrackLocal

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

func (*SimulcastTrack) VideoLayer

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

type StreamBytesOptions

type StreamBytesOptions struct {
	Topic                 string
	MimeType              string
	DestinationIdentities []string
	StreamId              *string
	TotalSize             uint64
	Attributes            map[string]string
	OnProgress            func(progress float64)
	FileName              *string
}

Options for publishing a byte stream

  • Topic is the topic of the stream
  • MimeType is the mime type of the stream, determined for SendFile if not provided
  • DestinationIdentities is the list of identities that will receive the stream, empty for all participants
  • StreamId is the id of the stream, generated if not provided
  • TotalSize is the total size of the stream, optional but calculated internally for SendFile
  • Attributes are any additional attributes of the stream
  • OnProgress is a callback function that will be called when the stream is being written
  • FileName is the name of the file, optional

type StreamTextOptions

type StreamTextOptions struct {
	Topic                 string
	DestinationIdentities []string
	StreamId              *string
	ReplyToStreamId       *string
	TotalSize             uint64
	Attributes            map[string]string
	OnProgress            func(progress float64)
	Attachments           []string
	AttachedStreamIds     []string
}

Options for publishing a text stream with mime type "text/plain"

  • Topic is the topic of the stream
  • DestinationIdentities is the list of identities that will receive the stream, empty for all participants
  • StreamId is the id of the stream, generated if not provided
  • ReplyToStreamId is the id of the stream to reply to, optional
  • TotalSize is the total size of the stream, optional but calculated internally for SendText if not provided
  • Attributes are any additional attributes of the stream
  • OnProgress is a callback function that will be called when the stream is being written
  • Attachments is the list of file paths to attach to the stream, optional
  • AttachedStreamIds is the list of stream ids that are attached to this stream, mapped by index to attachments, optional, generated if not provided

type TextStreamHandler

type TextStreamHandler func(reader *TextStreamReader, participantIdentity string)

TextStreamHandler is a function that will be called when a text stream is received. It will be called with the stream reader and the participant identity that sent the stream.

type TextStreamInfo

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

Info for text streams

  • Id is the id of the stream
  • MimeType is the mime type of the stream, always "text/plain" for text streams
  • Topic is the topic of the stream
  • Timestamp is the timestamp of sending the stream
  • Size is the total size of the stream, if provided
  • Attributes are any additional attributes of the stream

type TextStreamReader

type TextStreamReader struct {
	Info TextStreamInfo
	// contains filtered or unexported fields
}

func NewTextStreamReader

func NewTextStreamReader(info TextStreamInfo, totalChunkCount *uint64) *TextStreamReader

func (TextStreamReader) OnProgress

func (r TextStreamReader) OnProgress(onProgress *func(progress float64))

OnProgress sets the callback function that will be called when the stream is being read only called if TotalSize of the stream is set

func (TextStreamReader) Read

func (r TextStreamReader) Read(bytes []byte) (int, error)

Read reads the next len(p) bytes from the stream or until the stream buffer is drained. The return value is the number of bytes read. If the buffer has no data to return, it will wait for a write to the stream or return io.EOF if the stream is closed.

func (*TextStreamReader) ReadAll

func (r *TextStreamReader) ReadAll() string

ReadAll reads all the data from the stream and returns it as a string. This will block until the stream is closed.

func (TextStreamReader) ReadByte

func (r TextStreamReader) ReadByte() (byte, error)

ReadByte reads and returns the next byte from the buffer. If no byte is available, it will wait for a write to the stream or return io.EOF if the stream is closed.

func (TextStreamReader) ReadBytes

func (r TextStreamReader) ReadBytes(delim byte) ([]byte, error)

ReadBytes reads until the first occurrence of delim in the input, returning a slice containing the data up to and including the delimiter. If ReadBytes encounters an error before finding a delimiter, it returns the data read before EOF, but does not return EOF until the stream is closed. ReadBytes returns err != nil if and only if the returned data does not end in delim.

func (*TextStreamReader) ReadRune

func (r *TextStreamReader) ReadRune() (rune, int, error)

ReadRune reads and returns the next UTF-8-encoded Unicode code point from the buffer. If no bytes are available, it will wait for a write to the stream or return io.EOF if the stream is closed. If the bytes are an erroneous UTF-8 encoding, it consumes one byte and returns U+FFFD, 1.

func (*TextStreamReader) ReadString

func (r *TextStreamReader) ReadString(delim byte) (string, error)

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before EOF, but does not return EOF until the stream is closed. ReadString returns err != nil if and only if the returned data does not end in delim.

type TextStreamWriter

type TextStreamWriter struct {
	Info TextStreamInfo
	// contains filtered or unexported fields
}

TextStreamWriter is a writer type for text streams

func (TextStreamWriter) Close

func (w TextStreamWriter) Close()

Close the stream, this will send a stream trailer to notify the receiver that the stream is closed

func (TextStreamWriter) Write

func (w TextStreamWriter) Write(data T, onDone *func())

Write data to the stream, data can be a byte slice or a string depending on the type of the stream writer onDone is a callback function that will be called when the data provided is written to the stream

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() media_router.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() media_router.TrackSource
	Kind() TrackKind
	MimeType() string
	IsMuted() bool
	IsSubscribed() bool
	TrackInfo() *media_router.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 media_router.TrackSource
	// Set dimensions for video
	VideoWidth  int
	VideoHeight int
	// Opus only
	DisableDTX bool
	Stereo     bool
	// which stream the track belongs to, used to group tracks together.
	// if not specified, server will infer it from track source to bundle camera/microphone, screenshare/audio together
	Stream string
	// encryption type
	Encryption media_router.Encryption_Type
}

type TranscriptionSegment

type TranscriptionSegment struct {
	ID        string
	Text      string
	Language  string
	StartTime uint64
	EndTime   uint64
	Final     bool
}

func ExtractTranscriptionSegments

func ExtractTranscriptionSegments(transcription *media_router.Transcription) []*TranscriptionSegment

type UserDataPacket

type UserDataPacket struct {
	Payload []byte
	Topic   string // optional
}

UserDataPacket is a custom user data that can be sent via WebRTC on a custom topic.

func UserData

func UserData(data []byte) *UserDataPacket

UserData is a custom user data that can be sent via WebRTC.

func (*UserDataPacket) ToProto

func (p *UserDataPacket) ToProto() *media_router.DataPacket

ToProto implements DataPacket.

Directories

Path Synopsis
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