mediasoup

package module
v1.10.10 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2024 License: ISC Imports: 29 Imported by: 1

README

Mediasoup library in golang

This golang library is aiming to help people who want to use mediasoup without coding in node.js. Be attention, in order to communicate with mediasoup worker, it uses the feature of Cmd.ExtraFiles which doesn't work on Windows platform. Because mediasoup uses single thread in C++ code, you still need to use PipeTransport to make use of multi-core cpu.

Install

Notice: Since mediasoup switched from JSON based messages to flatbuffers, this library can only support mediasoup to version 3.12.16.

Build mediasoup worker binary

npm install -g mediasoup@3.12.16

or set environment variable MEDIASOUP_WORKER_BIN to your mediasoup worker binary path. It can also be done in golang

mediasoup.WorkerBin = "your mediasoup worker binary path"

In golang project.

import "github.com/jiyeyuran/mediasoup-go"

Document

Golang API document. mediasoup-go api is consistent with the node.js api. It would be very helpful to read official document.

Demo Application

mediasoup-go-demo.

Usage

package main

import (
	"encoding/json"

	"github.com/jiyeyuran/mediasoup-go"
	"github.com/jiyeyuran/mediasoup-go/h264"
)

var logger = mediasoup.NewLogger("ExampleApp")

var consumerDeviceCapabilities = mediasoup.RtpCapabilities{
	Codecs: []*mediasoup.RtpCodecCapability{
		{
			MimeType:             "audio/opus",
			Kind:                 "audio",
			PreferredPayloadType: 100,
			ClockRate:            48000,
			Channels:             2,
		},
		{
			MimeType:             "video/H264",
			Kind:                 "video",
			PreferredPayloadType: 101,
			ClockRate:            90000,
			Parameters: mediasoup.RtpCodecSpecificParameters{
				RtpParameter: h264.RtpParameter{
					LevelAsymmetryAllowed: 1,
					PacketizationMode:     Uint8(1),
					ProfileLevelId:        "4d0032",
				},
			},
			RtcpFeedback: []mediasoup.RtcpFeedback{
				{Type: "nack", Parameter: ""},
				{Type: "nack", Parameter: "pli"},
				{Type: "ccm", Parameter: "fir"},
				{Type: "goog-remb", Parameter: ""},
			},
		},
		{
			MimeType:             "video/rtx",
			Kind:                 "video",
			PreferredPayloadType: 102,
			ClockRate:            90000,
			Parameters: mediasoup.RtpCodecSpecificParameters{
				Apt: 101,
			},
		},
	},
}

func main() {
	worker, err := mediasoup.NewWorker()
	if err != nil {
		panic(err)
	}
	worker.On("died", func(err error) {
		logger.Error("%s", err)
	})

	dump, _ := worker.Dump()
	logger.Debug("dump: %+v", dump)

	usage, err := worker.GetResourceUsage()
	if err != nil {
		panic(err)
	}
	data, _ := json.Marshal(usage)
	logger.Debug("usage: %s", data)

	router, err := worker.CreateRouter(mediasoup.RouterOptions{
		MediaCodecs: []*mediasoup.RtpCodecCapability{
			{
				Kind:      "audio",
				MimeType:  "audio/opus",
				ClockRate: 48000,
				Channels:  2,
			},
			{
				Kind:      "video",
				MimeType:  "video/VP8",
				ClockRate: 90000,
			},
			{
				Kind:      "video",
				MimeType:  "video/H264",
				ClockRate: 90000,
				Parameters: mediasoup.RtpCodecSpecificParameters{
					RtpParameter: h264.RtpParameter{
						LevelAsymmetryAllowed: 1,
						PacketizationMode:     Uint8(1),
						ProfileLevelId:        "4d0032",
					},
				},
			},
		},
	})
	if err != nil {
		panic(err)
	}

	sendTransport, err := router.CreateWebRtcTransport(mediasoup.WebRtcTransportOptions{
		ListenIps: []mediasoup.TransportListenIp{
			{Ip: "0.0.0.0", AnnouncedIp: "192.168.1.101"}, // AnnouncedIp is optional
		},
	})
	if err != nil {
		panic(err)
	}

	producer, err := sendTransport.Produce(mediasoup.ProducerOptions{
		Kind: mediasoup.MediaKind_Audio,
		RtpParameters: mediasoup.RtpParameters{
			Mid: "VIDEO",
			Codecs: []*mediasoup.RtpCodecParameters{
				{
					MimeType:    "video/h264",
					PayloadType: 112,
					ClockRate:   90000,
					Parameters: mediasoup.RtpCodecSpecificParameters{
						RtpParameter: h264.RtpParameter{
							PacketizationMode: Uint8(1),
							ProfileLevelId:    "4d0032",
						},
					},
					RtcpFeedback: []mediasoup.RtcpFeedback{
						{Type: "nack", Parameter: ""},
						{Type: "nack", Parameter: "pli"},
						{Type: "goog-remb", Parameter: ""},
					},
				},
				{
					MimeType:    "video/rtx",
					PayloadType: 113,
					ClockRate:   90000,
					Parameters:  mediasoup.RtpCodecSpecificParameters{Apt: 112},
				},
			},
			HeaderExtensions: []mediasoup.RtpHeaderExtensionParameters{
				{
					Uri: "urn:ietf:params:rtp-hdrext:sdes:mid",
					Id:  10,
				},
				{
					Uri: "urn:3gpp:video-orientation",
					Id:  13,
				},
			},
			Encodings: []mediasoup.RtpEncodingParameters{
				{Ssrc: 22222222, Rtx: &mediasoup.RtpEncodingRtx{Ssrc: 22222223}},
				{Ssrc: 22222224, Rtx: &mediasoup.RtpEncodingRtx{Ssrc: 22222225}},
				{Ssrc: 22222226, Rtx: &mediasoup.RtpEncodingRtx{Ssrc: 22222227}},
				{Ssrc: 22222228, Rtx: &mediasoup.RtpEncodingRtx{Ssrc: 22222229}},
			},
			Rtcp: mediasoup.RtcpParameters{
				Cname: "video-1",
			},
		},
		AppData: mediasoup.H{"foo": 1, "bar": "2"},
	})
	if err != nil {
		panic(err)
	}

	recvTransport, err := router.CreateWebRtcTransport(mediasoup.WebRtcTransportOptions{
		ListenIps: []mediasoup.TransportListenIp{
			{Ip: "0.0.0.0", AnnouncedIp: "192.168.1.101"}, // AnnouncedIp is optional
		},
	})
	if err != nil {
		panic(err)
	}

	producer.Pause()

	// TODO: sent back producer id to client

	consumer, err := recvTransport.Consume(mediasoup.ConsumerOptions{
		ProducerId:      producer.Id(),
		RtpCapabilities: consumerDeviceCapabilities,
		AppData:         mediasoup.H{"baz": "LOL"},
	})
	if err != nil {
		panic(err)
	}

	consumerDump, _ := consumer.Dump()
	data, _ = json.Marshal(consumerDump)
	logger.Debug("consumer, %s", data)

	wait := make(chan struct{})
	<-wait
}

License

ISC

Documentation

Index

Constants

View Source
const (
	NS_MESSAGE_MAX_LEN = 4194308
	NS_PAYLOAD_MAX_LEN = 4194304
)
View Source
const (
	SctpState_New        = "new"
	SctpState_Connecting = "connecting"
	SctpState_Connected  = "connected"
	SctpState_Failed     = "failed"
	SctpState_Closed     = "closed"
)

Variables

View Source
var (
	// WorkerBin indicates the worker binary path, prefer WithWorkerBin
	WorkerBin = getDefaultWorkerBin()
	// WorkerVersion indicates the worker binary version, prefer WithWorkerVersion
	WorkerVersion = getDefaultWorkerVersion()
)
View Source
var DYNAMIC_PAYLOAD_TYPES = [...]byte{
	100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115,
	116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 96, 97, 98, 99, 77,
	78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 35, 36,
	37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
	57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
}
View Source
var (

	// NewLogger defines function to create logger instance.
	NewLogger = func(scope string) logr.Logger {
		shouldDebug := false
		if debug := os.Getenv("DEBUG"); len(debug) > 0 {
			for _, part := range strings.Split(debug, ",") {
				part := strings.TrimSpace(part)
				if len(part) == 0 {
					continue
				}
				shouldMatch := true
				if part[0] == '-' {
					shouldMatch = false
					part = part[1:]
				}
				if g, err := glob.Compile(part); err == nil && g.Match(scope) {
					shouldDebug = shouldMatch
				}
			}
		}

		level := defaultLoggerLevel

		if shouldDebug {
			level = zerolog.DebugLevel
		}

		logger := defaultLoggerImpl.Level(level)

		return zerologr.New(&logger).WithName(scope)
	}
)

Functions

func Bool

func Bool(b bool) *bool

func NewInvalidStateError

func NewInvalidStateError(format string, args ...interface{}) error

func NewTypeError

func NewTypeError(format string, args ...interface{}) error

func NewUnsupportedError

func NewUnsupportedError(format string, args ...interface{}) error

func Uint8 added in v1.10.10

func Uint8(v uint8) *uint8

Types

type ActiveSpeakerObserver added in v1.9.5

type ActiveSpeakerObserver struct {
	IRtpObserver
	// contains filtered or unexported fields
}

ActiveSpeakerObserver monitors the speech activity of the selected audio producers. It just handles audio producers (if addProducer() is called with a video producer it will fail).

Implementation of Dominant Speaker Identification for Multipoint Videoconferencing by Ilana Volfin and Israel Cohen. This implementation uses the RTP Audio Level extension from RFC-6464 for the input signal. This has been ported from DominantSpeakerIdentification.java in Jitsi. Audio levels used for speech detection are read from an RTP header extension. No decoding of audio data is done. See RFC6464 for more information.

  • @emits dominantspeaker - (activity *ActiveSpeakerObserverActivity)

func (*ActiveSpeakerObserver) Observer added in v1.9.5

func (o *ActiveSpeakerObserver) Observer() IEventEmitter

Deprecated

  • @emits dominantspeaker - (activity *ActiveSpeakerObserverActivity)

func (*ActiveSpeakerObserver) OnDominantSpeaker added in v1.10.5

func (o *ActiveSpeakerObserver) OnDominantSpeaker(handler func(speaker *ActiveSpeakerObserverActivity))

OnDominantSpeaker set handler on "dominantspeaker" event

type ActiveSpeakerObserverActivity added in v1.9.5

type ActiveSpeakerObserverActivity struct {
	// Producer is the dominant audio producer instance.
	Producer *Producer
}

type ActiveSpeakerObserverOptions added in v1.9.5

type ActiveSpeakerObserverOptions struct {
	Interval int         `json:"interval"`
	AppData  interface{} `json:"appData,omitempty"`
}

type AudioLevelObserver

type AudioLevelObserver struct {
	IRtpObserver
	// contains filtered or unexported fields
}

AudioLevelObserver monitors the volume of the selected audio producers. It just handles audio producers (if AddProducer() is called with a video producer it will fail).

Audio levels are read from an RTP header extension. No decoding of audio data is done. See RFC6464 for more information.

  • @emits volumes - (volumes []AudioLevelObserverVolume)
  • @emits silence

func (*AudioLevelObserver) Observer

func (o *AudioLevelObserver) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits pause
  • @emits resume
  • @emits addproducer - (producer *Producer)
  • @emits removeproducer - (producer *Producer)
  • @emits volumes - (volumes []AudioLevelObserverVolume)
  • @emits silence

func (*AudioLevelObserver) OnSilence added in v1.10.5

func (o *AudioLevelObserver) OnSilence(handler func())

OnSilence set handler on "silence" event

func (*AudioLevelObserver) OnVolumes added in v1.10.5

func (o *AudioLevelObserver) OnVolumes(handler func(volumes []AudioLevelObserverVolume))

OnVolumes set handler on "volumes" event

type AudioLevelObserverOptions

type AudioLevelObserverOptions struct {
	// MaxEntries is maximum int of entries in the 'volumes”' event. Default 1.
	MaxEntries int `json:"maxEntries"`

	// Threshold is minimum average volume (in dBvo from -127 to 0) for entries in the
	// "volumes" event.	Default -80.
	Threshold int `json:"threshold"`

	// Interval in ms for checking audio volumes. Default 1000.
	Interval int `json:"interval"`

	// AppData is custom application data.
	AppData interface{} `json:"appData,omitempty"`
}

AudioLevelObserverOptions define options to create an AudioLevelObserver.

type AudioLevelObserverVolume

type AudioLevelObserverVolume struct {
	// Producer is the audio producer instance.
	Producer *Producer

	// Volume is the average volume (in dBvo from -127 to 0) of the audio producer in the
	// last interval.
	Volume int
}

type Channel

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

func (*Channel) Close

func (c *Channel) Close() error

func (*Channel) Closed

func (c *Channel) Closed() bool

func (*Channel) Request

func (c *Channel) Request(method string, internal internalData, data ...interface{}) (rsp workerResponse)

func (*Channel) Start added in v1.7.1

func (c *Channel) Start()

func (*Channel) Subscribe added in v1.10.4

func (c *Channel) Subscribe(targetId string, handler channelSubscriber)

func (*Channel) Unsubscribe added in v1.10.4

func (c *Channel) Unsubscribe(targetId string)

type Consumer

type Consumer struct {
	IEventEmitter
	// contains filtered or unexported fields
}

Consumer represents an audio or video source being forwarded from a mediasoup router to an endpoint. It's created on top of a transport that defines how the media packets are carried.

  • @emits transportclose
  • @emits producerclose
  • @emits producerpause
  • @emits producerresume
  • @emits score - (score *ConsumerScore)
  • @emits layerschange - (layers *ConsumerLayers | nil)
  • @emits rtp - (packet []byte)
  • @emits trace - (trace *ConsumerTraceEventData)
  • @emits @close
  • @emits @producerclose

func (*Consumer) AppData

func (consumer *Consumer) AppData() interface{}

AppData returns app custom data.

func (*Consumer) Close

func (consumer *Consumer) Close() (err error)

Close the Consumer.

func (*Consumer) Closed

func (consumer *Consumer) Closed() bool

Closed returns whether the Consumer is closed.

func (*Consumer) ConsumerId

func (consumer *Consumer) ConsumerId() string

ConsumerId returns associated Consumer id.

func (*Consumer) CurrentLayers

func (consumer *Consumer) CurrentLayers() *ConsumerLayers

CurrentLayers returns current video layers.

func (*Consumer) Dump

func (consumer *Consumer) Dump() (dump *ConsumerDump, err error)

Dump Consumer.

func (*Consumer) EnableTraceEvent

func (consumer *Consumer) EnableTraceEvent(types ...ConsumerTraceEventType) error

EnableTraceEvent eenable "trace" event.

func (*Consumer) GetStats

