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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import { getLogger } from '@jitsi/logger';
  2. import MediaDirection from '../../service/RTC/MediaDirection';
  3. import * as 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('video');
  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
  155. * the id of {@link LocalSdpMunger#tpc} at the end, preceding by a dash
  156. * sign.
  157. *
  158. * @param {MLineWrap} mediaSection - The media part (audio or video) of the
  159. * session description which will be modified in place.
  160. * @returns {void}
  161. * @private
  162. */
  163. _transformMediaIdentifiers(mediaSection) {
  164. const pcId = this.tpc.id;
  165. for (const ssrcLine of mediaSection.ssrcs) {
  166. switch (ssrcLine.attribute) {
  167. case 'cname':
  168. case 'label':
  169. case 'mslabel':
  170. ssrcLine.value = ssrcLine.value && `${ssrcLine.value}-${pcId}`;
  171. break;
  172. case 'msid': {
  173. if (ssrcLine.value) {
  174. const streamAndTrackIDs = ssrcLine.value.split(' ');
  175. if (streamAndTrackIDs.length === 2) {
  176. ssrcLine.value
  177. = this._generateMsidAttribute(
  178. mediaSection.mLine?.type,
  179. streamAndTrackIDs[1],
  180. streamAndTrackIDs[0]);
  181. } else {
  182. logger.warn(`Unable to munge local MSID - weird format detected: ${ssrcLine.value}`);
  183. }
  184. }
  185. break;
  186. }
  187. }
  188. }
  189. // Additional transformations related to MSID are applicable to Unified-plan implementation only.
  190. if (!this.tpc.usesUnifiedPlan()) {
  191. return;
  192. }
  193. // If the msid attribute is missing, then remove the ssrc from the transformed description so that a
  194. // source-remove is signaled to Jicofo. This happens when the direction of the transceiver (or m-line)
  195. // is set to 'inactive' or 'recvonly' on Firefox, Chrome (unified) and Safari.
  196. const mediaDirection = mediaSection.mLine?.direction;
  197. if (mediaDirection === MediaDirection.RECVONLY || mediaDirection === MediaDirection.INACTIVE) {
  198. mediaSection.ssrcs = undefined;
  199. mediaSection.ssrcGroups = undefined;
  200. // Add the msid attribute if it is missing when the direction is sendrecv/sendonly. Firefox doesn't produce a
  201. // a=ssrc line with msid attribute for p2p connection.
  202. } else {
  203. const msidLine = mediaSection.mLine?.msid;
  204. const trackId = msidLine && msidLine.split(' ')[1];
  205. const sources = [ ...new Set(mediaSection.mLine?.ssrcs?.map(s => s.id)) ];
  206. for (const source of sources) {
  207. const msidExists = mediaSection.ssrcs
  208. .find(ssrc => ssrc.id === source && ssrc.attribute === 'msid');
  209. if (!msidExists) {
  210. const generatedMsid = this._generateMsidAttribute(mediaSection.mLine?.type, trackId);
  211. mediaSection.ssrcs.push({
  212. id: source,
  213. attribute: 'msid',
  214. value: generatedMsid
  215. });
  216. }
  217. }
  218. }
  219. }
  220. /**
  221. * Maybe modifies local description to fake local video tracks SDP when
  222. * those are muted.
  223. *
  224. * @param {object} desc the WebRTC SDP object instance for the local
  225. * description.
  226. * @returns {RTCSessionDescription}
  227. */
  228. maybeAddMutedLocalVideoTracksToSDP(desc) {
  229. if (!desc) {
  230. throw new Error('No local description passed in.');
  231. }
  232. const transformer = new SdpTransformWrap(desc.sdp);
  233. if (this._addMutedLocalVideoTracksToSDP(transformer)) {
  234. return new RTCSessionDescription({
  235. type: desc.type,
  236. sdp: transformer.toRawSDP()
  237. });
  238. }
  239. return desc;
  240. }
  241. /**
  242. * This transformation will make sure that stream identifiers are unique
  243. * across all of the local PeerConnections even if the same stream is used
  244. * by multiple instances at the same time.
  245. * Each PeerConnection assigns different SSRCs to the same local
  246. * MediaStream, but the MSID remains the same as it's used to identify
  247. * the stream by the WebRTC backend. The transformation will append
  248. * {@link TraceablePeerConnection#id} at the end of each stream's identifier
  249. * ("cname", "msid", "label" and "mslabel").
  250. *
  251. * @param {RTCSessionDescription} sessionDesc - The local session
  252. * description (this instance remains unchanged).
  253. * @return {RTCSessionDescription} - Transformed local session description
  254. * (a modified copy of the one given as the input).
  255. */
  256. transformStreamIdentifiers(sessionDesc) {
  257. // FIXME similar check is probably duplicated in all other transformers
  258. if (!sessionDesc || !sessionDesc.sdp || !sessionDesc.type) {
  259. return sessionDesc;
  260. }
  261. const transformer = new SdpTransformWrap(sessionDesc.sdp);
  262. const audioMLine = transformer.selectMedia('audio');
  263. if (audioMLine) {
  264. this._transformMediaIdentifiers(audioMLine);
  265. this._injectSourceNames(audioMLine);
  266. }
  267. const videoMLine = transformer.selectMedia('video');
  268. if (videoMLine) {
  269. this._transformMediaIdentifiers(videoMLine);
  270. this._injectSourceNames(videoMLine);
  271. }
  272. return new RTCSessionDescription({
  273. type: sessionDesc.type,
  274. sdp: transformer.toRawSDP()
  275. });
  276. }
  277. /**
  278. * Injects source names. Source names are need to for multiple streams per endpoint support. The final plan is to
  279. * use the "mid" attribute for source names, but because the SDP to Jingle conversion still operates in the Plan-B
  280. * semantics (one source name per media), a custom "name" attribute is injected into SSRC lines..
  281. *
  282. * @param {MLineWrap} mediaSection - The media part (audio or video) of the session description which will be
  283. * modified in place.
  284. * @returns {void}
  285. * @private
  286. */
  287. _injectSourceNames(mediaSection) {
  288. if (!FeatureFlags.isSourceNameSignalingEnabled()) {
  289. return;
  290. }
  291. const sources = [ ...new Set(mediaSection.mLine?.ssrcs?.map(s => s.id)) ];
  292. const mediaType = mediaSection.mLine?.type;
  293. if (!mediaType) {
  294. throw new Error('_transformMediaIdentifiers - no media type in mediaSection');
  295. }
  296. for (const source of sources) {
  297. const nameExists = mediaSection.ssrcs.find(ssrc => ssrc.id === source && ssrc.attribute === 'name');
  298. if (!nameExists) {
  299. // Inject source names as a=ssrc:3124985624 name:endpointA-v0
  300. mediaSection.ssrcs.push({
  301. id: source,
  302. attribute: 'name',
  303. value: getSourceNameForJitsiTrack(this.localEndpointId, mediaType, 0)
  304. });
  305. }
  306. }
  307. }
  308. }