forked from googlecodelabs/webrtc-web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
364 lines (303 loc) · 9.94 KB
/
Copy pathmain.js
File metadata and controls
364 lines (303 loc) · 9.94 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
'use strict';
/****************************************************************************
* Initial setup
****************************************************************************/
// var configuration = {
// 'iceServers': [{
// 'urls': 'stun:stun.l.google.com:19302'
// }]
// };
var configuration = null;
// var roomURL = document.getElementById('url');
var video = document.querySelector('video');
var photo = document.getElementById('photo');
var photoContext = photo.getContext('2d');
var trail = document.getElementById('trail');
var snapBtn = document.getElementById('snap');
var sendBtn = document.getElementById('send');
var snapAndSendBtn = document.getElementById('snapAndSend');
var photoContextW;
var photoContextH;
// Attach event handlers
snapBtn.addEventListener('click', snapPhoto);
sendBtn.addEventListener('click', sendPhoto);
snapAndSendBtn.addEventListener('click', snapAndSend);
// Create a random room if not already present in the URL.
var isInitiator;
var room = window.location.hash.substring(1);
if (!room) {
room = window.location.hash = randomToken();
}
/****************************************************************************
* Signaling server
****************************************************************************/
// Connect to the signaling server
var socket = io.connect();
socket.on('ipaddr', function(ipaddr) {
console.log('Server IP address is: ' + ipaddr);
// updateRoomURL(ipaddr);
});
socket.on('created', function(room, clientId) {
console.log('Created room', room, '- my client ID is', clientId);
isInitiator = true;
grabWebCamVideo();
});
socket.on('joined', function(room, clientId) {
console.log('This peer has joined room', room, 'with client ID', clientId);
isInitiator = false;
createPeerConnection(isInitiator, configuration);
grabWebCamVideo();
});
socket.on('full', function(room) {
alert('Room ' + room + ' is full. We will create a new room for you.');
window.location.hash = '';
window.location.reload();
});
socket.on('ready', function() {
console.log('Socket is ready');
createPeerConnection(isInitiator, configuration);
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
socket.on('message', function(message) {
console.log('Client received message:', message);
signalingMessageCallback(message);
});
// Join a room
socket.emit('create or join', room);
if (location.hostname.match(/localhost|127\.0\.0/)) {
socket.emit('ipaddr');
}
/**
* Send message to signaling server
*/
function sendMessage(message) {
console.log('Client sending message: ', message);
socket.emit('message', message);
}
/**
* Updates URL on the page so that users can copy&paste it to their peers.
*/
// function updateRoomURL(ipaddr) {
// var url;
// if (!ipaddr) {
// url = location.href;
// } else {
// url = location.protocol + '//' + ipaddr + ':2013/#' + room;
// }
// roomURL.innerHTML = url;
// }
/****************************************************************************
* User media (webcam)
****************************************************************************/
function grabWebCamVideo() {
console.log('Getting user media (video) ...');
navigator.mediaDevices.getUserMedia({
audio: false,
video: true
})
.then(gotStream)
.catch(function(e) {
alert('getUserMedia() error: ' + e.name);
});
}
function gotStream(stream) {
var streamURL = window.URL.createObjectURL(stream);
console.log('getUserMedia video stream URL:', streamURL);
window.stream = stream; // stream available to console
video.src = streamURL;
video.onloadedmetadata = function() {
photo.width = photoContextW = video.videoWidth;
photo.height = photoContextH = video.videoHeight;
console.log('gotStream with with and height:', photoContextW, photoContextH);
};
show(snapBtn);
}
/****************************************************************************
* WebRTC peer connection and data channel
****************************************************************************/
var peerConn;
var dataChannel;
function signalingMessageCallback(message) {
if (message.type === 'offer') {
console.log('Got offer. Sending answer to peer.');
peerConn.setRemoteDescription(new RTCSessionDescription(message), function() {},
logError);
peerConn.createAnswer(onLocalSessionCreated, logError);
} else if (message.type === 'answer') {
console.log('Got answer.');
peerConn.setRemoteDescription(new RTCSessionDescription(message), function() {},
logError);
} else if (message.type === 'candidate') {
peerConn.addIceCandidate(new RTCIceCandidate({
candidate: message.candidate,
sdpMid: message.id,
sdpMLineIndex: message.label,
}));
} else if (message === 'bye') {
// TODO: cleanup RTC connection?
}
}
function createPeerConnection(isInitiator, config) {
console.log('Creating Peer connection as initiator?', isInitiator, 'config:',
config);
peerConn = new RTCPeerConnection(config);
// send any ice candidates to the other peer
peerConn.onicecandidate = function(event) {
console.log('icecandidate event:', event);
if (event.candidate) {
sendMessage({
type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
});
} else {
console.log('End of candidates.');
}
};
if (isInitiator) {
console.log('Creating Data Channel');
dataChannel = peerConn.createDataChannel('photos');
onDataChannelCreated(dataChannel);
console.log('Creating an offer');
peerConn.createOffer(onLocalSessionCreated, logError);
} else {
peerConn.ondatachannel = function(event) {
console.log('ondatachannel:', event.channel);
dataChannel = event.channel;
onDataChannelCreated(dataChannel);
};
}
}
function onLocalSessionCreated(desc) {
console.log('local session created:', desc);
peerConn.setLocalDescription(desc, function() {
console.log('sending local desc:', peerConn.localDescription);
sendMessage(peerConn.localDescription);
}, logError);
}
function onDataChannelCreated(channel) {
console.log('onDataChannelCreated:', channel);
channel.onopen = function() {
console.log('CHANNEL opened!!!');
};
channel.onmessage = (adapter.browserDetails.browser === 'firefox') ?
receiveDataFirefoxFactory() : receiveDataChromeFactory();
}
function receiveDataChromeFactory() {
var buf, count;
return function onmessage(event) {
if (typeof event.data === 'string') {
buf = window.buf = new Uint8ClampedArray(parseInt(event.data));
count = 0;
console.log('Expecting a total of ' + buf.byteLength + ' bytes');
return;
}
var data = new Uint8ClampedArray(event.data);
buf.set(data, count);
count += data.byteLength;
console.log('count: ' + count);
if (count === buf.byteLength) {
// we're done: all data chunks have been received
console.log('Done. Rendering photo.');
renderPhoto(buf);
}
};
}
function receiveDataFirefoxFactory() {
var count, total, parts;
return function onmessage(event) {
if (typeof event.data === 'string') {
total = parseInt(event.data);
parts = [];
count = 0;
console.log('Expecting a total of ' + total + ' bytes');
return;
}
parts.push(event.data);
count += event.data.size;
console.log('Got ' + event.data.size + ' byte(s), ' + (total - count) +
' to go.');
if (count === total) {
console.log('Assembling payload');
var buf = new Uint8ClampedArray(total);
var compose = function(i, pos) {
var reader = new FileReader();
reader.onload = function() {
buf.set(new Uint8ClampedArray(this.result), pos);
if (i + 1 === parts.length) {
console.log('Done. Rendering photo.');
renderPhoto(buf);
} else {
compose(i + 1, pos + this.result.byteLength);
}
};
reader.readAsArrayBuffer(parts[i]);
};
compose(0, 0);
}
};
}
/****************************************************************************
* Aux functions, mostly UI-related
****************************************************************************/
function snapPhoto() {
photoContext.drawImage(video, 0, 0, photo.width, photo.height);
show(photo, sendBtn);
}
function sendPhoto() {
// Split data channel message in chunks of this byte length.
var CHUNK_LEN = 64000;
console.log('width and height ', photoContextW, photoContextH);
var img = photoContext.getImageData(0, 0, photoContextW, photoContextH),
len = img.data.byteLength,
n = len / CHUNK_LEN | 0;
console.log('Sending a total of ' + len + ' byte(s)');
dataChannel.send(len);
// split the photo and send in chunks of about 64KB
for (var i = 0; i < n; i++) {
var start = i * CHUNK_LEN,
end = (i + 1) * CHUNK_LEN;
console.log(start + ' - ' + (end - 1));
dataChannel.send(img.data.subarray(start, end));
}
// send the reminder, if any
if (len % CHUNK_LEN) {
console.log('last ' + len % CHUNK_LEN + ' byte(s)');
dataChannel.send(img.data.subarray(n * CHUNK_LEN));
}
}
function snapAndSend() {
snapPhoto();
sendPhoto();
}
function renderPhoto(data) {
var canvas = document.createElement('canvas');
canvas.width = photoContextW;
canvas.height = photoContextH;
canvas.classList.add('incomingPhoto');
// trail is the element holding the incoming images
trail.insertBefore(canvas, trail.firstChild);
var context = canvas.getContext('2d');
var img = context.createImageData(photoContextW, photoContextH);
img.data.set(data);
context.putImageData(img, 0, 0);
}
function show() {
Array.prototype.forEach.call(arguments, function(elem) {
elem.style.display = null;
});
}
function hide() {
Array.prototype.forEach.call(arguments, function(elem) {
elem.style.display = 'none';
});
}
function randomToken() {
return Math.floor((1 + Math.random()) * 1e16).toString(16).substring(1);
}
function logError(err) {
console.log(err.toString(), err);
}