-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestv.html
341 lines (333 loc) · 13.9 KB
/
testv.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
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>WebRTC Scalable Broadcast using RTCMultiConnection</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
</head>
<body>
<h1>
WebRTC Scalable Broadcast using RTCMultiConnection
<p>
Use peer-to-peer protocol to broadcast your video over 20+ users.
</p>
</h1>
<section class="make-center">
<div class="make-center">
<input type="text" id="broadcast-id" value="room-xyz" autocorrect=off autocapitalize=off size=20>
<button id="open-or-join">Open or Join Broadcast</button>
<div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div>
<div class="make-center" id="broadcast-viewers-counter"></div>
<video id="video-preview" controls loop></video>
</section>
<script src="js/RTCMultiConnection.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<!-- <script src="https://cdn.webrtc-experiment.com/RecordRTC.js"></script> -->
<script>
// recording is disabled because it is resulting for browser-crash
// if you enable below line, please also uncomment above "RecordRTC.js"
var enableRecordings = false;
var connection = new RTCMultiConnection();
// its mandatory in v3
connection.enableScalableBroadcast = true;
// each relaying-user should serve only 1 users
connection.maxRelayLimitPerUser = 1;
// we don't need to keep room-opened
// scalable-broadcast.js will handle stuff itself.
connection.autoCloseEntireSession = true;
// by default, socket.io server is assumed to be deployed on your own URL
//connection.socketURL = '/';
// comment-out below line if you do not have your own socket.io server
// connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
connection.socketURL = 'http://52.201.63.254:7070/';
connection.socketMessageEvent = 'scalable-media-broadcast-demo';
// document.getElementById('broadcast-id').value = connection.userid;
// user need to connect server, so that others can reach him.
connection.connectSocket(function(socket) {
socket.on('logs', function(log) {
document.querySelector('h1').innerHTML = log.replace(/</g, '----').replace(/>/g, '___').replace(/----/g, '(<span style="color:red;">').replace(/___/g, '</span>)');
});
// this event is emitted when a broadcast is already created.
socket.on('join-broadcaster', function(hintsToJoinBroadcast) {
console.log('join-broadcaster', hintsToJoinBroadcast);
connection.session = hintsToJoinBroadcast.typeOfStreams;
connection.sdpConstraints.mandatory = {
OfferToReceiveVideo: !!connection.session.video,
OfferToReceiveAudio: !!connection.session.audio
};
connection.broadcastId = hintsToJoinBroadcast.broadcastId;
connection.join(hintsToJoinBroadcast.userid);
});
socket.on('rejoin-broadcast', function(broadcastId) {
console.log('rejoin-broadcast', broadcastId);
connection.attachStreams = [];
socket.emit('check-broadcast-presence', broadcastId, function(isBroadcastExists) {
if (!isBroadcastExists) {
// the first person (i.e. real-broadcaster) MUST set his user-id
connection.userid = broadcastId;
}
socket.emit('join-broadcast', {
broadcastId: broadcastId,
userid: connection.userid,
typeOfStreams: connection.session
});
});
});
socket.on('broadcast-stopped', function(broadcastId) {
// alert('Broadcast has been stopped.');
// location.reload();
console.error('broadcast-stopped', broadcastId);
alert('This broadcast has been stopped.');
});
// this event is emitted when a broadcast is absent.
socket.on('start-broadcasting', function(typeOfStreams) {
console.log('start-broadcasting', typeOfStreams);
// host i.e. sender should always use this!
connection.sdpConstraints.mandatory = {
OfferToReceiveVideo: false,
OfferToReceiveAudio: false
};
connection.session = typeOfStreams;
// "open" method here will capture media-stream
// we can skip this function always; it is totally optional here.
// we can use "connection.getUserMediaHandler" instead
connection.open(connection.userid, function() {
showRoomURL(connection.sessionid);
});
});
});
window.onbeforeunload = function() {
// Firefox is ugly.
document.getElementById('open-or-join').disabled = false;
};
var videoPreview = document.getElementById('video-preview');
connection.onstream = function(event) {
if (connection.isInitiator && event.type !== 'local') {
return;
}
if (event.mediaElement) {
event.mediaElement.pause();
delete event.mediaElement;
}
connection.isUpperUserLeft = false;
videoPreview.src = URL.createObjectURL(event.stream);
videoPreview.play();
videoPreview.userid = event.userid;
if (event.type === 'local') {
videoPreview.muted = true;
}
if (connection.isInitiator == false && event.type === 'remote') {
// he is merely relaying the media
connection.dontCaptureUserMedia = true;
connection.attachStreams = [event.stream];
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: false,
OfferToReceiveVideo: false
};
var socket = connection.getSocket();
socket.emit('can-relay-broadcast');
if (connection.DetectRTC.browser.name === 'Chrome') {
connection.getAllParticipants().forEach(function(p) {
if (p + '' != event.userid + '') {
var peer = connection.peers[p].peer;
peer.getLocalStreams().forEach(function(localStream) {
peer.removeStream(localStream);
});
peer.addStream(event.stream);
connection.dontAttachStream = true;
connection.renegotiate(p);
connection.dontAttachStream = false;
}
});
}
if (connection.DetectRTC.browser.name === 'Firefox') {
// Firefox is NOT supporting removeStream method
// that's why using alternative hack.
// NOTE: Firefox seems unable to replace-tracks of the remote-media-stream
// need to ask all deeper nodes to rejoin
connection.getAllParticipants().forEach(function(p) {
if (p + '' != event.userid + '') {
connection.replaceTrack(event.stream, p);
}
});
}
// Firefox seems UN_ABLE to record remote MediaStream
// WebAudio solution merely records audio
// so recording is skipped for Firefox.
if (connection.DetectRTC.browser.name === 'Chrome') {
repeatedlyRecordStream(event.stream);
}
}
};
// ask node.js server to look for a broadcast
// if broadcast is available, simply join it. i.e. "join-broadcaster" event should be emitted.
// if broadcast is absent, simply create it. i.e. "start-broadcasting" event should be fired.
document.getElementById('open-or-join').onclick = function() {
var broadcastId = document.getElementById('broadcast-id').value;
if (broadcastId.replace(/^\s+|\s+$/g, '').length <= 0) {
alert('Please enter broadcast-id');
document.getElementById('broadcast-id').focus();
return;
}
document.getElementById('open-or-join').disabled = true;
connection.session = {
audio: true,
video: true,
oneway: true
};
var socket = connection.getSocket();
socket.emit('check-broadcast-presence', broadcastId, function(isBroadcastExists) {
if (!isBroadcastExists) {
// the first person (i.e. real-broadcaster) MUST set his user-id
connection.userid = broadcastId;
}
console.log('check-broadcast-presence', broadcastId, isBroadcastExists);
socket.emit('join-broadcast', {
broadcastId: broadcastId,
userid: connection.userid,
typeOfStreams: connection.session
});
});
};
connection.onstreamended = function() {};
connection.onleave = function(event) {
if (event.userid !== videoPreview.userid) return;
var socket = connection.getSocket();
socket.emit('can-not-relay-broadcast');
connection.isUpperUserLeft = true;
if (allRecordedBlobs.length) {
// playing lats recorded blob
var lastBlob = allRecordedBlobs[allRecordedBlobs.length - 1];
videoPreview.src = URL.createObjectURL(lastBlob);
videoPreview.play();
allRecordedBlobs = [];
} else if (connection.currentRecorder) {
var recorder = connection.currentRecorder;
connection.currentRecorder = null;
recorder.stopRecording(function() {
if (!connection.isUpperUserLeft) return;
videoPreview.src = URL.createObjectURL(recorder.blob);
videoPreview.play();
});
}
if (connection.currentRecorder) {
connection.currentRecorder.stopRecording();
connection.currentRecorder = null;
}
};
var allRecordedBlobs = [];
function repeatedlyRecordStream(stream) {
if (!enableRecordings) {
return;
}
connection.currentRecorder = RecordRTC(stream, {
type: 'video'
});
connection.currentRecorder.startRecording();
setTimeout(function() {
if (connection.isUpperUserLeft || !connection.currentRecorder) {
return;
}
connection.currentRecorder.stopRecording(function() {
allRecordedBlobs.push(connection.currentRecorder.blob);
if (connection.isUpperUserLeft) {
return;
}
connection.currentRecorder = null;
repeatedlyRecordStream(stream);
});
}, 30 * 1000); // 30-seconds
};
function disableInputButtons() {
document.getElementById('open-or-join').disabled = true;
document.getElementById('broadcast-id').disabled = true;
}
// ......................................................
// ......................Handling broadcast-id................
// ......................................................
function showRoomURL(broadcastId) {
var roomHashURL = '#' + broadcastId;
var roomQueryStringURL = '?broadcastId=' + broadcastId;
var html = '<h2>Unique URL for your room:</h2><br>';
html += 'Hash URL: <a href="' + roomHashURL + '" target="_blank">' + roomHashURL + '</a>';
html += '<br>';
html += 'QueryString URL: <a href="' + roomQueryStringURL + '" target="_blank">' + roomQueryStringURL + '</a>';
var roomURLsDiv = document.getElementById('room-urls');
roomURLsDiv.innerHTML = html;
roomURLsDiv.style.display = 'block';
}
(function() {
var params = {},
r = /([^&=]+)=?([^&]*)/g;
function d(s) {
return decodeURIComponent(s.replace(/\+/g, ' '));
}
var match, search = window.location.search;
while (match = r.exec(search.substring(1)))
params[d(match[1])] = d(match[2]);
window.params = params;
})();
var broadcastId = '';
if (localStorage.getItem(connection.socketMessageEvent)) {
broadcastId = localStorage.getItem(connection.socketMessageEvent);
} else {
broadcastId = connection.token();
}
document.getElementById('broadcast-id').value = broadcastId;
document.getElementById('broadcast-id').onkeyup = function() {
localStorage.setItem(connection.socketMessageEvent, this.value);
};
var hashString = location.hash.replace('#', '');
if (hashString.length && hashString.indexOf('comment-') == 0) {
hashString = '';
}
var broadcastId = params.broadcastId;
if (!broadcastId && hashString.length) {
broadcastId = hashString;
}
if (broadcastId && broadcastId.length) {
document.getElementById('broadcast-id').value = broadcastId;
localStorage.setItem(connection.socketMessageEvent, broadcastId);
// auto-join-room
(function reCheckRoomPresence() {
connection.checkPresence(broadcastId, function(isRoomExists) {
if (isRoomExists) {
document.getElementById('open-or-join').onclick();
return;
}
setTimeout(reCheckRoomPresence, 5000);
});
})();
disableInputButtons();
}
// below section detects how many users are viewing your broadcast
connection.onNumberOfBroadcastViewersUpdated = function(event) {
if (!connection.isInitiator) return;
document.getElementById('broadcast-viewers-counter').innerHTML = 'Number of broadcast viewers: <b>' + event.numberOfBroadcastViewers + '</b>';
};
</script>
<section>
<h2>How this works?</h2>
<p>
This module simply initializes socket.io and configures it in a way that single audio/video/screen stream can be shared/relayed over unlimited users without any <a href="https://www.webrtc-experiment.com/docs/RTP-usage.html">bandwidth/CPU usage issues</a>. Everything happens peer-to-peer!
</p>
<p>
Check <a href="https://github.com/muaz-khan/WebRTC-Experiment/issues/2">this thread</a> or <a href="https://github.com/muaz-khan/WebRTC-Scalable-Broadcast">this github repository</a>.
</p>
</section>
<section>
<h2>iOS or Android</h2>
<p>
This demo <a href="http://webrtcweb.com/cordova-apps/scalable-broadcast/" target="_blank">has built-in (open-sourced)</a> cordova apps both for <b>iOS</b> and <b>Android</b>.
</p>
<p>
Google AppStore Link: <a href="https://play.google.com/store/apps/details?id=com.webrtc.scalablebroadcast" target="_blank">https://play.google.com/store/apps/details?id=com.webrtc.scalablebroadcast</a>
</p>
</section>
<footer>
<small id="send-message"></small>
</footer>
<script src="https://cdn.webrtc-experiment.com/common.js"></script>
</body>
</html>