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

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