modified lib-jitsi-meet dev repo
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

TraceablePeerConnection.js 113KB

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