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.

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