func (consumer *Consumer) GetStats() (stats []*ConsumerStat, err error)

GetStats returns Consumer stats.

func (*Consumer) Id

func (consumer *Consumer) Id() string

Id returns consumer id

func (*Consumer) Kind

func (consumer *Consumer) Kind() MediaKind

Kind returns media kind.

func (*Consumer) Observer

func (consumer *Consumer) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits pause
  • @emits resume
  • @emits score - (score *ConsumerScore)
  • @emits layerschange - (layers *ConsumerLayers | nil)
  • @emits trace - (trace *ConsumerTraceEventData)

func (*Consumer) OnClose added in v1.10.4

func (consumer *Consumer) OnClose(handler func())

OnClose set handler on "close" event

func (*Consumer) OnLayersChange added in v1.10.4

func (consumer *Consumer) OnLayersChange(handler func(layers *ConsumerLayers))

OnLayersChange set handler on "layerschange" event

func (*Consumer) OnPause added in v1.10.4

func (consumer *Consumer) OnPause(handler func())

OnPause set handler on "pause" event

func (*Consumer) OnProducerClose added in v1.10.5

func (consumer *Consumer) OnProducerClose(handler func())

OnProducerClose set handler on "producerclose" event

func (*Consumer) OnProducerPause added in v1.10.6

func (consumer *Consumer) OnProducerPause(handler func())

OnProducerPause set handler on "producerpause" event

func (*Consumer) OnProducerResume added in v1.10.6

func (consumer *Consumer) OnProducerResume(handler func())

OnProducerResume set handler on "producerresume" event

func (*Consumer) OnResume added in v1.10.4

func (consumer *Consumer) OnResume(handler func())

OnResume set handler on "resume" event

func (*Consumer) OnRtp added in v1.10.4

func (consumer *Consumer) OnRtp(handler func(data []byte))

OnRtp set handler on "rtp" event

func (*Consumer) OnScore added in v1.10.4

func (consumer *Consumer) OnScore(handler func(score *ConsumerScore))

OnScore set handler on "score" event

func (*Consumer) OnTrace added in v1.10.4

func (consumer *Consumer) OnTrace(handler func(trace *ConsumerTraceEventData))

OnTrace set handler on "trace" event

func (*Consumer) OnTransportClose added in v1.10.5

func (consumer *Consumer) OnTransportClose(handler func())

OnTransportClose set handler on "transportclose" event

func (*Consumer) Pause

func (consumer *Consumer) Pause() (err error)

Pause the Consumer.

func (*Consumer) Paused

func (consumer *Consumer) Paused() bool

Paused returns whether the Consumer is paused.

func (*Consumer) PreferredLayers

func (consumer *Consumer) PreferredLayers() *ConsumerLayers

PreferredLayers returns preferred video layers.

func (*Consumer) Priority

func (consumer *Consumer) Priority() uint32

Priority returns current priority.

func (*Consumer) ProducerId

func (consumer *Consumer) ProducerId() string

ProducerId returns associated Producer id.

func (*Consumer) ProducerPaused

func (consumer *Consumer) ProducerPaused() bool

ProducerPaused returns whether the associate Producer is paused.

func (*Consumer) RequestKeyFrame

func (consumer *Consumer) RequestKeyFrame() error

RequestKeyFrame request a key frame to the Producer.

func (*Consumer) Resume

func (consumer *Consumer) Resume() (err error)

Resume the Consumer.

func (*Consumer) RtpParameters

func (consumer *Consumer) RtpParameters() RtpParameters

RtpParameters returns RTP parameters.

func (*Consumer) Score

func (consumer *Consumer) Score() *ConsumerScore

Score returns consumer score with consumer and consumer keys.

func (*Consumer) SetPreferredLayers

func (consumer *Consumer) SetPreferredLayers(layers ConsumerLayers) (err error)

SetPreferredLayers set preferred video layers.

func (*Consumer) SetPriority

func (consumer *Consumer) SetPriority(priority uint32) (err error)

SetPriority set priority.

func (*Consumer) Type

func (consumer *Consumer) Type() ConsumerType

Type returns consumer type.

func (*Consumer) UnsetPriority

func (consumer *Consumer) UnsetPriority() (err error)

UnsetPriority unset priority.

type ConsumerDump

type ConsumerDump struct {
	Id                         string               `json:"id,omitempty"`
	ProducerId                 string               `json:"producerId,omitempty"`
	Kind                       string               `json:"kind,omitempty"`
	Type                       string               `json:"type,omitempty"`
	RtpParameters              RtpParameters        `json:"rtpParameters,omitempty"`
	ConsumableRtpEncodings     []RtpMappingEncoding `json:"consumableRtpEncodings,omitempty"`
	SupportedCodecPayloadTypes []uint32             `json:"supportedCodecPayloadTypes,omitempty"`
	Paused                     bool                 `json:"paused,omitempty"`
	ProducerPaused             bool                 `json:"producerPaused,omitempty"`
	Priority                   uint8                `json:"priority,omitempty"`
	TraceEventTypes            string               `json:"traceEventTypes,omitempty"`
	RtpStreams                 []RtpStream          `json:"rtpStreams,omitempty"`
	RtpStream                  *RtpStream           `json:"rtpStream,omitempty"` // dump by SvcConsumer
	*SimulcastConsumerDump
}

func (ConsumerDump) String added in v1.10.0

func (d ConsumerDump) String() string

type ConsumerLayers

type ConsumerLayers struct {
	// SpatialLayer is the spatial layer index (from 0 to N).
	SpatialLayer uint8 `json:"spatialLayer"`

	// TemporalLayer is the temporal layer index (from 0 to N).
	TemporalLayer uint8 `json:"temporalLayer"`
}

type ConsumerOptions

type ConsumerOptions struct {
	// ProducerId is the id of the Producer to consume.
	ProducerId string `json:"producerId,omitempty"`

	// RtpCapabilities is RTP capabilities of the consuming endpoint.
	RtpCapabilities RtpCapabilities `json:"rtpCapabilities,omitempty"`

	// Paused define whether the Consumer must start in paused mode. Default false.
	//
	// When creating a video Consumer, it's recommended to set paused to true,
	// then transmit the Consumer parameters to the consuming endpoint and, once
	// the consuming endpoint has created its local side Consumer, unpause the
	// server side Consumer using the resume() method. This is an optimization
	// to make it possible for the consuming endpoint to render the video as far
	// as possible. If the server side Consumer was created with paused false,
	// mediasoup will immediately request a key frame to the remote Producer and
	// suych a key frame may reach the consuming endpoint even before it's ready
	// to consume it, generating “black” video until the device requests a keyframe
	// by itself.
	Paused bool `json:"paused,omitempty"`

	// Mid is the MID for the Consumer. If not specified, a sequentially growing
	// number will be assigned.
	Mid string `json:"mid,omitempty"`

	//
	// PreferredLayers define preferred spatial and temporal layer for simulcast or
	// SVC media sources. If unset, the highest ones are selected.
	PreferredLayers *ConsumerLayers `json:"preferredLayers,omitempty"`

	// IgnoreDtx define whether this Consumer should ignore DTX packets (only valid for
	// Opus codec). If set, DTX packets are not forwarded to the remote Consumer.
	IgnoreDtx bool `json:"ignoreDtx,omitempty"`

	// Pipe define whether this Consumer should consume all RTP streams generated by the
	// Producer.
	Pipe bool `json:"pipe,omitempty"`

	// AppData is custom application data.
	AppData interface{} `json:"appData,omitempty"`
}

ConsumerOptions define options to create a Consumer.

type ConsumerScore

type ConsumerScore struct {
	// Score of the RTP stream of the consumer.
	Score uint16 `json:"score"`

	// Score of the currently selected RTP stream of the producer.
	ProducerScore uint16 `json:"producerScore"`

	// ProducerScores is he scores of all RTP streams in the producer ordered
	// by encoding (just useful when the producer uses simulcast).
	ProducerScores []uint16 `json:"producerScores,omitempty"`
}

ConsumerScore define "score" event data

type ConsumerStat

type ConsumerStat struct {
	// Common to all RtpStreams
	Type                 string  `json:"type,omitempty"`
	Timestamp            int64   `json:"timestamp,omitempty"`
	Ssrc                 uint32  `json:"ssrc,omitempty"`
	RtxSsrc              uint32  `json:"rtxSsrc,omitempty"`
	Rid                  string  `json:"rid,omitempty"`
	Kind                 string  `json:"kind,omitempty"`
	MimeType             string  `json:"mimeType,omitempty"`
	PacketsLost          uint32  `json:"packetsLost,omitempty"`
	FractionLost         uint32  `json:"fractionLost,omitempty"`
	PacketsDiscarded     uint32  `json:"packetsDiscarded,omitempty"`
	PacketsRetransmitted uint32  `json:"packetsRetransmitted,omitempty"`
	PacketsRepaired      uint32  `json:"packetsRepaired,omitempty"`
	NackCount            uint32  `json:"nackCount,omitempty"`
	NackPacketCount      uint32  `json:"nackPacketCount,omitempty"`
	PliCount             uint32  `json:"pliCount,omitempty"`
	FirCount             uint32  `json:"firCount,omitempty"`
	Score                uint32  `json:"score,omitempty"`
	PacketCount          int64   `json:"packetCount,omitempty"`
	ByteCount            int64   `json:"byteCount,omitempty"`
	Bitrate              uint32  `json:"bitrate,omitempty"`
	RoundTripTime        float32 `json:"roundTripTime,omitempty"`
	RtxPacketsDiscarded  uint32  `json:"rtxPacketsDiscarded,omitempty"`
}

ConsumerStat include two entries: the statistics of the RTP stream in the consumer (type: "outbound-rtp") and the statistics of the associated RTP stream in the producer (type: "inbound-rtp").

type ConsumerTraceEventData

type ConsumerTraceEventData struct {
	// Type is trace type.
	Type ConsumerTraceEventType `json:"type,omitempty"`

	// timestamp is event timestamp.
	Timestamp int64 `json:"timestamp,omitempty"`

	// Direction is event direction, "in" | "out".
	Direction string `json:"direction,omitempty"`

	// Info is per type information.
	Info H `json:"info,omitempty"`
}

ConsumerTraceEventData is "trace" event data.

type ConsumerTraceEventType

type ConsumerTraceEventType string

ConsumerTraceEventType is valid types for "trace" event.

const (
	ConsumerTraceEventType_Rtp      ConsumerTraceEventType = "rtp"
	ConsumerTraceEventType_Keyframe ConsumerTraceEventType = "keyframe"
	ConsumerTraceEventType_Nack     ConsumerTraceEventType = "nack"
	ConsumerTraceEventType_Pli      ConsumerTraceEventType = "pli"
	ConsumerTraceEventType_Fir      ConsumerTraceEventType = "fir"
)

type ConsumerType

type ConsumerType string

ProducerType define Consumer type.

const (
	ConsumerType_Simple    ConsumerType = "simple"
	ConsumerType_Simulcast ConsumerType = "simulcast"
	ConsumerType_Svc       ConsumerType = "svc"
	ConsumerType_Pipe      ConsumerType = "pipe"
)

type DataConsumer

type DataConsumer struct {
	IEventEmitter
	// contains filtered or unexported fields
}

DataConsumer represents an endpoint capable of receiving data messages from a mediasoup Router. A data consumer can use SCTP (AKA DataChannel) to receive those messages, or can directly receive them in the golang application if the data consumer was created on top of a DirectTransport.

  • @emits transportclose
  • @emits dataproducerclose
  • @emits message - (message []bytee, ppid int)
  • @emits sctpsendbufferfull
  • @emits bufferedamountlow - (bufferedAmount int64)
  • @emits @close
  • @emits @dataproducerclose

func (*DataConsumer) AppData

func (c *DataConsumer) AppData() interface{}

AppData returns app custom data.

func (*DataConsumer) Close

func (c *DataConsumer) Close() (err error)

Close the DataConsumer.

func (*DataConsumer) Closed

func (c *DataConsumer) Closed() bool

Closed returns whether the DataConsumer is closed.

func (*DataConsumer) DataProducerId

func (c *DataConsumer) DataProducerId() string

DataProducerId returns the associated DataProducer id.

func (*DataConsumer) Dump

func (c *DataConsumer) Dump() (data DataConsumerDump, err error)

Dump DataConsumer.

func (*DataConsumer) GetBufferedAmount

func (c *DataConsumer) GetBufferedAmount() (bufferedAmount int64, err error)

GetBufferedAmount returns buffered amount size.

func (*DataConsumer) GetStats

func (c *DataConsumer) GetStats() (stats []*DataConsumerStat, err error)

GetStats returns DataConsumer stats.

func (*DataConsumer) Id

func (c *DataConsumer) Id() string

Id returns DataConsumer id

func (*DataConsumer) Label

func (c *DataConsumer) Label() string

Label returns DataChannel label.

func (*DataConsumer) Observer

func (c *DataConsumer) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits dataproducerclose
  • @emits sctpsendbufferfull
  • @emits message - (message []bytee, ppid int)
  • @emits bufferedamountlow - (bufferAmount int64)

func (*DataConsumer) OnBufferedAmountLow added in v1.10.4

func (c *DataConsumer) OnBufferedAmountLow(handler func(bufferAmount uint32))

OnBufferedAmountLow set handler on "bufferedamountlow" event

func (*DataConsumer) OnClose added in v1.10.4

func (c *DataConsumer) OnClose(handler func())

OnClose set handler on "close" event

func (*DataConsumer) OnDataProducerClose added in v1.10.5

func (consumer *DataConsumer) OnDataProducerClose(handler func())

OnDataProducerClose set handler on "dataproducerclose" event

func (*DataConsumer) OnMessage added in v1.10.4

func (c *DataConsumer) OnMessage(handler func(payload []byte, ppid int))

OnMessage set handler on "message" event

func (*DataConsumer) OnSctpSendBufferFull added in v1.10.4

func (c *DataConsumer) OnSctpSendBufferFull(handler func())

OnSctpSendBufferFull set handler on "sctpsendbufferfull" event

func (*DataConsumer) OnTransportClose added in v1.10.5

func (consumer *DataConsumer) OnTransportClose(handler func())

OnTransportClose set handler on "transportclose" event

func (*DataConsumer) Protocol

func (c *DataConsumer) Protocol() string

Protocol returns DataChannel protocol.

func (*DataConsumer) SctpStreamParameters

func (c *DataConsumer) SctpStreamParameters() *SctpStreamParameters

SctpStreamParameters returns SCTP stream parameters.

func (*DataConsumer) Send

func (c *DataConsumer) Send(data []byte) (err error)

Send data.

func (*DataConsumer) SendText

func (c *DataConsumer) SendText(message string) error

SendText send text.

func (*DataConsumer) SetBufferedAmountLowThreshold

func (c *DataConsumer) SetBufferedAmountLowThreshold(threshold int) error

