您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. /* global __filename */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import BridgeChannel from './BridgeChannel';
  4. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  5. import * as JitsiConferenceEvents from '../../JitsiConferenceEvents';
  6. import JitsiLocalTrack from './JitsiLocalTrack';
  7. import JitsiTrackError from '../../JitsiTrackError';
  8. import * as JitsiTrackErrors from '../../JitsiTrackErrors';
  9. import Listenable from '../util/Listenable';
  10. import * as MediaType from '../../service/RTC/MediaType';
  11. import RTCEvents from '../../service/RTC/RTCEvents';
  12. import RTCUtils from './RTCUtils';
  13. import TraceablePeerConnection from './TraceablePeerConnection';
  14. import VideoType from '../../service/RTC/VideoType';
  15. const logger = getLogger(__filename);
  16. let rtcTrackIdCounter = 0;
  17. /**
  18. *
  19. * @param tracksInfo
  20. * @param options
  21. */
  22. function createLocalTracks(tracksInfo, options) {
  23. const newTracks = [];
  24. let deviceId = null;
  25. tracksInfo.forEach(trackInfo => {
  26. if (trackInfo.mediaType === MediaType.AUDIO) {
  27. deviceId = options.micDeviceId;
  28. } else if (trackInfo.videoType === VideoType.CAMERA) {
  29. deviceId = options.cameraDeviceId;
  30. }
  31. rtcTrackIdCounter += 1;
  32. const localTrack = new JitsiLocalTrack({
  33. ...trackInfo,
  34. deviceId,
  35. facingMode: options.facingMode,
  36. rtcId: rtcTrackIdCounter
  37. });
  38. newTracks.push(localTrack);
  39. });
  40. return newTracks;
  41. }
  42. /**
  43. *
  44. */
  45. export default class RTC extends Listenable {
  46. /**
  47. *
  48. * @param conference
  49. * @param options
  50. */
  51. constructor(conference, options = {}) {
  52. super();
  53. this.conference = conference;
  54. /**
  55. * A map of active <tt>TraceablePeerConnection</tt>.
  56. * @type {Map.<number, TraceablePeerConnection>}
  57. */
  58. this.peerConnections = new Map();
  59. /**
  60. * The counter used to generated id numbers assigned to peer connections
  61. * @type {number}
  62. */
  63. this.peerConnectionIdCounter = 1;
  64. this.localTracks = [];
  65. this.options = options;
  66. // BridgeChannel instance.
  67. // @private
  68. // @type {BridgeChannel}
  69. this._channel = null;
  70. // A flag whether we had received that the channel had opened we can
  71. // get this flag out of sync if for some reason channel got closed
  72. // from server, a desired behaviour so we can see errors when this
  73. // happen.
  74. // @private
  75. // @type {boolean}
  76. this._channelOpen = false;
  77. /**
  78. * The value specified to the last invocation of setLastN before the
  79. * channel completed opening. If non-null, the value will be sent
  80. * through a channel (once) as soon as it opens and will then be
  81. * discarded.
  82. * @private
  83. * @type {number}
  84. */
  85. this._lastN = -1;
  86. /**
  87. * Defines the last N endpoints list. It can be null or an array once
  88. * initialised with a channel last N event.
  89. * @type {Array<string>|null}
  90. * @private
  91. */
  92. this._lastNEndpoints = null;
  93. /**
  94. * The endpoint ID of currently pinned participant or <tt>null</tt> if
  95. * no user is pinned.
  96. * @type {string|null}
  97. * @private
  98. */
  99. this._pinnedEndpoint = null;
  100. /**
  101. * The endpoint ID of currently selected participant or <tt>null</tt> if
  102. * no user is selected.
  103. * @type {string|null}
  104. * @private
  105. */
  106. this._selectedEndpoint = null;
  107. // The last N change listener.
  108. this._lastNChangeListener = this._onLastNChanged.bind(this);
  109. // Switch audio output device on all remote audio tracks. Local audio
  110. // tracks handle this event by themselves.
  111. if (RTCUtils.isDeviceChangeAvailable('output')) {
  112. RTCUtils.addListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  113. deviceId => {
  114. const remoteAudioTracks
  115. = this.getRemoteTracks(MediaType.AUDIO);
  116. for (const track of remoteAudioTracks) {
  117. track.setAudioOutput(deviceId);
  118. }
  119. });
  120. }
  121. }
  122. /**
  123. * Creates the local MediaStreams.
  124. * @param {object} [options] Optional parameters.
  125. * @param {array} options.devices The devices that will be requested.
  126. * @param {string} options.resolution Resolution constraints.
  127. * @param {bool} options.dontCreateJitsiTrack If <tt>true</tt> objects with
  128. * the following structure {stream: the Media Stream, type: "audio" or
  129. * "video", videoType: "camera" or "desktop"} will be returned trough
  130. * the Promise, otherwise JitsiTrack objects will be returned.
  131. * @param {string} options.cameraDeviceId
  132. * @param {string} options.micDeviceId
  133. * @returns {*} Promise object that will receive the new JitsiTracks
  134. */
  135. static obtainAudioAndVideoPermissions(options) {
  136. return RTCUtils.obtainAudioAndVideoPermissions(options).then(
  137. tracksInfo => {
  138. const tracks = createLocalTracks(tracksInfo, options);
  139. return tracks.some(track => !track._isReceivingData())
  140. ? Promise.reject(
  141. new JitsiTrackError(
  142. JitsiTrackErrors.NO_DATA_FROM_SOURCE))
  143. : tracks;
  144. });
  145. }
  146. /**
  147. * Initializes the bridge channel of this instance.
  148. * At least one of both, peerconnection or wsUrl parameters, must be
  149. * given.
  150. * @param {RTCPeerConnection} [peerconnection] WebRTC peer connection
  151. * instance.
  152. * @param {string} [wsUrl] WebSocket URL.
  153. */
  154. initializeBridgeChannel(peerconnection, wsUrl) {
  155. this._channel = new BridgeChannel(
  156. peerconnection, wsUrl, this.eventEmitter);
  157. this._channelOpenListener = () => {
  158. // Mark that channel as opened.
  159. this._channelOpen = true;
  160. // When the channel becomes available, tell the bridge about
  161. // video selections so that it can do adaptive simulcast,
  162. // we want the notification to trigger even if userJid
  163. // is undefined, or null.
  164. try {
  165. this._channel.sendPinnedEndpointMessage(
  166. this._pinnedEndpoint);
  167. this._channel.sendSelectedEndpointMessage(
  168. this._selectedEndpoint);
  169. } catch (error) {
  170. GlobalOnErrorHandler.callErrorHandler(error);
  171. logger.error(
  172. `Cannot send selected(${this._selectedEndpoint})`
  173. + `pinned(${this._pinnedEndpoint}) endpoint message.`,
  174. error);
  175. }
  176. this.removeListener(RTCEvents.DATA_CHANNEL_OPEN,
  177. this._channelOpenListener);
  178. this._channelOpenListener = null;
  179. // If setLastN was invoked before the bridge channel completed
  180. // opening, apply the specified value now that the channel
  181. // is open. NOTE that -1 is the default value assumed by both
  182. // RTC module and the JVB.
  183. if (this._lastN !== -1) {
  184. this._channel.sendSetLastNMessage(this._lastN);
  185. }
  186. };
  187. this.addListener(RTCEvents.DATA_CHANNEL_OPEN,
  188. this._channelOpenListener);
  189. // Add Last N change listener.
  190. this.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  191. this._lastNChangeListener);
  192. }
  193. /**
  194. * Receives events when Last N had changed.
  195. * @param {array} lastNEndpoints The new Last N endpoints.
  196. * @private
  197. */
  198. _onLastNChanged(lastNEndpoints = []) {
  199. const oldLastNEndpoints = this._lastNEndpoints || [];
  200. let leavingLastNEndpoints = [];
  201. let enteringLastNEndpoints = [];
  202. this._lastNEndpoints = lastNEndpoints;
  203. leavingLastNEndpoints = oldLastNEndpoints.filter(
  204. id => !this.isInLastN(id));
  205. enteringLastNEndpoints = lastNEndpoints.filter(
  206. id => oldLastNEndpoints.indexOf(id) === -1);
  207. this.conference.eventEmitter.emit(
  208. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  209. leavingLastNEndpoints,
  210. enteringLastNEndpoints);
  211. }
  212. /**
  213. * Should be called when current media session ends and after the
  214. * PeerConnection has been closed using PeerConnection.close() method.
  215. */
  216. onCallEnded() {
  217. if (this._channel) {
  218. // The BridgeChannel is not explicitly closed as the PeerConnection
  219. // is closed on call ended which triggers datachannel onclose
  220. // events. If using a WebSocket, the channel must be closed since
  221. // it is not managed by the PeerConnection.
  222. // The reference is cleared to disable any logic related to the
  223. // channel.
  224. if (this._channel && this._channel.mode === 'websocket') {
  225. this._channel.close();
  226. }
  227. this._channel = null;
  228. this._channelOpen = false;
  229. }
  230. }
  231. /**
  232. * Elects the participant with the given id to be the selected participant
  233. * in order to always receive video for this participant (even when last n
  234. * is enabled).
  235. * If there is no channel we store it and send it through the channel once
  236. * it is created.
  237. * @param {string} id The user id.
  238. * @throws NetworkError or InvalidStateError or Error if the operation
  239. * fails.
  240. */
  241. selectEndpoint(id) {
  242. // Cache the value if channel is missing, till we open it.
  243. this._selectedEndpoint = id;
  244. if (this._channel && this._channelOpen) {
  245. this._channel.sendSelectedEndpointMessage(id);
  246. }
  247. }
  248. /**
  249. * Elects the participant with the given id to be the pinned participant in
  250. * order to always receive video for this participant (even when last n is
  251. * enabled).
  252. * @param {stirng} id The user id.
  253. * @throws NetworkError or InvalidStateError or Error if the operation
  254. * fails.
  255. */
  256. pinEndpoint(id) {
  257. // Cache the value if channel is missing, till we open it.
  258. this._pinnedEndpoint = id;
  259. if (this._channel && this._channelOpen) {
  260. this._channel.sendPinnedEndpointMessage(id);
  261. }
  262. }
  263. /**
  264. *
  265. * @param eventType
  266. * @param listener
  267. */
  268. static addListener(eventType, listener) {
  269. RTCUtils.addListener(eventType, listener);
  270. }
  271. /**
  272. *
  273. * @param eventType
  274. * @param listener
  275. */
  276. static removeListener(eventType, listener) {
  277. RTCUtils.removeListener(eventType, listener);
  278. }
  279. /**
  280. *
  281. */
  282. static isRTCReady() {
  283. return RTCUtils.isRTCReady();
  284. }
  285. /**
  286. *
  287. * @param options
  288. */
  289. static init(options = {}) {
  290. this.options = options;
  291. return RTCUtils.init(this.options);
  292. }
  293. /**
  294. *
  295. */
  296. static getDeviceAvailability() {
  297. return RTCUtils.getDeviceAvailability();
  298. }
  299. /* eslint-disable max-params */
  300. /**
  301. * Creates new <tt>TraceablePeerConnection</tt>
  302. * @param {SignalingLayer} signaling The signaling layer that will
  303. * provide information about the media or participants which is not
  304. * carried over SDP.
  305. * @param {object} iceConfig An object describing the ICE config like
  306. * defined in the WebRTC specification.
  307. * @param {boolean} isP2P Indicates whether or not the new TPC will be used
  308. * in a peer to peer type of session.
  309. * @param {object} options The config options.
  310. * @param {boolean} options.disableSimulcast If set to 'true' will disable
  311. * the simulcast.
  312. * @param {boolean} options.disableRtx If set to 'true' will disable the
  313. * RTX.
  314. * @param {boolean} options.preferH264 If set to 'true' H264 will be
  315. * preferred over other video codecs.
  316. * @return {TraceablePeerConnection}
  317. */
  318. createPeerConnection(signaling, iceConfig, isP2P, options) {
  319. const newConnection
  320. = new TraceablePeerConnection(
  321. this,
  322. this.peerConnectionIdCounter,
  323. signaling,
  324. iceConfig, RTC.getPCConstraints(isP2P), isP2P, options);
  325. this.peerConnections.set(newConnection.id, newConnection);
  326. this.peerConnectionIdCounter += 1;
  327. return newConnection;
  328. }
  329. /* eslint-enable max-params */
  330. /**
  331. * Removed given peer connection from this RTC module instance.
  332. * @param {TraceablePeerConnection} traceablePeerConnection
  333. * @return {boolean} <tt>true</tt> if the given peer connection was removed
  334. * successfully or <tt>false</tt> if there was no peer connection mapped in
  335. * this RTC instance.
  336. */
  337. _removePeerConnection(traceablePeerConnection) {
  338. const id = traceablePeerConnection.id;
  339. if (this.peerConnections.has(id)) {
  340. // NOTE Remote tracks are not removed here.
  341. this.peerConnections.delete(id);
  342. return true;
  343. }
  344. return false;
  345. }
  346. /**
  347. *
  348. * @param track
  349. */
  350. addLocalTrack(track) {
  351. if (!track) {
  352. throw new Error('track must not be null nor undefined');
  353. }
  354. this.localTracks.push(track);
  355. track.conference = this.conference;
  356. }
  357. /**
  358. * Returns the current value for "lastN" - the amount of videos are going
  359. * to be delivered. When set to -1 for unlimited or all available videos.
  360. * @return {number}
  361. */
  362. getLastN() {
  363. return this._lastN;
  364. }
  365. /**
  366. * Get local video track.
  367. * @returns {JitsiLocalTrack|undefined}
  368. */
  369. getLocalVideoTrack() {
  370. const localVideo = this.getLocalTracks(MediaType.VIDEO);
  371. return localVideo.length ? localVideo[0] : undefined;
  372. }
  373. /**
  374. * Get local audio track.
  375. * @returns {JitsiLocalTrack|undefined}
  376. */
  377. getLocalAudioTrack() {
  378. const localAudio = this.getLocalTracks(MediaType.AUDIO);
  379. return localAudio.length ? localAudio[0] : undefined;
  380. }
  381. /**
  382. * Returns the local tracks of the given media type, or all local tracks if
  383. * no specific type is given.
  384. * @param {MediaType} [mediaType] Optional media type filter.
  385. * (audio or video).
  386. */
  387. getLocalTracks(mediaType) {
  388. let tracks = this.localTracks.slice();
  389. if (mediaType !== undefined) {
  390. tracks = tracks.filter(
  391. track => track.getType() === mediaType);
  392. }
  393. return tracks;
  394. }
  395. /**
  396. * Obtains all remote tracks currently known to this RTC module instance.
  397. * @param {MediaType} [mediaType] The remote tracks will be filtered
  398. * by their media type if this argument is specified.
  399. * @return {Array<JitsiRemoteTrack>}
  400. */
  401. getRemoteTracks(mediaType) {
  402. let remoteTracks = [];
  403. for (const tpc of this.peerConnections.values()) {
  404. const pcRemoteTracks = tpc.getRemoteTracks(undefined, mediaType);
  405. if (pcRemoteTracks) {
  406. remoteTracks = remoteTracks.concat(pcRemoteTracks);
  407. }
  408. }
  409. return remoteTracks;
  410. }
  411. /**
  412. * Set mute for all local audio streams attached to the conference.
  413. * @param value The mute value.
  414. * @returns {Promise}
  415. */
  416. setAudioMute(value) {
  417. const mutePromises = [];
  418. this.getLocalTracks(MediaType.AUDIO).forEach(audioTrack => {
  419. // this is a Promise
  420. mutePromises.push(value ? audioTrack.mute() : audioTrack.unmute());
  421. });
  422. // We return a Promise from all Promises so we can wait for their
  423. // execution.
  424. return Promise.all(mutePromises);
  425. }
  426. /**
  427. *
  428. * @param track
  429. */
  430. removeLocalTrack(track) {
  431. const pos = this.localTracks.indexOf(track);
  432. if (pos === -1) {
  433. return;
  434. }
  435. this.localTracks.splice(pos, 1);
  436. }
  437. /**
  438. * Removes all JitsiRemoteTracks associated with given MUC nickname
  439. * (resource part of the JID). Returns array of removed tracks.
  440. *
  441. * @param {string} Owner The resource part of the MUC JID.
  442. * @returns {JitsiRemoteTrack[]}
  443. */
  444. removeRemoteTracks(owner) {
  445. let removedTracks = [];
  446. for (const tpc of this.peerConnections.values()) {
  447. const pcRemovedTracks = tpc.removeRemoteTracks(owner);
  448. removedTracks = removedTracks.concat(pcRemovedTracks);
  449. }
  450. logger.debug(
  451. `Removed remote tracks for ${owner}`
  452. + ` count: ${removedTracks.length}`);
  453. return removedTracks;
  454. }
  455. /**
  456. *
  457. */
  458. static getPCConstraints(isP2P) {
  459. return isP2P ? RTCUtils.p2pPcConstraints : RTCUtils.pcConstraints;
  460. }
  461. /**
  462. *
  463. * @param elSelector
  464. * @param stream
  465. */
  466. static attachMediaStream(elSelector, stream) {
  467. return RTCUtils.attachMediaStream(elSelector, stream);
  468. }
  469. /**
  470. * Returns the id of the given stream.
  471. * @param {MediaStream} stream
  472. */
  473. static getStreamID(stream) {
  474. return RTCUtils.getStreamID(stream);
  475. }
  476. /**
  477. * Returns the id of the given track.
  478. * @param {MediaStreamTrack} track
  479. */
  480. static getTrackID(track) {
  481. return RTCUtils.getTrackID(track);
  482. }
  483. /**
  484. * Returns true if retrieving the the list of input devices is supported
  485. * and false if not.
  486. */
  487. static isDeviceListAvailable() {
  488. return RTCUtils.isDeviceListAvailable();
  489. }
  490. /**
  491. * Returns true if changing the input (camera / microphone) or output
  492. * (audio) device is supported and false if not.
  493. * @param {string} [deviceType] Type of device to change. Default is
  494. * undefined or 'input', 'output' - for audio output device change.
  495. * @returns {boolean} true if available, false otherwise.
  496. */
  497. static isDeviceChangeAvailable(deviceType) {
  498. return RTCUtils.isDeviceChangeAvailable(deviceType);
  499. }
  500. /**
  501. * Returns currently used audio output device id, '' stands for default
  502. * device
  503. * @returns {string}
  504. */
  505. static getAudioOutputDevice() {
  506. return RTCUtils.getAudioOutputDevice();
  507. }
  508. /**
  509. * Returns list of available media devices if its obtained, otherwise an
  510. * empty array is returned/
  511. * @returns {array} list of available media devices.
  512. */
  513. static getCurrentlyAvailableMediaDevices() {
  514. return RTCUtils.getCurrentlyAvailableMediaDevices();
  515. }
  516. /**
  517. * Returns event data for device to be reported to stats.
  518. * @returns {MediaDeviceInfo} device.
  519. */
  520. static getEventDataForActiveDevice(device) {
  521. return RTCUtils.getEventDataForActiveDevice(device);
  522. }
  523. /**
  524. * Sets current audio output device.
  525. * @param {string} deviceId Id of 'audiooutput' device from
  526. * navigator.mediaDevices.enumerateDevices().
  527. * @returns {Promise} resolves when audio output is changed, is rejected
  528. * otherwise
  529. */
  530. static setAudioOutputDevice(deviceId) {
  531. return RTCUtils.setAudioOutputDevice(deviceId);
  532. }
  533. /**
  534. * Returns <tt>true<tt/> if given WebRTC MediaStream is considered a valid
  535. * "user" stream which means that it's not a "receive only" stream nor a
  536. * "mixed" JVB stream.
  537. *
  538. * Clients that implement Unified Plan, such as Firefox use recvonly
  539. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  540. * to Plan B where there are only 3 channels: audio, video and data.
  541. *
  542. * @param {MediaStream} stream The WebRTC MediaStream instance.
  543. * @returns {boolean}
  544. */
  545. static isUserStream(stream) {
  546. return RTC.isUserStreamById(RTCUtils.getStreamID(stream));
  547. }
  548. /**
  549. * Returns <tt>true<tt/> if a WebRTC MediaStream identified by given stream
  550. * ID is considered a valid "user" stream which means that it's not a
  551. * "receive only" stream nor a "mixed" JVB stream.
  552. *
  553. * Clients that implement Unified Plan, such as Firefox use recvonly
  554. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  555. * to Plan B where there are only 3 channels: audio, video and data.
  556. *
  557. * @param {string} streamId The id of WebRTC MediaStream.
  558. * @returns {boolean}
  559. */
  560. static isUserStreamById(streamId) {
  561. return streamId && streamId !== 'mixedmslabel'
  562. && streamId !== 'default';
  563. }
  564. /**
  565. * Allows to receive list of available cameras/microphones.
  566. * @param {function} callback Would receive array of devices as an
  567. * argument.
  568. */
  569. static enumerateDevices(callback) {
  570. RTCUtils.enumerateDevices(callback);
  571. }
  572. /**
  573. * A method to handle stopping of the stream.
  574. * One point to handle the differences in various implementations.
  575. * @param {MediaStream} mediaStream MediaStream object to stop.
  576. */
  577. static stopMediaStream(mediaStream) {
  578. RTCUtils.stopMediaStream(mediaStream);
  579. }
  580. /**
  581. * Returns whether the desktop sharing is enabled or not.
  582. * @returns {boolean}
  583. */
  584. static isDesktopSharingEnabled() {
  585. return RTCUtils.isDesktopSharingEnabled();
  586. }
  587. /**
  588. * Closes the currently opened bridge channel.
  589. */
  590. closeBridgeChannel() {
  591. if (this._channel) {
  592. this._channel.close();
  593. this._channelOpen = false;
  594. this.removeListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  595. this._lastNChangeListener);
  596. }
  597. }
  598. /* eslint-disable max-params */
  599. /**
  600. *
  601. * @param {TraceablePeerConnection} tpc
  602. * @param {number} ssrc
  603. * @param {number} audioLevel
  604. * @param {boolean} isLocal
  605. */
  606. setAudioLevel(tpc, ssrc, audioLevel, isLocal) {
  607. const track = tpc.getTrackBySSRC(ssrc);
  608. if (!track) {
  609. return;
  610. } else if (!track.isAudioTrack()) {
  611. logger.warn(`Received audio level for non-audio track: ${ssrc}`);
  612. return;
  613. } else if (track.isLocal() !== isLocal) {
  614. logger.error(
  615. `${track} was expected to ${isLocal ? 'be' : 'not be'} local`);
  616. }
  617. track.setAudioLevel(audioLevel, tpc);
  618. }
  619. /* eslint-enable max-params */
  620. /**
  621. * Sends message via the bridge channel.
  622. * @param {string} to The id of the endpoint that should receive the
  623. * message. If "" the message will be sent to all participants.
  624. * @param {object} payload The payload of the message.
  625. * @throws NetworkError or InvalidStateError or Error if the operation
  626. * fails or there is no data channel created.
  627. */
  628. sendChannelMessage(to, payload) {
  629. if (this._channel) {
  630. this._channel.sendMessage(to, payload);
  631. } else {
  632. throw new Error('Channel support is disabled!');
  633. }
  634. }
  635. /**
  636. * Selects a new value for "lastN". The requested amount of videos are going
  637. * to be delivered after the value is in effect. Set to -1 for unlimited or
  638. * all available videos.
  639. * @param {number} value the new value for lastN.
  640. */
  641. setLastN(value) {
  642. if (this._lastN !== value) {
  643. this._lastN = value;
  644. if (this._channel && this._channelOpen) {
  645. this._channel.sendSetLastNMessage(value);
  646. }
  647. this.eventEmitter.emit(RTCEvents.LASTN_VALUE_CHANGED, value);
  648. }
  649. }
  650. /**
  651. * Indicates if the endpoint id is currently included in the last N.
  652. * @param {string} id The endpoint id that we check for last N.
  653. * @returns {boolean} true if the endpoint id is in the last N or if we
  654. * don't have bridge channel support, otherwise we return false.
  655. */
  656. isInLastN(id) {
  657. return !this._lastNEndpoints // lastNEndpoints not initialised yet.
  658. || this._lastNEndpoints.indexOf(id) > -1;
  659. }
  660. }