/
two-way-streaming.js
346 lines (324 loc) · 10.4 KB
/
two-way-streaming.js
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
const constants = SFU.constants;
const sfu = SFU;
let mainConfig;
let localDisplay;
let remoteDisplay;
let publishState;
let playState;
const PUBLISH = "publish";
const PLAY = "play";
const STOP = "stop";
const PRELOADER_URL="../commons/media/silence.mp3"
/**
* Default publishing config
*/
const defaultConfig = {
room: {
url: "wss://127.0.0.1:8888",
name: "ROOM1",
pin: "1234",
nickName: "User1"
},
media: {
audio: {
tracks: [
{
source: "mic",
channels: 1
}
]
},
video: {
tracks: [
{
source: "camera",
width: 640,
height: 360,
codec: "H264",
encodings: [
{ rid: "360p", active: true, maxBitrate: 500000 },
{ rid: "180p", active: true, maxBitrate: 200000, scaleResolutionDownBy: 2 }
]
}
]
}
}
};
/**
* Current state object
*/
const CurrentState = function(prefix) {
let state = {
prefix: prefix,
pc: null,
session: null,
room: null,
set: function(pc, session, room) {
state.pc = pc;
state.session = session;
state.room = room;
},
clear: function() {
state.room = null;
state.session = null;
state.pc = null;
},
buttonId: function() {
return state.prefix + "Btn";
},
buttonText: function() {
return (state.prefix.charAt(0).toUpperCase() + state.prefix.slice(1));
},
inputId: function() {
return state.prefix + "Name";
},
statusId: function() {
return state.prefix + "Status";
},
formId: function() {
return state.prefix + "Form";
},
errInfoId: function() {
return state.prefix + "ErrorInfo";
},
is: function(value) {
return (prefix === value);
}
};
return state;
}
/**
* load config and set default values
*/
const init = function() {
let configName = getUrlParam("config") || "./config.json";
$("#publishBtn").prop('disabled', true);
$("#playBtn").prop('disabled', true);
$("#url").prop('disabled', true);
$("#roomName").prop('disabled', true);
$("#publishName").prop('disabled', true);
$("#playName").prop('disabled', true);
publishState = CurrentState(PUBLISH);
playState = CurrentState(PLAY);
$.getJSON(configName, function(cfg){
mainConfig = cfg;
onDisconnected(publishState);
onDisconnected(playState);
}).fail(function(e){
//use default config
console.error("Error reading configuration file " + configName + ": " + e.status + " " + e.statusText)
console.log("Default config will be used");
mainConfig = defaultConfig;
onDisconnected(publishState);
onDisconnected(playState);
});
$("#url").val(setURL());
$("#roomName").val("ROOM1-"+createUUID(4));
$("#publishName").val("Publisher1-"+createUUID(4));
$("#playName").val("Player1-"+createUUID(4));
}
/**
* connect to server
*/
const connect = function(state) {
//create peer connection
pc = new RTCPeerConnection();
//get config object for room creation
const roomConfig = getRoomConfig(mainConfig);
roomConfig.pc = pc;
roomConfig.url = $("#url").val();
roomConfig.roomName = $("#roomName").val();
roomConfig.nickname = $("#" + state.inputId()).val();
// clean state display items
setStatus(state.statusId(), "");
setStatus(state.errInfoId(), "");
// connect to server and create a room if not
const session = sfu.createRoom(roomConfig);
session.on(constants.SFU_EVENT.CONNECTED, function(room) {
state.set(pc, session, room);
onConnected(state);
setStatus(state.statusId(), "ESTABLISHED", "green");
}).on(constants.SFU_EVENT.DISCONNECTED, function() {
state.clear();
onDisconnected(state);
setStatus(state.statusId(), "DISCONNECTED", "green");
}).on(constants.SFU_EVENT.FAILED, function(e) {
state.clear();
onDisconnected(state);
setStatus(state.statusId(), "FAILED", "red");
setStatus(state.errInfoId(), e.status + " " + e.statusText, "red");
});
}
const onConnected = function(state) {
$("#" + state.buttonId()).text("Stop").off('click').click(function () {
onStopClick(state);
});
$('#url').prop('disabled', true);
$("#roomName").prop('disabled', true);
$("#" + state.inputId()).prop('disabled', true);
// Add errors displaying
state.room.on(constants.SFU_ROOM_EVENT.FAILED, function(e) {
setStatus(state.errInfoId(), e, "red");
}).on(constants.SFU_ROOM_EVENT.OPERATION_FAILED, function (e) {
setStatus(state.errInfoId(), e.operation + " failed: " + e.error, "red");
});
if (state.is(PUBLISH)) {
publishStreams(state);
} else if (state.is(PLAY)) {
playStreams(state);
}
}
const onDisconnected = function(state) {
$("#" + state.buttonId()).text(state.buttonText()).off('click').click(function () {
onStartClick(state);
}).prop('disabled', false);
$("#" + state.inputId()).prop('disabled', false);
// Check if other session is active
if ((state.is(PUBLISH) && playState.session)
|| (state.is(PLAY) && publishState.session)) {
return;
}
$('#url').prop('disabled', false);
$("#roomName").prop('disabled', false);
}
const onStartClick = function(state) {
if (validateForm("connectionForm") && validateForm(state.formId())) {
$("#" + state.buttonId()).prop('disabled', true);
if (state.is(PLAY) && Browser().isSafariWebRTC()) {
playFirstSound(document.getElementById("main"), PRELOADER_URL).then(function () {
connect(state);
});
} else {
connect(state);
}
}
}
const onStopClick = function(state) {
$("#" + state.buttonId()).prop('disabled', true);
if (state.is(PUBLISH)) {
unPublishStreams(state);
} else if (state.is(PLAY)) {
stopStreams(state);
}
state.session.disconnect();
}
const publishStreams = async function(state) {
let timerId;
//create local display item to show local streams
localDisplay = initLocalDisplay(document.getElementById("localVideo"));
try {
//get configured local video streams
let streams = await getVideoStreams(mainConfig);
let audioStreams = await getAudioStreams(mainConfig);
//combine local video streams with audio streams
streams.push.apply(streams, audioStreams);
let config = {};
//add our local streams to the room (to PeerConnection)
streams.forEach(function (s) {
//add local stream to local display
localDisplay.add(s.stream.id, $("#" + state.inputId()).val(), s.stream);
//add each track to PeerConnection
s.stream.getTracks().forEach((track) => {
if (s.source === "screen") {
config[track.id] = s.source;
}
addTrackToPeerConnection(state.pc, s.stream, track, s.encodings);
subscribeTrackToEndedEvent(state.room, track, state.pc);
});
});
state.room.join(config);
// TODO: Use room state or promises to detect if publishing started to enable stop button
timerId = waitFor(document.getElementById("localVideo"), 3000, state);
} catch(e) {
console.error("Failed to capture streams: " + e);
setStatus(state.errInfoId(), e.name, "red");
if (timerId) {
clearTimeout(timerId);
timerId = null;
}
onStopClick(state);
}
}
// A workaround to check if publishing or playback is started
const waitFor = function (div, timeout, state) {
let timerId = setTimeout(function () {
if (div.innerHTML !== "") {
// Enable stop button
$("#" + state.buttonId()).prop('disabled', false);
}
else {
setStatus(state.errInfoId(), "Something went wrong, stopping", "red");
onStopClick(state);
}
}, timeout);
return timerId;
}
const unPublishStreams = function(state) {
if (localDisplay) {
localDisplay.stop();
}
}
const playStreams = function(state) {
//create remote display item to show remote streams
remoteDisplay = initRemoteDisplay(document.getElementById("remoteVideo"), state.room, state.pc);
state.room.join();
$("#" + state.buttonId()).prop('disabled', false);
}
const stopStreams = function(state) {
if (remoteDisplay) {
remoteDisplay.stop();
}
}
const subscribeTrackToEndedEvent = function(room, track, pc) {
track.addEventListener("ended", function() {
//track ended, see if we need to cleanup
let negotiate = false;
for (const sender of pc.getSenders()) {
if (sender.track === track) {
pc.removeTrack(sender);
//track found, set renegotiation flag
negotiate = true;
break;
}
}
if (negotiate) {
//kickoff renegotiation
room.updateState();
}
});
};
const addTrackToPeerConnection = function(pc, stream, track, encodings) {
pc.addTransceiver(track, {
direction: "sendonly",
streams: [stream],
sendEncodings: encodings ? encodings : [] //passing encoding types for video simulcast tracks
});
}
const setStatus = function (status, text, color) {
const field = document.getElementById(status);
if (color) {
field.style.color = color;
}
field.innerText = text;
}
const validateForm = function (formId) {
var valid = true;
$('#' + formId + ' :text').each(function () {
if (!$(this).val()) {
highlightInput($(this));
valid = false;
} else {
removeHighlight($(this));
}
});
return valid;
function highlightInput(input) {
input.closest('.input-group').addClass("has-error");
}
function removeHighlight(input) {
input.closest('.input-group').removeClass("has-error");
}
}
const buttonText = function (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}