Overview
This example creates a simple SFU (Selective Forwarding Unit) that accepts one video stream from a broadcaster and distributes it to multiple viewers. The broadcaster only uploads once, dramatically reducing bandwidth requirements compared to peer-to-peer mesh architectures.Key Features
- One-to-many video distribution
- Minimal bandwidth usage for broadcaster
- HTTP server for easy SDP exchange
- Automatic track forwarding to all connected viewers
- Support for unlimited viewers
- Interval PLI for keyframe management
Architecture
How It Works
Create Local Track for Distribution
When receiving the remote track, create a local track to forward to viewers:
Complete Source Code
Important Implementation Details
TrackLocalStaticRTP
TrackLocalStaticRTP
The example uses Why StaticRTP?
TrackLocalStaticRTP to forward packets:- Direct packet forwarding without re-encoding
- Low CPU usage
- Preserves original quality
- No transcoding overhead
ErrClosedPipe Handling
ErrClosedPipe Handling
When no viewers are connected, writing to the local track returns This is expected and should not cause the application to panic. Once viewers connect, packets will be successfully delivered.
io.ErrClosedPipe:HTTP Signaling
HTTP Signaling
This example uses HTTP POST for signaling:For production, implement:
- WebSocket signaling for bidirectional communication
- Authentication and authorization
- Session management
- Proper error handling
Scalability Considerations
Scalability Considerations
Current implementation:
- Single server process
- Unlimited viewers (limited by server resources)
- No load balancing
- Implement clustering with multiple SFU servers
- Use cascading SFUs for geographic distribution
- Add bandwidth estimation and adaptive bitrate
- Monitor server resources and connection health
- Consider using established SFU solutions like Pion SFU
Running the Example
Connect broadcaster
- Open the broadcast page in a browser
- Enable your webcam
- Generate and copy the offer
- Send it via curl:
- Copy the answer from terminal and paste in browser
Connect viewers
For each viewer:
- Open the viewer page in a new browser/tab
- Generate and copy the offer
- Send via curl (same command as broadcaster)
- Copy the answer and paste in browser
- Video should start playing
Bandwidth Comparison
Mesh (P2P)
For 10 viewers:
- Broadcaster upload: 10x bandwidth
- Each viewer: 1x bandwidth
- Total: 20x bandwidth
SFU (This Example)
For 10 viewers:
- Broadcaster upload: 1x bandwidth
- Server processing: Packet forwarding only
- Total: 11x bandwidth (10x viewer download + 1x upload)
Use Cases
- Live streaming events and webinars
- Video conferencing (with modifications for multi-publisher)
- Online education and virtual classrooms
- Live sports broadcasting
- Concert and performance streaming
Related Examples
- Play from Disk - Stream pre-recorded content
- Save to Disk - Record the broadcast
- Simulcast - Handle multiple quality streams