forked from rtc-io/rtc-taskqueue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
381 lines (298 loc) · 10.1 KB
/
index.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
var detect = require('rtc-core/detect');
var findPlugin = require('rtc-core/plugin');
var PriorityQueue = require('priorityqueuejs');
var pluck = require('whisk/pluck');
var pluckSessionDesc = pluck('sdp', 'type');
// some validation routines
var checkCandidate = require('rtc-validator/candidate');
// the sdp cleaner
var sdpclean = require('rtc-sdpclean');
var parseSdp = require('rtc-sdp');
var PRIORITY_LOW = 100;
var PRIORITY_WAIT = 1000;
// priority order (lower is better)
var DEFAULT_PRIORITIES = [
'candidate',
'setLocalDescription',
'setRemoteDescription',
'createAnswer',
'createOffer'
];
// define event mappings
var METHOD_EVENTS = {
setLocalDescription: 'setlocaldesc',
setRemoteDescription: 'setremotedesc',
createOffer: 'offer',
createAnswer: 'answer'
};
var MEDIA_MAPPINGS = {
data: 'application'
};
// define states in which we will attempt to finalize a connection on receiving a remote offer
var VALID_RESPONSE_STATES = ['have-remote-offer', 'have-local-pranswer'];
/**
# rtc-taskqueue
This is a package that assists with applying actions to an `RTCPeerConnection`
in as reliable order as possible. It is primarily used by the coupling logic
of the [`rtc-tools`](https://github.com/rtc-io/rtc-tools).
## Example Usage
For the moment, refer to the simple coupling test as an example of how to use
this package (see below):
<<< test/couple.js
**/
module.exports = function(pc, opts) {
// create the task queue
var queue = new PriorityQueue(orderTasks);
var tq = require('mbus')('', (opts || {}).logger);
// initialise task importance
var priorities = (opts || {}).priorities || DEFAULT_PRIORITIES;
var queueInterval = (opts || {}).interval || 50;
// check for plugin usage
var plugin = findPlugin((opts || {}).plugins);
// initialise state tracking
var checkQueueTimer = 0;
var defaultFail = tq.bind(tq, 'fail');
// look for an sdpfilter function (allow slight mis-spellings)
var sdpFilter = (opts || {}).sdpfilter || (opts || {}).sdpFilter;
// initialise session description and icecandidate objects
var RTCSessionDescription = (opts || {}).RTCSessionDescription ||
detect('RTCSessionDescription');
var RTCIceCandidate = (opts || {}).RTCIceCandidate ||
detect('RTCIceCandidate');
function abortQueue(err) {
console.error(err);
}
function applyCandidate(task, next) {
var data = task.args[0];
// Allow selective filtering of ICE candidates
if (opts && opts.filterCandidate && !opts.filterCandidate(data)) {
tq('ice.remote.filtered', candidate);
return next();
}
var candidate = data && data.candidate && createIceCandidate(data);
function handleOk() {
tq('ice.remote.applied', candidate);
next();
}
function handleFail(err) {
tq('ice.remote.invalid', candidate);
next(err);
}
// we have a null candidate, we have finished gathering candidates
if (! candidate) {
return next();
}
pc.addIceCandidate(candidate, handleOk, handleFail);
}
function checkQueue() {
// peek at the next item on the queue
var next = (! queue.isEmpty()) && queue.peek();
var ready = next && testReady(next);
// reset the queue timer
checkQueueTimer = 0;
// if we don't have a task ready, then abort
if (! ready) {
// if we have a task and it has expired then dequeue it
if (next && expired(next)) {
tq('task.expire', next);
queue.deq();
}
return (! queue.isEmpty()) && isNotClosed(pc) && triggerQueueCheck();
}
// properly dequeue task
next = queue.deq();
// process the task
next.fn(next, function(err) {
var fail = next.fail || defaultFail;
var pass = next.pass;
var taskName = next.name;
// if errored, fail
if (err) {
console.error(taskName + ' task failed: ', err);
return fail(err);
}
if (typeof pass == 'function') {
pass.apply(next, [].slice.call(arguments, 1));
}
triggerQueueCheck();
});
}
function cleansdp(desc) {
// ensure we have clean sdp
var sdpErrors = [];
var sdp = desc && sdpclean(desc.sdp, { collector: sdpErrors });
// if we don't have a match, log some info
if (desc && sdp !== desc.sdp) {
console.info('invalid lines removed from sdp: ', sdpErrors);
desc.sdp = sdp;
}
// if a filter has been specified, then apply the filter
if (typeof sdpFilter == 'function') {
desc.sdp = sdpFilter(desc.sdp, pc);
}
return desc;
}
function completeConnection() {
if (VALID_RESPONSE_STATES.indexOf(pc.signalingState) >= 0) {
return tq.createAnswer();
}
}
function createIceCandidate(data) {
if (plugin && typeof plugin.createIceCandidate == 'function') {
return plugin.createIceCandidate(data);
}
return new RTCIceCandidate(data);
}
function createSessionDescription(data) {
if (plugin && typeof plugin.createSessionDescription == 'function') {
return plugin.createSessionDescription(data);
}
return new RTCSessionDescription(data);
}
function emitSdp() {
tq('sdp.local', pluckSessionDesc(this.args[0]));
}
function enqueue(name, handler, opts) {
return function() {
var args = [].slice.call(arguments);
if (opts && typeof opts.processArgs == 'function') {
args = args.map(opts.processArgs);
}
queue.enq({
args: args,
name: name,
fn: handler,
// record the time at which the task was queued
start: Date.now(),
// initilaise any checks that need to be done prior
// to the task executing
checks: [ isNotClosed ].concat((opts || {}).checks || []),
// initialise the pass and fail handlers
pass: (opts || {}).pass,
fail: (opts || {}).fail
});
triggerQueueCheck();
};
}
function execMethod(task, next) {
var fn = pc[task.name];
var eventName = METHOD_EVENTS[task.name] || (task.name || '').toLowerCase();
var cbArgs = [ success, fail ];
var isOffer = task.name === 'createOffer';
function fail(err) {
tq.apply(tq, [ 'negotiate.error', task.name, err ].concat(task.args));
next(err);
}
function success() {
tq.apply(tq, [ ['negotiate', eventName, 'ok'], task.name ].concat(task.args));
next.apply(null, [null].concat([].slice.call(arguments)));
}
if (! fn) {
return next(new Error('cannot call "' + task.name + '" on RTCPeerConnection'));
}
// invoke the function
tq.apply(tq, ['negotiate.' + eventName].concat(task.args));
fn.apply(
pc,
task.args.concat(cbArgs).concat(isOffer ? generateConstraints() : [])
);
}
function expired(task) {
return (typeof task.ttl == 'number') && (task.start + task.ttl < Date.now());
}
function extractCandidateEventData(data) {
// extract nested candidate data (like we will see in an event being passed to this function)
while (data && data.candidate && data.candidate.candidate) {
data = data.candidate;
}
return data;
}
function generateConstraints() {
var allowedKeys = {
offertoreceivevideo: 'OfferToReceiveVideo',
offertoreceiveaudio: 'OfferToReceiveAudio',
icerestart: 'IceRestart',
voiceactivitydetection: 'VoiceActivityDetection'
};
var constraints = {
OfferToReceiveVideo: true,
OfferToReceiveAudio: true
};
// update known keys to match
Object.keys(opts || {}).forEach(function(key) {
if (allowedKeys[key.toLowerCase()]) {
constraints[allowedKeys[key.toLowerCase()]] = opts[key];
}
});
return { mandatory: constraints };
}
function hasLocalOrRemoteDesc(pc, task) {
return pc.__hasDesc || (pc.__hasDesc = !!pc.remoteDescription);
}
function isNotNegotiating(pc) {
return pc.signalingState !== 'have-local-offer';
}
function isNotClosed(pc) {
return pc.signalingState !== 'closed';
}
function isStable(pc) {
return pc.signalingState === 'stable';
}
function isValidCandidate(pc, data) {
return data.__valid ||
(data.__valid = checkCandidate(data.args[0]).length === 0);
}
function isConnReadyForCandidate(pc, data) {
var sdp = parseSdp(pc.remoteDescription && pc.remoteDescription.sdp);
var mediaTypes = sdp.getMediaTypes();
var sdpMid = data.args[0] && data.args[0].sdpMid;
// remap media types as appropriate
sdpMid = MEDIA_MAPPINGS[sdpMid] || sdpMid;
// the candidate is valid if we know about the media type
return (sdpMid === '') || mediaTypes.indexOf(sdpMid) >= 0;
}
function orderTasks(a, b) {
// apply each of the checks for each task
var tasks = [a,b];
var readiness = tasks.map(testReady);
var taskPriorities = tasks.map(function(task, idx) {
var ready = readiness[idx];
var priority = ready && priorities.indexOf(task.name);
return ready ? (priority >= 0 ? priority : PRIORITY_LOW) : PRIORITY_WAIT;
});
return taskPriorities[1] - taskPriorities[0];
}
// check whether a task is ready (does it pass all the checks)
function testReady(task) {
return (task.checks || []).reduce(function(memo, check) {
return memo && check(pc, task);
}, true);
}
function triggerQueueCheck() {
if (checkQueueTimer) return;
checkQueueTimer = setTimeout(checkQueue, queueInterval);
}
// patch in the queue helper methods
tq.addIceCandidate = enqueue('addIceCandidate', applyCandidate, {
processArgs: extractCandidateEventData,
checks: [hasLocalOrRemoteDesc, isValidCandidate, isConnReadyForCandidate ],
// set ttl to 5s
ttl: 5000
});
tq.setLocalDescription = enqueue('setLocalDescription', execMethod, {
processArgs: cleansdp,
pass: emitSdp
});
tq.setRemoteDescription = enqueue('setRemoteDescription', execMethod, {
processArgs: createSessionDescription,
pass: completeConnection
});
tq.createOffer = enqueue('createOffer', execMethod, {
checks: [ isNotNegotiating ],
pass: tq.setLocalDescription
});
tq.createAnswer = enqueue('createAnswer', execMethod, {
pass: tq.setLocalDescription
});
return tq;
};