rtc

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: BSD-2-Clause Imports: 33 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package rtc implements a WebRTC transport for jargo. It terminates a peer connection, decodes received Opus audio into PCM frames, and encodes outgoing PCM frames into Opus sent over an RTP track.

Video goes both ways too. The client's camera and screen share are decoded (VP8 through libvpx, H.264 through OpenH264) into RGB images, and the images the bot shows are encoded to VP8 on its own video track. The codec libraries are loaded at run time, the first time video needs them; VideoCodecConfig locates them.

Pion is the WebRTC implementation it is built on, which is why it imports github.com/pion/webrtc. That is an implementation detail rather than part of the interface this package offers.

Signaling runs over HTTP and is driven by the application. The simplest form is a single SDP offer/answer exchange through Connection.Answer. RequestHandler adds the rest of the protocol a browser client speaks: peer connections keyed by pc_id, renegotiation and restarts, and remote ICE candidates trickled in after the offer.

Index

Examples

Constants

View Source
const (
	AudioTransceiverIndex       = 0
	VideoTransceiverIndex       = 1
	ScreenVideoTransceiverIndex = 2
)

The positions of the client's transceivers, in the order the client offers them: its microphone, its camera, then its screen share.

View Source
const (
	// FormatYUV420P is planar YUV 4:2:0: a luma plane, then two chroma planes
	// at half the width and height, rounded up.
	FormatYUV420P = "yuv420p"
)

Pixel formats of a VideoFrame.

Variables

View Source
var ErrNoAnswer = errors.New("rtc: connection produced no SDP answer")

ErrNoAnswer is returned when a connection has no SDP answer to give.

View Source
var ErrTrackEnded = errors.New("rtc: track ended")

ErrTrackEnded is returned by Track.Recv once the track has ended: the client stopped sending it, or the connection stopped it.

Functions

func SDPMunging added in v0.4.0

func SDPMunging(sdp, host string) string

SDPMunging rewrites an answer for clients with a minimal WebRTC stack, such as an ESP32: it drops the fingerprint algorithms they cannot handle and, when host is set, every ICE candidate except the direct ones for that host.

Types

type Answer added in v0.4.0

type Answer struct {
	SDP  string `json:"sdp"`
	Type string `json:"type"`
	PCID string `json:"pc_id"`
}

Answer is the SDP answer to an offer, with the identifier of the peer connection that produced it. A client sends the identifier back with a renegotiation offer and with the ICE candidates it trickles in.

type Connection

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

Connection wraps a Pion peer connection for one client session. It owns the outgoing audio track and exposes the incoming one, and the client's camera and screen share as Tracks. It is safe for concurrent use.

The peer connection behind it can be replaced: a renegotiation that asks for a restart closes the current one and answers on a new one, which also takes a new pc_id. The Connection itself, and the session built on it, carry on.

func NewConnection

func NewConnection(opts ...Option) (*Connection, error)

NewConnection creates a peer connection with an outgoing Opus audio track. By default a public STUN server is configured so it works across NATs; override with WithICEServers.

func (*Connection) AddICECandidate added in v0.4.0

func (c *Connection) AddICECandidate(candidate webrtc.ICECandidateInit) error

AddICECandidate adds a remote ICE candidate the client trickled in after its offer. A candidate with an empty candidate string is the end-of-candidates marker for its media line.

func (*Connection) Answer

Answer completes the signaling handshake in one call: it applies the remote offer and returns an answer carrying every local candidate.

func (*Connection) AskToRenegotiate added in v0.4.0

func (c *Connection) AskToRenegotiate()

AskToRenegotiate asks the client to send a new offer. A request made while a renegotiation is still settling is dropped.

func (*Connection) Close

func (c *Connection) Close() error

Close tears down the peer connection.

func (*Connection) Connect added in v0.4.0

func (c *Connection) Connect()

Connect tells the connection the pipeline is ready for it. The connected event waits for this, and application messages received before it are held and delivered now.

func (*Connection) Disconnect added in v0.4.0

func (c *Connection) Disconnect() error

Disconnect tells the client the bot is leaving, then closes the connection.

