modified lib-jitsi-meet dev repo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TraceablePeerConnection.js 106KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001
  1. /* global __filename, RTCSessionDescription */
  2. import { Interop } from '@jitsi/sdp-interop';
  3. import { getLogger } from 'jitsi-meet-logger';
  4. import transform from 'sdp-transform';
  5. import * as CodecMimeType from '../../service/RTC/CodecMimeType';
  6. import * as MediaType from '../../service/RTC/MediaType';
  7. import RTCEvents from '../../service/RTC/RTCEvents';
  8. import * as SignalingEvents from '../../service/RTC/SignalingEvents';
  9. import * as VideoType from '../../service/RTC/VideoType';
  10. import browser from '../browser';
  11. import LocalSdpMunger from '../sdp/LocalSdpMunger';
  12. import RtxModifier from '../sdp/RtxModifier';
  13. import SDP from '../sdp/SDP';
  14. import SDPUtil from '../sdp/SDPUtil';
  15. import SdpConsistency from '../sdp/SdpConsistency';
  16. import { SdpTransformWrap } from '../sdp/SdpTransformUtil';
  17. import * as GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  18. import JitsiRemoteTrack from './JitsiRemoteTrack';
  19. import RTC from './RTC';
  20. import RTCUtils from './RTCUtils';
  21. import { SIM_LAYER_RIDS, TPCUtils } from './TPCUtils';
  22. // FIXME SDP tools should end up in some kind of util module
  23. const logger = getLogger(__filename);
  24. const DEGRADATION_PREFERENCE_CAMERA = 'maintain-framerate';
  25. const DEGRADATION_PREFERENCE_DESKTOP = 'maintain-resolution';
  26. const DESKTOP_SHARE_RATE = 500000;
  27. const HD_BITRATE = 2500000;
  28. const LD_BITRATE = 200000;
  29. const SD_BITRATE = 700000;
  30. /* eslint-disable max-params */
  31. /**
  32. * Creates new instance of 'TraceablePeerConnection'.
  33. *
  34. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  35. * @param {number} id the peer connection id assigned by the parent RTC module.
  36. * @param {SignalingLayer} signalingLayer the signaling layer instance
  37. * @param {object} iceConfig WebRTC 'PeerConnection' ICE config
  38. * @param {object} constraints WebRTC 'PeerConnection' constraints
  39. * @param {boolean} isP2P indicates whether or not the new instance will be used in a peer to peer connection.
  40. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  41. * @param {boolean} options.disableSimulcast if set to 'true' will disable the simulcast.
  42. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX.
  43. * @param {string} options.disabledCodec the mime type of the code that should not be negotiated on the peerconnection.
  44. * @param {string} options.preferredCodec the mime type of the codec that needs to be made the preferred codec for the
  45. * peerconnection.
  46. * @param {boolean} options.startSilent If set to 'true' no audio will be sent or received.
  47. * @param {boolean} options.usesUnifiedPlan Indicates if the browser is running in unified plan mode.
  48. *
  49. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  50. * debug the peer connection. Since many other responsibilities have been added
  51. * it would make sense to extract a separate class from it and come up with
  52. * a more suitable name.
  53. *
  54. * @constructor
  55. */
  56. export default function TraceablePeerConnection(
  57. rtc,
  58. id,
  59. signalingLayer,
  60. iceConfig,
  61. constraints,
  62. isP2P,
  63. options) {
  64. /**
  65. * Indicates whether or not this peer connection instance is actively
  66. * sending/receiving audio media. When set to <tt>false</tt> the SDP audio
  67. * media direction will be adjusted to 'inactive' in order to suspend
  68. * the transmission.
  69. * @type {boolean}
  70. * @private
  71. */
  72. this.audioTransferActive = !(options.startSilent === true);
  73. /**
  74. * The DTMF sender instance used to send DTMF tones.
  75. *
  76. * @type {RTCDTMFSender|undefined}
  77. * @private
  78. */
  79. this._dtmfSender = undefined;
  80. /**
  81. * @typedef {Object} TouchToneRequest
  82. * @property {string} tones - The DTMF tones string as defined by
  83. * {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  84. * @property {number} duration - The amount of time in milliseconds that
  85. * each DTMF should last.
  86. * @property {string} interToneGap - The length of time in miliseconds to
  87. * wait between tones.
  88. */
  89. /**
  90. * TouchToneRequests which are waiting to be played. This queue is filled
  91. * if there are touch tones currently being played.
  92. *
  93. * @type {Array<TouchToneRequest>}
  94. * @private
  95. */
  96. this._dtmfTonesQueue = [];
  97. /**
  98. * Indicates whether or not this peer connection instance is actively
  99. * sending/receiving video media. When set to <tt>false</tt> the SDP video
  100. * media direction will be adjusted to 'inactive' in order to suspend
  101. * the transmission.
  102. * @type {boolean}
  103. * @private
  104. */
  105. this.videoTransferActive = true;
  106. /**
  107. * The parent instance of RTC service which created this
  108. * <tt>TracablePeerConnection</tt>.
  109. * @type {RTC}
  110. */
  111. this.rtc = rtc;
  112. /**
  113. * The peer connection identifier assigned by the RTC module.
  114. * @type {number}
  115. */
  116. this.id = id;
  117. /**
  118. * Indicates whether or not this instance is used in a peer to peer
  119. * connection.
  120. * @type {boolean}
  121. */
  122. this.isP2P = isP2P;
  123. // FIXME: We should support multiple streams per jid.
  124. /**
  125. * The map holds remote tracks associated with this peer connection.
  126. * It maps user's JID to media type and remote track
  127. * (one track per media type per user's JID).
  128. * @type {Map<string, Map<MediaType, JitsiRemoteTrack>>}
  129. */
  130. this.remoteTracks = new Map();
  131. /**
  132. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  133. * @type {Map<number, JitsiLocalTrack>}
  134. */
  135. this.localTracks = new Map();
  136. /**
  137. * Keeps tracks of the WebRTC <tt>MediaStream</tt>s that have been added to
  138. * the underlying WebRTC PeerConnection.
  139. * @type {Array}
  140. * @private
  141. */
  142. this._addedStreams = [];
  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 local ICE username fragment for this session.
  164. */
  165. this.localUfrag = null;
  166. /**
  167. * The remote ICE username fragment for this session.
  168. */
  169. this.remoteUfrag = null;
  170. /**
  171. * The signaling layer which operates this peer connection.
  172. * @type {SignalingLayer}
  173. */
  174. this.signalingLayer = signalingLayer;
  175. // SignalingLayer listeners
  176. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  177. this.signalingLayer.on(
  178. SignalingEvents.PEER_VIDEO_TYPE_CHANGED,
  179. this._peerVideoTypeChanged);
  180. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  181. this.signalingLayer.on(
  182. SignalingEvents.PEER_MUTED_CHANGED,
  183. this._peerMutedChanged);
  184. this.options = options;
  185. // Make sure constraints is properly formatted in order to provide information about whether or not this
  186. // connection is P2P to rtcstats.
  187. const safeConstraints = constraints || {};
  188. safeConstraints.optional = safeConstraints.optional || [];
  189. // The `optional` parameter needs to be of type array, otherwise chrome will throw an error.
  190. // Firefox and Safari just ignore it.
  191. if (Array.isArray(safeConstraints.optional)) {
  192. safeConstraints.optional.push({ rtcStatsSFUP2P: this.isP2P });
  193. } else {
  194. logger.warn('Optional param is not an array, rtcstats p2p data is omitted.');
  195. }
  196. this.peerconnection
  197. = new RTCUtils.RTCPeerConnectionType(iceConfig, safeConstraints);
  198. // The standard video bitrates are used in Unified plan when switching
  199. // between camera/desktop tracks on the same sender.
  200. const standardVideoBitrates = {
  201. low: LD_BITRATE,
  202. standard: SD_BITRATE,
  203. high: HD_BITRATE
  204. };
  205. // Check if the max. bitrates for video are specified through config.js videoQuality settings.
  206. // These bitrates will be applied on all browsers for camera sources in both simulcast and p2p mode.
  207. this.videoBitrates = this.options.videoQuality && this.options.videoQuality.maxBitratesVideo
  208. ? this.options.videoQuality.maxBitratesVideo
  209. : standardVideoBitrates;
  210. this.tpcUtils = new TPCUtils(this, this.videoBitrates);
  211. this.updateLog = [];
  212. this.stats = {};
  213. this.statsinterval = null;
  214. /**
  215. * Flag used to indicate if the browser is running in unified plan mode.
  216. */
  217. this._usesUnifiedPlan = options.usesUnifiedPlan;
  218. /**
  219. * Flag used to indicate if RTCRtpTransceiver#setCodecPreferences is to be used instead of SDP
  220. * munging for codec selection.
  221. */
  222. this._usesTransceiverCodecPreferences = browser.supportsCodecPreferences() && this._usesUnifiedPlan;
  223. this._usesTransceiverCodecPreferences
  224. && logger.info('Using RTCRtpTransceiver#setCodecPreferences for codec selection');
  225. /**
  226. * @type {number} The max number of stats to keep in this.stats. Limit to
  227. * 300 values, i.e. 5 minutes; set to 0 to disable
  228. */
  229. this.maxstats = options.maxstats;
  230. this.interop = new Interop();
  231. const Simulcast = require('@jitsi/sdp-simulcast');
  232. this.simulcast = new Simulcast(
  233. {
  234. numOfLayers: SIM_LAYER_RIDS.length,
  235. explodeRemoteSimulcast: false,
  236. usesUnifiedPlan: this._usesUnifiedPlan
  237. });
  238. this.sdpConsistency = new SdpConsistency(this.toString());
  239. /**
  240. * Munges local SDP provided to the Jingle Session in order to prevent from
  241. * sending SSRC updates on attach/detach and mute/unmute (for video).
  242. * @type {LocalSdpMunger}
  243. */
  244. this.localSdpMunger = new LocalSdpMunger(this, this.rtc.getLocalEndpointId());
  245. /**
  246. * TracablePeerConnection uses RTC's eventEmitter
  247. * @type {EventEmitter}
  248. */
  249. this.eventEmitter = rtc.eventEmitter;
  250. this.rtxModifier = new RtxModifier();
  251. /**
  252. * The height constraint applied on the video sender.
  253. */
  254. this.senderVideoMaxHeight = null;
  255. // override as desired
  256. this.trace = (what, info) => {
  257. logger.debug(what, info);
  258. this.updateLog.push({
  259. time: new Date(),
  260. type: what,
  261. value: info || ''
  262. });
  263. };
  264. this.onicecandidate = null;
  265. this.peerconnection.onicecandidate = event => {
  266. this.trace(
  267. 'onicecandidate',
  268. JSON.stringify(event.candidate, null, ' '));
  269. if (this.onicecandidate !== null) {
  270. this.onicecandidate(event);
  271. }
  272. };
  273. // Use track events when browser is running in unified plan mode and stream events in plan-b mode.
  274. if (this._usesUnifiedPlan) {
  275. this.onTrack = evt => {
  276. const stream = evt.streams[0];
  277. this._remoteTrackAdded(stream, evt.track, evt.transceiver);
  278. stream.addEventListener('removetrack', e => {
  279. this._remoteTrackRemoved(stream, e.track);
  280. });
  281. };
  282. this.peerconnection.addEventListener('track', this.onTrack);
  283. } else {
  284. this.peerconnection.onaddstream = event => this._remoteStreamAdded(event.stream);
  285. this.peerconnection.onremovestream = event => this._remoteStreamRemoved(event.stream);
  286. }
  287. this.onsignalingstatechange = null;
  288. this.peerconnection.onsignalingstatechange = event => {
  289. this.trace('onsignalingstatechange', this.signalingState);
  290. if (this.onsignalingstatechange !== null) {
  291. this.onsignalingstatechange(event);
  292. }
  293. };
  294. this.oniceconnectionstatechange = null;
  295. this.peerconnection.oniceconnectionstatechange = event => {
  296. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  297. if (this.oniceconnectionstatechange !== null) {
  298. this.oniceconnectionstatechange(event);
  299. }
  300. };
  301. this.onnegotiationneeded = null;
  302. this.peerconnection.onnegotiationneeded = event => {
  303. this.trace('onnegotiationneeded');
  304. if (this.onnegotiationneeded !== null) {
  305. this.onnegotiationneeded(event);
  306. }
  307. };
  308. this.ondatachannel = null;
  309. this.peerconnection.ondatachannel = event => {
  310. this.trace('ondatachannel');
  311. if (this.ondatachannel !== null) {
  312. this.ondatachannel(event);
  313. }
  314. };
  315. if (this.maxstats) {
  316. this.statsinterval = window.setInterval(() => {
  317. this.getStats().then(stats => {
  318. if (typeof stats?.result === 'function') {
  319. const results = stats.result();
  320. for (let i = 0; i < results.length; ++i) {
  321. const res = results[i];
  322. res.names().forEach(name => {
  323. this._processStat(res, name, res.stat(name));
  324. });
  325. }
  326. } else {
  327. stats.forEach(r => this._processStat(r, '', r));
  328. }
  329. });
  330. }, 1000);
  331. }
  332. logger.info(`Create new ${this}`);
  333. }
  334. /* eslint-enable max-params */
  335. /**
  336. * Process stat and adds it to the array of stats we store.
  337. * @param report the current stats report.
  338. * @param name the name of the report, if available
  339. * @param statValue the value to add.
  340. * @private
  341. */
  342. TraceablePeerConnection.prototype._processStat
  343. = function(report, name, statValue) {
  344. const id = `${report.id}-${name}`;
  345. let s = this.stats[id];
  346. const now = new Date();
  347. if (!s) {
  348. this.stats[id] = s = {
  349. startTime: now,
  350. endTime: now,
  351. values: [],
  352. times: []
  353. };
  354. }
  355. s.values.push(statValue);
  356. s.times.push(now.getTime());
  357. if (s.values.length > this.maxstats) {
  358. s.values.shift();
  359. s.times.shift();
  360. }
  361. s.endTime = now;
  362. };
  363. /**
  364. * Returns a string representation of a SessionDescription object.
  365. */
  366. const dumpSDP = function(description) {
  367. if (typeof description === 'undefined' || description === null) {
  368. return '';
  369. }
  370. return `type: ${description.type}\r\n${description.sdp}`;
  371. };
  372. /**
  373. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  374. * will convert "completed" into "connected" where both mean that the ICE has
  375. * succeeded and is up and running. We never see "completed" state for
  376. * the JVB connection, but it started appearing for the P2P one. This method
  377. * allows to adapt old logic to this new situation.
  378. * @return {string}
  379. */
  380. TraceablePeerConnection.prototype.getConnectionState = function() {
  381. const state = this.peerconnection.iceConnectionState;
  382. if (state === 'completed') {
  383. return 'connected';
  384. }
  385. return state;
  386. };
  387. /**
  388. * Obtains the media direction for given {@link MediaType}. The method takes
  389. * into account whether or not there are any local tracks for media and
  390. * the {@link audioTransferActive} and {@link videoTransferActive} flags.
  391. * @param {MediaType} mediaType
  392. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly'
  393. * etc.) which should be used when setting local description on the peer
  394. * connection.
  395. * @private
  396. */
  397. TraceablePeerConnection.prototype._getDesiredMediaDirection = function(
  398. mediaType) {
  399. let mediaTransferActive = true;
  400. if (mediaType === MediaType.AUDIO) {
  401. mediaTransferActive = this.audioTransferActive;
  402. } else if (mediaType === MediaType.VIDEO) {
  403. mediaTransferActive = this.videoTransferActive;
  404. }
  405. if (mediaTransferActive) {
  406. return this.hasAnyTracksOfType(mediaType) ? 'sendrecv' : 'recvonly';
  407. }
  408. return 'inactive';
  409. };
  410. /**
  411. * Returns the list of RTCRtpReceivers created for the source of the given media type associated with
  412. * the set of remote endpoints specified.
  413. * @param {Array<string>} endpoints list of the endpoints
  414. * @param {string} mediaType 'audio' or 'video'
  415. * @returns {Array<RTCRtpReceiver>} list of receivers created by the peerconnection.
  416. */
  417. TraceablePeerConnection.prototype._getReceiversByEndpointIds = function(endpoints, mediaType) {
  418. let remoteTracks = [];
  419. let receivers = [];
  420. for (const endpoint of endpoints) {
  421. remoteTracks = remoteTracks.concat(this.getRemoteTracks(endpoint, mediaType));
  422. }
  423. // Get the ids of the MediaStreamTracks associated with each of these remote tracks.
  424. const remoteTrackIds = remoteTracks.map(remote => remote.track?.id);
  425. receivers = this.peerconnection.getReceivers()
  426. .filter(receiver => receiver.track
  427. && receiver.track.kind === mediaType
  428. && remoteTrackIds.find(trackId => trackId === receiver.track.id));
  429. return receivers;
  430. };
  431. /**
  432. * Tells whether or not this TPC instance is using Simulcast.
  433. * @return {boolean} <tt>true</tt> if simulcast is enabled and active or
  434. * <tt>false</tt> if it's turned off.
  435. */
  436. TraceablePeerConnection.prototype.isSimulcastOn = function() {
  437. return !this.options.disableSimulcast;
  438. };
  439. /**
  440. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  441. * @param {string} endpointId the video owner's ID (MUC nickname)
  442. * @param {VideoType} videoType the new value
  443. * @private
  444. */
  445. TraceablePeerConnection.prototype._peerVideoTypeChanged = function(
  446. endpointId,
  447. videoType) {
  448. // Check if endpointId has a value to avoid action on random track
  449. if (!endpointId) {
  450. logger.error(`${this} No endpointID on peerVideoTypeChanged`);
  451. return;
  452. }
  453. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  454. if (videoTrack.length) {
  455. // NOTE 1 track per media type is assumed
  456. videoTrack[0]._setVideoType(videoType);
  457. }
  458. };
  459. /**
  460. * Handles remote track mute / unmute events.
  461. * @param {string} endpointId the track owner's identifier (MUC nickname)
  462. * @param {MediaType} mediaType "audio" or "video"
  463. * @param {boolean} isMuted the new mute state
  464. * @private
  465. */
  466. TraceablePeerConnection.prototype._peerMutedChanged = function(
  467. endpointId,
  468. mediaType,
  469. isMuted) {
  470. // Check if endpointId is a value to avoid doing action on all remote tracks
  471. if (!endpointId) {
  472. logger.error(`${this} On peerMuteChanged - no endpoint ID`);
  473. return;
  474. }
  475. const track = this.getRemoteTracks(endpointId, mediaType);
  476. if (track.length) {
  477. // NOTE 1 track per media type is assumed
  478. track[0].setMute(isMuted);
  479. }
  480. };
  481. /**
  482. * Obtains audio levels of the remote audio tracks by getting the source information on the RTCRtpReceivers.
  483. * The information relevant to the ssrc is updated each time a RTP packet constaining the ssrc is received.
  484. * @param {Array<string>} speakerList list of endpoint ids for which audio levels are to be gathered.
  485. * @returns {Object} containing ssrc and audio level information as a key-value pair.
  486. */
  487. TraceablePeerConnection.prototype.getAudioLevels = function(speakerList = []) {
  488. const audioLevels = {};
  489. const audioReceivers = speakerList.length
  490. ? this._getReceiversByEndpointIds(speakerList, MediaType.AUDIO)
  491. : this.peerconnection.getReceivers()
  492. .filter(receiver => receiver.track && receiver.track.kind === MediaType.AUDIO && receiver.track.enabled);
  493. audioReceivers.forEach(remote => {
  494. const ssrc = remote.getSynchronizationSources();
  495. if (ssrc && ssrc.length) {
  496. // As per spec, this audiolevel is a value between 0..1 (linear), where 1.0
  497. // represents 0 dBov, 0 represents silence, and 0.5 represents approximately
  498. // 6 dBSPL change in the sound pressure level from 0 dBov.
  499. // https://www.w3.org/TR/webrtc/#dom-rtcrtpcontributingsource-audiolevel
  500. audioLevels[ssrc[0].source] = ssrc[0].audioLevel;
  501. }
  502. });
  503. return audioLevels;
  504. };
  505. /**
  506. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  507. * argument is omitted the list of all local tracks will be returned.
  508. * @param {MediaType} [mediaType]
  509. * @return {Array<JitsiLocalTrack>}
  510. */
  511. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  512. let tracks = Array.from(this.localTracks.values());
  513. if (mediaType !== undefined) {
  514. tracks = tracks.filter(track => track.getType() === mediaType);
  515. }
  516. return tracks;
  517. };
  518. /**
  519. * Retrieves the local video track.
  520. *
  521. * @returns {JitsiLocalTrack|undefined} - local video track.
  522. */
  523. TraceablePeerConnection.prototype.getLocalVideoTrack = function() {
  524. return this.getLocalTracks(MediaType.VIDEO)[0];
  525. };
  526. /**
  527. * Checks whether or not this {@link TraceablePeerConnection} instance contains
  528. * any local tracks for given <tt>mediaType</tt>.
  529. * @param {MediaType} mediaType
  530. * @return {boolean}
  531. */
  532. TraceablePeerConnection.prototype.hasAnyTracksOfType = function(mediaType) {
  533. if (!mediaType) {
  534. throw new Error('"mediaType" is required');
  535. }
  536. return this.getLocalTracks(mediaType).length > 0;
  537. };
  538. /**
  539. * Obtains all remote tracks currently known to this PeerConnection instance.
  540. * @param {string} [endpointId] the track owner's identifier (MUC nickname)
  541. * @param {MediaType} [mediaType] the remote tracks will be filtered
  542. * by their media type if this argument is specified.
  543. * @return {Array<JitsiRemoteTrack>}
  544. */
  545. TraceablePeerConnection.prototype.getRemoteTracks = function(
  546. endpointId,
  547. mediaType) {
  548. const remoteTracks = [];
  549. const endpoints
  550. = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  551. for (const endpoint of endpoints) {
  552. const endpointTrackMap = this.remoteTracks.get(endpoint);
  553. if (!endpointTrackMap) {
  554. // Otherwise an empty Map() would have to be allocated above
  555. // eslint-disable-next-line no-continue
  556. continue;
  557. }
  558. for (const trackMediaType of endpointTrackMap.keys()) {
  559. // per media type filtering
  560. if (!mediaType || mediaType === trackMediaType) {
  561. const mediaTrack = endpointTrackMap.get(trackMediaType);
  562. if (mediaTrack) {
  563. remoteTracks.push(mediaTrack);
  564. }
  565. }
  566. }
  567. }
  568. return remoteTracks;
  569. };
  570. /**
  571. * Parses the remote description and returns the sdp lines of the sources associated with a remote participant.
  572. *
  573. * @param {string} id Endpoint id of the remote participant.
  574. * @returns {Array<string>} The sdp lines that have the ssrc information.
  575. */
  576. TraceablePeerConnection.prototype.getRemoteSourceInfoByParticipant = function(id) {
  577. const removeSsrcInfo = [];
  578. const remoteTracks = this.getRemoteTracks(id);
  579. if (!remoteTracks?.length) {
  580. return removeSsrcInfo;
  581. }
  582. const primarySsrcs = remoteTracks.map(track => track.getSSRC());
  583. const sdp = new SDP(this.remoteDescription.sdp);
  584. primarySsrcs.forEach((ssrc, idx) => {
  585. for (const media of sdp.media) {
  586. let lines = '';
  587. let ssrcLines = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  588. if (ssrcLines.length) {
  589. if (!removeSsrcInfo[idx]) {
  590. removeSsrcInfo[idx] = '';
  591. }
  592. // Check if there are any FID groups present for the primary ssrc.
  593. const fidLines = SDPUtil.findLines(media, `a=ssrc-group:FID ${ssrc}`);
  594. if (fidLines.length) {
  595. const secondarySsrc = fidLines[0].split(' ')[2];
  596. lines += `${fidLines[0]}\r\n`;
  597. ssrcLines = ssrcLines.concat(SDPUtil.findLines(media, `a=ssrc:${secondarySsrc}`));
  598. }
  599. removeSsrcInfo[idx] += `${ssrcLines.join('\r\n')}\r\n`;
  600. removeSsrcInfo[idx] += lines;
  601. }
  602. }
  603. });
  604. return removeSsrcInfo;
  605. };
  606. /**
  607. * Returns the target bitrates configured for the local video source.
  608. *
  609. * @returns {Object}
  610. */
  611. TraceablePeerConnection.prototype.getTargetVideoBitrates = function() {
  612. const currentCodec = this.getConfiguredVideoCodec();
  613. return this.videoBitrates[currentCodec.toUpperCase()] || this.videoBitrates;
  614. };
  615. /**
  616. * Tries to find {@link JitsiTrack} for given SSRC number. It will search both
  617. * local and remote tracks bound to this instance.
  618. * @param {number} ssrc
  619. * @return {JitsiTrack|null}
  620. */
  621. TraceablePeerConnection.prototype.getTrackBySSRC = function(ssrc) {
  622. if (typeof ssrc !== 'number') {
  623. throw new Error(`SSRC ${ssrc} is not a number`);
  624. }
  625. for (const localTrack of this.localTracks.values()) {
  626. if (this.getLocalSSRC(localTrack) === ssrc) {
  627. return localTrack;
  628. }
  629. }
  630. for (const remoteTrack of this.getRemoteTracks()) {
  631. if (remoteTrack.getSSRC() === ssrc) {
  632. return remoteTrack;
  633. }
  634. }
  635. return null;
  636. };
  637. /**
  638. * Tries to find SSRC number for given {@link JitsiTrack} id. It will search
  639. * both local and remote tracks bound to this instance.
  640. * @param {string} id
  641. * @return {number|null}
  642. */
  643. TraceablePeerConnection.prototype.getSsrcByTrackId = function(id) {
  644. const findTrackById = track => track.getTrack().id === id;
  645. const localTrack = this.getLocalTracks().find(findTrackById);
  646. if (localTrack) {
  647. return this.getLocalSSRC(localTrack);
  648. }
  649. const remoteTrack = this.getRemoteTracks().find(findTrackById);
  650. if (remoteTrack) {
  651. return remoteTrack.getSSRC();
  652. }
  653. return null;
  654. };
  655. /**
  656. * Called when new remote MediaStream is added to the PeerConnection.
  657. * @param {MediaStream} stream the WebRTC MediaStream for remote participant
  658. */
  659. TraceablePeerConnection.prototype._remoteStreamAdded = function(stream) {
  660. const streamId = RTC.getStreamID(stream);
  661. if (!RTC.isUserStreamById(streamId)) {
  662. logger.info(`${this} ignored remote 'stream added' event for non-user stream[id=${streamId}]`);
  663. return;
  664. }
  665. // Bind 'addtrack'/'removetrack' event handlers
  666. if (browser.isChromiumBased()) {
  667. stream.onaddtrack = event => {
  668. this._remoteTrackAdded(stream, event.track);
  669. };
  670. stream.onremovetrack = event => {
  671. this._remoteTrackRemoved(stream, event.track);
  672. };
  673. }
  674. // Call remoteTrackAdded for each track in the stream
  675. const streamAudioTracks = stream.getAudioTracks();
  676. for (const audioTrack of streamAudioTracks) {
  677. this._remoteTrackAdded(stream, audioTrack);
  678. }
  679. const streamVideoTracks = stream.getVideoTracks();
  680. for (const videoTrack of streamVideoTracks) {
  681. this._remoteTrackAdded(stream, videoTrack);
  682. }
  683. };
  684. /**
  685. * Called on "track added" and "stream added" PeerConnection events (because we
  686. * handle streams on per track basis). Finds the owner and the SSRC for
  687. * the track and passes that to ChatRoom for further processing.
  688. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  689. * the parent of the track
  690. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  691. * participant.
  692. * @param {RTCRtpTransceiver} transceiver the WebRTC transceiver that is created
  693. * for the remote participant in unified plan.
  694. */
  695. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track, transceiver = null) {
  696. const streamId = RTC.getStreamID(stream);
  697. const mediaType = track.kind;
  698. if (!this.isP2P && !RTC.isUserStreamById(streamId)) {
  699. logger.info(`${this} ignored remote 'stream added' event for non-user stream[id=${streamId}]`);
  700. return;
  701. }
  702. logger.info(`${this} adding remote track for stream[id=${streamId},type=${mediaType}]`);
  703. // look up an associated JID for a stream id
  704. if (!mediaType) {
  705. GlobalOnErrorHandler.callErrorHandler(
  706. new Error(
  707. `MediaType undefined for remote track, stream id: ${streamId}`
  708. ));
  709. // Abort
  710. return;
  711. }
  712. const remoteSDP = this._usesUnifiedPlan
  713. ? new SDP(this.peerconnection.remoteDescription.sdp)
  714. : new SDP(this.remoteDescription.sdp);
  715. let mediaLines;
  716. // In unified plan mode, find the matching mline using 'mid' if its availble, otherwise use the
  717. // 'msid' attribute of the stream.
  718. if (this._usesUnifiedPlan) {
  719. if (transceiver && transceiver.mid) {
  720. const mid = transceiver.mid;
  721. mediaLines = remoteSDP.media.filter(mls => SDPUtil.findLine(mls, `a=mid:${mid}`));
  722. } else {
  723. mediaLines = remoteSDP.media.filter(mls => {
  724. const msid = SDPUtil.findLine(mls, 'a=msid:');
  725. return typeof msid !== 'undefined' && streamId === msid.substring(7).split(' ')[0];
  726. });
  727. }
  728. } else {
  729. mediaLines = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  730. }
  731. if (!mediaLines.length) {
  732. GlobalOnErrorHandler.callErrorHandler(
  733. new Error(`No media lines found in remote SDP for remote stream[id=${streamId},type=${mediaType}]`));
  734. // Abort
  735. return;
  736. }
  737. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  738. ssrcLines
  739. = ssrcLines.filter(line => line.indexOf(`msid:${streamId}`) !== -1);
  740. if (!ssrcLines.length) {
  741. GlobalOnErrorHandler.callErrorHandler(
  742. new Error(`No SSRC lines found in remote SDP for remote stream[msid=${streamId},type=${mediaType}]`));
  743. // Abort
  744. return;
  745. }
  746. // FIXME the length of ssrcLines[0] not verified, but it will fail
  747. // with global error handler anyway
  748. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  749. const trackSsrc = Number(ssrcStr);
  750. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  751. if (isNaN(trackSsrc) || trackSsrc < 0) {
  752. GlobalOnErrorHandler.callErrorHandler(
  753. new Error(
  754. `Invalid SSRC for remote stream[ssrc=${trackSsrc},id=${streamId},type=${mediaType}]`));
  755. // Abort
  756. return;
  757. } else if (!ownerEndpointId) {
  758. GlobalOnErrorHandler.callErrorHandler(
  759. new Error(
  760. `No SSRC owner known for remote stream[ssrc=${trackSsrc},id=${streamId},type=${mediaType}]`));
  761. // Abort
  762. return;
  763. }
  764. logger.info(`${this} creating remote track[endpoint=${ownerEndpointId},ssrc=${trackSsrc},type=${mediaType}]`);
  765. const peerMediaInfo
  766. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  767. if (!peerMediaInfo) {
  768. GlobalOnErrorHandler.callErrorHandler(
  769. new Error(`${this}: no peer media info available for ${ownerEndpointId}`));
  770. return;
  771. }
  772. const muted = peerMediaInfo.muted;
  773. const videoType = peerMediaInfo.videoType; // can be undefined
  774. this._createRemoteTrack(
  775. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  776. };
  777. // FIXME cleanup params
  778. /* eslint-disable max-params */
  779. /**
  780. * Initializes a new JitsiRemoteTrack instance with the data provided by
  781. * the signaling layer and SDP.
  782. *
  783. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  784. * @param {MediaStream} stream the WebRTC stream instance
  785. * @param {MediaStreamTrack} track the WebRTC track instance
  786. * @param {MediaType} mediaType the track's type of the media
  787. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  788. * @param {number} ssrc the track's main SSRC number
  789. * @param {boolean} muted the initial muted status
  790. */
  791. TraceablePeerConnection.prototype._createRemoteTrack = function(
  792. ownerEndpointId,
  793. stream,
  794. track,
  795. mediaType,
  796. videoType,
  797. ssrc,
  798. muted) {
  799. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  800. if (!remoteTracksMap) {
  801. remoteTracksMap = new Map();
  802. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  803. }
  804. const existingTrack = remoteTracksMap.get(mediaType);
  805. if (existingTrack && existingTrack.getTrack() === track) {
  806. // Ignore duplicated event which can originate either from 'onStreamAdded' or 'onTrackAdded'.
  807. logger.info(`${this} ignored duplicated track event for track[endpoint=${ownerEndpointId},type=${mediaType}]`);
  808. return;
  809. } else if (existingTrack) {
  810. logger.error(`${this} received a second remote track for track[endpoint=${ownerEndpointId},type=${mediaType}]`
  811. + 'deleting the existing track');
  812. // The exisiting track needs to be removed here. We can get here when Jicofo reverses the order of source-add
  813. // and source-remove messages. Ideally, when a remote endpoint changes source, like switching devices, it sends
  814. // a source-remove (for old ssrc) followed by a source-add (for new ssrc) and Jicofo then should forward these
  815. // two messages to all the other endpoints in the conference in the same order. However, sometimes, these
  816. // messages arrive at the client in the reverse order resulting in two remote tracks (of same media type) being
  817. // created and in case of video, a black strip (that of the first track which has ended) appears over the live
  818. // track obscuring it. Removing the existing track when that happens will fix this issue.
  819. this._remoteTrackRemoved(existingTrack.getOriginalStream(), existingTrack.getTrack());
  820. }
  821. const remoteTrack
  822. = new JitsiRemoteTrack(
  823. this.rtc,
  824. this.rtc.conference,
  825. ownerEndpointId,
  826. stream,
  827. track,
  828. mediaType,
  829. videoType,
  830. ssrc,
  831. muted,
  832. this.isP2P);
  833. remoteTracksMap.set(mediaType, remoteTrack);
  834. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack, this);
  835. };
  836. /* eslint-enable max-params */
  837. /**
  838. * Handles remote stream removal.
  839. * @param stream the WebRTC MediaStream object which is being removed from the
  840. * PeerConnection
  841. */
  842. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  843. if (!RTC.isUserStream(stream)) {
  844. const id = RTC.getStreamID(stream);
  845. logger.info(`Ignored remote 'stream removed' event for stream[id=${id}]`);
  846. return;
  847. }
  848. // Call remoteTrackRemoved for each track in the stream
  849. const streamVideoTracks = stream.getVideoTracks();
  850. for (const videoTrack of streamVideoTracks) {
  851. this._remoteTrackRemoved(stream, videoTrack);
  852. }
  853. const streamAudioTracks = stream.getAudioTracks();
  854. for (const audioTrack of streamAudioTracks) {
  855. this._remoteTrackRemoved(stream, audioTrack);
  856. }
  857. };
  858. /**
  859. * Handles remote media track removal.
  860. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  861. * of the track.
  862. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  863. * removed from the PeerConnection.
  864. */
  865. TraceablePeerConnection.prototype._remoteTrackRemoved = function(
  866. stream,
  867. track) {
  868. const streamId = RTC.getStreamID(stream);
  869. const trackId = track && RTC.getTrackID(track);
  870. if (!RTC.isUserStreamById(streamId)) {
  871. logger.info(`${this} ignored remote 'stream removed' event for non-user stream[id=${streamId}]`);
  872. return;
  873. }
  874. logger.info(`${this} remote track removed stream[id=${streamId},trackId=${trackId}]`);
  875. if (!streamId) {
  876. GlobalOnErrorHandler.callErrorHandler(new Error(`${this} remote track removal failed - no stream ID`));
  877. return;
  878. }
  879. if (!trackId) {
  880. GlobalOnErrorHandler.callErrorHandler(new Error(`${this} remote track removal failed - no track ID`));
  881. return;
  882. }
  883. if (!this._removeRemoteTrackById(streamId, trackId)) {
  884. // NOTE this warning is always printed when user leaves the room,
  885. // because we remove remote tracks manually on MUC member left event,
  886. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  887. // ignore this warning, but still it's better to keep it printed for
  888. // debugging purposes.
  889. //
  890. // We could change the behaviour to emit track removed only from here,
  891. // but the order of the events will change and consuming apps could
  892. // behave unexpectedly (the "user left" event would come before "track
  893. // removed" events).
  894. logger.warn(`${this} Removed track not found for stream[id=${streamId},trackId=${trackId}]`);
  895. }
  896. };
  897. /**
  898. * Finds remote track by it's stream and track ids.
  899. * @param {string} streamId the media stream id as defined by the WebRTC
  900. * @param {string} trackId the media track id as defined by the WebRTC
  901. * @return {JitsiRemoteTrack|undefined} the track's instance or
  902. * <tt>undefined</tt> if not found.
  903. * @private
  904. */
  905. TraceablePeerConnection.prototype._getRemoteTrackById = function(
  906. streamId,
  907. trackId) {
  908. // .find will break the loop once the first match is found
  909. for (const endpointTrackMap of this.remoteTracks.values()) {
  910. for (const mediaTrack of endpointTrackMap.values()) {
  911. // FIXME verify and try to use ===
  912. /* eslint-disable eqeqeq */
  913. if (mediaTrack.getStreamId() == streamId
  914. && mediaTrack.getTrackId() == trackId) {
  915. return mediaTrack;
  916. }
  917. /* eslint-enable eqeqeq */
  918. }
  919. }
  920. return undefined;
  921. };
  922. /**
  923. * Removes all JitsiRemoteTracks associated with given MUC nickname
  924. * (resource part of the JID). Returns array of removed tracks.
  925. *
  926. * @param {string} owner - The resource part of the MUC JID.
  927. * @returns {JitsiRemoteTrack[]}
  928. */
  929. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  930. const removedTracks = [];
  931. const remoteTracksMap = this.remoteTracks.get(owner);
  932. if (remoteTracksMap) {
  933. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  934. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  935. removedAudioTrack && removedTracks.push(removedAudioTrack);
  936. removedVideoTrack && removedTracks.push(removedVideoTrack);
  937. this.remoteTracks.delete(owner);
  938. }
  939. logger.debug(`${this} removed remote tracks[endpoint=${owner},count=${removedTracks.length}`);
  940. return removedTracks;
  941. };
  942. /**
  943. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits
  944. * {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  945. * @param {JitsiRemoteTrack} toBeRemoved
  946. */
  947. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  948. toBeRemoved.dispose();
  949. const participantId = toBeRemoved.getParticipantId();
  950. const remoteTracksMap = this.remoteTracks.get(participantId);
  951. if (!remoteTracksMap) {
  952. logger.error(`${this} removeRemoteTrack: no remote tracks map for endpoint=${participantId}`);
  953. } else if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  954. logger.error(`${this} Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  955. }
  956. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  957. };
  958. /**
  959. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  960. * track ids.
  961. *
  962. * @param {string} streamId the media stream id as defined by the WebRTC
  963. * @param {string} trackId the media track id as defined by the WebRTC
  964. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  965. * <tt>undefined</tt> if no track matching given stream and track ids was
  966. * found.
  967. */
  968. TraceablePeerConnection.prototype._removeRemoteTrackById = function(
  969. streamId,
  970. trackId) {
  971. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  972. if (toBeRemoved) {
  973. this._removeRemoteTrack(toBeRemoved);
  974. }
  975. return toBeRemoved;
  976. };
  977. /**
  978. * @typedef {Object} SSRCGroupInfo
  979. * @property {Array<number>} ssrcs group's SSRCs
  980. * @property {string} semantics
  981. */
  982. /**
  983. * @typedef {Object} TrackSSRCInfo
  984. * @property {Array<number>} ssrcs track's SSRCs
  985. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  986. */
  987. /**
  988. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  989. * @param {Object} desc the WebRTC SDP instance.
  990. * @return {Map<string,TrackSSRCInfo>}
  991. */
  992. function extractSSRCMap(desc) {
  993. /**
  994. * Track SSRC infos mapped by stream ID (msid)
  995. * @type {Map<string,TrackSSRCInfo>}
  996. */
  997. const ssrcMap = new Map();
  998. /**
  999. * Groups mapped by primary SSRC number
  1000. * @type {Map<number,Array<SSRCGroupInfo>>}
  1001. */
  1002. const groupsMap = new Map();
  1003. if (typeof desc !== 'object' || desc === null
  1004. || typeof desc.sdp !== 'string') {
  1005. logger.warn('An empty description was passed as an argument');
  1006. return ssrcMap;
  1007. }
  1008. const session = transform.parse(desc.sdp);
  1009. if (!Array.isArray(session.media)) {
  1010. return ssrcMap;
  1011. }
  1012. for (const mLine of session.media) {
  1013. if (!Array.isArray(mLine.ssrcs)) {
  1014. continue; // eslint-disable-line no-continue
  1015. }
  1016. if (Array.isArray(mLine.ssrcGroups)) {
  1017. for (const group of mLine.ssrcGroups) {
  1018. if (typeof group.semantics !== 'undefined'
  1019. && typeof group.ssrcs !== 'undefined') {
  1020. // Parse SSRCs and store as numbers
  1021. const groupSSRCs
  1022. = group.ssrcs.split(' ').map(
  1023. ssrcStr => parseInt(ssrcStr, 10));
  1024. const primarySSRC = groupSSRCs[0];
  1025. // Note that group.semantics is already present
  1026. group.ssrcs = groupSSRCs;
  1027. // eslint-disable-next-line max-depth
  1028. if (!groupsMap.has(primarySSRC)) {
  1029. groupsMap.set(primarySSRC, []);
  1030. }
  1031. groupsMap.get(primarySSRC).push(group);
  1032. }
  1033. }
  1034. }
  1035. for (const ssrc of mLine.ssrcs) {
  1036. if (ssrc.attribute !== 'msid') {
  1037. continue; // eslint-disable-line no-continue
  1038. }
  1039. const msid = ssrc.value;
  1040. let ssrcInfo = ssrcMap.get(msid);
  1041. if (!ssrcInfo) {
  1042. ssrcInfo = {
  1043. ssrcs: [],
  1044. groups: [],
  1045. msid
  1046. };
  1047. ssrcMap.set(msid, ssrcInfo);
  1048. }
  1049. const ssrcNumber = ssrc.id;
  1050. ssrcInfo.ssrcs.push(ssrcNumber);
  1051. if (groupsMap.has(ssrcNumber)) {
  1052. const ssrcGroups = groupsMap.get(ssrcNumber);
  1053. for (const group of ssrcGroups) {
  1054. ssrcInfo.groups.push(group);
  1055. }
  1056. }
  1057. }
  1058. }
  1059. return ssrcMap;
  1060. }
  1061. /**
  1062. * Takes a SessionDescription object and returns a "normalized" version.
  1063. * Currently it takes care of ordering the a=ssrc lines and denoting receive
  1064. * only SSRCs.
  1065. */
  1066. const normalizePlanB = function(desc) {
  1067. if (typeof desc !== 'object' || desc === null
  1068. || typeof desc.sdp !== 'string') {
  1069. logger.warn('An empty description was passed as an argument');
  1070. return desc;
  1071. }
  1072. // eslint-disable-next-line no-shadow
  1073. const transform = require('sdp-transform');
  1074. const session = transform.parse(desc.sdp);
  1075. if (typeof session !== 'undefined'
  1076. && typeof session.media !== 'undefined'
  1077. && Array.isArray(session.media)) {
  1078. session.media.forEach(mLine => {
  1079. // Chrome appears to be picky about the order in which a=ssrc lines
  1080. // are listed in an m-line when rtx is enabled (and thus there are
  1081. // a=ssrc-group lines with FID semantics). Specifically if we have
  1082. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  1083. // the "a=ssrc:S1" lines, SRD fails.
  1084. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  1085. // first.
  1086. const firstSsrcs = [];
  1087. const newSsrcLines = [];
  1088. if (typeof mLine.ssrcGroups !== 'undefined'
  1089. && Array.isArray(mLine.ssrcGroups)) {
  1090. mLine.ssrcGroups.forEach(group => {
  1091. if (typeof group.semantics !== 'undefined'
  1092. && group.semantics === 'FID') {
  1093. if (typeof group.ssrcs !== 'undefined') {
  1094. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  1095. }
  1096. }
  1097. });
  1098. }
  1099. if (Array.isArray(mLine.ssrcs)) {
  1100. let i;
  1101. for (i = 0; i < mLine.ssrcs.length; i++) {
  1102. if (typeof mLine.ssrcs[i] === 'object'
  1103. && typeof mLine.ssrcs[i].id !== 'undefined'
  1104. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  1105. newSsrcLines.push(mLine.ssrcs[i]);
  1106. delete mLine.ssrcs[i];
  1107. }
  1108. }
  1109. for (i = 0; i < mLine.ssrcs.length; i++) {
  1110. if (typeof mLine.ssrcs[i] !== 'undefined') {
  1111. newSsrcLines.push(mLine.ssrcs[i]);
  1112. }
  1113. }
  1114. mLine.ssrcs = replaceDefaultUnifiedPlanMsid(newSsrcLines);
  1115. }
  1116. });
  1117. }
  1118. const resStr = transform.write(session);
  1119. return new RTCSessionDescription({
  1120. type: desc.type,
  1121. sdp: resStr
  1122. });
  1123. };
  1124. /**
  1125. * Unified plan differentiates a remote track not associated with a stream using
  1126. * the msid "-", which can incorrectly trigger an onaddstream event in plan-b.
  1127. * For jitsi, these tracks are actually receive-only ssrcs. To prevent
  1128. * onaddstream from firing, remove the ssrcs with msid "-" except the cname
  1129. * line. Normally the ssrcs are not used by the client, as the bridge controls
  1130. * media flow, but keep one reference to the ssrc for the p2p case.
  1131. *
  1132. * @param {Array<Object>} ssrcLines - The ssrc lines from a remote description.
  1133. * @private
  1134. * @returns {Array<Object>} ssrcLines with removed lines referencing msid "-".
  1135. */
  1136. function replaceDefaultUnifiedPlanMsid(ssrcLines = []) {
  1137. if (!browser.isChrome() || !browser.isVersionGreaterThan(70)) {
  1138. return ssrcLines;
  1139. }
  1140. let filteredLines = [ ...ssrcLines ];
  1141. const problematicSsrcIds = ssrcLines.filter(ssrcLine =>
  1142. ssrcLine.attribute === 'mslabel' && ssrcLine.value === '-')
  1143. .map(ssrcLine => ssrcLine.id);
  1144. problematicSsrcIds.forEach(ssrcId => {
  1145. // Find the cname which is to be modified and left in.
  1146. const cnameLine = filteredLines.find(line =>
  1147. line.id === ssrcId && line.attribute === 'cname');
  1148. cnameLine.value = `recvonly-${ssrcId}`;
  1149. // Remove all of lines for the ssrc.
  1150. filteredLines
  1151. = filteredLines.filter(line => line.id !== ssrcId);
  1152. // But re-add the cname line so there is a reference kept to the ssrc
  1153. // in the SDP.
  1154. filteredLines.push(cnameLine);
  1155. });
  1156. return filteredLines;
  1157. }
  1158. /**
  1159. * Makes sure that both audio and video directions are configured as 'sendrecv'.
  1160. * @param {Object} localDescription the SDP object as defined by WebRTC.
  1161. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  1162. */
  1163. const enforceSendRecv = function(localDescription, options) {
  1164. if (!localDescription) {
  1165. throw new Error('No local description passed in.');
  1166. }
  1167. const transformer = new SdpTransformWrap(localDescription.sdp);
  1168. const audioMedia = transformer.selectMedia('audio');
  1169. let changed = false;
  1170. if (audioMedia && audioMedia.direction !== 'sendrecv') {
  1171. if (options.startSilent) {
  1172. audioMedia.direction = 'inactive';
  1173. } else {
  1174. audioMedia.direction = 'sendrecv';
  1175. }
  1176. changed = true;
  1177. }
  1178. const videoMedia = transformer.selectMedia('video');
  1179. if (videoMedia && videoMedia.direction !== 'sendrecv') {
  1180. videoMedia.direction = 'sendrecv';
  1181. changed = true;
  1182. }
  1183. if (changed) {
  1184. return new RTCSessionDescription({
  1185. type: localDescription.type,
  1186. sdp: transformer.toRawSDP()
  1187. });
  1188. }
  1189. return localDescription;
  1190. };
  1191. /**
  1192. *
  1193. * @param {JitsiLocalTrack} localTrack
  1194. */
  1195. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  1196. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  1197. return ssrcInfo && ssrcInfo.ssrcs[0];
  1198. };
  1199. /**
  1200. * When doing unified plan simulcast, we'll have a set of ssrcs with the
  1201. * same msid but no ssrc-group, since unified plan signals the simulcast
  1202. * group via the a=simulcast line. Unfortunately, Jicofo will complain
  1203. * if it sees ssrcs with matching msids but no ssrc-group, so we'll inject
  1204. * an ssrc-group line to make Jicofo happy.
  1205. * @param desc A session description object (with 'type' and 'sdp' fields)
  1206. * @return A session description object with its sdp field modified to
  1207. * contain an inject ssrc-group for simulcast
  1208. */
  1209. TraceablePeerConnection.prototype._injectSsrcGroupForUnifiedSimulcast
  1210. = function(desc) {
  1211. const sdp = transform.parse(desc.sdp);
  1212. const video = sdp.media.find(mline => mline.type === 'video');
  1213. // Check if the browser supports RTX, add only the primary ssrcs to the
  1214. // SIM group if that is the case.
  1215. video.ssrcGroups = video.ssrcGroups || [];
  1216. const fidGroups = video.ssrcGroups.filter(group => group.semantics === 'FID');
  1217. if (video.simulcast || video.simulcast_03) {
  1218. const ssrcs = [];
  1219. if (fidGroups && fidGroups.length) {
  1220. fidGroups.forEach(group => {
  1221. ssrcs.push(group.ssrcs.split(' ')[0]);
  1222. });
  1223. } else {
  1224. video.ssrcs.forEach(ssrc => {
  1225. if (ssrc.attribute === 'msid') {
  1226. ssrcs.push(ssrc.id);
  1227. }
  1228. });
  1229. }
  1230. if (video.ssrcGroups.find(group => group.semantics === 'SIM')) {
  1231. // Group already exists, no need to do anything
  1232. return desc;
  1233. }
  1234. video.ssrcGroups.push({
  1235. semantics: 'SIM',
  1236. ssrcs: ssrcs.join(' ')
  1237. });
  1238. }
  1239. return new RTCSessionDescription({
  1240. type: desc.type,
  1241. sdp: transform.write(sdp)
  1242. });
  1243. };
  1244. /* eslint-disable-next-line vars-on-top */
  1245. const getters = {
  1246. signalingState() {
  1247. return this.peerconnection.signalingState;
  1248. },
  1249. iceConnectionState() {
  1250. return this.peerconnection.iceConnectionState;
  1251. },
  1252. localDescription() {
  1253. let desc = this.peerconnection.localDescription;
  1254. if (!desc) {
  1255. logger.debug(`${this} getLocalDescription no localDescription found`);
  1256. return {};
  1257. }
  1258. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1259. // If the browser is running in unified plan mode and this is a jvb connection,
  1260. // transform the SDP to Plan B first.
  1261. if (this._usesUnifiedPlan && !this.isP2P) {
  1262. desc = this.interop.toPlanB(desc);
  1263. this.trace('getLocalDescription::postTransform (Plan B)',
  1264. dumpSDP(desc));
  1265. desc = this._injectSsrcGroupForUnifiedSimulcast(desc);
  1266. this.trace('getLocalDescription::postTransform (inject ssrc group)',
  1267. dumpSDP(desc));
  1268. } else if (!this._usesUnifiedPlan) {
  1269. if (browser.doesVideoMuteByStreamRemove()) {
  1270. desc = this.localSdpMunger.maybeAddMutedLocalVideoTracksToSDP(desc);
  1271. logger.debug(
  1272. 'getLocalDescription::postTransform (munge local SDP)', desc);
  1273. }
  1274. // What comes out of this getter will be signalled over Jingle to
  1275. // the other peer, so we need to make sure the media direction is
  1276. // 'sendrecv' because we won't change the direction later and don't want
  1277. // the other peer to think we can't send or receive.
  1278. //
  1279. // Note that the description we set in chrome does have the accurate
  1280. // direction (e.g. 'recvonly'), since that is technically what is
  1281. // happening (check setLocalDescription impl).
  1282. desc = enforceSendRecv(desc, this.options);
  1283. }
  1284. // See the method's doc for more info about this transformation.
  1285. desc = this.localSdpMunger.transformStreamIdentifiers(desc);
  1286. return desc;
  1287. },
  1288. remoteDescription() {
  1289. let desc = this.peerconnection.remoteDescription;
  1290. if (!desc) {
  1291. logger.debug(`${this} getRemoteDescription no remoteDescription found`);
  1292. return {};
  1293. }
  1294. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1295. // If the browser is running in unified plan mode and this is a jvb connection,
  1296. // transform the SDP to Plan B first.
  1297. if (this._usesUnifiedPlan && !this.isP2P) {
  1298. desc = this.interop.toPlanB(desc);
  1299. this.trace(
  1300. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  1301. }
  1302. return desc;
  1303. }
  1304. };
  1305. Object.keys(getters).forEach(prop => {
  1306. Object.defineProperty(
  1307. TraceablePeerConnection.prototype,
  1308. prop, {
  1309. get: getters[prop]
  1310. }
  1311. );
  1312. });
  1313. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1314. return this.localSSRCs.get(rtcId);
  1315. };
  1316. /**
  1317. * Checks if screensharing is in progress.
  1318. *
  1319. * @returns {boolean} Returns true if a desktop track has been added to the
  1320. * peerconnection, false otherwise.
  1321. */
  1322. TraceablePeerConnection.prototype._isSharingScreen = function() {
  1323. const track = this.getLocalVideoTrack();
  1324. return track && track.videoType === VideoType.DESKTOP;
  1325. };
  1326. /**
  1327. * Munges the order of the codecs in the SDP passed based on the preference
  1328. * set through config.js settings. All instances of the specified codec are
  1329. * moved up to the top of the list when it is preferred. The specified codec
  1330. * is deleted from the list if the configuration specifies that the codec be
  1331. * disabled.
  1332. * @param {RTCSessionDescription} description that needs to be munged.
  1333. * @returns {RTCSessionDescription} the munged description.
  1334. */
  1335. TraceablePeerConnection.prototype._mungeCodecOrder = function(description) {
  1336. if (!this.codecPreference || this._usesTransceiverCodecPreferences) {
  1337. return description;
  1338. }
  1339. const parsedSdp = transform.parse(description.sdp);
  1340. for (const mLine of parsedSdp.media) {
  1341. if (this.codecPreference.enable && mLine.type === this.codecPreference.mediaType) {
  1342. SDPUtil.preferCodec(mLine, this.codecPreference.mimeType);
  1343. // Strip the high profile H264 codecs on mobile clients for p2p connection.
  1344. // High profile codecs give better quality at the expense of higher load which
  1345. // we do not want on mobile clients.
  1346. // Jicofo offers only the baseline code for the jvb connection.
  1347. // TODO - add check for mobile browsers once js-utils provides that check.
  1348. if (this.codecPreference.mimeType === CodecMimeType.H264 && browser.isReactNative() && this.isP2P) {
  1349. SDPUtil.stripCodec(mLine, this.codecPreference.mimeType, true /* high profile */);
  1350. }
  1351. // Set the max bitrate here on the SDP so that the configured max. bitrate is effective
  1352. // as soon as the browser switches to VP9.
  1353. if (this.codecPreference.mimeType === CodecMimeType.VP9) {
  1354. const bitrates = this.videoBitrates.VP9 || this.videoBitrates;
  1355. const hdBitrate = bitrates.high ? bitrates.high : HD_BITRATE;
  1356. const limit = Math.floor((this._isSharingScreen() ? HD_BITRATE : hdBitrate) / 1000);
  1357. // Use only the HD bitrate for now as there is no API available yet for configuring
  1358. // the bitrates on the individual SVC layers.
  1359. mLine.bandwidth = [ {
  1360. type: 'AS',
  1361. limit
  1362. } ];
  1363. } else {
  1364. // Clear the bandwidth limit in SDP when VP9 is no longer the preferred codec.
  1365. // This is needed on react native clients as react-native-webrtc returns the
  1366. // SDP that the application passed instead of returning the SDP off the native side.
  1367. // This line automatically gets cleared on web on every renegotiation.
  1368. mLine.bandwidth = undefined;
  1369. }
  1370. } else if (mLine.type === this.codecPreference.mediaType) {
  1371. SDPUtil.stripCodec(mLine, this.codecPreference.mimeType);
  1372. }
  1373. }
  1374. return new RTCSessionDescription({
  1375. type: description.type,
  1376. sdp: transform.write(parsedSdp)
  1377. });
  1378. };
  1379. /**
  1380. * Checks if given track belongs to this peerconnection instance.
  1381. *
  1382. * @param {JitsiLocalTrack|JitsiRemoteTrack} track - The track to be checked.
  1383. * @returns {boolean}
  1384. */
  1385. TraceablePeerConnection.prototype.containsTrack = function(track) {
  1386. if (track.isLocal()) {
  1387. return this.localTracks.has(track.rtcId);
  1388. }
  1389. const participantId = track.getParticipantId();
  1390. const remoteTracksMap = this.remoteTracks.get(participantId);
  1391. return Boolean(remoteTracksMap && remoteTracksMap.get(track.getType()) === track);
  1392. };
  1393. /**
  1394. * Add {@link JitsiLocalTrack} to this TPC.
  1395. * @param {JitsiLocalTrack} track
  1396. * @param {boolean} isInitiator indicates if the endpoint is the offerer.
  1397. * @returns {Promise<void>} - resolved when done.
  1398. */
  1399. TraceablePeerConnection.prototype.addTrack = function(track, isInitiator = false) {
  1400. const rtcId = track.rtcId;
  1401. logger.info(`${this} adding ${track}`);
  1402. if (this.localTracks.has(rtcId)) {
  1403. return Promise.reject(new Error(`${track} is already in ${this}`));
  1404. }
  1405. this.localTracks.set(rtcId, track);
  1406. if (this._usesUnifiedPlan) {
  1407. try {
  1408. this.tpcUtils.addTrack(track, isInitiator);
  1409. } catch (error) {
  1410. logger.error(`${this} Adding track=${track} failed: ${error?.message}`);
  1411. return Promise.reject(error);
  1412. }
  1413. } else {
  1414. // In all other cases, i.e., plan-b and unified plan bridge case, use addStream API to
  1415. // add the track to the peerconnection.
  1416. // TODO - addTransceiver doesn't generate a MSID for the stream, which is needed for signaling
  1417. // the ssrc to Jicofo. Switch to using UUID as MSID when addTransceiver is used in Unified plan
  1418. // JVB connection case as well.
  1419. const webrtcStream = track.getOriginalStream();
  1420. if (webrtcStream) {
  1421. this._addStream(webrtcStream);
  1422. // It's not ok for a track to not have a WebRTC stream if:
  1423. } else if (!browser.doesVideoMuteByStreamRemove()
  1424. || track.isAudioTrack()
  1425. || (track.isVideoTrack() && !track.isMuted())) {
  1426. return Promise.reject(new Error(`${this} no WebRTC stream for track=${track}`));
  1427. }
  1428. // Muted video tracks do not have WebRTC stream
  1429. if (browser.doesVideoMuteByStreamRemove() && track.isVideoTrack() && track.isMuted()) {
  1430. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  1431. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  1432. const simGroup
  1433. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  1434. if (simGroup) {
  1435. this.simulcast.setSsrcCache(simGroup.ssrcs);
  1436. }
  1437. const fidGroups
  1438. = ssrcInfo.groups.filter(
  1439. groupInfo => groupInfo.semantics === 'FID');
  1440. if (fidGroups) {
  1441. const rtxSsrcMapping = new Map();
  1442. fidGroups.forEach(fidGroup => {
  1443. const primarySsrc = fidGroup.ssrcs[0];
  1444. const rtxSsrc = fidGroup.ssrcs[1];
  1445. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  1446. });
  1447. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  1448. }
  1449. }
  1450. }
  1451. let promiseChain = Promise.resolve();
  1452. // On Firefox, the encodings have to be configured on the sender only after the transceiver is created.
  1453. if (browser.isFirefox()) {
  1454. promiseChain = promiseChain.then(() => this.tpcUtils.setEncodings(track));
  1455. }
  1456. return promiseChain;
  1457. };
  1458. /**
  1459. * Adds local track as part of the unmute operation.
  1460. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  1461. * operation
  1462. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's
  1463. * state has changed and renegotiation is required, false if no renegotiation is needed or
  1464. * Promise is rejected when something goes wrong.
  1465. */
  1466. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  1467. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  1468. // Abort
  1469. return Promise.reject('Track not found on the peerconnection');
  1470. }
  1471. logger.info(`${this} Adding track=${track} as unmute`);
  1472. const webRtcStream = track.getOriginalStream();
  1473. if (!webRtcStream) {
  1474. logger.error(`${this} Unable to add track=${track} as unmute - no WebRTC stream`);
  1475. return Promise.reject('Stream not found');
  1476. }
  1477. if (this._usesUnifiedPlan) {
  1478. return this.tpcUtils.addTrackUnmute(track);
  1479. }
  1480. this._addStream(webRtcStream);
  1481. return Promise.resolve(true);
  1482. };
  1483. /**
  1484. * Adds WebRTC media stream to the underlying PeerConnection
  1485. * @param {MediaStream} mediaStream
  1486. * @private
  1487. */
  1488. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  1489. this.peerconnection.addStream(mediaStream);
  1490. this._addedStreams.push(mediaStream);
  1491. };
  1492. /**
  1493. * Removes WebRTC media stream from the underlying PeerConection
  1494. * @param {MediaStream} mediaStream
  1495. */
  1496. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  1497. this.peerconnection.removeStream(mediaStream);
  1498. this._addedStreams
  1499. = this._addedStreams.filter(stream => stream !== mediaStream);
  1500. };
  1501. /**
  1502. * This method when called will check if given <tt>localTrack</tt> belongs to
  1503. * this TPC (that it has been previously added using {@link addTrack}). If the
  1504. * track does not belong an error message will be logged.
  1505. * @param {string} methodName the method name that will be logged in an error
  1506. * message
  1507. * @param {JitsiLocalTrack} localTrack
  1508. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1509. * <tt>false</tt> otherwise.
  1510. * @private
  1511. */
  1512. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1513. methodName,
  1514. localTrack) {
  1515. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1516. if (!doesBelong) {
  1517. logger.error(`${this} ${methodName}: track=${localTrack} does not belong to pc`);
  1518. }
  1519. return doesBelong;
  1520. };
  1521. /**
  1522. * Returns the codec that is configured on the client as the preferred video codec.
  1523. * This takes into account the current order of codecs in the local description sdp.
  1524. *
  1525. * @returns {CodecMimeType} The codec that is set as the preferred codec to receive
  1526. * video in the local SDP.
  1527. */
  1528. TraceablePeerConnection.prototype.getConfiguredVideoCodec = function() {
  1529. const sdp = this.peerconnection.localDescription?.sdp;
  1530. const defaultCodec = CodecMimeType.VP8;
  1531. if (!sdp) {
  1532. return defaultCodec;
  1533. }
  1534. const parsedSdp = transform.parse(sdp);
  1535. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  1536. const codec = mLine.rtp[0].codec;
  1537. if (codec) {
  1538. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  1539. }
  1540. return defaultCodec;
  1541. };
  1542. /**
  1543. * Sets the codec preference on the peerconnection. The codec preference goes into effect when
  1544. * the next renegotiation happens.
  1545. *
  1546. * @param {CodecMimeType} preferredCodec the preferred codec.
  1547. * @param {CodecMimeType} disabledCodec the codec that needs to be disabled.
  1548. * @returns {void}
  1549. */
  1550. TraceablePeerConnection.prototype.setVideoCodecs = function(preferredCodec = null, disabledCodec = null) {
  1551. // If both enable and disable are set, disable settings will prevail.
  1552. const enable = disabledCodec === null;
  1553. const mimeType = disabledCodec ? disabledCodec : preferredCodec;
  1554. if (this.codecPreference && (preferredCodec || disabledCodec)) {
  1555. this.codecPreference.enable = enable;
  1556. this.codecPreference.mimeType = mimeType;
  1557. } else if (preferredCodec || disabledCodec) {
  1558. this.codecPreference = {
  1559. enable,
  1560. mediaType: MediaType.VIDEO,
  1561. mimeType
  1562. };
  1563. } else {
  1564. logger.warn(`${this} Invalid codec settings[preferred=${preferredCodec},disabled=${disabledCodec}],
  1565. atleast one value is needed`);
  1566. }
  1567. };
  1568. /**
  1569. * Tells if the given WebRTC <tt>MediaStream</tt> has been added to
  1570. * the underlying WebRTC PeerConnection.
  1571. * @param {MediaStream} mediaStream
  1572. * @returns {boolean}
  1573. */
  1574. TraceablePeerConnection.prototype.isMediaStreamInPc = function(mediaStream) {
  1575. return this._addedStreams.indexOf(mediaStream) > -1;
  1576. };
  1577. /**
  1578. * Remove local track from this TPC.
  1579. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1580. *
  1581. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1582. * The same applies to addTrack.
  1583. */
  1584. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1585. const webRtcStream = localTrack.getOriginalStream();
  1586. this.trace(
  1587. 'removeStream',
  1588. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1589. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1590. // Abort - nothing to be done here
  1591. return;
  1592. }
  1593. this.localTracks.delete(localTrack.rtcId);
  1594. this.localSSRCs.delete(localTrack.rtcId);
  1595. if (webRtcStream) {
  1596. this.peerconnection.removeStream(webRtcStream);
  1597. }
  1598. };
  1599. /**
  1600. * Returns the sender corresponding to the given media type.
  1601. * @param {MEDIA_TYPE} mediaType - The media type 'audio' or 'video' to be used for the search.
  1602. * @returns {RTPSender|undefined} - The found sender or undefined if no sender
  1603. * was found.
  1604. */
  1605. TraceablePeerConnection.prototype.findSenderByKind = function(mediaType) {
  1606. return this.peerconnection.getSenders().find(s => s.track && s.track.kind === mediaType);
  1607. };
  1608. /**
  1609. * Returns the receiver corresponding to the given MediaStreamTrack.
  1610. *
  1611. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1612. * @returns {RTCRtpReceiver|undefined} - The found receiver or undefined if no receiver
  1613. * was found.
  1614. */
  1615. TraceablePeerConnection.prototype.findReceiverForTrack = function(track) {
  1616. return this.peerconnection.getReceivers().find(r => r.track === track);
  1617. };
  1618. /**
  1619. * Returns the sender corresponding to the given MediaStreamTrack.
  1620. *
  1621. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1622. * @returns {RTCRtpSender|undefined} - The found sender or undefined if no sender
  1623. * was found.
  1624. */
  1625. TraceablePeerConnection.prototype.findSenderForTrack = function(track) {
  1626. return this.peerconnection.getSenders().find(s => s.track === track);
  1627. };
  1628. /**
  1629. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1630. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1631. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1632. * <tt>oldTrack</tt>
  1633. *
  1634. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be
  1635. * replaced
  1636. * @param {JitsiLocalTrack|null} newTrack - The new track to use
  1637. * @returns {Promise<boolean>} - If the promise resolves with true,
  1638. * renegotiation will be needed. Otherwise no renegotiation is needed.
  1639. */
  1640. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack) {
  1641. if (this._usesUnifiedPlan) {
  1642. logger.debug(`${this} TPC.replaceTrack using unified plan`);
  1643. return this.tpcUtils.replaceTrack(oldTrack, newTrack)
  1644. // renegotiate when SDP is used for simulcast munging
  1645. .then(() => this.isSimulcastOn() && browser.usesSdpMungingForSimulcast());
  1646. }
  1647. logger.debug(`${this} TPC.replaceTrack using plan B`);
  1648. let promiseChain = Promise.resolve();
  1649. if (oldTrack) {
  1650. this.removeTrack(oldTrack);
  1651. }
  1652. if (newTrack) {
  1653. promiseChain = this.addTrack(newTrack);
  1654. }
  1655. return promiseChain.then(() => true);
  1656. };
  1657. /**
  1658. * Removes local track as part of the mute operation.
  1659. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1660. * the mute operation.
  1661. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's
  1662. * state has changed and renegotiation is required, false if no renegotiation is needed or
  1663. * Promise is rejected when something goes wrong.
  1664. */
  1665. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1666. const webRtcStream = localTrack.getOriginalStream();
  1667. this.trace(
  1668. 'removeStreamMute',
  1669. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1670. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1671. // Abort - nothing to be done here
  1672. return Promise.reject('Track not found in the peerconnection');
  1673. }
  1674. if (this._usesUnifiedPlan) {
  1675. return this.tpcUtils.removeTrackMute(localTrack);
  1676. }
  1677. if (webRtcStream) {
  1678. logger.info(`${this} Removing track=${localTrack} as mute`);
  1679. this._removeStream(webRtcStream);
  1680. return Promise.resolve(true);
  1681. }
  1682. logger.error(`${this} removeStreamMute - no WebRTC stream for track=${localTrack}`);
  1683. return Promise.reject('Stream not found');
  1684. };
  1685. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1686. this.trace('createDataChannel', label, opts);
  1687. return this.peerconnection.createDataChannel(label, opts);
  1688. };
  1689. /**
  1690. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1691. * in the SDP so that simulcast is properly activated.
  1692. *
  1693. * @param {Object} localSdp the WebRTC session description instance for
  1694. * the local description.
  1695. * @private
  1696. */
  1697. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast = function(
  1698. localSdp) {
  1699. let sdpStr = localSdp.sdp;
  1700. const videoStartIndex = sdpStr.indexOf('m=video');
  1701. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1702. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1703. if (simStartIndex === -1
  1704. || otherStartIndex === -1
  1705. || otherStartIndex === simStartIndex) {
  1706. return localSdp;
  1707. }
  1708. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1709. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1710. sdpStr = sdpStr.replace(simStr, '');
  1711. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1712. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1713. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1714. const simStrTrimmed = simStr.trim();
  1715. const sdpTail = sdpStr.slice(otherEndIndex);
  1716. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1717. return new RTCSessionDescription({
  1718. type: localSdp.type,
  1719. sdp: sdpStr
  1720. });
  1721. };
  1722. /**
  1723. * Will adjust audio and video media direction in the given SDP object to
  1724. * reflect the current status of the {@link audioTransferActive} and
  1725. * {@link videoTransferActive} flags.
  1726. * @param {Object} localDescription the WebRTC session description instance for
  1727. * the local description.
  1728. * @private
  1729. */
  1730. TraceablePeerConnection.prototype._adjustLocalMediaDirection = function(
  1731. localDescription) {
  1732. const transformer = new SdpTransformWrap(localDescription.sdp);
  1733. let modifiedDirection = false;
  1734. const audioMedia = transformer.selectMedia('audio');
  1735. if (audioMedia) {
  1736. const desiredAudioDirection
  1737. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1738. if (audioMedia.direction !== desiredAudioDirection) {
  1739. audioMedia.direction = desiredAudioDirection;
  1740. logger.info(`${this} Adjusted local audio direction to ${desiredAudioDirection}`);
  1741. modifiedDirection = true;
  1742. }
  1743. } else {
  1744. logger.warn(`${this} No "audio" media found in the local description`);
  1745. }
  1746. const videoMedia = transformer.selectMedia('video');
  1747. if (videoMedia) {
  1748. const desiredVideoDirection
  1749. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1750. if (videoMedia.direction !== desiredVideoDirection) {
  1751. videoMedia.direction = desiredVideoDirection;
  1752. logger.info(`${this} Adjusted local video direction to ${desiredVideoDirection}`);
  1753. modifiedDirection = true;
  1754. }
  1755. } else {
  1756. logger.warn(`${this} No "video" media found in the local description`);
  1757. }
  1758. if (modifiedDirection) {
  1759. return new RTCSessionDescription({
  1760. type: localDescription.type,
  1761. sdp: transformer.toRawSDP()
  1762. });
  1763. }
  1764. return localDescription;
  1765. };
  1766. /**
  1767. * Munges the stereo flag as well as the opusMaxAverageBitrate in the SDP, based
  1768. * on values set through config.js, if present.
  1769. *
  1770. * @param {RTCSessionDescription} description that needs to be munged.
  1771. * @returns {RTCSessionDescription} the munged description.
  1772. */
  1773. TraceablePeerConnection.prototype._mungeOpus = function(description) {
  1774. const { audioQuality } = this.options;
  1775. if (!audioQuality?.stereo && !audioQuality?.opusMaxAverageBitrate) {
  1776. return description;
  1777. }
  1778. const parsedSdp = transform.parse(description.sdp);
  1779. const mLines = parsedSdp.media;
  1780. for (const mLine of mLines) {
  1781. if (mLine.type === 'audio') {
  1782. const { payload } = mLine.rtp.find(protocol => protocol.codec === CodecMimeType.OPUS);
  1783. if (!payload) {
  1784. // eslint-disable-next-line no-continue
  1785. continue;
  1786. }
  1787. let fmtpOpus = mLine.fmtp.find(protocol => protocol.payload === payload);
  1788. if (!fmtpOpus) {
  1789. fmtpOpus = {
  1790. payload,
  1791. config: ''
  1792. };
  1793. }
  1794. const fmtpConfig = transform.parseParams(fmtpOpus.config);
  1795. let sdpChanged = false;
  1796. if (audioQuality?.stereo) {
  1797. fmtpConfig.stereo = 1;
  1798. sdpChanged = true;
  1799. }
  1800. if (audioQuality?.opusMaxAverageBitrate) {
  1801. fmtpConfig.maxaveragebitrate = audioQuality.opusMaxAverageBitrate;
  1802. sdpChanged = true;
  1803. }
  1804. if (!sdpChanged) {
  1805. // eslint-disable-next-line no-continue
  1806. continue;
  1807. }
  1808. let mungedConfig = '';
  1809. for (const key of Object.keys(fmtpConfig)) {
  1810. mungedConfig += `${key}=${fmtpConfig[key]}; `;
  1811. }
  1812. fmtpOpus.config = mungedConfig.trim();
  1813. }
  1814. }
  1815. return new RTCSessionDescription({
  1816. type: description.type,
  1817. sdp: transform.write(parsedSdp)
  1818. });
  1819. };
  1820. TraceablePeerConnection.prototype.setLocalDescription = function(description) {
  1821. let localSdp = description;
  1822. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1823. // Munge the order of the codecs based on the preferences set through config.js
  1824. localSdp = this._mungeCodecOrder(localSdp);
  1825. // Munge stereo flag and opusMaxAverageBitrate based on config.js
  1826. localSdp = this._mungeOpus(localSdp);
  1827. if (!this._usesUnifiedPlan) {
  1828. localSdp = this._adjustLocalMediaDirection(localSdp);
  1829. localSdp = this._ensureSimulcastGroupIsLast(localSdp);
  1830. } else if (!this.isP2P) {
  1831. // if we're using unified plan, transform to it first.
  1832. localSdp = this.interop.toUnifiedPlan(localSdp);
  1833. this.trace(
  1834. 'setLocalDescription::postTransform (Unified Plan)',
  1835. dumpSDP(localSdp));
  1836. }
  1837. return new Promise((resolve, reject) => {
  1838. this.peerconnection.setLocalDescription(localSdp)
  1839. .then(() => {
  1840. this.trace('setLocalDescriptionOnSuccess');
  1841. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1842. if (localUfrag !== this.localUfrag) {
  1843. this.localUfrag = localUfrag;
  1844. this.eventEmitter.emit(
  1845. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1846. }
  1847. resolve();
  1848. }, err => {
  1849. this.trace('setLocalDescriptionOnFailure', err);
  1850. this.eventEmitter.emit(
  1851. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1852. err, this);
  1853. reject(err);
  1854. });
  1855. });
  1856. };
  1857. /**
  1858. * Enables/disables audio media transmission on this peer connection. When
  1859. * disabled the SDP audio media direction in the local SDP will be adjusted to
  1860. * 'inactive' which means that no data will be sent nor accepted, but
  1861. * the connection should be kept alive.
  1862. * @param {boolean} active <tt>true</tt> to enable audio media transmission or
  1863. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1864. * no effect.
  1865. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1866. * needs to be executed in order for the changes to take effect or
  1867. * <tt>false</tt> if the given value was the same as the previous one.
  1868. * @public
  1869. */
  1870. TraceablePeerConnection.prototype.setAudioTransferActive = function(active) {
  1871. logger.debug(`${this} audio transfer active: ${active}`);
  1872. const changed = this.audioTransferActive !== active;
  1873. this.audioTransferActive = active;
  1874. if (this._usesUnifiedPlan) {
  1875. this.tpcUtils.setAudioTransferActive(active);
  1876. // false means no renegotiation up the chain which is not needed in the Unified mode
  1877. return false;
  1878. }
  1879. return changed;
  1880. };
  1881. /**
  1882. * Sets the degradation preference on the video sender. This setting determines if
  1883. * resolution or framerate will be preferred when bandwidth or cpu is constrained.
  1884. * Sets it to 'maintain-framerate' when a camera track is added to the pc, sets it
  1885. * to 'maintain-resolution' when a desktop track is being shared instead.
  1886. * @returns {Promise<void>}
  1887. */
  1888. TraceablePeerConnection.prototype.setSenderVideoDegradationPreference = function() {
  1889. if (!this.peerconnection.getSenders) {
  1890. logger.debug(`${this} Browser does not support RTCRtpSender`);
  1891. return Promise.resolve();
  1892. }
  1893. const localVideoTrack = this.getLocalVideoTrack();
  1894. const videoSender = this.findSenderByKind(MediaType.VIDEO);
  1895. if (!videoSender) {
  1896. return Promise.resolve();
  1897. }
  1898. const parameters = videoSender.getParameters();
  1899. const preference = localVideoTrack.videoType === VideoType.CAMERA
  1900. ? DEGRADATION_PREFERENCE_CAMERA
  1901. : this.options.capScreenshareBitrate && !this._usesUnifiedPlan
  1902. // Prefer resolution for low fps share.
  1903. ? DEGRADATION_PREFERENCE_DESKTOP
  1904. // Prefer frame-rate for high fps share.
  1905. : DEGRADATION_PREFERENCE_CAMERA;
  1906. logger.info(`${this} Setting a degradation preference [preference=${preference},track=${localVideoTrack}`);
  1907. parameters.degradationPreference = preference;
  1908. this.tpcUtils.updateEncodingsResolution(parameters);
  1909. return videoSender.setParameters(parameters);
  1910. };
  1911. /**
  1912. * Sets the max bitrate on the RTCRtpSender so that the
  1913. * bitrate of the enocder doesn't exceed the configured value.
  1914. * This is needed for the desktop share until spec-complaint
  1915. * simulcast is implemented.
  1916. * @param {JitsiLocalTrack} localTrack - the local track whose
  1917. * max bitrate is to be configured.
  1918. * @returns {Promise<void>}
  1919. */
  1920. TraceablePeerConnection.prototype.setMaxBitRate = function() {
  1921. // For VP9, max bitrate is configured by setting b=AS value in SDP. Browsers do
  1922. // not yet support setting max bitrates for individual VP9 SVC layers.
  1923. if (this.getConfiguredVideoCodec() === CodecMimeType.VP9 || !window.RTCRtpSender) {
  1924. return Promise.resolve();
  1925. }
  1926. const localVideoTrack = this.getLocalVideoTrack();
  1927. if (!localVideoTrack) {
  1928. return Promise.resolve();
  1929. }
  1930. const videoType = localVideoTrack.videoType;
  1931. const planBScreenSharing = !this._usesUnifiedPlan && videoType === VideoType.DESKTOP;
  1932. // Apply the maxbitrates on the video track when one of the conditions is met.
  1933. // 1. Max. bitrates for video are specified through videoQuality settings in config.js
  1934. // 2. Track is a desktop track and bitrate is capped using capScreenshareBitrate option in plan-b mode.
  1935. // 3. The client is running in Unified plan mode.
  1936. if (!((this.options.videoQuality && this.options.videoQuality.maxBitratesVideo)
  1937. || (planBScreenSharing && this.options.capScreenshareBitrate)
  1938. || this._usesUnifiedPlan)) {
  1939. return Promise.resolve();
  1940. }
  1941. const presenterEnabled = localVideoTrack._originalStream
  1942. && localVideoTrack._originalStream.id !== localVideoTrack.getStreamId();
  1943. const videoSender = this.findSenderByKind(MediaType.VIDEO);
  1944. if (!videoSender) {
  1945. return Promise.resolve();
  1946. }
  1947. const parameters = videoSender.getParameters();
  1948. if (!(parameters.encodings && parameters.encodings.length)) {
  1949. return Promise.resolve();
  1950. }
  1951. if (this.isSimulcastOn()) {
  1952. for (const encoding in parameters.encodings) {
  1953. if (parameters.encodings.hasOwnProperty(encoding)) {
  1954. let bitrate;
  1955. if (planBScreenSharing) {
  1956. // On chromium, set a max bitrate of 500 Kbps for screenshare when capScreenshareBitrate
  1957. // is enabled through config.js and presenter is not turned on.
  1958. // FIXME the top 'isSimulcastOn' condition is confusing for screensharing, because
  1959. // if capScreenshareBitrate option is enabled then the simulcast is turned off
  1960. bitrate = this.options.capScreenshareBitrate
  1961. ? presenterEnabled ? HD_BITRATE : DESKTOP_SHARE_RATE
  1962. // Remove the bitrate config if not capScreenshareBitrate:
  1963. // When switching from camera to desktop and videoQuality.maxBitratesVideo were set,
  1964. // then the 'maxBitrate' setting must be cleared, because if simulcast is enabled for screen
  1965. // and maxBitrates are set then Chrome will not send the screen stream (plan B).
  1966. : undefined;
  1967. } else {
  1968. bitrate = this.tpcUtils.localStreamEncodingsConfig[encoding].maxBitrate;
  1969. }
  1970. logger.info(`${this} Setting a max bitrate of ${bitrate} bps on layer `
  1971. + `${this.tpcUtils.localStreamEncodingsConfig[encoding].rid}`);
  1972. parameters.encodings[encoding].maxBitrate = bitrate;
  1973. }
  1974. }
  1975. } else {
  1976. // Do not change the max bitrate for desktop tracks in non-simulcast mode.
  1977. let bitrate = this.getTargetVideoBitrates()?.high;
  1978. if (videoType === VideoType.CAMERA) {
  1979. // Determine the bitrates based on the sender constraint applied for unicast tracks.
  1980. const scaleFactor = this.senderVideoMaxHeight
  1981. ? Math.floor(localVideoTrack.resolution / this.senderVideoMaxHeight)
  1982. : 1;
  1983. const encoding = this.tpcUtils.localStreamEncodingsConfig
  1984. .find(layer => layer.scaleResolutionDownBy === scaleFactor);
  1985. if (encoding) {
  1986. logger.info(`${this} Setting max bitrate=${encoding.maxBitrate} bps on track=${localVideoTrack}`);
  1987. bitrate = encoding.maxBitrate;
  1988. }
  1989. }
  1990. parameters.encodings[0].maxBitrate = bitrate;
  1991. }
  1992. this.tpcUtils.updateEncodingsResolution(parameters);
  1993. return videoSender.setParameters(parameters);
  1994. };
  1995. TraceablePeerConnection.prototype.setRemoteDescription = function(description) {
  1996. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1997. /* eslint-disable no-param-reassign */
  1998. // Munge the order of the codecs based on the preferences set through config.js
  1999. description = this._mungeCodecOrder(description);
  2000. // Munge stereo flag and opusMaxAverageBitrate based on config.js
  2001. description = this._mungeOpus(description);
  2002. /* eslint-enable no-param-reassign */
  2003. if (!this._usesUnifiedPlan) {
  2004. // TODO the focus should squeze or explode the remote simulcast
  2005. if (this.isSimulcastOn()) {
  2006. // eslint-disable-next-line no-param-reassign
  2007. description = this.simulcast.mungeRemoteDescription(description, true /* add x-google-conference flag */);
  2008. this.trace(
  2009. 'setRemoteDescription::postTransform (simulcast)',
  2010. dumpSDP(description));
  2011. }
  2012. // eslint-disable-next-line no-param-reassign
  2013. description = normalizePlanB(description);
  2014. } else if (!this.isP2P) {
  2015. const currentDescription = this.peerconnection.remoteDescription;
  2016. // eslint-disable-next-line no-param-reassign
  2017. description = this.interop.toUnifiedPlan(description, currentDescription);
  2018. this.trace(
  2019. 'setRemoteDescription::postTransform (Unified)',
  2020. dumpSDP(description));
  2021. if (this.isSimulcastOn()) {
  2022. // eslint-disable-next-line no-param-reassign
  2023. description = this.simulcast.mungeRemoteDescription(description);
  2024. // eslint-disable-next-line no-param-reassign
  2025. description = this.tpcUtils.insertUnifiedPlanSimulcastReceive(description);
  2026. this.trace(
  2027. 'setRemoteDescription::postTransform (sim receive)',
  2028. dumpSDP(description));
  2029. // eslint-disable-next-line no-param-reassign
  2030. description = this.tpcUtils.ensureCorrectOrderOfSsrcs(description);
  2031. }
  2032. }
  2033. return new Promise((resolve, reject) => {
  2034. this.peerconnection.setRemoteDescription(description)
  2035. .then(() => {
  2036. this.trace('setRemoteDescriptionOnSuccess');
  2037. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  2038. if (remoteUfrag !== this.remoteUfrag) {
  2039. this.remoteUfrag = remoteUfrag;
  2040. this.eventEmitter.emit(
  2041. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  2042. }
  2043. resolve();
  2044. }, err => {
  2045. this.trace('setRemoteDescriptionOnFailure', err);
  2046. this.eventEmitter.emit(
  2047. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  2048. err,
  2049. this);
  2050. reject(err);
  2051. });
  2052. });
  2053. };
  2054. /**
  2055. * Changes the resolution of the video stream that is sent to the peer based on
  2056. * the user preferred value. If simulcast is enabled on the peerconection, all the
  2057. * simulcast encodings that have a resolution height lower or equal to the value
  2058. * provided will remain active. For the non-simulcast case, video constraint is
  2059. * applied on the track.
  2060. * @param {number} frameHeight - The user preferred max frame height.
  2061. * @returns {Promise} promise that will be resolved when the operation is
  2062. * successful and rejected otherwise.
  2063. */
  2064. TraceablePeerConnection.prototype.setSenderVideoConstraint = function(frameHeight = null) {
  2065. if (frameHeight < 0) {
  2066. throw new Error(`Invalid frameHeight: ${frameHeight}`);
  2067. }
  2068. // XXX: This is not yet supported on mobile.
  2069. if (browser.isReactNative()) {
  2070. return Promise.resolve();
  2071. }
  2072. // Need to explicitly check for null as 0 is falsy, but a valid value
  2073. const newHeight = frameHeight === null ? this.senderVideoMaxHeight : frameHeight;
  2074. this.senderVideoMaxHeight = newHeight;
  2075. // If layer suspension is disabled and sender constraint is not configured for the conference,
  2076. // resolve here so that the encodings stay enabled. This can happen in custom apps built using
  2077. // lib-jitsi-meet.
  2078. if (newHeight === null) {
  2079. return Promise.resolve();
  2080. }
  2081. logger.log(`${this} senderVideoMaxHeight: ${newHeight}`);
  2082. const localVideoTrack = this.getLocalVideoTrack();
  2083. if (!localVideoTrack || localVideoTrack.isMuted()) {
  2084. return Promise.resolve();
  2085. }
  2086. const videoSender = this.findSenderByKind(MediaType.VIDEO);
  2087. if (!videoSender) {
  2088. return Promise.resolve();
  2089. }
  2090. const parameters = videoSender.getParameters();
  2091. if (!parameters || !parameters.encodings || !parameters.encodings.length) {
  2092. return Promise.resolve();
  2093. }
  2094. if (this.isSimulcastOn()) {
  2095. // Determine the encodings that need to stay enabled based on the new frameHeight provided.
  2096. this.encodingsEnabledState = this.tpcUtils.getLocalStreamHeightConstraints(localVideoTrack.track)
  2097. .map(height => height <= newHeight);
  2098. // Always keep the LD stream enabled, specifically when the LD stream's resolution is higher than of the
  2099. // requested resolution. This can happen when camera is captured at resolutions higher than 720p but the
  2100. // requested resolution is 180. Since getParameters doesn't give us information about the resolutions
  2101. // of the simulcast encodings, we have to rely on our initial config for the simulcast streams.
  2102. const ldStreamIndex = this.tpcUtils.localStreamEncodingsConfig
  2103. .findIndex(layer => layer.scaleResolutionDownBy === 4.0);
  2104. if (newHeight > 0 && ldStreamIndex !== -1) {
  2105. this.encodingsEnabledState[ldStreamIndex] = true;
  2106. }
  2107. for (const encoding in parameters.encodings) {
  2108. if (parameters.encodings.hasOwnProperty(encoding)) {
  2109. parameters.encodings[encoding].active = this.encodingsEnabledState[encoding];
  2110. }
  2111. }
  2112. this.tpcUtils.updateEncodingsResolution(parameters);
  2113. } else if (newHeight > 0) {
  2114. // Do not scale down the desktop tracks until SendVideoController is able to propagate the sender constraints
  2115. // only on the active media connection. Right now, the sender constraints received on the bridge channel
  2116. // are propagated on both the jvb and p2p connections in cases where they both are active at the same time.
  2117. parameters.encodings[0].scaleResolutionDownBy
  2118. = localVideoTrack.videoType === VideoType.DESKTOP || localVideoTrack.resolution <= newHeight
  2119. ? 1
  2120. : Math.floor(localVideoTrack.resolution / newHeight);
  2121. parameters.encodings[0].active = true;
  2122. } else {
  2123. parameters.encodings[0].scaleResolutionDownBy = undefined;
  2124. parameters.encodings[0].active = false;
  2125. }
  2126. logger.info(`${this} setting max height=${newHeight},encodings=${JSON.stringify(parameters.encodings)}`);
  2127. return videoSender.setParameters(parameters).then(() => {
  2128. localVideoTrack.maxEnabledResolution = newHeight;
  2129. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_MAX_ENABLED_RESOLUTION_CHANGED, localVideoTrack);
  2130. // Max bitrate needs to be reconfigured on the sender in p2p/non-simulcast case if needed when
  2131. // the send resolution changes.
  2132. if (this.isP2P || !this.isSimulcastOn()) {
  2133. return this.setMaxBitRate();
  2134. }
  2135. });
  2136. };
  2137. /**
  2138. * Enables/disables video media transmission on this peer connection. When
  2139. * disabled the SDP video media direction in the local SDP will be adjusted to
  2140. * 'inactive' which means that no data will be sent nor accepted, but
  2141. * the connection should be kept alive.
  2142. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  2143. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  2144. * no effect.
  2145. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  2146. * needs to be executed in order for the changes to take effect or
  2147. * <tt>false</tt> if the given value was the same as the previous one.
  2148. * @public
  2149. */
  2150. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  2151. logger.debug(`${this} video transfer active: ${active}`);
  2152. const changed = this.videoTransferActive !== active;
  2153. this.videoTransferActive = active;
  2154. if (this._usesUnifiedPlan) {
  2155. this.tpcUtils.setVideoTransferActive(active);
  2156. // false means no renegotiation up the chain which is not needed in the Unified mode
  2157. return false;
  2158. }
  2159. return changed;
  2160. };
  2161. /**
  2162. * Sends DTMF tones if possible.
  2163. *
  2164. * @param {string} tones - The DTMF tones string as defined by {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  2165. * @param {number} duration - The amount of time in milliseconds that each DTMF should last. It's 200ms by default.
  2166. * @param {number} interToneGap - The length of time in miliseconds to wait between tones. It's 200ms by default.
  2167. *
  2168. * @returns {void}
  2169. */
  2170. TraceablePeerConnection.prototype.sendTones = function(tones, duration = 200, interToneGap = 200) {
  2171. if (!this._dtmfSender) {
  2172. if (this.peerconnection.getSenders) {
  2173. const rtpSender = this.peerconnection.getSenders().find(s => s.dtmf);
  2174. this._dtmfSender = rtpSender && rtpSender.dtmf;
  2175. this._dtmfSender && logger.info(`${this} initialized DTMFSender using getSenders`);
  2176. }
  2177. if (!this._dtmfSender) {
  2178. const localAudioTrack = Array.from(this.localTracks.values()).find(t => t.isAudioTrack());
  2179. if (this.peerconnection.createDTMFSender && localAudioTrack) {
  2180. this._dtmfSender = this.peerconnection.createDTMFSender(localAudioTrack.getTrack());
  2181. }
  2182. this._dtmfSender && logger.info(`${this} initialized DTMFSender using deprecated createDTMFSender`);
  2183. }
  2184. if (this._dtmfSender) {
  2185. this._dtmfSender.ontonechange = this._onToneChange.bind(this);
  2186. }
  2187. }
  2188. if (this._dtmfSender) {
  2189. if (this._dtmfSender.toneBuffer) {
  2190. this._dtmfTonesQueue.push({
  2191. tones,
  2192. duration,
  2193. interToneGap
  2194. });
  2195. return;
  2196. }
  2197. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2198. } else {
  2199. logger.warn(`${this} sendTones - failed to select DTMFSender`);
  2200. }
  2201. };
  2202. /**
  2203. * Callback ivoked by {@code this._dtmfSender} when it has finished playing
  2204. * a single tone.
  2205. *
  2206. * @param {Object} event - The tonechange event which indicates what characters
  2207. * are left to be played for the current tone.
  2208. * @private
  2209. * @returns {void}
  2210. */
  2211. TraceablePeerConnection.prototype._onToneChange = function(event) {
  2212. // An empty event.tone indicates the current tones have finished playing.
  2213. // Automatically start playing any queued tones on finish.
  2214. if (this._dtmfSender && event.tone === '' && this._dtmfTonesQueue.length) {
  2215. const { tones, duration, interToneGap } = this._dtmfTonesQueue.shift();
  2216. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2217. }
  2218. };
  2219. /**
  2220. * Makes the underlying TraceablePeerConnection generate new SSRC for
  2221. * the recvonly video stream.
  2222. */
  2223. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  2224. const newSSRC = SDPUtil.generateSsrc();
  2225. logger.info(`${this} generated new recvonly SSRC=${newSSRC}`);
  2226. this.sdpConsistency.setPrimarySsrc(newSSRC);
  2227. };
  2228. /**
  2229. * Makes the underlying TraceablePeerConnection forget the current primary video
  2230. * SSRC.
  2231. */
  2232. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  2233. logger.info(`${this} Clearing primary video SSRC!`);
  2234. this.sdpConsistency.clearVideoSsrcCache();
  2235. };
  2236. /**
  2237. * Closes underlying WebRTC PeerConnection instance and removes all remote
  2238. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  2239. * them.
  2240. */
  2241. TraceablePeerConnection.prototype.close = function() {
  2242. this.trace('stop');
  2243. // Off SignalingEvents
  2244. this.signalingLayer.off(SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  2245. this.signalingLayer.off(SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  2246. this._usesUnifiedPlan && this.peerconnection.removeEventListener('track', this.onTrack);
  2247. for (const peerTracks of this.remoteTracks.values()) {
  2248. for (const remoteTrack of peerTracks.values()) {
  2249. this._removeRemoteTrack(remoteTrack);
  2250. }
  2251. }
  2252. this.remoteTracks.clear();
  2253. this._addedStreams = [];
  2254. this._dtmfSender = null;
  2255. this._dtmfTonesQueue = [];
  2256. if (!this.rtc._removePeerConnection(this)) {
  2257. logger.error(`${this} RTC._removePeerConnection returned false`);
  2258. }
  2259. if (this.statsinterval !== null) {
  2260. window.clearInterval(this.statsinterval);
  2261. this.statsinterval = null;
  2262. }
  2263. logger.info(`${this} Closing peerconnection`);
  2264. this.peerconnection.close();
  2265. };
  2266. TraceablePeerConnection.prototype.createAnswer = function(constraints) {
  2267. return this._createOfferOrAnswer(false /* answer */, constraints);
  2268. };
  2269. TraceablePeerConnection.prototype.createOffer = function(constraints) {
  2270. return this._createOfferOrAnswer(true /* offer */, constraints);
  2271. };
  2272. TraceablePeerConnection.prototype._createOfferOrAnswer = function(
  2273. isOffer,
  2274. constraints) {
  2275. const logName = isOffer ? 'Offer' : 'Answer';
  2276. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  2277. const handleSuccess = (resultSdp, resolveFn, rejectFn) => {
  2278. try {
  2279. this.trace(
  2280. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  2281. if (!this._usesUnifiedPlan) {
  2282. // If there are no local video tracks, then a "recvonly"
  2283. // SSRC needs to be generated
  2284. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  2285. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  2286. this.generateRecvonlySsrc();
  2287. }
  2288. // eslint-disable-next-line no-param-reassign
  2289. resultSdp = new RTCSessionDescription({
  2290. type: resultSdp.type,
  2291. sdp: this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  2292. resultSdp.sdp)
  2293. });
  2294. this.trace(
  2295. `create${logName}OnSuccess::postTransform `
  2296. + '(make primary audio/video ssrcs consistent)',
  2297. dumpSDP(resultSdp));
  2298. }
  2299. // Configure simulcast for camera tracks always and for desktop tracks only when
  2300. // the "capScreenshareBitrate" flag in config.js is disabled.
  2301. if (this.isSimulcastOn() && browser.usesSdpMungingForSimulcast()
  2302. && (!this.options.capScreenshareBitrate
  2303. || (this.options.capScreenshareBitrate && !this._isSharingScreen()))) {
  2304. // eslint-disable-next-line no-param-reassign
  2305. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  2306. this.trace(
  2307. `create${logName}`
  2308. + 'OnSuccess::postTransform (simulcast)',
  2309. dumpSDP(resultSdp));
  2310. }
  2311. if (!this.options.disableRtx && browser.usesSdpMungingForSimulcast()) {
  2312. // eslint-disable-next-line no-param-reassign
  2313. resultSdp = new RTCSessionDescription({
  2314. type: resultSdp.type,
  2315. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  2316. });
  2317. this.trace(
  2318. `create${logName}`
  2319. + 'OnSuccess::postTransform (rtx modifier)',
  2320. dumpSDP(resultSdp));
  2321. }
  2322. const ssrcMap = extractSSRCMap(resultSdp);
  2323. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  2324. this._processLocalSSRCsMap(ssrcMap);
  2325. resolveFn(resultSdp);
  2326. } catch (e) {
  2327. this.trace(`create${logName}OnError`, e);
  2328. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  2329. logger.error(`${this} create${logName}OnError`, e, dumpSDP(resultSdp));
  2330. rejectFn(e);
  2331. }
  2332. };
  2333. const handleFailure = (err, rejectFn) => {
  2334. this.trace(`create${logName}OnFailure`, err);
  2335. const eventType
  2336. = isOffer
  2337. ? RTCEvents.CREATE_OFFER_FAILED
  2338. : RTCEvents.CREATE_ANSWER_FAILED;
  2339. this.eventEmitter.emit(eventType, err, this);
  2340. rejectFn(err);
  2341. };
  2342. // Set the codec preference before creating an offer or answer so that the generated SDP will have
  2343. // the correct preference order.
  2344. if (this._usesTransceiverCodecPreferences) {
  2345. const transceiver = this.peerconnection.getTransceivers()
  2346. .find(t => t.receiver && t.receiver?.track?.kind === MediaType.VIDEO);
  2347. if (transceiver) {
  2348. let capabilities = RTCRtpReceiver.getCapabilities(MediaType.VIDEO)?.codecs;
  2349. const mimeType = this.codecPreference?.mimeType;
  2350. const enable = this.codecPreference?.enable;
  2351. if (capabilities && mimeType && enable) {
  2352. // Move the desired codec (all variations of it as well) to the beginning of the list.
  2353. /* eslint-disable-next-line arrow-body-style */
  2354. capabilities.sort(caps => {
  2355. return caps.mimeType.toLowerCase() === `${MediaType.VIDEO}/${mimeType}` ? -1 : 1;
  2356. });
  2357. } else if (capabilities && mimeType) {
  2358. capabilities = capabilities
  2359. .filter(caps => caps.mimeType.toLowerCase() !== `${MediaType.VIDEO}/${mimeType}`);
  2360. }
  2361. try {
  2362. transceiver.setCodecPreferences(capabilities);
  2363. } catch (err) {
  2364. logger.warn(`${this} Setting codec[preference=${mimeType},enable=${enable}] failed`, err);
  2365. }
  2366. }
  2367. }
  2368. return new Promise((resolve, reject) => {
  2369. let oaPromise;
  2370. if (isOffer) {
  2371. oaPromise = this.peerconnection.createOffer(constraints);
  2372. } else {
  2373. oaPromise = this.peerconnection.createAnswer(constraints);
  2374. }
  2375. oaPromise
  2376. .then(
  2377. sdp => handleSuccess(sdp, resolve, reject),
  2378. error => handleFailure(error, reject));
  2379. });
  2380. };
  2381. /**
  2382. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  2383. * @param {TrackSSRCInfo} ssrcObj
  2384. * @return {number|null} the primary SSRC or <tt>null</tt>
  2385. */
  2386. TraceablePeerConnection.prototype._extractPrimarySSRC = function(ssrcObj) {
  2387. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  2388. return ssrcObj.groups[0].ssrcs[0];
  2389. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  2390. return ssrcObj.ssrcs[0];
  2391. }
  2392. return null;
  2393. };
  2394. /**
  2395. * Goes over the SSRC map extracted from the latest local description and tries
  2396. * to match them with the local tracks (by MSID). Will update the values
  2397. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  2398. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  2399. * @private
  2400. */
  2401. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  2402. for (const track of this.localTracks.values()) {
  2403. const trackMSID = track.storedMSID;
  2404. if (ssrcMap.has(trackMSID)) {
  2405. const newSSRC = ssrcMap.get(trackMSID);
  2406. if (!newSSRC) {
  2407. logger.error(`${this} No SSRC found for stream=${trackMSID}`);
  2408. return;
  2409. }
  2410. const oldSSRC = this.localSSRCs.get(track.rtcId);
  2411. const newSSRCNum = this._extractPrimarySSRC(newSSRC);
  2412. const oldSSRCNum = this._extractPrimarySSRC(oldSSRC);
  2413. // eslint-disable-next-line no-negated-condition
  2414. if (newSSRCNum !== oldSSRCNum) {
  2415. oldSSRCNum && logger.error(`${this} Overwriting SSRC for [track=${track},id=${trackMSID}]`
  2416. + ` with ssrc=${newSSRC}`);
  2417. this.localSSRCs.set(track.rtcId, newSSRC);
  2418. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_SSRC_UPDATED, track, newSSRCNum);
  2419. }
  2420. } else if (!track.isVideoTrack() && !track.isMuted()) {
  2421. // It is normal to find no SSRCs for a muted video track in
  2422. // the local SDP as the recv-only SSRC is no longer munged in.
  2423. // So log the warning only if it's not a muted video track.
  2424. logger.warn(`${this} No SSRCs found in the local SDP for track[track=${track},id=${trackMSID}]`);
  2425. }
  2426. }
  2427. };
  2428. TraceablePeerConnection.prototype.addIceCandidate = function(candidate) {
  2429. this.trace('addIceCandidate', JSON.stringify({
  2430. candidate: candidate.candidate,
  2431. sdpMid: candidate.sdpMid,
  2432. sdpMLineIndex: candidate.sdpMLineIndex,
  2433. usernameFragment: candidate.usernameFragment
  2434. }, null, ' '));
  2435. return this.peerconnection.addIceCandidate(candidate);
  2436. };
  2437. /**
  2438. * Returns the number of simulcast streams that are currently enabled on the peerconnection.
  2439. *
  2440. * @returns {number} The number of simulcast streams currently enabled or 1 when simulcast is disabled.
  2441. */
  2442. TraceablePeerConnection.prototype.getActiveSimulcastStreams = function() {
  2443. let activeStreams = 1;
  2444. if (this.isSimulcastOn() && this.encodingsEnabledState) {
  2445. activeStreams = this.encodingsEnabledState.filter(stream => Boolean(stream))?.length;
  2446. } else if (this.isSimulcastOn()) {
  2447. activeStreams = SIM_LAYER_RIDS.length;
  2448. }
  2449. return activeStreams;
  2450. };
  2451. /**
  2452. * Obtains call-related stats from the peer connection.
  2453. *
  2454. * @returns {Promise<Object>} Promise which resolves with data providing statistics about
  2455. * the peerconnection.
  2456. */
  2457. TraceablePeerConnection.prototype.getStats = function() {
  2458. return this.peerconnection.getStats();
  2459. };
  2460. /**
  2461. * Generates and stores new SSRC info object for given local track.
  2462. * The method should be called only for a video track being added to this TPC
  2463. * in the muted state (given that the current browser uses this strategy).
  2464. * @param {JitsiLocalTrack} track
  2465. * @return {TPCSSRCInfo}
  2466. */
  2467. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  2468. const rtcId = track.rtcId;
  2469. let ssrcInfo = this._getSSRC(rtcId);
  2470. if (ssrcInfo) {
  2471. logger.error(`${this} Overwriting local SSRCs for track id=${rtcId}`);
  2472. }
  2473. // Configure simulcast for camera tracks always and for desktop tracks only when
  2474. // the "capScreenshareBitrate" flag in config.js is disabled.
  2475. if (this.isSimulcastOn()
  2476. && (!this.options.capScreenshareBitrate
  2477. || (this.options.capScreenshareBitrate && !this._isSharingScreen()))) {
  2478. ssrcInfo = {
  2479. ssrcs: [],
  2480. groups: []
  2481. };
  2482. for (let i = 0; i < SIM_LAYER_RIDS.length; i++) {
  2483. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  2484. }
  2485. ssrcInfo.groups.push({
  2486. ssrcs: ssrcInfo.ssrcs.slice(),
  2487. semantics: 'SIM'
  2488. });
  2489. } else {
  2490. ssrcInfo = {
  2491. ssrcs: [ SDPUtil.generateSsrc() ],
  2492. groups: []
  2493. };
  2494. }
  2495. if (!this.options.disableRtx) {
  2496. // Specifically use a for loop here because we'll
  2497. // be adding to the list we're iterating over, so we
  2498. // only want to iterate through the items originally
  2499. // on the list
  2500. const currNumSsrcs = ssrcInfo.ssrcs.length;
  2501. for (let i = 0; i < currNumSsrcs; ++i) {
  2502. const primarySsrc = ssrcInfo.ssrcs[i];
  2503. const rtxSsrc = SDPUtil.generateSsrc();
  2504. ssrcInfo.ssrcs.push(rtxSsrc);
  2505. ssrcInfo.groups.push({
  2506. ssrcs: [ primarySsrc, rtxSsrc ],
  2507. semantics: 'FID'
  2508. });
  2509. }
  2510. }
  2511. ssrcInfo.msid = track.storedMSID;
  2512. this.localSSRCs.set(rtcId, ssrcInfo);
  2513. return ssrcInfo;
  2514. };
  2515. /**
  2516. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2517. * instance.
  2518. * @return {string}
  2519. */
  2520. TraceablePeerConnection.prototype.toString = function() {
  2521. return `TPC[id=${this.id},type=${this.isP2P ? 'P2P' : 'JVB'}]`;
  2522. };