modified lib-jitsi-meet dev repo
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TraceablePeerConnection.js 109KB

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