-
Notifications
You must be signed in to change notification settings - Fork 216
/
localparticipant.js
1325 lines (1156 loc) · 53.2 KB
/
localparticipant.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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const assert = require('assert');
const { DEFAULT_CHROME_SDP_SEMANTICS } = require('../../../lib/util/constants');
const sdpFormat = require('@twilio/webrtc/lib/util/sdp').getSdpFormat(DEFAULT_CHROME_SDP_SEMANTICS);
const {
connect,
createLocalAudioTrack,
createLocalTracks,
createLocalVideoTrack,
LocalDataTrack,
LocalVideoTrack
} = require('../../../lib');
const LocalTrackPublication = require('../../../lib/media/track/localtrackpublication');
const RemoteAudioTrack = require('../../../lib/media/track/remoteaudiotrack');
const RemoteAudioTrackPublication = require('../../../lib/media/track/remoteaudiotrackpublication');
const RemoteDataTrack = require('../../../lib/media/track/remotedatatrack');
const RemoteDataTrackPublication = require('../../../lib/media/track/remotedatatrackpublication');
const RemoteVideoTrack = require('../../../lib/media/track/remotevideotrack');
const RemoteVideoTrackPublication = require('../../../lib/media/track/remotevideotrackpublication');
const { flatMap } = require('../../../lib/util');
const { trackPriority: { PRIORITY_HIGH, PRIORITY_LOW, PRIORITY_STANDARD } } = require('../../../lib/util/constants');
const { getMediaSections } = require('../../../lib/util/sdp');
const { TrackNameIsDuplicatedError, TrackNameTooLongError } = require('../../../lib/util/twilio-video-errors');
const defaults = require('../../lib/defaults');
const { isChrome, isFirefox, isSafari } = require('../../lib/guessbrowser');
const { createRoom, completeRoom } = require('../../lib/rest');
const getToken = require('../../lib/token');
const {
capitalize,
combinationContext,
isRTCRtpSenderParamsSupported,
participantsConnected,
randomName,
smallVideoConstraints,
tracksSubscribed,
tracksPublished,
tracksUnpublished,
trackStarted,
waitFor,
waitForSometime,
waitForTracks
} = require('../../lib/util');
describe('LocalParticipant', function() {
// eslint-disable-next-line no-invalid-this
this.timeout(60000);
(defaults.topology !== 'peer-to-peer' ? describe : describe.skip)('"networkQualityLevelChanged" event', () => {
combinationContext([
[
[null, 1, 2, 3],
x => `when local verbosity is ${x || 'default'}`
],
[
[null, 0, 1, 2, 3],
x => `when remote verbosity is ${x || 'default'}`
]
], ([local, remote]) => {
const options = Object.assign({ name: randomName() }, defaults);
let thisRoom;
let thatRoom;
let localNqLevel;
let localNqStats;
let remoteNqLevel;
let remoteNqStats;
const nqConfig = (local || remote) ? { local, remote } : true;
function inRange(num, low, high) {
return typeof num === 'number' && low <= num && num <= high;
}
async function setup() {
const thisTracks = await createLocalTracks({ audio: true, fake: true });
thisRoom = await connect(getToken(randomName()), Object.assign({ tracks: thisTracks }, options, { networkQuality: nqConfig }));
const localNqLevelPromise = new Promise(resolve => thisRoom.localParticipant.once('networkQualityLevelChanged',
(level, stats) => resolve([level, stats])));
const remoteNqLevelPromise = inRange(nqConfig.remote, 1, 3)
? new Promise(resolve => thisRoom.on('participantConnected',
participant => participant.once('networkQualityLevelChanged', (level, stats) => resolve([level, stats]))))
: Promise.resolve([]);
const thatTracks = await createLocalTracks({ audio: true, fake: true });
thatRoom = await connect(getToken(randomName()), Object.assign({ tracks: thatTracks }, options));
[localNqLevel, localNqStats] = await localNqLevelPromise;
[remoteNqLevel, remoteNqStats] = await remoteNqLevelPromise;
}
before(async () => {
await setup();
});
it('is raised whenever network quality level for the LocalParticipant changes', () => {
assert.equal(localNqLevel, thisRoom.localParticipant.networkQualityLevel);
switch (nqConfig.local) {
case 1:
assert.equal(localNqStats, null);
break;
case 2:
assert.notEqual(localNqStats.audio, null);
assert.notEqual(localNqStats.video, null);
assert.equal(localNqStats.audio.sendStats, null);
assert.equal(localNqStats.video.sendStats, null);
assert.equal(localNqStats.audio.recvStats, null);
assert.equal(localNqStats.video.recvStats, null);
break;
case 3:
assert.notEqual(localNqStats.audio, null);
assert.notEqual(localNqStats.video, null);
assert.notEqual(localNqStats.audio.sendStats, null);
assert.notEqual(localNqStats.video.sendStats, null);
assert.notEqual(localNqStats.audio.recvStats, null);
assert.notEqual(localNqStats.video.recvStats, null);
}
assert.deepStrictEqual(localNqStats, thisRoom.localParticipant.networkQualityStats);
});
if (inRange(nqConfig.remote, 1, 3)) {
it('is raised whenever network quality level for the RemoteParticipant changes', () => {
assert.equal(remoteNqLevel, Array.from(thisRoom.participants.values())[0].networkQualityLevel);
switch (nqConfig.remote) {
case 1:
assert.equal(remoteNqStats, null);
break;
case 2:
assert.notEqual(remoteNqStats.audio, null);
assert.notEqual(remoteNqStats.video, null);
assert.equal(remoteNqStats.audio.sendStats, null);
assert.equal(remoteNqStats.video.sendStats, null);
assert.equal(remoteNqStats.audio.recvStats, null);
assert.equal(remoteNqStats.video.recvStats, null);
break;
case 3:
assert.notEqual(remoteNqStats.audio, null);
assert.notEqual(remoteNqStats.video, null);
assert.notEqual(remoteNqStats.audio.sendStats, null);
assert.notEqual(remoteNqStats.video.sendStats, null);
assert.notEqual(remoteNqStats.audio.recvStats, null);
assert.notEqual(remoteNqStats.video.recvStats, null);
}
assert.deepStrictEqual(remoteNqStats, Array.from(thisRoom.participants.values())[0].networkQualityStats);
});
}
after(() => {
if (thisRoom) {
thisRoom.disconnect();
}
if (thatRoom) {
thatRoom.disconnect();
}
});
});
});
describe('#publishTrack', function() {
// eslint-disable-next-line no-invalid-this
this.retries(2);
let room;
let sid;
let trackPublications = [];
let tracks;
async function setup() {
sid = await createRoom(name, defaults.topology);
const options = Object.assign({ name: sid, tracks: [] }, defaults);
const token = getToken(randomName());
[room, tracks] = await waitFor([
connect(token, options),
createLocalTracks({ audio: true, video: smallVideoConstraints })
], 'connect and create local tracks');
tracks.push(new LocalDataTrack());
}
[
[
'when three LocalTracks (audio, video, and data) are published sequentially',
async () => {
trackPublications = [
await room.localParticipant.publishTrack(tracks[0]),
await room.localParticipant.publishTrack(tracks[1]),
await room.localParticipant.publishTrack(tracks[2])
];
}
],
[
'when three LocalTracks (audio, video, and data) are published together',
async () => {
trackPublications = await waitFor(tracks.map(track => {
return room.localParticipant.publishTrack(track);
}), 'publish tracks');
}
]
].forEach(([ctx, publish]) => {
context(ctx, () => {
before(async () => {
await waitFor(setup(), 'setup');
await waitFor(publish(), 'publish');
});
it('should return LocalTrackPublications for each LocalTrack', () => {
trackPublications.forEach((localTrackPublication, i) => {
const track = tracks[i];
assert(localTrackPublication instanceof LocalTrackPublication);
assert.equal(localTrackPublication.track, track);
assert(localTrackPublication.trackSid.match(/^MT[a-f0-9]{32}$/));
});
});
it('should add each of the LocalTracks to the LocalParticipant\'s ._tracks and their respective kinds\' collections', () => {
tracks.forEach(track => {
assert.equal(room.localParticipant._tracks.get(track.id), track);
assert.equal(room.localParticipant[`_${track.kind}Tracks`].get(track.id), track);
});
});
it('should add each of the LocalTrackPublications to the LocalParticipant\'s .tracks and their respective kinds\' collections', () => {
trackPublications.forEach(trackPublication => {
assert.equal(room.localParticipant.tracks.get(trackPublication.trackSid), trackPublication);
assert.equal(room.localParticipant[`${trackPublication.track.kind}Tracks`].get(trackPublication.trackSid), trackPublication);
});
});
after(() => {
trackPublications = [];
tracks.splice(0).forEach(track => track.kind !== 'data' && track.stop());
if (room) {
room.disconnect();
}
return completeRoom(sid);
});
});
});
context('when a LocalTrack is published to two Rooms', function() {
// eslint-disable-next-line no-invalid-this
this.retries(2);
let anotherRoom;
let anotherSid;
before(async () => {
anotherSid = await createRoom(randomName(), defaults.topology);
const options = Object.assign({ name: anotherSid, tracks: [] }, defaults);
const token = getToken(randomName());
[anotherRoom] = await waitFor([
connect(token, options),
setup()
], 'connect and setup');
trackPublications = await waitFor([
room.localParticipant.publishTrack(tracks[0], { priority: PRIORITY_LOW }),
anotherRoom.localParticipant.publishTrack(tracks[0], { priority: PRIORITY_HIGH })
], 'publish tracks');
});
it('should add the LocalTrack to the LocalParticipant\'s ._tracks in both Rooms', () => {
assert.equal(room.localParticipant._tracks.get(tracks[0].id), tracks[0]);
assert.equal(anotherRoom.localParticipant._tracks.get(tracks[0].id), tracks[0]);
});
it('should create two different LocalTrackPublications', () => {
assert(trackPublications[0] instanceof LocalTrackPublication);
assert(trackPublications[1] instanceof LocalTrackPublication);
assert.notEqual(trackPublications[0], trackPublications[1]);
});
it('should add each LocalTrackPublication to its corresponding Room\'s LocalParticipant .tracks', () => {
const localTrackPublication1 = [...room.localParticipant.tracks.values()].find(
localTrackPublication => localTrackPublication.track === tracks[0]);
const localTrackPublication2 = [...anotherRoom.localParticipant.tracks.values()].find(
localTrackPublication => localTrackPublication.track === tracks[0]);
assert.equal(localTrackPublication1.track, tracks[0]);
assert.equal(localTrackPublication2.track, tracks[0]);
});
it('should assign different SIDs to the two LocalTrackPublications', () => {
assert.notEqual(trackPublications[0].trackSid, trackPublications[1].trackSid);
});
it('should set the appropriate priority values to the two LocalTrackPublications', () => {
const localTrackPublication1 = [...room.localParticipant.tracks.values()].find(
localTrackPublication => localTrackPublication.track === tracks[0]);
const localTrackPublication2 = [...anotherRoom.localParticipant.tracks.values()].find(
localTrackPublication => localTrackPublication.track === tracks[0]);
assert.equal(localTrackPublication1.priority, PRIORITY_LOW);
assert.equal(localTrackPublication2.priority, PRIORITY_HIGH);
});
after(() => {
trackPublications = [];
tracks.splice(0).forEach(track => track.kind !== 'data' && track.stop());
[anotherRoom, room].forEach(room => room && room.disconnect());
return Promise.all([anotherSid, sid].map(completeRoom));
});
});
context('when the Room disconnects while a LocalTrack is being published', () => {
before(setup);
it('should reject the Promise returned by LocalParticipant#publishTrack with an Error', async () => {
try {
const promise = room.localParticipant.publishTrack(tracks[0]);
room.disconnect();
await promise;
} catch (error) {
assert.equal(error.message, 'LocalParticipant disconnected');
return;
}
throw new Error('Unexpected resolution');
});
after(() => {
trackPublications = [];
tracks.splice(0).forEach(track => track.kind !== 'data' && track.stop());
return completeRoom(sid);
});
});
combinationContext([
[
[true, false],
x => `called with ${x ? 'an enabled' : 'a disabled'}`
],
[
['audio', 'video', 'data'],
x => `Local${capitalize(x)}Track`
],
[
[true, false],
x => `with${x ? '' : 'out'} a name for the LocalTrack`
],
[
[undefined, PRIORITY_HIGH, PRIORITY_LOW, PRIORITY_STANDARD],
x => `with${x ? ` priority "${x}"` : 'out specifying a priority'}`
],
[
['never', 'previously'],
x => `that has ${x} been published`
],
[
[true],
// eslint-disable-next-line no-unused-vars
_x => defaults.topology === 'peer-to-peer' ? '(@unstable)' : ''
]
], ([isEnabled, kind, withName, priority, when]) => {
// eslint-disable-next-line no-warning-comments
// TODO(mmalavalli): Enable this scenario for Firefox when the following
// bug is fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=1526253
if (isFirefox && kind === 'data' && when === 'previously') {
return;
}
// eslint-disable-next-line no-warning-comments
// TODO(mmalavalli): Until we find out why Travis is failing tests due
// to not being able to create enough RTCPeerConnections, we will enable
// testing for only when priority is set to "high". (JSDK-2417)
if (priority !== PRIORITY_HIGH) {
return;
}
let thisRoom;
let thisParticipant;
let thisLocalTrackPublication;
let thisTrack;
let thoseRooms;
let thoseParticipants;
let thoseTracksBefore;
let thoseTracksPublished;
let thoseTracksSubscribed;
let thoseTracksMap;
const localTrackNameByKind = {
audio: 'foo',
video: 'bar',
data: 'baz'
}[kind];
before(async () => {
sid = await createRoom(randomName(), defaults.topology);
const identities = [randomName(), randomName(), randomName()];
const options = Object.assign({ name: sid }, defaults);
const localTrackOptions = Object.assign(
withName
? { name: localTrackNameByKind }
: {},
smallVideoConstraints);
thisTrack = await {
audio: createLocalAudioTrack,
video: createLocalVideoTrack,
data() { return new LocalDataTrack(); }
}[kind](localTrackOptions);
// eslint-disable-next-line no-warning-comments
// TODO(mroberts): Really this test needs to be refactored so that only
// the LocalAudio- and LocalVideo-Track tests test the enable/disable
// functionality.
if (kind !== 'data') {
thisTrack.enable(isEnabled);
}
const tracks = when === 'previously'
? [thisTrack]
: [];
const thisIdentity = identities[0];
const thisToken = getToken(thisIdentity);
const theseOptions = Object.assign({ tracks }, options);
thisRoom = await connect(thisToken, theseOptions);
thisParticipant = thisRoom.localParticipant;
await waitFor(tracksPublished(thisParticipant, tracks.length), `tracksPublished: ${sid}`);
const thoseIdentities = identities.slice(1);
const thoseTokens = thoseIdentities.map(getToken);
const thoseOptions = Object.assign({ tracks: [] }, options);
thoseRooms = await waitFor(thoseTokens.map(thatToken => {
return connect(thatToken, thoseOptions);
}), `Rooms to connect: ${sid}`);
await waitFor([thisRoom].concat(thoseRooms).map(room => {
return participantsConnected(room, identities.length - 1);
}), `all Participants to connect: ${sid}`);
thoseParticipants = thoseRooms.map(thatRoom => {
return thatRoom.participants.get(thisParticipant.sid);
});
await waitFor(thoseParticipants.map(thatParticipant => {
return tracksSubscribed(thatParticipant, tracks.length);
}), `tracksSubscribed: ${sid}`);
thoseTracksBefore = flatMap(thoseParticipants, thatParticipant => {
return [...thatParticipant._tracks.values()];
});
if (when === 'previously') {
thisParticipant.unpublishTrack(thisTrack);
await waitFor(thoseParticipants.map(thatParticipant => {
return tracksUnpublished(thatParticipant, tracks.length);
}), `tracksUnpublished: ${sid}`);
// NOTE(mmalavalli): Even though the "trackUnpublished" events are
// fired on the RemoteParticipants, we need to make sure that the
// SDP negotiation is complete before we re-publish the LocalTrack.
// Therefore we wait for 2 seconds.
await waitForSometime(2000);
}
const thisLocalTrackPublicationPromise = priority ? thisParticipant.publishTrack(thisTrack, { priority }) : thisParticipant.publishTrack(thisTrack);
const thoseTracksPublishedPromise = thoseParticipants.map(thatParticipant => waitForTracks('trackPublished', thatParticipant, 1));
const thoseTracksSubscribedPromise = thoseParticipants.map(thatParticipant => waitForTracks('trackSubscribed', thatParticipant, 1));
thisLocalTrackPublication = await waitFor(thisLocalTrackPublicationPromise, `Track to publish: ${sid}`);
thoseTracksPublished = await waitFor(thoseTracksPublishedPromise, `Participants to receive trackPublished: ${sid}`);
thoseTracksSubscribed = await waitFor(thoseTracksSubscribedPromise, `Participants to receive trackSubscribed: ${sid}`);
thoseTracksPublished = flatMap(thoseTracksPublished);
thoseTracksSubscribed = flatMap(thoseTracksSubscribed);
thoseTracksMap = {
trackPublished: thoseTracksPublished,
trackSubscribed: thoseTracksSubscribed
};
});
after(() => {
if (kind !== 'data') {
thisTrack.stop();
}
[thisRoom, ...thoseRooms].forEach(room => room && room.disconnect());
return completeRoom(sid);
});
it('should raise a "trackPublished" event on the corresponding RemoteParticipant with a RemoteTrackPublication', () => {
const thoseTrackPublications = thoseTracksMap.trackPublished;
thoseTrackPublications.forEach(thatPublication => assert(thatPublication instanceof {
audio: RemoteAudioTrackPublication,
data: RemoteDataTrackPublication,
video: RemoteVideoTrackPublication
}[kind]));
});
['isTrackEnabled', ['publishPriority', 'priority'], 'trackName', 'trackSid'].forEach(propOrPropPair => {
const [remoteProp, localProp] = Array.isArray(propOrPropPair) ? propOrPropPair : [propOrPropPair, propOrPropPair];
it(`should set the RemoteTrackPublication's .${remoteProp} to the LocalTrackPublication's .${localProp}`, () => {
const thoseTrackPublications = thoseTracksMap.trackPublished;
thoseTrackPublications.forEach(thatPublication => assert.equal(thatPublication[remoteProp], thisLocalTrackPublication[localProp]));
});
});
it('should raise a "trackSubscribed" event on the corresponding RemoteParticipants with a RemoteTrack', () => {
const thoseTracks = thoseTracksMap.trackSubscribed;
thoseTracks.forEach(thatTrack => assert(thatTrack instanceof {
audio: RemoteAudioTrack,
video: RemoteVideoTrack,
data: RemoteDataTrack
}[thatTrack.kind]));
});
describe('should raise a "trackSubscribed" event on the corresponding RemoteParticipants with a RemoteTrack and', () => {
it('should set the RemoteTrack\'s .sid to the LocalTrackPublication\'s .trackSid', () => {
const thoseTracks = thoseTracksMap.trackSubscribed;
thoseTracks.forEach(thatTrack => assert.equal(thatTrack.sid, thisLocalTrackPublication.trackSid));
});
it(`should set each RemoteTrack's .kind to "${kind}"`, () => {
const thoseTracks = thoseTracksMap.trackSubscribed;
thoseTracks.forEach(thatTrack => assert.equal(thatTrack.kind, kind));
});
it('should set each RemoteTrack\'s .name to the LocalTrackPublication\'s .trackName', () => {
const thoseTracks = thoseTracksMap.trackSubscribed;
thoseTracks.forEach(thatTrack => assert.equal(thatTrack.name, thisLocalTrackPublication.trackName));
});
if (kind === 'data') {
['string', 'arraybuffer'].forEach(dataType => {
it(`should transmit any ${dataType} data sent through the LocalDataTrack to the Room to each RemoteDataTrack`, async () => {
const data = dataType === 'string' ? 'foo' : new Uint32Array([1, 2, 3]);
const thoseTracks = thoseTracksMap.trackSubscribed;
const thoseTracksReceivedData = thoseTracks.map(track => new Promise(resolve => track.once('message', resolve)));
const dataChannelSendInterval = setInterval(() => thisTrack.send(dataType === 'string' ? data : data.buffer), 1000);
const receivedData = await waitFor(thoseTracksReceivedData, 'thoseTracksReceivedData');
clearInterval(dataChannelSendInterval);
receivedData.forEach(item => dataType === 'string' ? assert.equal(item, data) : assert.deepEqual(new Uint32Array(item), data));
});
});
} else {
it(`should set each RemoteTrack's .isEnabled state to ${isEnabled}`, () => {
const thoseTracks = thoseTracksMap.trackSubscribed;
thoseTracks.forEach(thatTrack => assert.equal(thatTrack.isEnabled, isEnabled));
});
}
if (when === 'previously') {
it('the RemoteTrack should be a new RemoteTrack instance', () => {
const thoseTracks = thoseTracksMap.trackSubscribed;
assert.equal(thoseTracksBefore.length, thoseTracks.length);
thoseTracksBefore.forEach((thatTrackBefore, i) => {
const thatTrackAfter = thoseTracks[i];
if (!isFirefox && !isSafari) {
assert.notEqual(thatTrackAfter.sid, thatTrackBefore.sid);
}
assert.equal(thatTrackAfter.kind, thatTrackBefore.kind);
assert.equal(thatTrackAfter.enabled, thatTrackBefore.enabled);
assert.notEqual(thatTrackAfter, thatTrackBefore);
});
});
}
});
});
// NOTE(mroberts): Waiting on a Group Rooms deploy.
describe('"trackPublicationFailed" event', () => {
combinationContext([
[
[
{
createLocalTrack() {
const { name } = tracks.find(track => track.kind === 'audio');
return createLocalAudioTrack({ name });
},
scenario: 'a LocalTrack whose name is the same as one of the currently published LocalTracks',
TwilioError: TrackNameIsDuplicatedError
},
{
createLocalTrack() {
const name = '0'.repeat(129);
return createLocalAudioTrack({ name });
},
scenario: 'a LocalTrack whose name is too long',
TwilioError: TrackNameTooLongError
}
],
({ scenario }) => `called with ${scenario}`
]
], ([{ createLocalTrack, scenario, TwilioError }]) => {
// eslint-disable-next-line no-void
void scenario;
let track;
let trackPublicationFailed;
before(async () => {
await setup();
await room.localParticipant.publishTracks(tracks);
track = await createLocalTrack();
try {
await room.localParticipant.publishTrack(track);
} catch (error) {
trackPublicationFailed = error;
return;
}
throw new Error('Unexpected publication');
});
it(`should emit "trackPublicationFailed" on the Room's LocalParticipant with a ${TwilioError.name}`, () => {
assert(trackPublicationFailed instanceof TwilioError);
});
it(`should reject the Promise returned by LocalParticipant#publishTrack with a ${TwilioError.name}`, () => {
assert(trackPublicationFailed instanceof TwilioError);
});
after(() => {
track.stop();
tracks.splice(0).forEach(track => track.stop && track.stop());
if (room) {
room.disconnect();
}
return completeRoom(sid);
});
});
});
});
describe('#unpublishTrack', function() {
// eslint-disable-next-line no-invalid-this
this.retries(2);
combinationContext([
[
[true, false],
x => `called with ${x ? 'an enabled' : 'a disabled'}`
],
[
['audio', 'video', 'data'],
x => `Local${capitalize(x)}Track`
],
[
['published', 'published, unpublished, and then published again'],
x => 'that was ' + x
],
[
[true],
// eslint-disable-next-line no-unused-vars
_x => defaults.topology === 'peer-to-peer' ? '(@unstable)' : ''
]
], ([isEnabled, kind, when]) => {
// eslint-disable-next-line no-warning-comments
// TODO(mmalavalli): Enable this scenario for Firefox when the following
// bug is fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=1526253
// eslint-disable-next-line no-warning-comments
// TODO(mmalavalli): Disabling DataTracks for Firefox P2P due to this
// bug: JSDK-2630. Re-enable once fixed.
if (isFirefox && kind === 'data' && (when !== 'published' || defaults.topology === 'peer-to-peer')) {
return;
}
let sid;
let thisRoom;
let thisParticipant;
let thisLocalTrackPublication;
let thisTrack;
let thoseRooms;
let thoseParticipants;
let thosePublicationsUnsubscribed;
let thoseTracksUnpublished;
let thoseTracksUnsubscribed;
let thoseTracksMap;
before(async () => {
sid = await createRoom(randomName(), defaults.topology);
const identities = [randomName(), randomName(), randomName()];
const options = Object.assign({ name: sid }, defaults);
thisTrack = await {
audio: createLocalAudioTrack,
video() { return createLocalVideoTrack(smallVideoConstraints); },
data() { return new LocalDataTrack(); }
}[kind]();
// eslint-disable-next-line no-warning-comments
// TODO(mroberts): Really this test needs to be refactored so that only
// the LocalAudio- and LocalVideo-Track tests test the enable/disable
// functionality.
if (kind !== 'data') {
thisTrack.enable(isEnabled);
}
const tracks = [thisTrack];
const thisIdentity = identities[0];
const thisToken = getToken(thisIdentity);
const theseOptions = Object.assign({ tracks }, options);
thisRoom = await connect(thisToken, theseOptions);
thisParticipant = thisRoom.localParticipant;
await tracksPublished(thisParticipant, tracks.length);
const thoseIdentities = identities.slice(1);
const thoseTokens = thoseIdentities.map(getToken);
const thoseOptions = Object.assign({ tracks: [] }, options);
thoseRooms = await waitFor(thoseTokens.map(thatToken => {
return connect(thatToken, thoseOptions);
}), `Rooms to get connected: ${sid}`);
await waitFor([thisRoom].concat(thoseRooms).map(room => {
return participantsConnected(room, identities.length - 1);
}), `all Participants to get connected: ${sid}`);
thoseParticipants = thoseRooms.map(thatRoom => {
return thatRoom.participants.get(thisParticipant.sid);
});
await waitFor(thoseParticipants.map(thatParticipant => {
return tracksSubscribed(thatParticipant, tracks.length);
}), `Track to get subscribed: ${sid}`);
if (when !== 'published') {
thisParticipant.unpublishTrack(thisTrack);
await waitFor(thoseParticipants.map(thatParticipant => {
return tracksUnpublished(thatParticipant, tracks.length - 1);
}), `Track to get unpublished: ${sid}`);
// NOTE(mmalavalli): Even though the "trackUnpublished" events are
// fired on the RemoteParticipants, we need to make sure that the
// SDP negotiation is complete before we re-publish the LocalTrack.
// Therefore we wait for 2 seconds.
await waitForSometime(2000);
await waitFor(thisParticipant.publishTrack(thisTrack), `Track to get re-published: ${sid}`);
await waitFor(thoseParticipants.map(thatParticipant => {
return tracksSubscribed(thatParticipant, tracks.length);
}), `Tracks to get re-subscribed: ${sid}`);
}
thisLocalTrackPublication = thisParticipant.unpublishTrack(thisTrack);
thosePublicationsUnsubscribed = flatMap(thoseParticipants, participant => [...participant.tracks.values()]).map(publication => {
return new Promise(resolve => publication.once('unsubscribed', resolve));
});
[thoseTracksUnsubscribed, thoseTracksUnpublished] = await waitFor([
'trackUnsubscribed',
'trackUnpublished'
].map(event => {
return Promise.all(thoseParticipants.map(async thatParticipant => {
const [trackOrPublication] = await waitForTracks(event, thatParticipant, 1);
return trackOrPublication;
}));
}), `tracks to get unsubscribed and unpublished: ${sid}`);
thoseTracksMap = {
trackUnpublished: thoseTracksUnpublished,
trackUnsubscribed: thoseTracksUnsubscribed
};
});
after(() => {
if (kind !== 'data') {
thisTrack.stop();
}
[thisRoom, ...thoseRooms].forEach(room => room && room.disconnect());
return completeRoom(sid);
});
it('should raise "unsubscribed" events on the corresponding RemoteParticipant\'s RemoteTrackPublications', async () => {
const thoseTracks = await waitFor(thosePublicationsUnsubscribed, 'thosePublicationsUnsubscribed');
assert.deepEqual(thoseTracks, thoseTracksMap.trackUnsubscribed);
});
it('should raise a "trackUnpublished" event on the corresponding RemoteParticipant with a RemoteTrackPublication', () => {
const thoseTrackPublications = thoseTracksMap.trackUnpublished;
thoseTrackPublications.forEach(thatPublication => assert(thatPublication instanceof {
audio: RemoteAudioTrackPublication,
data: RemoteDataTrackPublication,
video: RemoteVideoTrackPublication
}[kind]));
});
['isTrackEnabled', 'trackName', 'trackSid'].forEach(prop => {
it(`should set the RemoteTrackPublication's .${prop} to the LocalTrackPublication's .${prop}`, () => {
const thoseTrackPublications = thoseTracksMap.trackUnpublished;
thoseTrackPublications.forEach(thatPublication => assert.equal(thatPublication[prop], thisLocalTrackPublication[prop]));
});
});
it('should raise a "trackUnsubscribed" event on the corresponding RemoteParticipants with a RemoteTrack', () => {
const thoseTracks = thoseTracksMap.trackUnsubscribed;
thoseTracks.forEach(thatTrack => assert(thatTrack instanceof {
audio: RemoteAudioTrack,
video: RemoteVideoTrack,
data: RemoteDataTrack
}[thatTrack.kind]));
});
describe('should raise a "trackUnsubscribed" event on the corresponding RemoteParticipants with a RemoteTrack and', () => {
it('should set the RemoteTrack\'s .sid to the LocalTrackPublication\'s .trackSid', () => {
const thoseTracks = thoseTracksMap.trackUnsubscribed;
thoseTracks.forEach(thatTrack => assert.equal(thatTrack.sid, thisLocalTrackPublication.trackSid));
});
it(`should set each RemoteTrack's .kind to "${kind}"`, () => {
const thoseTracks = thoseTracksMap.trackUnsubscribed;
thoseTracks.forEach(thatTrack => assert.equal(thatTrack.kind, kind));
});
if (kind !== 'data') {
it(`should set each RemoteTrack's .isEnabled state to ${isEnabled}`, () => {
const thoseTracks = thoseTracksMap.trackUnsubscribed;
thoseTracks.forEach(thatTrack => assert.equal(thatTrack.isEnabled, isEnabled));
});
}
});
});
});
// NOTE(mroberts): The following test reproduces the issue described in
//
// https://github.com/twilio/twilio-video.js/issues/72
//
describe('#unpublishTrack and #publishTrack called with two different LocalVideoTracks in quick succession', () => {
let sid;
let thisRoom;
let thisParticipant;
let thisLocalTrackPublication1;
let thisLocalTrackPublication2;
let thisTrack1;
let thisTrack2;
let thatRoom;
let thatParticipant;
let thatTrackUnpublished;
let thatTrackUnsubscribed;
let thatTrackSubscribed;
let thatTrackPublished;
let thatTracksPublished;
let thatTracksUnpublished;
before(async () => {
sid = await createRoom(randomName(), defaults.topology);
const constraints = { video: smallVideoConstraints, fake: true };
// Answerer
const thoseOptions = Object.assign({ name: sid, tracks: [] }, defaults);
thatRoom = await connect(getToken(randomName()), thoseOptions);
[thisTrack1] = await createLocalTracks(constraints);
// Offerer
const theseOptions = Object.assign({ name: sid, tracks: [thisTrack1] }, defaults);
thisRoom = await connect(getToken(randomName()), theseOptions);
thisParticipant = thisRoom.localParticipant;
await Promise.all([thisRoom, thatRoom].map(room => participantsConnected(room, 1)));
thatParticipant = thatRoom.participants.get(thisParticipant.sid);
assert(thatParticipant);
await tracksSubscribed(thatParticipant, thisParticipant._tracks.size);
// NOTE(mroberts): Wait 5 seconds.
await new Promise(resolve => setTimeout(resolve, 5 * 1000));
const trackUnpublishedPromise = new Promise(resolve => thatParticipant.once('trackUnpublished', resolve));
const trackUnsubscribedPromise = new Promise(resolve => thatParticipant.once('trackUnsubscribed', resolve));
const trackPublishedPromise = new Promise(resolve => thatParticipant.once('trackPublished', resolve));
const trackSubscribedPromise = new Promise(resolve => thatParticipant.once('trackSubscribed', resolve));
thisLocalTrackPublication1 = thisParticipant.unpublishTrack(thisTrack1);
[thisTrack2] = await createLocalTracks(constraints);
[thatTrackUnpublished, thatTrackUnsubscribed, thatTrackPublished, thatTrackSubscribed, thisLocalTrackPublication2] = await Promise.all([
trackUnpublishedPromise,
trackUnsubscribedPromise,
trackPublishedPromise,
trackSubscribedPromise,
thisParticipant.publishTrack(thisTrack2)
]);
thatTracksPublished = {
trackPublished: thatTrackPublished,
trackSubscribed: thatTrackSubscribed
};
thatTracksUnpublished = {
trackUnpublished: thatTrackUnpublished,
trackUnsubscribed: thatTrackUnsubscribed
};
});
after(() => {
thisTrack1.stop();
thisTrack2.stop();
[thisRoom, thatRoom].forEach(room => room && room.disconnect());
return completeRoom(sid);
});
it('should eventually raise a "trackUnpublished" event for the unpublished LocalVideoTrack', () => {
const thatTrackPublication = thatTracksUnpublished.trackUnpublished;
assert(thatTrackPublication instanceof RemoteVideoTrackPublication);
['isTrackEnabled', 'kind', 'trackName', 'trackSid'].forEach(prop => {
assert.equal(thatTrackPublication[prop], thisLocalTrackPublication1[prop]);
});
});
it('should eventually raise a "trackPublished" event for the published LocalVideoTrack', () => {
const thatTrackPublication = thatTracksPublished.trackPublished;
assert(thatTrackPublication instanceof RemoteVideoTrackPublication);
['isTrackEnabled', 'kind', 'trackName', 'trackSid'].forEach(prop => {
assert.equal(thatTrackPublication[prop], thisLocalTrackPublication2[prop]);
});
});
it('should eventually raise a "trackUnsubscribed" event for the unpublished LocalVideoTrack', () => {
const thatTrack = thatTracksUnpublished.trackUnsubscribed;
assert.equal(thatTrack.sid, thisLocalTrackPublication1.trackSid);
assert.equal(thatTrack.kind, thisLocalTrackPublication1.kind);
assert.equal(thatTrack.enabled, thisLocalTrackPublication1.enabled);
if (isChrome && sdpFormat === 'planb') {
assert.equal(thatTrack.mediaStreamTrack.readyState, 'ended');
}
});
it('should eventually raise a "trackSubscribed" event for the published LocalVideoTrack', () => {
const thatTrack = thatTracksPublished.trackSubscribed;
assert.equal(thatTrack.sid, thisLocalTrackPublication2.trackSid);
assert.equal(thatTrack.kind, thisLocalTrackPublication2.kind);
assert.equal(thatTrack.enabled, thisLocalTrackPublication2.enabled);
assert.equal(thatTrack.mediaStreamTrack.readyState, thisTrack2.mediaStreamTrack.readyState);
});
it('should eventually raise a "trackStarted" event for the published LocalVideoTrack', async () => {
if (isFirefox /* && isGroupRoom */) {
return;
}
await trackStarted(thatTrackSubscribed);
});
});
describe('#publishTrack called twice in quick succession', () => {
function kindCombination(contextPrefix) {
return [
[
{
createLocalTrack: () => createLocalAudioTrack({ fake: true }),
kind: 'audio',
RemoteTrackPublication: RemoteAudioTrackPublication
},
{
createLocalTrack: () => new LocalDataTrack(),
kind: 'data',
RemoteTrackPublication: RemoteDataTrackPublication
},
{
createLocalTrack: () => createLocalVideoTrack(smallVideoConstraints),
kind: 'video',
RemoteTrackPublication: RemoteVideoTrackPublication
}
],
({ kind }) => `${contextPrefix} a Local${capitalize(kind)}Track`
];
}
combinationContext(['with', 'and'].map(kindCombination), ([kindCombination1, kindCombination2]) => {
const createLocalTrack1 = kindCombination1.createLocalTrack;
const createLocalTrack2 = kindCombination2.createLocalTrack;
const kind1 = kindCombination1.kind;
const kind2 = kindCombination2.kind;
const RemoteTrackPublication1 = kindCombination1.RemoteTrackPublication;
const RemoteTrackPublication2 = kindCombination2.RemoteTrackPublication;
let sid;
let thisRoom;
let thisParticipant;
let thisLocalTrack1;
let thisLocalTrack2;
let thisLocalTrackPublication1;
let thisLocalTrackPublication2;
let thatRoom;
let thatParticipant;
let thoseTracks1;
let thoseTracks2;
before(async () => {
sid = await createRoom(randomName(), defaults.topology);
// Answerer
const thoseOptions = Object.assign({ name: sid, tracks: [] }, defaults);
thatRoom = await connect(getToken(randomName()), thoseOptions);
[thisLocalTrack1, thisLocalTrack2] = [
await createLocalTrack1(),
await createLocalTrack2()
];
// Offerer
const theseOptions = Object.assign({ name: sid, tracks: [] }, defaults);
thisRoom = await connect(getToken(randomName()), theseOptions);
thisParticipant = thisRoom.localParticipant;