-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdualStream.js
375 lines (317 loc) · 9.78 KB
/
dualStream.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
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
// create Agora client
var client = AgoraRTC.createClient({
mode: "rtc",
codec: "vp8",
});
AgoraRTC.enableLogUpload();
var localTracks = {
videoTrack: null,
audioTrack: null,
};
var remoteUsers = {};
// Agora client options
var options = {
subscribeOnly: true,
appid: "",
channel: "",
uid: "",
token: "",
cameraLabel: "OBS",
};
const streamQualityConfig = {
low: {
width: 640,
height: 360,
framerate: 24,
bitrate: 960,
},
high: {
width: { min: 1270, max: 1920 },
height: { min: 720, max: 1080 },
frameRate: { min: 23, max: 30 },
bitrateMin: 1620,
bitrateMax: 3240,
},
};
// the demo can auto join channel with params in url
$(() => {
const urlParams = new URL(location.href).searchParams;
const keys = ["subscribeOnly", "appid", "channel", "token", "uid"];
keys.forEach((key) => {
const value = urlParams.get(key);
options[key] = decodeURIComponent(value);
if (key === "subscribeOnly") {
options[key] = options[key] === "true";
}
});
if (options.appid && options.channel) {
$("#uid").val(options.uid);
$("#appid").val(options.appid);
$("#token").val(options.token);
$("#channel").val(options.channel);
$("#join-form").submit();
}
});
$("#join-form").submit(async function (e) {
e.preventDefault();
$("#join").attr("disabled", true);
$("#auto-switch").attr("disabled", false);
try {
options.channel = $("#channel").val();
options.uid = Number($("#uid").val());
options.appid = $("#appid").val();
options.token = $("#token").val();
await join();
if (options.token) {
$("#success-alert-with-token").css("display", "block");
} else {
$("#success-alert a").attr(
"href",
`index.html?appid=${options.appid}&channel=${options.channel}&token=${options.token}`,
);
$("#success-alert").css("display", "block");
}
} catch (error) {
console.error(error);
} finally {
$("#leave").attr("disabled", false);
}
});
$("#leave").click(function (e) {
leave();
});
async function join() {
// add event listener to play remote tracks when remote user publishs.
client.on("user-published", handleUserPublished);
client.on("user-unpublished", handleUserUnpublished);
// Customize the video profile of the low-quality stream: 160 × 120, 15 fps, 120 Kbps.
client.setLowStreamParameter(streamQualityConfig.low);
// Enable dual-stream mode.
await client.enableDualStream();
options.uid = await client.join(
options.appid,
options.channel,
options.token || null,
options.uid || null,
);
// Set the stream type of the video streams that the client has subscribed to.
await setSomeUserHQStream();
if (options.subscribeOnly) {
return;
}
[localTracks.audioTrack, localTracks.videoTrack] = await Promise.all([
AgoraRTC.createMicrophoneAudioTrack({
encoderConfig: "music_standard",
}),
AgoraRTC.createCameraVideoTrack({
encoderConfig: streamQualityConfig.high,
}),
]);
await applyCamera(options.cameraLabel);
// play local video track
localTracks.videoTrack.play("local-player");
$("#local-player-name").text(`localVideo(${options.uid})`);
$("#joined-setup").css("display", "flex");
// publish local tracks to channel
await client.publish(Object.values(localTracks));
console.log("publish success");
}
async function setSomeUserHQStream(HQStreamUserList = []) {
// get a list of all remote users
const allUserList = [...Object.keys(remoteUsers)].map(Number);
// set default HQStreamUserList
if (
!HQStreamUserList ||
(Array.isArray(HQStreamUserList) && HQStreamUserList.length === 0)
) {
if (allUserList.length) {
HQStreamUserList = [allUserList[0]];
}
}
// All other elements are the elements of the LQStreamUserList
const LQStreamUserList = allUserList.filter(
(user) => !HQStreamUserList.includes(user),
);
const handlePromiseList = [];
// Get a queue
// The queue settings for all streams
// On desktop browsers, a user can subscribe to up to four high-quality streams and 13 low-quality streams.
// On mobile browsers, a user can subscribe to one high-quality stream and four low-quality streams
LQStreamUserList.forEach(
(user) =>
void handlePromiseList.push(async () => {
console.log(`set user: ${user} to LQ Stream`);
const result = await client.setRemoteVideoStreamType(user, 1);
return result;
}),
);
HQStreamUserList.forEach(
(user) =>
void handlePromiseList.push(async () => {
console.log(`set user: ${user} to HQ Stream`);
const result = await client.setRemoteVideoStreamType(user, 0);
return result;
}),
);
// return a promise.all
// promise.all requires an array of promises.
return Promise.all(handlePromiseList.map((m) => m()));
}
async function leave() {
for (trackName in localTracks) {
var track = localTracks[trackName];
if (track) {
track.stop();
track.close();
localTracks[trackName] = undefined;
}
}
// remove remote users and player views
remoteUsers = {};
$("#remote-playerlist").html("");
// leave the channel
await client.leave();
$("#local-player-name").text("");
$("#join").attr("disabled", false);
$("#leave").attr("disabled", true);
$("#auto-switch").attr("disabled", true);
$("#joined-setup").css("display", "none");
console.log("client leaves channel success");
}
async function subscribe(user, mediaType) {
const uid = user.uid;
// Set stream at each subscription
await setSomeUserHQStream();
// subscribe to a remote user
await client.subscribe(user, mediaType);
console.log("subscribe success");
if (mediaType === "video") {
const player = $(`
<div id="player-wrapper-${uid}">
<p class="player-name">remoteUser(${uid})</p>
<div id="player-${uid}" class="player" data-uid="${uid}"></div>
</div>
`);
$("#remote-playerlist").append(player);
user.videoTrack.play(`player-${uid}`);
}
if (mediaType === "audio") {
user.audioTrack.play();
}
}
function handleUserPublished(user, mediaType) {
const id = user.uid;
remoteUsers[id] = user;
subscribe(user, mediaType);
}
function handleUserUnpublished(user, mediaType) {
if (mediaType === "video") {
const id = user.uid;
delete remoteUsers[id];
$(`#player-wrapper-${id}`).remove();
}
}
$("#auto-switch").click((e) => {
const isEnabled = e.target.getAttribute("data-enabled") === "true";
if (isEnabled) {
e.target.setAttribute("data-enabled", "false");
e.target.textContent = "Start switching";
return stopAutoSwitching();
}
e.target.setAttribute("data-enabled", "true");
e.target.textContent = "Stop switching";
hqUserId = Object.values(remoteUsers)[0].uid;
startAutoSwitching().catch(() => {
e.target.setAttribute("data-enabled", "false");
e.target.textContent = "Start switching";
console.debug("Settings remain the same. Stopped");
});
});
let autoSwitchingEnabled = false;
let hqUserId = null;
async function startAutoSwitching() {
autoSwitchingEnabled = true;
while (autoSwitchingEnabled) {
const user = Object.values(remoteUsers)[0];
const uid = user.uid;
const previousTrackSettings = user.videoTrack
.getMediaStreamTrack()
.getSettings();
await switchStreamQuality(uid);
const delay = getRandomArbitrary(500, 5_000);
console.debug("delay before next switch:", delay);
await sleep(delay);
const areSettingsTheSame = () => {
const currentTrackSettings = remoteUsers[uid].videoTrack
.getMediaStreamTrack()
.getSettings();
console.debug(
"currentTrackSettings",
JSON.stringify(currentTrackSettings),
);
return (
currentTrackSettings.height === previousTrackSettings.height ||
currentTrackSettings.width === previousTrackSettings.width
);
};
if (areSettingsTheSame()) {
console.debug("DETECTED UNCHANGED STREAM QUALITY:", {
uid,
currentTrackSettings: remoteUsers[uid].videoTrack
.getMediaStreamTrack()
.getSettings(),
previousTrackSettings,
});
const urlParams = new URL(location.href).searchParams;
const delay = urlParams.has('delay')
? parseInt(urlParams.get('delay'))
: 10_000;
console.debug(`Wait ${delay / 1000} seconds and check track settings again`);
await sleep(delay);
if (areSettingsTheSame()) {
autoSwitchingEnabled = false;
throw new Error("DETECTED UNCHANGED STREAM QUALITY");
}
}
}
}
function stopAutoSwitching() {
autoSwitchingEnabled = false;
}
async function sleep(delay = 3000) {
return new Promise((resolve) => setTimeout(resolve, delay));
}
async function switchStreamQuality(uid) {
if (hqUserId === uid) {
await setSomeUserHQStream([NaN]);
hqUserId = null;
const player = document.getElementById(`player-${uid}`);
player.parentElement.classList.remove("first-player");
player.style.cssText = "border: unset;";
} else {
await setSomeUserHQStream([parseInt(uid)]);
hqUserId = uid;
const player = document.getElementById(`player-${uid}`);
player.style.cssText = "border: 2px solid red;";
player.parentElement.classList.add("first-player");
}
}
async function listCameras() {
const cams = await AgoraRTC.getCameras();
console.debug("Cameras: ", cams);
}
async function switchCamera(deviceId) {
localTracks.videoTrack.setDevice(deviceId);
}
async function applyCamera(label = "OBS") {
const cams = await AgoraRTC.getCameras();
const camera = cams.find((cam) => cam.label.includes("OBS"));
if (!camera) {
console.error(`No camera with label: ${label}`);
return;
}
localTracks.videoTrack.setDevice(camera.deviceId);
}
function getRandomArbitrary(min, max) {
return Math.ceil(Math.random() * (max - min) + min);
}