SetBufferedAmountLowThreshold set buffered amount low threshold.

func (*DataConsumer) Type

func (c *DataConsumer) Type() DataConsumerType

Type returns DataConsumer type.

type DataConsumerDump

type DataConsumerDump struct {
	Id                         string                `json:"id,omitempty"`
	DataProducerId             string                `json:"dataProducerId,omitempty"`
	Type                       string                `json:"type,omitempty"`
	SctpStreamParameters       *SctpStreamParameters `json:"sctpStreamParameters,omitempty"`
	Label                      string                `json:"label,omitempty"`
	Protocol                   string                `json:"protocol,omitempty"`
	BufferedAmount             uint32                `json:"bufferedAmount,omitempty"`
	BufferedAmountLowThreshold uint32                `json:"bufferedAmountLowThreshold,omitempty"`
}

func (DataConsumerDump) String added in v1.10.0

func (d DataConsumerDump) String() string

type DataConsumerOptions

type DataConsumerOptions struct {
	// DataProducerId is the id of the DataProducer to consume.
	DataProducerId string `json:"dataProducerId,omitempty"`

	// Ordered define just if consuming over SCTP.
	// Whether data messages must be received in order. If true the messages will
	// be sent reliably. Defaults to the value in the DataProducer if it has type
	// "sctp" or to true if it has type "direct".
	Ordered *bool `json:"ordered,omitempty"`

	// MaxPacketLifeTime define just if consuming over SCTP.
	// When ordered is false indicates the time (in milliseconds) after which a
	// SCTP packet will stop being retransmitted. Defaults to the value in the
	// DataProducer if it has type 'sctp' or unset if it has type 'direct'.
	MaxPacketLifeTime uint16 `json:"maxPacketLifeTime,omitempty"`

	// MaxRetransmits define just if consuming over SCTP.
	// When ordered is false indicates the maximum number of times a packet will
	// be retransmitted. Defaults to the value in the DataProducer if it has type
	// 'sctp' or unset if it has type 'direct'.
	MaxRetransmits uint16 `json:"maxRetransmits,omitempty"`

	// AppData is custom application data.
	AppData interface{} `json:"appData,omitempty"`
}

DataConsumerOptions define options to create a DataConsumer.

type DataConsumerStat

type DataConsumerStat struct {
	Type           string `json:"type,omitempty"`
	Timestamp      int64  `json:"timestamp,omitempty"`
	Label          string `json:"label,omitempty"`
	Protocol       string `json:"protocol,omitempty"`
	MessagesSent   int64  `json:"messagesSent,omitempty"`
	BytesSent      int64  `json:"bytesSent,omitempty"`
	BufferedAmount uint32 `json:"bufferedAmount,omitempty"`
}

DataConsumerStat define the statistic info for DataConsumer.

type DataConsumerType

type DataConsumerType string

DataConsumerType define DataConsumer type.

const (
	DataConsumerType_Sctp   DataConsumerType = "sctp"
	DataConsumerType_Direct DataConsumerType = "direct"
)

type DataProducer

type DataProducer struct {
	IEventEmitter
	// contains filtered or unexported fields
}

DataProducer represents an endpoint capable of injecting data messages into a mediasoup Router. A data producer can use SCTP (AKA DataChannel) to deliver those messages, or can directly send them from the golang application if the data producer was created on top of a DirectTransport.

  • @emits transportclose
  • @emits @close

func (*DataProducer) AppData

func (p *DataProducer) AppData() interface{}

AppData returns app custom data.

func (*DataProducer) Close

func (p *DataProducer) Close() (err error)

Close the DataProducer.

func (*DataProducer) Closed

func (p *DataProducer) Closed() bool

Closed returns whether the DataProducer is closed.

func (*DataProducer) Dump

func (p *DataProducer) Dump() (dump DataProducerDump, err error)

Dump DataConsumer.

func (*DataProducer) GetStats

func (p *DataProducer) GetStats() (stats []*DataProducerStat, err error)

GetStats returns DataConsumer stats.

func (*DataProducer) Id

func (p *DataProducer) Id() string

Id returns DataProducer id

func (*DataProducer) Label

func (p *DataProducer) Label() string

Label returns DataChannel label.

func (*DataProducer) Observer

func (p *DataProducer) Observer() IEventEmitter

Deprecated

  • @emits close

func (*DataProducer) OnClose added in v1.10.5

func (p *DataProducer) OnClose(handler func())

OnClose set handler on "close" event

func (*DataProducer) OnTransportClose added in v1.10.5

func (p *DataProducer) OnTransportClose(handler func())

OnTransportClose set handler on "transportclose" event

func (*DataProducer) Protocol

func (p *DataProducer) Protocol() string

Protocol returns DataChannel protocol.

func (*DataProducer) SctpStreamParameters

func (p *DataProducer) SctpStreamParameters() SctpStreamParameters

SctpStreamParameters returns SCTP stream parameters.

func (*DataProducer) Send

func (p *DataProducer) Send(data []byte) (err error)

Send data.

func (*DataProducer) SendText

func (p *DataProducer) SendText(message string) error

SendText send text.

func (*DataProducer) Type

func (p *DataProducer) Type() DataProducerType

Type returns DataProducer type.

type DataProducerDump

type DataProducerDump struct {
	Id                   string                `json:"id,omitempty"`
	Type                 string                `json:"type,omitempty"`
	SctpStreamParameters *SctpStreamParameters `json:"sctpStreamParameters,omitempty"`
	Label                string                `json:"label,omitempty"`
	Protocol             string                `json:"protocol,omitempty"`
}

func (DataProducerDump) String added in v1.10.0

func (d DataProducerDump) String() string

type DataProducerOptions

type DataProducerOptions struct {
	// Id is DataProducer id (just for Router.pipeToRouter() method).
	Id string `json:"id,omitempty"`

	// SctpStreamParameters define how the endpoint is sending the data.
	// Just if messages are sent over SCTP.
	SctpStreamParameters *SctpStreamParameters `json:"sctpStreamParameters,omitempty"`

	// Label can be used to distinguish this DataChannel from others.
	Label string `json:"label,omitempty"`

	// Protocol is the name of the sub-protocol used by this DataChannel.
	Protocol string `json:"protocol,omitempty"`

	// AppData is custom application data.
	AppData interface{} `json:"app_data,omitempty"`
}

DataProducerOptions define options to create a DataProducer.

type DataProducerStat

type DataProducerStat struct {
	Type             string
	Timestamp        int64
	Label            string
	Protocol         string
	MessagesReceived int64
	BytesReceived    int64
}

DataProducerStat define the statistic info for DataProducer.

type DataProducerType

type DataProducerType string

DataProducerType define DataProducer type.

const (
	DataProducerType_Sctp   DataProducerType = "sctp"
	DataProducerType_Direct DataProducerType = "direct"
)

type DirectTransport

type DirectTransport struct {
	ITransport
	// contains filtered or unexported fields
}

A direct transport can also be used to inject and directly consume RTP and RTCP packets in golang by using the producer.Send(rtpPacket) and consumer.On('rtp') API (plus directTransport.SendRtcp(rtcpPacket) and directTransport.On('rtcp') API).

  • @emits rtcp - (packet []byte)
  • @emits trace - (trace *TransportTraceEventData)

func (*DirectTransport) Connect

func (transport *DirectTransport) Connect(TransportConnectOptions) error

Connect is a NO-OP method in DirectTransport.

func (*DirectTransport) Observer

func (transport *DirectTransport) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits newdataproducer - (dataProducer *DataProducer)
  • @emits newdataconsumer - (dataProducer *DataProducer)
  • @emits rtcp - (packet []byte)
  • @emits trace - (trace: *TransportTraceEventData)

func (*DirectTransport) OnRtcp added in v1.10.4

func (transport *DirectTransport) OnRtcp(handler func(data []byte))

OnRtcp set handler on "rtcp" event

func (*DirectTransport) SendRtcp

func (transport *DirectTransport) SendRtcp(rtcpPacket []byte) error

SendRtcp send RTCP packet.

func (*DirectTransport) SetMaxIncomingBitrate added in v1.10.4

func (transport *DirectTransport) SetMaxIncomingBitrate(bitrate int) error

SetMaxIncomingBitrate always returns error.

type DirectTransportOptions

type DirectTransportOptions struct {
	// MaxMessageSize define maximum allowed size for direct messages sent from DataProducers.
	// Default 262144.
	MaxMessageSize uint32 `json:"maxMessageSize,omitempty"`

	// AppData is custom application data.
	AppData interface{} `json:"appData,omitempty"`
}

DirectTransportOptions define options to create a DirectTransport.

type DtlsFingerprint

type DtlsFingerprint struct {
	Algorithm string `json:"algorithm"`
	Value     string `json:"value"`
}

DtlsFingerprint defines the hash function algorithm (as defined in the "Hash function Textual Names" registry initially specified in RFC 4572 Section 8) and its corresponding certificate fingerprint value (in lowercase hex string as expressed utilizing the syntax of "fingerprint" in RFC 4572 Section 5).

type DtlsParameters

type DtlsParameters struct {
	Role         DtlsRole          `json:"role,omitempty"`
	Fingerprints []DtlsFingerprint `json:"fingerprints"`
}

type DtlsRole

type DtlsRole string
const (
	DtlsRole_Auto   DtlsRole = "auto"
	DtlsRole_Client DtlsRole = "client"
	DtlsRole_Server DtlsRole = "server"
)

type DtlsState

type DtlsState string
const (
	DtlsState_New        DtlsState = "new"
	DtlsState_Connecting DtlsState = "connecting"
	DtlsState_Connected  DtlsState = "connected"
	DtlsState_Failed     DtlsState = "failed"
	DtlsState_Closed     DtlsState = "closed"
)

type EventEmitter added in v1.10.1

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

func (*EventEmitter) Emit added in v1.10.1

func (e *EventEmitter) Emit(event string, args ...interface{}) bool

func (*EventEmitter) ListenerCount added in v1.10.4

func (e *EventEmitter) ListenerCount(events ...string) (total int)

func (*EventEmitter) Off added in v1.10.1

func (e *EventEmitter) Off(event string, listener interface{})

func (*EventEmitter) On added in v1.10.1

func (e *EventEmitter) On(event string, listener interface{})

func (*EventEmitter) Once added in v1.10.1

func (e *EventEmitter) Once(event string, listener interface{})

func (*EventEmitter) RemoveAllListeners added in v1.10.1

func (e *EventEmitter) RemoveAllListeners(events ...string)

func (*EventEmitter) SafeEmit added in v1.10.1

func (e *EventEmitter) SafeEmit(event string, args ...interface{}) bool

type H

type H map[string]interface{}

type IEventEmitter

type IEventEmitter interface {
	// On adds the listener function to the end of the listeners array for the event named eventName.
	// No checks are made to see if the listener has already been added.
	// Multiple calls passing the same combination of eventName and listener will result in the listener
	// being added, and called, multiple times.
	// By default, a maximum of 10 listeners can be registered for any single event.
	// This is a useful default that helps finding memory leaks. Note that this is not a hard limit.
	// The EventEmitter instance will allow more listeners to be added but will output a trace warning
	// to log indicating that a "possible EventEmitter memory leak" has been detected.
	On(eventName string, listener interface{})

	// Once adds a one-time listener function for the event named eventName.
	// The next time eventName is triggered, this listener is removed and then invoked.
	Once(eventName string, listener interface{})

	// Emit calls each of the listeners registered for the event named eventName,
	// in the order they were registered, passing the supplied arguments to each.
	// Returns true if the event had listeners, false otherwise.
	Emit(eventName string, argv ...interface{}) bool

	// SafeEmit calls each of the listeners registered for the event named eventName. It recovers
	// panic and logs panic info with provided logger.
	SafeEmit(eventName string, argv ...interface{}) bool

	// Off removes the specified listener from the listener array for the event named eventName.
	Off(eventName string, listener interface{})

	// RemoveAllListeners removes all listeners, or those of the specified eventNames.
	RemoveAllListeners(eventNames ...string)

	// ListenerCount returns total number of all listeners, or those of the specified eventNames.
	ListenerCount(eventNames ...string) int
}

EventEmitter defines an interface of the Event-based architecture(like EventEmitter in JavaScript).

func NewEventEmitter

func NewEventEmitter() IEventEmitter

type IRtpObserver

type IRtpObserver interface {
	IEventEmitter

	Id() string
	Closed() bool
	Paused() bool
	Observer() IEventEmitter
	Close()

	Pause()
	Resume()
	AddProducer(producerId string)
	RemoveProducer(producerId string)
	// contains filtered or unexported methods
}

type ITransport

type ITransport interface {
	IEventEmitter
	Id() string
	Closed() bool
	AppData() interface{}
	Observer() IEventEmitter
	Close()
	Dump() (*TransportDump, error)
	GetStats() ([]*TransportStat, error)
	Connect(TransportConnectOptions) error
	SetMaxIncomingBitrate(bitrate int) error
	Produce(ProducerOptions) (*Producer, error)
	Consume(ConsumerOptions) (*Consumer, error)
	ProduceData(DataProducerOptions) (*DataProducer, error)
	ConsumeData(DataConsumerOptions) (*DataConsumer, error)
	EnableTraceEvent(types ...TransportTraceEventType) error
	OnTrace(handler func(trace *TransportTraceEventData))
	OnClose(handler func())
	// contains filtered or unexported methods
}

type IceCandidate

type IceCandidate struct {
	Foundation string            `json:"foundation"`
	Priority   uint32            `json:"priority"`
	Ip         string            `json:"ip"`
	Protocol   TransportProtocol `json:"protocol"`
	Port       uint16            `json:"port"`
	// alway "host"
	Type string `json:"type,omitempty"`
	// "passive" | ""
	TcpType string `json:"tcpType,omitempty"`
}

type IceParameters

type IceParameters struct {
	UsernameFragment string `json:"usernameFragment"`
	Password         string `json:"password"`
	IceLite          bool   `json:"iceLite,omitempty"`
}

type IceState

type IceState string
const (
	IceState_New          IceState = "new"
	IceState_Connected    IceState = "connected"
	IceState_Completed    IceState = "completed"
	IceState_Disconnected IceState = "disconnected"
	IceState_Closed       IceState = "closed"
)

type InvalidStateError

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

InvalidStateError produced when calling a method in an invalid state.

func (InvalidStateError) Error

func (e InvalidStateError) Error() string

type LocalIceUsernameFragment added in v1.10.0

type LocalIceUsernameFragment struct {
	LocalIceUsernameFragment string `json:"localIceUsernameFragment,omitempty"`
	WebRtcTransportId        string `json:"webRtcTransportId,omitempty"`
}

type MediaKind

type MediaKind string

Media kind ("audio" or "video").

const (
	MediaKind_Audio MediaKind = "audio"
	MediaKind_Video MediaKind = "video"
)

type NetAddr added in v1.10.0

