-
-
Notifications
You must be signed in to change notification settings - Fork 338
/
MediaStream.js
510 lines (401 loc) · 11.7 KB
/
MediaStream.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
/**
* Expose the MediaStream class.
*/
module.exports = MediaStream;
/**
* Spec: http://w3c.github.io/mediacapture-main/#mediastream
*/
/**
* Dependencies.
*/
var debug = require('debug')('iosrtc:MediaStream'),
exec = require('cordova/exec'),
EventTarget = require('./EventTarget'),
{ MediaStreamTrack } = require('./MediaStreamTrack'),
/**
* Local variables.
*/
// Dictionary of MediaStreams (provided via getMediaStreams() class method).
// - key: MediaStream blobId.
// - value: MediaStream.
mediaStreams;
// TODO longer UUID like native call
// - "4021904575-2849079001-3048689102-1644344044-4021904575-2849079001-3048689102-1644344044"
function newMediaStreamId() {
return window.crypto.getRandomValues(new Uint32Array(4)).join('-');
}
// Save original MediaStream
var originalMediaStream = window.MediaStream || window.Blob;
//var originalMediaStream = window.Blob;
var originalMediaStreamTrack = MediaStreamTrack.originalMediaStreamTrack;
/**
* Expose the MediaStream class.
*/
function MediaStream(arg, id) {
debug('new MediaStream(arg) | [arg:%o]', arg);
// Detect native MediaStream usage
// new MediaStream(originalMediaStream) // stream
// new MediaStream(originalMediaStreamTrack[]) // tracks
if (
(!(arg instanceof window.Blob) &&
arg instanceof originalMediaStream &&
typeof arg.getBlobId === 'undefined') ||
(Array.isArray(arg) && arg[0] instanceof originalMediaStreamTrack)
) {
return new originalMediaStream(arg);
}
// new MediaStream(MediaStream) // stream
// new MediaStream(MediaStreamTrack[]) // tracks
// new MediaStream() // empty
id = id || newMediaStreamId();
var blobId = 'MediaStream_' + id;
// Extend returned MediaTream with custom MediaStream
var stream;
if (originalMediaStream !== window.Blob) {
stream = new (Function.prototype.bind.apply(originalMediaStream.bind(this), []))();
} else {
// Fallback on Blob if originalMediaStream is not a MediaStream and Emulate EventTarget
stream = new Blob([blobId], {
type: 'stream'
});
var target = document.createTextNode(null);
stream.addEventListener = target.addEventListener.bind(target);
stream.removeEventListener = target.removeEventListener.bind(target);
stream.dispatchEvent = target.dispatchEvent.bind(target);
}
Object.defineProperties(stream, Object.getOwnPropertyDescriptors(MediaStream.prototype));
// Make it an EventTarget.
EventTarget.call(stream);
// Public atributes.
stream._id = id || newMediaStreamId();
stream._active = true;
// Init Stream by Id
exec(null, null, 'iosrtcPlugin', 'MediaStream_init', [stream.id]);
// Public but internal attributes.
stream.connected = false;
stream._addedToConnection = false;
// Private attributes.
stream._audioTracks = {};
stream._videoTracks = {};
// Store the stream into the dictionary.
stream._blobId = blobId;
mediaStreams[stream._blobId] = stream;
// Convert arg to array of tracks if possible
if (arg instanceof MediaStream || arg instanceof MediaStream.originalMediaStream) {
arg = arg.getTracks();
}
if (Array.isArray(arg)) {
arg.forEach(function (track) {
stream.addTrack(track);
});
} else if (typeof arg !== 'undefined') {
throw new TypeError(
"Failed to construct 'MediaStream': No matching constructor signature."
);
}
function onResultOK(data) {
onEvent.call(stream, data);
}
exec(onResultOK, null, 'iosrtcPlugin', 'MediaStream_setListener', [stream.id]);
return stream;
}
MediaStream.prototype = Object.create(originalMediaStream.prototype, {
id: {
get: function () {
return this._id;
}
},
active: {
get: function () {
return this._active;
}
},
// Backwards compatibility.
label: {
get: function () {
return this._id;
}
},
addedToConnection: {
get: function () {
return this._addedToConnection;
},
set: function (value) {
this._addedToConnection = value;
}
}
});
Object.defineProperties(
MediaStream.prototype,
Object.getOwnPropertyDescriptors(EventTarget.prototype)
);
MediaStream.prototype.constructor = MediaStream;
// Static reference to original MediaStream
MediaStream.originalMediaStream = originalMediaStream;
/**
* Class methods.
*/
MediaStream.setMediaStreams = function (_mediaStreams) {
mediaStreams = _mediaStreams;
};
MediaStream.getMediaStreams = function () {
return mediaStreams;
};
MediaStream.create = function (dataFromEvent) {
debug('create() | [dataFromEvent:%o]', dataFromEvent);
var trackId,
track,
stream = new MediaStream([], dataFromEvent.id);
// We do not use addTrack to prevent false positive "ERROR: video track not added" and "ERROR: audio track not added"
// cause the rtcMediaStream already has them internaly.
for (trackId in dataFromEvent.audioTracks) {
if (dataFromEvent.audioTracks.hasOwnProperty(trackId)) {
track = new MediaStreamTrack(dataFromEvent.audioTracks[trackId]);
stream._audioTracks[track.id] = track;
addListenerForTrackEnded.call(stream, track);
}
}
for (trackId in dataFromEvent.videoTracks) {
if (dataFromEvent.videoTracks.hasOwnProperty(trackId)) {
track = new MediaStreamTrack(dataFromEvent.videoTracks[trackId]);
stream._videoTracks[track.id] = track;
addListenerForTrackEnded.call(stream, track);
}
}
return stream;
};
MediaStream.prototype.getBlobId = function () {
return this._blobId;
};
MediaStream.prototype.getAudioTracks = function () {
debug('getAudioTracks()');
var tracks = [],
id;
for (id in this._audioTracks) {
if (this._audioTracks.hasOwnProperty(id)) {
tracks.push(this._audioTracks[id]);
}
}
return tracks;
};
MediaStream.prototype.getVideoTracks = function () {
debug('getVideoTracks()');
var tracks = [],
id;
for (id in this._videoTracks) {
if (this._videoTracks.hasOwnProperty(id)) {
tracks.push(this._videoTracks[id]);
}
}
return tracks;
};
MediaStream.prototype.getTracks = function () {
debug('getTracks()');
var tracks = [],
id;
for (id in this._audioTracks) {
if (this._audioTracks.hasOwnProperty(id)) {
tracks.push(this._audioTracks[id]);
}
}
for (id in this._videoTracks) {
if (this._videoTracks.hasOwnProperty(id)) {
tracks.push(this._videoTracks[id]);
}
}
return tracks;
};
MediaStream.prototype.getTrackById = function (id) {
debug('getTrackById()');
return this._audioTracks[id] || this._videoTracks[id] || null;
};
MediaStream.prototype.addTrack = function (track) {
debug('addTrack() [track:%o]', track);
if (!(track instanceof MediaStreamTrack)) {
throw new Error('argument must be an instance of MediaStreamTrack');
}
if (this._audioTracks[track.id] || this._videoTracks[track.id]) {
return;
}
if (track.kind === 'audio') {
this._audioTracks[track.id] = track;
} else if (track.kind === 'video') {
this._videoTracks[track.id] = track;
} else {
throw new Error('unknown kind attribute: ' + track.kind);
}
addListenerForTrackEnded.call(this, track);
exec(null, null, 'iosrtcPlugin', 'MediaStream_addTrack', [this.id, track.id]);
this.dispatchEvent(new Event('update'));
this.emitConnected();
};
MediaStream.prototype.removeTrack = function (track) {
debug('removeTrack() [track:%o]', track);
if (!(track instanceof MediaStreamTrack)) {
throw new Error('argument must be an instance of MediaStreamTrack');
}
if (!this._audioTracks[track.id] && !this._videoTracks[track.id]) {
return;
}
if (track.kind === 'audio') {
delete this._audioTracks[track.id];
} else if (track.kind === 'video') {
delete this._videoTracks[track.id];
} else {
throw new Error('unknown kind attribute: ' + track.kind);
}
exec(null, null, 'iosrtcPlugin', 'MediaStream_removeTrack', [this.id, track.id]);
this.dispatchEvent(new Event('update'));
checkActive.call(this);
};
MediaStream.prototype.clone = function () {
var newStream = MediaStream();
this.getTracks().forEach(function (track) {
newStream.addTrack(track.clone());
});
return newStream;
};
// Backwards compatible API.
MediaStream.prototype.stop = function () {
debug('stop()');
var trackId;
for (trackId in this._audioTracks) {
if (this._audioTracks.hasOwnProperty(trackId)) {
this._audioTracks[trackId].stop();
}
}
for (trackId in this._videoTracks) {
if (this._videoTracks.hasOwnProperty(trackId)) {
this._videoTracks[trackId].stop();
}
}
};
// TODO: API methods and events.
/**
* Private API.
*/
MediaStream.prototype.emitConnected = function () {
debug('emitConnected()');
var self = this;
if (this.connected) {
return;
}
this.connected = true;
setTimeout(
function (self) {
var event = new Event('connected');
Object.defineProperty(event, 'target', { value: self, enumerable: true });
self.dispatchEvent(event);
},
0,
self
);
};
function addListenerForTrackEnded(track) {
var self = this;
track.addEventListener('ended', function () {
if (track.kind === 'audio' && !self._audioTracks[track.id]) {
return;
} else if (track.kind === 'video' && !self._videoTracks[track.id]) {
return;
}
checkActive.call(self);
});
}
function checkActive() {
// A MediaStream object is said to be active when it has at least one MediaStreamTrack
// that has not ended. A MediaStream that does not have any tracks or only has tracks
// that are ended is inactive.
var self = this,
trackId;
if (!this.active) {
return;
}
// Fixes Twilio fails to read a local video if the stream is released.
if (this._addedToConnection) {
return;
}
if (
Object.keys(this._audioTracks).length === 0 &&
Object.keys(this._videoTracks).length === 0
) {
debug('no tracks, releasing MediaStream');
release();
return;
}
for (trackId in this._audioTracks) {
if (this._audioTracks.hasOwnProperty(trackId)) {
if (this._audioTracks[trackId].readyState !== 'ended') {
return;
}
}
}
for (trackId in this._videoTracks) {
if (this._videoTracks.hasOwnProperty(trackId)) {
if (this._videoTracks[trackId].readyState !== 'ended') {
return;
}
}
}
release();
function release() {
debug('all tracks are ended, releasing MediaStream %s', self.id);
self._active = false;
self.dispatchEvent(new Event('inactive'));
// Remove the stream from the dictionary.
delete mediaStreams[self._blobId];
exec(null, null, 'iosrtcPlugin', 'MediaStream_release', [self.id]);
}
}
function onEvent(data) {
var type = data.type,
event,
track;
debug('onEvent() | [type:%s, data:%o]', type, data);
switch (type) {
case 'addtrack':
// check if a track already exists before initializing a new
// track and calling setListener again.
if (data.track.kind === 'audio') {
track = this._audioTracks[data.track.id];
} else if (data.track.kind === 'video') {
track = this._videoTracks[data.track.id];
}
if (!track) {
track = new MediaStreamTrack(data.track);
if (track.kind === 'audio') {
this._audioTracks[track.id] = track;
} else if (track.kind === 'video') {
this._videoTracks[track.id] = track;
}
addListenerForTrackEnded.call(this, track);
}
event = new Event('addtrack');
event.track = track;
this.dispatchEvent(event);
// Also emit 'update' for the MediaStreamRenderer.
this.dispatchEvent(new Event('update'));
break;
case 'removetrack':
if (data.track.kind === 'audio') {
track = this._audioTracks[data.track.id];
delete this._audioTracks[data.track.id];
} else if (data.track.kind === 'video') {
track = this._videoTracks[data.track.id];
delete this._videoTracks[data.track.id];
}
if (!track) {
throw new Error(
'"removetrack" event fired on MediaStream for a non existing MediaStreamTrack'
);
}
event = new Event('removetrack');
event.track = track;
this.dispatchEvent(event);
// Also emit 'update' for the MediaStreamRenderer.
this.dispatchEvent(new Event('update'));
// Check whether the MediaStream still is active.
checkActive.call(this);
break;
}
}