Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

SignalingLayerImpl.js 15KB

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