-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
320 lines (277 loc) · 10.5 KB
/
index.html
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
<html>
<head>
<title>Twilio WebRTC Peer-to-Peer Sample </title>
<style>
textarea{resize:none}
</style>
</head>
<body>
<script type="text/javascript" src="/_ah/channel/jsapi"></script>
<script type="text/javascript">
var channelToken = "{{ token }}";
var user = "{{ user }}";
var connected = false
var localStream = null;
var peerConnection = null;
var peer = null;
var iceCandidates = [];
var canSendIceCandidate = false;
var statisticsInterval = null;
var video = typeof document !== 'undefined' && document.createElement("video");
video.autoplay = "autoplay";
function clearStatus() {
textarea = document.getElementById("statusArea");
textarea.innerHTML = "";
}
function status(msg) {
textarea = document.getElementById("statusArea");
textarea.innerHTML += msg;
console.log(msg);
}
function getMedia(successCallback) {
if (localStream) {
successCallback(localStream);
} else {
var constraints = { audio:true }
navigator.webkitGetUserMedia(constraints, successCallback, function(error) {
status("Error while accessing microphone: " + error.name + "\n");
});
}
}
function connect() {
var channel = new goog.appengine.Channel('{{ token }}');
var socket = channel.open();
socket.onopen = function() {
status("Channel connected\n");
connected = true;
}
socket.onerror = function() {
status("Channel error\n");
connected = false;
}
socket.onclose = function() {
status("Channel closed\n");
connected = false;
}
socket.onmessage = function(message) {
status("Channel message: " + message.data + "\n");
}
socket.onmessage = function(message) {
var message = JSON.parse(message.data);
if (message.INVITE) {
peer = message.INVITE.from;
callerSend = message.INVITE.callerSend;
canSendIceCandidate = true;
status("Received call from: " + peer + ", send audio: " + !callerSend + "\n");
getMedia(function(stream) {
localStream = stream;
answerCall(!callerSend, message.INVITE.sdp);
});
} else if (message.INVITE_RESPONSE) {
status("Call accepted\n")
// send queued ice candidates
canSendIceCandidate = true;
for (i = 0; i < iceCandidates.length; i++) {
sendIceCandidate(iceCandidates[i]);
}
peerConnection.setRemoteDescription(new RTCSessionDescription({sdp: message.INVITE_RESPONSE.sdp, type:"answer"}), function() {}, function(error) {
status("Failed to set remote description\n");
});
} else if (message.ICE) {
status("Received ICE candidate: " + message.ICE.candidate + "\n");
if (peerConnection) {
peerConnection.addIceCandidate(new RTCIceCandidate({sdpMLineIndex: message.ICE.sdpMLineIndex, candidate: message.ICE.candidate}));
} else {
status("Cannot set remote ICE candidate\n");
}
} else if (message.HANGUP) {
status("Received HANGUP\n");
doHangup();
} else if (message.ERROR) {
status("Received ERROR: " + message.ERROR + "\n");
doHangup()
}
}
}
function sendMessage(message) {
var path = "/message";
var xhr = new XMLHttpRequest();
xhr.open('POST', path, true);
xhr.send(message);
}
function createPeerConnection(sender, receiver) {
peerConnection = new webkitRTCPeerConnection({ iceServers: [] });
if (sender) {
peerConnection.addStream(localStream);
}
if (receiver) {
peerConnection.onaddstream = function(event) {
status("Attaching remote stream\n");
if (typeof video.srcObject !== 'undefined') {
video.srcObject = event.stream;
} else if (typeof video.mozSrcObject !== 'undefined') {
video.mozSrcObject = event.stream;
} else if (typeof video.src !== 'undefined') {
video.src = URL.createObjectURL(event.stream);
} else {
status("Error attaching stream\n");
}
}
}
peerConnection.onicecandidate = function (candidate) {
if (candidate.candidate) {
if (canSendIceCandidate) {
sendIceCandidate(candidate);
} else {
iceCandidates[iceCandidates.length] = candidate;
}
}
}
peerConnection.oniceconnectionstatechange = function() {
if (peerConnection) {
status("ICE state: " + peerConnection.iceConnectionState + "\n");
}
}
statisticsInterval = setInterval(getStatistics, 1000);
}
function getStatistics() {
if (peerConnection) {
peerConnection.getStats(processStatistics, function(error) {
status("Statistcs error\n");
});
}
}
function processStatistics(statistics) {
var statisticsArea = document.getElementById("statisticsArea");
var result = "Sender statistics:\n";
for (var i = 0; i < statistics.result().length; i++) {
var res = statistics.result()[i];
if (res.type == "ssrc") {
for (var j = 0; j < res.names().length; j++) {
var item = res.names()[j];
if (item == "audioInputLevel"
|| item == "packetsSent"
|| item == "bytesSent") {
result += item + ": " + res.stat(item) + "\n";
statisticsArea.innerHTML = result;
}
}
}
}
}
function clearStatistics() {
var statisticsArea = document.getElementById("statisticsArea");
stataticsArea = "Sender statistics:\naudioInputLevel: 0\npacketsSent: 0\nbytesSent: 0";
}
function sendIceCandidate(candidate) {
var message = '{"ICE":{ "to":"' + peer + '", "from":"' + user + '", "sdpMid":"' + candidate.candidate.sdpMid + '", "sdpMLineIndex":' + candidate.candidate.sdpMLineIndex + ', "candidate":"' + candidate.candidate.candidate + '"}}';
sendMessage(message);
}
function call() {
if (!connected) {
status("Please connect\n")
return;
}
peer = document.getElementById("peerName").value
if (!peer.length) {
status("Please specify peer name\n");
return;
}
status("Making call\n");
getMedia(call2);
}
function call2(stream) {
var audioTracks = stream.getAudioTracks();
if (audioTracks.length > 0) {
status('Using Audio device: ' + audioTracks[0].label + "\n");
}
clearStatistics();
localStream = stream;
var callerSend = document.getElementById("callerSend").checked;
createPeerConnection(true, !callerSend);
var constraints = { 'mandatory': { 'OfferToReceiveAudio': true, 'OfferToReceiveVideo': false } };
peerConnection.createOffer(function(desc) {
peerConnection.setLocalDescription(new RTCSessionDescription(desc), sendInvite, function(error) {
status("Failed to set local description\n");
})
}, function (err) {
status("Failed to create offer\n");
}, constraints);
}
function answerCall(sendMedia, sdp) {
clearStatistics();
createPeerConnection(sendMedia, true);
var constraints = { 'mandatory': { 'OfferToReceiveAudio': true, 'OfferToReceiveVideo': false } };
peerConnection.setRemoteDescription(new RTCSessionDescription({ sdp: sdp, type: "offer"}), function() {
peerConnection.createAnswer(function(desc) {
peerConnection.setLocalDescription(new RTCSessionDescription(desc), sendInviteResponse, function(error) {
status("Failed to set local description\n");
});
}, function (error) {
status("Failed to create answer\n");
}, constraints);
}, function(error) {
status("Failed to set remote description\n");
});
}
function sendInvite() {
var callerSend = document.getElementById("callerSend").checked;
var message = '{"INVITE":{ "to":"' + peer + '", "from":"' + user + '", "callerSend":' + callerSend + ', "sdp":' + JSON.stringify(peerConnection.localDescription.sdp) + '}}';
sendMessage(message);
}
function sendInviteResponse() {
var message = '{"INVITE_RESPONSE":{ "to":"' + peer + '", "from":"' + user + '", "sdp":' + JSON.stringify(peerConnection.localDescription.sdp) + '}}';
sendMessage(message);
}
function hangup() {
if (peerConnection) {
status("Hanging up\n");
var message = '{"HANGUP":{ "to":"' + peer + '", "from":"' + user + '"}}';
sendMessage(message);
doHangup();
} else {
status("Not in a call\n");
}
}
doHangup = function() {
clearInterval(statisticsInterval);
if (peerConnection) {
peerConnection.close();
peerConnection = null;
}
var reuseMedia = document.getElementById("reuseMedia").checked;
if (localStream && !reuseMedia) {
localStream.stop();
localStream = null;
}
peer = null;
canSendIceCandidate = false;
iceCandidates = [];
}
</script>
<h1>Twilio WebRTC Peer-to-Peer Sample</h1>
<table>
<tr>
<td width="412">
<label>User: {{ user }}</label>
<button onclick="connect()">Connect</button>
<p>
<input type=checkbox id="reuseMedia"/>Reuse local audio stream</br>
<input type=checkbox id="callerSend"/>Only caller sends audio</br>
</p>
<p>
<label>Peer:</label>
<input type="text" id="peerName"/>
<button onclick="call()">Call</button>
<button onclick="hangup()">Hangup</button>
</p>
</td>
<td>
<textarea rows="8" cols="40" id="statisticsArea" readonly></textarea>
</td>
</tr>
</table>
<p><button onclick="clearStatus()">Clear</button></p>
<p><textarea rows="30" cols="100" id="statusArea" readonly></textarea></p>
</body>
</html>