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

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