type NetAddr struct {
	Ip   string `json:"ip,omitempty"`
	Port uint16 `json:"port,omitempty"`
}

type NumSctpStreams

type NumSctpStreams struct {
	// OS defines initially requested int of outgoing SCTP streams.
	OS uint16 `json:"OS"`

	// MIS defines maximum int of incoming SCTP streams.
	MIS uint16 `json:"MIS"`
}

NumSctpStreams defines the SCTP streams configuration.

Both OS and MIS are part of the SCTP INIT+ACK handshake. OS refers to the initial int of outgoing SCTP streams that the server side transport creates (to be used by DataConsumers), while MIS refers to the maximum int of incoming SCTP streams that the server side transport can receive (to be used by DataProducers). So, if the server side transport will just be used to create data producers (but no data consumers), OS can be low (~1). However, if data consumers are desired on the server side transport, OS must have a proper value and such a proper value depends on whether the remote endpoint supports SCTP_ADD_STREAMS extension or not.

libwebrtc (Chrome, Safari, etc) does not enable SCTP_ADD_STREAMS so, if data consumers are required, OS should be 1024 (the maximum int of DataChannels that libwebrtc enables).

Firefox does enable SCTP_ADD_STREAMS so, if data consumers are required, OS can be lower (16 for instance). The mediasoup transport will allocate and announce more outgoing SCTM streams when needed.

mediasoup-client provides specific per browser/version OS and MIS values via the device.sctpCapabilities getter.

type Option

type Option func(w *WorkerSettings)

func WithCustomOption added in v1.6.39

func WithCustomOption(key string, value interface{}) Option

func WithDtlsCert

func WithDtlsCert(dtlsCertificateFile, dtlsPrivateKeyFile string) Option

func WithLogLevel

func WithLogLevel(logLevel WorkerLogLevel) Option

func WithLogTags

func WithLogTags(logTags []WorkerLogTag) Option

func WithRtcMaxPort

func WithRtcMaxPort(rtcMaxPort uint16) Option

func WithRtcMinPort

func WithRtcMinPort(rtcMinPort uint16) Option

func WithWorkerBin added in v1.9.5

func WithWorkerBin(workerBin string) Option

func WithWorkerVersion added in v1.9.5

func WithWorkerVersion(workerVersion string) Option

type PayloadChannel

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

func (*PayloadChannel) Close

func (c *PayloadChannel) Close() error

func (*PayloadChannel) Closed

func (c *PayloadChannel) Closed() bool

func (*PayloadChannel) Notify

func (c *PayloadChannel) Notify(event string, internal internalData, data string, payload []byte) (err error)

func (*PayloadChannel) Request

func (c *PayloadChannel) Request(method string, internal internalData, data string, payload []byte) (rsp workerResponse)

func (*PayloadChannel) Start added in v1.9.1

func (c *PayloadChannel) Start()

func (*PayloadChannel) Subscribe added in v1.10.4

func (c *PayloadChannel) Subscribe(targetId string, handler payloadChannelSubscriber)

func (*PayloadChannel) Unsubscribe added in v1.10.4

func (c *PayloadChannel) Unsubscribe(targetId string)

type PipeToRouterOptions

type PipeToRouterOptions struct {
	// ProducerId is the id of the Producer to consume.
	ProducerId string `json:"producerId,omitempty"`

	// DataProducerId is the id of the DataProducer to consume.
	DataProducerId string `json:"dataProducerId,omitempty"`

	// Router is the target Router instance.
	Router *Router `json:"router,omitempty"`

	// ListenIp is the ip used in the PipeTransport pair. Default '127.0.0.1'.
	ListenIp TransportListenIp `json:"listenIp,omitempty"`

	// Create a SCTP association. Default false.
	EnableSctp bool `json:"enableSctp,omitempty"`

	// NumSctpStreams define SCTP streams number.
	NumSctpStreams NumSctpStreams `json:"numSctpStreams,omitempty"`

	// EnableRtx enable RTX and NACK for RTP retransmission.
	EnableRtx bool `json:"enableRtx,omitempty"`

	// EnableSrtp enable SRTP.
	EnableSrtp bool `json:"enableSrtp,omitempty"`
}

PipeToRouterOptions define options to pipe an another router.

type PipeToRouterResult

type PipeToRouterResult struct {
	// PipeConsumer is the Consumer created in the current Router.
	PipeConsumer *Consumer

	// PipeConsumer is the Producer created in the target Router.
	PipeProducer *Producer

	// PipeDataConsumer is the DataConsumer created in the current Router.
	PipeDataConsumer *DataConsumer

	// PipeDataProducer is the DataProducer created in the target Router.
	PipeDataProducer *DataProducer
}

PipeToRouterResult is the result to piping router.

type PipeTransport

type PipeTransport struct {
	ITransport
	// contains filtered or unexported fields
}

PipeTransport represents a network path through which RTP, RTCP (optionally secured with SRTP) and SCTP (DataChannel) is transmitted. Pipe transports are intented to intercommunicate two Router instances collocated on the same host or on separate hosts.

  • @emits sctpstatechange - (sctpState SctpState)
  • @emits trace - (trace *TransportTraceEventData)

func (*PipeTransport) Close

func (transport *PipeTransport) Close()

Close the PipeTransport.

func (*PipeTransport) Connect

func (transport *PipeTransport) Connect(options TransportConnectOptions) (err error)

Connect provide the PlainTransport remote parameters.

func (*PipeTransport) Consume

func (transport *PipeTransport) Consume(options ConsumerOptions) (consumer *Consumer, err error)

Consume create a pipe Consumer.

func (*PipeTransport) Observer

func (transport *PipeTransport) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits newproducer - (producer *Producer)
  • @emits newconsumer - (consumer *Consumer)
  • @emits newdataproducer - (dataProducer *DataProducer)
  • @emits newdataconsumer - (dataConsumer *DataConsumer)
  • @emits sctpstatechange - (sctpState SctpState)
  • @emits trace - (trace: TransportTraceEventData)

func (*PipeTransport) OnSctpStateChange added in v1.10.4

func (transport *PipeTransport) OnSctpStateChange(handler func(sctpState SctpState))

OnSctpStateChange set handler on "sctpstatechange" event

func (PipeTransport) SctpParameters

func (t PipeTransport) SctpParameters() SctpParameters

SctpParameters returns SCTP parameters.

func (PipeTransport) SctpState

func (t PipeTransport) SctpState() SctpState

SctpState returns SCTP state.

func (PipeTransport) SrtpParameters

func (t PipeTransport) SrtpParameters() *SrtpParameters

SrtpParameters returns SRTP parameters.

func (PipeTransport) Tuple

func (t PipeTransport) Tuple() TransportTuple

Tuple returns transport tuple.

type PipeTransportOptions

type PipeTransportOptions struct {
	// ListenIp define Listening IP address.
	ListenIp TransportListenIp `json:"listenIp,omitempty"`

	// EnableSctp define whether create a SCTP association. Default false.
	EnableSctp bool `json:"enableSctp,omitempty"`

	// NumSctpStreams define SCTP streams number.
	NumSctpStreams NumSctpStreams `json:"numSctpStreams,omitempty"`

	// MaxSctpMessageSize define maximum allowed size for SCTP messages sent by DataProducers.
	// Default 268435456.
	MaxSctpMessageSize int `json:"maxSctpMessageSize,omitempty"`

	// SctpSendBufferSize define maximum SCTP send buffer used by DataConsumers.
	// Default 268435456.
	SctpSendBufferSize int `json:"sctpSendBufferSize,omitempty"`

	// EnableSrtp enable SRTP. For this to work, connect() must be called
	// with remote SRTP parameters. Default false.
	EnableSrtp bool `json:"enableSrtp,omitempty"`

	// EnableRtx enable RTX and NACK for RTP retransmission. Useful if both Routers are
	// located in different hosts and there is packet lost in the link. For this
	// to work, both PipeTransports must enable this setting. Default false.
	EnableRtx bool `json:"enableRtx,omitempty"`

	// AppData is custom application data.
	AppData interface{} `json:"appData,omitempty"`
}

PipeTransportOptions define options to create a PipeTransport

type PlainTransport

type PlainTransport struct {
	ITransport
	// contains filtered or unexported fields
}

PlainTransport represents a network path through which RTP, RTCP (optionally secured with SRTP) and SCTP = data.hannel is transmitted.

  • @emits tuple - (tuple *TransportTuple)
  • @emits rtcptuple - (rtcpTuple *TransportTuple)
  • @emits sctpstatechange - (sctpState SctpState)
  • @emits trace - (trace *TransportTraceEventData)

func (*PlainTransport) Close

func (transport *PlainTransport) Close()

Close the PlainTransport.

func (*PlainTransport) Connect

func (transport *PlainTransport) Connect(options TransportConnectOptions) (err error)

Connect provide the PlainTransport remote parameters.

func (*PlainTransport) Observer

func (transport *PlainTransport) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits newproducer - (producer *Producer)
  • @emits newconsumer - (consumer *Consumer)
  • @emits newdataproducer - = data.roducer *DataProducer
  • @emits newdataconsumer - = data.onsumer *DataConsumer
  • @emits tuple - (tuple TransportTuple)
  • @emits rtcptuple - (rtcpTuple TransportTuple)
  • @emits sctpstatechange - (sctpState SctpState)
  • @emits trace - (trace *TransportTraceEventData)

func (*PlainTransport) OnRtcpTuple added in v1.10.4

func (transport *PlainTransport) OnRtcpTuple(handler func(rtcpTuple *TransportTuple))

OnRtcpTuple set handler on "rtcptuple" event

func (*PlainTransport) OnSctpStateChange added in v1.10.4

func (transport *PlainTransport) OnSctpStateChange(handler func(sctpState SctpState))

OnSctpStateChange set handler on "sctpstatechange" event

func (*PlainTransport) OnTuple added in v1.10.4

func (transport *PlainTransport) OnTuple(handler func(tuple *TransportTuple))

OnTuple set handler on "tuple" event

func (PlainTransport) RtcpTuple

func (t PlainTransport) RtcpTuple() *TransportTuple

RtcpTuple returns transport RTCP tuple.

func (PlainTransport) SctpParameters

func (t PlainTransport) SctpParameters() SctpParameters

SctpParameters returns SCTP parameters.

func (PlainTransport) SctpState

func (t PlainTransport) SctpState() SctpState

SctpState returns SCTP state.

func (PlainTransport) SrtpParameters

func (t PlainTransport) SrtpParameters() *SrtpParameters

SrtpParameters returns SRTP parameters.

func (PlainTransport) Tuple

func (t PlainTransport) Tuple() *TransportTuple

Tuple returns transport tuple.

type PlainTransportDump

type PlainTransportDump struct {
	RtcpMux        bool            `json:"rtcpMux,omitempty"`
	Comedia        bool            `json:"comedia,omitempty"`
	Tuple          *TransportTuple `json:"tuple,omitempty"`
	RtcpTuple      *TransportTuple `json:"rtcpTuple,omitempty"`
	SrtpParameters *SrtpParameters `json:"srtpParameters,omitempty"`
}

func (PlainTransportDump) String added in v1.10.0

func (d PlainTransportDump) String() string

type PlainTransportOptions

type PlainTransportOptions struct {
	// ListenIp define Listening IP address.
	ListenIp TransportListenIp `json:"listenIp,omitempty"`

	// RtcpMux define wether use RTCP-mux (RTP and RTCP in the same port). Default true.
	RtcpMux *bool `json:"rtcpMux,omitempty"`

	// Comedia define whether remote IP:port should be auto-detected based on first RTP/RTCP
	// packet received. If enabled, connect() method must not be called unless
	// SRTP is enabled. If so, it must be called with just remote SRTP parameters.
	// Default false.
	Comedia bool `json:"comedia,omitempty"`

	// EnableSctp define whether create a SCTP association. Default false.
	EnableSctp bool `json:"enableSctp,omitempty"`

	// NumSctpStreams define SCTP streams number.
	NumSctpStreams NumSctpStreams `json:"numSctpStreams,omitempty"`

	// MaxSctpMessageSize define maximum allowed size for SCTP messages sent by DataProducers.
	// Default 262144.
	MaxSctpMessageSize int `json:"maxSctpMessageSize,omitempty"`

	// SctpSendBufferSize define maximum SCTP send buffer used by DataConsumers.
	// Default 262144.
	SctpSendBufferSize int `json:"sctpSendBufferSize,omitempty"`

	// EnableSrtp enable SRTP. For this to work, connect() must be called
	// with remote SRTP parameters. Default false.
	EnableSrtp bool `json:"enableSrtp,omitempty"`

	// SrtpCryptoSuite define the SRTP crypto suite to be used if enableSrtp is set. Default
	// 'AES_CM_128_HMAC_SHA1_80'.
	SrtpCryptoSuite SrtpCryptoSuite `json:"srtpCryptoSuite,omitempty"`

	// AppData is custom application data.
	AppData interface{} `json:"appData,omitempty"`
}

PlainTransportOptions define options to create a PlainTransport

type PlainTransportSpecificStat

type PlainTransportSpecificStat struct {
	RtcpMux   bool            `json:"rtcp_mux"`
	Comedia   bool            `json:"comedia"`
	Tuple     TransportTuple  `json:"tuple"`
	RtcpTuple *TransportTuple `json:"rtcpTuple,omitempty"`
}

PlainTransportSpecificStat define the stat info for PlainTransport

type Producer

type Producer struct {
	IEventEmitter
	// contains filtered or unexported fields
}

Producer represents an audio or video source being injected into a mediasoup router. It's created on top of a transport that defines how the media packets are carried.

  • @emits transportclose
  • @emits score - (scores []ProducerScore)
  • @emits videoorientationchange - (videoOrientation *ProducerVideoOrientation)
  • @emits trace - (trace *ProducerTraceEventData)
  • @emits @close

func (*Producer) AppData

func (producer *Producer) AppData() interface{}

AppData returns app custom data.

func (*Producer) Close

func (producer *Producer) Close() (err error)

Close the producer.

func (*Producer) Closed

func (producer *Producer) Closed() bool

Closed returns whether the Producer is closed.

func (*Producer) ConsumableRtpParameters

func (producer *Producer) ConsumableRtpParameters() RtpParameters

ConsumableRtpParameters returns consumable RTP parameters.

func (*Producer) Dump

func (producer *Producer) Dump() (dump ProducerDump, err error)

Dump producer.

func (*Producer) EnableTraceEvent

func (producer *Producer) EnableTraceEvent(types ...ProducerTraceEventType) error

EnableTraceEvent enable "trace" event.

func (*Producer) GetStats

func (producer *Producer) GetStats() (stats []*ProducerStat, err error)

GetStats returns producer stats.

func (*Producer) Id

func (producer *Producer) Id() string

Id returns producer id

func (*Producer) Kind

func (producer *Producer) Kind() MediaKind

