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.

TraceablePeerConnection.js 98KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731
  1. import { getLogger } from '@jitsi/logger';
  2. import { Interop } from '@jitsi/sdp-interop';
  3. import transform from 'sdp-transform';
  4. import { CodecMimeType } from '../../service/RTC/CodecMimeType';
  5. import { MediaDirection } from '../../service/RTC/MediaDirection';
  6. import { MediaType } from '../../service/RTC/MediaType';
  7. import RTCEvents from '../../service/RTC/RTCEvents';
  8. import * as SignalingEvents from '../../service/RTC/SignalingEvents';
  9. import { getSourceIndexFromSourceName } from '../../service/RTC/SignalingLayer';
  10. import { VIDEO_QUALITY_LEVELS } from '../../service/RTC/StandardVideoSettings';
  11. import { VideoType } from '../../service/RTC/VideoType';
  12. import { SS_DEFAULT_FRAME_RATE } from '../RTC/ScreenObtainer';
  13. import browser from '../browser';
  14. import FeatureFlags from '../flags/FeatureFlags';
  15. import LocalSdpMunger from '../sdp/LocalSdpMunger';
  16. import RtxModifier from '../sdp/RtxModifier';
  17. import SDP from '../sdp/SDP';
  18. import SDPUtil from '../sdp/SDPUtil';
  19. import SdpSimulcast from '../sdp/SdpSimulcast';
  20. import { SdpTransformWrap } from '../sdp/SdpTransformUtil';
  21. import JitsiRemoteTrack from './JitsiRemoteTrack';
  22. import RTCUtils from './RTCUtils';
  23. import { TPCUtils } from './TPCUtils';
  24. // FIXME SDP tools should end up in some kind of util module
  25. const logger = getLogger(__filename);
  26. const DEGRADATION_PREFERENCE_CAMERA = 'maintain-framerate';
  27. const DEGRADATION_PREFERENCE_DESKTOP = 'maintain-resolution';
  28. const DD_HEADER_EXT_URI
  29. = 'https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension';
  30. const DD_HEADER_EXT_ID = 11;
  31. /* eslint-disable max-params */
  32. /**
  33. * Creates new instance of 'TraceablePeerConnection'.
  34. *
  35. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  36. * @param {number} id the peer connection id assigned by the parent RTC module.
  37. * @param {SignalingLayer} signalingLayer the signaling layer instance
  38. * @param {object} pcConfig The {@code RTCConfiguration} to use for the WebRTC peer connection.
  39. * @param {object} constraints WebRTC 'PeerConnection' constraints
  40. * @param {boolean} isP2P indicates whether or not the new instance will be used in a peer to peer connection.
  41. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  42. * @param {Object} options.audioQuality - Quality settings to applied on the outbound audio stream.
  43. * @param {boolean} options.capScreenshareBitrate if set to true, lower layers will be disabled for screenshare.
  44. * @param {Array<CodecMimeType>} options.codecSettings - codec settings to be applied for video streams.
  45. * @param {boolean} options.disableSimulcast if set to 'true' will disable the simulcast.
  46. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX.
  47. * @param {boolean} options.enableInsertableStreams set to true when the insertable streams constraints is to be
  48. * enabled on the PeerConnection.
  49. * @param {boolean} options.forceTurnRelay If set to true, the browser will generate only Relay ICE candidates.
  50. * @param {boolean} options.startSilent If set to 'true' no audio will be sent or received.
  51. * @param {Object} options.videoQuality - Quality settings to applied on the outbound video streams.
  52. *
  53. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  54. * debug the peer connection. Since many other responsibilities have been added
  55. * it would make sense to extract a separate class from it and come up with
  56. * a more suitable name.
  57. *
  58. * @constructor
  59. */
  60. export default function TraceablePeerConnection(
  61. rtc,
  62. id,
  63. signalingLayer,
  64. pcConfig,
  65. constraints,
  66. isP2P,
  67. options) {
  68. /**
  69. * Indicates whether or not this peer connection instance is actively
  70. * sending/receiving audio media. When set to <tt>false</tt> the SDP audio
  71. * media direction will be adjusted to 'inactive' in order to suspend
  72. * the transmission.
  73. * @type {boolean}
  74. * @private
  75. */
  76. this.audioTransferActive = !(options.startSilent === true);
  77. /**
  78. * The DTMF sender instance used to send DTMF tones.
  79. *
  80. * @type {RTCDTMFSender|undefined}
  81. * @private
  82. */
  83. this._dtmfSender = undefined;
  84. /**
  85. * @typedef {Object} TouchToneRequest
  86. * @property {string} tones - The DTMF tones string as defined by
  87. * {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  88. * @property {number} duration - The amount of time in milliseconds that
  89. * each DTMF should last.
  90. * @property {string} interToneGap - The length of time in miliseconds to
  91. * wait between tones.
  92. */
  93. /**
  94. * TouchToneRequests which are waiting to be played. This queue is filled
  95. * if there are touch tones currently being played.
  96. *
  97. * @type {Array<TouchToneRequest>}
  98. * @private
  99. */
  100. this._dtmfTonesQueue = [];
  101. /**
  102. * Indicates whether or not this peer connection instance is actively
  103. * sending/receiving video media. When set to <tt>false</tt> the SDP video
  104. * media direction will be adjusted to 'inactive' in order to suspend
  105. * the transmission.
  106. * @type {boolean}
  107. * @private
  108. */
  109. this.videoTransferActive = true;
  110. /**
  111. * The parent instance of RTC service which created this
  112. * <tt>TracablePeerConnection</tt>.
  113. * @type {RTC}
  114. */
  115. this.rtc = rtc;
  116. /**
  117. * The peer connection identifier assigned by the RTC module.
  118. * @type {number}
  119. */
  120. this.id = id;
  121. /**
  122. * Indicates whether or not this instance is used in a peer to peer
  123. * connection.
  124. * @type {boolean}
  125. */
  126. this.isP2P = isP2P;
  127. /**
  128. * A map that holds remote tracks signaled on the peerconnection indexed by their SSRC.
  129. * @type {Map<number, JitsiRemoteTrack>}
  130. */
  131. this.remoteTracksBySsrc = new Map();
  132. /**
  133. * The map holds remote tracks associated with this peer connection. It maps user's JID to media type and a set of
  134. * remote tracks.
  135. * @type {Map<string, Map<MediaType, Set<JitsiRemoteTrack>>>}
  136. */
  137. this.remoteTracks = new Map();
  138. /**
  139. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  140. * @type {Map<number, JitsiLocalTrack>}
  141. */
  142. this.localTracks = new Map();
  143. /**
  144. * @typedef {Object} TPCGroupInfo
  145. * @property {string} semantics the SSRC groups semantics
  146. * @property {Array<number>} ssrcs group's SSRCs in order where the first
  147. * one is group's primary SSRC, the second one is secondary (RTX) and so
  148. * on...
  149. */
  150. /**
  151. * @typedef {Object} TPCSSRCInfo
  152. * @property {Array<number>} ssrcs an array which holds all track's SSRCs
  153. * @property {Array<TPCGroupInfo>} groups an array stores all track's SSRC
  154. * groups
  155. */
  156. /**
  157. * Holds the info about local track's SSRCs mapped per their
  158. * {@link JitsiLocalTrack.rtcId}
  159. * @type {Map<number, TPCSSRCInfo>}
  160. */
  161. this.localSSRCs = new Map();
  162. /**
  163. * The set of remote SSRCs seen so far.
  164. * Distinguishes new SSRCs from those that have been remapped.
  165. * @type {Set<number>}
  166. */
  167. this.remoteSSRCs = new Set();
  168. /**
  169. * Mapping of source-names and their associated SSRCs that have been signaled by the JVB.
  170. * @type {Map<string, number>}
  171. */
  172. this.remoteSources = new Map();
  173. /**
  174. * The local ICE username fragment for this session.
  175. */
  176. this.localUfrag = null;
  177. /**
  178. * The remote ICE username fragment for this session.
  179. */
  180. this.remoteUfrag = null;
  181. /**
  182. * The DTLS transport object for the PeerConnection.
  183. * Note: this assume only one shared transport exists because we bundled
  184. * all streams on the same underlying transport.
  185. */
  186. this._dtlsTransport = null;
  187. /**
  188. * The signaling layer which operates this peer connection.
  189. * @type {SignalingLayer}
  190. */
  191. this.signalingLayer = signalingLayer;
  192. // SignalingLayer listeners
  193. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  194. this.signalingLayer.on(SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  195. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  196. this.signalingLayer.on(SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  197. this.options = options;
  198. // Setup SignalingLayer listeners for source-name based events.
  199. this.signalingLayer.on(SignalingEvents.SOURCE_MUTED_CHANGED,
  200. (sourceName, isMuted) => this._sourceMutedChanged(sourceName, isMuted));
  201. this.signalingLayer.on(SignalingEvents.SOURCE_VIDEO_TYPE_CHANGED,
  202. (sourceName, videoType) => this._sourceVideoTypeChanged(sourceName, videoType));
  203. // Make sure constraints is properly formatted in order to provide information about whether or not this
  204. // connection is P2P to rtcstats.
  205. const safeConstraints = constraints || {};
  206. safeConstraints.optional = safeConstraints.optional || [];
  207. // The `optional` parameter needs to be of type array, otherwise chrome will throw an error.
  208. // Firefox and Safari just ignore it.
  209. if (Array.isArray(safeConstraints.optional)) {
  210. safeConstraints.optional.push({ rtcStatsSFUP2P: this.isP2P });
  211. } else {
  212. logger.warn('Optional param is not an array, rtcstats p2p data is omitted.');
  213. }
  214. this.peerconnection = new RTCPeerConnection(pcConfig, safeConstraints);
  215. this.tpcUtils = new TPCUtils(this);
  216. this.updateLog = [];
  217. this.stats = {};
  218. this.statsinterval = null;
  219. /**
  220. * Flag used to indicate if low fps screenshare is desired.
  221. */
  222. this._capScreenshareBitrate = this.options.capScreenshareBitrate;
  223. /**
  224. * Codec preferences set for the peerconnection through config.js.
  225. */
  226. this.codecSettings = this.options.codecSettings;
  227. /**
  228. * Flag used to indicate if RTCRtpTransceiver#setCodecPreferences is to be used instead of SDP
  229. * munging for codec selection.
  230. */
  231. browser.supportsCodecPreferences()
  232. && logger.info('Using RTCRtpTransceiver#setCodecPreferences for codec selection');
  233. /**
  234. * Indicates whether an audio track has ever been added to the peer connection.
  235. */
  236. this._hasHadAudioTrack = false;
  237. /**
  238. * Indicates whether a video track has ever been added to the peer connection.
  239. */
  240. this._hasHadVideoTrack = false;
  241. /**
  242. * @type {number} The max number of stats to keep in this.stats. Limit to
  243. * 300 values, i.e. 5 minutes; set to 0 to disable
  244. */
  245. this.maxstats = options.maxstats;
  246. this.interop = new Interop();
  247. this.simulcast = new SdpSimulcast();
  248. /**
  249. * Munges local SDP provided to the Jingle Session in order to prevent from
  250. * sending SSRC updates on attach/detach and mute/unmute (for video).
  251. * @type {LocalSdpMunger}
  252. */
  253. this.localSdpMunger = new LocalSdpMunger(this, this.rtc.getLocalEndpointId());
  254. /**
  255. * TracablePeerConnection uses RTC's eventEmitter
  256. * @type {EventEmitter}
  257. */
  258. this.eventEmitter = rtc.eventEmitter;
  259. this.rtxModifier = new RtxModifier();
  260. /**
  261. * The height constraints to be applied on the sender per local video source (source name as the key).
  262. * @type {Map<string, number>}
  263. */
  264. this._senderMaxHeights = new Map();
  265. /**
  266. * Flag indicating bridge support for AV1 codec. On the bridge connection, it is supported only when support for
  267. * Dependency Descriptor header extensions is offered by Jicofo. H.264 simulcast is also possible when these
  268. * header extensions are negotiated.
  269. */
  270. this._supportsDDHeaderExt = false;
  271. /**
  272. * Holds the RTCRtpTransceiver mids that the local tracks are attached to, mapped per their
  273. * {@link JitsiLocalTrack.rtcId}.
  274. * @type {Map<string, string>}
  275. */
  276. this._localTrackTransceiverMids = new Map();
  277. // override as desired
  278. this.trace = (what, info) => {
  279. logger.trace(what, info);
  280. this.updateLog.push({
  281. time: new Date(),
  282. type: what,
  283. value: info || ''
  284. });
  285. };
  286. this.onicecandidate = null;
  287. this.peerconnection.onicecandidate = event => {
  288. this.trace(
  289. 'onicecandidate',
  290. JSON.stringify(event.candidate, null, ' '));
  291. if (this.onicecandidate !== null) {
  292. this.onicecandidate(event);
  293. }
  294. };
  295. this.onTrack = evt => {
  296. const stream = evt.streams[0];
  297. this._remoteTrackAdded(stream, evt.track, evt.transceiver);
  298. stream.addEventListener('removetrack', e => {
  299. this._remoteTrackRemoved(stream, e.track);
  300. });
  301. };
  302. this.peerconnection.addEventListener('track', this.onTrack);
  303. this.onsignalingstatechange = null;
  304. this.peerconnection.onsignalingstatechange = event => {
  305. this.trace('onsignalingstatechange', this.signalingState);
  306. if (this.onsignalingstatechange !== null) {
  307. this.onsignalingstatechange(event);
  308. }
  309. };
  310. this.oniceconnectionstatechange = null;
  311. this.peerconnection.oniceconnectionstatechange = event => {
  312. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  313. if (this.oniceconnectionstatechange !== null) {
  314. this.oniceconnectionstatechange(event);
  315. }
  316. };
  317. this.onnegotiationneeded = null;
  318. this.peerconnection.onnegotiationneeded = event => {
  319. this.trace('onnegotiationneeded');
  320. if (this.onnegotiationneeded !== null) {
  321. this.onnegotiationneeded(event);
  322. }
  323. };
  324. this.onconnectionstatechange = null;
  325. this.peerconnection.onconnectionstatechange = event => {
  326. this.trace('onconnectionstatechange', this.connectionState);
  327. if (this.onconnectionstatechange !== null) {
  328. this.onconnectionstatechange(event);
  329. }
  330. };
  331. this.ondatachannel = null;
  332. this.peerconnection.ondatachannel = event => {
  333. this.trace('ondatachannel');
  334. if (this.ondatachannel !== null) {
  335. this.ondatachannel(event);
  336. }
  337. };
  338. if (this.maxstats) {
  339. this.statsinterval = window.setInterval(() => {
  340. this.getStats().then(stats => {
  341. if (typeof stats?.result === 'function') {
  342. const results = stats.result();
  343. for (let i = 0; i < results.length; ++i) {
  344. const res = results[i];
  345. res.names().forEach(name => {
  346. this._processStat(res, name, res.stat(name));
  347. });
  348. }
  349. } else {
  350. stats.forEach(r => this._processStat(r, '', r));
  351. }
  352. });
  353. }, 1000);
  354. }
  355. this._lastVideoSenderUpdatePromise = Promise.resolve();
  356. logger.info(`Create new ${this}`);
  357. }
  358. /* eslint-enable max-params */
  359. /**
  360. * Process stat and adds it to the array of stats we store.
  361. * @param report the current stats report.
  362. * @param name the name of the report, if available
  363. * @param statValue the value to add.
  364. * @private
  365. */
  366. TraceablePeerConnection.prototype._processStat
  367. = function(report, name, statValue) {
  368. const id = `${report.id}-${name}`;
  369. let s = this.stats[id];
  370. const now = new Date();
  371. if (!s) {
  372. this.stats[id] = s = {
  373. startTime: now,
  374. endTime: now,
  375. values: [],
  376. times: []
  377. };
  378. }
  379. s.values.push(statValue);
  380. s.times.push(now.getTime());
  381. if (s.values.length > this.maxstats) {
  382. s.values.shift();
  383. s.times.shift();
  384. }
  385. s.endTime = now;
  386. };
  387. /**
  388. * Returns a string representation of a SessionDescription object.
  389. */
  390. const dumpSDP = function(description) {
  391. if (typeof description === 'undefined' || description === null) {
  392. return '';
  393. }
  394. return `type: ${description.type}\r\n${description.sdp}`;
  395. };
  396. /**
  397. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  398. * will convert "completed" into "connected" where both mean that the ICE has
  399. * succeeded and is up and running. We never see "completed" state for
  400. * the JVB connection, but it started appearing for the P2P one. This method
  401. * allows to adapt old logic to this new situation.
  402. * @return {string}
  403. */
  404. TraceablePeerConnection.prototype.getConnectionState = function() {
  405. const state = this.peerconnection.iceConnectionState;
  406. if (state === 'completed') {
  407. return 'connected';
  408. }
  409. return state;
  410. };
  411. /**
  412. * Obtains the media direction for given {@link MediaType} that needs to be set on a p2p peerconnection's remote SDP
  413. * after a source-add or source-remove action. The method takes into account whether or not there are any
  414. * local tracks for the given media type.
  415. * @param {MediaType} mediaType
  416. * @param {boolean} isAddOperation whether the direction is to be calculated after a source-add action.
  417. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly' etc.) which should be used when setting
  418. * local description on the peerconnection.
  419. * @private
  420. */
  421. TraceablePeerConnection.prototype.getDesiredMediaDirection = function(mediaType, isAddOperation = false) {
  422. const hasLocalSource = this.hasAnyTracksOfType(mediaType);
  423. if (isAddOperation) {
  424. return hasLocalSource ? MediaDirection.SENDRECV : MediaDirection.SENDONLY;
  425. }
  426. return hasLocalSource ? MediaDirection.RECVONLY : MediaDirection.INACTIVE;
  427. };
  428. /**
  429. * Returns the list of RTCRtpReceivers created for the source of the given media type associated with
  430. * the set of remote endpoints specified.
  431. * @param {Array<string>} endpoints list of the endpoints
  432. * @param {string} mediaType 'audio' or 'video'
  433. * @returns {Array<RTCRtpReceiver>} list of receivers created by the peerconnection.
  434. */
  435. TraceablePeerConnection.prototype._getReceiversByEndpointIds = function(endpoints, mediaType) {
  436. let remoteTracks = [];
  437. let receivers = [];
  438. for (const endpoint of endpoints) {
  439. remoteTracks = remoteTracks.concat(this.getRemoteTracks(endpoint, mediaType));
  440. }
  441. // Get the ids of the MediaStreamTracks associated with each of these remote tracks.
  442. const remoteTrackIds = remoteTracks.map(remote => remote.track?.id);
  443. receivers = this.peerconnection.getReceivers()
  444. .filter(receiver => receiver.track
  445. && receiver.track.kind === mediaType
  446. && remoteTrackIds.find(trackId => trackId === receiver.track.id));
  447. return receivers;
  448. };
  449. /**
  450. * Tells whether or not this TPC instance has spatial scalability enabled.
  451. * @return {boolean} <tt>true</tt> if spatial scalability is enabled and active or
  452. * <tt>false</tt> if it's turned off.
  453. */
  454. TraceablePeerConnection.prototype.isSpatialScalabilityOn = function() {
  455. const h264SimulcastEnabled = this.tpcUtils.codecSettings[CodecMimeType.H264].scalabilityModeEnabled
  456. && this._supportsDDHeaderExt;
  457. return !this.options.disableSimulcast
  458. && (this.codecSettings.codecList[0] !== CodecMimeType.H264 || h264SimulcastEnabled);
  459. };
  460. /**
  461. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  462. * @param {string} endpointId the video owner's ID (MUC nickname)
  463. * @param {VideoType} videoType the new value
  464. * @private
  465. */
  466. TraceablePeerConnection.prototype._peerVideoTypeChanged = function(endpointId, videoType) {
  467. // Check if endpointId has a value to avoid action on random track
  468. if (!endpointId) {
  469. logger.error(`${this} No endpointID on peerVideoTypeChanged`);
  470. return;
  471. }
  472. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  473. if (videoTrack.length) {
  474. // NOTE 1 track per media type is assumed
  475. videoTrack[0]._setVideoType(videoType);
  476. }
  477. };
  478. /**
  479. * Handles remote track mute / unmute events.
  480. * @param {string} endpointId the track owner's identifier (MUC nickname)
  481. * @param {MediaType} mediaType "audio" or "video"
  482. * @param {boolean} isMuted the new mute state
  483. * @private
  484. */
  485. TraceablePeerConnection.prototype._peerMutedChanged = function(endpointId, mediaType, isMuted) {
  486. // Check if endpointId is a value to avoid doing action on all remote tracks
  487. if (!endpointId) {
  488. logger.error(`${this} On peerMuteChanged - no endpoint ID`);
  489. return;
  490. }
  491. const track = this.getRemoteTracks(endpointId, mediaType);
  492. if (track.length) {
  493. // NOTE 1 track per media type is assumed
  494. track[0].setMute(isMuted);
  495. }
  496. };
  497. /**
  498. * Handles remote source mute and unmute changed events.
  499. *
  500. * @param {string} sourceName - The name of the remote source.
  501. * @param {boolean} isMuted - The new mute state.
  502. */
  503. TraceablePeerConnection.prototype._sourceMutedChanged = function(sourceName, isMuted) {
  504. const track = this.getRemoteTracks().find(t => t.getSourceName() === sourceName);
  505. if (!track) {
  506. if (FeatureFlags.isSsrcRewritingSupported()) {
  507. logger.debug(`Remote track not found for source=${sourceName}, mute update failed!`);
  508. }
  509. return;
  510. }
  511. track.setMute(isMuted);
  512. };
  513. /**
  514. * Handles remote source videoType changed events.
  515. *
  516. * @param {string} sourceName - The name of the remote source.
  517. * @param {boolean} isMuted - The new value.
  518. */
  519. TraceablePeerConnection.prototype._sourceVideoTypeChanged = function(sourceName, videoType) {
  520. const track = this.getRemoteTracks().find(t => t.getSourceName() === sourceName);
  521. if (!track) {
  522. return;
  523. }
  524. track._setVideoType(videoType);
  525. };
  526. /**
  527. * Obtains audio levels of the remote audio tracks by getting the source information on the RTCRtpReceivers.
  528. * The information relevant to the ssrc is updated each time a RTP packet constaining the ssrc is received.
  529. * @param {Array<string>} speakerList list of endpoint ids for which audio levels are to be gathered.
  530. * @returns {Object} containing ssrc and audio level information as a key-value pair.
  531. */
  532. TraceablePeerConnection.prototype.getAudioLevels = function(speakerList = []) {
  533. const audioLevels = {};
  534. const audioReceivers = speakerList.length
  535. ? this._getReceiversByEndpointIds(speakerList, MediaType.AUDIO)
  536. : this.peerconnection.getReceivers()
  537. .filter(receiver => receiver.track && receiver.track.kind === MediaType.AUDIO && receiver.track.enabled);
  538. audioReceivers.forEach(remote => {
  539. const ssrc = remote.getSynchronizationSources();
  540. if (ssrc && ssrc.length) {
  541. // As per spec, this audiolevel is a value between 0..1 (linear), where 1.0
  542. // represents 0 dBov, 0 represents silence, and 0.5 represents approximately
  543. // 6 dBSPL change in the sound pressure level from 0 dBov.
  544. // https://www.w3.org/TR/webrtc/#dom-rtcrtpcontributingsource-audiolevel
  545. audioLevels[ssrc[0].source] = ssrc[0].audioLevel;
  546. }
  547. });
  548. return audioLevels;
  549. };
  550. /**
  551. * Checks if the browser is currently doing true simulcast where in three different media streams are being sent to the
  552. * bridge. Currently this happens always for VP8 and only if simulcast is enabled for VP9/AV1/H264.
  553. * @returns {boolean}
  554. */
  555. TraceablePeerConnection.prototype.doesTrueSimulcast = function() {
  556. const currentCodec = this.getConfiguredVideoCodec();
  557. return this.isSpatialScalabilityOn() && this.tpcUtils.isRunningInSimulcastMode(currentCodec);
  558. };
  559. /**
  560. * Returns the SSRCs associated with a given local video track.
  561. *
  562. * @param {JitsiLocalTrack} localTrack
  563. * @returns
  564. */
  565. TraceablePeerConnection.prototype.getLocalVideoSSRCs = function(localTrack) {
  566. const ssrcs = [];
  567. if (!localTrack || !localTrack.isVideoTrack()) {
  568. return ssrcs;
  569. }
  570. const ssrcGroup = this.isSpatialScalabilityOn() ? 'SIM' : 'FID';
  571. return this.localSSRCs.get(localTrack.rtcId)?.groups?.find(group => group.semantics === ssrcGroup)?.ssrcs || ssrcs;
  572. };
  573. /**
  574. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  575. * argument is omitted the list of all local tracks will be returned.
  576. * @param {MediaType} [mediaType]
  577. * @return {Array<JitsiLocalTrack>}
  578. */
  579. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  580. let tracks = Array.from(this.localTracks.values());
  581. if (mediaType !== undefined) {
  582. tracks = tracks.filter(track => track.getType() === mediaType);
  583. }
  584. return tracks;
  585. };
  586. /**
  587. * Retrieves the local video tracks.
  588. *
  589. * @returns {Array<JitsiLocalTrack>} - local video tracks.
  590. */
  591. TraceablePeerConnection.prototype.getLocalVideoTracks = function() {
  592. return this.getLocalTracks(MediaType.VIDEO);
  593. };
  594. /**
  595. * Checks whether or not this {@link TraceablePeerConnection} instance contains any local tracks for given
  596. * <tt>mediaType</tt>.
  597. *
  598. * @param {MediaType} mediaType - The media type.
  599. * @return {boolean}
  600. */
  601. TraceablePeerConnection.prototype.hasAnyTracksOfType = function(mediaType) {
  602. if (!mediaType) {
  603. throw new Error('"mediaType" is required');
  604. }
  605. return this.getLocalTracks(mediaType).length > 0;
  606. };
  607. /**
  608. * Obtains all remote tracks currently known to this PeerConnection instance.
  609. *
  610. * @param {string} [endpointId] - The track owner's identifier (MUC nickname)
  611. * @param {MediaType} [mediaType] - The remote tracks will be filtered by their media type if this argument is
  612. * specified.
  613. * @return {Array<JitsiRemoteTrack>}
  614. */
  615. TraceablePeerConnection.prototype.getRemoteTracks = function(endpointId, mediaType) {
  616. let remoteTracks = [];
  617. if (FeatureFlags.isSsrcRewritingSupported()) {
  618. for (const remoteTrack of this.remoteTracksBySsrc.values()) {
  619. const owner = remoteTrack.getParticipantId();
  620. if (owner && (!endpointId || owner === endpointId)) {
  621. if (!mediaType || remoteTrack.getType() === mediaType) {
  622. remoteTracks.push(remoteTrack);
  623. }
  624. }
  625. }
  626. return remoteTracks;
  627. }
  628. const endpoints = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  629. for (const endpoint of endpoints) {
  630. const endpointTracksByMediaType = this.remoteTracks.get(endpoint);
  631. if (endpointTracksByMediaType) {
  632. for (const trackMediaType of endpointTracksByMediaType.keys()) {
  633. // per media type filtering
  634. if (!mediaType || mediaType === trackMediaType) {
  635. remoteTracks = remoteTracks.concat(Array.from(endpointTracksByMediaType.get(trackMediaType)));
  636. }
  637. }
  638. }
  639. }
  640. return remoteTracks;
  641. };
  642. /**
  643. * Parses the remote description and returns the sdp lines of the sources associated with a remote participant.
  644. *
  645. * @param {string} id Endpoint id of the remote participant.
  646. * @returns {Array<string>} The sdp lines that have the ssrc information.
  647. */
  648. TraceablePeerConnection.prototype.getRemoteSourceInfoByParticipant = function(id) {
  649. const removeSsrcInfo = [];
  650. const remoteTracks = this.getRemoteTracks(id);
  651. if (!remoteTracks?.length) {
  652. return removeSsrcInfo;
  653. }
  654. const primarySsrcs = remoteTracks.map(track => track.getSSRC());
  655. const sdp = new SDP(this.remoteDescription.sdp);
  656. primarySsrcs.forEach((ssrc, idx) => {
  657. for (const media of sdp.media) {
  658. let lines = '';
  659. let ssrcLines = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  660. if (ssrcLines.length) {
  661. if (!removeSsrcInfo[idx]) {
  662. removeSsrcInfo[idx] = '';
  663. }
  664. // Check if there are any FID groups present for the primary ssrc.
  665. const fidLines = SDPUtil.findLines(media, `a=ssrc-group:FID ${ssrc}`);
  666. if (fidLines.length) {
  667. const secondarySsrc = fidLines[0].split(' ')[2];
  668. lines += `${fidLines[0]}\r\n`;
  669. ssrcLines = ssrcLines.concat(SDPUtil.findLines(media, `a=ssrc:${secondarySsrc}`));
  670. }
  671. removeSsrcInfo[idx] += `${ssrcLines.join('\r\n')}\r\n`;
  672. removeSsrcInfo[idx] += lines;
  673. }
  674. }
  675. });
  676. return removeSsrcInfo;
  677. };
  678. /**
  679. * Returns the target bitrates configured for the local video source.
  680. *
  681. * @returns {Object}
  682. */
  683. TraceablePeerConnection.prototype.getTargetVideoBitrates = function() {
  684. const currentCodec = this.getConfiguredVideoCodec();
  685. return this.tpcUtils.codecSettings[currentCodec].maxBitratesVideo;
  686. };
  687. /**
  688. * Tries to find {@link JitsiTrack} for given SSRC number. It will search both
  689. * local and remote tracks bound to this instance.
  690. * @param {number} ssrc
  691. * @return {JitsiTrack|null}
  692. */
  693. TraceablePeerConnection.prototype.getTrackBySSRC = function(ssrc) {
  694. if (FeatureFlags.isSsrcRewritingSupported()) {
  695. return this.remoteTracksBySsrc.get(ssrc);
  696. }
  697. if (typeof ssrc !== 'number') {
  698. throw new Error(`SSRC ${ssrc} is not a number`);
  699. }
  700. for (const localTrack of this.localTracks.values()) {
  701. if (this.getLocalSSRC(localTrack) === ssrc) {
  702. return localTrack;
  703. }
  704. }
  705. for (const remoteTrack of this.getRemoteTracks()) {
  706. if (remoteTrack.getSSRC() === ssrc) {
  707. return remoteTrack;
  708. }
  709. }
  710. return null;
  711. };
  712. /**
  713. * Tries to find SSRC number for given {@link JitsiTrack} id. It will search
  714. * both local and remote tracks bound to this instance.
  715. * @param {string} id
  716. * @return {number|null}
  717. */
  718. TraceablePeerConnection.prototype.getSsrcByTrackId = function(id) {
  719. const findTrackById = track => track.getTrack().id === id;
  720. const localTrack = this.getLocalTracks().find(findTrackById);
  721. if (localTrack) {
  722. return this.getLocalSSRC(localTrack);
  723. }
  724. const remoteTrack = this.getRemoteTracks().find(findTrackById);
  725. if (remoteTrack) {
  726. return remoteTrack.getSSRC();
  727. }
  728. return null;
  729. };
  730. /**
  731. * Called on "track added" and "stream added" PeerConnection events (because we
  732. * handle streams on per track basis). Finds the owner and the SSRC for
  733. * the track and passes that to ChatRoom for further processing.
  734. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  735. * the parent of the track
  736. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  737. * participant.
  738. * @param {RTCRtpTransceiver} transceiver the WebRTC transceiver that is created
  739. * for the remote participant in unified plan.
  740. */
  741. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track, transceiver = null) {
  742. const streamId = stream.id;
  743. const mediaType = track.kind;
  744. // Do not create remote tracks for 'mixed' JVB SSRCs (used by JVB for RTCP termination).
  745. if (!this.isP2P && !RTCUtils.isUserStreamById(streamId)) {
  746. return;
  747. }
  748. logger.info(`${this} Received track event for remote stream[id=${streamId},type=${mediaType}]`);
  749. // look up an associated JID for a stream id
  750. if (!mediaType) {
  751. logger.error(`MediaType undefined for remote track, stream id: ${streamId}, track creation failed!`);
  752. return;
  753. }
  754. const remoteSDP = new SDP(this.peerconnection.remoteDescription.sdp);
  755. let mediaLine;
  756. // Find the matching mline using 'mid' or the 'msid' attr of the stream.
  757. if (transceiver?.mid) {
  758. const mid = transceiver.mid;
  759. mediaLine = remoteSDP.media.find(mls => SDPUtil.findLine(mls, `a=mid:${mid}`));
  760. } else {
  761. mediaLine = remoteSDP.media.find(mls => {
  762. const msid = SDPUtil.findLine(mls, 'a=msid:');
  763. return typeof msid === 'string' && streamId === msid.substring(7).split(' ')[0];
  764. });
  765. }
  766. if (!mediaLine) {
  767. logger.error(`Matching media line not found in remote SDP for remote stream[id=${streamId},type=${mediaType}],`
  768. + 'track creation failed!');
  769. return;
  770. }
  771. let ssrcLines = SDPUtil.findLines(mediaLine, 'a=ssrc:');
  772. ssrcLines = ssrcLines.filter(line => line.indexOf(`msid:${streamId}`) !== -1);
  773. if (!ssrcLines.length) {
  774. logger.error(`No SSRC lines found in remote SDP for remote stream[msid=${streamId},type=${mediaType}]`
  775. + 'track creation failed!');
  776. return;
  777. }
  778. // FIXME the length of ssrcLines[0] not verified, but it will fail
  779. // with global error handler anyway
  780. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  781. const trackSsrc = Number(ssrcStr);
  782. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  783. if (isNaN(trackSsrc) || trackSsrc < 0) {
  784. logger.error(`Invalid SSRC for remote stream[ssrc=${trackSsrc},id=${streamId},type=${mediaType}]`
  785. + 'track creation failed!');
  786. return;
  787. }
  788. if (!ownerEndpointId) {
  789. logger.error(`No SSRC owner known for remote stream[ssrc=${trackSsrc},id=${streamId},type=${mediaType}]`
  790. + 'track creation failed!');
  791. return;
  792. }
  793. const sourceName = this.signalingLayer.getTrackSourceName(trackSsrc);
  794. const peerMediaInfo = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType, sourceName);
  795. // Assume default presence state for remote source. Presence can be received after source signaling. This shouldn't
  796. // prevent the endpoint from creating a remote track for the source.
  797. let muted = true;
  798. let videoType = mediaType === MediaType.VIDEO ? VideoType.CAMERA : undefined; // 'camera' by default
  799. if (peerMediaInfo) {
  800. muted = peerMediaInfo.muted;
  801. videoType = peerMediaInfo.videoType; // can be undefined
  802. } else {
  803. logger.info(`${this}: no source-info available for ${ownerEndpointId}:${sourceName}, assuming default state`);
  804. }
  805. this._createRemoteTrack(ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted, sourceName);
  806. };
  807. // FIXME cleanup params
  808. /* eslint-disable max-params */
  809. /**
  810. * Initializes a new JitsiRemoteTrack instance with the data provided by
  811. * the signaling layer and SDP.
  812. *
  813. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  814. * @param {MediaStream} stream the WebRTC stream instance
  815. * @param {MediaStreamTrack} track the WebRTC track instance
  816. * @param {MediaType} mediaType the track's type of the media
  817. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  818. * @param {number} ssrc the track's main SSRC number
  819. * @param {boolean} muted the initial muted status
  820. * @param {String} sourceName the track's source name
  821. */
  822. TraceablePeerConnection.prototype._createRemoteTrack = function(
  823. ownerEndpointId,
  824. stream,
  825. track,
  826. mediaType,
  827. videoType,
  828. ssrc,
  829. muted,
  830. sourceName) {
  831. logger.info(`${this} creating remote track[endpoint=${ownerEndpointId},ssrc=${ssrc},`
  832. + `type=${mediaType},sourceName=${sourceName}]`);
  833. let remoteTracksMap;
  834. let userTracksByMediaType;
  835. if (FeatureFlags.isSsrcRewritingSupported()) {
  836. const existingTrack = this.remoteTracksBySsrc.get(ssrc);
  837. if (existingTrack) {
  838. logger.info(`${this} ignored duplicated track event for SSRC[ssrc=${ssrc},type=${mediaType}]`);
  839. return;
  840. }
  841. } else {
  842. remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  843. if (!remoteTracksMap) {
  844. remoteTracksMap = new Map();
  845. remoteTracksMap.set(MediaType.AUDIO, new Set());
  846. remoteTracksMap.set(MediaType.VIDEO, new Set());
  847. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  848. }
  849. userTracksByMediaType = remoteTracksMap.get(mediaType);
  850. if (userTracksByMediaType?.size
  851. && Array.from(userTracksByMediaType).find(jitsiTrack => jitsiTrack.getTrack() === track)) {
  852. // Ignore duplicated event which can originate either from 'onStreamAdded' or 'onTrackAdded'.
  853. logger.info(`${this} ignored duplicated track event for track[endpoint=${ownerEndpointId},`
  854. + `type=${mediaType}]`);
  855. return;
  856. }
  857. }
  858. const remoteTrack
  859. = new JitsiRemoteTrack(
  860. this.rtc,
  861. this.rtc.conference,
  862. ownerEndpointId,
  863. stream,
  864. track,
  865. mediaType,
  866. videoType,
  867. ssrc,
  868. muted,
  869. this.isP2P,
  870. sourceName);
  871. if (FeatureFlags.isSsrcRewritingSupported()) {
  872. this.remoteTracksBySsrc.set(ssrc, remoteTrack);
  873. } else {
  874. userTracksByMediaType.add(remoteTrack);
  875. }
  876. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack, this);
  877. };
  878. /**
  879. * Handles remote media track removal.
  880. *
  881. * @param {MediaStream} stream - WebRTC MediaStream instance which is the parent of the track.
  882. * @param {MediaStreamTrack} track - WebRTC MediaStreamTrack which has been removed from the PeerConnection.
  883. * @returns {void}
  884. */
  885. TraceablePeerConnection.prototype._remoteTrackRemoved = function(stream, track) {
  886. const streamId = stream.id;
  887. const trackId = track?.id;
  888. // Ignore stream removed events for JVB "mixed" sources (used for RTCP termination).
  889. if (!RTCUtils.isUserStreamById(streamId)) {
  890. return;
  891. }
  892. if (!streamId) {
  893. logger.error(`${this} remote track removal failed - no stream ID`);
  894. return;
  895. }
  896. if (!trackId) {
  897. logger.error(`${this} remote track removal failed - no track ID`);
  898. return;
  899. }
  900. const toBeRemoved = this.getRemoteTracks().find(
  901. remoteTrack => remoteTrack.getStreamId() === streamId && remoteTrack.getTrackId() === trackId);
  902. if (!toBeRemoved) {
  903. logger.error(`${this} remote track removal failed - track not found`);
  904. return;
  905. }
  906. this._removeRemoteTrack(toBeRemoved);
  907. };
  908. /**
  909. * Removes all JitsiRemoteTracks associated with given MUC nickname (resource part of the JID).
  910. *
  911. * @param {string} owner - The resource part of the MUC JID.
  912. * @returns {JitsiRemoteTrack[]} - The array of removed tracks.
  913. */
  914. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  915. let removedTracks = [];
  916. const remoteTracksByMedia = this.remoteTracks.get(owner);
  917. if (remoteTracksByMedia) {
  918. removedTracks = removedTracks.concat(Array.from(remoteTracksByMedia.get(MediaType.AUDIO)));
  919. removedTracks = removedTracks.concat(Array.from(remoteTracksByMedia.get(MediaType.VIDEO)));
  920. this.remoteTracks.delete(owner);
  921. }
  922. logger.debug(`${this} removed remote tracks[endpoint=${owner},count=${removedTracks.length}`);
  923. return removedTracks;
  924. };
  925. /**
  926. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  927. *
  928. * @param {JitsiRemoteTrack} toBeRemoved - The remote track to be removed.
  929. * @returns {void}
  930. */
  931. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  932. logger.info(`${this} Removing remote track stream[id=${toBeRemoved.getStreamId()},`
  933. + `trackId=${toBeRemoved.getTrackId()}]`);
  934. toBeRemoved.dispose();
  935. const participantId = toBeRemoved.getParticipantId();
  936. if (FeatureFlags.isSsrcRewritingSupported() && !participantId) {
  937. return;
  938. } else if (!FeatureFlags.isSsrcRewritingSupported()) {
  939. const userTracksByMediaType = this.remoteTracks.get(participantId);
  940. if (!userTracksByMediaType) {
  941. logger.error(`${this} removeRemoteTrack: no remote tracks map for endpoint=${participantId}`);
  942. } else if (!userTracksByMediaType.get(toBeRemoved.getType())?.delete(toBeRemoved)) {
  943. logger.error(`${this} Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  944. }
  945. }
  946. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  947. };
  948. /**
  949. * Returns a map with keys msid/mediaType and <tt>TrackSSRCInfo</tt> values.
  950. * @param {RTCSessionDescription} desc the local description.
  951. * @return {Map<string,TrackSSRCInfo>}
  952. */
  953. TraceablePeerConnection.prototype._extractSSRCMap = function(desc) {
  954. /**
  955. * Track SSRC infos mapped by stream ID (msid) or mediaType (unified-plan)
  956. * @type {Map<string,TrackSSRCInfo>}
  957. */
  958. const ssrcMap = new Map();
  959. /**
  960. * Groups mapped by primary SSRC number
  961. * @type {Map<number,Array<SSRCGroupInfo>>}
  962. */
  963. const groupsMap = new Map();
  964. if (typeof desc !== 'object' || desc === null
  965. || typeof desc.sdp !== 'string') {
  966. logger.warn('An empty description was passed as an argument');
  967. return ssrcMap;
  968. }
  969. const session = transform.parse(desc.sdp);
  970. if (!Array.isArray(session.media)) {
  971. return ssrcMap;
  972. }
  973. let media = session.media;
  974. media = media.filter(mline => mline.direction === MediaDirection.SENDONLY
  975. || mline.direction === MediaDirection.SENDRECV);
  976. let index = 0;
  977. for (const mLine of media) {
  978. if (!Array.isArray(mLine.ssrcs)) {
  979. continue; // eslint-disable-line no-continue
  980. }
  981. if (Array.isArray(mLine.ssrcGroups)) {
  982. for (const group of mLine.ssrcGroups) {
  983. if (typeof group.semantics !== 'undefined' && typeof group.ssrcs !== 'undefined') {
  984. // Parse SSRCs and store as numbers
  985. const groupSSRCs = group.ssrcs.split(' ').map(ssrcStr => parseInt(ssrcStr, 10));
  986. const primarySSRC = groupSSRCs[0];
  987. // Note that group.semantics is already present
  988. group.ssrcs = groupSSRCs;
  989. // eslint-disable-next-line max-depth
  990. if (!groupsMap.has(primarySSRC)) {
  991. groupsMap.set(primarySSRC, []);
  992. }
  993. groupsMap.get(primarySSRC).push(group);
  994. }
  995. }
  996. const simGroup = mLine.ssrcGroups.find(group => group.semantics === 'SIM');
  997. // Add a SIM group if its missing in the description (happens on Firefox).
  998. if (!simGroup) {
  999. const groupSsrcs = mLine.ssrcGroups.map(group => group.ssrcs[0]);
  1000. groupsMap.get(groupSsrcs[0]).push({
  1001. semantics: 'SIM',
  1002. ssrcs: groupSsrcs
  1003. });
  1004. }
  1005. }
  1006. let ssrcs = mLine.ssrcs;
  1007. // Filter the ssrcs with 'cname' attribute.
  1008. ssrcs = ssrcs.filter(s => s.attribute === 'cname');
  1009. for (const ssrc of ssrcs) {
  1010. // Use the mediaType as key for the source map for unified plan clients since msids are not part of
  1011. // the standard and the unified plan SDPs do not have a proper msid attribute for the sources.
  1012. // Also the ssrcs for sources do not change for Unified plan clients since RTCRtpSender#replaceTrack is
  1013. // used for switching the tracks so it is safe to use the mediaType as the key for the TrackSSRCInfo map.
  1014. const key = `${mLine.type}-${index}`;
  1015. const ssrcNumber = ssrc.id;
  1016. let ssrcInfo = ssrcMap.get(key);
  1017. if (!ssrcInfo) {
  1018. ssrcInfo = {
  1019. ssrcs: [],
  1020. groups: [],
  1021. msid: key
  1022. };
  1023. ssrcMap.set(key, ssrcInfo);
  1024. }
  1025. ssrcInfo.ssrcs.push(ssrcNumber);
  1026. if (groupsMap.has(ssrcNumber)) {
  1027. const ssrcGroups = groupsMap.get(ssrcNumber);
  1028. for (const group of ssrcGroups) {
  1029. ssrcInfo.groups.push(group);
  1030. }
  1031. }
  1032. }
  1033. // Currently multi-stream is supported for video only.
  1034. mLine.type === MediaType.VIDEO && index++;
  1035. }
  1036. return ssrcMap;
  1037. };
  1038. /**
  1039. *
  1040. * @param {JitsiLocalTrack} localTrack
  1041. */
  1042. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  1043. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  1044. return ssrcInfo && ssrcInfo.ssrcs[0];
  1045. };
  1046. /**
  1047. * When doing unified plan simulcast, we'll have a set of ssrcs but no ssrc-groups on Firefox. Unfortunately, Jicofo
  1048. * will complain if it sees ssrcs with matching msids but no ssrc-group, so a ssrc-group line is injected to make
  1049. * Jicofo happy.
  1050. *
  1051. * @param desc A session description object (with 'type' and 'sdp' fields)
  1052. * @return A session description object with its sdp field modified to contain an inject ssrc-group for simulcast.
  1053. */
  1054. TraceablePeerConnection.prototype._injectSsrcGroupForUnifiedSimulcast = function(desc) {
  1055. const sdp = transform.parse(desc.sdp);
  1056. const video = sdp.media.find(mline => mline.type === 'video');
  1057. // Check if the browser supports RTX, add only the primary ssrcs to the SIM group if that is the case.
  1058. video.ssrcGroups = video.ssrcGroups || [];
  1059. const fidGroups = video.ssrcGroups.filter(group => group.semantics === 'FID');
  1060. if (video.simulcast || video.simulcast_03) {
  1061. const ssrcs = [];
  1062. if (fidGroups && fidGroups.length) {
  1063. fidGroups.forEach(group => {
  1064. ssrcs.push(group.ssrcs.split(' ')[0]);
  1065. });
  1066. } else {
  1067. video.ssrcs.forEach(ssrc => {
  1068. if (ssrc.attribute === 'msid') {
  1069. ssrcs.push(ssrc.id);
  1070. }
  1071. });
  1072. }
  1073. if (video.ssrcGroups.find(group => group.semantics === 'SIM')) {
  1074. // Group already exists, no need to do anything
  1075. return desc;
  1076. }
  1077. // Add a SIM group for every 3 FID groups.
  1078. for (let i = 0; i < ssrcs.length; i += 3) {
  1079. const simSsrcs = ssrcs.slice(i, i + 3);
  1080. video.ssrcGroups.push({
  1081. semantics: 'SIM',
  1082. ssrcs: simSsrcs.join(' ')
  1083. });
  1084. }
  1085. }
  1086. return new RTCSessionDescription({
  1087. type: desc.type,
  1088. sdp: transform.write(sdp)
  1089. });
  1090. };
  1091. /* eslint-disable-next-line vars-on-top */
  1092. const getters = {
  1093. signalingState() {
  1094. return this.peerconnection.signalingState;
  1095. },
  1096. iceConnectionState() {
  1097. return this.peerconnection.iceConnectionState;
  1098. },
  1099. connectionState() {
  1100. return this.peerconnection.connectionState;
  1101. },
  1102. localDescription() {
  1103. let desc = this.peerconnection.localDescription;
  1104. if (!desc) {
  1105. logger.debug(`${this} getLocalDescription no localDescription found`);
  1106. return {};
  1107. }
  1108. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1109. // For a jvb connection, transform the SDP to Plan B first.
  1110. if (!this.isP2P) {
  1111. desc = this.interop.toPlanB(desc);
  1112. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  1113. desc = this._injectSsrcGroupForUnifiedSimulcast(desc);
  1114. this.trace('getLocalDescription::postTransform (inject ssrc group)', dumpSDP(desc));
  1115. }
  1116. // See the method's doc for more info about this transformation.
  1117. desc = this.localSdpMunger.transformStreamIdentifiers(desc);
  1118. return desc;
  1119. },
  1120. remoteDescription() {
  1121. let desc = this.peerconnection.remoteDescription;
  1122. if (!desc) {
  1123. logger.debug(`${this} getRemoteDescription no remoteDescription found`);
  1124. return {};
  1125. }
  1126. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1127. if (this.isP2P) {
  1128. // Adjust the media direction for p2p based on whether a local source has been added.
  1129. desc = this._adjustRemoteMediaDirection(desc);
  1130. } else {
  1131. // If this is a jvb connection, transform the SDP to Plan B first.
  1132. desc = this.interop.toPlanB(desc);
  1133. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  1134. }
  1135. return desc;
  1136. }
  1137. };
  1138. Object.keys(getters).forEach(prop => {
  1139. Object.defineProperty(
  1140. TraceablePeerConnection.prototype,
  1141. prop, {
  1142. get: getters[prop]
  1143. }
  1144. );
  1145. });
  1146. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1147. return this.localSSRCs.get(rtcId);
  1148. };
  1149. /**
  1150. * Checks if low fps screensharing is in progress.
  1151. *
  1152. * @private
  1153. * @returns {boolean} Returns true if 5 fps screensharing is in progress, false otherwise.
  1154. */
  1155. TraceablePeerConnection.prototype.isSharingLowFpsScreen = function() {
  1156. return this._isSharingScreen() && this._capScreenshareBitrate;
  1157. };
  1158. /**
  1159. * Checks if screensharing is in progress.
  1160. *
  1161. * @returns {boolean} Returns true if a desktop track has been added to the peerconnection, false otherwise.
  1162. */
  1163. TraceablePeerConnection.prototype._isSharingScreen = function() {
  1164. const tracks = this.getLocalVideoTracks();
  1165. return Boolean(tracks.find(track => track.videoType === VideoType.DESKTOP));
  1166. };
  1167. /**
  1168. * Munges the order of the codecs in the SDP passed based on the preference
  1169. * set through config.js settings. All instances of the specified codec are
  1170. * moved up to the top of the list when it is preferred. The specified codec
  1171. * is deleted from the list if the configuration specifies that the codec be
  1172. * disabled.
  1173. * @param {RTCSessionDescription} description that needs to be munged.
  1174. * @returns {RTCSessionDescription} the munged description.
  1175. */
  1176. TraceablePeerConnection.prototype._mungeCodecOrder = function(description) {
  1177. if (!this.codecSettings) {
  1178. return description;
  1179. }
  1180. const parsedSdp = transform.parse(description.sdp);
  1181. const mLines = parsedSdp.media.filter(m => m.type === this.codecSettings.mediaType);
  1182. if (!mLines.length) {
  1183. return description;
  1184. }
  1185. for (const mLine of mLines) {
  1186. const currentCodecs = this.getConfiguredVideoCodecs(description);
  1187. for (const codec of currentCodecs) {
  1188. if (this.isP2P) {
  1189. // 1. Strip the high profile H264 codecs on all clients. macOS started offering encoder for H.264 level
  1190. // 5.2 but a decoder only for level 3.1. Therfore, strip all main and high level codecs for H.264.
  1191. // 2. There are multiple VP9 payload types generated by the browser, more payload types are added if the
  1192. // endpoint doesn't have a local video source. Therefore, strip all the high profile codec variants
  1193. // for VP9 so that only one payload type for VP9 is negotiated between the peers.
  1194. if (codec === CodecMimeType.H264 || codec === CodecMimeType.VP9) {
  1195. SDPUtil.stripCodec(mLine, codec, true /* high profile */);
  1196. }
  1197. // Do not negotiate ULPFEC and RED either.
  1198. if (codec === CodecMimeType.ULPFEC || codec === CodecMimeType.RED) {
  1199. SDPUtil.stripCodec(mLine, codec, false);
  1200. }
  1201. }
  1202. }
  1203. // Reorder the codecs based on the preferred settings.
  1204. for (const codec of this.codecSettings.codecList.slice().reverse()) {
  1205. SDPUtil.preferCodec(mLine, codec, this.isP2P);
  1206. }
  1207. }
  1208. return new RTCSessionDescription({
  1209. type: description.type,
  1210. sdp: transform.write(parsedSdp)
  1211. });
  1212. };
  1213. /**
  1214. * Checks if the AV1 Dependency descriptors are negotiated on the bridge peerconnection and disables them when the
  1215. * codec selected is VP8 or VP9.
  1216. *
  1217. * @param {RTCSessionDescription} description that needs to be munged.
  1218. * @returns {RTCSessionDescription} the munged description.
  1219. */
  1220. TraceablePeerConnection.prototype._updateAv1DdHeaders = function(description) {
  1221. const parsedSdp = transform.parse(description.sdp);
  1222. const mLines = parsedSdp.media.filter(m => m.type === MediaType.VIDEO);
  1223. if (!mLines.length || !browser.supportsDDExtHeaders()) {
  1224. return description;
  1225. }
  1226. mLines.forEach((mLine, idx) => {
  1227. const senderMids = Array.from(this._localTrackTransceiverMids.values());
  1228. const isSender = senderMids.length
  1229. ? senderMids.find(mid => mLine.mid.toString() === mid.toString())
  1230. : idx === 0;
  1231. const payload = mLine.payloads.split(' ')[0];
  1232. let { codec } = mLine.rtp.find(rtp => rtp.payload === Number(payload));
  1233. codec = codec.toLowerCase();
  1234. if (isSender && mLine.ext?.length) {
  1235. const headerIndex = mLine.ext.findIndex(ext => ext.uri === DD_HEADER_EXT_URI);
  1236. const shouldNegotiateHeaderExts = codec === CodecMimeType.AV1 || codec === CodecMimeType.H264;
  1237. if (!this._supportsDDHeaderExt && headerIndex >= 0) {
  1238. this._supportsDDHeaderExt = true;
  1239. }
  1240. if (this._supportsDDHeaderExt && shouldNegotiateHeaderExts && headerIndex < 0) {
  1241. mLine.ext.push({
  1242. value: DD_HEADER_EXT_ID,
  1243. uri: DD_HEADER_EXT_URI
  1244. });
  1245. } else if (!shouldNegotiateHeaderExts && headerIndex >= 0) {
  1246. mLine.ext.splice(headerIndex, 1);
  1247. }
  1248. }
  1249. });
  1250. return new RTCSessionDescription({
  1251. type: description.type,
  1252. sdp: transform.write(parsedSdp)
  1253. });
  1254. };
  1255. /**
  1256. * Add {@link JitsiLocalTrack} to this TPC.
  1257. * @param {JitsiLocalTrack} track
  1258. * @param {boolean} isInitiator indicates if the endpoint is the offerer.
  1259. * @returns {Promise<void>} - resolved when done.
  1260. */
  1261. TraceablePeerConnection.prototype.addTrack = function(track, isInitiator = false) {
  1262. const rtcId = track.rtcId;
  1263. logger.info(`${this} adding ${track}`);
  1264. if (this.localTracks.has(rtcId)) {
  1265. return Promise.reject(new Error(`${track} is already in ${this}`));
  1266. }
  1267. this.localTracks.set(rtcId, track);
  1268. const webrtcStream = track.getOriginalStream();
  1269. try {
  1270. this.tpcUtils.addTrack(track, isInitiator);
  1271. if (track) {
  1272. if (track.isAudioTrack()) {
  1273. this._hasHadAudioTrack = true;
  1274. } else {
  1275. this._hasHadVideoTrack = true;
  1276. }
  1277. }
  1278. } catch (error) {
  1279. logger.error(`${this} Adding track=${track} failed: ${error?.message}`);
  1280. return Promise.reject(error);
  1281. }
  1282. let promiseChain = Promise.resolve();
  1283. // On Firefox, the encodings have to be configured on the sender only after the transceiver is created.
  1284. if (browser.isFirefox()) {
  1285. promiseChain = promiseChain.then(() => webrtcStream && this.tpcUtils.setEncodings(track));
  1286. }
  1287. return promiseChain;
  1288. };
  1289. /**
  1290. * Adds local track to the RTCPeerConnection.
  1291. *
  1292. * @param {JitsiLocalTrack} track the track to be added to the pc.
  1293. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's state has changed and
  1294. * renegotiation is required, false if no renegotiation is needed or Promise is rejected when something goes wrong.
  1295. */
  1296. TraceablePeerConnection.prototype.addTrackToPc = function(track) {
  1297. logger.info(`${this} Adding track=${track} to PC`);
  1298. if (!this._assertTrackBelongs('addTrackToPc', track)) {
  1299. // Abort
  1300. return Promise.reject('Track not found on the peerconnection');
  1301. }
  1302. const webRtcStream = track.getOriginalStream();
  1303. if (!webRtcStream) {
  1304. logger.error(`${this} Unable to add track=${track} to PC - no WebRTC stream`);
  1305. return Promise.reject('Stream not found');
  1306. }
  1307. return this.tpcUtils.replaceTrack(null, track).then(() => {
  1308. if (track) {
  1309. if (track.isAudioTrack()) {
  1310. this._hasHadAudioTrack = true;
  1311. } else {
  1312. this._hasHadVideoTrack = true;
  1313. }
  1314. }
  1315. return false;
  1316. });
  1317. };
  1318. /**
  1319. * This method when called will check if given <tt>localTrack</tt> belongs to
  1320. * this TPC (that it has been previously added using {@link addTrack}). If the
  1321. * track does not belong an error message will be logged.
  1322. * @param {string} methodName the method name that will be logged in an error
  1323. * message
  1324. * @param {JitsiLocalTrack} localTrack
  1325. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1326. * <tt>false</tt> otherwise.
  1327. * @private
  1328. */
  1329. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1330. methodName,
  1331. localTrack) {
  1332. const doesBelong = this.localTracks.has(localTrack?.rtcId);
  1333. if (!doesBelong) {
  1334. logger.error(`${this} ${methodName}: track=${localTrack} does not belong to pc`);
  1335. }
  1336. return doesBelong;
  1337. };
  1338. /**
  1339. * Returns the codec that is configured on the client as the preferred video codec.
  1340. * This takes into account the current order of codecs in the local description sdp.
  1341. *
  1342. * @returns {CodecMimeType} The codec that is set as the preferred codec to receive
  1343. * video in the local SDP.
  1344. */
  1345. TraceablePeerConnection.prototype.getConfiguredVideoCodec = function() {
  1346. const sdp = this.peerconnection.remoteDescription?.sdp;
  1347. const defaultCodec = CodecMimeType.VP8;
  1348. if (!sdp) {
  1349. return defaultCodec;
  1350. }
  1351. const parsedSdp = transform.parse(sdp);
  1352. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  1353. const payload = mLine.payloads.split(' ')[0];
  1354. const { codec } = mLine.rtp.find(rtp => rtp.payload === Number(payload));
  1355. if (codec) {
  1356. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  1357. }
  1358. return defaultCodec;
  1359. };
  1360. /**
  1361. * Returns the codecs in the current order of preference as configured on the peerconnection.
  1362. *
  1363. * @param {RTCSessionDescription} - The local description to be used.
  1364. * @returns {Array}
  1365. */
  1366. TraceablePeerConnection.prototype.getConfiguredVideoCodecs = function(description) {
  1367. const currentSdp = description?.sdp ?? this.peerconnection.localDescription?.sdp;
  1368. if (!currentSdp) {
  1369. return [];
  1370. }
  1371. const parsedSdp = transform.parse(currentSdp);
  1372. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  1373. const codecs = new Set(mLine.rtp
  1374. .filter(pt => pt.codec.toLowerCase() !== 'rtx')
  1375. .map(pt => pt.codec.toLowerCase()));
  1376. return Array.from(codecs);
  1377. };
  1378. /**
  1379. * Checks if the client has negotiated not to receive video encoded using the given codec, i.e., the codec has been
  1380. * removed from the local description.
  1381. */
  1382. TraceablePeerConnection.prototype.isVideoCodecDisabled = function(codec) {
  1383. const sdp = this.peerconnection.localDescription?.sdp;
  1384. if (!sdp) {
  1385. return false;
  1386. }
  1387. const parsedSdp = transform.parse(sdp);
  1388. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  1389. return !mLine.rtp.find(r => r.codec === codec);
  1390. };
  1391. /**
  1392. * Enables or disables simulcast for screenshare based on the frame rate requested for desktop track capture.
  1393. *
  1394. * @param {number} maxFps framerate to be used for desktop track capture.
  1395. */
  1396. TraceablePeerConnection.prototype.setDesktopSharingFrameRate = function(maxFps) {
  1397. const lowFps = maxFps <= SS_DEFAULT_FRAME_RATE;
  1398. this._capScreenshareBitrate = this.isSpatialScalabilityOn() && lowFps;
  1399. };
  1400. /**
  1401. * Sets the codec preference on the peerconnection. The codec preference goes into effect when
  1402. * the next renegotiation happens.
  1403. *
  1404. * @param {CodecMimeType} preferredCodec the preferred codec.
  1405. * @param {CodecMimeType} disabledCodec the codec that needs to be disabled.
  1406. * @returns {void}
  1407. */
  1408. TraceablePeerConnection.prototype.setVideoCodecs = function(codecList) {
  1409. if (!this.codecSettings || !codecList?.length) {
  1410. return;
  1411. }
  1412. this.codecSettings.codecList = codecList;
  1413. };
  1414. /**
  1415. * Remove local track from this TPC.
  1416. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1417. *
  1418. * FIXME It should probably remove a boolean just like {@link removeTrackFromPc}
  1419. * The same applies to addTrack.
  1420. */
  1421. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1422. const webRtcStream = localTrack.getOriginalStream();
  1423. this.trace(
  1424. 'removeStream',
  1425. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1426. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1427. // Abort - nothing to be done here
  1428. return;
  1429. }
  1430. this.localTracks.delete(localTrack.rtcId);
  1431. this.localSSRCs.delete(localTrack.rtcId);
  1432. if (webRtcStream) {
  1433. this.peerconnection.removeStream(webRtcStream);
  1434. }
  1435. };
  1436. /**
  1437. * Returns the sender corresponding to the given media type.
  1438. * @param {MEDIA_TYPE} mediaType - The media type 'audio' or 'video' to be used for the search.
  1439. * @returns {RTPSender|undefined} - The found sender or undefined if no sender
  1440. * was found.
  1441. */
  1442. TraceablePeerConnection.prototype.findSenderByKind = function(mediaType) {
  1443. if (this.peerconnection.getSenders) {
  1444. return this.peerconnection.getSenders().find(s => s.track && s.track.kind === mediaType);
  1445. }
  1446. };
  1447. /**
  1448. * Returns the receiver corresponding to the given MediaStreamTrack.
  1449. *
  1450. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1451. * @returns {RTCRtpReceiver|undefined} - The found receiver or undefined if no receiver
  1452. * was found.
  1453. */
  1454. TraceablePeerConnection.prototype.findReceiverForTrack = function(track) {
  1455. return this.peerconnection.getReceivers().find(r => r.track === track);
  1456. };
  1457. /**
  1458. * Returns the sender corresponding to the given MediaStreamTrack.
  1459. *
  1460. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1461. * @returns {RTCRtpSender|undefined} - The found sender or undefined if no sender
  1462. * was found.
  1463. */
  1464. TraceablePeerConnection.prototype.findSenderForTrack = function(track) {
  1465. if (this.peerconnection.getSenders) {
  1466. return this.peerconnection.getSenders().find(s => s.track === track);
  1467. }
  1468. };
  1469. /**
  1470. * Processes the local description SDP and caches the mids of the mlines associated with the given tracks.
  1471. *
  1472. * @param {Array<JitsiLocalTrack>} localTracks - local tracks that are added to the peerconnection.
  1473. * @returns {void}
  1474. */
  1475. TraceablePeerConnection.prototype.processLocalSdpForTransceiverInfo = function(localTracks) {
  1476. const localSdp = this.peerconnection.localDescription?.sdp;
  1477. if (!localSdp) {
  1478. return;
  1479. }
  1480. [ MediaType.AUDIO, MediaType.VIDEO ].forEach(mediaType => {
  1481. const tracks = localTracks.filter(t => t.getType() === mediaType);
  1482. const parsedSdp = transform.parse(localSdp);
  1483. const mLines = parsedSdp.media.filter(mline => mline.type === mediaType);
  1484. tracks.forEach((track, idx) => {
  1485. if (!this._localTrackTransceiverMids.has(track.rtcId)) {
  1486. this._localTrackTransceiverMids.set(track.rtcId, mLines[idx].mid.toString());
  1487. }
  1488. });
  1489. });
  1490. };
  1491. /**
  1492. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1493. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1494. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1495. * <tt>oldTrack</tt>
  1496. *
  1497. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be replaced on the pc.
  1498. * @param {JitsiLocalTrack|null} newTrack - The new track to be used.
  1499. *
  1500. * @returns {Promise<boolean>} - If the promise resolves with true, renegotiation will be needed.
  1501. * Otherwise no renegotiation is needed.
  1502. */
  1503. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack) {
  1504. if (!(oldTrack || newTrack)) {
  1505. logger.info(`${this} replaceTrack called with no new track and no old track`);
  1506. return Promise.resolve();
  1507. }
  1508. logger.info(`${this} TPC.replaceTrack old=${oldTrack}, new=${newTrack}`);
  1509. return this.tpcUtils.replaceTrack(oldTrack, newTrack)
  1510. .then(transceiver => {
  1511. if (oldTrack) {
  1512. this.localTracks.delete(oldTrack.rtcId);
  1513. this._localTrackTransceiverMids.delete(oldTrack.rtcId);
  1514. }
  1515. if (newTrack) {
  1516. if (newTrack.isAudioTrack()) {
  1517. this._hasHadAudioTrack = true;
  1518. } else {
  1519. this._hasHadVideoTrack = true;
  1520. }
  1521. this._localTrackTransceiverMids.set(newTrack.rtcId, transceiver?.mid?.toString());
  1522. this.localTracks.set(newTrack.rtcId, newTrack);
  1523. }
  1524. // Update the local SSRC cache for the case when one track gets replaced with another and no
  1525. // renegotiation is triggered as a result of this.
  1526. if (oldTrack && newTrack) {
  1527. const oldTrackSSRC = this.localSSRCs.get(oldTrack.rtcId);
  1528. if (oldTrackSSRC) {
  1529. this.localSSRCs.delete(oldTrack.rtcId);
  1530. this.localSSRCs.set(newTrack.rtcId, oldTrackSSRC);
  1531. }
  1532. }
  1533. if (transceiver) {
  1534. // In the scenario where we remove the oldTrack (oldTrack is not null and newTrack is null) on FF
  1535. // if we change the direction to RECVONLY, create answer will generate SDP with only 1 receive
  1536. // only ssrc instead of keeping all 6 ssrcs that we currently have. Stopping the screen sharing
  1537. // and then starting it again will trigger 2 rounds of source-remove and source-add replacing
  1538. // the 6 ssrcs for the screen sharing with 1 receive only ssrc and then removing the receive
  1539. // only ssrc and adding the same 6 ssrcs. On the remote participant's side the same ssrcs will
  1540. // be reused on a new m-line and if the remote participant is FF due to
  1541. // https://bugzilla.mozilla.org/show_bug.cgi?id=1768729 the video stream won't be rendered.
  1542. // That's why we need keep the direction to SENDRECV for FF.
  1543. //
  1544. // NOTE: If we return back to the approach of not removing the track for FF and instead using the
  1545. // enabled property for mute or stopping screensharing we may need to change the direction to
  1546. // RECVONLY if FF still sends the media even though the enabled flag is set to false.
  1547. transceiver.direction
  1548. = newTrack || browser.isFirefox() ? MediaDirection.SENDRECV : MediaDirection.RECVONLY;
  1549. }
  1550. // Avoid configuring the video encodings on Chromium/Safari until simulcast is configured
  1551. // for the newly added video track using SDP munging which happens during the renegotiation.
  1552. const configureEncodingsPromise
  1553. = !newTrack || (newTrack.getType() === MediaType.VIDEO && browser.usesSdpMungingForSimulcast())
  1554. ? Promise.resolve()
  1555. : this.tpcUtils.setEncodings(newTrack);
  1556. return configureEncodingsPromise.then(() => this.isP2P);
  1557. });
  1558. };
  1559. /**
  1560. * Removes local track from the RTCPeerConnection.
  1561. *
  1562. * @param {JitsiLocalTrack} localTrack the local track to be removed.
  1563. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's state has changed and
  1564. * renegotiation is required, false if no renegotiation is needed or Promise is rejected when something goes wrong.
  1565. */
  1566. TraceablePeerConnection.prototype.removeTrackFromPc = function(localTrack) {
  1567. const webRtcStream = localTrack.getOriginalStream();
  1568. this.trace('removeTrack', localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1569. if (!this._assertTrackBelongs('removeTrack', localTrack)) {
  1570. // Abort - nothing to be done here
  1571. return Promise.reject('Track not found in the peerconnection');
  1572. }
  1573. return this.tpcUtils.replaceTrack(localTrack, null).then(() => false);
  1574. };
  1575. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1576. this.trace('createDataChannel', label, opts);
  1577. return this.peerconnection.createDataChannel(label, opts);
  1578. };
  1579. /**
  1580. * Adjusts the media direction on the remote description based on availability of local and remote sources in a p2p
  1581. * media connection.
  1582. *
  1583. * @param {RTCSessionDescription} remoteDescription the WebRTC session description instance for the remote description.
  1584. * @returns the transformed remoteDescription.
  1585. * @private
  1586. */
  1587. TraceablePeerConnection.prototype._adjustRemoteMediaDirection = function(remoteDescription) {
  1588. const transformer = new SdpTransformWrap(remoteDescription.sdp);
  1589. [ MediaType.AUDIO, MediaType.VIDEO ].forEach(mediaType => {
  1590. const media = transformer.selectMedia(mediaType);
  1591. const localSources = this.getLocalTracks(mediaType).length;
  1592. const remoteSources = this.getRemoteTracks(null, mediaType).length;
  1593. media.forEach((mLine, idx) => {
  1594. if (localSources && localSources === remoteSources) {
  1595. mLine.direction = MediaDirection.SENDRECV;
  1596. } else if (!localSources && !remoteSources) {
  1597. mLine.direction = MediaDirection.INACTIVE;
  1598. } else if (!localSources) {
  1599. mLine.direction = MediaDirection.SENDONLY;
  1600. } else if (!remoteSources) {
  1601. mLine.direction = MediaDirection.RECVONLY;
  1602. // When there are 2 local sources and 1 remote source, the first m-line should be set to 'sendrecv' while
  1603. // the second one needs to be set to 'recvonly'.
  1604. } else if (localSources > remoteSources) {
  1605. mLine.direction = idx ? MediaDirection.RECVONLY : MediaDirection.SENDRECV;
  1606. // When there are 2 remote sources and 1 local source, the first m-line should be set to 'sendrecv' while
  1607. // the second one needs to be set to 'sendonly'.
  1608. } else {
  1609. mLine.direction = idx ? MediaDirection.SENDONLY : MediaDirection.SENDRECV;
  1610. }
  1611. });
  1612. });
  1613. return new RTCSessionDescription({
  1614. type: remoteDescription.type,
  1615. sdp: transformer.toRawSDP()
  1616. });
  1617. };
  1618. /**
  1619. * Munges the stereo flag as well as the opusMaxAverageBitrate in the SDP, based
  1620. * on values set through config.js, if present.
  1621. *
  1622. * @param {RTCSessionDescription} description that needs to be munged.
  1623. * @returns {RTCSessionDescription} the munged description.
  1624. */
  1625. TraceablePeerConnection.prototype._mungeOpus = function(description) {
  1626. const { audioQuality } = this.options;
  1627. if (!audioQuality?.enableOpusDtx && !audioQuality?.stereo && !audioQuality?.opusMaxAverageBitrate) {
  1628. return description;
  1629. }
  1630. const parsedSdp = transform.parse(description.sdp);
  1631. const mLines = parsedSdp.media;
  1632. for (const mLine of mLines) {
  1633. if (mLine.type === 'audio') {
  1634. const { payload } = mLine.rtp.find(protocol => protocol.codec === CodecMimeType.OPUS);
  1635. if (!payload) {
  1636. // eslint-disable-next-line no-continue
  1637. continue;
  1638. }
  1639. let fmtpOpus = mLine.fmtp.find(protocol => protocol.payload === payload);
  1640. if (!fmtpOpus) {
  1641. fmtpOpus = {
  1642. payload,
  1643. config: ''
  1644. };
  1645. }
  1646. const fmtpConfig = transform.parseParams(fmtpOpus.config);
  1647. let sdpChanged = false;
  1648. if (audioQuality?.stereo) {
  1649. fmtpConfig.stereo = 1;
  1650. sdpChanged = true;
  1651. }
  1652. if (audioQuality?.opusMaxAverageBitrate) {
  1653. fmtpConfig.maxaveragebitrate = audioQuality.opusMaxAverageBitrate;
  1654. sdpChanged = true;
  1655. }
  1656. // On Firefox, the OpusDtx enablement has no effect
  1657. if (!browser.isFirefox() && audioQuality?.enableOpusDtx) {
  1658. fmtpConfig.usedtx = 1;
  1659. sdpChanged = true;
  1660. }
  1661. if (!sdpChanged) {
  1662. // eslint-disable-next-line no-continue
  1663. continue;
  1664. }
  1665. let mungedConfig = '';
  1666. for (const key of Object.keys(fmtpConfig)) {
  1667. mungedConfig += `${key}=${fmtpConfig[key]}; `;
  1668. }
  1669. fmtpOpus.config = mungedConfig.trim();
  1670. }
  1671. }
  1672. return new RTCSessionDescription({
  1673. type: description.type,
  1674. sdp: transform.write(parsedSdp)
  1675. });
  1676. };
  1677. /**
  1678. * Munges the SDP to set all directions to inactive and drop all ssrc and ssrc-groups.
  1679. *
  1680. * @param {RTCSessionDescription} description that needs to be munged.
  1681. * @returns {RTCSessionDescription} the munged description.
  1682. */
  1683. TraceablePeerConnection.prototype._mungeInactive = function(description) {
  1684. const parsedSdp = transform.parse(description.sdp);
  1685. const mLines = parsedSdp.media;
  1686. for (const mLine of mLines) {
  1687. mLine.direction = MediaDirection.INACTIVE;
  1688. mLine.ssrcs = undefined;
  1689. mLine.ssrcGroups = undefined;
  1690. }
  1691. return new RTCSessionDescription({
  1692. type: description.type,
  1693. sdp: transform.write(parsedSdp)
  1694. });
  1695. };
  1696. /**
  1697. * Sets up the _dtlsTransport object and initializes callbacks for it.
  1698. */
  1699. TraceablePeerConnection.prototype._initializeDtlsTransport = function() {
  1700. // We are assuming here that we only have one bundled transport here
  1701. if (!this.peerconnection.getSenders || this._dtlsTransport) {
  1702. return;
  1703. }
  1704. const senders = this.peerconnection.getSenders();
  1705. if (senders.length !== 0 && senders[0].transport) {
  1706. this._dtlsTransport = senders[0].transport;
  1707. this._dtlsTransport.onerror = error => {
  1708. logger.error(`${this} DtlsTransport error: ${error}`);
  1709. };
  1710. this._dtlsTransport.onstatechange = () => {
  1711. this.trace('dtlsTransport.onstatechange', this._dtlsTransport.state);
  1712. };
  1713. }
  1714. };
  1715. /**
  1716. * Sets the max bitrates on the video m-lines when VP9/AV1 is the selected codec.
  1717. *
  1718. * @param {RTCSessionDescription} description - The local description that needs to be munged.
  1719. * @param {boolean} isLocalSdp - Whether the max bitrate (via b=AS line in SDP) is set on local SDP.
  1720. * @returns RTCSessionDescription
  1721. */
  1722. TraceablePeerConnection.prototype._setMaxBitrates = function(description, isLocalSdp = false) {
  1723. if (!this.codecSettings) {
  1724. return description;
  1725. }
  1726. const parsedSdp = transform.parse(description.sdp);
  1727. // Find all the m-lines associated with the local sources.
  1728. const direction = isLocalSdp ? MediaDirection.RECVONLY : MediaDirection.SENDONLY;
  1729. const mLines = parsedSdp.media.filter(m => m.type === MediaType.VIDEO && m.direction !== direction);
  1730. const currentCodec = this.codecSettings.codecList[0];
  1731. const codecScalabilityModeSettings = this.tpcUtils.codecSettings[currentCodec];
  1732. for (const mLine of mLines) {
  1733. const isDoingVp9KSvc = currentCodec === CodecMimeType.VP9
  1734. && !codecScalabilityModeSettings.scalabilityModeEnabled;
  1735. const localTrack = this.getLocalVideoTracks()
  1736. .find(track => this._localTrackTransceiverMids.get(track.rtcId) === mLine.mid.toString());
  1737. if ((isDoingVp9KSvc || this.tpcUtils._isRunningInFullSvcMode(currentCodec)) && localTrack) {
  1738. let maxBitrate;
  1739. if (localTrack.getVideoType() === VideoType.DESKTOP) {
  1740. maxBitrate = codecScalabilityModeSettings.maxBitratesVideo.ssHigh;
  1741. } else {
  1742. const { level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= localTrack.getCaptureResolution());
  1743. maxBitrate = codecScalabilityModeSettings.maxBitratesVideo[level];
  1744. }
  1745. const limit = Math.floor(maxBitrate / 1000);
  1746. // Use only the highest spatial layer bitrates for now as there is no API available yet for configuring
  1747. // the bitrates on the individual SVC layers.
  1748. mLine.bandwidth = [ {
  1749. type: 'AS',
  1750. limit
  1751. } ];
  1752. } else {
  1753. // Clear the bandwidth limit in SDP when VP9 is no longer the preferred codec.
  1754. // This is needed on react native clients as react-native-webrtc returns the
  1755. // SDP that the application passed instead of returning the SDP off the native side.
  1756. // This line automatically gets cleared on web on every renegotiation.
  1757. mLine.bandwidth = undefined;
  1758. }
  1759. }
  1760. return new RTCSessionDescription({
  1761. type: description.type,
  1762. sdp: transform.write(parsedSdp)
  1763. });
  1764. };
  1765. /**
  1766. * Configures the stream encodings for the audio tracks that are added to the peerconnection.
  1767. *
  1768. * @param {JitsiLocalTrack} localAudioTrack - The local audio track.
  1769. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1770. */
  1771. TraceablePeerConnection.prototype.configureAudioSenderEncodings = function(localAudioTrack = null) {
  1772. if (localAudioTrack) {
  1773. return this.tpcUtils.setEncodings(localAudioTrack);
  1774. }
  1775. const promises = [];
  1776. for (const track of this.getLocalTracks(MediaType.AUDIO)) {
  1777. promises.push(this.tpcUtils.setEncodings(track));
  1778. }
  1779. return Promise.allSettled(promises);
  1780. };
  1781. /**
  1782. * Configures the stream encodings depending on the video type, scalability mode and the bitrate settings for the codec
  1783. * that is currently selected.
  1784. *
  1785. * @param {JitsiLocalTrack} - The local track for which the sender encodings have to configured.
  1786. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1787. */
  1788. TraceablePeerConnection.prototype.configureVideoSenderEncodings = function(localVideoTrack = null) {
  1789. if (localVideoTrack) {
  1790. return this.setSenderVideoConstraints(
  1791. this._senderMaxHeights.get(localVideoTrack.getSourceName()),
  1792. localVideoTrack);
  1793. }
  1794. const promises = [];
  1795. for (const track of this.getLocalVideoTracks()) {
  1796. const maxHeight = this._senderMaxHeights.get(track.getSourceName()) ?? VIDEO_QUALITY_LEVELS[0].height;
  1797. promises.push(this.setSenderVideoConstraints(maxHeight, track));
  1798. }
  1799. return Promise.allSettled(promises);
  1800. };
  1801. TraceablePeerConnection.prototype.setLocalDescription = function(description) {
  1802. let localDescription = description;
  1803. this.trace('setLocalDescription::preTransform', dumpSDP(localDescription));
  1804. // Munge stereo flag and opusMaxAverageBitrate based on config.js
  1805. localDescription = this._mungeOpus(localDescription);
  1806. // Munge the order of the codecs based on the preferences set through config.js.
  1807. localDescription = this._mungeCodecOrder(localDescription);
  1808. localDescription = this._setMaxBitrates(localDescription, true);
  1809. localDescription = this._updateAv1DdHeaders(localDescription);
  1810. this.trace('setLocalDescription::postTransform', dumpSDP(localDescription));
  1811. return new Promise((resolve, reject) => {
  1812. this.peerconnection.setLocalDescription(localDescription)
  1813. .then(() => {
  1814. this.trace('setLocalDescriptionOnSuccess');
  1815. const localUfrag = SDPUtil.getUfrag(localDescription.sdp);
  1816. if (localUfrag !== this.localUfrag) {
  1817. this.localUfrag = localUfrag;
  1818. this.eventEmitter.emit(RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1819. }
  1820. this._initializeDtlsTransport();
  1821. resolve();
  1822. }, err => {
  1823. this.trace('setLocalDescriptionOnFailure', err);
  1824. this.eventEmitter.emit(RTCEvents.SET_LOCAL_DESCRIPTION_FAILED, err, this);
  1825. reject(err);
  1826. });
  1827. });
  1828. };
  1829. TraceablePeerConnection.prototype.setRemoteDescription = function(description) {
  1830. let remoteDescription = description;
  1831. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1832. // Munge stereo flag and opusMaxAverageBitrate based on config.js
  1833. remoteDescription = this._mungeOpus(remoteDescription);
  1834. if (!this.isP2P) {
  1835. const currentDescription = this.peerconnection.remoteDescription;
  1836. remoteDescription = this.interop.toUnifiedPlan(remoteDescription, currentDescription);
  1837. this.trace('setRemoteDescription::postTransform (Unified)', dumpSDP(remoteDescription));
  1838. }
  1839. if (this.isSpatialScalabilityOn()) {
  1840. remoteDescription = this.tpcUtils.insertUnifiedPlanSimulcastReceive(remoteDescription);
  1841. this.trace('setRemoteDescription::postTransform (sim receive)', dumpSDP(remoteDescription));
  1842. }
  1843. remoteDescription = this.tpcUtils.ensureCorrectOrderOfSsrcs(remoteDescription);
  1844. this.trace('setRemoteDescription::postTransform (correct ssrc order)', dumpSDP(remoteDescription));
  1845. // Munge the order of the codecs based on the preferences set through config.js.
  1846. remoteDescription = this._mungeCodecOrder(remoteDescription);
  1847. remoteDescription = this._setMaxBitrates(remoteDescription);
  1848. remoteDescription = this._updateAv1DdHeaders(remoteDescription);
  1849. this.trace('setRemoteDescription::postTransform (munge codec order)', dumpSDP(remoteDescription));
  1850. return new Promise((resolve, reject) => {
  1851. this.peerconnection.setRemoteDescription(remoteDescription)
  1852. .then(() => {
  1853. this.trace('setRemoteDescriptionOnSuccess');
  1854. const remoteUfrag = SDPUtil.getUfrag(remoteDescription.sdp);
  1855. if (remoteUfrag !== this.remoteUfrag) {
  1856. this.remoteUfrag = remoteUfrag;
  1857. this.eventEmitter.emit(RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1858. }
  1859. this._initializeDtlsTransport();
  1860. resolve();
  1861. }, err => {
  1862. this.trace('setRemoteDescriptionOnFailure', err);
  1863. this.eventEmitter.emit(RTCEvents.SET_REMOTE_DESCRIPTION_FAILED, err, this);
  1864. reject(err);
  1865. });
  1866. });
  1867. };
  1868. /**
  1869. * Changes the resolution of the video stream that is sent to the peer based on the resolution requested by the peer
  1870. * and user preference, sets the degradation preference on the sender based on the video type, configures the maximum
  1871. * bitrates on the send stream.
  1872. *
  1873. * @param {number} frameHeight - The max frame height to be imposed on the outgoing video stream.
  1874. * @param {JitsiLocalTrack} - The local track for which the sender constraints have to be applied.
  1875. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1876. */
  1877. TraceablePeerConnection.prototype.setSenderVideoConstraints = function(frameHeight, localVideoTrack) {
  1878. if (frameHeight < 0 || isNaN(frameHeight)) {
  1879. throw new Error(`Invalid frameHeight: ${frameHeight}`);
  1880. }
  1881. if (!localVideoTrack) {
  1882. throw new Error('Local video track is missing');
  1883. }
  1884. const sourceName = localVideoTrack.getSourceName();
  1885. // Ignore sender constraints if the video track is muted.
  1886. if (localVideoTrack.isMuted()) {
  1887. this._senderMaxHeights.set(sourceName, frameHeight);
  1888. return Promise.resolve();
  1889. }
  1890. return this._updateVideoSenderParameters(
  1891. () => this._updateVideoSenderEncodings(frameHeight, localVideoTrack));
  1892. };
  1893. /**
  1894. * Returns a wrapped-up promise so that the setParameters() call on the RTCRtpSender for video sources are chained.
  1895. * This is needed on Chrome as it resets the transaction id after executing setParameters() and can affect the next on
  1896. * the fly updates if they are not chained.
  1897. * https://chromium.googlesource.com/external/webrtc/+/master/pc/rtp_sender.cc#340
  1898. * @param {Function} nextFunction - The function to be called when the last video sender update promise is settled.
  1899. * @returns {Promise}
  1900. */
  1901. TraceablePeerConnection.prototype._updateVideoSenderParameters = function(nextFunction) {
  1902. const nextPromise = this._lastVideoSenderUpdatePromise
  1903. .finally(nextFunction);
  1904. this._lastVideoSenderUpdatePromise = nextPromise;
  1905. return nextPromise;
  1906. };
  1907. /**
  1908. * Configures the video stream with resolution / degradation / maximum bitrates
  1909. *
  1910. * @param {number} frameHeight - The max frame height to be imposed on the outgoing video stream.
  1911. * @param {JitsiLocalTrack} - The local track for which the sender constraints have to be applied.
  1912. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1913. */
  1914. TraceablePeerConnection.prototype._updateVideoSenderEncodings = function(frameHeight, localVideoTrack) {
  1915. const videoSender = this.findSenderForTrack(localVideoTrack.getTrack());
  1916. if (!videoSender) {
  1917. return Promise.resolve();
  1918. }
  1919. const parameters = videoSender.getParameters();
  1920. if (!parameters?.encodings?.length) {
  1921. return Promise.resolve();
  1922. }
  1923. const isSharingLowFpsScreen = localVideoTrack.getVideoType() === VideoType.DESKTOP && this._capScreenshareBitrate;
  1924. // Set the degradation preference.
  1925. const preference = isSharingLowFpsScreen
  1926. ? DEGRADATION_PREFERENCE_DESKTOP // Prefer resolution for low fps share.
  1927. : DEGRADATION_PREFERENCE_CAMERA; // Prefer frame-rate for high fps share and camera.
  1928. parameters.degradationPreference = preference;
  1929. // Calculate the encodings active state based on the resolution requested by the bridge.
  1930. const codec = this.getConfiguredVideoCodec();
  1931. const bitrates = this.tpcUtils.calculateEncodingsBitrates(localVideoTrack, codec, frameHeight);
  1932. const activeState = this.tpcUtils.calculateEncodingsActiveState(localVideoTrack, codec, frameHeight);
  1933. const scaleFactors = this.tpcUtils.calculateEncodingsScaleFactor(localVideoTrack, codec, frameHeight);
  1934. const scalabilityModes = this.tpcUtils.calculateEncodingsScalabilityMode(localVideoTrack, codec, frameHeight);
  1935. const sourceName = localVideoTrack.getSourceName();
  1936. let needsUpdate = false;
  1937. for (const idx in parameters.encodings) {
  1938. if (parameters.encodings.hasOwnProperty(idx)) {
  1939. const {
  1940. active = undefined,
  1941. maxBitrate = undefined,
  1942. scalabilityMode = undefined,
  1943. scaleResolutionDownBy = undefined
  1944. } = parameters.encodings[idx];
  1945. if (active !== activeState[idx]) {
  1946. parameters.encodings[idx].active = activeState[idx];
  1947. needsUpdate = true;
  1948. }
  1949. // Firefox doesn't follow the spec and lets application specify the degradation preference on the
  1950. // encodings.
  1951. browser.isFirefox() && (parameters.encodings[idx].degradationPreference = preference);
  1952. // Do not configure 'scaleResolutionDownBy' and 'maxBitrate' for encoders running in legacy K-SVC mode
  1953. // since the browser sends only the lowest resolution layer when those are configured.
  1954. if (codec !== CodecMimeType.VP9
  1955. || !this.isSpatialScalabilityOn()
  1956. || (browser.supportsScalabilityModeAPI()
  1957. && this.tpcUtils.codecSettings[codec].scalabilityModeEnabled)) {
  1958. if (scaleResolutionDownBy !== scaleFactors[idx]) {
  1959. parameters.encodings[idx].scaleResolutionDownBy = scaleFactors[idx];
  1960. needsUpdate = true;
  1961. }
  1962. if (maxBitrate !== bitrates[idx]) {
  1963. parameters.encodings[idx].maxBitrate = bitrates[idx];
  1964. needsUpdate = true;
  1965. }
  1966. }
  1967. // Configure scalability mode when its supported and enabled.
  1968. if (scalabilityModes) {
  1969. if (scalabilityMode !== scalabilityModes[idx]) {
  1970. parameters.encodings[idx].scalabilityMode = scalabilityModes[idx];
  1971. needsUpdate = true;
  1972. }
  1973. } else {
  1974. parameters.encodings[idx].scalabilityMode = undefined;
  1975. }
  1976. }
  1977. }
  1978. if (!needsUpdate) {
  1979. this._senderMaxHeights.set(sourceName, frameHeight);
  1980. return Promise.resolve();
  1981. }
  1982. logger.info(`${this} setting max height=${frameHeight},encodings=${JSON.stringify(parameters.encodings)}`);
  1983. return videoSender.setParameters(parameters).then(() => {
  1984. this._senderMaxHeights.set(sourceName, frameHeight);
  1985. localVideoTrack.maxEnabledResolution = frameHeight;
  1986. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_MAX_ENABLED_RESOLUTION_CHANGED, localVideoTrack);
  1987. });
  1988. };
  1989. /**
  1990. * Enables/disables outgoing video media transmission on this peer connection. When disabled the stream encoding's
  1991. * active state is enabled or disabled to send or stop the media.
  1992. * @param {boolean} active <tt>true</tt> to enable video media transmission or <tt>false</tt> to disable. If the value
  1993. * is not a boolean the call will have no effect.
  1994. * @return {Promise} A promise that is resolved when the change is succesful, rejected otherwise.
  1995. * @public
  1996. */
  1997. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  1998. logger.debug(`${this} video transfer active: ${active}`);
  1999. const changed = this.videoTransferActive !== active;
  2000. this.videoTransferActive = active;
  2001. if (changed) {
  2002. return this.tpcUtils.setMediaTransferActive(active, MediaType.VIDEO);
  2003. }
  2004. return Promise.resolve();
  2005. };
  2006. /**
  2007. * Sends DTMF tones if possible.
  2008. *
  2009. * @param {string} tones - The DTMF tones string as defined by {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  2010. * @param {number} duration - The amount of time in milliseconds that each DTMF should last. It's 200ms by default.
  2011. * @param {number} interToneGap - The length of time in miliseconds to wait between tones. It's 200ms by default.
  2012. *
  2013. * @returns {void}
  2014. */
  2015. TraceablePeerConnection.prototype.sendTones = function(tones, duration = 200, interToneGap = 200) {
  2016. if (!this._dtmfSender) {
  2017. if (this.peerconnection.getSenders) {
  2018. const rtpSender = this.peerconnection.getSenders().find(s => s.dtmf);
  2019. this._dtmfSender = rtpSender && rtpSender.dtmf;
  2020. this._dtmfSender && logger.info(`${this} initialized DTMFSender using getSenders`);
  2021. }
  2022. if (!this._dtmfSender) {
  2023. const localAudioTrack = Array.from(this.localTracks.values()).find(t => t.isAudioTrack());
  2024. if (this.peerconnection.createDTMFSender && localAudioTrack) {
  2025. this._dtmfSender = this.peerconnection.createDTMFSender(localAudioTrack.getTrack());
  2026. }
  2027. this._dtmfSender && logger.info(`${this} initialized DTMFSender using deprecated createDTMFSender`);
  2028. }
  2029. if (this._dtmfSender) {
  2030. this._dtmfSender.ontonechange = this._onToneChange.bind(this);
  2031. }
  2032. }
  2033. if (this._dtmfSender) {
  2034. if (this._dtmfSender.toneBuffer) {
  2035. this._dtmfTonesQueue.push({
  2036. tones,
  2037. duration,
  2038. interToneGap
  2039. });
  2040. return;
  2041. }
  2042. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2043. } else {
  2044. logger.warn(`${this} sendTones - failed to select DTMFSender`);
  2045. }
  2046. };
  2047. /**
  2048. * Callback ivoked by {@code this._dtmfSender} when it has finished playing
  2049. * a single tone.
  2050. *
  2051. * @param {Object} event - The tonechange event which indicates what characters
  2052. * are left to be played for the current tone.
  2053. * @private
  2054. * @returns {void}
  2055. */
  2056. TraceablePeerConnection.prototype._onToneChange = function(event) {
  2057. // An empty event.tone indicates the current tones have finished playing.
  2058. // Automatically start playing any queued tones on finish.
  2059. if (this._dtmfSender && event.tone === '' && this._dtmfTonesQueue.length) {
  2060. const { tones, duration, interToneGap } = this._dtmfTonesQueue.shift();
  2061. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2062. }
  2063. };
  2064. /**
  2065. * Closes underlying WebRTC PeerConnection instance and removes all remote
  2066. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  2067. * them.
  2068. */
  2069. TraceablePeerConnection.prototype.close = function() {
  2070. this.trace('stop');
  2071. // Off SignalingEvents
  2072. this.signalingLayer.off(SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  2073. this.signalingLayer.off(SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  2074. this.peerconnection.removeEventListener('track', this.onTrack);
  2075. if (FeatureFlags.isSsrcRewritingSupported()) {
  2076. for (const remoteTrack of this.remoteTracksBySsrc.values()) {
  2077. this._removeRemoteTrack(remoteTrack);
  2078. }
  2079. this.remoteTracksBySsrc.clear();
  2080. } else {
  2081. for (const peerTracks of this.remoteTracks.values()) {
  2082. for (const remoteTracks of peerTracks.values()) {
  2083. for (const remoteTrack of remoteTracks) {
  2084. this._removeRemoteTrack(remoteTrack);
  2085. }
  2086. }
  2087. }
  2088. this.remoteTracks.clear();
  2089. }
  2090. this._dtmfSender = null;
  2091. this._dtmfTonesQueue = [];
  2092. if (!this.rtc._removePeerConnection(this)) {
  2093. logger.error(`${this} rtc._removePeerConnection returned false`);
  2094. }
  2095. if (this.statsinterval !== null) {
  2096. window.clearInterval(this.statsinterval);
  2097. this.statsinterval = null;
  2098. }
  2099. logger.info(`${this} Closing peerconnection`);
  2100. this.peerconnection.close();
  2101. };
  2102. TraceablePeerConnection.prototype.createAnswer = function(constraints) {
  2103. return this._createOfferOrAnswer(false /* answer */, constraints);
  2104. };
  2105. TraceablePeerConnection.prototype.createOffer = function(constraints) {
  2106. return this._createOfferOrAnswer(true /* offer */, constraints);
  2107. };
  2108. TraceablePeerConnection.prototype._createOfferOrAnswer = function(
  2109. isOffer,
  2110. constraints) {
  2111. const logName = isOffer ? 'Offer' : 'Answer';
  2112. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  2113. const handleSuccess = (resultSdp, resolveFn, rejectFn) => {
  2114. try {
  2115. this.trace(
  2116. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  2117. // Munge local description to add 3 SSRCs for video tracks when spatial scalability is enabled.
  2118. if (this.isSpatialScalabilityOn() && browser.usesSdpMungingForSimulcast()) {
  2119. // eslint-disable-next-line no-param-reassign
  2120. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  2121. this.trace(`create${logName} OnSuccess::postTransform (simulcast)`, dumpSDP(resultSdp));
  2122. }
  2123. if (!this.options.disableRtx && browser.usesSdpMungingForSimulcast()) {
  2124. // eslint-disable-next-line no-param-reassign
  2125. resultSdp = new RTCSessionDescription({
  2126. type: resultSdp.type,
  2127. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  2128. });
  2129. this.trace(
  2130. `create${logName}`
  2131. + 'OnSuccess::postTransform (rtx modifier)',
  2132. dumpSDP(resultSdp));
  2133. }
  2134. const ssrcMap = this._extractSSRCMap(resultSdp);
  2135. this._processLocalSSRCsMap(ssrcMap);
  2136. resolveFn(resultSdp);
  2137. } catch (e) {
  2138. this.trace(`create${logName}OnError`, e);
  2139. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  2140. logger.error(`${this} create${logName}OnError`, e, dumpSDP(resultSdp));
  2141. rejectFn(e);
  2142. }
  2143. };
  2144. const handleFailure = (err, rejectFn) => {
  2145. this.trace(`create${logName}OnFailure`, err);
  2146. const eventType
  2147. = isOffer
  2148. ? RTCEvents.CREATE_OFFER_FAILED
  2149. : RTCEvents.CREATE_ANSWER_FAILED;
  2150. this.eventEmitter.emit(eventType, err, this);
  2151. rejectFn(err);
  2152. };
  2153. // Set the codec preference before creating an offer or answer so that the generated SDP will have
  2154. // the correct preference order.
  2155. if (browser.supportsCodecPreferences() && this.codecSettings) {
  2156. const { codecList, mediaType } = this.codecSettings;
  2157. const transceivers = this.peerconnection.getTransceivers()
  2158. .filter(t => t.receiver && t.receiver?.track?.kind === mediaType);
  2159. let capabilities = RTCRtpReceiver.getCapabilities(mediaType)?.codecs;
  2160. if (transceivers.length && capabilities) {
  2161. // Rearrange the codec list as per the preference order.
  2162. for (const codec of codecList.slice().reverse()) {
  2163. // Move the desired codecs (all variations of it as well) to the beginning of the list
  2164. /* eslint-disable-next-line arrow-body-style */
  2165. capabilities.sort(caps => {
  2166. return caps.mimeType.toLowerCase() === `${mediaType}/${codec}` ? -1 : 1;
  2167. });
  2168. }
  2169. // Disable ulpfec and RED on the p2p peerconnection.
  2170. if (this.isP2P && mediaType === MediaType.VIDEO) {
  2171. capabilities = capabilities
  2172. .filter(caps => caps.mimeType.toLowerCase() !== `${MediaType.VIDEO}/${CodecMimeType.ULPFEC}`
  2173. && caps.mimeType.toLowerCase() !== `${MediaType.VIDEO}/${CodecMimeType.RED}`);
  2174. }
  2175. // Apply codec preference to all the transceivers associated with the given media type.
  2176. for (const transceiver of transceivers) {
  2177. transceiver.setCodecPreferences(capabilities);
  2178. }
  2179. }
  2180. }
  2181. return new Promise((resolve, reject) => {
  2182. let oaPromise;
  2183. if (isOffer) {
  2184. oaPromise = this.peerconnection.createOffer(constraints);
  2185. } else {
  2186. oaPromise = this.peerconnection.createAnswer(constraints);
  2187. }
  2188. oaPromise
  2189. .then(
  2190. sdp => handleSuccess(sdp, resolve, reject),
  2191. error => handleFailure(error, reject));
  2192. });
  2193. };
  2194. /**
  2195. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  2196. * @param {TrackSSRCInfo} ssrcObj
  2197. * @return {number|null} the primary SSRC or <tt>null</tt>
  2198. */
  2199. TraceablePeerConnection.prototype._extractPrimarySSRC = function(ssrcObj) {
  2200. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  2201. return ssrcObj.groups[0].ssrcs[0];
  2202. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  2203. return ssrcObj.ssrcs[0];
  2204. }
  2205. return null;
  2206. };
  2207. /**
  2208. * Goes over the SSRC map extracted from the latest local description and tries
  2209. * to match them with the local tracks (by MSID). Will update the values
  2210. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  2211. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  2212. * @private
  2213. */
  2214. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  2215. for (const track of this.localTracks.values()) {
  2216. const sourceName = track.getSourceName();
  2217. const sourceIndex = getSourceIndexFromSourceName(sourceName);
  2218. const sourceIdentifier = `${track.getType()}-${sourceIndex}`;
  2219. if (ssrcMap.has(sourceIdentifier)) {
  2220. const newSSRC = ssrcMap.get(sourceIdentifier);
  2221. if (!newSSRC) {
  2222. logger.error(`${this} No SSRC found for stream=${sourceIdentifier}`);
  2223. return;
  2224. }
  2225. const oldSSRC = this.localSSRCs.get(track.rtcId);
  2226. const newSSRCNum = this._extractPrimarySSRC(newSSRC);
  2227. const oldSSRCNum = this._extractPrimarySSRC(oldSSRC);
  2228. // eslint-disable-next-line no-negated-condition
  2229. if (newSSRCNum !== oldSSRCNum) {
  2230. oldSSRCNum && logger.error(`${this} Overwriting SSRC for track=${track}] with ssrc=${newSSRC}`);
  2231. this.localSSRCs.set(track.rtcId, newSSRC);
  2232. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_SSRC_UPDATED, track, newSSRCNum);
  2233. }
  2234. } else if (!track.isVideoTrack() && !track.isMuted()) {
  2235. // It is normal to find no SSRCs for a muted video track in
  2236. // the local SDP as the recv-only SSRC is no longer munged in.
  2237. // So log the warning only if it's not a muted video track.
  2238. logger.warn(`${this} No SSRCs found in the local SDP for track=${track}, stream=${sourceIdentifier}`);
  2239. }
  2240. }
  2241. };
  2242. /**
  2243. * Track the SSRCs seen so far.
  2244. * @param {number} ssrc - SSRC.
  2245. * @return {boolean} - Whether this is a new SSRC.
  2246. */
  2247. TraceablePeerConnection.prototype.addRemoteSsrc = function(ssrc) {
  2248. const existing = this.remoteSSRCs.has(ssrc);
  2249. if (!existing) {
  2250. this.remoteSSRCs.add(ssrc);
  2251. }
  2252. return !existing;
  2253. };
  2254. TraceablePeerConnection.prototype.addIceCandidate = function(candidate) {
  2255. this.trace('addIceCandidate', JSON.stringify({
  2256. candidate: candidate.candidate,
  2257. sdpMid: candidate.sdpMid,
  2258. sdpMLineIndex: candidate.sdpMLineIndex,
  2259. usernameFragment: candidate.usernameFragment
  2260. }, null, ' '));
  2261. return this.peerconnection.addIceCandidate(candidate);
  2262. };
  2263. /**
  2264. * Obtains call-related stats from the peer connection.
  2265. *
  2266. * @returns {Promise<Object>} Promise which resolves with data providing statistics about
  2267. * the peerconnection.
  2268. */
  2269. TraceablePeerConnection.prototype.getStats = function() {
  2270. return this.peerconnection.getStats();
  2271. };
  2272. /**
  2273. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2274. * instance.
  2275. * @return {string}
  2276. */
  2277. TraceablePeerConnection.prototype.toString = function() {
  2278. return `TPC[id=${this.id},type=${this.isP2P ? 'P2P' : 'JVB'}]`;
  2279. };