Skip to main content

Overview

The PeerConnection represents a WebRTC connection that establishes peer-to-peer communications with another PeerConnection instance in a browser, or to another endpoint implementing the required protocols.
Source: peerconnection.go:33-98

Type Definition

type PeerConnection struct {
    configuration Configuration
    
    currentLocalDescription  *SessionDescription
    pendingLocalDescription  *SessionDescription
    currentRemoteDescription *SessionDescription
    pendingRemoteDescription *SessionDescription
    
    signalingState      SignalingState
    iceConnectionState  ICEConnectionState
    connectionState     PeerConnectionState
    
    rtpTransceivers []*RTPTransceiver
    iceGatherer     *ICEGatherer
    iceTransport    *ICETransport
    dtlsTransport   *DTLSTransport
    sctpTransport   *SCTPTransport
    // ... internal fields
}

Constructors

NewPeerConnection

Creates a PeerConnection with the default codecs and interceptors.
Source: peerconnection.go:100-109
func NewPeerConnection(configuration Configuration) (*PeerConnection, error)
configuration
Configuration
Configuration for the new PeerConnection
pc
*PeerConnection
The newly created PeerConnection
error
error
Error if creation fails, nil otherwise
If you wish to customize the set of available codecs and/or the set of active interceptors, create an API with a custom MediaEngine and/or interceptor.Registry, then call api.NewPeerConnection() instead.
config := webrtc.Configuration{
    ICEServers: []webrtc.ICEServer{
        {URLs: []string{"stun:stun.l.google.com:19302"}},
    },
}

pc, err := webrtc.NewPeerConnection(config)
if err != nil {
    panic(err)
}
defer pc.Close()

Offer/Answer Methods

CreateOffer

Starts the PeerConnection and generates the local description.
Source: peerconnection.go:665-797
func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription, error)
options
*OfferOptions
Optional offer options (e.g., ICERestart)
offer
SessionDescription
The generated SDP offer
error
error
Error if offer creation fails
offer, err := pc.CreateOffer(nil)
if err != nil {
    return err
}

err = pc.SetLocalDescription(offer)
if err != nil {
    return err
}

// Send offer.SDP to remote peer via signaling

CreateAnswer

Starts the PeerConnection and generates the local description in response to an offer.
Source: peerconnection.go:893-965
func (pc *PeerConnection) CreateAnswer(options *AnswerOptions) (SessionDescription, error)
options
*AnswerOptions
Optional answer options
answer
SessionDescription
The generated SDP answer
error
error
Error if answer creation fails, or if no remote description is set
answer, err := pc.CreateAnswer(nil)
if err != nil {
    return err
}

err = pc.SetLocalDescription(answer)
if err != nil {
    return err
}

// Send answer.SDP to remote peer via signaling

SetLocalDescription

Sets the SessionDescription of the local peer.
Source: peerconnection.go:1087-1146
func (pc *PeerConnection) SetLocalDescription(desc SessionDescription) error
desc
SessionDescription
The local session description to set
error
error
Error if the description is invalid or connection is closed
According to JSEP 5.4, if desc.SDP is empty, the last created offer or answer will be used based on desc.Type.

SetRemoteDescription

Sets the SessionDescription of the remote peer.
Source: peerconnection.go:1160-1369
func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error
desc
SessionDescription
The remote session description to set
error
error
Error if the description is invalid or connection is closed
// Receive SDP from remote peer
remoteDesc := webrtc.SessionDescription{
    Type: webrtc.SDPTypeOffer,
    SDP:  receivedSDP,
}

err := pc.SetRemoteDescription(remoteDesc)
if err != nil {
    return err
}

Session Description Accessors

LocalDescription

Returns PendingLocalDescription if it is not null, otherwise returns CurrentLocalDescription.
Source: peerconnection.go:1148-1158
func (pc *PeerConnection) LocalDescription() *SessionDescription
desc
*SessionDescription
The current local description, or nil

RemoteDescription

Returns pendingRemoteDescription if it is not null, otherwise returns currentRemoteDescription.
Source: peerconnection.go:2056-2069
func (pc *PeerConnection) RemoteDescription() *SessionDescription
desc
*SessionDescription
The current remote description, or nil