Kind returns media kind.

func (*Producer) Observer

func (producer *Producer) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits pause
  • @emits resume
  • @emits score - (scores []ProducerScore)
  • @emits videoorientationchange - (videoOrientation *ProducerVideoOrientation)
  • @emits trace - (trace *ProducerTraceEventData)

func (*Producer) OnClose added in v1.10.4

func (producer *Producer) OnClose(handler func())

OnClose set handler on "close" event

func (*Producer) OnPause added in v1.10.4

func (producer *Producer) OnPause(handler func())

OnPause set handler on "pause" event

func (*Producer) OnResume added in v1.10.4

func (producer *Producer) OnResume(handler func())

OnResume set handler on "resume" event

func (*Producer) OnScore added in v1.10.4

func (producer *Producer) OnScore(handler func(score []ProducerScore))

OnScore set handler on "score" event

func (*Producer) OnTrace added in v1.10.4

func (producer *Producer) OnTrace(handler func(trace *ProducerTraceEventData))

OnTrace set handler on "trace" event

func (*Producer) OnTransportClose added in v1.10.5

func (producer *Producer) OnTransportClose(handler func())

OnTransportClose set handler on "transportclose" event

func (*Producer) OnVideoOrientationChange added in v1.10.4

func (producer *Producer) OnVideoOrientationChange(handler func(videoOrientation *ProducerVideoOrientation))

OnVideoOrientationChange set handler on "videoorientationchange" event

func (*Producer) Pause

func (producer *Producer) Pause() (err error)

Pause the producer.

func (*Producer) Paused

func (producer *Producer) Paused() bool

Paused returns whether the Producer is paused.

func (*Producer) Resume

func (producer *Producer) Resume() (err error)

Resume the producer.

func (*Producer) RtpParameters

func (producer *Producer) RtpParameters() RtpParameters

RtpParameters returns RTP parameters.

func (*Producer) Score

func (producer *Producer) Score() []ProducerScore

Score returns producer score list.

func (*Producer) Send

func (producer *Producer) Send(rtpPacket []byte) error

Send RTP packet (just valid for Producers created on a DirectTransport).

func (*Producer) Type

func (producer *Producer) Type() ProducerType

Type returns producer type.

type ProducerDump

type ProducerDump struct {
	Id              string             `json:"id,omitempty"`
	Kind            string             `json:"kind,omitempty"`
	Type            string             `json:"type,omitempty"`
	RtpParameters   RtpParameters      `json:"rtpParameters,omitempty"`
	RtpMapping      RtpMapping         `json:"rtpMapping,omitempty"`
	Encodings       RtpMappingEncoding `json:"encodings,omitempty"`
	RtpStreams      []RtpStream        `json:"rtpStreams,omitempty"`
	Paused          bool               `json:"paused,omitempty"`
	TraceEventTypes string             `json:"traceEventTypes,omitempty"`
}

func (ProducerDump) String added in v1.10.0

func (d ProducerDump) String() string

type ProducerOptions

type ProducerOptions struct {
	// Id is the producer id (just for Router.pipeToRouter() method).
	Id string `json:"id,omitempty"`

	// Kind is media kind ("audio" or "video").
	Kind MediaKind `json:"kind,omitempty"`

	// RtpParameters define what the endpoint is sending.
	RtpParameters RtpParameters `json:"rtpParameters,omitempty"`

	// Paused define whether the producer must start in paused mode. Default false.
	Paused bool `json:"paused,omitempty"`

	// KeyFrameRequestDelay is just used for video. Time (in ms) before asking
	// the sender for a new key frame after having asked a previous one. Default 0.
	KeyFrameRequestDelay uint32 `json:"keyFrameRequestDelay,omitempty"`

	// AppData is custom application data.
	AppData interface{} `json:"appData,omitempty"`
}

ProducerOptions define options to create a producer.

type ProducerScore

type ProducerScore struct {
	// Ssrc of the RTP stream.
	Ssrc uint32 `json:"ssrc,omitempty"`

	// Rid of the RTP stream.
	Rid string `json:"rid,omitempty"`

	// Score of the RTP stream.
	Score uint32 `json:"score"`
}

ProducerScore define "score" event data

type ProducerStat

type ProducerStat struct {
	ConsumerStat
	// Jitter is the jitter buffer.
	Jitter uint32 `json:"jitter,omitempty"`
	// BitrateByLayer is a map of bitrate of each layer (such as {"0.0": 100, "1.0": 500})
	BitrateByLayer map[string]uint32 `json:"bitrateByLayer,omitempty"`
}

ProducerStat define the statistic info of a producer

type ProducerTraceEventData

type ProducerTraceEventData struct {
	// Type is the trace type.
	Type ProducerTraceEventType `json:"type,omitempty"`

	// Timestamp is event timestamp.
	Timestamp uint32 `json:"timestamp,omitempty"`

	// Direction is event direction, "in" | "out".
	Direction string `json:"direction,omitempty"`

	// Info is per type information.
	Info H `json:"info,omitempty"`
}

ProducerTraceEventData define "trace" event data.

type ProducerTraceEventType

type ProducerTraceEventType string

ProducerTraceEventType define the type for "trace" event.

const (
	ProducerTraceEventType_Rtp      ProducerTraceEventType = "rtp"
	ProducerTraceEventType_Keyframe ProducerTraceEventType = "keyframe"
	ProducerTraceEventType_Nack     ProducerTraceEventType = "nack"
	ProducerTraceEventType_Pli      ProducerTraceEventType = "pli"
	ProducerTraceEventType_Fir      ProducerTraceEventType = "fir"
)

type ProducerType

type ProducerType string

ProducerType define Producer type.

const (
	ProducerType_Simple    ProducerType = "simple"
	ProducerType_Simulcast ProducerType = "simulcast"
	ProducerType_Svc       ProducerType = "svc"
)

type ProducerVideoOrientation

type ProducerVideoOrientation struct {
	// Camera define whether the source is a video camera.
	Camera bool `json:"Camera,omitempty"`

	// Flip define whether the video source is flipped.
	Flip bool `json:"flip,omitempty"`

	// Rotation degrees (0, 90, 180 or 270).
	Rotation uint32 `json:"rotation"`
}

ProducerVideoOrientation define "videoorientationchange" event data

type RecvRtpHeaderExtensions

type RecvRtpHeaderExtensions struct {
	Mid               uint8 `json:"mid,omitempty"`
	Rid               uint8 `json:"rid,omitempty"`
	Rrid              uint8 `json:"rrid,omitempty"`
	AbsSendTime       uint8 `json:"absSendTime,omitempty"`
	TransportWideCc01 uint8 `json:"transportWideCc01,omitempty"`
}

type Router

type Router struct {
	IEventEmitter
	// contains filtered or unexported fields
}

Router enables injection, selection and forwarding of media streams through Transport instances created on it.

  • @emits workerclose
  • @emits @close

func (*Router) AppData added in v1.10.0

func (router *Router) AppData() interface{}

AppData returns App custom data.

func (*Router) CanConsume

func (router *Router) CanConsume(producerId string, rtpCapabilities RtpCapabilities) bool

CanConsume check whether the given RTP capabilities can consume the given Producer.

func (*Router) Close

func (router *Router) Close() (err error)

Close the Router.

func (*Router) Closed

func (router *Router) Closed() bool

Closed returns whether the Router is closed.

func (*Router) CreateActiveSpeakerObserver added in v1.9.5

func (router *Router) CreateActiveSpeakerObserver(options ...func(*ActiveSpeakerObserverOptions)) (activeSpeakerObserver *ActiveSpeakerObserver, err error)

CreateActiveSpeakerObserver create an ActiveSpeakerObserver

func (*Router) CreateAudioLevelObserver

func (router *Router) CreateAudioLevelObserver(options ...func(o *AudioLevelObserverOptions)) (audioLevelObserver *AudioLevelObserver, err error)

CreateAudioLevelObserver create an AudioLevelObserver.

func (*Router) CreateDirectTransport

func (router *Router) CreateDirectTransport(params ...DirectTransportOptions) (transport *DirectTransport, err error)

CreateDirectTransport create a DirectTransport.

func (*Router) CreatePipeTransport

func (router *Router) CreatePipeTransport(option PipeTransportOptions) (transport *PipeTransport, err error)

CreatePipeTransport create a PipeTransport.

func (*Router) CreatePlainTransport

func (router *Router) CreatePlainTransport(option PlainTransportOptions) (transport *PlainTransport, err error)

CreatePlainTransport create a PlainTransport.

func (*Router) CreateWebRtcTransport

func (router *Router) CreateWebRtcTransport(option WebRtcTransportOptions) (transport *WebRtcTransport, err error)

CreateWebRtcTransport create a WebRtcTransport.

func (*Router) DataProducers added in v1.9.0

func (router *Router) DataProducers() []*DataProducer

DataProducers returns available producers on the router.

func (*Router) Dump

func (router *Router) Dump() (data *RouterDump, err error)

Dump Router.

func (*Router) Id

func (router *Router) Id() string

Id returns Router id

func (*Router) Observer

func (router *Router) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits newrtpobserver - (observer IRtpObserver)
  • @emits newtransport - (transport ITransport)

func (*Router) OnClose added in v1.10.8

func (router *Router) OnClose(handler func())

func (*Router) OnNewRtpObserver added in v1.10.5

func (router *Router) OnNewRtpObserver(handler func(transport IRtpObserver))

OnNewRtpObserver set handler on "newrtpobserver" event

func (*Router) OnNewTransport added in v1.10.5

func (router *Router) OnNewTransport(handler func(transport ITransport))

OnNewTransport set handler on "newtransport" event

func (*Router) PipeToRouter

func (router *Router) PipeToRouter(option PipeToRouterOptions) (result *PipeToRouterResult, err error)

PipeToRouter pipes the given Producer or DataProducer into another Router in same host.

func (*Router) Producers added in v1.9.0

func (router *Router) Producers() []*Producer

Producers returns available producers on the router.

func (*Router) RtpCapabilities

func (router *Router) RtpCapabilities() RtpCapabilities

RtpCapabilities returns RTC capabilities of the Router.

func (*Router) Transports added in v1.9.0

func (router *Router) Transports() []ITransport

Transports returns available transports on the router.

type RouterDump

type RouterDump struct {
	Id                               string              `json:"id,omitempty"`
	TransportIds                     []string            `json:"transportIds,omitempty"`
	RtpObserverIds                   []string            `json:"rtpObserverIds,omitempty"`
	MapProducerIdConsumerIds         map[string][]string `json:"mapProducerIdConsumerIds,omitempty"`
	MapConsumerIdProducerId          map[string]string   `json:"mapConsumerIdProducerId,omitempty"`
	MapProducerIdObserverIds         map[string][]string `json:"mapProducerIdObserverIds,omitempty"`
	MapDataProducerIdDataConsumerIds map[string][]string `json:"mapDataProducerIdDataConsumerIds,omitempty"`
	MapDataConsumerIdDataProducerId  map[string]string   `json:"mapDataConsumerIdDataProducerId,omitempty"`
}

func (RouterDump) String added in v1.10.0

func (d RouterDump) String() string

type RouterOptions

type RouterOptions struct {
	// MediaCodecs defines Router media codecs.
	MediaCodecs []*RtpCodecCapability `json:"mediaCodecs,omitempty"`

	// AppData is custom application data.
	AppData interface{} `json:"appData,omitempty"`
}

RouterOptions define options to create a router.

type RtcpFeedback

type RtcpFeedback struct {
	// Type is RTCP feedback type.
	Type string `json:"type"`

	// Parameter is RTCP feedback parameter.
	Parameter string `json:"parameter,omitempty"`
}

RtcpFeedback provides information on RTCP feedback messages for a specific codec. Those messages can be transport layer feedback messages or codec-specific feedback messages. The list of RTCP feedbacks supported by mediasoup is defined in the supported_rtp_capabilities.go file.

type RtcpParameters

type RtcpParameters struct {
	// Cname is the Canonical Name (CNAME) used by RTCP (e.g. in SDES messages).
	Cname string `json:"cname,omitempty"`

	// ReducedSize defines whether reduced size RTCP RFC 5506 is configured (if true) or
	// compound RTCP as specified in RFC 3550 (if false). Default true.
	ReducedSize *bool `json:"reducedSize,omitempty"`

	// Mux defines whether RTCP-mux is used. Default true.
	Mux *bool `json:"mux,omitempty"`
}

RtcpParameters provides information on RTCP settings within the RTP parameters.

If no cname is given in a producer's RTP parameters, the mediasoup transport will choose a random one that will be used into RTCP SDES messages sent to all its associated consumers.

mediasoup assumes reducedSize to always be true.

type RtpCapabilities

type RtpCapabilities struct {
	// Codecs is the supported media and RTX codecs.
	Codecs []*RtpCodecCapability `json:"codecs,omitempty"`

	// HeaderExtensions is the supported RTP header extensions.
	HeaderExtensions []*RtpHeaderExtension `json:"headerExtensions,omitempty"`

	// FecMechanisms is the supported FEC mechanisms.
	FecMechanisms []string `json:"fecMechanisms,omitempty"`
}

RtpCapabilities define what mediasoup or an endpoint can receive at media level.

func GetSupportedRtpCapabilities

func GetSupportedRtpCapabilities() (rtpCapabilities RtpCapabilities)

type RtpCodecCapability

type RtpCodecCapability struct {
	// Kind is the media kind.
	Kind MediaKind `json:"kind"`

	// MimeType is the codec MIME media type/subtype (e.g. 'audio/opus', 'video/VP8').
	MimeType string `json:"mimeType"`

	// PreferredPayloadType is the preferred RTP payload type.
	PreferredPayloadType byte `json:"preferredPayloadType,omitempty"`

	// ClockRate is the codec clock rate expressed in Hertz.
	ClockRate int `json:"clockRate"`

	// Channels is the int of channels supported (e.g. 2 for stereo). Just for audio.
	// Default 1.
	Channels int `json:"channels,omitempty"`

	// Parameters is the codec specific parameters. Some parameters (such as
	// 'packetization-mode' and 'profile-level-id' in H264 or 'profile-id' in VP9)
	// are critical for codec matching.
	Parameters RtpCodecSpecificParameters `json:"parameters"`

	// RtcpFeedback is the transport layer and codec-specific feedback messages for this codec.
	RtcpFeedback []RtcpFeedback `json:"rtcpFeedback"`
}

RtpCodecCapability provides information on the capabilities of a codec within the RTP capabilities. The list of media codecs supported by mediasoup and their settings is defined in the supported_rtp_capabilities.go file.

Exactly one RtpCodecCapability will be present for each supported combination of parameters that requires a distinct value of preferredPayloadType. For example

  • Multiple H264 codecs, each with their own distinct 'packetization-mode' and 'profile-level-id' values.
  • Multiple VP9 codecs, each with their own distinct 'profile-id' value.

