-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.html
307 lines (262 loc) · 9.72 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
<!DOCTYPE html>
<html>
<head>
<title>WebRTC Demo</title>
<style>
h1, h2, h3 {
background: rgb(238, 238, 238);
border-bottom-width: 1px;
display: block;
margin-top: 0;
padding: .2em;
text-align: center;
}
.left-video {
width: 320px;
height: 240px;
border: 1px solid black;
}
.right-video {
width: 320px;
height: 240px;
border: 1px solid black;
}
.left-section {
float: left;
}
.right-section {
float: right;
}
.buttons-left-section {
position: absolute;
float: left;
}
.buttons-right-section {
position: absolute;
right: 6px;
}
</style>
</head>
<body>
<h1>WebRTC Audio \ Video Demo using node.js and WebSocket</h1>
<h2>Use Chrome or Firefox, connect two browsers and off you go.</h2>
<div class="left-section">
<h3> Local Video </h3>
<video class="left-video" id="localvideo" autoplay controls></video>
<div class="buttons-left-section">
<button type="button" onclick="startMedia();">Start media</button>
<button type="button" onclick="stopMedia();">Stop media</button>
</div>
</div>
<div class="right-section">
<h3> Remote Video </h3>
<video class="right-video" id="remotevideo" autoplay controls></video>
<div class="buttons-right-section">
<button type="button" onclick="connect();">Connect</button>
<button type="button" onclick="disconnect();">Disconnect</button>
</div>
</div>
<script>
var hostArray = window.location.host.split(':');
var serverLoc = 'wss://' + hostArray[0] + ':443/'
var socket = new WebSocket(serverLoc);
var localvid = document.getElementById('localvideo');
var remotevid = document.getElementById('remotevideo');
var localStream = null;
var pc = null;
var mediaFlowing = false;
var useH264 = true;
var mediaConstraints = {'mandatory': {
'offerToReceiveAudio':true,
'offerToReceiveVideo':true }};
function startMedia() {
var promisifiedOldGUM = function(constraints, successCallback, errorCallback) {
// First get ahold of getUserMedia, if present
var getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia);
// Some browsers just don't implement it - return a rejected promise with an error
// to keep a consistent interface
if(!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
// Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
return new Promise(function(successCallback, errorCallback) {
getUserMedia.call(navigator, constraints, successCallback, errorCallback);
});
}
// Older browsers might not implement mediaDevices at all, so we set an empty object first
if(navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
// Some browsers partially implement mediaDevices. We can't just assign an object
// with getUserMedia as it would overwrite existing properties.
// Here, we will just add the getUserMedia property if it's missing.
if(navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = promisifiedOldGUM;
}
// Prefer camera resolution nearest to 1280x720.
var constraints = { audio: true, video: { width: 1280, height: 720 } };
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
localStream = stream;
try {
localvid.src = window.URL.createObjectURL(stream);
localvid.play();
} catch(e) {
console.log("Error setting video src: ", e);
}
})
.catch(function(err) {
console.log(err.name + ": " + err.message);
if (location.protocol === 'http:') {
alert('Please test this using HTTPS.');
} else {
alert('Have you enabled the appropriate flag? see README.md');
}
console.error(e);
});
}
// stop local video
function stopMedia() {
localvid.src = "";
localStream.getVideoTracks()[0].stop();
}
function useH264Codec(sdp) {
var isFirefox = typeof InstallTrigger !== 'undefined';
if (isFirefox)
updated_sdp = sdp.replace("m=video 9 UDP/TLS/RTP/SAVPF 120 126 97\r\n","m=video 9 UDP/TLS/RTP/SAVPF 126 120 97\r\n");
else
updated_sdp = sdp.replace("m=video 9 UDP/TLS/RTP/SAVPF 100 101 107 116 117 96 97 99 98\r\n","m=video 9 UDP/TLS/RTP/SAVPF 107 101 100 116 117 96 97 99 98\r\n");
return updated_sdp;
}
function setLocalDescAndSendMessageOffer(sessionDescription) {
if (useH264) {
// use H264 video codec in offer every time
sessionDescription.sdp = useH264Codec(sessionDescription.sdp);
}
pc.setLocalDescription(sessionDescription);
console.log("Sending SDP offer: ");
console.log(sessionDescription);
socket.send(JSON.stringify({
"messageType": "offer",
"peerDescription": sessionDescription
}));
}
function setLocalDescAndSendMessageAnswer(sessionDescription) {
if (useH264) {
// use H264 video codec in offer every time
sessionDescription.sdp = useH264Codec(sessionDescription.sdp);
}
pc.setLocalDescription(sessionDescription);
console.log("Sending SDP answer:");
console.log(sessionDescription);
socket.send(JSON.stringify({
"messageType": "answer",
"peerDescription": sessionDescription
}));
}
function onCreateOfferFailed() {
console.log("Create Offer failed");
}
// start the connection on button click
function connect() {
if (!mediaFlowing && localStream) {
createPeerConnection();
mediaFlowing = true;
pc.createOffer(setLocalDescAndSendMessageOffer, onCreateOfferFailed, mediaConstraints);
} else {
alert("Local stream not running yet or media still flowing");
}
}
// stop the connection on button click
function disconnect() {
console.log("disconnect.");
socket.send(JSON.stringify({messageType: "bye"}));
stop();
}
function stop() {
pc.close();
pc = null;
remotevid.src = null;
mediaFlowing = false;
}
function onCreateAnswerFailed(error) {
console.log("Create Answer failed:",error);
}
socket.addEventListener("message", onWebSocketMessage, false);
// process messages from web socket
function onWebSocketMessage(evt) {
var message = JSON.parse(evt.data);
if (message.messageType === 'offer') {
console.log("Received offer...")
console.log(evt);
if (!mediaFlowing) {
createPeerConnection();
mediaFlowing = true;
}
console.log('Creating remote session description...' );
var remoteDescription = message.peerDescription;
var RTCSessionDescription = window.RTCSessionDescription || window.webkitRTCSessionDescription || window.RTCSessionDescription;
pc.setRemoteDescription(new RTCSessionDescription(remoteDescription), function() {
console.log('Sending answer...');
pc.createAnswer(setLocalDescAndSendMessageAnswer, onCreateAnswerFailed);
}, function() {
console.log('Error setting remote description');
});
} else if (message.messageType === 'answer' && mediaFlowing) {
console.log('Received answer...');
console.log('Setting remote session description...' );
var remoteDescription = message.peerDescription;
var RTCSessionDescription = window.RTCSessionDescription || window.webkitRTCSessionDescription || window.RTCSessionDescription;
pc.setRemoteDescription(new RTCSessionDescription(remoteDescription));
} else if (message.messageType === "iceCandidate" && mediaFlowing) {
console.log('Received ICE candidate...');
var RTCIceCandidate = window.RTCIceCandidate || window.webkitRTCIceCandidate || window.RTCIceCandidate;
var candidate = new RTCIceCandidate({sdpMLineIndex:message.candidate.sdpMLineIndex, sdpMid:message.candidate.sdpMid, candidate:message.candidate.candidate});
pc.addIceCandidate(candidate );
} else if (message.messageType === 'bye' && mediaFlowing) {
console.log("Received bye");
stop();
}
}
function createPeerConnection() {
console.log("Creating peer connection");
RTCPeerConnection = window.webkitRTCPeerConnection || window.RTCPeerConnection;
var pc_config = {"iceServers":[]};
try {
pc = new RTCPeerConnection(pc_config);
} catch (e) {
console.log("Failed to create PeerConnection, exception: " + e.message);
}
// send any ice candidates to the other peer
pc.onicecandidate = function (evt) {
if (evt.candidate) {
console.log('Sending ICE candidate...');
console.log(evt.candidate);
socket.send(JSON.stringify({
"messageType": "iceCandidate",
"candidate": evt.candidate
}));
} else {
console.log("End of candidates.");
}
};
console.log('Adding local stream...');
pc.addStream(localStream);
pc.addEventListener("addstream", onRemoteStreamAdded, false);
pc.addEventListener("removestream", onRemoteStreamRemoved, false)
// when remote adds a stream, hand it on to the local video element
function onRemoteStreamAdded(evt) {
console.log("Added remote stream");
remotevid.src = window.URL.createObjectURL(evt.stream);
}
// when remote removes a stream, remove it from the local video element
function onRemoteStreamRemoved(evt) {
console.log("Remove remote stream");
remotevid.src = "";
}
}
</script>
</body>
</html>