-
Notifications
You must be signed in to change notification settings - Fork 0
/
whip.js
442 lines (384 loc) · 11 KB
/
whip.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
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
/* global navigator */
/* global window */
/* global RTCPeerConnection */
export class WHIPClient
{
constructor()
{
//Ice properties
this.iceUsername = null;
this.icePassword = null;
//Pending candidadtes
this.candidates = [];
this.endOfcandidates = false;
}
async publish(pc, url, token)
{
//If already publishing
if (this.pc)
throw new Error("Already publishing")
//Store pc object and token
this.token = token;
this.pc = pc;
//Listen for state change events
pc.onconnectionstatechange = (event) =>
{
switch (pc.connectionState)
{
case "connected":
// The connection has become fully connected
break;
case "disconnected":
case "failed":
// One or more transports has terminated unexpectedly or in an error
break;
case "closed":
// The connection has been closed
break;
}
}
//Listen for candidates
pc.onicecandidate = (event) =>
{
if (event.candidate)
{
//Ignore candidates not from the first m line
if (event.candidate.sdpMLineIndex > 0)
//Skip
return;
//Store candidate
this.candidates.push(event.candidate);
} else
{
//No more candidates
this.endOfcandidates = true;
}
//Schedule patch on next tick if there is no already a timer or doing restart
if (!this.iceTrickeTimeout && !this.restartIce)
this.iceTrickeTimeout = setTimeout(() => this.patch(), 0);
}
//Create SDP offer
const offer = await pc.createOffer();
//Request headers
const headers = {
"Content-Type": "application/sdp"
};
//If token is set
if (token)
headers["Authorization"] = "Bearer " + token;
//Do the post request to the WHIP endpoint with the SDP offer
const fetched = await fetch(url, {
method : "POST",
body : offer.sdp,
headers
});
if (!fetched.ok)
throw new Error("Request rejected with status " + fetched.status)
//Get the resource url
if (fetched.headers.has("location")) {
this.resourceURL = new URL(fetched.headers.get("location"), url);
} else if (fetched.headers.has("Location")){
this.resourceURL = new URL(fetched.headers.get("Location"), url);
} else {
console.log("Response missing location header")
this.resourceURL = new URL(url);
}
//Get the links
const links = {};
//If the response contained any
if (fetched.headers.has("link"))
{
//Get all links headers
const linkHeaders = fetched.headers.get("link").split(/,\s+(?=<)/)
//For each one
for (const header of linkHeaders)
{
try
{
let rel, params = {};
//Split in parts
const items = header.split(";");
//Create url server
const url = items[0].trim().replace(/<(.*)>/, "$1").trim();
//For each other item
for (let i = 1; i < items.length; ++i)
{
//Split into key/val
const subitems = items[i].split(/=(.*)/);
//Get key
const key = subitems[0].trim();
//Unquote value
const value = subitems[1]
? subitems[1]
.trim()
.replaceAll("\"", "")
.replaceAll("'", "")
: subitems[1];
//Check if it is the rel attribute
if (key === "rel")
//Get rel value
rel = value;
else
//Unquote value and set them
params[key] = value
}
//Ensure it is an ice server
if (!rel)
continue;
if (!links[rel])
links[rel] = [];
//Add to config
links[rel].push({ url, params });
} catch (e)
{
console.error(e)
}
}
}
//Get current config
const config = pc.getConfiguration();
//If it has ice server info and it is not overriden by the client
if ((!config.iceServer || !config.iceServer.length) && links.hasOwnProperty("ice-server"))
{
//ICe server config
config.iceServers = [];
//For each one
for (const server of links["ice-server"])
{
try
{
//Create ice server
const iceServer = {
urls: server.url
}
//For each other param
for (const [ key, value ] of Object.entries(server.params))
{
//Get key in cammel case
const cammelCase = key.replace(/([-_][a-z])/ig, $1 => $1.toUpperCase().replace("-", "").replace("_", ""))
//Unquote value and set them
iceServer[cammelCase] = value;
}
//Add to config
config.iceServers.push(iceServer);
} catch (e) {
//Ignore errors
}
}
//If any configured
if (config.iceServers.length)
//Set it
pc.setConfiguration(config);
}
//Get the SDP answer
const answer = await fetched.text();
//Get etag
this.etag = fetched.headers.get("etag");
//Schedule patch on next tick
if (!this.iceTrickeTimeout)
this.iceTrickeTimeout = setTimeout(() => this.patch(), 0);
//Set local description
await pc.setLocalDescription(offer);
// TODO: chrome is returning a wrong value, so don't use it for now
//try {
// //Get local ice properties
// const local = this.pc.getTransceivers()[0].sender.transport.iceTransport.getLocalParameters();
// //Get them for transport
// this.iceUsername = local.usernameFragment;
// this.icePassword = local.password;
//} catch (e) {
//Fallback for browsers not supporting ice transport
this.iceUsername = offer.sdp.match(/a=ice-ufrag:(.*)\r\n/)[1];
this.icePassword = offer.sdp.match(/a=ice-pwd:(.*)\r\n/)[1];
//}
//And set remote description
await pc.setRemoteDescription({ type: "answer", sdp: answer });
}
async restart()
{
//Clear any pendint timeout
this.iceTrickeTimeout = clearTimeout(this.iceTrickeTimeout);
//Clean candidates and end of candidates flag as new ones will be retrieved
this.candidates = [];
this.endOfcandidates = false;
//Restart ice
this.pc.restartIce();
//Create a new offer
const offer = await this.pc.createOffer({ iceRestart: true });
//Update ice
this.iceUsername = offer.sdp.match(/a=ice-ufrag:(.*)\r\n/)[1];
this.icePassword = offer.sdp.match(/a=ice-pwd:(.*)\r\n/)[1];
//Set it
await this.pc.setLocalDescription(offer);
//Set restart flag time
this.restartIce = new Date();
//Clear any pendint timeout
this.iceTrickeTimeout = clearTimeout(this.iceTrickeTimeout);
//patch
return this.patch();
}
async patch()
{
//Clear any pendint timeout
this.iceTrickeTimeout = clearTimeout(this.iceTrickeTimeout);
//Check if there is any pending data
if (!(this.candidates.length || this.endOfcandidates || this.restartIce) || !this.resourceURL)
//Do nothing
return;
//Get data
const candidates = this.candidates;
const endOfcandidates = this.endOfcandidates;
const restartIce = this.restartIce;
//Clean pending data before async operation
this.candidates = [];
this.endOfcandidates = false;
//Prepare fragment
let fragment
= "a=ice-ufrag:" + this.iceUsername + "\r\n"
+ "a=ice-pwd:" + this.icePassword + "\r\n";
//Get peerconnection transceivers
const transceivers = this.pc.getTransceivers();
//Get medias
const medias = {};
//If doing something else than a restart
if (candidates.length || endOfcandidates)
//Create media object for first media always
medias[transceivers[0].mid] = {
mid : transceivers[0].mid,
kind : transceivers[0].receiver.track.kind,
candidates : [],
};
//For each candidate
for (const candidate of candidates)
{
//Get mid for candidate
const mid = candidate.sdpMid
//Get associated transceiver
const transceiver = transceivers.find(t => t.mid === mid);
//Get media
let media = medias[mid];
//If not found yet
if (!media)
//Create media object
media = medias[mid] = {
mid,
kind : transceiver.receiver.track.kind,
candidates : [],
};
//Add candidate
media.candidates.push(candidate);
}
//For each media
for (const media of Object.values(medias))
{
//Add media to fragment
fragment
+= "m=" + media.kind + " 9 UDP/TLS/RTP/SAVPF 0\r\n"
+ "a=mid:" + media.mid + "\r\n";
//Add candidate
for (const candidate of media.candidates)
fragment += "a=" + candidate.candidate + "\r\n";
if (endOfcandidates)
fragment += "a=end-of-candidates\r\n";
}
//Request headers
const headers = {
"Content-Type": "application/trickle-ice-sdpfrag"
};
//If doing an ice restart
if (restartIce)
//Set if match to any
headers["If-Match"] = "*";
else if (this.etag)
//Set if match to last known etag
headers["If-Match"] = this.etag;
//If token is set
if (this.token)
headers["Authorization"] = "Bearer " + this.token;
//Do the post request to the WHIP resource
const fetched = await fetch(this.resourceURL, {
method : "PATCH",
body : fragment,
headers
});
if (!fetched.ok && fetched.status !== 501 && fetched.status !== 405)
throw new Error("Request rejected with status " + fetched.status)
//If we have got an answer for the ice restart
if (restartIce && fetched.status === 200)
{
//Get etag
this.etag = fetched.headers.get("etag");
//Get the SDP answer
const answer = await fetched.text();
//Get remote icename and password
const iceUsername = answer.match(/a=ice-ufrag:(.*)\r\n/)[1];
const icePassword = answer.match(/a=ice-pwd:(.*)\r\n/)[1];
const candidates = Array.from(answer.matchAll(/(a=candidate:.*\r\n)/gm)).map(res => res[1])
//Get current remote rescription
const remoteDescription = this.pc.remoteDescription;
//Change username and password
remoteDescription.sdp = remoteDescription.sdp.replaceAll(/(a=ice-ufrag:)(.*)\r\n/gm, "$1" + iceUsername + "\r\n");
remoteDescription.sdp = remoteDescription.sdp.replaceAll(/(a=ice-pwd:)(.*)\r\n/gm, "$1" + icePassword + "\r\n");
//Remove all candidates
remoteDescription.sdp = remoteDescription.sdp.replaceAll(/(a=candidate:.*\r\n)/gm, "");
//Add candidates
remoteDescription.sdp = remoteDescription.sdp.replaceAll(/(m=.*\r\n)/gm, "$1" + candidates.join());
//Set it
await this.pc.setRemoteDescription(remoteDescription);
//If we are still the last ice restart
if (this.restartIce === restartIce)
{
//Clean the flag
this.restartIce = null;
//Check if there is any pending data
if (this.candidates.length || this.endOfcandidates)
//Tricke again
this.patch();
}
}
}
async mute(muted)
{
//Request headers
const headers = {
"Content-Type": "application/json"
};
//If token is set
if (this.token)
headers["Authorization"] = "Bearer " + this.token;
//Do the post request to the WHIP resource
const fetched = await fetch(this.resourceURL, {
method : "POST",
body : JSON.stringify(muted),
headers
});
}
async stop()
{
if (!this.pc)
{
// Already stopped
return
}
//Cancel any pending timeout
this.iceTrickeTimeout = clearTimeout(this.iceTrickeTimeout);
//Close peerconnection
this.pc.close();
//Null
this.pc = null;
//If we don't have the resource url
if (!this.resourceURL)
throw new Error("WHIP resource url not available yet");
//Request headers
const headers = {
};
//If token is set
if (this.token)
headers["Authorization"] = "Bearer " + this.token;
//Send a delete
await fetch(this.resourceURL, {
method: "DELETE",
headers
});
}
}