modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

LocalSdpMunger.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. // If the msid attribute is missing, then remove the ssrc from the transformed description so that a
  211. // source-remove is signaled to Jicofo. This happens when the direction of the transceiver (or m-line)
  212. // is set to 'inactive' or 'recvonly' on Firefox, Chrome (unified) and Safari.
  213. const mediaDirection = mediaSection.mLine?.direction;
  214. if (mediaDirection === MediaDirection.RECVONLY || mediaDirection === MediaDirection.INACTIVE) {
  215. mediaSection.ssrcs = undefined;
  216. mediaSection.ssrcGroups = undefined;
  217. // Add the msid attribute if it is missing when the direction is sendrecv/sendonly. Firefox doesn't produce a
  218. // a=ssrc line with msid attribute for p2p connection.
  219. } else {
  220. const msidLine = mediaSection.mLine?.msid;
  221. const trackId = msidLine && msidLine.split(' ')[1];
  222. const sources = [ ...new Set(mediaSection.mLine?.ssrcs?.map(s => s.id)) ];
  223. for (const source of sources) {
  224. const msidExists = mediaSection.ssrcs
  225. .find(ssrc => ssrc.id === source && ssrc.attribute === 'msid');
  226. if (!msidExists && trackId) {
  227. const generatedMsid = this._generateMsidAttribute(mediaType, trackId);
  228. mediaSection.ssrcs.push({
  229. id: source,
  230. attribute: 'msid',
  231. value: generatedMsid
  232. });
  233. }
  234. }
  235. }
  236. }
  237. /**
  238. * Maybe modifies local description to fake local video tracks SDP when
  239. * those are muted.
  240. *
  241. * @param {object} desc the WebRTC SDP object instance for the local
  242. * description.
  243. * @returns {RTCSessionDescription}
  244. */
  245. maybeAddMutedLocalVideoTracksToSDP(desc) {
  246. if (!desc) {
  247. throw new Error('No local description passed in.');
  248. }
  249. const transformer = new SdpTransformWrap(desc.sdp);
  250. if (this._addMutedLocalVideoTracksToSDP(transformer)) {
  251. return new RTCSessionDescription({
  252. type: desc.type,
  253. sdp: transformer.toRawSDP()
  254. });
  255. }
  256. return desc;
  257. }
  258. /**
  259. * This transformation will make sure that stream identifiers are unique
  260. * across all of the local PeerConnections even if the same stream is used
  261. * by multiple instances at the same time.
  262. * Each PeerConnection assigns different SSRCs to the same local
  263. * MediaStream, but the MSID remains the same as it's used to identify
  264. * the stream by the WebRTC backend. The transformation will append
  265. * {@link TraceablePeerConnection#id} at the end of each stream's identifier
  266. * ("cname", "msid", "label" and "mslabel").
  267. *
  268. * @param {RTCSessionDescription} sessionDesc - The local session
  269. * description (this instance remains unchanged).
  270. * @return {RTCSessionDescription} - Transformed local session description
  271. * (a modified copy of the one given as the input).
  272. */
  273. transformStreamIdentifiers(sessionDesc) {
  274. // FIXME similar check is probably duplicated in all other transformers
  275. if (!sessionDesc || !sessionDesc.sdp || !sessionDesc.type) {
  276. return sessionDesc;
  277. }
  278. const transformer = new SdpTransformWrap(sessionDesc.sdp);
  279. const audioMLine = transformer.selectMedia(MediaType.AUDIO)?.[0];
  280. if (audioMLine) {
  281. this._transformMediaIdentifiers(audioMLine);
  282. this._injectSourceNames(audioMLine);
  283. }
  284. const videoMlines = transformer.selectMedia(MediaType.VIDEO);
  285. if (!FeatureFlags.isMultiStreamSupportEnabled()) {
  286. videoMlines.splice(1);
  287. }
  288. for (const videoMLine of videoMlines) {
  289. this._transformMediaIdentifiers(videoMLine);
  290. this._injectSourceNames(videoMLine);
  291. }
  292. // Plan-b clients generate new SSRCs and trackIds whenever tracks are removed and added back to the
  293. // peerconnection, therefore local track based map for msids needs to be reset after every transformation.
  294. if (FeatureFlags.isSourceNameSignalingEnabled() && !this.tpc._usesUnifiedPlan) {
  295. this.audioSourcesToMsidMap.clear();
  296. this.videoSourcesToMsidMap.clear();
  297. }
  298. return new RTCSessionDescription({
  299. type: sessionDesc.type,
  300. sdp: transformer.toRawSDP()
  301. });
  302. }
  303. /**
  304. * Injects source names. Source names are need to for multiple streams per endpoint support. The final plan is to
  305. * use the "mid" attribute for source names, but because the SDP to Jingle conversion still operates in the Plan-B
  306. * semantics (one source name per media), a custom "name" attribute is injected into SSRC lines..
  307. *
  308. * @param {MLineWrap} mediaSection - The media part (audio or video) of the session description which will be
  309. * modified in place.
  310. * @returns {void}
  311. * @private
  312. */
  313. _injectSourceNames(mediaSection) {
  314. if (!FeatureFlags.isSourceNameSignalingEnabled()) {
  315. return;
  316. }
  317. const sources = [ ...new Set(mediaSection.mLine?.ssrcs?.map(s => s.id)) ];
  318. const mediaType = mediaSection.mLine?.type;
  319. if (!mediaType) {
  320. throw new Error('_transformMediaIdentifiers - no media type in mediaSection');
  321. }
  322. for (const source of sources) {
  323. const nameExists = mediaSection.ssrcs.find(ssrc => ssrc.id === source && ssrc.attribute === 'name');
  324. const msid = mediaSection.ssrcs.find(ssrc => ssrc.id === source && ssrc.attribute === 'msid')?.value;
  325. let trackIndex;
  326. if (msid) {
  327. const streamId = msid.split(' ')[0];
  328. trackIndex = streamId.split('-')[2];
  329. }
  330. if (!nameExists) {
  331. // Inject source names as a=ssrc:3124985624 name:endpointA-v0
  332. mediaSection.ssrcs.push({
  333. id: source,
  334. attribute: 'name',
  335. value: getSourceNameForJitsiTrack(this.localEndpointId, mediaType, trackIndex)
  336. });
  337. }
  338. }
  339. }
  340. }