Pion WebRTC is a pure Go implementation of the WebRTC API, providing real-time communication capabilities without relying on C libraries or external dependencies. It enables developers to build scalable, high-performance applications for video conferencing, live streaming, gaming, and IoT communications.
Pion WebRTC uses an API object to configure global settings before creating PeerConnections:
api.go
// API allows configuration of a PeerConnection// with APIs that are available in the standard. This// lets you set custom behavior via the SettingEngine, configure// codecs via the MediaEngine and define custom media behaviors via// Interceptors.type API struct { settingEngine *SettingEngine mediaEngine *MediaEngine interceptorRegistry *interceptor.Registry interceptor interceptor.Interceptor}
// Create a MediaEngine to configure codecsmediaEngine := &webrtc.MediaEngine{}if err := mediaEngine.RegisterDefaultCodecs(); err != nil { panic(err)}// Create a SettingEngine to configure behaviorsettingEngine := webrtc.SettingEngine{}settingEngine.DetachDataChannels()// Create an API with custom settingsapi := webrtc.NewAPI( webrtc.WithMediaEngine(mediaEngine), webrtc.WithSettingEngine(settingEngine),)
The API object is copied when creating a PeerConnection, so you can safely reuse the same API instance for multiple connections.
pc.OnConnectionStateChange(func(state webrtc.PeerConnectionState) { fmt.Printf("Connection state changed: %s\n", state) switch state { case webrtc.PeerConnectionStateConnected: fmt.Println("Peers connected!") case webrtc.PeerConnectionStateFailed: fmt.Println("Connection failed") case webrtc.PeerConnectionStateClosed: fmt.Println("Connection closed") }})
The Configuration struct controls PeerConnection behavior:
configuration.go
config := webrtc.Configuration{ // STUN/TURN servers for NAT traversal ICEServers: []webrtc.ICEServer{ {URLs: []string{"stun:stun.l.google.com:19302"}}, { URLs: []string{"turn:turn.example.com:3478"}, Username: "user", Credential: "pass", }, }, // ICE transport policy ICETransportPolicy: webrtc.ICETransportPolicyAll, // or Relay // Bundle policy for media multiplexing BundlePolicy: webrtc.BundlePolicyBalanced, // RTCP multiplexing (required in WebRTC) RTCPMuxPolicy: webrtc.RTCPMuxPolicyRequire, // Pre-generate ICE candidates ICECandidatePoolSize: 0,}
Setting ICETransportPolicy to Relay will force all traffic through TURN servers, which can be useful for privacy but increases latency and server costs.
Pion WebRTC is designed to be thread-safe. All public methods can be called from multiple goroutines:
peerconnection.go
type PeerConnection struct { mu sync.RWMutex // ...}
While Pion WebRTC handles internal synchronization, you should still be careful about race conditions in your own callback handlers and application state.