func (*Connection) Done

func (c *Connection) Done() <-chan struct{}

Done returns a channel closed when the connection closes for good: it was closed, it failed, or it never finished connecting. A peer connection that is only disconnected may still recover, so it does not close it.

func (*Connection) GetAnswer added in v0.4.0

func (c *Connection) GetAnswer() *Answer

GetAnswer returns the answer to the last offer applied, or nil when there is none yet.

func (*Connection) Initialize added in v0.4.0

func (c *Connection) Initialize(offer webrtc.SessionDescription) error

Initialize applies the client's offer and prepares the answer, which GetAnswer then returns.

func (*Connection) IsConnected added in v0.4.0

func (c *Connection) IsConnected() bool

IsConnected reports whether the connection is up and the pipeline has been connected to it. Once the client has sent a keep-alive ping, it also requires the last one to be recent.

func (*Connection) OnClosed added in v0.4.0

func (c *Connection) OnClosed(h func())

OnClosed registers a handler for the connection closing for good.

func (*Connection) OnConnected added in v0.4.0

func (c *Connection) OnConnected(h func())

OnConnected registers a handler for the peer connection being established, raised once the pipeline has connected (see Connect).

func (*Connection) OnConnecting added in v1.2.0

func (c *Connection) OnConnecting(h func())

OnConnecting registers a handler for the peer connection starting to connect.

func (*Connection) OnDisconnected added in v0.4.0

func (c *Connection) OnDisconnected(h func())

OnDisconnected registers a handler for the peer connection being lost. The session may still recover, through ICE or a restart.

func (*Connection) OnFailed added in v0.4.0

func (c *Connection) OnFailed(h func())

OnFailed registers a handler for the peer connection failing. The connection closes right after.

func (*Connection) OnMessage

func (c *Connection) OnMessage(h func([]byte))

OnMessage registers a handler for application messages received on the data channel. Messages that arrive before the pipeline has connected are held, and delivered in order by Connect.

func (*Connection) OnNew added in v1.2.0

func (c *Connection) OnNew(h func())

OnNew registers a handler for the peer connection entering its new state.

func (*Connection) OnTrackStarted added in v1.2.0

func (c *Connection) OnTrackStarted(h func(*webrtc.TrackRemote))

OnTrackStarted registers a handler for a track the client sends being received.

func (*Connection) OnTrackStatus added in v0.4.0

func (c *Connection) OnTrackStatus(h func(receiverIndex int, enabled bool))

OnTrackStatus registers a handler for the client turning one of its tracks on or off. receiverIndex is the track's position: 0 for audio, 1 for the camera, 2 for a screen share.

func (*Connection) PCID added in v0.4.0

func (c *Connection) PCID() string

PCID identifies the current peer connection. It changes when the connection is restarted.

func (*Connection) RemoteAudioTrack

func (c *Connection) RemoteAudioTrack(ctx context.Context) (*webrtc.TrackRemote, error)

RemoteAudioTrack returns the incoming audio track, blocking until it arrives, ctx is done, or the connection closes.

func (*Connection) Renegotiate added in v0.4.0

func (c *Connection) Renegotiate(offer webrtc.SessionDescription, restartPC bool) error

Renegotiate answers a new offer from the client on the same session. With restartPC the current peer connection is closed and the offer is answered on a new one; without it the offer is applied to the current one.

func (*Connection) ReplaceScreenVideoTrack added in v0.7.0

func (c *Connection) ReplaceScreenVideoTrack(track webrtc.TrackLocal)

ReplaceScreenVideoTrack sends track on the screen share's transceiver, the third.

func (*Connection) ReplaceVideoTrack added in v0.7.0

func (c *Connection) ReplaceVideoTrack(track webrtc.TrackLocal)

ReplaceVideoTrack sends track on the camera's transceiver, the second.

func (*Connection) ScreenVideoInputTrack added in v0.7.0

func (c *Connection) ScreenVideoInputTrack() *Track

ScreenVideoInputTrack returns the client's screen share, the track of the third transceiver, or nil when the client offered none.

func (*Connection) SendAppMessage added in v0.4.0

