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.

SignalingLayerImpl.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. import { getLogger } from '@jitsi/logger';
  2. import { Strophe } from 'strophe.js';
  3. import * as MediaType from '../../service/RTC/MediaType';
  4. import * as SignalingEvents from '../../service/RTC/SignalingEvents';
  5. import SignalingLayer, { getMediaTypeFromSourceName } from '../../service/RTC/SignalingLayer';
  6. import VideoType from '../../service/RTC/VideoType';
  7. import { XMPPEvents } from '../../service/xmpp/XMPPEvents';
  8. import FeatureFlags from '../flags/FeatureFlags';
  9. import { filterNodeFromPresenceJSON } from './ChatRoom';
  10. const logger = getLogger(__filename);
  11. export const SOURCE_INFO_PRESENCE_ELEMENT = 'SourceInfo';
  12. /**
  13. * Default XMPP implementation of the {@link SignalingLayer} interface. Obtains
  14. * the data from the MUC presence.
  15. */
  16. export default class SignalingLayerImpl extends SignalingLayer {
  17. /**
  18. * Creates new instance.
  19. */
  20. constructor() {
  21. super();
  22. /**
  23. * A map that stores SSRCs of remote streams. And is used only locally
  24. * We store the mapping when jingle is received, and later is used
  25. * onaddstream webrtc event where we have only the ssrc
  26. * FIXME: This map got filled and never cleaned and can grow during long
  27. * conference
  28. * @type {Map<number, string>} maps SSRC number to jid
  29. */
  30. this.ssrcOwners = new Map();
  31. /**
  32. *
  33. * @type {ChatRoom|null}
  34. */
  35. this.chatRoom = null;
  36. /**
  37. * @type {Map<SourceName, SourceInfo>}
  38. * @private
  39. */
  40. this._localSourceState = { };
  41. /**
  42. * @type {Map<EndpointId, Map<SourceName, SourceInfo>>}
  43. * @private
  44. */
  45. this._remoteSourceState = { };
  46. /**
  47. * A map that stores the source name of a track identified by it's ssrc.
  48. * We store the mapping when jingle is received, and later is used
  49. * onaddstream webrtc event where we have only the ssrc
  50. * FIXME: This map got filled and never cleaned and can grow during long
  51. * conference
  52. * @type {Map<number, string>} maps SSRC number to source name
  53. */
  54. this._sourceNames = new Map();
  55. }
  56. /**
  57. * Adds <SourceInfo> element to the local presence.
  58. *
  59. * @returns {void}
  60. * @private
  61. */
  62. _addLocalSourceInfoToPresence() {
  63. if (this.chatRoom) {
  64. return this.chatRoom.addOrReplaceInPresence(
  65. SOURCE_INFO_PRESENCE_ELEMENT,
  66. { value: JSON.stringify(this._localSourceState) });
  67. }
  68. return false;
  69. }
  70. /**
  71. * Check is given endpoint has advertised <SourceInfo/> in it's presence which means that the source name signaling
  72. * is used by this endpoint.
  73. *
  74. * @param {EndpointId} endpointId
  75. * @returns {boolean}
  76. */
  77. _doesEndpointSendNewSourceInfo(endpointId) {
  78. const presence = this.chatRoom?.getLastPresence(endpointId);
  79. return Boolean(presence && presence.find(node => node.tagName === SOURCE_INFO_PRESENCE_ELEMENT));
  80. }
  81. /**
  82. * Sets the <tt>ChatRoom</tt> instance used and binds presence listeners.
  83. * @param {ChatRoom} room
  84. */
  85. setChatRoom(room) {
  86. const oldChatRoom = this.chatRoom;
  87. this.chatRoom = room;
  88. if (oldChatRoom) {
  89. oldChatRoom.removePresenceListener(
  90. 'audiomuted', this._audioMuteHandler);
  91. oldChatRoom.removePresenceListener(
  92. 'videomuted', this._videoMuteHandler);
  93. oldChatRoom.removePresenceListener(
  94. 'videoType', this._videoTypeHandler);
  95. if (FeatureFlags.isSourceNameSignalingEnabled()) {
  96. this._sourceInfoHandler
  97. && oldChatRoom.removePresenceListener(
  98. SOURCE_INFO_PRESENCE_ELEMENT, this._sourceInfoHandler);
  99. this._memberLeftHandler
  100. && oldChatRoom.removeEventListener(
  101. XMPPEvents.MUC_MEMBER_LEFT, this._memberLeftHandler);
  102. }
  103. }
  104. if (room) {
  105. if (FeatureFlags.isSourceNameSignalingEnabled()) {
  106. this._bindChatRoomEventHandlers(room);
  107. this._addLocalSourceInfoToPresence();
  108. } else {
  109. // TODO the logic below has been duplicated in _bindChatRoomEventHandlers, clean this up once
  110. // the new impl has been tested well enough
  111. // SignalingEvents
  112. this._audioMuteHandler = (node, from) => {
  113. this.eventEmitter.emit(
  114. SignalingEvents.PEER_MUTED_CHANGED,
  115. from, MediaType.AUDIO, node.value === 'true');
  116. };
  117. room.addPresenceListener('audiomuted', this._audioMuteHandler);
  118. this._videoMuteHandler = (node, from) => {
  119. this.eventEmitter.emit(
  120. SignalingEvents.PEER_MUTED_CHANGED,
  121. from, MediaType.VIDEO, node.value === 'true');
  122. };
  123. room.addPresenceListener('videomuted', this._videoMuteHandler);
  124. this._videoTypeHandler = (node, from) => {
  125. this.eventEmitter.emit(
  126. SignalingEvents.PEER_VIDEO_TYPE_CHANGED,
  127. from, node.value);
  128. };
  129. room.addPresenceListener('videoType', this._videoTypeHandler);
  130. }
  131. }
  132. }
  133. /**
  134. * Binds event listeners to the chat room instance.
  135. * @param {ChatRoom} room
  136. * @private
  137. * @returns {void}
  138. */
  139. _bindChatRoomEventHandlers(room) {
  140. const emitAudioMutedEvent = (endpointId, muted) => {
  141. this.eventEmitter.emit(
  142. SignalingEvents.PEER_MUTED_CHANGED,
  143. endpointId,
  144. MediaType.AUDIO,
  145. muted);
  146. };
  147. const emitVideoMutedEvent = (endpointId, muted) => {
  148. this.eventEmitter.emit(
  149. SignalingEvents.PEER_MUTED_CHANGED,
  150. endpointId,
  151. MediaType.VIDEO,
  152. muted);
  153. };
  154. // SignalingEvents
  155. this._audioMuteHandler = (node, from) => {
  156. if (!this._doesEndpointSendNewSourceInfo(from)) {
  157. emitAudioMutedEvent(from, node.value === 'true');
  158. }
  159. };
  160. room.addPresenceListener('audiomuted', this._audioMuteHandler);
  161. this._videoMuteHandler = (node, from) => {
  162. if (!this._doesEndpointSendNewSourceInfo(from)) {
  163. emitVideoMutedEvent(from, node.value === 'true');
  164. }
  165. };
  166. room.addPresenceListener('videomuted', this._videoMuteHandler);
  167. const emitVideoTypeEvent = (endpointId, videoType) => {
  168. this.eventEmitter.emit(
  169. SignalingEvents.PEER_VIDEO_TYPE_CHANGED,
  170. endpointId, videoType);
  171. };
  172. this._videoTypeHandler = (node, from) => {
  173. if (!this._doesEndpointSendNewSourceInfo(from)) {
  174. emitVideoTypeEvent(from, node.value);
  175. }
  176. };
  177. if (!FeatureFlags.isMultiStreamSupportEnabled()) {
  178. room.addPresenceListener('videoType', this._videoTypeHandler);
  179. }
  180. this._sourceInfoHandler = (node, mucNick) => {
  181. const endpointId = mucNick;
  182. const { value } = node;
  183. const sourceInfoJSON = JSON.parse(value);
  184. const emitEventsFromHere = this._doesEndpointSendNewSourceInfo(endpointId);
  185. const endpointSourceState
  186. = this._remoteSourceState[endpointId] || (this._remoteSourceState[endpointId] = {});
  187. for (const sourceName of Object.keys(sourceInfoJSON)) {
  188. const mediaType = getMediaTypeFromSourceName(sourceName);
  189. const newMutedState = Boolean(sourceInfoJSON[sourceName].muted);
  190. const oldSourceState = endpointSourceState[sourceName]
  191. || (endpointSourceState[sourceName] = { sourceName });
  192. if (oldSourceState.muted !== newMutedState) {
  193. oldSourceState.muted = newMutedState;
  194. if (emitEventsFromHere && mediaType === MediaType.AUDIO) {
  195. emitAudioMutedEvent(endpointId, newMutedState);
  196. } else {
  197. emitVideoMutedEvent(endpointId, newMutedState);
  198. }
  199. }
  200. // Assume a default videoType of 'camera' for video sources.
  201. const newVideoType = mediaType === MediaType.VIDEO
  202. ? sourceInfoJSON[sourceName].videoType ?? VideoType.CAMERA
  203. : undefined;
  204. if (oldSourceState.videoType !== newVideoType) {
  205. oldSourceState.videoType = newVideoType;
  206. // videoType is not allowed to change on a given JitsiLocalTrack when multi stream support is
  207. // enabled.
  208. emitEventsFromHere
  209. && !FeatureFlags.isMultiStreamSupportEnabled()
  210. && emitVideoTypeEvent(endpointId, newVideoType);
  211. }
  212. }
  213. // Cleanup removed source names
  214. const newSourceNames = Object.keys(sourceInfoJSON);
  215. for (const sourceName of Object.keys(endpointSourceState)) {
  216. if (newSourceNames.indexOf(sourceName) === -1) {
  217. delete endpointSourceState[sourceName];
  218. }
  219. }
  220. };
  221. room.addPresenceListener('SourceInfo', this._sourceInfoHandler);
  222. // Cleanup when participant leaves
  223. this._memberLeftHandler = jid => {
  224. const endpointId = Strophe.getResourceFromJid(jid);
  225. delete this._remoteSourceState[endpointId];
  226. if (FeatureFlags.isSourceNameSignalingEnabled()) {
  227. for (const [ key, value ] of this.ssrcOwners.entries()) {
  228. if (value === endpointId) {
  229. delete this._sourceNames[key];
  230. }
  231. }
  232. }
  233. };
  234. room.addEventListener(XMPPEvents.MUC_MEMBER_LEFT, this._memberLeftHandler);
  235. }
  236. /**
  237. * Finds the first source of given media type for the given endpoint.
  238. * @param endpointId
  239. * @param mediaType
  240. * @returns {SourceInfo|null}
  241. * @private
  242. */
  243. _findEndpointSourceInfoForMediaType(endpointId, mediaType) {
  244. const remoteSourceState = this._remoteSourceState[endpointId];
  245. if (!remoteSourceState) {
  246. return null;
  247. }
  248. for (const sourceInfo of Object.values(remoteSourceState)) {
  249. const _mediaType = getMediaTypeFromSourceName(sourceInfo.sourceName);
  250. if (_mediaType === mediaType) {
  251. return sourceInfo;
  252. }
  253. }
  254. return null;
  255. }
  256. /**
  257. * @inheritDoc
  258. */
  259. getPeerMediaInfo(owner, mediaType) {
  260. const legacyGetPeerMediaInfo = () => {
  261. if (this.chatRoom) {
  262. return this.chatRoom.getMediaPresenceInfo(owner, mediaType);
  263. }
  264. logger.error('Requested peer media info, before room was set');
  265. };
  266. if (FeatureFlags.isSourceNameSignalingEnabled()) {
  267. const lastPresence = this.chatRoom.getLastPresence(owner);
  268. if (!lastPresence) {
  269. throw new Error(`getPeerMediaInfo - no presence stored for: ${owner}`);
  270. }
  271. if (!this._doesEndpointSendNewSourceInfo(owner)) {
  272. return legacyGetPeerMediaInfo();
  273. }
  274. /**
  275. * @type {PeerMediaInfo}
  276. */
  277. const mediaInfo = {};
  278. const endpointMediaSource = this._findEndpointSourceInfoForMediaType(owner, mediaType);
  279. // The defaults are provided only, because getPeerMediaInfo is a legacy method. This will be eventually
  280. // changed into a getSourceInfo method which returns undefined if there's no source. Also there will be
  281. // no mediaType argument there.
  282. if (mediaType === MediaType.AUDIO) {
  283. mediaInfo.muted = endpointMediaSource ? endpointMediaSource.muted : true;
  284. } else if (mediaType === MediaType.VIDEO) {
  285. mediaInfo.muted = endpointMediaSource ? endpointMediaSource.muted : true;
  286. mediaInfo.videoType = endpointMediaSource ? endpointMediaSource.videoType : undefined;
  287. const codecTypeNode = filterNodeFromPresenceJSON(lastPresence, 'jitsi_participant_codecType');
  288. if (codecTypeNode.length > 0) {
  289. mediaInfo.codecType = codecTypeNode[0].value;
  290. }
  291. } else {
  292. throw new Error(`Unsupported media type: ${mediaType}`);
  293. }
  294. return mediaInfo;
  295. }
  296. return legacyGetPeerMediaInfo();
  297. }
  298. /**
  299. * @inheritDoc
  300. */
  301. getPeerSourceInfo(owner, sourceName) {
  302. return this._remoteSourceState[owner] ? this._remoteSourceState[owner][sourceName] : undefined;
  303. }
  304. /**
  305. * @inheritDoc
  306. */
  307. getSSRCOwner(ssrc) {
  308. return this.ssrcOwners.get(ssrc);
  309. }
  310. /**
  311. * Set an SSRC owner.
  312. * @param {number} ssrc an SSRC to be owned
  313. * @param {string} endpointId owner's ID (MUC nickname)
  314. * @throws TypeError if <tt>ssrc</tt> is not a number
  315. */
  316. setSSRCOwner(ssrc, endpointId) {
  317. if (typeof ssrc !== 'number') {
  318. throw new TypeError(`SSRC(${ssrc}) must be a number`);
  319. }
  320. // Now signaling layer instance is shared between different JingleSessionPC instances, so although very unlikely
  321. // an SSRC conflict could potentially occur. Log a message to make debugging easier.
  322. const existingOwner = this.ssrcOwners.get(ssrc);
  323. if (existingOwner && existingOwner !== endpointId) {
  324. logger.error(`SSRC owner re-assigned from ${existingOwner} to ${endpointId}`);
  325. }
  326. this.ssrcOwners.set(ssrc, endpointId);
  327. }
  328. /**
  329. * Adjusts muted status of given track.
  330. *
  331. * @param {SourceName} sourceName - the name of the track's source.
  332. * @param {boolean} muted - the new muted status.
  333. * @returns {boolean}
  334. */
  335. setTrackMuteStatus(sourceName, muted) {
  336. if (!this._localSourceState[sourceName]) {
  337. this._localSourceState[sourceName] = {};
  338. }
  339. this._localSourceState[sourceName].muted = muted;
  340. if (this.chatRoom) {
  341. // FIXME This only adjusts the presence, but doesn't actually send it. Here we temporarily rely on
  342. // the legacy signaling part to send the presence. Remember to add "send presence" here when the legacy
  343. // signaling is removed.
  344. return this._addLocalSourceInfoToPresence();
  345. }
  346. return false;
  347. }
  348. /**
  349. * Sets track's video type.
  350. * @param {SourceName} sourceName - the track's source name.
  351. * @param {VideoType} videoType - the new video type.
  352. * @returns {boolean}
  353. */
  354. setTrackVideoType(sourceName, videoType) {
  355. if (!this._localSourceState[sourceName]) {
  356. this._localSourceState[sourceName] = {};
  357. }
  358. if (this._localSourceState[sourceName].videoType !== videoType) {
  359. // Include only if not a camera (default)
  360. this._localSourceState[sourceName].videoType = videoType === VideoType.CAMERA ? undefined : videoType;
  361. // NOTE this doesn't send the actual presence, because is called from the same place where the legacy video
  362. // type is emitted which does the actual sending. A send presence statement needs to be added when
  363. // the legacy part is removed.
  364. return this._addLocalSourceInfoToPresence();
  365. }
  366. return false;
  367. }
  368. /**
  369. * @inheritDoc
  370. */
  371. getTrackSourceName(ssrc) {
  372. return this._sourceNames.get(ssrc);
  373. }
  374. /**
  375. * Saves the source name for a track identified by it's ssrc.
  376. * @param {number} ssrc the ssrc of the target track.
  377. * @param {SourceName} sourceName the track's source name to save.
  378. * @throws TypeError if <tt>ssrc</tt> is not a number
  379. */
  380. setTrackSourceName(ssrc, sourceName) {
  381. if (typeof ssrc !== 'number') {
  382. throw new TypeError(`SSRC(${ssrc}) must be a number`);
  383. }
  384. // Now signaling layer instance is shared between different JingleSessionPC instances, so although very unlikely
  385. // an SSRC conflict could potentially occur. Log a message to make debugging easier.
  386. const existingName = this._sourceNames.get(ssrc);
  387. if (existingName && existingName !== sourceName) {
  388. logger.error(`SSRC(${ssrc}) sourceName re-assigned from ${existingName} to ${sourceName}`);
  389. }
  390. this._sourceNames.set(ssrc, sourceName);
  391. }
  392. }