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

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