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

SignalingLayerImpl.js 16KB

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