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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 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, trackInfo.resolution, deviceId);
  29. newTracks.push(localTrack);
  30. });
  31. return newTracks;
  32. }
  33. function RTC(room, options) {
  34. this.room = room;
  35. this.localTracks = [];
  36. //FIXME: We should support multiple streams per jid.
  37. this.remoteTracks = {};
  38. this.localAudio = null;
  39. this.localVideo = null;
  40. this.eventEmitter = new EventEmitter();
  41. var self = this;
  42. this.options = options || {};
  43. room.addPresenceListener("videomuted", function (values, from) {
  44. var videoTrack = self.getRemoteVideoTrack(from);
  45. if (videoTrack) {
  46. videoTrack.setMute(values.value == "true");
  47. }
  48. });
  49. room.addPresenceListener("audiomuted", function (values, from) {
  50. var audioTrack = self.getRemoteAudioTrack(from);
  51. if (audioTrack) {
  52. audioTrack.setMute(values.value == "true");
  53. }
  54. });
  55. room.addPresenceListener("videoType", function(data, from) {
  56. var videoTrack = self.getRemoteVideoTrack(from);
  57. if (videoTrack) {
  58. videoTrack._setVideoType(data.value);
  59. }
  60. });
  61. // Switch audio output device on all remote audio tracks. Local audio tracks
  62. // handle this event by themselves.
  63. if (RTCUtils.isDeviceChangeAvailable('output')) {
  64. RTCUtils.addListener(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  65. function (deviceId) {
  66. for (var key in self.remoteTracks) {
  67. if (self.remoteTracks.hasOwnProperty(key)
  68. && self.remoteTracks[key].audio) {
  69. self.remoteTracks[key].audio.setAudioOutput(deviceId);
  70. }
  71. }
  72. });
  73. }
  74. }
  75. /**
  76. * Creates the local MediaStreams.
  77. * @param {Object} [options] optional parameters
  78. * @param {Array} options.devices the devices that will be requested
  79. * @param {string} options.resolution resolution constraints
  80. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the
  81. * following structure {stream: the Media Stream,
  82. * type: "audio" or "video", videoType: "camera" or "desktop"}
  83. * will be returned trough the Promise, otherwise JitsiTrack objects will be
  84. * returned.
  85. * @param {string} options.cameraDeviceId
  86. * @param {string} options.micDeviceId
  87. * @returns {*} Promise object that will receive the new JitsiTracks
  88. */
  89. RTC.obtainAudioAndVideoPermissions = function (options) {
  90. return RTCUtils.obtainAudioAndVideoPermissions(options).then(
  91. function (tracksInfo) {
  92. return createLocalTracks(tracksInfo, options);
  93. });
  94. };
  95. RTC.prototype.onIncommingCall = function(event) {
  96. if(this.options.config.openSctp)
  97. this.dataChannels = new DataChannels(event.peerconnection,
  98. this.eventEmitter);
  99. // Add local Tracks to the ChatRoom
  100. this.localTracks.forEach(function(localTrack) {
  101. var ssrcInfo = null;
  102. if(localTrack.isVideoTrack() && localTrack.isMuted()) {
  103. /**
  104. * Handles issues when the stream is added before the peerconnection
  105. * is created. The peerconnection is created when second participant
  106. * enters the call. In that use case the track doesn't have
  107. * information about it's ssrcs and no jingle packets are sent. That
  108. * can cause inconsistent behavior later.
  109. *
  110. * For example:
  111. * If we mute the stream and than second participant enter it's
  112. * remote SDP won't include that track. On unmute we are not sending
  113. * any jingle packets which will brake the unmute.
  114. *
  115. * In order to solve issues like the above one here we have to
  116. * generate the ssrc information for the track .
  117. */
  118. localTrack._setSSRC(
  119. this.room.generateNewStreamSSRCInfo());
  120. ssrcInfo = {
  121. mtype: localTrack.getType(),
  122. type: "addMuted",
  123. ssrc: localTrack.ssrc,
  124. msid: localTrack.initialMSID
  125. };
  126. }
  127. try {
  128. this.room.addStream(
  129. localTrack.getOriginalStream(), function () {}, ssrcInfo, true);
  130. } catch(e) {
  131. GlobalOnErrorHandler.callErrorHandler(e);
  132. logger.error(e);
  133. }
  134. }.bind(this));
  135. };
  136. RTC.prototype.selectedEndpoint = function (id) {
  137. if(this.dataChannels)
  138. this.dataChannels.handleSelectedEndpointEvent(id);
  139. };
  140. RTC.prototype.pinEndpoint = function (id) {
  141. if(this.dataChannels)
  142. this.dataChannels.handlePinnedEndpointEvent(id);
  143. };
  144. RTC.prototype.addListener = function (type, listener) {
  145. this.eventEmitter.on(type, listener);
  146. };
  147. RTC.prototype.removeListener = function (eventType, listener) {
  148. this.eventEmitter.removeListener(eventType, listener);
  149. };
  150. RTC.addListener = function (eventType, listener) {
  151. RTCUtils.addListener(eventType, listener);
  152. };
  153. RTC.removeListener = function (eventType, listener) {
  154. RTCUtils.removeListener(eventType, listener)
  155. };
  156. RTC.isRTCReady = function () {
  157. return RTCUtils.isRTCReady();
  158. };
  159. RTC.init = function (options) {
  160. this.options = options || {};
  161. return RTCUtils.init(this.options);
  162. };
  163. RTC.getDeviceAvailability = function () {
  164. return RTCUtils.getDeviceAvailability();
  165. };
  166. RTC.prototype.addLocalTrack = function (track) {
  167. if (!track)
  168. throw new Error('track must not be null nor undefined');
  169. this.localTracks.push(track);
  170. track._setRTC(this);
  171. if (track.isAudioTrack()) {
  172. this.localAudio = track;
  173. } else {
  174. this.localVideo = track;
  175. }
  176. };
  177. /**
  178. * Get local video track.
  179. * @returns {JitsiLocalTrack}
  180. */
  181. RTC.prototype.getLocalVideoTrack = function () {
  182. return this.localVideo;
  183. };
  184. /**
  185. * Gets JitsiRemoteTrack for AUDIO MediaType associated with given MUC nickname
  186. * (resource part of the JID).
  187. * @param resource the resource part of the MUC JID
  188. * @returns {JitsiRemoteTrack|null}
  189. */
  190. RTC.prototype.getRemoteAudioTrack = function (resource) {
  191. if (this.remoteTracks[resource])
  192. return this.remoteTracks[resource][MediaType.AUDIO];
  193. else
  194. return null;
  195. };
  196. /**
  197. * Gets JitsiRemoteTrack for VIDEO MediaType associated with given MUC nickname
  198. * (resource part of the JID).
  199. * @param resource the resource part of the MUC JID
  200. * @returns {JitsiRemoteTrack|null}
  201. */
  202. RTC.prototype.getRemoteVideoTrack = function (resource) {
  203. if (this.remoteTracks[resource])
  204. return this.remoteTracks[resource][MediaType.VIDEO];
  205. else
  206. return null;
  207. };
  208. /**
  209. * Set mute for all local audio streams attached to the conference.
  210. * @param value the mute value
  211. * @returns {Promise}
  212. */
  213. RTC.prototype.setAudioMute = function (value) {
  214. var mutePromises = [];
  215. for(var i = 0; i < this.localTracks.length; i++) {
  216. var track = this.localTracks[i];
  217. if(track.getType() !== MediaType.AUDIO) {
  218. continue;
  219. }
  220. // this is a Promise
  221. mutePromises.push(value ? track.mute() : track.unmute());
  222. }
  223. // we return a Promise from all Promises so we can wait for their execution
  224. return Promise.all(mutePromises);
  225. };
  226. RTC.prototype.removeLocalTrack = function (track) {
  227. var pos = this.localTracks.indexOf(track);
  228. if (pos === -1) {
  229. return;
  230. }
  231. this.localTracks.splice(pos, 1);
  232. if (track.isAudioTrack()) {
  233. this.localAudio = null;
  234. } else {
  235. this.localVideo = null;
  236. }
  237. };
  238. /**
  239. * Initializes a new JitsiRemoteTrack instance with the data provided by (a)
  240. * ChatRoom to XMPPEvents.REMOTE_TRACK_ADDED.
  241. *
  242. * @param {Object} event the data provided by (a) ChatRoom to
  243. * XMPPEvents.REMOTE_TRACK_ADDED to (a)
  244. */
  245. RTC.prototype.createRemoteTrack = function (event) {
  246. var ownerJid = event.owner;
  247. var remoteTrack = new JitsiRemoteTrack(
  248. this, ownerJid, event.stream, event.track,
  249. event.mediaType, event.videoType, event.ssrc, event.muted);
  250. var resource = Strophe.getResourceFromJid(ownerJid);
  251. var remoteTracks
  252. = this.remoteTracks[resource] || (this.remoteTracks[resource] = {});
  253. var mediaType = remoteTrack.getType();
  254. if (remoteTracks[mediaType]) {
  255. logger.warn("Overwriting remote track!", resource, mediaType);
  256. }
  257. remoteTracks[mediaType] = remoteTrack;
  258. return remoteTrack;
  259. };
  260. /**
  261. * Removes all JitsiRemoteTracks associated with given MUC nickname (resource
  262. * part of the JID).
  263. * @param resource the resource part of the MUC JID
  264. * @returns {JitsiRemoteTrack|null}
  265. */
  266. RTC.prototype.removeRemoteTracks = function (resource) {
  267. var remoteTracks = this.remoteTracks[resource];
  268. if(remoteTracks) {
  269. remoteTracks['audio'] && remoteTracks['audio'].dispose();
  270. remoteTracks['video'] && remoteTracks['video'].dispose();
  271. delete this.remoteTracks[resource];
  272. }
  273. };
  274. RTC.getPCConstraints = function () {
  275. return RTCUtils.pc_constraints;
  276. };
  277. RTC.attachMediaStream = function (elSelector, stream) {
  278. return RTCUtils.attachMediaStream(elSelector, stream);
  279. };
  280. RTC.getStreamID = function (stream) {
  281. return RTCUtils.getStreamID(stream);
  282. };
  283. RTC.getVideoSrc = function (element) {
  284. return RTCUtils.getVideoSrc(element);
  285. };
  286. /**
  287. * Returns true if retrieving the the list of input devices is supported and
  288. * false if not.
  289. */
  290. RTC.isDeviceListAvailable = function () {
  291. return RTCUtils.isDeviceListAvailable();
  292. };
  293. /**
  294. * Returns true if changing the input (camera / microphone) or output
  295. * (audio) device is supported and false if not.
  296. * @params {string} [deviceType] - type of device to change. Default is
  297. * undefined or 'input', 'output' - for audio output device change.
  298. * @returns {boolean} true if available, false otherwise.
  299. */
  300. RTC.isDeviceChangeAvailable = function (deviceType) {
  301. return RTCUtils.isDeviceChangeAvailable(deviceType);
  302. };
  303. /**
  304. * Returns currently used audio output device id, '' stands for default
  305. * device
  306. * @returns {string}
  307. */
  308. RTC.getAudioOutputDevice = function () {
  309. return RTCUtils.getAudioOutputDevice();
  310. };
  311. /**
  312. * Sets current audio output device.
  313. * @param {string} deviceId - id of 'audiooutput' device from
  314. * navigator.mediaDevices.enumerateDevices()
  315. * @returns {Promise} - resolves when audio output is changed, is rejected
  316. * otherwise
  317. */
  318. RTC.setAudioOutputDevice = function (deviceId) {
  319. return RTCUtils.setAudioOutputDevice(deviceId);
  320. };
  321. /**
  322. * Returns <tt>true<tt/> if given WebRTC MediaStream is considered a valid
  323. * "user" stream which means that it's not a "receive only" stream nor a "mixed"
  324. * JVB stream.
  325. *
  326. * Clients that implement Unified Plan, such as Firefox use recvonly
  327. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed to
  328. * Plan B where there are only 3 channels: audio, video and data.
  329. *
  330. * @param stream WebRTC MediaStream instance
  331. * @returns {boolean}
  332. */
  333. RTC.isUserStream = function (stream) {
  334. var streamId = RTCUtils.getStreamID(stream);
  335. return streamId && streamId !== "mixedmslabel" && streamId !== "default";
  336. };
  337. /**
  338. * Allows to receive list of available cameras/microphones.
  339. * @param {function} callback would receive array of devices as an argument
  340. */
  341. RTC.enumerateDevices = function (callback) {
  342. RTCUtils.enumerateDevices(callback);
  343. };
  344. RTC.setVideoSrc = function (element, src) {
  345. RTCUtils.setVideoSrc(element, src);
  346. };
  347. /**
  348. * A method to handle stopping of the stream.
  349. * One point to handle the differences in various implementations.
  350. * @param mediaStream MediaStream object to stop.
  351. */
  352. RTC.stopMediaStream = function (mediaStream) {
  353. RTCUtils.stopMediaStream(mediaStream);
  354. };
  355. /**
  356. * Returns whether the desktop sharing is enabled or not.
  357. * @returns {boolean}
  358. */
  359. RTC.isDesktopSharingEnabled = function () {
  360. return RTCUtils.isDesktopSharingEnabled();
  361. };
  362. /**
  363. * Closes all currently opened data channels.
  364. */
  365. RTC.prototype.closeAllDataChannels = function () {
  366. this.dataChannels.closeAllChannels();
  367. };
  368. RTC.prototype.dispose = function() {
  369. };
  370. /*
  371. //FIXME Never used, but probably *should* be used for switching
  372. // between camera and screen, but has to be adjusted to work with tracks.
  373. // Current when switching to desktop we can see recv-only being advertised
  374. // because we do remove and add.
  375. //
  376. // Leaving it commented out, in order to not forget about FF specific
  377. // thing
  378. RTC.prototype.switchVideoTracks = function (newStream) {
  379. this.localVideo.stream = newStream;
  380. this.localTracks = [];
  381. //in firefox we have only one stream object
  382. if (this.localAudio.getOriginalStream() != newStream)
  383. this.localTracks.push(this.localAudio);
  384. this.localTracks.push(this.localVideo);
  385. };*/
  386. RTC.prototype.setAudioLevel = function (resource, audioLevel) {
  387. if(!resource)
  388. return;
  389. var audioTrack = this.getRemoteAudioTrack(resource);
  390. if(audioTrack) {
  391. audioTrack.setAudioLevel(audioLevel);
  392. }
  393. };
  394. /**
  395. * Searches in localTracks(session stores ssrc for audio and video) and
  396. * remoteTracks for the ssrc and returns the corresponding resource.
  397. * @param ssrc the ssrc to check.
  398. */
  399. RTC.prototype.getResourceBySSRC = function (ssrc) {
  400. if((this.localVideo && ssrc == this.localVideo.getSSRC())
  401. || (this.localAudio && ssrc == this.localAudio.getSSRC())) {
  402. return Strophe.getResourceFromJid(this.room.myroomjid);
  403. }
  404. var self = this;
  405. var resultResource = null;
  406. Object.keys(this.remoteTracks).some(function (resource) {
  407. var audioTrack = self.getRemoteAudioTrack(resource);
  408. var videoTrack = self.getRemoteVideoTrack(resource);
  409. if((audioTrack && audioTrack.getSSRC() == ssrc) ||
  410. (videoTrack && videoTrack.getSSRC() == ssrc)) {
  411. resultResource = resource;
  412. return true;
  413. }
  414. });
  415. return resultResource;
  416. };
  417. module.exports = RTC;