func (c *Connection) SendAppMessage(message any) error

SendAppMessage encodes message as JSON and sends it like SendMessage.

func (*Connection) SendMessage

func (c *Connection) SendMessage(data []byte) error

SendMessage sends an application message to the client over the data channel. While the channel is not open yet the message is queued, up to a limit, and flushed in order once it opens. If the channel never opens, queueing stops and messages are discarded.

func (*Connection) VideoInputTrack added in v0.7.0

func (c *Connection) VideoInputTrack() *Track

VideoInputTrack returns the client's camera, the track of the second transceiver, or nil when the client offered none.

func (*Connection) WaitConnected

func (c *Connection) WaitConnected(ctx context.Context) error

WaitConnected blocks until the peer connection is established, ctx is done, or the connection closes.

func (*Connection) WriteAudio

func (c *Connection) WriteAudio(packet []byte, dur time.Duration) error

WriteAudio sends one Opus packet on the outgoing track. dur is the packet's playback duration, used to advance RTP timestamps.

type ConnectionMode added in v0.4.0

type ConnectionMode string

ConnectionMode is how many connections a RequestHandler allows at once.

const (
	// ConnectionModeMultiple allows several simultaneous connections. It is the
	// default.
	ConnectionModeMultiple ConnectionMode = "multiple"
	// ConnectionModeSingle allows only one active connection.
	ConnectionModeSingle ConnectionMode = "single"
)

type ICECandidate added in v0.4.0

type ICECandidate struct {
	Candidate     string `json:"candidate"`
	SDPMid        string `json:"sdp_mid"`
	SDPMLineIndex uint16 `json:"sdp_mline_index"`
}

ICECandidate is a remote ICE candidate the client trickled in after its offer. An empty Candidate is the end-of-candidates marker for its media line.

type Option

type Option func(*Connection)

Option configures a Connection.

func WithConnectionTimeout added in v0.4.0

func WithConnectionTimeout(d time.Duration) Option

WithConnectionTimeout sets how long the peer connection may stay in the connecting state before it is closed. The default is 60 seconds.

func WithICEServers

func WithICEServers(servers ...webrtc.ICEServer) Option

WithICEServers sets the ICE servers used for connectivity. Passing none (or an empty list) disables STUN, leaving only host candidates (useful for same-host connections and tests).

func WithVideoCodecs added in v0.7.0

func WithVideoCodecs(cfg VideoCodecConfig) Option

WithVideoCodecs locates the native libraries video is decoded and encoded with. Without it they are looked for by their conventional names.

type PatchRequest added in v0.4.0

type PatchRequest struct {
	PCID       string         `json:"pc_id"`
	Candidates []ICECandidate `json:"candidates"`
}

PatchRequest carries ICE candidates for an existing connection.

type Request added in v0.4.0

type Request struct {
	SDP       string `json:"sdp"`
	Type      string `json:"type"`
	PCID      string `json:"pc_id,omitempty"`
	RestartPC bool   `json:"restart_pc,omitempty"`
	// RequestData is custom data the client sent along with the offer.
	RequestData json.RawMessage `json:"request_data,omitempty"`
}

Request is an SDP offer from a client. A first offer carries no PCID and opens a new connection; an offer carrying the PCID of an existing connection renegotiates it, restarting its peer connection when RestartPC is set.

func (*Request) UnmarshalJSON added in v0.4.0

func (r *Request) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts the custom data under either request_data or requestData.

type RequestError added in v0.4.0

type RequestError struct {
	Status int
	Detail string
}

RequestError is a request the handler refused, with the HTTP status that describes why.

func (*RequestError) Error added in v0.4.0

func (e *RequestError) Error() string

type RequestHandler added in v0.4.0

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

RequestHandler answers the offers and ICE candidates clients send over HTTP. It creates a Connection for each new client, keeps it under its pc_id so later requests reach it, and hands each new one to a callback that runs the session on it.

Example

A RequestHandler answers the offers and trickled ICE candidates a browser client posts, and hands each new connection to a callback that starts the session on it. The development runner serves these same routes; this is the way to serve them from an application's own HTTP server.

package main

