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

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