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 19KB

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