Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

SignalingLayerImpl.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. import { getLogger } from '@jitsi/logger';
  2. import { Strophe } from 'strophe.js';
  3. import { 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. * Binds event listeners to the chat room instance.
  72. * @param {ChatRoom} room
  73. * @private
  74. * @returns {void}
  75. */
  76. _bindChatRoomEventHandlers(room) {
  77. // Add handlers for 'audiomuted', 'videomuted' and 'videoType' fields in presence in order to support interop
  78. // with very old versions of mobile clients and jigasi that do not support source-name signaling.
  79. const emitAudioMutedEvent = (endpointId, muted) => {
  80. this.eventEmitter.emit(
  81. SignalingEvents.PEER_MUTED_CHANGED,
  82. endpointId,
  83. MediaType.AUDIO,
  84. muted);
  85. };
  86. this._audioMuteHandler = (node, from) => {
  87. if (!this._doesEndpointSendNewSourceInfo(from)) {
  88. emitAudioMutedEvent(from, node.value === 'true');
  89. }
  90. };
  91. room.addPresenceListener('audiomuted', this._audioMuteHandler);
  92. const emitVideoMutedEvent = (endpointId, muted) => {
  93. this.eventEmitter.emit(
  94. SignalingEvents.PEER_MUTED_CHANGED,
  95. endpointId,
  96. MediaType.VIDEO,
  97. muted);
  98. };
  99. this._videoMuteHandler = (node, from) => {
  100. if (!this._doesEndpointSendNewSourceInfo(from)) {
  101. emitVideoMutedEvent(from, node.value === 'true');
  102. }
  103. };
  104. room.addPresenceListener('videomuted', this._videoMuteHandler);
  105. const emitVideoTypeEvent = (endpointId, videoType) => {
  106. this.eventEmitter.emit(
  107. SignalingEvents.PEER_VIDEO_TYPE_CHANGED,
  108. endpointId, videoType);
  109. };
  110. this._videoTypeHandler = (node, from) => {
  111. if (!this._doesEndpointSendNewSourceInfo(from)) {
  112. emitVideoTypeEvent(from, node.value);
  113. }
  114. };
  115. room.addPresenceListener('videoType', this._videoTypeHandler);
  116. // Add handlers for presence in the new format.
  117. this._sourceInfoHandler = (node, mucNick) => {
  118. const endpointId = mucNick;
  119. const { value } = node;
  120. const sourceInfoJSON = JSON.parse(value);
  121. const emitEventsFromHere = this._doesEndpointSendNewSourceInfo(endpointId);
  122. const endpointSourceState
  123. = this._remoteSourceState[endpointId] || (this._remoteSourceState[endpointId] = {});
  124. for (const sourceName of Object.keys(sourceInfoJSON)) {
  125. let sourceChanged = false;
  126. const mediaType = getMediaTypeFromSourceName(sourceName);
  127. const newMutedState = Boolean(sourceInfoJSON[sourceName].muted);
  128. const oldSourceState = endpointSourceState[sourceName]
  129. || (endpointSourceState[sourceName] = { sourceName });
  130. if (oldSourceState.muted !== newMutedState) {
  131. sourceChanged = true;
  132. oldSourceState.muted = newMutedState;
  133. if (emitEventsFromHere && !this._localSourceState[sourceName]) {
  134. this.eventEmitter.emit(SignalingEvents.SOURCE_MUTED_CHANGED, sourceName, newMutedState);
  135. }
  136. }
  137. // Assume a default videoType of 'camera' for video sources.
  138. const newVideoType = mediaType === MediaType.VIDEO
  139. ? sourceInfoJSON[sourceName].videoType ?? VideoType.CAMERA
  140. : undefined;
  141. if (oldSourceState.videoType !== newVideoType) {
  142. oldSourceState.videoType = newVideoType;
  143. sourceChanged = true;
  144. // Since having a mix of eps that do/don't support multi-stream in the same call is supported, emit
  145. // SOURCE_VIDEO_TYPE_CHANGED event when the remote source changes videoType.
  146. if (emitEventsFromHere && !this._localSourceState[sourceName]) {
  147. this.eventEmitter.emit(SignalingEvents.SOURCE_VIDEO_TYPE_CHANGED, sourceName, newVideoType);
  148. }
  149. }
  150. if (sourceChanged && FeatureFlags.isSsrcRewritingSupported()) {
  151. this.eventEmitter.emit(
  152. SignalingEvents.SOURCE_UPDATED,
  153. sourceName,
  154. mucNick,
  155. newMutedState,
  156. newVideoType);
  157. }
  158. }
  159. // Cleanup removed source names
  160. const newSourceNames = Object.keys(sourceInfoJSON);
  161. for (const sourceName of Object.keys(endpointSourceState)) {
  162. if (newSourceNames.indexOf(sourceName) === -1) {
  163. delete endpointSourceState[sourceName];
  164. }
  165. }
  166. };
  167. room.addPresenceListener('SourceInfo', this._sourceInfoHandler);
  168. // Cleanup when participant leaves
  169. this._memberLeftHandler = jid => {
  170. const endpointId = Strophe.getResourceFromJid(jid);
  171. delete this._remoteSourceState[endpointId];
  172. for (const [ key, value ] of this.ssrcOwners.entries()) {
  173. if (value === endpointId) {
  174. delete this._sourceNames[key];
  175. }
  176. }
  177. };
  178. room.addEventListener(XMPPEvents.MUC_MEMBER_LEFT, this._memberLeftHandler);
  179. }
  180. /**
  181. * Check is given endpoint has advertised <SourceInfo/> in it's presence which means that the source name signaling
  182. * is used by this endpoint.
  183. *
  184. * @param {EndpointId} endpointId
  185. * @returns {boolean}
  186. */
  187. _doesEndpointSendNewSourceInfo(endpointId) {
  188. const presence = this.chatRoom?.getLastPresence(endpointId);
  189. return Boolean(presence && presence.find(node => node.tagName === SOURCE_INFO_PRESENCE_ELEMENT));
  190. }
  191. /**
  192. * Logs a debug or error message to console depending on whether SSRC rewriting is enabled or not.
  193. * Owner changes are permitted only when SSRC rewriting is enabled.
  194. *
  195. * @param {string} message - The message to be logged.
  196. * @returns {void}
  197. */
  198. _logOwnerChangedMessage(message) {
  199. if (FeatureFlags.isSsrcRewritingSupported()) {
  200. logger.debug(message);
  201. } else {
  202. logger.error(message);
  203. }
  204. }
  205. /**
  206. * @inheritDoc
  207. */
  208. getPeerMediaInfo(owner, mediaType, sourceName) {
  209. const legacyGetPeerMediaInfo = () => {
  210. if (this.chatRoom) {
  211. return this.chatRoom.getMediaPresenceInfo(owner, mediaType);
  212. }
  213. logger.warn('Requested peer media info, before room was set');
  214. };
  215. const lastPresence = this.chatRoom?.getLastPresence(owner);
  216. if (!lastPresence) {
  217. logger.warn(`getPeerMediaInfo - no presence stored for: ${owner}`);
  218. return;
  219. }
  220. if (!this._doesEndpointSendNewSourceInfo(owner)) {
  221. return legacyGetPeerMediaInfo();
  222. }
  223. if (sourceName) {
  224. return this.getPeerSourceInfo(owner, sourceName);
  225. }
  226. const mediaInfo = {
  227. muted: true
  228. };
  229. if (mediaType === MediaType.VIDEO) {
  230. mediaInfo.videoType = undefined;
  231. const codecTypeNode = filterNodeFromPresenceJSON(lastPresence, 'jitsi_participant_codecType');
  232. if (codecTypeNode.length > 0) {
  233. mediaInfo.codecType = codecTypeNode[0].value;
  234. }
  235. }
  236. return mediaInfo;
  237. }
  238. /**
  239. * @inheritDoc
  240. */
  241. getPeerSourceInfo(owner, sourceName) {
  242. const mediaInfo = {
  243. muted: true, // muted by default
  244. videoType: VideoType.CAMERA // 'camera' by default
  245. };
  246. return this._remoteSourceState[owner]
  247. ? this._remoteSourceState[owner][sourceName] ?? mediaInfo
  248. : undefined;
  249. }
  250. /**
  251. * @inheritDoc
  252. */
  253. getSSRCOwner(ssrc) {
  254. return this.ssrcOwners.get(ssrc);
  255. }
  256. /**
  257. * @inheritDoc
  258. */
  259. getTrackSourceName(ssrc) {
  260. return this._sourceNames.get(ssrc);
  261. }
  262. /**
  263. * @inheritDoc
  264. */
  265. removeSSRCOwners(ssrcList) {
  266. if (!ssrcList?.length) {
  267. return;
  268. }
  269. for (const ssrc of ssrcList) {
  270. this.ssrcOwners.delete(ssrc);
  271. }
  272. }
  273. /**
  274. * Sets the <tt>ChatRoom</tt> instance used and binds presence listeners.
  275. * @param {ChatRoom} room
  276. */
  277. setChatRoom(room) {
  278. const oldChatRoom = this.chatRoom;
  279. this.chatRoom = room;
  280. if (oldChatRoom) {
  281. oldChatRoom.removePresenceListener(
  282. 'audiomuted', this._audioMuteHandler);
  283. oldChatRoom.removePresenceListener(
  284. 'videomuted', this._videoMuteHandler);
  285. oldChatRoom.removePresenceListener(
  286. 'videoType', this._videoTypeHandler);
  287. this._sourceInfoHandler
  288. && oldChatRoom.removePresenceListener(SOURCE_INFO_PRESENCE_ELEMENT, this._sourceInfoHandler);
  289. this._memberLeftHandler
  290. && oldChatRoom.removeEventListener(XMPPEvents.MUC_MEMBER_LEFT, this._memberLeftHandler);
  291. }
  292. if (room) {
  293. this._bindChatRoomEventHandlers(room);
  294. this._addLocalSourceInfoToPresence();
  295. }
  296. }
  297. /**
  298. * @inheritDoc
  299. */
  300. setSSRCOwner(ssrc, endpointId) {
  301. if (typeof ssrc !== 'number') {
  302. throw new TypeError(`SSRC(${ssrc}) must be a number`);
  303. }
  304. // Now signaling layer instance is shared between different JingleSessionPC instances, so although very unlikely
  305. // an SSRC conflict could potentially occur. Log a message to make debugging easier.
  306. const existingOwner = this.ssrcOwners.get(ssrc);
  307. if (existingOwner && existingOwner !== endpointId) {
  308. this._logOwnerChangedMessage(`SSRC owner re-assigned from ${existingOwner} to ${endpointId}`);
  309. }
  310. this.ssrcOwners.set(ssrc, endpointId);
  311. }
  312. /**
  313. * @inheritDoc
  314. */
  315. setTrackMuteStatus(sourceName, muted) {
  316. if (!this._localSourceState[sourceName]) {
  317. this._localSourceState[sourceName] = {};
  318. }
  319. this._localSourceState[sourceName].muted = muted;
  320. if (this.chatRoom) {
  321. return this._addLocalSourceInfoToPresence();
  322. }
  323. return false;
  324. }
  325. /**
  326. * @inheritDoc
  327. */
  328. setTrackSourceName(ssrc, sourceName) {
  329. if (typeof ssrc !== 'number') {
  330. throw new TypeError(`SSRC(${ssrc}) must be a number`);
  331. }
  332. // Now signaling layer instance is shared between different JingleSessionPC instances, so although very unlikely
  333. // an SSRC conflict could potentially occur. Log a message to make debugging easier.
  334. const existingName = this._sourceNames.get(ssrc);
  335. if (existingName && existingName !== sourceName) {
  336. this._logOwnerChangedMessage(`SSRC(${ssrc}) sourceName re-assigned from ${existingName} to ${sourceName}`);
  337. }
  338. this._sourceNames.set(ssrc, sourceName);
  339. }
  340. /**
  341. * @inheritDoc
  342. */
  343. setTrackVideoType(sourceName, videoType) {
  344. if (!this._localSourceState[sourceName]) {
  345. this._localSourceState[sourceName] = {};
  346. }
  347. if (this._localSourceState[sourceName].videoType !== videoType) {
  348. // Include only if not a camera (default)
  349. this._localSourceState[sourceName].videoType = videoType === VideoType.CAMERA ? undefined : videoType;
  350. return this._addLocalSourceInfoToPresence();
  351. }
  352. return false;
  353. }
  354. /**
  355. * @inheritDoc
  356. */
  357. updateSsrcOwnersOnLeave(id) {
  358. const ssrcs = Array.from(this.ssrcOwners)
  359. .filter(entry => entry[1] === id)
  360. .map(entry => entry[0]);
  361. if (!ssrcs?.length) {
  362. return;
  363. }
  364. this.removeSSRCOwners(ssrcs);
  365. }
  366. }