-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathRoom.js
885 lines (789 loc) · 28.5 KB
/
Room.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
import ErizoConnectionManager from './ErizoConnectionManager';
import ConnectionHelpers from './utils/ConnectionHelpers';
import { EventDispatcher, StreamEvent, RoomEvent } from './Events';
import { Socket } from './Socket';
import Stream from './Stream';
import ErizoMap from './utils/ErizoMap';
import Base64 from './utils/Base64';
import Logger from './utils/Logger';
/*
* Class Room represents a Licode Room. It will handle the connection, local stream publication and
* remote stream subscription.
* Typical Room initialization would be:
* var room = Erizo.Room({token:'213h8012hwduahd-321ueiwqewq'});
* It also handles RoomEvents and StreamEvents. For example:
* Event 'room-connected' points out that the user has been successfully connected to the room.
* Event 'room-disconnected' shows that the user has been already disconnected.
* Event 'stream-added' indicates that there is a new stream available in the room.
* Event 'stream-removed' shows that a previous available stream has been removed from the room.
*/
const Room = (altIo, altConnectionHelpers, altConnectionManager, specInput) => {
const spec = specInput;
const that = EventDispatcher(specInput);
const DISCONNECTED = 0;
const CONNECTING = 1;
const CONNECTED = 2;
that.remoteStreams = ErizoMap();
that.localStreams = ErizoMap();
that.roomID = '';
that.state = DISCONNECTED;
that.p2p = false;
that.ConnectionHelpers =
altConnectionHelpers === undefined ? ConnectionHelpers : altConnectionHelpers;
that.erizoConnectionManager =
altConnectionManager === undefined ? new ErizoConnectionManager()
: new altConnectionManager.ErizoConnectionManager();
let socket = Socket(altIo);
that.socket = socket;
let remoteStreams = that.remoteStreams;
let localStreams = that.localStreams;
// Private functions
const removeStream = (streamInput) => {
const stream = streamInput;
if (stream.stream) {
// Remove HTML element
stream.hide();
stream.stop();
stream.close();
delete stream.stream;
}
// Close PC stream
if (stream.pc) {
if (stream.local && that.p2p) {
stream.pc.forEach((connection, id) => {
connection.close();
stream.pc.remove(id);
});
} else {
stream.pc.removeStream(stream);
that.erizoConnectionManager.maybeCloseConnection(stream.pc);
delete stream.pc;
}
}
};
const onStreamFailed = (streamInput, message) => {
const stream = streamInput;
if (that.state !== DISCONNECTED && stream && !stream.failed) {
stream.failed = true;
const streamFailedEvt = StreamEvent(
{ type: 'stream-failed',
msg: message || 'Stream failed after connection',
stream });
that.dispatchEvent(streamFailedEvt);
if (stream.local) {
that.unpublish(stream);
} else {
that.unsubscribe(stream);
}
}
};
const dispatchStreamSubscribed = (streamInput, evt) => {
const stream = streamInput;
// Draw on html
Logger.info('Stream subscribed');
stream.stream = evt.stream;
if (!that.p2p) {
stream.pc.addStream(stream);
}
const evt2 = StreamEvent({ type: 'stream-subscribed', stream });
that.dispatchEvent(evt2);
};
const getP2PConnectionOptions = (stream, peerSocket) => {
const options = {
callback(msg) {
socket.sendSDP('signaling_message', {
streamId: stream.getID(),
peerSocket,
msg });
},
audio: stream.hasAudio(),
video: stream.hasVideo(),
iceServers: that.iceServers,
maxAudioBW: stream.maxAudioBW,
maxVideoBW: stream.maxVideoBW,
limitMaxAudioBW: spec.maxAudioBW,
limitMaxVideoBW: spec.maxVideoBW,
forceTurn: stream.forceTurn,
p2p: true,
};
return options;
};
const createRemoteStreamP2PConnection = (streamInput, peerSocket) => {
const stream = streamInput;
stream.addPC(that.erizoConnectionManager.getOrBuildErizoConnection(
getP2PConnectionOptions(stream, peerSocket)));
stream.on('added', dispatchStreamSubscribed.bind(null, stream));
stream.on('icestatechanged', (evt) => {
Logger.info(`${stream.getID()} - iceConnectionState: ${evt.msg.state}`);
if (evt.msg.state === 'failed') {
onStreamFailed(stream);
}
});
};
const createLocalStreamP2PConnection = (streamInput, peerSocket) => {
const stream = streamInput;
const connection = that.erizoConnectionManager.getOrBuildErizoConnection(
getP2PConnectionOptions(stream, peerSocket));
stream.addPC(connection, peerSocket);
stream.on('icestatechanged', (evt) => {
Logger.info(`${stream.getID()} - iceConnectionState: ${evt.msg.state}`);
if (evt.msg.state === 'failed') {
stream.pc.get(peerSocket).close();
stream.pc.remove(peerSocket);
}
});
connection.addStream(stream);
connection.createOffer();
};
const removeLocalStreamP2PConnection = (streamInput, peerSocket) => {
const stream = streamInput;
if (stream.pc === undefined || !stream.pc.has(peerSocket)) {
return;
}
const pc = stream.pc.get(peerSocket);
pc.close();
stream.pc.remove(peerSocket);
};
const getErizoConnectionOptions = (stream, options, isRemote) => {
const connectionOpts = {
callback(message, streamId = stream.getID()) {
Logger.info('Sending message', message, stream.getID(), streamId);
socket.sendSDP('signaling_message', {
streamId,
msg: message,
browser: stream.pc && stream.pc.browser }, undefined, () => {});
},
nop2p: true,
audio: options.audio && stream.hasAudio(),
video: options.video && stream.hasVideo(),
maxAudioBW: options.maxAudioBW,
maxVideoBW: options.maxVideoBW,
limitMaxAudioBW: spec.maxAudioBW,
limitMaxVideoBW: spec.maxVideoBW,
label: stream.getLabel(),
iceServers: that.iceServers,
forceTurn: stream.forceTurn,
p2p: false,
};
if (!isRemote) {
connectionOpts.simulcast = options.simulcast;
connectionOpts.startVideoBW = options.startVideoBW;
connectionOpts.hardMinVideoBW = options.hardMinVideoBW;
}
return connectionOpts;
};
const createRemoteStreamErizoConnection = (streamInput, erizoId, options) => {
const stream = streamInput;
stream.addPC(that.erizoConnectionManager.getOrBuildErizoConnection(
getErizoConnectionOptions(stream, options, true), erizoId, spec.singlePC));
stream.on('added', dispatchStreamSubscribed.bind(null, stream));
stream.on('icestatechanged', (evt) => {
Logger.info(`${stream.getID()} - iceConnectionState: ${evt.msg.state}`);
if (evt.msg.state === 'failed') {
onStreamFailed(stream);
}
});
stream.pc.createOffer(true, false, stream.getID());
};
const createLocalStreamErizoConnection = (streamInput, erizoId, options) => {
const stream = streamInput;
stream.addPC(that.erizoConnectionManager.getOrBuildErizoConnection(
getErizoConnectionOptions(stream, options), erizoId, spec.singlePC));
stream.on('icestatechanged', (evt) => {
Logger.info(`${stream.getID()} - iceConnectionState: ${evt.msg.state}`);
if (evt.msg.state === 'failed') {
onStreamFailed(stream);
}
});
stream.pc.addStream(stream);
if (!options.createOffer) { stream.pc.createOffer(false, spec.singlePC, stream.getID()); }
};
// We receive an event with a new stream in the room.
// type can be "media" or "data"
const socketOnAddStream = (arg) => {
if (remoteStreams.has(arg.id)) {
return;
}
const stream = Stream(that.Connection, { streamID: arg.id,
local: false,
audio: arg.audio,
video: arg.video,
data: arg.data,
label: arg.label,
screen: arg.screen,
attributes: arg.attributes });
stream.room = that;
remoteStreams.add(arg.id, stream);
const evt = StreamEvent({ type: 'stream-added', stream });
that.dispatchEvent(evt);
};
const socketOnErizoMessage = (arg) => {
let stream;
if (arg.peerId) {
stream = remoteStreams.get(arg.peerId);
} else {
stream = localStreams.get(arg.streamId);
}
if (stream && stream.pc && !stream.failed) {
stream.pc.processSignalingMessage(arg.mess);
}
};
const socketOnPeerMessage = (arg) => {
let stream = localStreams.get(arg.streamId);
if (stream && !stream.failed) {
stream.pc.get(arg.peerSocket).processSignalingMessage(arg.msg);
} else {
stream = remoteStreams.get(arg.streamId);
if (!stream.pc) {
createRemoteStreamP2PConnection(stream, arg.peerSocket);
}
stream.pc.processSignalingMessage(arg.msg);
}
};
const socketOnPublishMe = (arg) => {
const myStream = localStreams.get(arg.streamId);
createLocalStreamP2PConnection(myStream, arg.peerSocket);
};
const socketOnUnpublishMe = (arg) => {
const myStream = localStreams.get(arg.streamId);
if (myStream) {
removeLocalStreamP2PConnection(myStream, arg.peerSocket);
}
};
const socketOnBandwidthAlert = (arg) => {
Logger.info('Bandwidth Alert on', arg.streamID, 'message',
arg.message, 'BW:', arg.bandwidth);
if (arg.streamID) {
const stream = remoteStreams.get(arg.streamID);
if (stream && !stream.failed) {
const evt = StreamEvent({ type: 'bandwidth-alert',
stream,
msg: arg.message,
bandwidth: arg.bandwidth });
stream.dispatchEvent(evt);
}
}
};
// We receive an event of new data in one of the streams
const socketOnDataStream = (arg) => {
const stream = remoteStreams.get(arg.id);
const evt = StreamEvent({ type: 'stream-data', msg: arg.msg, stream });
stream.dispatchEvent(evt);
};
// We receive an event of new data in one of the streams
const socketOnUpdateAttributeStream = (arg) => {
const stream = remoteStreams.get(arg.id);
const evt = StreamEvent({ type: 'stream-attributes-update',
attrs: arg.attrs,
stream });
stream.updateLocalAttributes(arg.attrs);
stream.dispatchEvent(evt);
};
// We receive an event of a stream removed from the room
const socketOnRemoveStream = (arg) => {
let stream = localStreams.get(arg.id);
if (stream) {
onStreamFailed(stream);
return;
}
stream = remoteStreams.get(arg.id);
if (stream) {
removeStream(stream);
remoteStreams.remove(arg.id);
const evt = StreamEvent({ type: 'stream-removed', stream });
that.dispatchEvent(evt);
}
};
// The socket has disconnected
const socketOnDisconnect = () => {
Logger.info('Socket disconnected, lost connection to ErizoController');
if (that.state !== DISCONNECTED) {
Logger.error('Unexpected disconnection from ErizoController');
const disconnectEvt = RoomEvent({ type: 'room-disconnected',
message: 'unexpected-disconnection' });
that.dispatchEvent(disconnectEvt);
}
};
const socketOnICEConnectionFailed = (arg) => {
let stream;
if (!arg.streamId) {
return;
}
const message = `ICE Connection Failed on ${arg.type} ${arg.streamId} ${that.state}`;
Logger.error(message);
if (arg.type === 'publish') {
stream = localStreams.get(arg.streamId);
} else {
stream = remoteStreams.get(arg.streamId);
}
onStreamFailed(stream, message);
};
const socketOnError = (e) => {
Logger.error('Cannot connect to erizo Controller');
const connectEvt = RoomEvent({ type: 'room-error', message: e });
that.dispatchEvent(connectEvt);
};
const sendDataSocketFromStreamEvent = (evt) => {
const stream = evt.stream;
const msg = evt.msg;
if (stream.local) {
socket.sendMessage('sendDataStream', { id: stream.getID(), msg });
} else {
Logger.error('You can not send data through a remote stream');
}
};
const updateAttributesFromStreamEvent = (evt) => {
const stream = evt.stream;
const attrs = evt.attrs;
if (stream.local) {
stream.updateLocalAttributes(attrs);
socket.sendMessage('updateStreamAttributes', { id: stream.getID(), attrs });
} else {
Logger.error('You can not update attributes in a remote stream');
}
};
const socketEventToArgs = (func, event) => {
if (event.args) {
func(...event.args);
} else {
func();
}
};
const createSdpConstraints = (type, stream, options) => ({
state: type,
data: stream.hasData(),
audio: stream.hasAudio(),
video: stream.hasVideo(),
label: stream.getLabel(),
screen: stream.hasScreen(),
attributes: stream.getAttributes(),
metadata: options.metadata,
createOffer: options.createOffer,
muteStream: options.muteStream,
});
const populateStreamFunctions = (id, streamInput, error, callback = () => {}) => {
const stream = streamInput;
if (id === null) {
Logger.error('Error when publishing the stream', error);
// Unauth -1052488119
// Network -5
callback(undefined, error);
return;
}
Logger.info('Stream published');
stream.getID = () => id;
stream.on('internal-send-data', sendDataSocketFromStreamEvent);
stream.on('internal-set-attributes', updateAttributesFromStreamEvent);
localStreams.add(id, stream);
stream.room = that;
callback(id);
};
const publishExternal = (streamInput, options, callback = () => {}) => {
const stream = streamInput;
let type;
let arg;
if (stream.url) {
type = 'url';
arg = stream.url;
} else {
type = 'recording';
arg = stream.recording;
}
Logger.info('Checking publish options for', stream.getID());
stream.checkOptions(options);
socket.sendSDP('publish', createSdpConstraints(type, stream, options), arg,
(id, error) => {
populateStreamFunctions(id, stream, error, callback);
});
};
const publishP2P = (streamInput, options, callback = () => {}) => {
const stream = streamInput;
// We save them now to be used when actually publishing in P2P mode.
stream.maxAudioBW = options.maxAudioBW;
stream.maxVideoBW = options.maxVideoBW;
socket.sendSDP('publish', createSdpConstraints('p2p', stream, options), undefined, (id, error) => {
populateStreamFunctions(id, stream, error, callback);
});
};
const publishData = (streamInput, options, callback = () => {}) => {
const stream = streamInput;
socket.sendSDP('publish', createSdpConstraints('data', stream, options), undefined, (id, error) => {
populateStreamFunctions(id, stream, error, callback);
});
};
const publishErizo = (streamInput, options, callback = () => {}) => {
const stream = streamInput;
Logger.info('Publishing to Erizo Normally, is createOffer', options.createOffer);
const constraints = createSdpConstraints('erizo', stream, options);
constraints.minVideoBW = options.minVideoBW;
constraints.maxVideoBW = options.maxVideoBW;
constraints.scheme = options.scheme;
socket.sendSDP('publish', constraints, undefined, (id, erizoId, error) => {
if (id === null) {
Logger.error('Error publishing stream', error);
callback(undefined, error);
return;
}
populateStreamFunctions(id, stream, error, undefined);
createLocalStreamErizoConnection(stream, erizoId, options);
callback(id);
});
};
const getVideoConstraints = (stream, video) => {
const hasVideo = video && stream.hasVideo();
const width = video && video.width;
const height = video && video.height;
const frameRate = video && video.frameRate;
if (width || height || frameRate) {
return { width, height, frameRate };
}
return hasVideo;
};
const subscribeErizo = (streamInput, optionsInput, callback = () => {}) => {
const stream = streamInput;
const options = optionsInput;
options.maxVideoBW = options.maxVideoBW || spec.defaultVideoBW;
if (options.maxVideoBW > spec.maxVideoBW) {
options.maxVideoBW = spec.maxVideoBW;
}
options.audio = (options.audio === undefined) ? true : options.audio;
options.video = (options.video === undefined) ? true : options.video;
options.data = (options.data === undefined) ? true : options.data;
stream.checkOptions(options);
const constraint = { streamId: stream.getID(),
audio: options.audio && stream.hasAudio(),
video: getVideoConstraints(stream, options.video),
maxVideoBW: options.maxVideoBW,
data: options.data && stream.hasData(),
browser: that.ConnectionHelpers.getBrowser(),
createOffer: options.createOffer,
metadata: options.metadata,
muteStream: options.muteStream,
slideShowMode: options.slideShowMode };
socket.sendSDP('subscribe', constraint, undefined, (result, erizoId, error) => {
if (result === null) {
Logger.error('Error subscribing to stream ', error);
callback(undefined, error);
return;
}
Logger.info('Subscriber added');
createRemoteStreamErizoConnection(stream, erizoId, options);
callback(true);
});
};
const subscribeData = (streamInput, options, callback = () => {}) => {
const stream = streamInput;
socket.sendSDP('subscribe',
{ streamId: stream.getID(),
data: options.data,
metadata: options.metadata },
undefined, (result, error) => {
if (result === null) {
Logger.error('Error subscribing to stream ', error);
callback(undefined, error);
return;
}
Logger.info('Stream subscribed');
const evt = StreamEvent({ type: 'stream-subscribed', stream });
that.dispatchEvent(evt);
callback(true);
});
};
const clearAll = () => {
that.state = DISCONNECTED;
socket.state = socket.DISCONNECTED;
// Remove all streams
remoteStreams.forEach((stream, id) => {
removeStream(stream);
remoteStreams.remove(id);
if (stream && !stream.failed) {
const evt2 = StreamEvent({ type: 'stream-removed', stream });
that.dispatchEvent(evt2);
}
});
remoteStreams = ErizoMap();
// Close Peer Connections
localStreams.forEach((stream, id) => {
removeStream(stream);
localStreams.remove(id);
});
localStreams = ErizoMap();
// Close socket
try {
socket.disconnect();
} catch (error) {
Logger.debug('Socket already disconnected');
}
socket = undefined;
};
// Public functions
// It stablishes a connection to the room.
// Once it is done it throws a RoomEvent("room-connected")
that.connect = (options = {}) => {
const token = Base64.decodeBase64(spec.token);
if (that.state !== DISCONNECTED) {
Logger.warning('Room already connected');
}
// 1- Connect to Erizo-Controller
that.state = CONNECTING;
socket.connect(JSON.parse(token), options, (response) => {
let stream;
const streamList = [];
const streams = response.streams || [];
const roomId = response.id;
that.p2p = response.p2p;
that.iceServers = response.iceServers;
that.state = CONNECTED;
spec.singlePC = response.singlePC;
spec.defaultVideoBW = response.defaultVideoBW;
spec.maxVideoBW = response.maxVideoBW;
// 2- Retrieve list of streams
const streamIndices = Object.keys(streams);
for (let index = 0; index < streamIndices.length; index += 1) {
const arg = streams[streamIndices[index]];
stream = Stream(that.ConnectionHelpers, { streamID: arg.id,
local: false,
audio: arg.audio,
video: arg.video,
data: arg.data,
label: arg.label,
screen: arg.screen,
attributes: arg.attributes });
stream.room = that;
streamList.push(stream);
remoteStreams.add(arg.id, stream);
}
// 3 - Update RoomID
that.roomID = roomId;
Logger.info(`Connected to room ${that.roomID}`);
const connectEvt = RoomEvent({ type: 'room-connected', streams: streamList });
that.dispatchEvent(connectEvt);
}, (error) => {
Logger.error(`Not Connected! Error: ${error}`);
const connectEvt = RoomEvent({ type: 'room-error', message: error });
that.dispatchEvent(connectEvt);
});
};
// It disconnects from the room, dispatching a new RoomEvent("room-disconnected")
that.disconnect = () => {
Logger.debug('Disconnection requested');
// 1- Disconnect from room
const disconnectEvt = RoomEvent({ type: 'room-disconnected',
message: 'expected-disconnection' });
that.dispatchEvent(disconnectEvt);
};
// It publishes the stream provided as argument. Once it is added it throws a
// StreamEvent("stream-added").
that.publish = (streamInput, optionsInput = {}, callback = () => {}) => {
const stream = streamInput;
const options = optionsInput;
options.maxVideoBW = options.maxVideoBW || spec.defaultVideoBW;
if (options.maxVideoBW > spec.maxVideoBW) {
options.maxVideoBW = spec.maxVideoBW;
}
if (options.minVideoBW === undefined) {
options.minVideoBW = 0;
}
if (options.minVideoBW > spec.defaultVideoBW) {
options.minVideoBW = spec.defaultVideoBW;
}
stream.forceTurn = options.forceTurn;
options.simulcast = options.simulcast || false;
options.muteStream = {
audio: stream.audioMuted,
video: stream.videoMuted,
};
// 1- If the stream is not local or it is a failed stream we do nothing.
if (stream && stream.local && !stream.failed && !localStreams.has(stream.getID())) {
// 2- Publish Media Stream to Erizo-Controller
if (stream.hasMedia()) {
if (stream.isExternal()) {
publishExternal(stream, options, callback);
} else if (that.p2p) {
publishP2P(stream, options, callback);
} else {
publishErizo(stream, options, callback);
}
} else if (stream.hasData()) {
publishData(stream, options, callback);
}
} else {
Logger.error('Trying to publish invalid stream');
callback(undefined, 'Invalid Stream');
}
};
// Returns callback(id, error)
that.startRecording = (stream, callback = () => {}) => {
if (stream === undefined) {
Logger.error('Trying to start recording on an invalid stream', stream);
callback(undefined, 'Invalid Stream');
return;
}
Logger.debug(`Start Recording stream: ${stream.getID()}`);
socket.sendMessage('startRecorder', { to: stream.getID() }, (id, error) => {
if (id === null) {
Logger.error('Error on start recording', error);
callback(undefined, error);
return;
}
Logger.info('Start recording', id);
callback(id);
});
};
// Returns callback(id, error)
that.stopRecording = (recordingId, callback = () => {}) => {
socket.sendMessage('stopRecorder', { id: recordingId }, (result, error) => {
if (result === null) {
Logger.error('Error on stop recording', error);
callback(undefined, error);
return;
}
Logger.info('Stop recording', recordingId);
callback(true);
});
};
// It unpublishes the local stream in the room, dispatching a StreamEvent("stream-removed")
that.unpublish = (streamInput, callback = () => {}) => {
const stream = streamInput;
// Unpublish stream from Erizo-Controller
if (stream && stream.local) {
// Media stream
socket.sendMessage('unpublish', stream.getID(), (result, error) => {
if (result === null) {
Logger.error('Error unpublishing stream', error);
callback(undefined, error);
return;
}
delete stream.failed;
Logger.info('Stream unpublished');
callback(true);
});
stream.room = undefined;
if (stream.hasMedia() && !stream.isExternal()) {
removeStream(stream);
}
localStreams.remove(stream.getID());
stream.getID = () => {};
stream.off('internal-send-data', sendDataSocketFromStreamEvent);
stream.off('internal-set-attributes', updateAttributesFromStreamEvent);
} else {
const error = 'Cannot unpublish, stream does not exist or is not local';
Logger.error(error);
callback(undefined, error);
}
};
that.sendControlMessage = (stream, type, action) => {
if (stream && stream.getID()) {
const msg = { type: 'control', action };
socket.sendSDP('signaling_message', { streamId: stream.getID(), msg });
}
};
// It subscribe to a remote stream and draws it inside the HTML tag given by the ID='elementID'
that.subscribe = (streamInput, optionsInput = {}, callback = () => {}) => {
const stream = streamInput;
const options = optionsInput;
if (stream && !stream.local && !stream.failed) {
if (stream.hasMedia()) {
// 1- Subscribe to Stream
if (!stream.hasVideo() && !stream.hasScreen()) {
options.video = false;
}
if (!stream.hasAudio()) {
options.audio = false;
}
options.muteStream = {
audio: stream.audioMuted,
video: stream.videoMuted,
};
stream.forceTurn = options.forceTurn;
if (that.p2p) {
socket.sendSDP('subscribe', { streamId: stream.getID(), metadata: options.metadata });
callback(true);
} else {
subscribeErizo(stream, options, callback);
}
} else if (stream.hasData() && options.data !== false) {
subscribeData(stream, options, callback);
} else {
Logger.warning('There\'s nothing to subscribe to');
callback(undefined, 'Nothing to subscribe to');
return;
}
// Subscribe to stream stream
Logger.info(`Subscribing to: ${stream.getID()}`);
} else {
let error = 'Error on subscribe';
if (!stream) {
Logger.warning('Cannot subscribe to invalid stream');
error = 'Invalid or undefined stream';
} else if (stream.local) {
Logger.warning('Cannot subscribe to local stream, you should ' +
'subscribe to the remote version of your local stream');
error = 'Local copy of stream';
} else if (stream.failed) {
Logger.warning('Cannot subscribe to failed stream.');
error = 'Failed stream';
}
callback(undefined, error);
}
};
// It unsubscribes from the stream, removing the HTML element.
that.unsubscribe = (streamInput, callback = () => {}) => {
const stream = streamInput;
// Unsubscribe from stream stream
if (socket !== undefined) {
if (stream && !stream.local) {
socket.sendMessage('unsubscribe', stream.getID(), (result, error) => {
if (result === null) {
callback(undefined, error);
return;
}
removeStream(stream);
delete stream.failed;
callback(true);
}, () => {
Logger.error('Error calling unsubscribe.');
});
}
}
};
that.getStreamStats = (stream, callback = () => {}) => {
if (!socket) {
return 'Error getting stats - no socket';
}
if (!stream) {
return 'Error getting stats - no stream';
}
socket.sendMessage('getStreamStats', stream.getID(), (result) => {
if (result) {
callback(result);
}
});
return undefined;
};
// It searchs the streams that have "name" attribute with "value" value
that.getStreamsByAttribute = (name, value) => {
const streams = [];
remoteStreams.forEach((stream) => {
if (stream.getAttributes() !== undefined && stream.getAttributes()[name] === value) {
streams.push(stream);
}
});
return streams;
};
that.on('room-disconnected', clearAll);
socket.on('onAddStream', socketEventToArgs.bind(null, socketOnAddStream));
socket.on('signaling_message_erizo', socketEventToArgs.bind(null, socketOnErizoMessage));
socket.on('signaling_message_peer', socketEventToArgs.bind(null, socketOnPeerMessage));
socket.on('publish_me', socketEventToArgs.bind(null, socketOnPublishMe));
socket.on('unpublish_me', socketEventToArgs.bind(null, socketOnUnpublishMe));
socket.on('onBandwidthAlert', socketEventToArgs.bind(null, socketOnBandwidthAlert));
socket.on('onDataStream', socketEventToArgs.bind(null, socketOnDataStream));
socket.on('onUpdateAttributeStream', socketEventToArgs.bind(null, socketOnUpdateAttributeStream));
socket.on('onRemoveStream', socketEventToArgs.bind(null, socketOnRemoveStream));
socket.on('disconnect', socketEventToArgs.bind(null, socketOnDisconnect));
socket.on('connection_failed', socketEventToArgs.bind(null, socketOnICEConnectionFailed));
socket.on('error', socketEventToArgs.bind(null, socketOnError));
return that;
};
export default Room;