CurrentLocalDescription

Represents the local description that was successfully negotiated the last time the PeerConnection transitioned into the stable state.
Source: peerconnection.go:2606-2619
func (pc *PeerConnection) CurrentLocalDescription() *SessionDescription

PendingLocalDescription

Represents a local description that is in the process of being negotiated. Returns nil if the PeerConnection is in the stable state.
Source: peerconnection.go:2621-2634
func (pc *PeerConnection) PendingLocalDescription() *SessionDescription

CurrentRemoteDescription

Represents the last remote description that was successfully negotiated.
Source: peerconnection.go:2636-2645
func (pc *PeerConnection) CurrentRemoteDescription() *SessionDescription

PendingRemoteDescription

Represents a remote description that is in the process of being negotiated.
Source: peerconnection.go:2647-2657
func (pc *PeerConnection) PendingRemoteDescription() *SessionDescription

ICE Methods

AddICECandidate

Accepts an ICE candidate string and adds it to the existing set of candidates.
Source: peerconnection.go:2071-2116
func (pc *PeerConnection) AddICECandidate(candidate ICECandidateInit) error
candidate
ICECandidateInit
The ICE candidate to add
error
error
Error if no remote description is set or candidate is invalid
err := pc.AddICECandidate(webrtc.ICECandidateInit{
    Candidate: "candidate:...",
})

OnICECandidate

Sets an event handler which is invoked when a new ICE candidate is found.
Source: peerconnection.go:456-464
func (pc *PeerConnection) OnICECandidate(f func(*ICECandidate))
f
func(*ICECandidate)
Handler called with each new ICE candidate (nil when gathering is finished)
ICE candidate gathering only begins when SetLocalDescription or SetRemoteDescription is called. The handler will be called with a nil pointer when gathering is finished.
pc.OnICECandidate(func(candidate *webrtc.ICECandidate) {
    if candidate != nil {
        // Send candidate to remote peer
        sendToRemote(candidate.ToJSON())
    }
})

OnICEGatheringStateChange

Sets an event handler which is invoked when the ICE candidate gathering state has changed.
Source: peerconnection.go:466-480
func (pc *PeerConnection) OnICEGatheringStateChange(f func(ICEGatheringState))
f
func(ICEGatheringState)
Handler called when gathering state changes

OnICEConnectionStateChange

Sets an event handler which is called when an ICE connection state is changed.
Source: peerconnection.go:505-509
func (pc *PeerConnection) OnICEConnectionStateChange(f func(ICEConnectionState))
f
func(ICEConnectionState)
Handler called when ICE connection state changes
pc.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
    fmt.Printf("ICE Connection State: %s\n", state.String())
})

Media Methods

AddTrack

Adds a Track to the PeerConnection.
Source: peerconnection.go:2181-2219
func (pc *PeerConnection) AddTrack(track TrackLocal) (*RTPSender, error)
track
TrackLocal
The local track to add
sender
*RTPSender
The RTPSender for the added track
error
error
Error if the connection is closed or track cannot be added
videoTrack, err := webrtc.NewTrackLocalStaticSample(
    webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8},
    "video",
    "pion",
)
if err != nil {
    return err
}

sender, err := pc.AddTrack(videoTrack)
if err != nil {
    return err
}

RemoveTrack

Removes a Track from the PeerConnection.
Source: peerconnection.go:2221-2247
func (pc *PeerConnection) RemoveTrack(sender *RTPSender) error
sender
*RTPSender
The RTPSender to remove
error
error
Error if the connection is closed or sender not found

OnTrack

Sets an event handler which is called when remote track arrives from a remote peer.
Source: peerconnection.go:482-488
func (pc *PeerConnection) OnTrack(f func(*TrackRemote, *RTPReceiver))
f
func(*TrackRemote, *RTPReceiver)
Handler called for each incoming remote track
pc.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
    fmt.Printf("Track has started, of type %d: %s\n", track.PayloadType(), track.Codec().MimeType)
    
    // Read RTP packets
    for {
        _, _, err := track.ReadRTP()
        if err != nil {
            return
        }
    }
})

