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.

SignalingLayerImpl.js 14KB

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