Skip to content

Commit 38ee94e

Browse files
asticodeSean-Der
authored andcommitted
Added examples/rtp-forwarder
Add new example that demonstrates how to take WebRTC to RTP. Also provides instructions and pre-canned SDP so you can easily playback in VLC and ffmpeg. Resolves pion#1061
1 parent d5998ae commit 38ee94e

File tree

10 files changed

+280
-0
lines changed

10 files changed

+280
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contribu
141141
* [lawl](https://github.com/lawl)
142142
* [Jorropo](https://github.com/Jorropo)
143143
* [Akil](https://github.com/akilude)
144+
* [Quentin Renard](https://github.com/asticode)
144145

145146
### License
146147
MIT License - see [LICENSE](LICENSE) for full text

examples/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ For more full featured examples that use 3rd party libraries see our **[example-
1212
* [Play from disk](play-from-disk): The play-from-disk example demonstrates how to send video to your browser from a file saved to disk.
1313
* [Save to Disk](save-to-disk): The save-to-disk example shows how to record your webcam and save the footage to disk on the server side.
1414
* [Broadcast](broadcast): The broadcast example demonstrates how to broadcast a video to multiple peers. A broadcaster uploads the video once and the server forwards it to all other peers.
15+
* [RTP Forwarder](rtp-forwarder): The rtp-forwarder example demonstrates how to forward your audio/video streams using RTP.
1516

1617
#### Data Channel API
1718
* [Data Channels](data-channels): The data-channels example shows how you can send/recv DataChannel messages from a web browser.

examples/examples.json

+6
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@
5353
"description": "The broadcast example demonstrates how to broadcast a video to multiple peers. A broadcaster uploads the video once and the server forwards it to all other peers.",
5454
"type": "browser"
5555
},
56+
{
57+
"title": "RTP Forwarder",
58+
"link": "rtp-forwarder",
59+
"description": "The rtp-forwarder example demonstrates how to forward your audio/video streams using RTP.",
60+
"type": "browser"
61+
},
5662
{
5763
"title": "Custom Logger",
5864
"link": "#",

examples/rtp-forwarder/README.md

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# rtp-forwarder
2+
rtp-forwarder is a simple application that shows how to forward your webcam/microphone via RTP using Pion WebRTC.
3+
4+
## Instructions
5+
### Download rtp-forwarder
6+
```
7+
go get github.com/pion/webrtc/examples/rtp-forwarder
8+
```
9+
10+
### Open rtp-forwarder example page
11+
[jsfiddle.net](https://jsfiddle.net/sq69370h/) you should see your Webcam, two text-areas and a 'Start Session' button
12+
13+
### Run rtp-forwarder, with your browsers SessionDescription as stdin
14+
In the jsfiddle the top textarea is your browser, copy that and:
15+
#### Linux/macOS
16+
Run `echo $BROWSER_SDP | rtp-forwarder`
17+
#### Windows
18+
1. Paste the SessionDescription into a file.
19+
1. Run `rtp-forwarder < my_file`
20+
21+
### Input rtp-forwarder's SessionDescription into your browser
22+
Copy the text that `rtp-forwarder` just emitted and copy into second text area
23+
24+
### Hit 'Start Session' in jsfiddle and enjoy your RTP forwarded stream!
25+
#### VLC
26+
Open `rtp-forwarder.sdp` with VLC and enjoy your live video!
27+
28+
### ffmpeg/ffprobe
29+
Run `ffprobe -i rtp-forwarder.sdp -protocol_whitelist file,udp,rtp` to get more details about your streams
30+
31+
Run `ffplay -i rtp-forwarder.sdp -protocol_whitelist file,udp,rtp` to play your streams
32+
+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
textarea {
2+
width: 500px;
3+
min-height: 75px;
4+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
name: rtp-forwarder
3+
description: Example of using Pion WebRTC to forward WebRTC streams via RTP
4+
authors:
5+
- Quentin Renard
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
Browser base64 Session Description<br />
2+
<textarea id="localSessionDescription" readonly="true"></textarea> <br />
3+
4+
Golang base64 Session Description<br />
5+
<textarea id="remoteSessionDescription"></textarea> <br/>
6+
<button onclick="window.startSession()"> Start Session </button><br />
7+
8+
<br />
9+
10+
Video<br />
11+
<video id="video1" width="160" height="120" autoplay muted></video> <br />
12+
13+
Logs<br />
14+
<div id="logs"></div>
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/* eslint-env browser */
2+
3+
let pc = new RTCPeerConnection({
4+
iceServers: [
5+
{
6+
urls: 'stun:stun.l.google.com:19302'
7+
}
8+
]
9+
})
10+
var log = msg => {
11+
document.getElementById('logs').innerHTML += msg + '<br>'
12+
}
13+
14+
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
15+
.then(stream => {
16+
pc.addStream(document.getElementById('video1').srcObject = stream)
17+
pc.createOffer().then(d => pc.setLocalDescription(d)).catch(log)
18+
}).catch(log)
19+
20+
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
21+
pc.onicecandidate = event => {
22+
if (event.candidate === null) {
23+
document.getElementById('localSessionDescription').value = btoa(JSON.stringify(pc.localDescription))
24+
}
25+
}
26+
27+
window.startSession = () => {
28+
let sd = document.getElementById('remoteSessionDescription').value
29+
if (sd === '') {
30+
return alert('Session Description must not be empty')
31+
}
32+
33+
try {
34+
pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(atob(sd))))
35+
} catch (e) {
36+
alert(e)
37+
}
38+
}

examples/rtp-forwarder/main.go

+170
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"net"
7+
"time"
8+
9+
"github.com/pion/rtcp"
10+
"github.com/pion/webrtc/v2"
11+
"github.com/pion/webrtc/v2/examples/internal/signal"
12+
)
13+
14+
type udpConn struct {
15+
conn *net.UDPConn
16+
port int
17+
}
18+
19+
func main() {
20+
// Create context
21+
ctx, cancel := context.WithCancel(context.Background())
22+
23+
// Create a MediaEngine object to configure the supported codec
24+
m := webrtc.MediaEngine{}
25+
26+
// Setup the codecs you want to use.
27+
// We'll use a VP8 codec but you can also define your own
28+
m.RegisterCodec(webrtc.NewRTPOpusCodec(webrtc.DefaultPayloadTypeOpus, 48000))
29+
m.RegisterCodec(webrtc.NewRTPVP8Codec(webrtc.DefaultPayloadTypeVP8, 90000))
30+
31+
// Create the API object with the MediaEngine
32+
api := webrtc.NewAPI(webrtc.WithMediaEngine(m))
33+
34+
// Everything below is the Pion WebRTC API! Thanks for using it ❤️.
35+
36+
// Prepare the configuration
37+
config := webrtc.Configuration{
38+
ICEServers: []webrtc.ICEServer{
39+
{
40+
URLs: []string{"stun:stun.l.google.com:19302"},
41+
},
42+
},
43+
}
44+
45+
// Create a new RTCPeerConnection
46+
peerConnection, err := api.NewPeerConnection(config)
47+
if err != nil {
48+
panic(err)
49+
}
50+
51+
// Allow us to receive 1 audio track, and 1 video track
52+
if _, err = peerConnection.AddTransceiver(webrtc.RTPCodecTypeAudio); err != nil {
53+
panic(err)
54+
} else if _, err = peerConnection.AddTransceiver(webrtc.RTPCodecTypeVideo); err != nil {
55+
panic(err)
56+
}
57+
58+
// Create a local addr
59+
var laddr *net.UDPAddr
60+
if laddr, err = net.ResolveUDPAddr("udp", "127.0.0.1:"); err != nil {
61+
panic(err)
62+
}
63+
64+
// Prepare udp conns
65+
udpConns := map[string]*udpConn{
66+
"audio": {port: 4000},
67+
"video": {port: 4002},
68+
}
69+
for _, c := range udpConns {
70+
// Create remote addr
71+
var raddr *net.UDPAddr
72+
if raddr, err = net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", c.port)); err != nil {
73+
panic(err)
74+
}
75+
76+
// Dial udp
77+
if c.conn, err = net.DialUDP("udp", laddr, raddr); err != nil {
78+
panic(err)
79+
}
80+
defer func(conn net.PacketConn) {
81+
if closeErr := conn.Close(); closeErr != nil {
82+
panic(closeErr)
83+
}
84+
}(c.conn)
85+
}
86+
87+
// Set a handler for when a new remote track starts, this handler will forward data to
88+
// our UDP listeners.
89+
// In your application this is where you would handle/process audio/video
90+
peerConnection.OnTrack(func(track *webrtc.Track, receiver *webrtc.RTPReceiver) {
91+
// Retrieve udp connection
92+
c, ok := udpConns[track.Kind().String()]
93+
if !ok {
94+
return
95+
}
96+
97+
// Send a PLI on an interval so that the publisher is pushing a keyframe every rtcpPLIInterval
98+
go func() {
99+
ticker := time.NewTicker(time.Second * 2)
100+
for range ticker.C {
101+
if rtcpErr := peerConnection.WriteRTCP([]rtcp.Packet{&rtcp.PictureLossIndication{MediaSSRC: track.SSRC()}}); rtcpErr != nil {
102+
fmt.Println(rtcpErr)
103+
}
104+
}
105+
}()
106+
107+
b := make([]byte, 1500)
108+
for {
109+
// Read
110+
n, readErr := track.Read(b)
111+
if readErr != nil {
112+
panic(readErr)
113+
}
114+
115+
// Write
116+
if _, err = c.conn.Write(b[:n]); err != nil {
117+
// For this particular example, third party applications usually timeout after a short
118+
// amount of time during which the user doesn't have enough time to provide the answer
119+
// to the browser.
120+
// That's why, for this particular example, the user first needs to provide the answer
121+
// to the browser then open the third party application. Therefore we must not kill
122+
// the forward on "connection refused" errors
123+
if opError, ok := err.(*net.OpError); ok && opError.Err.Error() == "write: connection refused" {
124+
continue
125+
}
126+
panic(err)
127+
}
128+
}
129+
})
130+
131+
// Set the handler for ICE connection state
132+
// This will notify you when the peer has connected/disconnected
133+
peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
134+
fmt.Printf("Connection State has changed %s \n", connectionState.String())
135+
136+
if connectionState == webrtc.ICEConnectionStateConnected {
137+
fmt.Println("Ctrl+C the remote client to stop the demo")
138+
} else if connectionState == webrtc.ICEConnectionStateFailed ||
139+
connectionState == webrtc.ICEConnectionStateDisconnected {
140+
fmt.Println("Done forwarding")
141+
cancel()
142+
}
143+
})
144+
145+
// Wait for the offer to be pasted
146+
offer := webrtc.SessionDescription{}
147+
signal.Decode(signal.MustReadStdin(), &offer)
148+
149+
// Set the remote SessionDescription
150+
if err = peerConnection.SetRemoteDescription(offer); err != nil {
151+
panic(err)
152+
}
153+
154+
// Create answer
155+
answer, err := peerConnection.CreateAnswer(nil)
156+
if err != nil {
157+
panic(err)
158+
}
159+
160+
// Sets the LocalDescription, and starts our UDP listeners
161+
if err = peerConnection.SetLocalDescription(answer); err != nil {
162+
panic(err)
163+
}
164+
165+
// Output the answer in base64 so we can paste it in browser
166+
fmt.Println(signal.Encode(answer))
167+
168+
// Wait for context to be done
169+
<-ctx.Done()
170+
}
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
v=0
2+
o=- 0 0 IN IP4 127.0.0.1
3+
s=Pion WebRTC
4+
c=IN IP4 127.0.0.1
5+
t=0 0
6+
m=audio 4000 RTP/AVP 111
7+
a=rtpmap:111 OPUS/48000/2
8+
m=video 4002 RTP/AVP 96
9+
a=rtpmap:96 VP8/90000

0 commit comments

Comments
 (0)