AddTransceiverFromKind

Creates a new RTPTransceiver and adds it to the set of transceivers.
Source: peerconnection.go:2284-2329
func (pc *PeerConnection) AddTransceiverFromKind(
    kind RTPCodecType,
    init ...RTPTransceiverInit,
) (*RTPTransceiver, error)
kind
RTPCodecType
The kind of media (Audio or Video)
init
...RTPTransceiverInit
Optional initialization parameters
transceiver
*RTPTransceiver
The created transceiver
error
error
Error if creation fails

AddTransceiverFromTrack

Creates a new RTPTransceiver (SendRecv or SendOnly) and adds it to the set of transceivers.
Source: peerconnection.go:2331-2355
func (pc *PeerConnection) AddTransceiverFromTrack(
    track TrackLocal,
    init ...RTPTransceiverInit,
) (*RTPTransceiver, error)
track
TrackLocal
The local track for the transceiver
init
...RTPTransceiverInit
Optional initialization parameters
transceiver
*RTPTransceiver
The created transceiver
error
error
Error if creation fails

GetSenders

Returns the RTPSender that are currently attached to this PeerConnection.
Source: peerconnection.go:2145-2157
func (pc *PeerConnection) GetSenders() []*RTPSender
senders
[]*RTPSender
Array of RTPSenders

GetReceivers

Returns the RTPReceivers that are currently attached to this PeerConnection.
Source: peerconnection.go:2159-2171
func (pc *PeerConnection) GetReceivers() []*RTPReceiver
receivers
[]*RTPReceiver
Array of RTPReceivers

GetTransceivers

Returns the RTPTransceivers that are currently attached to this PeerConnection.
Source: peerconnection.go:2173-2179
func (pc *PeerConnection) GetTransceivers() []*RTPTransceiver
transceivers
[]*RTPTransceiver
Array of RTPTransceivers

Data Channel Methods

CreateDataChannel

Creates a new DataChannel object with the given label and optional DataChannelInit.
Source: peerconnection.go:2357-2442
func (pc *PeerConnection) CreateDataChannel(
    label string,
    options *DataChannelInit,
) (*DataChannel, error)
label
string
Label for the data channel
options
*DataChannelInit
Optional configuration for the data channel
dc
*DataChannel
The created data channel
error
error
Error if creation fails or connection is closed
dc, err := pc.CreateDataChannel("chat", nil)
if err != nil {
    return err
}

dc.OnOpen(func() {
    fmt.Println("Data channel opened")
    dc.SendText("Hello!")
})

dc.OnMessage(func(msg webrtc.DataChannelMessage) {
    fmt.Printf("Message: %s\n", string(msg.Data))
})

OnDataChannel

Sets an event handler which is invoked when a data channel message arrives from a remote peer.
Source: peerconnection.go:298-304
func (pc *PeerConnection) OnDataChannel(f func(*DataChannel))
f
func(*DataChannel)
Handler called for each incoming data channel
pc.OnDataChannel(func(dc *webrtc.DataChannel) {
    fmt.Printf("New DataChannel: %s\n", dc.Label())
    
    dc.OnMessage(func(msg webrtc.DataChannelMessage) {
        // Handle message
    })
})

State Accessors

SignalingState

Returns the signaling state of the PeerConnection instance.
Source: peerconnection.go:2668-2672
func (pc *PeerConnection) SignalingState() SignalingState
state
SignalingState
Current signaling state

ICEGatheringState

Returns the ICE gathering state of the PeerConnection instance.
Source: peerconnection.go:2674-2689
func (pc *PeerConnection) ICEGatheringState() ICEGatheringState
state
ICEGatheringState
Current ICE gathering state

ICEConnectionState

Returns the ICE connection state of the PeerConnection instance.
Source: peerconnection.go:2135-2143
func (pc *PeerConnection) ICEConnectionState() ICEConnectionState
state
ICEConnectionState
Current ICE connection state

ConnectionState

Returns the connection state of the PeerConnection instance.
Source: peerconnection.go:2691-2699
func (pc *PeerConnection) ConnectionState() PeerConnectionState
state
PeerConnectionState
Current peer connection state

