modified lib-jitsi-meet dev repo
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.

LocalSdpMunger.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import { getLogger } from '@jitsi/logger';
  2. import { MediaDirection } from '../../service/RTC/MediaDirection';
  3. import { MediaType } from '../../service/RTC/MediaType';
  4. import { getSourceNameForJitsiTrack } from '../../service/RTC/SignalingLayer';
  5. import { VideoType } from '../../service/RTC/VideoType';
  6. import FeatureFlags from '../flags/FeatureFlags';
  7. import { SdpTransformWrap } from './SdpTransformUtil';
  8. const logger = getLogger(__filename);
  9. /**
  10. * Fakes local SDP exposed to {@link JingleSessionPC} through the local
  11. * description getter. Modifies the SDP, so that it will contain muted local
  12. * video tracks description, even though their underlying {MediaStreamTrack}s
  13. * are no longer in the WebRTC peerconnection. That prevents from SSRC updates
  14. * being sent to Jicofo/remote peer and prevents sRD/sLD cycle on the remote
  15. * side.
  16. */
  17. export default class LocalSdpMunger {
  18. /**
  19. * Creates new <tt>LocalSdpMunger</tt> instance.
  20. *
  21. * @param {TraceablePeerConnection} tpc
  22. * @param {string} localEndpointId - The endpoint id of the local user.
  23. */
  24. constructor(tpc, localEndpointId) {
  25. this.tpc = tpc;
  26. this.localEndpointId = localEndpointId;
  27. this.audioSourcesToMsidMap = new Map();
  28. this.videoSourcesToMsidMap = new Map();
  29. }
  30. /**
  31. * Makes sure that muted local video tracks associated with the parent
  32. * {@link TraceablePeerConnection} are described in the local SDP. It's done
  33. * in order to prevent from sending 'source-remove'/'source-add' Jingle
  34. * notifications when local video track is muted (<tt>MediaStream</tt> is
  35. * removed from the peerconnection).
  36. *
  37. * NOTE 1 video track is assumed
  38. *
  39. * @param {SdpTransformWrap} transformer the transformer instance which will
  40. * be used to process the SDP.
  41. * @return {boolean} <tt>true</tt> if there were any modifications to
  42. * the SDP wrapped by <tt>transformer</tt>.
  43. * @private
  44. */
  45. _addMutedLocalVideoTracksToSDP(transformer) {
  46. // Go over each video tracks and check if the SDP has to be changed
  47. const localVideos = this.tpc.getLocalTracks(MediaType.VIDEO);
  48. if (!localVideos.length) {
  49. return false;
  50. } else if (localVideos.length !== 1) {
  51. logger.error(
  52. `${this.tpc} there is more than 1 video track ! `
  53. + 'Strange things may happen !', localVideos);
  54. }
  55. const videoMLine = transformer.selectMedia(MediaType.VIDEO)?.[0];
  56. if (!videoMLine) {
  57. logger.debug(
  58. `${this.tpc} unable to hack local video track SDP`
  59. + '- no "video" media');
  60. return false;
  61. }
  62. let modified = false;
  63. for (const videoTrack of localVideos) {
  64. const muted = videoTrack.isMuted();
  65. const mediaStream = videoTrack.getOriginalStream();
  66. const isCamera = videoTrack.videoType === VideoType.CAMERA;
  67. // During the mute/unmute operation there are periods of time when
  68. // the track's underlying MediaStream is not added yet to
  69. // the PeerConnection. The SDP needs to be munged in such case.
  70. const isInPeerConnection
  71. = mediaStream && this.tpc.isMediaStreamInPc(mediaStream);
  72. const shouldFakeSdp = isCamera && (muted || !isInPeerConnection);
  73. if (!shouldFakeSdp) {
  74. continue; // eslint-disable-line no-continue
  75. }
  76. // Inject removed SSRCs
  77. const requiredSSRCs
  78. = this.tpc.isSimulcastOn()
  79. ? this.tpc.simulcast.ssrcCache
  80. : [ this.tpc.sdpConsistency.cachedPrimarySsrc ];
  81. if (!requiredSSRCs.length) {
  82. logger.error(`No SSRCs stored for: ${videoTrack} in ${this.tpc}`);
  83. continue; // eslint-disable-line no-continue
  84. }
  85. modified = true;
  86. // We need to fake sendrecv.
  87. // NOTE the SDP produced here goes only to Jicofo and is never set
  88. // as localDescription. That's why
  89. // TraceablePeerConnection.mediaTransferActive is ignored here.
  90. videoMLine.direction = MediaDirection.SENDRECV;
  91. // Check if the recvonly has MSID
  92. const primarySSRC = requiredSSRCs[0];
  93. // FIXME The cname could come from the stream, but may turn out to
  94. // be too complex. It is fine to come up with any value, as long as
  95. // we only care about the actual SSRC values when deciding whether
  96. // or not an update should be sent.
  97. const primaryCname = `injected-${primarySSRC}`;
  98. for (const ssrcNum of requiredSSRCs) {
  99. // Remove old attributes
  100. videoMLine.removeSSRC(ssrcNum);
  101. // Inject
  102. videoMLine.addSSRCAttribute({
  103. id: ssrcNum,
  104. attribute: 'cname',
  105. value: primaryCname
  106. });
  107. videoMLine.addSSRCAttribute({
  108. id: ssrcNum,
  109. attribute: 'msid',
  110. value: videoTrack.storedMSID
  111. });
  112. }
  113. if (requiredSSRCs.length > 1) {
  114. const group = {
  115. ssrcs: requiredSSRCs.join(' '),
  116. semantics: 'SIM'
  117. };
  118. if (!videoMLine.findGroup(group.semantics, group.ssrcs)) {
  119. // Inject the group
  120. videoMLine.addSSRCGroup(group);
  121. }
  122. }
  123. // Insert RTX
  124. // FIXME in P2P RTX is used by Chrome regardless of config option
  125. // status. Because of that 'source-remove'/'source-add'
  126. // notifications are still sent to remove/add RTX SSRC and FID group
  127. if (!this.tpc.options.disableRtx) {
  128. this.tpc.rtxModifier.modifyRtxSsrcs2(videoMLine);
  129. }
  130. }
  131. return modified;
  132. }
  133. /**
  134. * Returns a string that can be set as the MSID attribute for a source.
  135. *
  136. * @param {string} mediaType - Media type of the source.
  137. * @param {string} trackId - Id of the MediaStreamTrack associated with the source.
  138. * @param {string} streamId - Id of the MediaStream associated with the source.
  139. * @returns {string|null}
  140. */
  141. _generateMsidAttribute(mediaType, trackId, streamId = null) {
  142. if (!(mediaType && trackId)) {
  143. logger.error(`Unable to munge local MSID - track id=${trackId} or media type=${mediaType} is missing`);
  144. return null;
  145. }
  146. const pcId = this.tpc.id;
  147. // Handle a case on Firefox when the browser doesn't produce a 'a:ssrc' line with the 'msid' attribute or has
  148. // '-' for the stream id part of the msid line. Jicofo needs an unique identifier to be associated with a ssrc
  149. // and uses the msid for that.
  150. if (streamId === '-' || !streamId) {
  151. return `${this.localEndpointId}-${mediaType}-${pcId} ${trackId}-${pcId}`;
  152. }
  153. return `${streamId}-${pcId} ${trackId}-${pcId}`;
  154. }
  155. /**
  156. * Modifies 'cname', 'msid', 'label' and 'mslabel' by appending the id of {@link LocalSdpMunger#tpc} at the end,
  157. * preceding by a dash sign.
  158. *
  159. * @param {MLineWrap} mediaSection - The media part (audio or video) of the session description which will be
  160. * modified in place.
  161. * @returns {void}
  162. * @private
  163. */
  164. _transformMediaIdentifiers(mediaSection) {
  165. const mediaType = mediaSection.mLine?.type;
  166. const pcId = this.tpc.id;
  167. for (const ssrcLine of mediaSection.ssrcs) {
  168. switch (ssrcLine.attribute) {
  169. case 'cname':
  170. case 'label':
  171. case 'mslabel':
  172. ssrcLine.value = ssrcLine.value && `${ssrcLine.value}-${pcId}`;
  173. break;
  174. case 'msid': {
  175. if (ssrcLine.value) {
  176. const streamAndTrackIDs = ssrcLine.value.split(' ');
  177. let streamId = streamAndTrackIDs[0];
  178. const trackId = streamAndTrackIDs[1];
  179. if (FeatureFlags.isSourceNameSignalingEnabled()) {
  180. // Always overwrite streamId since we want the msid to be in this format even if the browser
  181. // generates one (in p2p mode).
  182. streamId = `${this.localEndpointId}-${mediaType}`;
  183. // eslint-disable-next-line max-depth
  184. if (mediaType === MediaType.VIDEO) {
  185. // eslint-disable-next-line max-depth
  186. if (!this.videoSourcesToMsidMap.has(trackId)) {
  187. streamId = `${streamId}-${this.videoSourcesToMsidMap.size}`;
  188. this.videoSourcesToMsidMap.set(trackId, streamId);
  189. }
  190. } else if (!this.audioSourcesToMsidMap.has(trackId)) {
  191. streamId = `${streamId}-${this.audioSourcesToMsidMap.size}`;
  192. this.audioSourcesToMsidMap.set(trackId, streamId);
  193. }
  194. streamId = mediaType === MediaType.VIDEO
  195. ? this.videoSourcesToMsidMap.get(trackId)
  196. : this.audioSourcesToMsidMap.get(trackId);
  197. }
  198. ssrcLine.value = this._generateMsidAttribute(mediaType, trackId, streamId);
  199. } else {
  200. logger.warn(`Unable to munge local MSID - weird format detected: ${ssrcLine.value}`);
  201. }
  202. break;
  203. }
  204. }
  205. }
  206. // Additional transformations related to MSID are applicable to Unified-plan implementation only.
  207. if (!this.tpc.usesUnifiedPlan()) {
  208. return;
  209. }
  210. // Add the msid attribute if it is missing when the direction is sendrecv/sendonly. Firefox doesn't produce a
  211. // a=ssrc line with msid attribute for p2p connection.
  212. const msidLine = mediaSection.mLine?.msid;
  213. const trackId = msidLine && msidLine.split(' ')[1];
  214. const sources = [ ...new Set(mediaSection.mLine?.ssrcs?.map(s => s.id)) ];
  215. for (const source of sources) {
  216. const msidExists = mediaSection.ssrcs
  217. .find(ssrc => ssrc.id === source && ssrc.attribute === 'msid');
  218. if (!msidExists && trackId) {
  219. const generatedMsid = this._generateMsidAttribute(mediaType, trackId);
  220. mediaSection.ssrcs.push({
  221. id: source,
  222. attribute: 'msid',
  223. value: generatedMsid
  224. });
  225. }
  226. }
  227. }
  228. /**
  229. * Maybe modifies local description to fake local video tracks SDP when
  230. * those are muted.
  231. *
  232. * @param {object} desc the WebRTC SDP object instance for the local
  233. * description.
  234. * @returns {RTCSessionDescription}
  235. */
  236. maybeAddMutedLocalVideoTracksToSDP(desc) {
  237. if (!desc) {
  238. throw new Error('No local description passed in.');
  239. }
  240. const transformer = new SdpTransformWrap(desc.sdp);
  241. if (this._addMutedLocalVideoTracksToSDP(transformer)) {
  242. return new RTCSessionDescription({
  243. type: desc.type,
  244. sdp: transformer.toRawSDP()
  245. });
  246. }
  247. return desc;
  248. }
  249. /**
  250. * This transformation will make sure that stream identifiers are unique
  251. * across all of the local PeerConnections even if the same stream is used
  252. * by multiple instances at the same time.
  253. * Each PeerConnection assigns different SSRCs to the same local
  254. * MediaStream, but the MSID remains the same as it's used to identify
  255. * the stream by the WebRTC backend. The transformation will append
  256. * {@link TraceablePeerConnection#id} at the end of each stream's identifier
  257. * ("cname", "msid", "label" and "mslabel").
  258. *
  259. * @param {RTCSessionDescription} sessionDesc - The local session
  260. * description (this instance remains unchanged).
  261. * @return {RTCSessionDescription} - Transformed local session description
  262. * (a modified copy of the one given as the input).
  263. */
  264. transformStreamIdentifiers(sessionDesc) {
  265. // FIXME similar check is probably duplicated in all other transformers
  266. if (!sessionDesc || !sessionDesc.sdp || !sessionDesc.type) {
  267. return sessionDesc;
  268. }
  269. const transformer = new SdpTransformWrap(sessionDesc.sdp);
  270. const audioMLine = transformer.selectMedia(MediaType.AUDIO)?.[0];
  271. if (audioMLine) {
  272. this._transformMediaIdentifiers(audioMLine);
  273. this._injectSourceNames(audioMLine);
  274. }
  275. const videoMlines = transformer.selectMedia(MediaType.VIDEO);
  276. if (!FeatureFlags.isMultiStreamSupportEnabled()) {
  277. videoMlines.splice(1);
  278. }
  279. for (const videoMLine of videoMlines) {
  280. this._transformMediaIdentifiers(videoMLine);
  281. this._injectSourceNames(videoMLine);
  282. }
  283. // Plan-b clients generate new SSRCs and trackIds whenever tracks are removed and added back to the
  284. // peerconnection, therefore local track based map for msids needs to be reset after every transformation.
  285. if (FeatureFlags.isSourceNameSignalingEnabled() && !this.tpc._usesUnifiedPlan) {
  286. this.audioSourcesToMsidMap.clear();
  287. this.videoSourcesToMsidMap.clear();
  288. }
  289. return new RTCSessionDescription({
  290. type: sessionDesc.type,
  291. sdp: transformer.toRawSDP()
  292. });
  293. }
  294. /**
  295. * Injects source names. Source names are need to for multiple streams per endpoint support. The final plan is to
  296. * use the "mid" attribute for source names, but because the SDP to Jingle conversion still operates in the Plan-B
  297. * semantics (one source name per media), a custom "name" attribute is injected into SSRC lines..
  298. *
  299. * @param {MLineWrap} mediaSection - The media part (audio or video) of the session description which will be
  300. * modified in place.
  301. * @returns {void}
  302. * @private
  303. */
  304. _injectSourceNames(mediaSection) {
  305. if (!FeatureFlags.isSourceNameSignalingEnabled()) {
  306. return;
  307. }
  308. const sources = [ ...new Set(mediaSection.mLine?.ssrcs?.map(s => s.id)) ];
  309. const mediaType = mediaSection.mLine?.type;
  310. if (!mediaType) {
  311. throw new Error('_transformMediaIdentifiers - no media type in mediaSection');
  312. }
  313. for (const source of sources) {
  314. const nameExists = mediaSection.ssrcs.find(ssrc => ssrc.id === source && ssrc.attribute === 'name');
  315. const msid = mediaSection.ssrcs.find(ssrc => ssrc.id === source && ssrc.attribute === 'msid')?.value;
  316. let trackIndex;
  317. if (msid) {
  318. const streamId = msid.split(' ')[0];
  319. trackIndex = streamId.split('-')[2];
  320. }
  321. if (!nameExists) {
  322. // Inject source names as a=ssrc:3124985624 name:endpointA-v0
  323. mediaSection.ssrcs.push({
  324. id: source,
  325. attribute: 'name',
  326. value: getSourceNameForJitsiTrack(this.localEndpointId, mediaType, trackIndex)
  327. });
  328. }
  329. }
  330. }
  331. }