import (
	"encoding/json"
	"errors"
	"net/http"

	"github.com/gojargo/jargo/transport"
	"github.com/gojargo/jargo/transport/rtc"
)

// A RequestHandler answers the offers and trickled ICE candidates a browser
// client posts, and hands each new connection to a callback that starts the
// session on it. The development runner serves these same routes; this is the
// way to serve them from an application's own HTTP server.
func main() {
	handler := rtc.NewRequestHandler(rtc.RequestHandlerConfig{})
	defer func() { _ = handler.Close() }()

	startSession := func(conn *rtc.Connection) error {
		t := rtc.NewTransport(conn, transport.DefaultParams())
		go runPipeline(t) // the session outlives the request
		return nil
	}

	writeError := func(w http.ResponseWriter, err error) {
		if reqErr, ok := errors.AsType[*rtc.RequestError](err); ok {
			http.Error(w, reqErr.Detail, reqErr.Status)
			return
		}
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	http.HandleFunc("POST /api/offer", func(w http.ResponseWriter, r *http.Request) {
		var req rtc.Request
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), http.StatusUnprocessableEntity)
			return
		}
		answer, err := handler.HandleWebRequest(req, startSession)
		if err != nil {
			writeError(w, err)
			return
		}
		_ = json.NewEncoder(w).Encode(answer)
	})
	http.HandleFunc("PATCH /api/offer", func(w http.ResponseWriter, r *http.Request) {
		var req rtc.PatchRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), http.StatusUnprocessableEntity)
			return
		}
		if err := handler.HandlePatchRequest(req); err != nil {
			writeError(w, err)
		}
	})
}

// runPipeline stands in for building and running the session's pipeline.
func runPipeline(*rtc.Transport) {}

func NewRequestHandler added in v0.4.0

func NewRequestHandler(cfg RequestHandlerConfig) *RequestHandler

NewRequestHandler returns a handler configured by cfg.

func (*RequestHandler) Close added in v0.4.0

func (h *RequestHandler) Close() error

Close disconnects every connection and forgets them.

func (*RequestHandler) HandlePatchRequest added in v0.4.0

func (h *RequestHandler) HandlePatchRequest(req PatchRequest) error

HandlePatchRequest adds the ICE candidates a client trickled in to the connection they belong to.

func (*RequestHandler) HandleWebRequest added in v0.4.0

func (h *RequestHandler) HandleWebRequest(req Request, onConnection func(*Connection) error) (*Answer, error)

HandleWebRequest answers an offer. An offer for a known pc_id renegotiates that connection; any other creates a new connection and passes it to onConnection, which should start the session in the background. An error from onConnection is logged, not returned: the client still gets its answer.

func (*RequestHandler) UpdateICEServers added in v0.4.0

func (h *RequestHandler) UpdateICEServers(servers []webrtc.ICEServer)

UpdateICEServers replaces the ICE servers used for new connections.

type RequestHandlerConfig added in v0.4.0

type RequestHandlerConfig struct {
	// ICEServers are the STUN and TURN servers each connection uses. None
	// leaves a connection with host candidates only.
	ICEServers []webrtc.ICEServer
	// ESP32Mode rewrites each answer for ESP32 clients (see SDPMunging).
	ESP32Mode bool
	// Host is the address answers are filtered to in ESP32 mode.
	Host string
	// ConnectionMode defaults to ConnectionModeMultiple.
	ConnectionMode ConnectionMode
	// VideoCodecs locates the libraries each connection's video is decoded and
	// encoded with. The zero value looks for them by their conventional names.
	VideoCodecs VideoCodecConfig
}

RequestHandlerConfig configures a RequestHandler.

type Track added in v0.7.0

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

Track is one of the client's incoming video tracks. Its packets are assembled into frames, decoded, and queued for Recv.

It is not consumed until Recv is first called: until then its packets are dropped, so pictures nobody reads do not pile up. It stops being consumed again, its queued pictures dropped, when Recv has not been called for two seconds.

The client can turn the track off, which SetEnabled records; Recv then returns no picture.

func (*Track) DiscardOldFrames added in v0.7.0

func (t *Track) DiscardOldFrames()

