Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

RTC.js 18KB

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