RtpCodecCapability entries in the mediaCodecs array of RouterOptions do not require preferredPayloadType field (if unset, mediasoup will choose a random one). If given, make sure it's in the 96-127 range.

type RtpCodecParameters

type RtpCodecParameters struct {
	// MimeType is the codec MIME media type/subtype (e.g. 'audio/opus', 'video/VP8').
	MimeType string `json:"mimeType"`

	// PayloadType is the value that goes in the RTP Payload Type Field. Must be unique.
	PayloadType byte `json:"payloadType"`

	// ClockRate is codec clock rate expressed in Hertz.
	ClockRate int `json:"clockRate"`

	// Channels is the int of channels supported (e.g. 2 for stereo). Just for audio.
	// Default 1.
	Channels int `json:"channels,omitempty"`

	// Parameters is Codec-specific parameters available for signaling. Some parameters
	// (such as 'packetization-mode' and 'profile-level-id' in H264 or 'profile-id' in
	// VP9) are critical for codec matching.
	Parameters RtpCodecSpecificParameters `json:"parameters,omitempty"`

	// RtcpFeedback is transport layer and codec-specific feedback messages for this codec.
	RtcpFeedback []RtcpFeedback `json:"rtcpFeedback,omitempty"`
}

RtpCodecParameters provides information on codec settings within the RTP parameters. The list of media codecs supported by mediasoup and their settings is defined in the supported_rtp_capabilities.go file.

type RtpCodecSpecificParameters

type RtpCodecSpecificParameters struct {
	h264.RtpParameter          // used by h264 codec
	ProfileId           *uint8 `json:"profile-id,omitempty"`   // used by vp9
	Apt                 uint8  `json:"apt,omitempty"`          // used by rtx codec
	SpropStereo         uint8  `json:"sprop-stereo,omitempty"` // used by audio, 1 or 0
	Useinbandfec        uint8  `json:"useinbandfec,omitempty"` // used by audio, 1 or 0
	Usedtx              uint8  `json:"usedtx,omitempty"`       // used by audio, 1 or 0
	Maxplaybackrate     uint32 `json:"maxplaybackrate,omitempty"`
	XGoogleMinBitrate   uint32 `json:"x-google-min-bitrate,omitempty"`
	XGoogleMaxBitrate   uint32 `json:"x-google-max-bitrate,omitempty"`
	XGoogleStartBitrate uint32 `json:"x-google-start-bitrate,omitempty"`
	ChannelMapping      string `json:"channel_mapping,omitempty"`
	NumStreams          uint8  `json:"num_streams,omitempty"`
	CoupledStreams      uint8  `json:"coupled_streams,omitempty"`
	Minptime            uint8  `json:"minptime,omitempty"` // used by opus audio, up to 120
}

RtpCodecSpecificParameters is the Codec-specific parameters available for signaling. Some parameters (such as 'packetization-mode' and 'profile-level-id' in H264 or 'profile-id' in VP9) are critical for codec matching.

type RtpEncodingParameters

type RtpEncodingParameters struct {
	// SSRC of media.
	Ssrc uint32 `json:"ssrc,omitempty"`

	// RID RTP extension value. Must be unique.
	Rid string `json:"rid,omitempty"`

	// CodecPayloadType is the codec payload type this encoding affects.
	// If unset, first media codec is chosen.
	CodecPayloadType byte `json:"codecPayloadType,omitempty"`

	// RTX stream information. It must contain a numeric ssrc field indicating
	// the RTX SSRC.
	Rtx *RtpEncodingRtx `json:"rtx,omitempty"`

	// Dtx indicates whether discontinuous RTP transmission will be used. Useful
	// for audio (if the codec supports it) and for video screen sharing (when
	// static content is being transmitted, this option disables the RTP
	// inactivity checks in mediasoup). Default false.
	Dtx bool `json:"dtx,omitempty"`

	// ScalabilityMode defines spatial and temporal layers in the RTP stream (e.g. 'L1T3').
	// See webrtc-svc.
	ScalabilityMode string `json:"scalabilityMode,omitempty"`

	// Others.
	ScaleResolutionDownBy int `json:"scaleResolutionDownBy,omitempty"`
	MaxBitrate            int `json:"maxBitrate,omitempty"`
}

RtpEncodingParameters provides information relating to an encoding, which represents a media RTP stream and its associated RTX stream (if any).

type RtpEncodingRtx

type RtpEncodingRtx struct {
	// SSRC of media.
	Ssrc uint32 `json:"ssrc"`
}

RtpEncodingRtx represents the associated RTX stream for RTP stream.

type RtpHeaderExtension

type RtpHeaderExtension struct {
	// Kind is media kind. If empty string, it's valid for all kinds.
	// Default any media kind.
	Kind MediaKind `json:"kind"`

	// URI of the RTP header extension, as defined in RFC 5285.
	Uri string `json:"uri"`

	// PreferredId is the preferred numeric identifier that goes in the RTP packet.
	// Must be unique.
	PreferredId int `json:"preferredId"`

	// PreferredEncrypt if true, it is preferred that the value in the header be
	// encrypted as per RFC 6904. Default false.
	PreferredEncrypt bool `json:"preferredEncrypt,omitempty"`

	// Direction if "sendrecv", mediasoup supports sending and receiving this RTP extension.
	// "sendonly" means that mediasoup can send (but not receive) it. "recvonly"
	// means that mediasoup can receive (but not send) it.
	Direction RtpHeaderExtensionDirection `json:"direction,omitempty"`
}

RtpHeaderExtension provides information relating to supported header extensions. The list of RTP header extensions supported by mediasoup is defined in the supported_rtp_capabilities.go file.

mediasoup does not currently support encrypted RTP header extensions. The direction field is just present in mediasoup RTP capabilities (retrieved via router.RtpCapabilities() or mediasoup.GetSupportedRtpCapabilities()). It's ignored if present in endpoints' RTP capabilities.

type RtpHeaderExtensionDirection

type RtpHeaderExtensionDirection string

Direction of RTP header extension.

const (
	Direction_Sendrecv RtpHeaderExtensionDirection = "sendrecv"
	Direction_Sendonly RtpHeaderExtensionDirection = "sendonly"
	Direction_Recvonly RtpHeaderExtensionDirection = "recvonly"
	Direction_Inactive RtpHeaderExtensionDirection = "inactive"
)

type RtpHeaderExtensionParameters

type RtpHeaderExtensionParameters struct {
	// URI of the RTP header extension, as defined in RFC 5285.
	Uri string `json:"uri"`

	// Id is the numeric identifier that goes in the RTP packet. Must be unique.
	Id int `json:"id"`

	// Encrypt if true, the value in the header is encrypted as per RFC 6904. Default false.
	Encrypt bool `json:"encrypt,omitempty"`

	// Parameters is the configuration parameters for the header extension.
	Parameters *RtpCodecSpecificParameters `json:"parameters,omitempty"`
}

RtpHeaderExtensionParameters defines a RTP header extension within the RTP parameters. The list of RTP header extensions supported by mediasoup is defined in the supported_rtp_capabilities.go file.

mediasoup does not currently support encrypted RTP header extensions and no parameters are currently considered.

type RtpListener

type RtpListener struct {
	SsrcTable map[string]string `json:"ssrcTable,omitempty"`
	MidTable  map[string]string `json:"midTable,omitempty"`
	RidTable  map[string]string `json:"ridTable,omitempty"`
}

type RtpMapping

type RtpMapping struct {
	Codecs    []RtpMappingCodec    `json:"codecs,omitempty"`
	Encodings []RtpMappingEncoding `json:"encodings,omitempty"`
}

type RtpMappingCodec

type RtpMappingCodec struct {
	PayloadType       byte `json:"payloadType"`
	MappedPayloadType byte `json:"mappedPayloadType"`
}

type RtpMappingEncoding

type RtpMappingEncoding struct {
	Ssrc            uint32 `json:"ssrc,omitempty"`
	Rid             string `json:"rid,omitempty"`
	ScalabilityMode string `json:"scalabilityMode,omitempty"`
	MappedSsrc      uint32 `json:"mappedSsrc"`
}

type RtpObserver

type RtpObserver struct {
	IEventEmitter
	// contains filtered or unexported fields
}

RtpObserver is a base class inherited by ActiveSpeakerObserver and AudioLevelObserver.

  • @emits routerclose
  • @emits @close

func (*RtpObserver) AddProducer

func (o *RtpObserver) AddProducer(producerId string)

AddProducer add a Producer to the RtpObserver.

func (*RtpObserver) AppData

func (o *RtpObserver) AppData() interface{}

AppData returns app custom data.

func (*RtpObserver) Close

func (o *RtpObserver) Close()

Close the RtpObserver.

func (*RtpObserver) Closed

func (o *RtpObserver) Closed() bool

Closed returns whether the RtpObserver is closed.

func (*RtpObserver) Id

func (o *RtpObserver) Id() string

Id returns RtpObserver id.

func (*RtpObserver) Observer

func (o *RtpObserver) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits pause
  • @emits resume
  • @emits addproducer - (producer *Producer)
  • @emits removeproducer - (producer *Producer)

func (*RtpObserver) Pause

func (o *RtpObserver) Pause()

Pause the RtpObserver.

func (*RtpObserver) Paused

func (o *RtpObserver) Paused() bool

Paused returns whether the RtpObserver is paused.

func (*RtpObserver) RemoveProducer

func (o *RtpObserver) RemoveProducer(producerId string)

RemoveProducer remove a Producer from the RtpObserver.

func (*RtpObserver) Resume

func (o *RtpObserver) Resume()

Resume the RtpObserver.

type RtpParameters

type RtpParameters struct {
	// MID RTP extension value as defined in the BUNDLE specification.
	Mid string `json:"mid,omitempty"`

	// Codecs defines media and RTX codecs in use.
	Codecs []*RtpCodecParameters `json:"codecs"`

	// HeaderExtensions is the RTP header extensions in use.
	HeaderExtensions []RtpHeaderExtensionParameters `json:"headerExtensions,omitempty"`

	// Encodings is the transmitted RTP streams and their settings.
	Encodings []RtpEncodingParameters `json:"encodings"`

	// Rtcp is the parameters used for RTCP.
	Rtcp RtcpParameters `json:"rtcp"`
}

RtpParameters describe a media stream received by mediasoup from an endpoint through its corresponding mediasoup Producer. These parameters may include a mid value that the mediasoup transport will use to match received RTP packets based on their MID RTP extension value.

mediasoup allows RTP send parameters with a single encoding and with multiple encodings (simulcast). In the latter case, each entry in the encodings array must include a ssrc field or a rid field (the RID RTP extension value). Check the Simulcast and SVC sections for more information.

The RTP receive parameters describe a media stream as sent by mediasoup to an endpoint through its corresponding mediasoup Consumer. The mid value is unset (mediasoup does not include the MID RTP extension into RTP packets being sent to endpoints).

There is a single entry in the encodings array (even if the corresponding producer uses simulcast). The consumer sends a single and continuous RTP stream to the endpoint and spatial/temporal layer selection is possible via consumer.setPreferredLayers().

As an exception, previous bullet is not true when consuming a stream over a PipeTransport, in which all RTP streams from the associated producer are forwarded verbatim through the consumer.

The RTP receive parameters will always have their ssrc values randomly generated for all of its encodings (and optional rtx { ssrc XXXX } if the endpoint supports RTX), regardless of the original RTP send parameters in the associated producer. This applies even if the producer's encodings have rid set.

type RtpStream

type RtpStream struct {
	Params    RtpStreamParams `json:"params,omitempty"`
	Score     uint8           `json:"score,omitempty"`
	RtxStream *RtpStream      `json:"rtxStream,omitempty"`
}

type RtpStreamParams

type RtpStreamParams struct {
	EncodingIdx    int    `json:"encodingIdx,omitempty"`
	Ssrc           uint32 `json:"ssrc,omitempty"`
	PayloadType    uint8  `json:"payloadType,omitempty"`
	MimeType       string `json:"mimeType,omitempty"`
	ClockRate      uint32 `json:"clockRate,omitempty"`
	Rid            string `json:"rid,omitempty"`
	RRid           string `json:"rrid,omitempty"`
	Cname          string `json:"cname,omitempty"`
	RtxSsrc        uint32 `json:"rtxSsrc,omitempty"`
	RtxPayloadType uint8  `json:"rtxPayloadType,omitempty"`
	UseNack        bool   `json:"useNack,omitempty"`
	UsePli         bool   `json:"usePli,omitempty"`
	UseFir         bool   `json:"useFir,omitempty"`
	UseInBandFec   bool   `json:"useInBandFec,omitempty"`
	UseDtx         bool   `json:"useDtx,omitempty"`
	SpatialLayers  uint8  `json:"spatialLayers,omitempty"`
	TemporalLayers uint8  `json:"temporalLayers,omitempty"`
}

type ScalabilityMode

type ScalabilityMode struct {
	SpatialLayers  uint8 `json:"spatialLayers"`
	TemporalLayers uint8 `json:"temporalLayers"`
	Ksvc           bool  `json:"ksvc"`
}

func ParseScalabilityMode

func ParseScalabilityMode(scalabilityMode string) ScalabilityMode

type SctpCapabilities

type SctpCapabilities struct {
	NumStreams NumSctpStreams `json:"numStreams"`
}

type SctpListener

type SctpListener struct {
	StreamIdTable map[string]string `json:"streamIdTable,omitempty"`
}

type SctpParameters

type SctpParameters struct {
	// Port must always equal 5000.
	Port uint16 `json:"port"`

	// OS defines initially requested int of outgoing SCTP streams.
	OS uint16 `json:"os"`

	// MIS defines maximum int of incoming SCTP streams.
	MIS uint16 `json:"mis"`

	// MaxMessageSize defines maximum allowed size for SCTP messages.
	MaxMessageSize uint32 `json:"maxMessageSize"`

	// Set by worker.
	IsDataChannel      bool `json:"isDataChannel,omitempty"`
	SctpBufferedAmount int  `json:"sctpBufferedAmount,omitempty"`
	SendBufferSize     int  `json:"sendBufferSize,omitempty"`
}

type SctpState

type SctpState string

type SctpStreamParameters

type SctpStreamParameters struct {
	// StreamId defines SCTP stream id.
	StreamId uint16 `json:"streamId"`

	// Ordered defines whether data messages must be received in order. If true the messages will
	// be sent reliably. Default true.
	Ordered *bool `json:"ordered,omitempty"`

	// MaxPacketLifeTime defines when ordered is false indicates the time (in milliseconds) after
	// which a SCTP packet will stop being retransmitted.
	MaxPacketLifeTime uint16 `json:"maxPacketLifeTime,omitempty"`

	// MaxRetransmits defines when ordered is false indicates the maximum number of times a packet
	// will be retransmitted.
	MaxRetransmits uint16 `json:"maxRetransmits,omitempty"`
}

