您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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