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

TraceablePeerConnection.js 105KB

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