-
Notifications
You must be signed in to change notification settings - Fork 4
/
pc1bwmain.js
278 lines (244 loc) · 7.99 KB
/
pc1bwmain.js
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* global TimelineDataSeries, TimelineGraphView */
'use strict';
const remoteVideo = document.querySelector('video#remoteVideo');
const localVideo = document.querySelector('video#localVideo');
const callButton = document.querySelector('button#callButton');
const hangupButton = document.querySelector('button#hangupButton');
const bandwidthSelector = document.querySelector('select#bandwidth');
hangupButton.disabled = true;
callButton.onclick = call;
hangupButton.onclick = hangup;
let pc1;
let pc2;
let localStream;
// Can be set in the console before making a call to test this keeps
// within the envelope set by the SDP. In kbps.
let maxBandwidth = 0;
let bitrateGraph;
let bitrateSeries;
let packetGraph;
let packetSeries;
let lastResult;
const offerOptions = {
offerToReceiveAudio: 0,
offerToReceiveVideo: 1
};
function gotStream(stream) {
hangupButton.disabled = false;
console.log('Received local stream');
localStream = stream;
localVideo.srcObject = stream;
localStream.getTracks().forEach(track => pc1.addTrack(track, localStream));
console.log('Adding Local Stream to peer connection');
pc1.createOffer(
offerOptions
).then(
gotDescription1,
onCreateSessionDescriptionError
);
bitrateSeries = new TimelineDataSeries();
bitrateGraph = new TimelineGraphView('bitrateGraph', 'bitrateCanvas');
bitrateGraph.updateEndDate();
packetSeries = new TimelineDataSeries();
packetGraph = new TimelineGraphView('packetGraph', 'packetCanvas');
packetGraph.updateEndDate();
}
function onCreateSessionDescriptionError(error) {
console.log('Failed to create session description: ' + error.toString());
}
function call() {
callButton.disabled = true;
bandwidthSelector.disabled = false;
console.log('Starting call');
const servers = null;
pc1 = new RTCPeerConnection(servers);
console.log('Created local peer connection object pc1');
pc1.onicecandidate = onIceCandidate.bind(pc1);
pc2 = new RTCPeerConnection(servers);
console.log('Created remote peer connection object pc2');
pc2.onicecandidate = onIceCandidate.bind(pc2);
pc2.ontrack = gotRemoteStream;
console.log('Requesting local stream');
navigator.mediaDevices.getUserMedia({video: true})
.then(gotStream)
.catch(e => alert('getUserMedia() error: ' + e.name));
}
function gotDescription1(desc) {
console.log('Offer from pc1 \n' + desc.sdp);
pc1.setLocalDescription(desc).then(
() => {
pc2.setRemoteDescription(desc)
.then(() => pc2.createAnswer().then(gotDescription2, onCreateSessionDescriptionError),
onSetSessionDescriptionError);
}, onSetSessionDescriptionError
);
}
function gotDescription2(desc) {
pc2.setLocalDescription(desc).then(
() => {
console.log('Answer from pc2 \n' + desc.sdp);
let p;
if (maxBandwidth) {
p = pc1.setRemoteDescription({
type: desc.type,
sdp: updateBandwidthRestriction(desc.sdp, maxBandwidth)
});
} else {
p = pc1.setRemoteDescription(desc);
}
p.then(() => {}, onSetSessionDescriptionError);
},
onSetSessionDescriptionError
);
}
function hangup() {
console.log('Ending call');
localStream.getTracks().forEach(track => track.stop());
pc1.close();
pc2.close();
pc1 = null;
pc2 = null;
hangupButton.disabled = true;
callButton.disabled = false;
bandwidthSelector.disabled = true;
}
function gotRemoteStream(e) {
if (remoteVideo.srcObject !== e.streams[0]) {
remoteVideo.srcObject = e.streams[0];
console.log('Received remote stream');
}
}
function getOtherPc(pc) {
return pc === pc1 ? pc2 : pc1;
}
function getName(pc) {
return pc === pc1 ? 'pc1' : 'pc2';
}
function onIceCandidate(event) {
getOtherPc(this)
.addIceCandidate(event.candidate)
.then(onAddIceCandidateSuccess)
.catch(onAddIceCandidateError);
console.log(`${getName(this)} ICE candidate:\n${event.candidate ? event.candidate.candidate : '(null)'}`);
}
function onAddIceCandidateSuccess() {
console.log('AddIceCandidate success.');
}
function onAddIceCandidateError(error) {
console.log('Failed to add ICE Candidate: ' + error.toString());
}
function onSetSessionDescriptionError(error) {
console.log('Failed to set session description: ' + error.toString());
}
// renegotiate bandwidth on the fly.
bandwidthSelector.onchange = () => {
bandwidthSelector.disabled = true;
const bandwidth = bandwidthSelector.options[bandwidthSelector.selectedIndex].value;
// In Chrome, use RTCRtpSender.setParameters to change bandwidth without
// (local) renegotiation. Note that this will be within the envelope of
// the initial maximum bandwidth negotiated via SDP.
if ((adapter.browserDetails.browser === 'chrome' ||
(adapter.browserDetails.browser === 'firefox' &&
adapter.browserDetails.version >= 64)) &&
'RTCRtpSender' in window &&
'setParameters' in window.RTCRtpSender.prototype) {
const sender = pc1.getSenders()[0];
const parameters = sender.getParameters();
if (!parameters.encodings) {
parameters.encodings = [{}];
}
if (bandwidth === 'unlimited') {
delete parameters.encodings[0].maxBitrate;
} else {
parameters.encodings[0].maxBitrate = bandwidth * 1000;
}
sender.setParameters(parameters)
.then(() => {
bandwidthSelector.disabled = false;
})
.catch(e => console.error(e));
return;
}
// Fallback to the SDP munging with local renegotiation way of limiting
// the bandwidth.
pc1.createOffer()
.then(offer => pc1.setLocalDescription(offer))
.then(() => {
const desc = {
type: pc1.remoteDescription.type,
sdp: bandwidth === 'unlimited'
? removeBandwidthRestriction(pc1.remoteDescription.sdp)
: updateBandwidthRestriction(pc1.remoteDescription.sdp, bandwidth)
};
console.log('Applying bandwidth restriction to setRemoteDescription:\n' +
desc.sdp);
return pc1.setRemoteDescription(desc);
})
.then(() => {
bandwidthSelector.disabled = false;
})
.catch(onSetSessionDescriptionError);
};
function updateBandwidthRestriction(sdp, bandwidth) {
let modifier = 'AS';
if (adapter.browserDetails.browser === 'firefox') {
bandwidth = (bandwidth >>> 0) * 1000;
modifier = 'TIAS';
}
if (sdp.indexOf('b=' + modifier + ':') === -1) {
// insert b= after c= line.
sdp = sdp.replace(/c=IN (.*)\r\n/, 'c=IN $1\r\nb=' + modifier + ':' + bandwidth + '\r\n');
} else {
sdp = sdp.replace(new RegExp('b=' + modifier + ':.*\r\n'), 'b=' + modifier + ':' + bandwidth + '\r\n');
}
return sdp;
}
function removeBandwidthRestriction(sdp) {
return sdp.replace(/b=AS:.*\r\n/, '').replace(/b=TIAS:.*\r\n/, '');
}
// query getStats every second
window.setInterval(() => {
if (!pc1) {
return;
}
const sender = pc1.getSenders()[0];
if (!sender) {
return;
}
sender.getStats().then(res => {
res.forEach(report => {
let bytes;
let packets;
if (report.type === 'outbound-rtp') {
if (report.isRemote) {
return;
}
const now = report.timestamp;
bytes = report.bytesSent;
packets = report.packetsSent;
if (lastResult && lastResult.has(report.id)) {
// calculate bitrate
const bitrate = 8 * (bytes - lastResult.get(report.id).bytesSent) /
(now - lastResult.get(report.id).timestamp);
// append to chart
bitrateSeries.addPoint(now, bitrate);
bitrateGraph.setDataSeries([bitrateSeries]);
bitrateGraph.updateEndDate();
// calculate number of packets and append to chart
packetSeries.addPoint(now, packets -
lastResult.get(report.id).packetsSent);
packetGraph.setDataSeries([packetSeries]);
packetGraph.updateEndDate();
}
}
});
lastResult = res;
});
}, 1000);