-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideo-room.html
536 lines (474 loc) · 18.4 KB
/
video-room.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
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
crossorigin="anonymous"></script>
<style type="text/css">
button {
margin: 5px 0px 0px 10px !important;
width: 150px;
}
video {
background-color: #ddd;
border-radius: 7px;
margin: 10px 0px 0px 10px;
width: 320px;
height: 240px;
}
.button-action {
margin: 5px 0px 0px 10px !important;
width: 654px;
}
#roomList {
border: 1px solid #ccc;
max-height: 300px;
}
.room-node {
display: flex;
justify-content: center;
align-items: center;
}
.vrg-room {
width: 200px;
height: 25px;
border: 1px solid #ccc;
text-align: center;
color: #000;
margin: 10px;
}
</style>
</head>
<body>
<button id="createRoomBtn">Create Room</button>
<br />
<button id="showRoomBtn">Show All Rooms</button></div><br />
</div>
<div id="roomList">
</div>
<div id="videoRoom">
<table>
<tr>
<td>
<video id="myVideo" autoplay muted></video>
<br /><br />
<label id="myLabel" style="margin-left: 20px">Me</label>
<span id="myId"></span>
</td>
<td>
<video id="friendsVideo1" autoplay></video>
<br /><br />
<label id="lbVideo1" style="margin-left: 20px">Friend 1</label>
<span id="spanVideo1"></span>
</td>
<td>
<video id="friendsVideo2" autoplay></video>
<br /><br />
<label id="lbVideo2" style="margin-left: 20px">Friend 2</label>
<span id="spanVideo2"></span>
</td>
</tr>
<tr>
<td>
<video id="friendsVideo3" autoplay></video>
<br /><br />
<label id="lbVideo3" style="margin-left: 20px">Friend 3</label>
<span id="spanVideo3"></span>
</td>
<td>
<video id="friendsVideo4" autoplay></video>
<br /><br />
<label id="lbVideo4" style="margin-left: 20px">Friend 4</label>
<span id="spanVideo4" style="display: none;"></span>
</td>
<td>
<video id="friendsVideo5" autoplay></video>
<br /><br />
<label id="lbVideo5" style="margin-left: 20px">Friend 5</label>
<span id="spanVideo5" style="display: none;"></span>
</td>
</tr>
</table>
<br />
<button class="button-action" id="call" type="button" class="btn btn-primary btn-lg">
<span class="glyphicon glyphicon-facetime-video" aria-hidden="true"></span> Publish
</button>
<br />
<button class="button-action" id="pause" type="button" class="btn btn-danger btn-lg">
pause
</button>
<br />
<button class="button-action" id="resume" type="button" class="btn btn-success btn-lg">
resume
</button>
<br />
<button class="button-action" id="stateCamMic" type="button" class="btn btn-warning btn-lg">
Cam - Mic
</button>
<br />
<button class="button-action" id="getStateCamMic" type="button" class="btn btn-primary btn-lg">
Get state Cam - Mic
</button>
<br />
<button class="button-action" id="updateGameData" type="button" class="btn btn-primary btn-lg">
Update game data
</button>
<br />
</div>
<script src="./gameData.js"></script>
<script src="https://unpkg.com/colyseus.js@^0.14.0/dist/colyseus.js"></script>
<script>
; (async () => {
await main()
})()
async function main() {
const userToken = localStorage.getItem('user_token')
const payload = parseJwt(userToken)
const visitor = await getVisitorData(payload)
document.querySelector('#createRoomBtn').addEventListener('click', (e) => {
e.preventDefault();
const urlCreateRoom = 'https://dev-proxy.gld-lab.link:6789/api/rooms'
// const urlCreateRoom = 'http://localhost:3000/api/rooms'
fetch(urlCreateRoom, {
method: 'POST',
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
"Authorization": `Bearer ${userToken}`
},
body: JSON.stringify({
visitorNumber: 10,
}),
}).then((response) => response.json())
.then(async (data) => {
if (data) {
const clientOptions = {
...visitor,
roomName: `Room-${data.id}`,
roomPassword: 2209,
userToken: userToken,
}
const room = await entryRoom(clientOptions);
await setupVideoRoom(room)
}
})
})
document.querySelector('#showRoomBtn').addEventListener('click', (e) => {
const urlListRoom = 'https://dev-proxy.gld-lab.link:6789/api/rooms'
// const urlListRoom = 'http://localhost:3000/api/rooms'
fetch(urlListRoom, {
method: 'GET',
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
"Authorization": `Bearer ${userToken}`
},
}).then((response) => response.json())
.then((res) => {
if (!res.data) {
document.querySelector('#roomList').innerHTML = `<div id="vrg-room">No room available, please create a room !</div>`;
} else {
const rooms = res.data;
let htmlString = '';
rooms.forEach(room => {
htmlString += `<div class="room-node"><div class="vrg-room">${room.id}</div><button id="joinRoomBtn">Join vrg-room-${room.id}</button></div>`
});
document.querySelector('#roomList').innerHTML = htmlString;
const joinBtns = document.querySelectorAll('#joinRoomBtn')
joinBtns.forEach((joinBtn) => {
joinBtn.addEventListener('click', async (e) => {
const roomId = e.path[1].querySelector('.vrg-room').innerHTML;
const clientOptions = {
...visitor,
roomName: `Room-${roomId}`,
roomPassword: "2209",
userToken: userToken,
}
const room = await entryRoom(clientOptions);
await setupVideoRoom(room)
})
})
}
}).catch((err) => {
console.log(err);
});
})
async function entryRoom(clientOptions) {
const url = getColyseusUrl()
console.log('colyseus url', url)
var client = new Colyseus.Client(url)
try {
var room = await client.join(clientOptions.roomName, {
...clientOptions,
})
$("#myLabel").text("ME: " + clientOptions.name)
$("#myId").text(clientOptions.userId)
return room;
} catch (e) {
console.log(e.message);
}
}
function getColyseusUrl() {
const url = window.location.href
// const hostname = url.split('/')[2]
// if (url.startsWith('https')) {
// return `wss://${hostname}`
// }
// return `ws://${hostname}`
return `wss://dev-proxy.gld-lab.link:2567`
}
async function getVisitorData(payload) {
const visitor = `https://dev-proxy.gld-lab.link:6789/api/visitors/${payload.id}`;
// const visitor = `http://localhost:3000/api/visitors/${payload.id}`;
const res = await fetch(visitor, {
method: 'GET',
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
"Authorization": `Bearer ${userToken}`
},
});
const data = await res.json();
return data;
}
function parseJwt(token) {
var base64Url = token.split('.')[1]
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
}).join(''))
return JSON.parse(jsonPayload)
}
async function setupVideoRoom(room) {
const NUMBER_FRIENDS = 10
const ICE_UPDATE_DELAY = 3000
const ICE_CONFIGURATION = {
iceServers: [
{ urls: 'stun:stun.services.mozilla.com' },
{ urls: 'stun:stun.l.google.com:19302' },
{
urls: 'turn:rtc.gld-lab.link:3478',
username: 'vrgDev',
credential: 'mirabo@2050',
},
],
}
var myVideo = document.getElementById('myVideo')
var publishPeerConnection = new RTCPeerConnection(ICE_CONFIGURATION)
var subscribePeerConnections = []
var friendIds = Array(NUMBER_FRIENDS).fill('')
var myId = room.sessionId
for (let i = 0; i < NUMBER_FRIENDS; i++) {
const elementId = 'friendsVideo' + (i + 1)
const friendsVideo = document.getElementById(elementId)
let peerConnection = new RTCPeerConnection(ICE_CONFIGURATION)
peerConnection.onaddstream = event => (friendsVideo.srcObject = event.stream)
subscribePeerConnections.push(peerConnection)
}
await syncShowMyFace();
function syncShowMyFace() {
console.log('show my face')
setTimeout(() => (async () => await showMyFace())(), 2000)
}
async function showMyFace() {
console.log('Request userMedia to show my face...')
let stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true })
myVideo.srcObject = stream
publishPeerConnection.addStream(stream)
}
// var publishPeerConnection = new RTCPeerConnection(servers);
publishPeerConnection.onicecandidate = event => {
if (event.candidate) {
console.log('BBBBBBBBBBBBBBBB[publisher] onIceCandidate: ' + JSON.stringify(event.candidate));
setTimeout(() => sendIceUpdate(myId, event.candidate), ICE_UPDATE_DELAY)
} else {
console.log('[publisher] Sent All Ice')
}
}
// var subscribePeerConnection = new RTCPeerConnection(servers);
for (let i = 0; i < NUMBER_FRIENDS; i++) {
subscribePeerConnections[i].onicecandidate = event => {
if (event.candidate) {
console.log('AAAAAAAAAAAA[subscriber] onIceCandidate: ' + JSON.stringify(event.candidate));
setTimeout(() => sendIceUpdate(friendIds[i], event.candidate), ICE_UPDATE_DELAY)
} else {
console.log(`[subscriber ${i + 1}] Sent All Ice`)
}
}
}
const sendMessage = (command, data) => {
// console.log(`Send message ${command}: ${JSON.stringify(data)}`);
room.send(command, data)
}
const sendIceUpdate = (publisherId, candidate) => {
sendMessage('WEBRTC_ICE_UPDATE', { publisherId: publisherId, ice: candidate })
}
const onNewPublisher = async ({ publisherId, username, uiClientUnity }) => {
console.log("client:: ", username);
console.log("UIClientUnity:: ", uiClientUnity);
let slot = -1
for (let i = 0; i < NUMBER_FRIENDS; i++) {
if (friendIds[i] == '') {
console.log(friendIds[i])
slot = i
break
}
}
if (slot == -1) {
console.log('No slot available for new publisher', publisherId)
return
}
console.log(`New publisher ${publisherId} assigned to slot: ${slot + 1}`)
friendIds[slot] = publisherId
const lbElementId = 'lbVideo' + (slot + 1)
const spanVideo = 'spanVideo' + (slot + 1)
$('#' + lbElementId).text('Friend: ' + username)
$('#' + spanVideo).text(publisherId)
console.log(lbElementId)
setTimeout(() => sendMessage('WEBRTC_SUBSCRIBE', { publisherId: publisherId }), ICE_UPDATE_DELAY)
}
const onPublisherClosed = async ({ publisherId }) => {
console.log('WEBRTC_PUBLISHER_CLOSED', publisherId)
const i = findFriendSlot(publisherId)
if (i >= 0) {
friendIds[i] = ''
}
}
const onSdpAnswer = async ({ sdp }) => {
console.log("ON SDP ANSWER -------------");
try {
console.log("SDP1================", sdp);
await publishPeerConnection.setRemoteDescription(new RTCSessionDescription(sdp))
} catch (err) {
console.log('Handle answer >> setRemoteDescription failed', err.message)
}
}
const onIceUpdate = async ({ publisherId, ice }) => {
console.log("ON ICE UPDATE -------------");
try {
console.log("ICE================", ice);
// update ice for publisher
if (publisherId == myId) {
console.log('[publisher] Add ICE candiate:', JSON.stringify(ice))
await publishPeerConnection.addIceCandidate(new RTCIceCandidate(ice))
return
}
// update ice for subscribers
const i = findFriendSlot(publisherId)
if (i == -1) {
console.log('[subscriber] No slot available for IceUpdate', publisherId)
return
}
console.log(`[subsciber-${i + 1}] Add ICE candidate:`, JSON.stringify(ice))
await subscribePeerConnections[i].addIceCandidate(new RTCIceCandidate(ice))
} catch (err) {
console.log('addIceCandidate failed', err.message)
}
}
const onSdpOffer = async ({ publisherId, sdp }) => {
console.log("ON SDP OFFER -------------");
try {
const i = findFriendSlot(publisherId)
if (i == -1) {
console.log('[subscriber] No slot available for IceUpdate', publisherId)
return
}
let peerConnection = subscribePeerConnections[i]
await peerConnection.setRemoteDescription(new RTCSessionDescription(sdp))
let answer = await peerConnection.createAnswer()
await peerConnection.setLocalDescription(answer)
sendMessage('WEBRTC_SDP_ANSWER', {
sdp: peerConnection.localDescription,
publisherId: publisherId,
})
} catch (err) {
console.log('Handler offer >> setRemoteDescription failed: ' + err.message)
}
}
function findFriendSlot(publisherId) {
for (let i = 0; i < NUMBER_FRIENDS; i++) {
if (friendIds[i] == publisherId) return i
}
return -1
}
function syncShowFriendsFace() {
console.log('request publish stream')
; (async () => await showFriendsFace())()
}
async function showFriendsFace() {
console.log("SHOW FRIEND FACE -------------");
try {
let offer = await publishPeerConnection.createOffer()
await publishPeerConnection.setLocalDescription(offer)
// console.log('offer sdp', publishPeerConnection.localDescription.sdp)
sendMessage('WEBRTC_PUBLISH', { sdp: publishPeerConnection.localDescription })
} catch (err) {
console.error(`Show friends face error: ${err.message}`)
}
}
const pauseStream = () => {
sendMessage('WEBRTC_PAUSE_STREAM', { publisherId: myId })
}
const resumeStream = () => {
sendMessage('WEBRTC_RESUME_STREAM', { publisherId: myId })
}
const sendStateCamMic = () => {
let stateCamMic = {
username: 'myName',
publisherId: myId,
camera: true,
micro: false
}
sendMessage('UPDATE_STATE_CAM_MIC', stateCamMic)
console.log("send State Cam - Mic to server: ", stateCamMic);
}
const updateStateCamMic = (stateCamMic) => {
console.log("State Cam - Mic: ", stateCamMic);
}
const getStateCamMic = () => {
sendMessage('GET_STATE_CAM_MIC');
}
const receiveStateCamMic = (message) => {
console.log("State Cam - Mic:== ", message);
}
const updateGameData = (message) => {
const eventGameData = {
command:"update",
resource: "vr_dome_list/1/vr_object_list/vr_model_list/2",
payload: gameData
}
sendMessage('HANDLE_STATE_GAMEDATA', eventGameData);
console.log('data game: ', eventGameData);
}
const getStateGameData = (message) => {
console.log("State game data:== ", message);
}
const handleStateGameData = (message) => {
console.log("State game data broadcast:== ", message);
}
room.onMessage('WEBRTC_SDP_ANSWER', onSdpAnswer)
room.onMessage('WEBRTC_NEW_PUBLISHER', onNewPublisher)
room.onMessage('WEBRTC_SDP_OFFER', onSdpOffer)
room.onMessage('WEBRTC_ICE_UPDATE', onIceUpdate)
room.onMessage('WEBRTC_PUBLISHER_CLOSED', onPublisherClosed)
room.onMessage('CLIENT_JOINED', message => console.log('CLIENT_JOINED', message))
room.onMessage('CLIENT_LEAVE', message => console.log('CLIENT_LEAVE', message))
room.onMessage('UPDATE_STATE_CAM_MIC', updateStateCamMic)
room.onMessage('GET_STATE_CAM_MIC', receiveStateCamMic)
room.onMessage('GET_STATE_GAMEDATA', getStateGameData)
room.onMessage('HANDLE_STATE_GAMEDATA', handleStateGameData)
room.onError((code, message) => {
console.log(`Room ${room.name} on error: ${code}-${message}`)
})
document.getElementById('call').onclick = syncShowFriendsFace
document.getElementById('pause').onclick = pauseStream
document.getElementById('resume').onclick = resumeStream
document.getElementById('stateCamMic').onclick = sendStateCamMic
document.getElementById('getStateCamMic').onclick = getStateCamMic
document.getElementById('updateGameData').onclick = updateGameData
}
}
</script>
</body>
</html>