SctpStreamParameters describe the reliability of a certain SCTP stream. If ordered is true then maxPacketLifeTime and maxRetransmits must be false. If ordered if false, only one of maxPacketLifeTime or maxRetransmits can be true.

type SimulcastConsumerDump

type SimulcastConsumerDump struct {
	PreferredSpatialLayer  int16 `json:"preferredSpatialLayer,omitempty"`
	TargetSpatialLayer     int16 `json:"targetSpatialLayer,omitempty"`
	CurrentSpatialLayer    int16 `json:"currentSpatialLayer,omitempty"`
	PreferredTemporalLayer int16 `json:"preferredTemporalLayer,omitempty"`
	TargetTemporalLayer    int16 `json:"targetTemporalLayer,omitempty"`
	CurrentTemporalLayer   int16 `json:"currentTemporalLayer,omitempty"`
}

func (SimulcastConsumerDump) String added in v1.10.0

func (d SimulcastConsumerDump) String() string

type SrtpCryptoSuite

type SrtpCryptoSuite string

SrtpCryptoSuite defines SRTP crypto suite.

const (
	AES_CM_128_HMAC_SHA1_80 SrtpCryptoSuite = "AES_CM_128_HMAC_SHA1_80"
	AES_CM_128_HMAC_SHA1_32 SrtpCryptoSuite = "AES_CM_128_HMAC_SHA1_32"
)

type SrtpParameters

type SrtpParameters struct {
	//Encryption and authentication transforms to be used.
	CryptoSuite SrtpCryptoSuite `json:"cryptoSuite"`

	// SRTP keying material (master key and salt) in Base64.
	KeyBase64 string `json:"keyBase64"`
}

SrtpParameters defines SRTP parameters.

type Transport

type Transport struct {
	IEventEmitter
	// contains filtered or unexported fields
}

Transport is a base class inherited by PlainTransport, PipeTransport, DirectTransport and WebRtcTransport.

  • @emits routerclose
  • @emits @close
  • @emits @newproducer - (producer *Producer)
  • @emits @producerclose - (producer *Producer)
  • @emits @newdataproducer - (dataProducer *DataProducer)
  • @emits @dataproducerclose - (dataProducer *DataProducer)

func (*Transport) AppData

func (transport *Transport) AppData() interface{}

AppData returns app custom data.

func (*Transport) Close

func (transport *Transport) Close()

Close the Transport.

func (*Transport) Closed

func (transport *Transport) Closed() bool

Closed returns Whether the Transport is closed.

func (*Transport) Connect

func (transport *Transport) Connect(TransportConnectOptions) error

Connect provide the Transport remote parameters.

func (*Transport) Consume

func (transport *Transport) Consume(options ConsumerOptions) (consumer *Consumer, err error)

Consume creates a Consumer.

func (*Transport) ConsumeData

func (transport *Transport) ConsumeData(options DataConsumerOptions) (dataConsumer *DataConsumer, err error)

ConsumeData creates a DataConsumer.

func (*Transport) Dump

func (transport *Transport) Dump() (data *TransportDump, err error)

Dump Transport.

func (*Transport) EnableTraceEvent

func (transport *Transport) EnableTraceEvent(types ...TransportTraceEventType) error

EnableTraceEvent enables 'trace' events.

func (*Transport) GetStats

func (transport *Transport) GetStats() (stat []*TransportStat, err error)

GetStats returns the Transport stats.

func (*Transport) Id

func (transport *Transport) Id() string

Id returns Transport id

func (*Transport) Observer

func (transport *Transport) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits newproducer - (producer *Producer)
  • @emits newconsumer - (producer *Producer)
  • @emits newdataproducer - (dataProducer *DataProducer)
  • @emits newdataconsumer - (dataProducer *DataProducer)

func (*Transport) OnClose added in v1.10.4

func (transport *Transport) OnClose(handler func())

OnClose set handler on "close" event

func (*Transport) OnTrace added in v1.10.4

func (transport *Transport) OnTrace(handler func(trace *TransportTraceEventData))

OnTrace set handler on "trace" event

func (*Transport) Produce

func (transport *Transport) Produce(options ProducerOptions) (producer *Producer, err error)

Produce creates a Producer.

func (*Transport) ProduceData

func (transport *Transport) ProduceData(options DataProducerOptions) (dataProducer *DataProducer, err error)

ProduceData creates a DataProducer.

func (*Transport) SetMaxIncomingBitrate

func (transport *Transport) SetMaxIncomingBitrate(bitrate int) error

SetMaxIncomingBitrate set maximum incoming bitrate for receiving media.

type TransportConnectOptions

type TransportConnectOptions struct {
	// pipe and plain transport
	Ip             string          `json:"ip,omitempty"`
	Port           uint16          `json:"port,omitempty"`
	SrtpParameters *SrtpParameters `json:"srtpParameters,omitempty"`

	// plain transport
	RtcpPort uint16 `json:"rtcpPort,omitempty"`

	// webrtc transport
	DtlsParameters *DtlsParameters `json:"dtlsParameters,omitempty"`
}

type TransportDump

type TransportDump struct {
	Id                      string                   `json:"id,omitempty"`
	Direct                  bool                     `json:"direct,omitempty"`
	ProducerIds             []string                 `json:"producerIds,omitempty"`
	ConsumerIds             []string                 `json:"consumerIds,omitempty"`
	MapSsrcConsumerId       map[string]string        `json:"mapSsrcConsumerId,omitempty"`
	MapRtxSsrcConsumerId    map[string]string        `json:"mapRtxSsrcConsumerId,omitempty"`
	DataProducerIds         []string                 `json:"dataProducerIds,omitempty"`
	DataConsumerIds         []string                 `json:"dataConsumerIds,omitempty"`
	RecvRtpHeaderExtensions *RecvRtpHeaderExtensions `json:"recvRtpHeaderExtensions,omitempty"`
	RtpListener             *RtpListener             `json:"rtpListener,omitempty"`
	SctpParameters          SctpParameters           `json:"SctpParameters,omitempty"`
	SctpState               SctpState                `json:"sctpState,omitempty"`
	SctpListener            *SctpListener            `json:"sctpListener,omitempty"`
	TraceEventTypes         string                   `json:"traceEventTypes,omitempty"`

	// plain transport
	*PlainTransportDump

	// webrtc transport
	*WebRtcTransportDump
}

func (TransportDump) String added in v1.10.0

func (d TransportDump) String() string

type TransportListenIp

type TransportListenIp struct {
	// Listening IPv4 or IPv6.
	Ip string `json:"ip,omitempty"`

	// Announced IPv4 or IPv6 (useful when running mediasoup behind NAT with private IP).
	AnnouncedIp string `json:"announcedIp,omitempty"`
}

type TransportProtocol

type TransportProtocol string

Transport protocol.

const (
	TransportProtocol_Udp TransportProtocol = "udp"
	TransportProtocol_Tcp TransportProtocol = "tcp"
)

type TransportStat

type TransportStat struct {
	// Common to all Transports.
	Type                     string    `json:"type,omitempty"`
	TransportId              string    `json:"transportId,omitempty"`
	Timestamp                int64     `json:"timestamp,omitempty"`
	SctpState                SctpState `json:"sctpState,omitempty"`
	BytesReceived            int64     `json:"bytesReceived,omitempty"`
	RecvBitrate              int64     `json:"recvBitrate,omitempty"`
	BytesSent                int64     `json:"bytesSent,omitempty"`
	SendBitrate              int64     `json:"sendBitrate,omitempty"`
	RtpBytesReceived         int64     `json:"rtpBytesReceived,omitempty"`
	RtpRecvBitrate           int64     `json:"rtpRecvBitrate,omitempty"`
	RtpBytesSent             int64     `json:"rtpBytesSent,omitempty"`
	RtpSendBitrate           int64     `json:"rtpSendBitrate,omitempty"`
	RtxBytesReceived         int64     `json:"rtxBytesReceived,omitempty"`
	RtxRecvBitrate           int64     `json:"rtxRecvBitrate,omitempty"`
	RtxBytesSent             int64     `json:"rtxBytesSent,omitempty"`
	RtxSendBitrate           int64     `json:"rtxSendBitrate,omitempty"`
	ProbationBytesSent       int64     `json:"probationBytesSent,omitempty"`
	ProbationSendBitrate     int64     `json:"probationSendBitrate,omitempty"`
	AvailableOutgoingBitrate int64     `json:"availableOutgoingBitrate,omitempty"`
	AvailableIncomingBitrate int64     `json:"availableIncomingBitrate,omitempty"`
	MaxIncomingBitrate       int64     `json:"maxIncomingBitrate,omitempty"`
	RtpPacketLossReceived    float64   `json:"rtpPacketLossReceived,omitempty"`
	RtpPacketLossSent        float64   `json:"rtpPacketLossSent,omitempty"`

	*WebRtcTransportSpecificStat
	*PlainTransportSpecificStat // share tuple with pipe transport stat
}

type TransportTraceEventData

type TransportTraceEventData struct {
	// Trace type.
	Type TransportTraceEventType `json:"type,omitempty"`

	// Event timestamp.
	Timestamp int64 `json:"timestamp,omitempty"`

	// Event direction.
	Direction string `json:"direction,omitempty"`

	// Per type information.
	Info interface{} `json:"info,omitempty"`
}

type TransportTraceEventType

type TransportTraceEventType string
const (
	TransportTraceEventType_Probation TransportTraceEventType = "probation"
	TransportTraceEventType_Bwe       TransportTraceEventType = "bwe"
)

type TransportTuple

type TransportTuple struct {
	LocalIp    string `json:"localIp,omitempty"`
	LocalPort  uint16 `json:"localPort,omitempty"`
	RemoteIp   string `json:"remoteIp,omitempty"`
	RemotePort uint16 `json:"remotePort,omitempty"`
	Protocol   string `json:"protocol,omitempty"`
}

type TransportType

type TransportType string
const (
	TransportType_Direct TransportType = "DirectTransport"
	TransportType_Plain  TransportType = "PlainTransport"
	TransportType_Pipe   TransportType = "PipeTransport"
	TransportType_Webrtc TransportType = "WebrtcTransport"
)

type TupleHash added in v1.10.0

type TupleHash struct {
	TupleHash         uint64 `json:"tupleHash,omitempty"`
	WebRtcTransportId string `json:"webRtcTransportId,omitempty"`
}

type TypeError

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

func (TypeError) Error

func (e TypeError) Error() string

type UnsupportedError

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

UnsupportedError indicating not support for something.

func (UnsupportedError) Error

func (e UnsupportedError) Error() string

type WebRtcServer added in v1.10.0

type WebRtcServer struct {
	IEventEmitter
	// contains filtered or unexported fields
}

WebRtcServer brings the ability to listen on a single UDP/TCP port to WebRtcTransports. Instead of passing listenIps to router.CreateWebRtcTransport() pass webRtcServer with an instance of a WebRtcServer so the new WebRTC transport will not listen on its own IP:port(s) but will have its network traffic handled by the WebRTC server instead.

A WebRTC server exists within the context of a Worker, meaning that if your app launches N workers it also needs to create N WebRTC servers listening on different ports (to not collide).

The WebRTC transport implementation of mediasoup is ICE Lite, meaning that it does not initiate ICE connections but expects ICE Binding Requests from endpoints.

  • @emits @close
  • @emits workerclose

func NewWebRtcServer added in v1.10.0

func NewWebRtcServer(params webrtcServerParams) *WebRtcServer

func (*WebRtcServer) AppData added in v1.10.0

func (s *WebRtcServer) AppData() interface{}

AppData returns App custom data.

func (*WebRtcServer) Close added in v1.10.0

func (s *WebRtcServer) Close()

Close the webrtc server.

func (*WebRtcServer) Closed added in v1.10.0

func (s *WebRtcServer) Closed() bool

Closed returns whether the router is closed or not.

func (*WebRtcServer) Dump added in v1.10.0

func (s *WebRtcServer) Dump() (data WebRtcServerDump, err error)

Dump returns WebRtcServer information.

func (*WebRtcServer) Id added in v1.10.0

func (s *WebRtcServer) Id() string

Id returns router id.

func (*WebRtcServer) Observer added in v1.10.0

func (s *WebRtcServer) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits webrtctransporthandled - (transport *WebRtcTransport)
  • @emits webrtctransportunhandled - (transport *WebRtcTransport)

type WebRtcServerDump added in v1.10.0

type WebRtcServerDump struct {
	Id                        string                     `json:"id,omitempty"`
	UdpSockets                []NetAddr                  `json:"udpSockets,omitempty"`
	TcpServers                []NetAddr                  `json:"tcpServers,omitempty"`
	WebRtcTransportIds        []string                   `json:"webRtcTransportIds,omitempty"`
	LocalIceUsernameFragments []LocalIceUsernameFragment `json:"localIceUsernameFragments,omitempty"`
	TupleHashes               []TupleHash                `json:"tupleHashes,omitempty"`
}

func (WebRtcServerDump) String added in v1.10.0

func (d WebRtcServerDump) String() string

type WebRtcServerListenInfo added in v1.10.0

type WebRtcServerListenInfo struct {
	// Network protocol.
	Protocol TransportProtocol `json:"protocol,omitempty"`

	// Listening IPv4 or IPv6.
	Ip string `json:"ip,omitempty"`

	// Announced IPv4 or IPv6 (useful when running mediasoup behind NAT with private IP).
	AnnouncedIp string `json:"announcedIp,omitempty"`

	// Listening port.
	Port uint16 `json:"port,omitempty"`
}

type WebRtcServerOptions added in v1.10.0

type WebRtcServerOptions struct {
	// Listen infos.
	ListenInfos []WebRtcServerListenInfo

	// appData
	AppData interface{}
}

type WebRtcTransport

type WebRtcTransport struct {
	ITransport
	// contains filtered or unexported fields
}

WebRtcTransport represents a network path negotiated by both, a WebRTC endpoint and mediasoup, via ICE and DTLS procedures. A WebRTC transport may be used to receive media, to send media or to both receive and send. There is no limitation in mediasoup. However, due to their design, mediasoup-client and libmediasoupclient require separate WebRTC transports for sending and receiving.

The WebRTC transport implementation of mediasoup is ICE Lite, meaning that it does not initiate ICE connections but expects ICE Binding Requests from endpoints.

  • @emits icestatechange - (iceState IceState)
  • @emits iceselectedtuplechange - (tuple *TransportTuple)
  • @emits dtlsstatechange - (dtlsState DtlsState)
  • @emits sctpstatechange - (sctpState SctpState)
  • @emits trace - (trace *TransportTraceEventData)

func (*WebRtcTransport) Close

func (t *WebRtcTransport) Close()

Close the WebRtcTransport.

func (*WebRtcTransport) Connect

func (t *WebRtcTransport) Connect(options TransportConnectOptions) (err error)

Connect provides the WebRtcTransport remote parameters.

