forked from pion/example-webrtc-applications
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroom.go
204 lines (170 loc) · 5.01 KB
/
room.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package main
import (
"io"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/pion/rtcp"
"github.com/pion/webrtc/v2"
)
// Peer config
var peerConnectionConfig = webrtc.Configuration{
ICEServers: []webrtc.ICEServer{
{
URLs: []string{"stun:stun.l.google.com:19302"},
},
},
SDPSemantics: webrtc.SDPSemanticsUnifiedPlanWithFallback,
}
var (
// Media engine
m webrtc.MediaEngine
// API object
api *webrtc.API
// Publisher Peer
pubCount int32
pubReceiver *webrtc.PeerConnection
// Local track
videoTrack *webrtc.Track
audioTrack *webrtc.Track
videoTrackLock = sync.RWMutex{}
audioTrackLock = sync.RWMutex{}
// Websocket upgrader
upgrader = websocket.Upgrader{}
// Broadcast channels
broadcastHub = newHub()
)
const (
rtcpPLIInterval = time.Second * 3
)
func room(w http.ResponseWriter, r *http.Request) {
// Websocket client
c, err := upgrader.Upgrade(w, r, nil)
checkError(err)
defer func() {
checkError(c.Close())
}()
// Read sdp from websocket
mt, msg, err := c.ReadMessage()
checkError(err)
if atomic.AddInt32(&pubCount, 1) == 1 {
// Create a new RTCPeerConnection
pubReceiver, err = api.NewPeerConnection(peerConnectionConfig)
checkError(err)
_, err = pubReceiver.AddTransceiver(webrtc.RTPCodecTypeAudio)
checkError(err)
_, err = pubReceiver.AddTransceiver(webrtc.RTPCodecTypeVideo)
checkError(err)
pubReceiver.OnTrack(func(remoteTrack *webrtc.Track, receiver *webrtc.RTPReceiver) {
if remoteTrack.PayloadType() == webrtc.DefaultPayloadTypeVP8 || remoteTrack.PayloadType() == webrtc.DefaultPayloadTypeVP9 || remoteTrack.PayloadType() == webrtc.DefaultPayloadTypeH264 {
// Create a local video track, all our SFU clients will be fed via this track
var err error
videoTrackLock.Lock()
videoTrack, err = pubReceiver.NewTrack(remoteTrack.PayloadType(), remoteTrack.SSRC(), "video", "pion")
videoTrackLock.Unlock()
checkError(err)
// Send a PLI on an interval so that the publisher is pushing a keyframe every rtcpPLIInterval
go func() {
ticker := time.NewTicker(rtcpPLIInterval)
for range ticker.C {
checkError(pubReceiver.WriteRTCP([]rtcp.Packet{&rtcp.PictureLossIndication{MediaSSRC: videoTrack.SSRC()}}))
}
}()
rtpBuf := make([]byte, 1400)
for {
i, err := remoteTrack.Read(rtpBuf)
checkError(err)
videoTrackLock.RLock()
_, err = videoTrack.Write(rtpBuf[:i])
videoTrackLock.RUnlock()
if err != io.ErrClosedPipe {
checkError(err)
}
}
} else {
// Create a local audio track, all our SFU clients will be fed via this track
var err error
audioTrackLock.Lock()
audioTrack, err = pubReceiver.NewTrack(remoteTrack.PayloadType(), remoteTrack.SSRC(), "audio", "pion")
audioTrackLock.Unlock()
checkError(err)
rtpBuf := make([]byte, 1400)
for {
i, err := remoteTrack.Read(rtpBuf)
checkError(err)
audioTrackLock.RLock()
_, err = audioTrack.Write(rtpBuf[:i])
audioTrackLock.RUnlock()
if err != io.ErrClosedPipe {
checkError(err)
}
}
}
})
// Set the remote SessionDescription
checkError(pubReceiver.SetRemoteDescription(
webrtc.SessionDescription{
SDP: string(msg),
Type: webrtc.SDPTypeOffer,
}))
// Create answer
answer, err := pubReceiver.CreateAnswer(nil)
checkError(err)
// Sets the LocalDescription, and starts our UDP listeners
checkError(pubReceiver.SetLocalDescription(answer))
// Send server sdp to publisher
checkError(c.WriteMessage(mt, []byte(answer.SDP)))
// Register incoming channel
pubReceiver.OnDataChannel(func(d *webrtc.DataChannel) {
d.OnMessage(func(msg webrtc.DataChannelMessage) {
// Broadcast the data to subSenders
broadcastHub.broadcastChannel <- msg.Data
})
})
} else {
// Create a new PeerConnection
subSender, err := api.NewPeerConnection(peerConnectionConfig)
checkError(err)
// Register data channel creation handling
subSender.OnDataChannel(func(d *webrtc.DataChannel) {
broadcastHub.addListener(d)
})
// Waiting for publisher track finish
for {
videoTrackLock.RLock()
if videoTrack == nil {
videoTrackLock.RUnlock()
//if videoTrack == nil, waiting..
time.Sleep(100 * time.Millisecond)
} else {
videoTrackLock.RUnlock()
break
}
}
// Add local video track
videoTrackLock.RLock()
_, err = subSender.AddTrack(videoTrack)
videoTrackLock.RUnlock()
checkError(err)
// Add local audio track
audioTrackLock.RLock()
_, err = subSender.AddTrack(audioTrack)
audioTrackLock.RUnlock()
checkError(err)
// Set the remote SessionDescription
checkError(subSender.SetRemoteDescription(
webrtc.SessionDescription{
SDP: string(msg),
Type: webrtc.SDPTypeOffer,
}))
// Create answer
answer, err := subSender.CreateAnswer(nil)
checkError(err)
// Sets the LocalDescription, and starts our UDP listeners
checkError(subSender.SetLocalDescription(answer))
// Send server sdp to subscriber
checkError(c.WriteMessage(mt, []byte(answer.SDP)))
}
}