DiscardOldFrames drops the pictures queued and not read yet, so the next Recv returns a fresh one.

func (*Track) IsEnabled added in v0.7.0

func (t *Track) IsEnabled() bool

IsEnabled reports whether the client is sending the track, as it last said.

func (*Track) Kind added in v0.7.0

func (t *Track) Kind() webrtc.RTPCodecType

Kind is the track's kind, audio or video.

func (*Track) Recv added in v0.7.0

func (t *Track) Recv(ctx context.Context) (*VideoFrame, error)

Recv returns the next picture, waiting for one until ctx is done. It starts the track being consumed. A video track the client turned off returns no picture, and no error, at once. Once the track has ended it returns ErrTrackEnded.

func (*Track) SetEnabled added in v0.7.0

func (t *Track) SetEnabled(enabled bool)

SetEnabled records whether the client is sending the track.

func (*Track) Stop added in v0.7.0

func (t *Track) Stop()

Stop stops the track: it is no longer read, and Recv returns ErrTrackEnded.

type Transport

type Transport struct {
	transport.BaseTransport
	// contains filtered or unexported fields
}

Transport is a WebRTC transport backed by a Pion connection. It provides the input and output processors for a pipeline.

It raises transport.EventClientConnected when the peer connection is established (again after a restart), transport.EventClientDisconnected when the client goes away, and transport.EventAppMessage for each message the client sends. The client passed to the first two is the *Connection.

With video input enabled, the client's camera is read from the start and its screen share once it is captured or an image is asked of it. Their pictures are pushed as UserImageRawFrames, sampled at the framerate each source is captured at (see CaptureParticipantVideo and Params.VideoInSources), and a UserImageRequestFrame is answered by the next picture of its source. With video output enabled, the images the pipeline shows are sent to the client as VP8 on the camera's transceiver.

func NewTransport

func NewTransport(conn *Connection, params transport.Params) *Transport

NewTransport builds a WebRTC transport over conn.

func (*Transport) CaptureParticipantVideo added in v0.7.0

func (t *Transport) CaptureParticipantVideo(
	_ context.Context, _ string, framerate int, videoSource string, onRequestOnly bool,
) error

CaptureParticipantVideo captures the peer's camera or screen share, passing on framerate frames per second, every frame for transport.EveryFrame, or with onRequestOnly only the frames that answer image requests. The transport has one peer, so participantID does not select it. An empty videoSource is the camera.

func (*Transport) Events added in v0.4.0

func (t *Transport) Events() *event.Registry

Events returns the registry of the events the transport raises.

func (*Transport) GetClientID added in v0.7.0

func (t *Transport) GetClientID(client any) string

GetClientID returns the id of the peer connection a client event carries, which is the participant id image requests take. A client that is not a *Connection has none.

func (*Transport) Input

func (t *Transport) Input() processor.Processor

Input returns the input processor.

func (*Transport) Output

func (t *Transport) Output() processor.Processor

Output returns the output processor.

type VideoCodecConfig added in v0.7.0

type VideoCodecConfig struct {
	// VPXLibPath is libvpx, which decodes and encodes VP8. Empty looks for its
	// conventional names (libvpx.so.12, libvpx.so.11, and so on) on the
	// loader's default search path.
	VPXLibPath string
	// OpenH264LibPath is libopenh264, which decodes H.264. Empty looks for its
	// conventional names (libopenh264.so.8, libopenh264.so.7, and so on).
	OpenH264LibPath string
}

VideoCodecConfig locates the native libraries video is decoded and encoded with. They are loaded the first time video needs them, so a session without video never loads them.

type VideoFrame added in v0.7.0

type VideoFrame struct {
	// Width and Height are the picture's size, in pixels.
	Width, Height int
	// Format is the pixel format of Planes, such as FormatYUV420P.
	Format string
	// Planes hold the picture, each plane's rows packed with no padding.
	Planes [][]byte
	// PTS is the picture's RTP timestamp, on the 90 kHz video clock.
	PTS int64
}

VideoFrame is a picture decoded from one of the client's video tracks.

Jump to

Keyboard shortcuts

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