func (WebRtcTransport) DtlsParameters

func (t WebRtcTransport) DtlsParameters() DtlsParameters

DtlsParameters returns DTLS parameters.

func (WebRtcTransport) DtlsRemoteCert

func (t WebRtcTransport) DtlsRemoteCert() string

DtlsRemoteCert returns remote certificate in PEM format

func (WebRtcTransport) DtlsState

func (t WebRtcTransport) DtlsState() DtlsState

DtlsState returns DTLS state.

func (WebRtcTransport) IceCandidates

func (t WebRtcTransport) IceCandidates() []IceCandidate

IceCandidates returns IceCandidates ICE candidates.

func (WebRtcTransport) IceParameters

func (t WebRtcTransport) IceParameters() IceParameters

IceParameters returns ICE parameters.

func (WebRtcTransport) IceRole

func (t WebRtcTransport) IceRole() string

IceRole returns ICE role.

func (WebRtcTransport) IceSelectedTuple

func (t WebRtcTransport) IceSelectedTuple() *TransportTuple

IceSelectedTuple returns ICE selected tuple.

func (WebRtcTransport) IceState

func (t WebRtcTransport) IceState() IceState

IceState returns ICE state.

func (*WebRtcTransport) Observer

func (t *WebRtcTransport) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits newproducer - (producer *Producer)
  • @emits newconsumer - (consumer *Consumer)
  • @emits newdataproducer - (dataProducer *DataProducer)
  • @emits newdataconsumer - (dataConsumer *DataConsumer)
  • @emits icestatechange - (iceState IceState)
  • @emits iceselectedtuplechange - (tuple *TransportTuple)
  • @emits dtlsstatechange - (dtlsState DtlsState)
  • @emits sctpstatechange - (sctpState SctpState)
  • @emits trace - (trace *TransportTraceEventData)

func (*WebRtcTransport) OnDtlsStateChange added in v1.10.4

func (t *WebRtcTransport) OnDtlsStateChange(handler func(DtlsState))

OnDtlsStateChange set handler on "dtlsstatechange" event

func (*WebRtcTransport) OnIceSelectedTupleChange added in v1.10.4

func (t *WebRtcTransport) OnIceSelectedTupleChange(handler func(*TransportTuple))

OnIceSelectedTupleChange set handler on "iceselectedtuplechange" event

func (*WebRtcTransport) OnIceStateChange added in v1.10.4

func (t *WebRtcTransport) OnIceStateChange(handler func(IceState))

OnIceStateChange set handler on "icestatechange" event

func (*WebRtcTransport) OnSctpStateChange added in v1.10.4

func (t *WebRtcTransport) OnSctpStateChange(handler func(SctpState))

OnSctpStateChange set handler on "sctpstatechange" event

func (*WebRtcTransport) RestartIce

func (t *WebRtcTransport) RestartIce() (iceParameters IceParameters, err error)

RestartIce restarts ICE.

func (WebRtcTransport) SctpParameters

func (t WebRtcTransport) SctpParameters() SctpParameters

SctpParameters returns SCTP parameters.

func (WebRtcTransport) SctpState

func (t WebRtcTransport) SctpState() SctpState

SctpState returns SRTP parameters.

type WebRtcTransportDump

type WebRtcTransportDump struct {
	IceRole          string          `json:"iceRole,omitempty"`
	IceParameters    IceParameters   `json:"iceParameters,omitempty"`
	IceCandidates    []IceCandidate  `json:"iceCandidates,omitempty"`
	IceState         IceState        `json:"iceState,omitempty"`
	IceSelectedTuple *TransportTuple `json:"iceSelectedTuple,omitempty"`
	DtlsParameters   DtlsParameters  `json:"dtlsParameters,omitempty"`
	DtlsState        DtlsState       `json:"dtlsState,omitempty"`
	DtlsRemoteCert   string          `json:"dtlsRemoteCert,omitempty"`
}

func (WebRtcTransportDump) String added in v1.10.0

func (d WebRtcTransportDump) String() string

type WebRtcTransportOptions

type WebRtcTransportOptions struct {
	// WebRtcServer is an instance of WebRtcServer. Mandatory unless listenIps is given.
	WebRtcServer *WebRtcServer

	// ListenIps are listening IP address or addresses in order of preference (first one
	// is the preferred one). Mandatory unless webRtcServer is given.
	ListenIps []TransportListenIp `json:"listenIps,omitempty"`

	// EnableUdp enables listening in UDP. Default true.
	EnableUdp *bool `json:"enableUdp,omitempty"`

	// EnableTcp enables listening in TCP. Default false.
	EnableTcp bool `json:"enableTcp,omitempty"`

	// PreferUdp prefers UDP. Default false.
	PreferUdp bool `json:"preferUdp,omitempty"`

	// PreferUdp prefers TCP. Default false.
	PreferTcp bool `json:"preferTcp,omitempty"`

	// InitialAvailableOutgoingBitrate sets the initial available outgoing bitrate (in bps). Default 600000.
	InitialAvailableOutgoingBitrate int `json:"initialAvailableOutgoingBitrate,omitempty"`

	// EnableSctp creates a SCTP association. Default false.
	EnableSctp bool `json:"enableSctp,omitempty"`

	// NumSctpStreams set up SCTP streams.
	NumSctpStreams NumSctpStreams `json:"numSctpStreams,omitempty"`

	// MaxSctpMessageSize defines the maximum allowed size for SCTP messages sent by DataProducers. Default 262144.
	MaxSctpMessageSize int `json:"maxSctpMessageSize,omitempty"`

	// SctpSendBufferSize defines the maximum SCTP send buffer used by DataConsumers. Default 262144.
	SctpSendBufferSize int `json:"sctpSendBufferSize,omitempty"`

	// AppData is the custom application data.
	AppData interface{} `json:"appData,omitempty"`
}

WebRtcTransportOptions defines the options to create webrtc t.

type WebRtcTransportSpecificStat

type WebRtcTransportSpecificStat struct {
	IceRole          string          `json:"iceRole"`
	IceState         IceState        `json:"iceState"`
	DtlsState        DtlsRole        `json:"dtlsState"`
	IceSelectedTuple *TransportTuple `json:"iceSelectedTuple,omitempty"`
}

type Worker

type Worker struct {
	IEventEmitter
	// contains filtered or unexported fields
}

Worker represents a mediasoup C++ subprocess that runs in a single CPU core and handles Router instances.

  • @emits died - (err error)

func NewWorker

func NewWorker(options ...Option) (worker *Worker, err error)

func (*Worker) AppData

func (w *Worker) AppData() interface{}

AppData returns the custom app data.

func (*Worker) Close

func (w *Worker) Close()

Close terminal the worker process and all allocated resouces

func (*Worker) Closed

func (w *Worker) Closed() bool

Closed returns if the worker process is closed

func (*Worker) CreateRouter

func (w *Worker) CreateRouter(options RouterOptions) (router *Router, err error)

CreateRouter creates a router.

func (*Worker) CreateWebRtcServer added in v1.10.0

func (w *Worker) CreateWebRtcServer(options WebRtcServerOptions) (webRtcServer *WebRtcServer, err error)

CreateWebRtcServer creates a WebRtcServer.

func (*Worker) Died added in v1.9.5

func (w *Worker) Died() bool

Died returns if the worker process died

func (*Worker) Dump

func (w *Worker) Dump() (dump WorkerDump, err error)

Dump returns the resources allocated by the worker.

func (*Worker) GetResourceUsage

func (w *Worker) GetResourceUsage() (usage WorkerResourceUsage, err error)

GetResourceUsage returns the worker process resource usage.

func (*Worker) Observer

func (w *Worker) Observer() IEventEmitter

Deprecated

  • @emits close
  • @emits newwebrtcserver - (webRtcServer *WebRtcServer)
  • @emits newrouter - (router *Router)

func (*Worker) OnNewRouter added in v1.10.5

func (w *Worker) OnNewRouter(handler func(router *Router))

OnNewRouter set handler on "newrouter" event

func (*Worker) OnNewWebRtcServer added in v1.10.5

func (w *Worker) OnNewWebRtcServer(handler func(webrtcServer *WebRtcServer))

OnNewWebRtcServer set handler on "newwebrtcserver" event

func (*Worker) Pid

func (w *Worker) Pid() int

Pid returns the worker process identifier.

func (*Worker) UpdateSettings

func (w *Worker) UpdateSettings(settings WorkerUpdatableSettings) error

UpdateSettings updates settings.

func (*Worker) Wait added in v1.10.1

func (w *Worker) Wait() error

Wait blocks until the worker process is stopped

type WorkerDump

type WorkerDump struct {
	Pid             int      `json:"pid,omitempty"`
	RouterIds       []string `json:"routerIds,omitempty"`
	WebRtcServerIds []string `json:"webRtcServerIds,omitempty"`
}

func (WorkerDump) String added in v1.10.0

func (d WorkerDump) String() string

type WorkerLogLevel

type WorkerLogLevel string

WorkerLogLevel controls log level in mediasoup-worker

const (
	WorkerLogLevel_Debug WorkerLogLevel = "debug"
	WorkerLogLevel_Warn  WorkerLogLevel = "warn"
	WorkerLogLevel_Error WorkerLogLevel = "error"
	WorkerLogLevel_None  WorkerLogLevel = "none"
)

type WorkerLogTag

type WorkerLogTag string

WorkerLogTag controls which tag of logs should display in mediasoup-worker

const (
	WorkerLogTag_INFO      WorkerLogTag = "info"
	WorkerLogTag_ICE       WorkerLogTag = "ice"
	WorkerLogTag_DTLS      WorkerLogTag = "dtls"
	WorkerLogTag_RTP       WorkerLogTag = "rtp"
	WorkerLogTag_SRTP      WorkerLogTag = "srtp"
	WorkerLogTag_RTCP      WorkerLogTag = "rtcp"
	WorkerLogTag_RTX       WorkerLogTag = "rtx"
	WorkerLogTag_BWE       WorkerLogTag = "bwe"
	WorkerLogTag_Score     WorkerLogTag = "score"
	WorkerLogTag_Simulcast WorkerLogTag = "simulcast"
	WorkerLogTag_SVC       WorkerLogTag = "svc"
	WorkerLogTag_SCTP      WorkerLogTag = "sctp"
	WorkerLogTag_Message   WorkerLogTag = "message"
)

type WorkerResourceUsage

type WorkerResourceUsage struct {
	// User CPU time used (in ms).
	Utime int64 `json:"ru_utime"`

	// System CPU time used (in ms).
	Stime int64 `json:"ru_stime"`

	// Maximum resident set size.
	Maxrss int64 `json:"ru_maxrss"`

	// Integral shared memory size.
	Ixrss int64 `json:"ru_ixrss"`

	// Integral unshared data size.
	Idrss int64 `json:"ru_idrss"`

	// Integral unshared stack size.
	Isrss int64 `json:"ru_isrss"`

	// Page reclaims (soft page faults).
	Minflt int64 `json:"ru_minflt"`

	// Page faults (hard page faults).
	Majflt int64 `json:"ru_majflt"`

	// Swaps.
	Nswap int64 `json:"ru_nswap"`

	// Block input operations.
	Inblock int64 `json:"ru_inblock"`

	// Block output operations.
	Oublock int64 `json:"ru_oublock"`

	// IPC messages sent.
	Msgsnd int64 `json:"ru_msgsnd"`

	// IPC messages received.
	Msgrcv int64 `json:"ru_msgrcv"`

	// Signals received.
	Nsignals int64 `json:"ru_nsignals"`

	// Voluntary context switches.
	Nvcsw int64 `json:"ru_nvcsw"`

	// Involuntary context switches.
	Nivcsw int64 `json:"ru_nivcsw"`
}

WorkerResourceUsage is an object with the fields of the uv_rusage_t struct.

- http//docs.libuv.org/en/v1.x/misc.html#c.uv_rusage_t - https//linux.die.net/man/2/getrusage

type WorkerSettings

type WorkerSettings struct {
	// WorkerBin is the absolute path of worker binary. The default value is read
	// in order from the following values: environment variable MEDIASOUP_WORKER_BIN,
	// /usr/local/lib/node_modules/mediasoup/worker/out/Release/mediasoup-worker.
	// To facilitate testing, it allows the use of the following pattern:
	// valgrind --tool=memcheck --leak-check=full ./mediasoup-worker
	WorkerBin string

	// WorkerVersion is the version of mediasoup-worker. In order to communicate with
	// mediasoup-worker, you must set this value correctly. If it is empty, mediasoup-go
	// will try to detect the worker version.
	WorkerVersion string

	// LogLevel is logging level for logs generated by the media worker subprocesses
	// (check the Debugging documentation). Valid values are 'debug', 'warn', 'error' and
	// 'none'. Default 'error'.
	LogLevel WorkerLogLevel `json:"logLevel,omitempty"`

	// LogTags are log tags for debugging. Check the meaning of each available tag in the
	// Debugging documentation.
	LogTags []WorkerLogTag `json:"logTags,omitempty"`

	// RtcMinPort is the minimum RTC port for ICE, DTLS, RTP, etc. Default 10000.
	RtcMinPort uint16 `json:"rtcMinPort,omitempty"`

	// RtcMaxPort is maximum RTC port for ICE, DTLS, RTP, etc. Default 59999.
	RtcMaxPort uint16 `json:"rtcMaxPort,omitempty"`

	// DtlsCertificateFile is the path to the DTLS public certificate file in PEM format.
	// If unset, a certificate is dynamically created.
	DtlsCertificateFile string `json:"dtlsCertificateFile,omitempty"`

	// DtlsPrivateKeyFile is the path to the DTLS certificate private key file in PEM format.
	// If unset, a certificate is dynamically created.
	DtlsPrivateKeyFile string `json:"dtlsPrivateKeyFile,omitempty"`

	// AppData is custom application data.
	AppData interface{} `json:"appData,omitempty"`

	// CustomOptions will be passed to mediasoup-worker command line such as
	// --key1=value1 --key2=value2.
	CustomOptions map[string]interface{}
}

func (WorkerSettings) Args

func (w WorkerSettings) Args() []string

args returns the arguments passed to mediasoup-worker command line.

type WorkerUpdatableSettings added in v1.10.4

type WorkerUpdatableSettings struct {
	// LogLevel is logging level for logs generated by the media worker subprocesses (check
	// the Debugging documentation). Valid values are 'debug', 'warn', 'error' and
	// 'none'. Default 'error'.
	LogLevel WorkerLogLevel `json:"logLevel,omitempty"`

	// LogTags are log tags for debugging. Check the meaning of each available tag in the
	// Debugging documentation.
	LogTags []WorkerLogTag `json:"logTags,omitempty"`
}

WorkerUpdatableSettings is an object with fields which can be updated during mediasoup-worker is running.

Directories

Path Synopsis
examples
app

Jump to

Keyboard shortcuts

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