CanTrickleICECandidates

Reports whether the remote endpoint indicated support for receiving trickled ICE candidates.
Source: peerconnection.go:2659-2666
func (pc *PeerConnection) CanTrickleICECandidates() ICETrickleCapability
capability
ICETrickleCapability
Trickle ICE capability (Unknown, Supported, or Unsupported)

Event Handlers

OnSignalingStateChange

Sets an event handler which is invoked when the peer connection’s signaling state changes.
Source: peerconnection.go:279-285
func (pc *PeerConnection) OnSignalingStateChange(f func(SignalingState))
f
func(SignalingState)
Handler called when signaling state changes

OnConnectionStateChange

Sets an event handler which is called when the PeerConnectionState has changed.
Source: peerconnection.go:519-523
func (pc *PeerConnection) OnConnectionStateChange(f func(PeerConnectionState))
f
func(PeerConnectionState)
Handler called when connection state changes
pc.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
    fmt.Printf("Connection State: %s\n", state.String())
    
    if state == webrtc.PeerConnectionStateFailed {
        // Connection has failed, clean up
    }
})

OnNegotiationNeeded

Sets an event handler which is invoked when a change has occurred which requires session negotiation.
Source: peerconnection.go:306-310
func (pc *PeerConnection) OnNegotiationNeeded(f func())
f
func()
Handler called when negotiation is needed
pc.OnNegotiationNeeded(func() {
    offer, err := pc.CreateOffer(nil)
    if err != nil {
        return
    }
    
    err = pc.SetLocalDescription(offer)
    if err != nil {
        return
    }
    
    // Send offer to remote peer
})

Configuration Methods

GetConfiguration

Returns a Configuration object representing the current configuration of this PeerConnection.
Source: peerconnection.go:632-639
func (pc *PeerConnection) GetConfiguration() Configuration
config
Configuration
Copy of the current configuration
The returned object is a copy and direct mutation on it will not take effect until SetConfiguration has been called.

SetConfiguration

Updates the configuration of this PeerConnection object.
Source: peerconnection.go:533-630
func (pc *PeerConnection) SetConfiguration(configuration Configuration) error
configuration
Configuration
New configuration to apply
error
error
Error if configuration is invalid or cannot be modified
Some configuration properties cannot be modified after initial creation (e.g., Certificates, BundlePolicy, RTCPMuxPolicy).

Statistics

GetStats

Returns data providing statistics about the overall connection.
Source: peerconnection.go:2701-2765
func (pc *PeerConnection) GetStats() StatsReport
report
StatsReport
Statistics report for the connection
stats := pc.GetStats()
for _, stat := range stats {
    fmt.Printf("%s: %+v\n", stat.GetID(), stat)
}

Lifecycle Methods

Close

Ends the PeerConnection.
Source: peerconnection.go:2461-2464
func (pc *PeerConnection) Close() error
error
error
Any errors encountered during closure (may be nil)
defer pc.Close()

GracefulClose

Ends the PeerConnection and waits for any goroutines it started to complete.
Source: peerconnection.go:2466-2471
func (pc *PeerConnection) GracefulClose() error
error
error
Any errors encountered during closure (may be nil)
This is only safe to call outside of PeerConnection callbacks or if in a callback, in its own goroutine.

RTCP Methods

WriteRTCP

Sends a user provided RTCP packet to the connected peer.
Source: peerconnection.go:2449-2455
func (pc *PeerConnection) WriteRTCP(pkts []rtcp.Packet) error
pkts
[]rtcp.Packet
RTCP packets to send
error
error
Error if sending fails
If no peer is connected the packet is discarded. It also runs any configured interceptors.

Additional Methods

SCTP

Returns the SCTPTransport for this PeerConnection.
Source: peerconnection.go:3101-3108
func (pc *PeerConnection) SCTP() *SCTPTransport
transport
*SCTPTransport
The SCTP transport, or nil if SCTP has not been negotiated

ID

Returns the unique identifier for this PeerConnection.
Source: peerconnection.go:641-646
func (pc *PeerConnection) ID() string
id
string
Unique identifier string

See Also

Build docs developers (and LLMs) love