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

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