modified lib-jitsi-meet dev repo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTC.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. /* global __filename, APP, module */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var EventEmitter = require("events");
  4. var RTCBrowserType = require("./RTCBrowserType");
  5. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  6. var RTCUtils = require("./RTCUtils.js");
  7. var JitsiTrack = require("./JitsiTrack");
  8. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  9. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  10. var JitsiTrackError = require("../../JitsiTrackError");
  11. var DataChannels = require("./DataChannels");
  12. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  13. var MediaType = require("../../service/RTC/MediaType");
  14. var VideoType = require("../../service/RTC/VideoType");
  15. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  16. function createLocalTracks(tracksInfo, options) {
  17. var newTracks = [];
  18. var deviceId = null;
  19. tracksInfo.forEach(function(trackInfo){
  20. if (trackInfo.mediaType === MediaType.AUDIO) {
  21. deviceId = options.micDeviceId;
  22. } else if (trackInfo.videoType === VideoType.CAMERA){
  23. deviceId = options.cameraDeviceId;
  24. }
  25. var localTrack
  26. = new JitsiLocalTrack(
  27. trackInfo.stream,
  28. trackInfo.track,
  29. trackInfo.mediaType,
  30. trackInfo.videoType,
  31. trackInfo.resolution,
  32. deviceId,
  33. options.facingMode);
  34. newTracks.push(localTrack);
  35. });
  36. return newTracks;
  37. }
  38. function RTC(conference, options) {
  39. this.conference = conference;
  40. this.localTracks = [];
  41. //FIXME: We should support multiple streams per jid.
  42. this.remoteTracks = {};
  43. this.localAudio = null;
  44. this.localVideo = null;
  45. this.eventEmitter = new EventEmitter();
  46. var self = this;
  47. this.options = options || {};
  48. // Switch audio output device on all remote audio tracks. Local audio tracks
  49. // handle this event by themselves.
  50. if (RTCUtils.isDeviceChangeAvailable('output')) {
  51. RTCUtils.addListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  52. function (deviceId) {
  53. for (var key in self.remoteTracks) {
  54. if (self.remoteTracks.hasOwnProperty(key)
  55. && self.remoteTracks[key].audio) {
  56. self.remoteTracks[key].audio.setAudioOutput(deviceId);
  57. }
  58. }
  59. });
  60. }
  61. }
  62. /**
  63. * Creates the local MediaStreams.
  64. * @param {Object} [options] optional parameters
  65. * @param {Array} options.devices the devices that will be requested
  66. * @param {string} options.resolution resolution constraints
  67. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the
  68. * following structure {stream: the Media Stream,
  69. * type: "audio" or "video", videoType: "camera" or "desktop"}
  70. * will be returned trough the Promise, otherwise JitsiTrack objects will be
  71. * returned.
  72. * @param {string} options.cameraDeviceId
  73. * @param {string} options.micDeviceId
  74. * @returns {*} Promise object that will receive the new JitsiTracks
  75. */
  76. RTC.obtainAudioAndVideoPermissions = function (options) {
  77. return RTCUtils.obtainAudioAndVideoPermissions(options).then(
  78. function (tracksInfo) {
  79. var tracks = createLocalTracks(tracksInfo, options);
  80. var allTracksAreReceivingData = true;
  81. tracks.some(function (track) {
  82. if(!track._isReceivingData()) {
  83. allTracksAreReceivingData = false;
  84. return true;
  85. }
  86. return false;
  87. });
  88. return allTracksAreReceivingData? tracks : Promise.reject(
  89. new JitsiTrackError(JitsiTrackErrors.NO_DATA_FROM_SOURCE));
  90. });
  91. };
  92. RTC.prototype.onIncommingCall = function(event) {
  93. if(this.options.config.openSctp) {
  94. this.dataChannels = new DataChannels(event.peerconnection,
  95. this.eventEmitter);
  96. this._dataChannelOpenListener = () => {
  97. // when the data channel becomes available, tell the bridge
  98. // about video selections so that it can do adaptive simulcast,
  99. // we want the notification to trigger even if userJid
  100. // is undefined, or null.
  101. // XXX why do we not do the same for pinned endpoints?
  102. try {
  103. this.dataChannels.sendSelectedEndpointMessage(
  104. this.selectedEndpoint);
  105. } catch (error) {
  106. GlobalOnErrorHandler.callErrorHandler(error);
  107. logger.error("Cannot sendSelectedEndpointMessage ",
  108. this.selectedEndpoint, ". Error: ", error);
  109. }
  110. this.removeListener(RTCEvents.DATA_CHANNEL_OPEN,
  111. this._dataChannelOpenListener);
  112. this._dataChannelOpenListener = null;
  113. };
  114. this.addListener(RTCEvents.DATA_CHANNEL_OPEN,
  115. this._dataChannelOpenListener);
  116. }
  117. };
  118. /**
  119. * Should be called when current media session ends and after the PeerConnection
  120. * has been closed using PeerConnection.close() method.
  121. */
  122. RTC.prototype.onCallEnded = function() {
  123. if (this.dataChannels) {
  124. // DataChannels are not explicitly closed as the PeerConnection
  125. // is closed on call ended which triggers data channel onclose events.
  126. // The reference is cleared to disable any logic related to the data
  127. // channels.
  128. this.dataChannels = null;
  129. }
  130. };
  131. /**
  132. * Elects the participant with the given id to be the selected participant in
  133. * order to always receive video for this participant (even when last n is
  134. * enabled).
  135. * If there is no data channel we store it and send it through the channel once
  136. * it is created.
  137. * @param id {string} the user id.
  138. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  139. */
  140. RTC.prototype.selectEndpoint = function (id) {
  141. // cache the value if channel is missing, till we open it
  142. this.selectedEndpoint = id;
  143. if(this.dataChannels)
  144. this.dataChannels.sendSelectedEndpointMessage(id);
  145. };
  146. /**
  147. * Elects the participant with the given id to be the pinned participant in
  148. * order to always receive video for this participant (even when last n is
  149. * enabled).
  150. * @param id {string} the user id
  151. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  152. */
  153. RTC.prototype.pinEndpoint = function (id) {
  154. if(this.dataChannels) {
  155. this.dataChannels.sendPinnedEndpointMessage(id);
  156. } else {
  157. // FIXME: cache value while there is no data channel created
  158. // and send the cached state once channel is created
  159. throw new Error("Data channels support is disabled!");
  160. }
  161. };
  162. RTC.prototype.addListener = function (type, listener) {
  163. this.eventEmitter.on(type, listener);
  164. };
  165. RTC.prototype.removeListener = function (eventType, listener) {
  166. this.eventEmitter.removeListener(eventType, listener);
  167. };
  168. RTC.addListener = function (eventType, listener) {
  169. RTCUtils.addListener(eventType, listener);
  170. };
  171. RTC.removeListener = function (eventType, listener) {
  172. RTCUtils.removeListener(eventType, listener)
  173. };
  174. RTC.isRTCReady = function () {
  175. return RTCUtils.isRTCReady();
  176. };
  177. RTC.init = function (options) {
  178. this.options = options || {};
  179. return RTCUtils.init(this.options);
  180. };
  181. RTC.getDeviceAvailability = function () {
  182. return RTCUtils.getDeviceAvailability();
  183. };
  184. RTC.prototype.addLocalTrack = function (track) {
  185. if (!track)
  186. throw new Error('track must not be null nor undefined');
  187. this.localTracks.push(track);
  188. track.conference = this.conference;
  189. if (track.isAudioTrack()) {
  190. this.localAudio = track;
  191. } else {
  192. this.localVideo = track;
  193. }
  194. };
  195. /**
  196. * Get local video track.
  197. * @returns {JitsiLocalTrack}
  198. */
  199. RTC.prototype.getLocalVideoTrack = function () {
  200. return this.localVideo;
  201. };
  202. /**
  203. * Gets JitsiRemoteTrack for the passed MediaType associated with given MUC
  204. * nickname (resource part of the JID).
  205. * @param type audio or video.
  206. * @param resource the resource part of the MUC JID
  207. * @returns {JitsiRemoteTrack|null}
  208. */
  209. RTC.prototype.getRemoteTrackByType = function (type, resource) {
  210. if (this.remoteTracks[resource])
  211. return this.remoteTracks[resource][type];
  212. else
  213. return null;
  214. };
  215. /**
  216. * Gets JitsiRemoteTrack for AUDIO MediaType associated with given MUC nickname
  217. * (resource part of the JID).
  218. * @param resource the resource part of the MUC JID
  219. * @returns {JitsiRemoteTrack|null}
  220. */
  221. RTC.prototype.getRemoteAudioTrack = function (resource) {
  222. return this.getRemoteTrackByType(MediaType.AUDIO, resource);
  223. };
  224. /**
  225. * Gets JitsiRemoteTrack for VIDEO MediaType associated with given MUC nickname
  226. * (resource part of the JID).
  227. * @param resource the resource part of the MUC JID
  228. * @returns {JitsiRemoteTrack|null}
  229. */
  230. RTC.prototype.getRemoteVideoTrack = function (resource) {
  231. return this.getRemoteTrackByType(MediaType.VIDEO, resource);
  232. };
  233. /**
  234. * Set mute for all local audio streams attached to the conference.
  235. * @param value the mute value
  236. * @returns {Promise}
  237. */
  238. RTC.prototype.setAudioMute = function (value) {
  239. var mutePromises = [];
  240. for(var i = 0; i < this.localTracks.length; i++) {
  241. var track = this.localTracks[i];
  242. if(track.getType() !== MediaType.AUDIO) {
  243. continue;
  244. }
  245. // this is a Promise
  246. mutePromises.push(value ? track.mute() : track.unmute());
  247. }
  248. // we return a Promise from all Promises so we can wait for their execution
  249. return Promise.all(mutePromises);
  250. };
  251. RTC.prototype.removeLocalTrack = function (track) {
  252. var pos = this.localTracks.indexOf(track);
  253. if (pos === -1) {
  254. return;
  255. }
  256. this.localTracks.splice(pos, 1);
  257. if (track.isAudioTrack()) {
  258. this.localAudio = null;
  259. } else {
  260. this.localVideo = null;
  261. }
  262. };
  263. /**
  264. * Initializes a new JitsiRemoteTrack instance with the data provided by (a)
  265. * ChatRoom to XMPPEvents.REMOTE_TRACK_ADDED.
  266. *
  267. * @param {Object} event the data provided by (a) ChatRoom to
  268. * XMPPEvents.REMOTE_TRACK_ADDED to (a)
  269. */
  270. RTC.prototype.createRemoteTrack = function (event) {
  271. var ownerJid = event.owner;
  272. var remoteTrack = new JitsiRemoteTrack(
  273. this.conference, ownerJid, event.stream, event.track,
  274. event.mediaType, event.videoType, event.ssrc, event.muted);
  275. var resource = Strophe.getResourceFromJid(ownerJid);
  276. var remoteTracks
  277. = this.remoteTracks[resource] || (this.remoteTracks[resource] = {});
  278. var mediaType = remoteTrack.getType();
  279. if (remoteTracks[mediaType]) {
  280. logger.warn("Overwriting remote track!", resource, mediaType);
  281. }
  282. remoteTracks[mediaType] = remoteTrack;
  283. return remoteTrack;
  284. };
  285. /**
  286. * Removes all JitsiRemoteTracks associated with given MUC nickname (resource
  287. * part of the JID). Returns array of removed tracks.
  288. *
  289. * @param {string} resource - The resource part of the MUC JID.
  290. * @returns {JitsiRemoteTrack[]}
  291. */
  292. RTC.prototype.removeRemoteTracks = function (resource) {
  293. var removedTracks = [];
  294. var removedAudioTrack = this.removeRemoteTrack(resource, MediaType.AUDIO);
  295. var removedVideoTrack = this.removeRemoteTrack(resource, MediaType.VIDEO);
  296. removedAudioTrack && removedTracks.push(removedAudioTrack);
  297. removedVideoTrack && removedTracks.push(removedVideoTrack);
  298. delete this.remoteTracks[resource];
  299. return removedTracks;
  300. };
  301. /**
  302. * Removes specified track type associated with given MUC nickname
  303. * (resource part of the JID). Returns removed track if any.
  304. *
  305. * @param {string} resource - The resource part of the MUC JID.
  306. * @param {string} mediaType - Type of track to remove.
  307. * @returns {JitsiRemoteTrack|undefined}
  308. */
  309. RTC.prototype.removeRemoteTrack = function (resource, mediaType) {
  310. var remoteTracksForResource = this.remoteTracks[resource];
  311. if (remoteTracksForResource && remoteTracksForResource[mediaType]) {
  312. var track = remoteTracksForResource[mediaType];
  313. track.dispose();
  314. delete remoteTracksForResource[mediaType];
  315. return track;
  316. }
  317. };
  318. RTC.getPCConstraints = function () {
  319. return RTCUtils.pc_constraints;
  320. };
  321. RTC.attachMediaStream = function (elSelector, stream) {
  322. return RTCUtils.attachMediaStream(elSelector, stream);
  323. };
  324. RTC.getStreamID = function (stream) {
  325. return RTCUtils.getStreamID(stream);
  326. };
  327. /**
  328. * Returns true if retrieving the the list of input devices is supported and
  329. * false if not.
  330. */
  331. RTC.isDeviceListAvailable = function () {
  332. return RTCUtils.isDeviceListAvailable();
  333. };
  334. /**
  335. * Returns true if changing the input (camera / microphone) or output
  336. * (audio) device is supported and false if not.
  337. * @params {string} [deviceType] - type of device to change. Default is
  338. * undefined or 'input', 'output' - for audio output device change.
  339. * @returns {boolean} true if available, false otherwise.
  340. */
  341. RTC.isDeviceChangeAvailable = function (deviceType) {
  342. return RTCUtils.isDeviceChangeAvailable(deviceType);
  343. };
  344. /**
  345. * Returns currently used audio output device id, '' stands for default
  346. * device
  347. * @returns {string}
  348. */
  349. RTC.getAudioOutputDevice = function () {
  350. return RTCUtils.getAudioOutputDevice();
  351. };
  352. /**
  353. * Returns list of available media devices if its obtained, otherwise an
  354. * empty array is returned/
  355. * @returns {Array} list of available media devices.
  356. */
  357. RTC.getCurrentlyAvailableMediaDevices = function () {
  358. return RTCUtils.getCurrentlyAvailableMediaDevices();
  359. };
  360. /**
  361. * Returns event data for device to be reported to stats.
  362. * @returns {MediaDeviceInfo} device.
  363. */
  364. RTC.getEventDataForActiveDevice = function (device) {
  365. return RTCUtils.getEventDataForActiveDevice(device);
  366. };
  367. /**
  368. * Sets current audio output device.
  369. * @param {string} deviceId - id of 'audiooutput' device from
  370. * navigator.mediaDevices.enumerateDevices()
  371. * @returns {Promise} - resolves when audio output is changed, is rejected
  372. * otherwise
  373. */
  374. RTC.setAudioOutputDevice = function (deviceId) {
  375. return RTCUtils.setAudioOutputDevice(deviceId);
  376. };
  377. /**
  378. * Returns <tt>true<tt/> if given WebRTC MediaStream is considered a valid
  379. * "user" stream which means that it's not a "receive only" stream nor a "mixed"
  380. * JVB stream.
  381. *
  382. * Clients that implement Unified Plan, such as Firefox use recvonly
  383. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed to
  384. * Plan B where there are only 3 channels: audio, video and data.
  385. *
  386. * @param stream WebRTC MediaStream instance
  387. * @returns {boolean}
  388. */
  389. RTC.isUserStream = function (stream) {
  390. var streamId = RTCUtils.getStreamID(stream);
  391. return streamId && streamId !== "mixedmslabel" && streamId !== "default";
  392. };
  393. /**
  394. * Allows to receive list of available cameras/microphones.
  395. * @param {function} callback would receive array of devices as an argument
  396. */
  397. RTC.enumerateDevices = function (callback) {
  398. RTCUtils.enumerateDevices(callback);
  399. };
  400. /**
  401. * A method to handle stopping of the stream.
  402. * One point to handle the differences in various implementations.
  403. * @param mediaStream MediaStream object to stop.
  404. */
  405. RTC.stopMediaStream = function (mediaStream) {
  406. RTCUtils.stopMediaStream(mediaStream);
  407. };
  408. /**
  409. * Returns whether the desktop sharing is enabled or not.
  410. * @returns {boolean}
  411. */
  412. RTC.isDesktopSharingEnabled = function () {
  413. return RTCUtils.isDesktopSharingEnabled();
  414. };
  415. /**
  416. * Closes all currently opened data channels.
  417. */
  418. RTC.prototype.closeAllDataChannels = function () {
  419. if(this.dataChannels)
  420. this.dataChannels.closeAllChannels();
  421. };
  422. RTC.prototype.dispose = function() {
  423. };
  424. /*
  425. //FIXME Never used, but probably *should* be used for switching
  426. // between camera and screen, but has to be adjusted to work with tracks.
  427. // Current when switching to desktop we can see recv-only being advertised
  428. // because we do remove and add.
  429. //
  430. // Leaving it commented out, in order to not forget about FF specific
  431. // thing
  432. RTC.prototype.switchVideoTracks = function (newStream) {
  433. this.localVideo.stream = newStream;
  434. this.localTracks = [];
  435. //in firefox we have only one stream object
  436. if (this.localAudio.getOriginalStream() != newStream)
  437. this.localTracks.push(this.localAudio);
  438. this.localTracks.push(this.localVideo);
  439. };*/
  440. RTC.prototype.setAudioLevel = function (resource, audioLevel) {
  441. if(!resource)
  442. return;
  443. var audioTrack = this.getRemoteAudioTrack(resource);
  444. if(audioTrack) {
  445. audioTrack.setAudioLevel(audioLevel);
  446. }
  447. };
  448. /**
  449. * Searches in localTracks(session stores ssrc for audio and video) and
  450. * remoteTracks for the ssrc and returns the corresponding resource.
  451. * @param ssrc the ssrc to check.
  452. */
  453. RTC.prototype.getResourceBySSRC = function (ssrc) {
  454. if((this.localVideo && ssrc == this.localVideo.getSSRC())
  455. || (this.localAudio && ssrc == this.localAudio.getSSRC())) {
  456. return this.conference.myUserId();
  457. }
  458. var track = this.getRemoteTrackBySSRC(ssrc);
  459. return track? track.getParticipantId() : null;
  460. };
  461. /**
  462. * Searches in remoteTracks for the ssrc and returns the corresponding track.
  463. * @param ssrc the ssrc to check.
  464. */
  465. RTC.prototype.getRemoteTrackBySSRC = function (ssrc) {
  466. for (var resource in this.remoteTracks) {
  467. var track = this.getRemoteAudioTrack(resource);
  468. if(track && track.getSSRC() == ssrc) {
  469. return track;
  470. }
  471. track = this.getRemoteVideoTrack(resource);
  472. if(track && track.getSSRC() == ssrc) {
  473. return track;
  474. }
  475. }
  476. return null;
  477. };
  478. /**
  479. * Handles remote track mute / unmute events.
  480. * @param type {string} "audio" or "video"
  481. * @param isMuted {boolean} the new mute state
  482. * @param from {string} user id
  483. */
  484. RTC.prototype.handleRemoteTrackMute = function (type, isMuted, from) {
  485. var track = this.getRemoteTrackByType(type, from);
  486. if (track) {
  487. track.setMute(isMuted);
  488. }
  489. }
  490. /**
  491. * Handles remote track video type events
  492. * @param value {string} the new video type
  493. * @param from {string} user id
  494. */
  495. RTC.prototype.handleRemoteTrackVideoTypeChanged = function (value, from) {
  496. var videoTrack = this.getRemoteVideoTrack(from);
  497. if (videoTrack) {
  498. videoTrack._setVideoType(value);
  499. }
  500. }
  501. /**
  502. * Sends message via the datachannels.
  503. * @param to {string} the id of the endpoint that should receive the message.
  504. * If "" the message will be sent to all participants.
  505. * @param payload {object} the payload of the message.
  506. * @throws NetworkError or InvalidStateError or Error if the operation fails
  507. * or there is no data channel created
  508. */
  509. RTC.prototype.sendDataChannelMessage = function (to, payload) {
  510. if(this.dataChannels) {
  511. this.dataChannels.sendDataChannelMessage(to, payload);
  512. } else {
  513. throw new Error("Data channels support is disabled!");
  514. }
  515. }
  516. module.exports = RTC;