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

TraceablePeerConnection.js 115KB

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