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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510
  1. /* global __filename, RTCSessionDescription */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import transform from 'sdp-transform';
  4. import * as GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  5. import JitsiRemoteTrack from './JitsiRemoteTrack';
  6. import * as MediaType from '../../service/RTC/MediaType';
  7. import LocalSdpMunger from './LocalSdpMunger';
  8. import RTC from './RTC';
  9. import RTCUtils from './RTCUtils';
  10. import browser from '../browser';
  11. import RTCEvents from '../../service/RTC/RTCEvents';
  12. import RtxModifier from '../xmpp/RtxModifier';
  13. // FIXME SDP tools should end up in some kind of util module
  14. import SDP from '../xmpp/SDP';
  15. import SdpConsistency from '../xmpp/SdpConsistency';
  16. import { SdpTransformWrap } from '../xmpp/SdpTransformUtil';
  17. import SDPUtil from '../xmpp/SDPUtil';
  18. import * as SignalingEvents from '../../service/RTC/SignalingEvents';
  19. const logger = getLogger(__filename);
  20. const SIMULCAST_LAYERS = 3;
  21. const SIM_LAYER_1_RID = '1';
  22. const SIM_LAYER_2_RID = '2';
  23. const SIM_LAYER_3_RID = '3';
  24. const SIM_LAYER_RIDS = [ SIM_LAYER_1_RID, SIM_LAYER_2_RID, SIM_LAYER_3_RID ];
  25. /* eslint-disable max-params */
  26. /**
  27. * Creates new instance of 'TraceablePeerConnection'.
  28. *
  29. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  30. * @param {number} id the peer connection id assigned by the parent RTC module.
  31. * @param {SignalingLayer} signalingLayer the signaling layer instance
  32. * @param {object} iceConfig WebRTC 'PeerConnection' ICE config
  33. * @param {object} constraints WebRTC 'PeerConnection' constraints
  34. * @param {boolean} isP2P indicates whether or not the new instance will be used
  35. * in a peer to peer connection
  36. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  37. * @param {boolean} options.disableSimulcast if set to 'true' will disable
  38. * the simulcast.
  39. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX
  40. * @param {boolean} options.enableFirefoxSimulcast if set to 'true' will enable
  41. * experimental simulcast support on Firefox.
  42. * @param {boolean} options.disableH264 If set to 'true' H264 will be
  43. * disabled by removing it from the SDP.
  44. * @param {boolean} options.preferH264 if set to 'true' H264 will be preferred
  45. * over other video codecs.
  46. * @param {boolean} options.enableLayerSuspension if set to 'true', we will
  47. * cap the video send bitrate when we are told we have not been selected by
  48. * any endpoints (and therefore the non-thumbnail streams are not in use).
  49. *
  50. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  51. * debug the peer connection. Since many other responsibilities have been added
  52. * it would make sense to extract a separate class from it and come up with
  53. * a more suitable name.
  54. *
  55. * @constructor
  56. */
  57. export default function TraceablePeerConnection(
  58. rtc,
  59. id,
  60. signalingLayer,
  61. iceConfig,
  62. constraints,
  63. isP2P,
  64. options) {
  65. /**
  66. * Indicates whether or not this peer connection instance is actively
  67. * sending/receiving audio media. When set to <tt>false</tt> the SDP audio
  68. * media direction will be adjusted to 'inactive' in order to suspend
  69. * the transmission.
  70. * @type {boolean}
  71. * @private
  72. */
  73. this.audioTransferActive = true;
  74. /**
  75. * Indicates whether or not this peer connection instance is actively
  76. * sending/receiving video media. When set to <tt>false</tt> the SDP video
  77. * media direction will be adjusted to 'inactive' in order to suspend
  78. * the transmission.
  79. * @type {boolean}
  80. * @private
  81. */
  82. this.videoTransferActive = true;
  83. /**
  84. * The parent instance of RTC service which created this
  85. * <tt>TracablePeerConnection</tt>.
  86. * @type {RTC}
  87. */
  88. this.rtc = rtc;
  89. /**
  90. * The peer connection identifier assigned by the RTC module.
  91. * @type {number}
  92. */
  93. this.id = id;
  94. /**
  95. * Indicates whether or not this instance is used in a peer to peer
  96. * connection.
  97. * @type {boolean}
  98. */
  99. this.isP2P = isP2P;
  100. // FIXME: We should support multiple streams per jid.
  101. /**
  102. * The map holds remote tracks associated with this peer connection.
  103. * It maps user's JID to media type and remote track
  104. * (one track per media type per user's JID).
  105. * @type {Map<string, Map<MediaType, JitsiRemoteTrack>>}
  106. */
  107. this.remoteTracks = new Map();
  108. /**
  109. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  110. * @type {Map<number, JitsiLocalTrack>}
  111. */
  112. this.localTracks = new Map();
  113. /**
  114. * Keeps tracks of the WebRTC <tt>MediaStream</tt>s that have been added to
  115. * the underlying WebRTC PeerConnection.
  116. * @type {Array}
  117. * @private
  118. */
  119. this._addedStreams = [];
  120. /**
  121. * @typedef {Object} TPCGroupInfo
  122. * @property {string} semantics the SSRC groups semantics
  123. * @property {Array<number>} ssrcs group's SSRCs in order where the first
  124. * one is group's primary SSRC, the second one is secondary (RTX) and so
  125. * on...
  126. */
  127. /**
  128. * @typedef {Object} TPCSSRCInfo
  129. * @property {Array<number>} ssrcs an array which holds all track's SSRCs
  130. * @property {Array<TPCGroupInfo>} groups an array stores all track's SSRC
  131. * groups
  132. */
  133. /**
  134. * Holds the info about local track's SSRCs mapped per their
  135. * {@link JitsiLocalTrack.rtcId}
  136. * @type {Map<number, TPCSSRCInfo>}
  137. */
  138. this.localSSRCs = new Map();
  139. /**
  140. * The local ICE username fragment for this session.
  141. */
  142. this.localUfrag = null;
  143. /**
  144. * The remote ICE username fragment for this session.
  145. */
  146. this.remoteUfrag = null;
  147. /**
  148. * The signaling layer which operates this peer connection.
  149. * @type {SignalingLayer}
  150. */
  151. this.signalingLayer = signalingLayer;
  152. // SignalingLayer listeners
  153. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  154. this.signalingLayer.on(
  155. SignalingEvents.PEER_VIDEO_TYPE_CHANGED,
  156. this._peerVideoTypeChanged);
  157. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  158. this.signalingLayer.on(
  159. SignalingEvents.PEER_MUTED_CHANGED,
  160. this._peerMutedChanged);
  161. this.options = options;
  162. this.peerconnection
  163. = new RTCUtils.RTCPeerConnectionType(iceConfig, constraints);
  164. this.updateLog = [];
  165. this.stats = {};
  166. this.statsinterval = null;
  167. /**
  168. * @type {number} The max number of stats to keep in this.stats. Limit to
  169. * 300 values, i.e. 5 minutes; set to 0 to disable
  170. */
  171. this.maxstats = options.maxstats;
  172. const Interop = require('@jitsi/sdp-interop').Interop;
  173. this.interop = new Interop();
  174. const Simulcast = require('@jitsi/sdp-simulcast');
  175. this.simulcast = new Simulcast({ numOfLayers: SIMULCAST_LAYERS,
  176. explodeRemoteSimulcast: false });
  177. this.sdpConsistency = new SdpConsistency(this.toString());
  178. /**
  179. * Munges local SDP provided to the Jingle Session in order to prevent from
  180. * sending SSRC updates on attach/detach and mute/unmute (for video).
  181. * @type {LocalSdpMunger}
  182. */
  183. this.localSdpMunger = new LocalSdpMunger(this);
  184. /**
  185. * TracablePeerConnection uses RTC's eventEmitter
  186. * @type {EventEmitter}
  187. */
  188. this.eventEmitter = rtc.eventEmitter;
  189. this.rtxModifier = new RtxModifier();
  190. // override as desired
  191. this.trace = (what, info) => {
  192. logger.debug(what, info);
  193. this.updateLog.push({
  194. time: new Date(),
  195. type: what,
  196. value: info || ''
  197. });
  198. };
  199. this.onicecandidate = null;
  200. this.peerconnection.onicecandidate = event => {
  201. this.trace(
  202. 'onicecandidate',
  203. JSON.stringify(event.candidate, null, ' '));
  204. if (this.onicecandidate !== null) {
  205. this.onicecandidate(event);
  206. }
  207. };
  208. this.peerconnection.onaddstream
  209. = event => this._remoteStreamAdded(event.stream);
  210. this.peerconnection.onremovestream
  211. = event => this._remoteStreamRemoved(event.stream);
  212. this.onsignalingstatechange = null;
  213. this.peerconnection.onsignalingstatechange = event => {
  214. this.trace('onsignalingstatechange', this.signalingState);
  215. if (this.onsignalingstatechange !== null) {
  216. this.onsignalingstatechange(event);
  217. }
  218. };
  219. this.oniceconnectionstatechange = null;
  220. this.peerconnection.oniceconnectionstatechange = event => {
  221. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  222. if (this.oniceconnectionstatechange !== null) {
  223. this.oniceconnectionstatechange(event);
  224. }
  225. };
  226. this.onnegotiationneeded = null;
  227. this.peerconnection.onnegotiationneeded = event => {
  228. this.trace('onnegotiationneeded');
  229. if (this.onnegotiationneeded !== null) {
  230. this.onnegotiationneeded(event);
  231. }
  232. };
  233. this.ondatachannel = null;
  234. this.peerconnection.ondatachannel = event => {
  235. this.trace('ondatachannel');
  236. if (this.ondatachannel !== null) {
  237. this.ondatachannel(event);
  238. }
  239. };
  240. if (this.maxstats) {
  241. this.statsinterval = window.setInterval(() => {
  242. this.getStats(stats => {
  243. if (stats.result
  244. && typeof stats.result === 'function') {
  245. const results = stats.result();
  246. for (let i = 0; i < results.length; ++i) {
  247. const res = results[i];
  248. res.names().forEach(name => {
  249. this._processStat(res, name, res.stat(name));
  250. });
  251. }
  252. } else {
  253. stats.forEach(r => this._processStat(r, '', r));
  254. }
  255. }, () => {
  256. // empty error callback
  257. });
  258. }, 1000);
  259. }
  260. logger.info(`Create new ${this}`);
  261. }
  262. /* eslint-enable max-params */
  263. /**
  264. * Process stat and adds it to the array of stats we store.
  265. * @param report the current stats report.
  266. * @param name the name of the report, if available
  267. * @param statValue the value to add.
  268. * @private
  269. */
  270. TraceablePeerConnection.prototype._processStat
  271. = function(report, name, statValue) {
  272. const id = `${report.id}-${name}`;
  273. let s = this.stats[id];
  274. const now = new Date();
  275. if (!s) {
  276. this.stats[id] = s = {
  277. startTime: now,
  278. endTime: now,
  279. values: [],
  280. times: []
  281. };
  282. }
  283. s.values.push(statValue);
  284. s.times.push(now.getTime());
  285. if (s.values.length > this.maxstats) {
  286. s.values.shift();
  287. s.times.shift();
  288. }
  289. s.endTime = now;
  290. };
  291. /**
  292. * Returns a string representation of a SessionDescription object.
  293. */
  294. const dumpSDP = function(description) {
  295. if (typeof description === 'undefined' || description === null) {
  296. return '';
  297. }
  298. return `type: ${description.type}\r\n${description.sdp}`;
  299. };
  300. /**
  301. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  302. * will convert "completed" into "connected" where both mean that the ICE has
  303. * succeeded and is up and running. We never see "completed" state for
  304. * the JVB connection, but it started appearing for the P2P one. This method
  305. * allows to adapt old logic to this new situation.
  306. * @return {string}
  307. */
  308. TraceablePeerConnection.prototype.getConnectionState = function() {
  309. const state = this.peerconnection.iceConnectionState;
  310. if (state === 'completed') {
  311. return 'connected';
  312. }
  313. return state;
  314. };
  315. /**
  316. * Obtains the media direction for given {@link MediaType}. The method takes
  317. * into account whether or not there are any local tracks for media and
  318. * the {@link audioTransferActive} and {@link videoTransferActive} flags.
  319. * @param {MediaType} mediaType
  320. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly'
  321. * etc.) which should be used when setting local description on the peer
  322. * connection.
  323. * @private
  324. */
  325. TraceablePeerConnection.prototype._getDesiredMediaDirection = function(
  326. mediaType) {
  327. let mediaTransferActive = true;
  328. if (mediaType === MediaType.AUDIO) {
  329. mediaTransferActive = this.audioTransferActive;
  330. } else if (mediaType === MediaType.VIDEO) {
  331. mediaTransferActive = this.videoTransferActive;
  332. }
  333. if (mediaTransferActive) {
  334. return this.hasAnyTracksOfType(mediaType) ? 'sendrecv' : 'recvonly';
  335. }
  336. return 'inactive';
  337. };
  338. /**
  339. * Tells whether or not this TPC instance is using Simulcast.
  340. * @return {boolean} <tt>true</tt> if simulcast is enabled and active or
  341. * <tt>false</tt> if it's turned off.
  342. */
  343. TraceablePeerConnection.prototype.isSimulcastOn = function() {
  344. return !this.options.disableSimulcast
  345. && browser.supportsSimulcast()
  346. // Firefox has been added as supporting simulcast, but it is
  347. // experimental so we only want to do it for firefox if the config
  348. // option is set. Unfortunately, browser::supportsSimulcast()
  349. // doesn't have a reference to the config options, so we have
  350. // to do it here
  351. && (!browser.isFirefox()
  352. || this.options.enableFirefoxSimulcast);
  353. };
  354. /**
  355. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  356. * @param {string} endpointId the video owner's ID (MUC nickname)
  357. * @param {VideoType} videoType the new value
  358. * @private
  359. */
  360. TraceablePeerConnection.prototype._peerVideoTypeChanged = function(
  361. endpointId,
  362. videoType) {
  363. // Check if endpointId has a value to avoid action on random track
  364. if (!endpointId) {
  365. logger.error(`No endpointID on peerVideoTypeChanged ${this}`);
  366. return;
  367. }
  368. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  369. if (videoTrack.length) {
  370. // NOTE 1 track per media type is assumed
  371. videoTrack[0]._setVideoType(videoType);
  372. }
  373. };
  374. /**
  375. * Handles remote track mute / unmute events.
  376. * @param {string} endpointId the track owner's identifier (MUC nickname)
  377. * @param {MediaType} mediaType "audio" or "video"
  378. * @param {boolean} isMuted the new mute state
  379. * @private
  380. */
  381. TraceablePeerConnection.prototype._peerMutedChanged = function(
  382. endpointId,
  383. mediaType,
  384. isMuted) {
  385. // Check if endpointId is a value to avoid doing action on all remote tracks
  386. if (!endpointId) {
  387. logger.error('On peerMuteChanged - no endpoint ID');
  388. return;
  389. }
  390. const track = this.getRemoteTracks(endpointId, mediaType);
  391. if (track.length) {
  392. // NOTE 1 track per media type is assumed
  393. track[0].setMute(isMuted);
  394. }
  395. };
  396. /**
  397. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  398. * argument is omitted the list of all local tracks will be returned.
  399. * @param {MediaType} [mediaType]
  400. * @return {Array<JitsiLocalTrack>}
  401. */
  402. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  403. let tracks = Array.from(this.localTracks.values());
  404. if (mediaType !== undefined) {
  405. tracks = tracks.filter(track => track.getType() === mediaType);
  406. }
  407. return tracks;
  408. };
  409. /**
  410. * Checks whether or not this {@link TraceablePeerConnection} instance contains
  411. * any local tracks for given <tt>mediaType</tt>.
  412. * @param {MediaType} mediaType
  413. * @return {boolean}
  414. */
  415. TraceablePeerConnection.prototype.hasAnyTracksOfType = function(mediaType) {
  416. if (!mediaType) {
  417. throw new Error('"mediaType" is required');
  418. }
  419. return this.getLocalTracks(mediaType).length > 0;
  420. };
  421. /**
  422. * Obtains all remote tracks currently known to this PeerConnection instance.
  423. * @param {string} [endpointId] the track owner's identifier (MUC nickname)
  424. * @param {MediaType} [mediaType] the remote tracks will be filtered
  425. * by their media type if this argument is specified.
  426. * @return {Array<JitsiRemoteTrack>}
  427. */
  428. TraceablePeerConnection.prototype.getRemoteTracks = function(
  429. endpointId,
  430. mediaType) {
  431. const remoteTracks = [];
  432. const endpoints
  433. = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  434. for (const endpoint of endpoints) {
  435. const endpointTrackMap = this.remoteTracks.get(endpoint);
  436. if (!endpointTrackMap) {
  437. // Otherwise an empty Map() would have to be allocated above
  438. // eslint-disable-next-line no-continue
  439. continue;
  440. }
  441. for (const trackMediaType of endpointTrackMap.keys()) {
  442. // per media type filtering
  443. if (!mediaType || mediaType === trackMediaType) {
  444. const mediaTrack = endpointTrackMap.get(trackMediaType);
  445. if (mediaTrack) {
  446. remoteTracks.push(mediaTrack);
  447. }
  448. }
  449. }
  450. }
  451. return remoteTracks;
  452. };
  453. /**
  454. * Tries to find {@link JitsiTrack} for given SSRC number. It will search both
  455. * local and remote tracks bound to this instance.
  456. * @param {number} ssrc
  457. * @return {JitsiTrack|null}
  458. */
  459. TraceablePeerConnection.prototype.getTrackBySSRC = function(ssrc) {
  460. if (typeof ssrc !== 'number') {
  461. throw new Error(`SSRC ${ssrc} is not a number`);
  462. }
  463. for (const localTrack of this.localTracks.values()) {
  464. if (this.getLocalSSRC(localTrack) === ssrc) {
  465. return localTrack;
  466. }
  467. }
  468. for (const remoteTrack of this.getRemoteTracks()) {
  469. if (remoteTrack.getSSRC() === ssrc) {
  470. return remoteTrack;
  471. }
  472. }
  473. return null;
  474. };
  475. /**
  476. * Tries to find SSRC number for given {@link JitsiTrack} id. It will search
  477. * both local and remote tracks bound to this instance.
  478. * @param {string} id
  479. * @return {number|null}
  480. */
  481. TraceablePeerConnection.prototype.getSsrcByTrackId = function(id) {
  482. const findTrackById = track => track.getTrack().id === id;
  483. const localTrack = this.getLocalTracks().find(findTrackById);
  484. if (localTrack) {
  485. return this.getLocalSSRC(localTrack);
  486. }
  487. const remoteTrack = this.getRemoteTracks().find(findTrackById);
  488. if (remoteTrack) {
  489. return remoteTrack.getSSRC();
  490. }
  491. return null;
  492. };
  493. /**
  494. * Called when new remote MediaStream is added to the PeerConnection.
  495. * @param {MediaStream} stream the WebRTC MediaStream for remote participant
  496. */
  497. TraceablePeerConnection.prototype._remoteStreamAdded = function(stream) {
  498. const streamId = RTC.getStreamID(stream);
  499. if (!RTC.isUserStreamById(streamId)) {
  500. logger.info(
  501. `${this} ignored remote 'stream added' event for non-user stream`
  502. + `id: ${streamId}`);
  503. return;
  504. }
  505. // Bind 'addtrack'/'removetrack' event handlers
  506. if (browser.isChromiumBased() || browser.isEdge()) {
  507. stream.onaddtrack = event => {
  508. this._remoteTrackAdded(stream, event.track);
  509. };
  510. stream.onremovetrack = event => {
  511. this._remoteTrackRemoved(stream, event.track);
  512. };
  513. }
  514. // Call remoteTrackAdded for each track in the stream
  515. const streamAudioTracks = stream.getAudioTracks();
  516. for (const audioTrack of streamAudioTracks) {
  517. this._remoteTrackAdded(stream, audioTrack);
  518. }
  519. const streamVideoTracks = stream.getVideoTracks();
  520. for (const videoTrack of streamVideoTracks) {
  521. this._remoteTrackAdded(stream, videoTrack);
  522. }
  523. };
  524. /**
  525. * Called on "track added" and "stream added" PeerConnection events (because we
  526. * handle streams on per track basis). Finds the owner and the SSRC for
  527. * the track and passes that to ChatRoom for further processing.
  528. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  529. * the parent of the track
  530. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  531. * participant
  532. */
  533. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  534. const streamId = RTC.getStreamID(stream);
  535. const mediaType = track.kind;
  536. logger.info(`${this} remote track added:`, streamId, mediaType);
  537. // look up an associated JID for a stream id
  538. if (!mediaType) {
  539. GlobalOnErrorHandler.callErrorHandler(
  540. new Error(
  541. `MediaType undefined for remote track, stream id: ${streamId}`
  542. ));
  543. // Abort
  544. return;
  545. }
  546. const remoteSDP = new SDP(this.remoteDescription.sdp);
  547. const mediaLines
  548. = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  549. if (!mediaLines.length) {
  550. GlobalOnErrorHandler.callErrorHandler(
  551. new Error(
  552. `No media lines for type ${
  553. mediaType} found in remote SDP for remote track: ${
  554. streamId}`));
  555. // Abort
  556. return;
  557. }
  558. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  559. ssrcLines
  560. = ssrcLines.filter(line => line.indexOf(`msid:${streamId}`) !== -1);
  561. if (!ssrcLines.length) {
  562. GlobalOnErrorHandler.callErrorHandler(
  563. new Error(
  564. `No SSRC lines for streamId ${
  565. streamId} for remote track, media type: ${mediaType}`));
  566. // Abort
  567. return;
  568. }
  569. // FIXME the length of ssrcLines[0] not verified, but it will fail
  570. // with global error handler anyway
  571. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  572. const trackSsrc = Number(ssrcStr);
  573. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  574. if (isNaN(trackSsrc) || trackSsrc < 0) {
  575. GlobalOnErrorHandler.callErrorHandler(
  576. new Error(
  577. `Invalid SSRC: ${ssrcStr} for remote track, msid: ${
  578. streamId} media type: ${mediaType}`));
  579. // Abort
  580. return;
  581. } else if (!ownerEndpointId) {
  582. GlobalOnErrorHandler.callErrorHandler(
  583. new Error(
  584. `No SSRC owner known for: ${
  585. trackSsrc} for remote track, msid: ${
  586. streamId} media type: ${mediaType}`));
  587. // Abort
  588. return;
  589. }
  590. logger.log(`${this} associated ssrc`, ownerEndpointId, trackSsrc);
  591. const peerMediaInfo
  592. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  593. if (!peerMediaInfo) {
  594. GlobalOnErrorHandler.callErrorHandler(
  595. new Error(
  596. `${this}: no peer media info available for ${
  597. ownerEndpointId}`));
  598. return;
  599. }
  600. const muted = peerMediaInfo.muted;
  601. const videoType = peerMediaInfo.videoType; // can be undefined
  602. this._createRemoteTrack(
  603. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  604. };
  605. // FIXME cleanup params
  606. /* eslint-disable max-params */
  607. /**
  608. * Initializes a new JitsiRemoteTrack instance with the data provided by
  609. * the signaling layer and SDP.
  610. *
  611. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  612. * @param {MediaStream} stream the WebRTC stream instance
  613. * @param {MediaStreamTrack} track the WebRTC track instance
  614. * @param {MediaType} mediaType the track's type of the media
  615. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  616. * @param {number} ssrc the track's main SSRC number
  617. * @param {boolean} muted the initial muted status
  618. */
  619. TraceablePeerConnection.prototype._createRemoteTrack = function(
  620. ownerEndpointId,
  621. stream,
  622. track,
  623. mediaType,
  624. videoType,
  625. ssrc,
  626. muted) {
  627. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  628. if (!remoteTracksMap) {
  629. remoteTracksMap = new Map();
  630. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  631. }
  632. const existingTrack = remoteTracksMap.get(mediaType);
  633. if (existingTrack && existingTrack.getTrack() === track) {
  634. // Ignore duplicated event which can originate either from
  635. // 'onStreamAdded' or 'onTrackAdded'.
  636. logger.info(
  637. `${this} ignored duplicated remote track added event for: `
  638. + `${ownerEndpointId}, ${mediaType}`);
  639. return;
  640. } else if (existingTrack) {
  641. logger.error(
  642. `${this} overwriting remote track for`
  643. + `${ownerEndpointId} ${mediaType}`);
  644. }
  645. const remoteTrack
  646. = new JitsiRemoteTrack(
  647. this.rtc,
  648. this.rtc.conference,
  649. ownerEndpointId,
  650. stream,
  651. track,
  652. mediaType,
  653. videoType,
  654. ssrc,
  655. muted,
  656. this.isP2P);
  657. remoteTracksMap.set(mediaType, remoteTrack);
  658. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack);
  659. };
  660. /* eslint-enable max-params */
  661. /**
  662. * Handles remote stream removal.
  663. * @param stream the WebRTC MediaStream object which is being removed from the
  664. * PeerConnection
  665. */
  666. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  667. if (!RTC.isUserStream(stream)) {
  668. const id = RTC.getStreamID(stream);
  669. logger.info(
  670. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  671. return;
  672. }
  673. // Call remoteTrackRemoved for each track in the stream
  674. const streamVideoTracks = stream.getVideoTracks();
  675. for (const videoTrack of streamVideoTracks) {
  676. this._remoteTrackRemoved(stream, videoTrack);
  677. }
  678. const streamAudioTracks = stream.getAudioTracks();
  679. for (const audioTrack of streamAudioTracks) {
  680. this._remoteTrackRemoved(stream, audioTrack);
  681. }
  682. };
  683. /**
  684. * Handles remote media track removal.
  685. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  686. * of the track.
  687. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  688. * removed from the PeerConnection.
  689. */
  690. TraceablePeerConnection.prototype._remoteTrackRemoved = function(
  691. stream,
  692. track) {
  693. const streamId = RTC.getStreamID(stream);
  694. const trackId = track && RTC.getTrackID(track);
  695. logger.info(`${this} - remote track removed: ${streamId}, ${trackId}`);
  696. if (!streamId) {
  697. GlobalOnErrorHandler.callErrorHandler(
  698. new Error(`${this} remote track removal failed - no stream ID`));
  699. return;
  700. }
  701. if (!trackId) {
  702. GlobalOnErrorHandler.callErrorHandler(
  703. new Error(`${this} remote track removal failed - no track ID`));
  704. return;
  705. }
  706. if (!this._removeRemoteTrackById(streamId, trackId)) {
  707. // NOTE this warning is always printed when user leaves the room,
  708. // because we remove remote tracks manually on MUC member left event,
  709. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  710. // ignore this warning, but still it's better to keep it printed for
  711. // debugging purposes.
  712. //
  713. // We could change the behaviour to emit track removed only from here,
  714. // but the order of the events will change and consuming apps could
  715. // behave unexpectedly (the "user left" event would come before "track
  716. // removed" events).
  717. logger.warn(
  718. `${this} Removed track not found for msid: ${streamId},
  719. track id: ${trackId}`);
  720. }
  721. };
  722. /**
  723. * Finds remote track by it's stream and track ids.
  724. * @param {string} streamId the media stream id as defined by the WebRTC
  725. * @param {string} trackId the media track id as defined by the WebRTC
  726. * @return {JitsiRemoteTrack|undefined} the track's instance or
  727. * <tt>undefined</tt> if not found.
  728. * @private
  729. */
  730. TraceablePeerConnection.prototype._getRemoteTrackById = function(
  731. streamId,
  732. trackId) {
  733. // .find will break the loop once the first match is found
  734. for (const endpointTrackMap of this.remoteTracks.values()) {
  735. for (const mediaTrack of endpointTrackMap.values()) {
  736. // FIXME verify and try to use ===
  737. /* eslint-disable eqeqeq */
  738. if (mediaTrack.getStreamId() == streamId
  739. && mediaTrack.getTrackId() == trackId) {
  740. return mediaTrack;
  741. }
  742. /* eslint-enable eqeqeq */
  743. }
  744. }
  745. return undefined;
  746. };
  747. /**
  748. * Removes all JitsiRemoteTracks associated with given MUC nickname
  749. * (resource part of the JID). Returns array of removed tracks.
  750. *
  751. * @param {string} owner - The resource part of the MUC JID.
  752. * @returns {JitsiRemoteTrack[]}
  753. */
  754. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  755. const removedTracks = [];
  756. const remoteTracksMap = this.remoteTracks.get(owner);
  757. if (remoteTracksMap) {
  758. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  759. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  760. removedAudioTrack && removedTracks.push(removedAudioTrack);
  761. removedVideoTrack && removedTracks.push(removedVideoTrack);
  762. this.remoteTracks.delete(owner);
  763. }
  764. logger.debug(
  765. `${this} removed remote tracks for ${owner} count: ${
  766. removedTracks.length}`);
  767. return removedTracks;
  768. };
  769. /**
  770. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits
  771. * {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  772. * @param {JitsiRemoteTrack} toBeRemoved
  773. */
  774. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  775. toBeRemoved.dispose();
  776. const participantId = toBeRemoved.getParticipantId();
  777. const remoteTracksMap = this.remoteTracks.get(participantId);
  778. if (!remoteTracksMap) {
  779. logger.error(
  780. `removeRemoteTrack: no remote tracks map for ${participantId}`);
  781. } else if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  782. logger.error(
  783. `Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  784. }
  785. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  786. };
  787. /**
  788. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  789. * track ids.
  790. *
  791. * @param {string} streamId the media stream id as defined by the WebRTC
  792. * @param {string} trackId the media track id as defined by the WebRTC
  793. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  794. * <tt>undefined</tt> if no track matching given stream and track ids was
  795. * found.
  796. */
  797. TraceablePeerConnection.prototype._removeRemoteTrackById = function(
  798. streamId,
  799. trackId) {
  800. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  801. if (toBeRemoved) {
  802. this._removeRemoteTrack(toBeRemoved);
  803. }
  804. return toBeRemoved;
  805. };
  806. /**
  807. * @typedef {Object} SSRCGroupInfo
  808. * @property {Array<number>} ssrcs group's SSRCs
  809. * @property {string} semantics
  810. */
  811. /**
  812. * @typedef {Object} TrackSSRCInfo
  813. * @property {Array<number>} ssrcs track's SSRCs
  814. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  815. */
  816. /**
  817. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  818. * @param {Object} desc the WebRTC SDP instance.
  819. * @return {Map<string,TrackSSRCInfo>}
  820. */
  821. function extractSSRCMap(desc) {
  822. /**
  823. * Track SSRC infos mapped by stream ID (msid)
  824. * @type {Map<string,TrackSSRCInfo>}
  825. */
  826. const ssrcMap = new Map();
  827. /**
  828. * Groups mapped by primary SSRC number
  829. * @type {Map<number,Array<SSRCGroupInfo>>}
  830. */
  831. const groupsMap = new Map();
  832. if (typeof desc !== 'object' || desc === null
  833. || typeof desc.sdp !== 'string') {
  834. logger.warn('An empty description was passed as an argument.');
  835. return ssrcMap;
  836. }
  837. const session = transform.parse(desc.sdp);
  838. if (!Array.isArray(session.media)) {
  839. return ssrcMap;
  840. }
  841. for (const mLine of session.media) {
  842. if (!Array.isArray(mLine.ssrcs)) {
  843. continue; // eslint-disable-line no-continue
  844. }
  845. if (Array.isArray(mLine.ssrcGroups)) {
  846. for (const group of mLine.ssrcGroups) {
  847. if (typeof group.semantics !== 'undefined'
  848. && typeof group.ssrcs !== 'undefined') {
  849. // Parse SSRCs and store as numbers
  850. const groupSSRCs
  851. = group.ssrcs.split(' ').map(
  852. ssrcStr => parseInt(ssrcStr, 10));
  853. const primarySSRC = groupSSRCs[0];
  854. // Note that group.semantics is already present
  855. group.ssrcs = groupSSRCs;
  856. // eslint-disable-next-line max-depth
  857. if (!groupsMap.has(primarySSRC)) {
  858. groupsMap.set(primarySSRC, []);
  859. }
  860. groupsMap.get(primarySSRC).push(group);
  861. }
  862. }
  863. }
  864. for (const ssrc of mLine.ssrcs) {
  865. if (ssrc.attribute !== 'msid') {
  866. continue; // eslint-disable-line no-continue
  867. }
  868. const msid = ssrc.value;
  869. let ssrcInfo = ssrcMap.get(msid);
  870. if (!ssrcInfo) {
  871. ssrcInfo = {
  872. ssrcs: [],
  873. groups: [],
  874. msid
  875. };
  876. ssrcMap.set(msid, ssrcInfo);
  877. }
  878. const ssrcNumber = ssrc.id;
  879. ssrcInfo.ssrcs.push(ssrcNumber);
  880. if (groupsMap.has(ssrcNumber)) {
  881. const ssrcGroups = groupsMap.get(ssrcNumber);
  882. for (const group of ssrcGroups) {
  883. ssrcInfo.groups.push(group);
  884. }
  885. }
  886. }
  887. }
  888. return ssrcMap;
  889. }
  890. /**
  891. * Takes a SessionDescription object and returns a "normalized" version.
  892. * Currently it only takes care of ordering the a=ssrc lines.
  893. */
  894. const normalizePlanB = function(desc) {
  895. if (typeof desc !== 'object' || desc === null
  896. || typeof desc.sdp !== 'string') {
  897. logger.warn('An empty description was passed as an argument.');
  898. return desc;
  899. }
  900. // eslint-disable-next-line no-shadow
  901. const transform = require('sdp-transform');
  902. const session = transform.parse(desc.sdp);
  903. if (typeof session !== 'undefined'
  904. && typeof session.media !== 'undefined'
  905. && Array.isArray(session.media)) {
  906. session.media.forEach(mLine => {
  907. // Chrome appears to be picky about the order in which a=ssrc lines
  908. // are listed in an m-line when rtx is enabled (and thus there are
  909. // a=ssrc-group lines with FID semantics). Specifically if we have
  910. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  911. // the "a=ssrc:S1" lines, SRD fails.
  912. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  913. // first.
  914. const firstSsrcs = [];
  915. const newSsrcLines = [];
  916. if (typeof mLine.ssrcGroups !== 'undefined'
  917. && Array.isArray(mLine.ssrcGroups)) {
  918. mLine.ssrcGroups.forEach(group => {
  919. if (typeof group.semantics !== 'undefined'
  920. && group.semantics === 'FID') {
  921. if (typeof group.ssrcs !== 'undefined') {
  922. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  923. }
  924. }
  925. });
  926. }
  927. if (Array.isArray(mLine.ssrcs)) {
  928. let i;
  929. for (i = 0; i < mLine.ssrcs.length; i++) {
  930. if (typeof mLine.ssrcs[i] === 'object'
  931. && typeof mLine.ssrcs[i].id !== 'undefined'
  932. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  933. newSsrcLines.push(mLine.ssrcs[i]);
  934. delete mLine.ssrcs[i];
  935. }
  936. }
  937. for (i = 0; i < mLine.ssrcs.length; i++) {
  938. if (typeof mLine.ssrcs[i] !== 'undefined') {
  939. newSsrcLines.push(mLine.ssrcs[i]);
  940. }
  941. }
  942. mLine.ssrcs = newSsrcLines;
  943. }
  944. });
  945. }
  946. const resStr = transform.write(session);
  947. return new RTCSessionDescription({
  948. type: desc.type,
  949. sdp: resStr
  950. });
  951. };
  952. /**
  953. * Makes sure that both audio and video directions are configured as 'sendrecv'.
  954. * @param {Object} localDescription the SDP object as defined by WebRTC.
  955. */
  956. const enforceSendRecv = function(localDescription) {
  957. if (!localDescription) {
  958. throw new Error('No local description passed in.');
  959. }
  960. const transformer = new SdpTransformWrap(localDescription.sdp);
  961. const audioMedia = transformer.selectMedia('audio');
  962. let changed = false;
  963. if (audioMedia && audioMedia.direction !== 'sendrecv') {
  964. audioMedia.direction = 'sendrecv';
  965. changed = true;
  966. }
  967. const videoMedia = transformer.selectMedia('video');
  968. if (videoMedia && videoMedia.direction !== 'sendrecv') {
  969. videoMedia.direction = 'sendrecv';
  970. changed = true;
  971. }
  972. if (changed) {
  973. return new RTCSessionDescription({
  974. type: localDescription.type,
  975. sdp: transformer.toRawSDP()
  976. });
  977. }
  978. return localDescription;
  979. };
  980. /**
  981. *
  982. * @param {JitsiLocalTrack} localTrack
  983. */
  984. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  985. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  986. return ssrcInfo && ssrcInfo.ssrcs[0];
  987. };
  988. /**
  989. * When doing unified plan simulcast, we'll have a set of ssrcs with the
  990. * same msid but no ssrc-group, since unified plan signals the simulcast
  991. * group via the a=simulcast line. Unfortunately, Jicofo will complain
  992. * if it sees ssrcs with matching msids but no ssrc-group, so we'll inject
  993. * an ssrc-group line to make Jicofo happy.
  994. * NOTE: unlike plan B simulcast, the ssrcs in this inject ssrc-group will
  995. * NOT necessarily be in order of quality (low to high) because:
  996. * a) when translating between unified plan and plan b the order of the ssrcs
  997. * is not preserved and
  998. * b) it isn't guaranteed that firefox will give them to us in order to begin
  999. * with
  1000. * @param desc A session description object (with 'type' and 'sdp' fields)
  1001. * @return A session description object with its sdp field modified to
  1002. * contain an inject ssrc-group for simulcast
  1003. */
  1004. TraceablePeerConnection.prototype._injectSsrcGroupForUnifiedSimulcast
  1005. = function(desc) {
  1006. const sdp = transform.parse(desc.sdp);
  1007. const video = sdp.media.find(mline => mline.type === 'video');
  1008. if (video.simulcast_03) {
  1009. const ssrcs = [];
  1010. video.ssrcs.forEach(ssrc => {
  1011. if (ssrc.attribute === 'msid') {
  1012. ssrcs.push(ssrc.id);
  1013. }
  1014. });
  1015. video.ssrcGroups = video.ssrcGroups || [];
  1016. if (video.ssrcGroups.find(group => group.semantics === 'SIM')) {
  1017. // Group already exists, no need to do anything
  1018. return desc;
  1019. }
  1020. video.ssrcGroups.push({
  1021. semantics: 'SIM',
  1022. ssrcs: ssrcs.join(' ')
  1023. });
  1024. }
  1025. return new RTCSessionDescription({
  1026. type: desc.type,
  1027. sdp: transform.write(sdp)
  1028. });
  1029. };
  1030. /* eslint-disable-next-line vars-on-top */
  1031. const getters = {
  1032. signalingState() {
  1033. return this.peerconnection.signalingState;
  1034. },
  1035. iceConnectionState() {
  1036. return this.peerconnection.iceConnectionState;
  1037. },
  1038. localDescription() {
  1039. let desc = this.peerconnection.localDescription;
  1040. if (!desc) {
  1041. logger.debug('getLocalDescription no localDescription found');
  1042. return {};
  1043. }
  1044. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1045. // if we're running on FF, transform to Plan B first.
  1046. if (browser.usesUnifiedPlan()) {
  1047. desc = this.interop.toPlanB(desc);
  1048. this.trace('getLocalDescription::postTransform (Plan B)',
  1049. dumpSDP(desc));
  1050. desc = this._injectSsrcGroupForUnifiedSimulcast(desc);
  1051. this.trace('getLocalDescription::postTransform (inject ssrc group)',
  1052. dumpSDP(desc));
  1053. }
  1054. if (browser.doesVideoMuteByStreamRemove()) {
  1055. desc = this.localSdpMunger.maybeAddMutedLocalVideoTracksToSDP(desc);
  1056. logger.debug(
  1057. 'getLocalDescription::postTransform (munge local SDP)', desc);
  1058. }
  1059. // What comes out of this getter will be signalled over Jingle to
  1060. // the other peer, so we need to make sure the media direction is
  1061. // 'sendrecv' because we won't change the direction later and don't want
  1062. // the other peer to think we can't send or receive.
  1063. //
  1064. // Note that the description we set in chrome does have the accurate
  1065. // direction (e.g. 'recvonly'), since that is technically what is
  1066. // happening (check setLocalDescription impl).
  1067. desc = enforceSendRecv(desc);
  1068. // See the method's doc for more info about this transformation.
  1069. desc = this.localSdpMunger.transformStreamIdentifiers(desc);
  1070. return desc;
  1071. },
  1072. remoteDescription() {
  1073. let desc = this.peerconnection.remoteDescription;
  1074. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1075. // if we're running on FF, transform to Plan B first.
  1076. if (browser.usesUnifiedPlan()) {
  1077. desc = this.interop.toPlanB(desc);
  1078. this.trace(
  1079. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  1080. }
  1081. return desc || {};
  1082. }
  1083. };
  1084. Object.keys(getters).forEach(prop => {
  1085. Object.defineProperty(
  1086. TraceablePeerConnection.prototype,
  1087. prop, {
  1088. get: getters[prop]
  1089. }
  1090. );
  1091. });
  1092. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1093. return this.localSSRCs.get(rtcId);
  1094. };
  1095. /**
  1096. * Add {@link JitsiLocalTrack} to this TPC.
  1097. * @param {JitsiLocalTrack} track
  1098. */
  1099. TraceablePeerConnection.prototype.addTrack = function(track) {
  1100. const rtcId = track.rtcId;
  1101. logger.info(`add ${track} to: ${this}`);
  1102. if (this.localTracks.has(rtcId)) {
  1103. logger.error(`${track} is already in ${this}`);
  1104. return;
  1105. }
  1106. this.localTracks.set(rtcId, track);
  1107. const webrtcStream = track.getOriginalStream();
  1108. if (webrtcStream) {
  1109. this._addStream(webrtcStream);
  1110. // It's not ok for a track to not have a WebRTC stream if:
  1111. } else if (!browser.doesVideoMuteByStreamRemove()
  1112. || track.isAudioTrack()
  1113. || (track.isVideoTrack() && !track.isMuted())) {
  1114. logger.error(`${this} no WebRTC stream for: ${track}`);
  1115. }
  1116. // Muted video tracks do not have WebRTC stream
  1117. if (browser.doesVideoMuteByStreamRemove()
  1118. && track.isVideoTrack() && track.isMuted()) {
  1119. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  1120. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  1121. const simGroup
  1122. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  1123. if (simGroup) {
  1124. this.simulcast.setSsrcCache(simGroup.ssrcs);
  1125. }
  1126. const fidGroups
  1127. = ssrcInfo.groups.filter(
  1128. groupInfo => groupInfo.semantics === 'FID');
  1129. if (fidGroups) {
  1130. const rtxSsrcMapping = new Map();
  1131. fidGroups.forEach(fidGroup => {
  1132. const primarySsrc = fidGroup.ssrcs[0];
  1133. const rtxSsrc = fidGroup.ssrcs[1];
  1134. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  1135. });
  1136. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  1137. }
  1138. }
  1139. };
  1140. /**
  1141. * Adds local track as part of the unmute operation.
  1142. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  1143. * operation
  1144. * @return {boolean} <tt>true</tt> if the state of underlying PC has changed and
  1145. * the renegotiation is required or <tt>false</tt> otherwise.
  1146. */
  1147. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  1148. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  1149. // Abort
  1150. return false;
  1151. }
  1152. logger.info(`Adding ${track} as unmute to ${this}`);
  1153. const webRtcStream = track.getOriginalStream();
  1154. if (!webRtcStream) {
  1155. logger.error(
  1156. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  1157. return false;
  1158. }
  1159. this._addStream(webRtcStream);
  1160. return true;
  1161. };
  1162. /**
  1163. * Adds WebRTC media stream to the underlying PeerConnection
  1164. * @param {MediaStream} mediaStream
  1165. * @private
  1166. */
  1167. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  1168. this.peerconnection.addStream(mediaStream);
  1169. this._addedStreams.push(mediaStream);
  1170. };
  1171. /**
  1172. * Removes WebRTC media stream from the underlying PeerConection
  1173. * @param {MediaStream} mediaStream
  1174. */
  1175. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  1176. if (browser.isFirefox()) {
  1177. this._handleFirefoxRemoveStream(mediaStream);
  1178. } else {
  1179. this.peerconnection.removeStream(mediaStream);
  1180. }
  1181. this._addedStreams
  1182. = this._addedStreams.filter(stream => stream !== mediaStream);
  1183. };
  1184. /**
  1185. * This method when called will check if given <tt>localTrack</tt> belongs to
  1186. * this TPC (that it has been previously added using {@link addTrack}). If the
  1187. * track does not belong an error message will be logged.
  1188. * @param {string} methodName the method name that will be logged in an error
  1189. * message
  1190. * @param {JitsiLocalTrack} localTrack
  1191. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1192. * <tt>false</tt> otherwise.
  1193. * @private
  1194. */
  1195. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1196. methodName,
  1197. localTrack) {
  1198. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1199. if (!doesBelong) {
  1200. logger.error(
  1201. `${methodName}: ${localTrack} does not belong to ${this}`);
  1202. }
  1203. return doesBelong;
  1204. };
  1205. /**
  1206. * Tells if the given WebRTC <tt>MediaStream</tt> has been added to
  1207. * the underlying WebRTC PeerConnection.
  1208. * @param {MediaStream} mediaStream
  1209. * @returns {boolean}
  1210. */
  1211. TraceablePeerConnection.prototype.isMediaStreamInPc = function(mediaStream) {
  1212. return this._addedStreams.indexOf(mediaStream) > -1;
  1213. };
  1214. /**
  1215. * Remove local track from this TPC.
  1216. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1217. *
  1218. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1219. * The same applies to addTrack.
  1220. */
  1221. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1222. const webRtcStream = localTrack.getOriginalStream();
  1223. this.trace(
  1224. 'removeStream',
  1225. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1226. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1227. // Abort - nothing to be done here
  1228. return;
  1229. }
  1230. this.localTracks.delete(localTrack.rtcId);
  1231. this.localSSRCs.delete(localTrack.rtcId);
  1232. if (webRtcStream) {
  1233. if (browser.isFirefox()) {
  1234. this._handleFirefoxRemoveStream(webRtcStream);
  1235. } else {
  1236. this.peerconnection.removeStream(webRtcStream);
  1237. }
  1238. }
  1239. };
  1240. /**
  1241. * Returns the sender corresponding to the given MediaStream.
  1242. *
  1243. * @param {MediaStream} stream - The media stream used for the search.
  1244. * @returns {RTPSender|undefined} - The found sender or undefined if no sender
  1245. * was found.
  1246. */
  1247. TraceablePeerConnection.prototype.findSenderByStream = function(stream) {
  1248. const track = stream.getTracks()[0];
  1249. if (!track) {
  1250. logger.error('Cannot find sender: no tracks.');
  1251. return;
  1252. }
  1253. // Find the right sender (for audio or video)
  1254. return this.peerconnection.getSenders().find(s => s.track === track);
  1255. };
  1256. /**
  1257. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1258. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1259. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1260. * <tt>oldTrack</tt>
  1261. *
  1262. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be
  1263. * replaced
  1264. * @param {JitsiLocalTrack|null} newTrack - The new track to use
  1265. * @returns {Promise<boolean>} - If the promise resolves with true,
  1266. * renegotiation will be needed. Otherwise no renegotiation is needed.
  1267. */
  1268. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack) {
  1269. if (browser.isFirefox() && oldTrack && newTrack) {
  1270. // Add and than remove stream in FF leads to wrong local SDP. In order
  1271. // to workaround the issue we need to use sender.replaceTrack().
  1272. const sender = this.findSenderByStream(oldTrack.getOriginalStream());
  1273. const stream = newTrack.getOriginalStream();
  1274. if (sender && stream) {
  1275. const track = stream.getTracks()[0];
  1276. if (track) {
  1277. return sender.replaceTrack(track, stream).then(() => {
  1278. // Since there is no need to do renegotiations we need to
  1279. // fix all ssrc-msid mappings here.
  1280. // NOTE: after sender.replaceTrack the sdp will remain the
  1281. // same but the stream attach to the new JitsiLocalTrack
  1282. // will have different msid. Luckily on FF we are not doing
  1283. // all the transformations related to video mute.
  1284. const ssrc = this.localSSRCs.get(oldTrack.rtcId);
  1285. this.localTracks.delete(oldTrack.rtcId);
  1286. this.localSSRCs.delete(oldTrack.rtcId);
  1287. this._addedStreams
  1288. = this._addedStreams.filter(s => s !== stream);
  1289. this.localTracks.set(newTrack.rtcId, newTrack);
  1290. // Override the msid of JitsiLocalTrack in order to be
  1291. // consistent with the SDP values.
  1292. newTrack.storedMSID = oldTrack.storedMSID;
  1293. this._addedStreams.push(stream);
  1294. this.localSSRCs.set(newTrack.rtcId, ssrc);
  1295. this.eventEmitter.emit(
  1296. RTCEvents.LOCAL_TRACK_SSRC_UPDATED,
  1297. newTrack,
  1298. extractPrimarySSRC(ssrc));
  1299. return false;
  1300. });
  1301. }
  1302. }
  1303. }
  1304. if (oldTrack) {
  1305. this.removeTrack(oldTrack);
  1306. }
  1307. if (newTrack) {
  1308. this.addTrack(newTrack);
  1309. }
  1310. return Promise.resolve(true);
  1311. };
  1312. /**
  1313. * Removes local track as part of the mute operation.
  1314. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1315. * the mute operation.
  1316. * @return {boolean} <tt>true</tt> if the underlying PeerConnection's state has
  1317. * changed and the renegotiation is required or <tt>false</tt> otherwise.
  1318. */
  1319. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1320. const webRtcStream = localTrack.getOriginalStream();
  1321. this.trace(
  1322. 'removeStreamMute',
  1323. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1324. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1325. // Abort - nothing to be done here
  1326. return false;
  1327. }
  1328. if (webRtcStream) {
  1329. logger.info(
  1330. `Removing ${localTrack} as mute from ${this}`);
  1331. this._removeStream(webRtcStream);
  1332. return true;
  1333. }
  1334. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1335. return false;
  1336. };
  1337. /**
  1338. * Remove stream handling for firefox
  1339. * @param stream: webrtc media stream
  1340. */
  1341. TraceablePeerConnection.prototype._handleFirefoxRemoveStream = function(
  1342. stream) {
  1343. if (!stream) {
  1344. // There is nothing to be changed
  1345. return;
  1346. }
  1347. const sender = this.findSenderByStream(stream);
  1348. if (sender) {
  1349. this.peerconnection.removeTrack(sender);
  1350. } else {
  1351. logger.log('Cannot remove tracks: no RTPSender.');
  1352. }
  1353. };
  1354. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1355. this.trace('createDataChannel', label, opts);
  1356. return this.peerconnection.createDataChannel(label, opts);
  1357. };
  1358. /**
  1359. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1360. * in the SDP so that simulcast is properly activated.
  1361. *
  1362. * @param {Object} localSdp the WebRTC session description instance for
  1363. * the local description.
  1364. * @private
  1365. */
  1366. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast = function(
  1367. localSdp) {
  1368. let sdpStr = localSdp.sdp;
  1369. const videoStartIndex = sdpStr.indexOf('m=video');
  1370. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1371. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1372. if (simStartIndex === -1
  1373. || otherStartIndex === -1
  1374. || otherStartIndex === simStartIndex) {
  1375. return localSdp;
  1376. }
  1377. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1378. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1379. sdpStr = sdpStr.replace(simStr, '');
  1380. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1381. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1382. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1383. const simStrTrimmed = simStr.trim();
  1384. const sdpTail = sdpStr.slice(otherEndIndex);
  1385. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1386. return new RTCSessionDescription({
  1387. type: localSdp.type,
  1388. sdp: sdpStr
  1389. });
  1390. };
  1391. /**
  1392. * Will adjust audio and video media direction in the given SDP object to
  1393. * reflect the current status of the {@link audioTransferActive} and
  1394. * {@link videoTransferActive} flags.
  1395. * @param {Object} localDescription the WebRTC session description instance for
  1396. * the local description.
  1397. * @private
  1398. */
  1399. TraceablePeerConnection.prototype._adjustLocalMediaDirection = function(
  1400. localDescription) {
  1401. const transformer = new SdpTransformWrap(localDescription.sdp);
  1402. let modifiedDirection = false;
  1403. const audioMedia = transformer.selectMedia('audio');
  1404. if (audioMedia) {
  1405. const desiredAudioDirection
  1406. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1407. if (audioMedia.direction !== desiredAudioDirection) {
  1408. audioMedia.direction = desiredAudioDirection;
  1409. logger.info(
  1410. `Adjusted local audio direction to ${desiredAudioDirection}`);
  1411. modifiedDirection = true;
  1412. }
  1413. } else {
  1414. logger.warn('No "audio" media found int the local description');
  1415. }
  1416. const videoMedia = transformer.selectMedia('video');
  1417. if (videoMedia) {
  1418. const desiredVideoDirection
  1419. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1420. if (videoMedia.direction !== desiredVideoDirection) {
  1421. videoMedia.direction = desiredVideoDirection;
  1422. logger.info(
  1423. `Adjusted local video direction to ${desiredVideoDirection}`);
  1424. modifiedDirection = true;
  1425. }
  1426. } else {
  1427. logger.warn('No "video" media found in the local description');
  1428. }
  1429. if (modifiedDirection) {
  1430. return new RTCSessionDescription({
  1431. type: localDescription.type,
  1432. sdp: transformer.toRawSDP()
  1433. });
  1434. }
  1435. return localDescription;
  1436. };
  1437. TraceablePeerConnection.prototype.setLocalDescription = function(description) {
  1438. let localSdp = description;
  1439. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1440. if (this.options.disableH264 || this.options.preferH264) {
  1441. const parsedSdp = transform.parse(localSdp.sdp);
  1442. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1443. if (this.options.disableH264) {
  1444. SDPUtil.stripVideoCodec(videoMLine, 'h264');
  1445. } else {
  1446. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1447. }
  1448. localSdp = new RTCSessionDescription({
  1449. type: localSdp.type,
  1450. sdp: transform.write(parsedSdp)
  1451. });
  1452. this.trace('setLocalDescription::postTransform (H264)',
  1453. dumpSDP(localSdp));
  1454. }
  1455. localSdp = this._adjustLocalMediaDirection(localSdp);
  1456. localSdp = this._ensureSimulcastGroupIsLast(localSdp);
  1457. // if we're using unified plan, transform to it first.
  1458. if (browser.usesUnifiedPlan()) {
  1459. localSdp = this.interop.toUnifiedPlan(localSdp);
  1460. this.trace(
  1461. 'setLocalDescription::postTransform (Unified Plan)',
  1462. dumpSDP(localSdp));
  1463. }
  1464. return new Promise((resolve, reject) => {
  1465. this.peerconnection.setLocalDescription(localSdp)
  1466. .then(() => {
  1467. this.trace('setLocalDescriptionOnSuccess');
  1468. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1469. if (localUfrag !== this.localUfrag) {
  1470. this.localUfrag = localUfrag;
  1471. this.eventEmitter.emit(
  1472. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1473. }
  1474. resolve();
  1475. }, err => {
  1476. this.trace('setLocalDescriptionOnFailure', err);
  1477. this.eventEmitter.emit(
  1478. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1479. err, this);
  1480. reject(err);
  1481. });
  1482. });
  1483. };
  1484. /**
  1485. * Enables/disables audio media transmission on this peer connection. When
  1486. * disabled the SDP audio media direction in the local SDP will be adjusted to
  1487. * 'inactive' which means that no data will be sent nor accepted, but
  1488. * the connection should be kept alive.
  1489. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  1490. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1491. * no effect.
  1492. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1493. * needs to be executed in order for the changes to take effect or
  1494. * <tt>false</tt> if the given value was the same as the previous one.
  1495. * @public
  1496. */
  1497. TraceablePeerConnection.prototype.setAudioTransferActive = function(active) {
  1498. logger.debug(`${this} audio transfer active: ${active}`);
  1499. const changed = this.audioTransferActive !== active;
  1500. this.audioTransferActive = active;
  1501. return changed;
  1502. };
  1503. /**
  1504. * Takes in a *unified plan* offer and inserts the appropriate
  1505. * parameters for adding simulcast receive support.
  1506. * @param {Object} desc - A session description object
  1507. * @param {String} desc.type - the type (offer/answer)
  1508. * @param {String} desc.sdp - the sdp content
  1509. *
  1510. * @return {Object} A session description (same format as above) object
  1511. * with its sdp field modified to advertise simulcast receive support
  1512. */
  1513. TraceablePeerConnection.prototype._insertUnifiedPlanSimulcastReceive
  1514. = function(desc) {
  1515. const sdp = transform.parse(desc.sdp);
  1516. const video = sdp.media.find(mline => mline.type === 'video');
  1517. // In order of lowest to highest spatial quality
  1518. video.rids = [
  1519. {
  1520. id: SIM_LAYER_1_RID,
  1521. direction: 'recv'
  1522. },
  1523. {
  1524. id: SIM_LAYER_2_RID,
  1525. direction: 'recv'
  1526. },
  1527. {
  1528. id: SIM_LAYER_3_RID,
  1529. direction: 'recv'
  1530. }
  1531. ];
  1532. // eslint-disable-next-line camelcase
  1533. video.simulcast_03 = {
  1534. value: `recv rid=${SIM_LAYER_RIDS.join(';')}`
  1535. };
  1536. return new RTCSessionDescription({
  1537. type: desc.type,
  1538. sdp: transform.write(sdp)
  1539. });
  1540. };
  1541. TraceablePeerConnection.prototype.setRemoteDescription = function(description) {
  1542. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1543. // TODO the focus should squeze or explode the remote simulcast
  1544. // eslint-disable-next-line no-param-reassign
  1545. description = this.simulcast.mungeRemoteDescription(description);
  1546. this.trace(
  1547. 'setRemoteDescription::postTransform (simulcast)',
  1548. dumpSDP(description));
  1549. if (this.options.preferH264) {
  1550. const parsedSdp = transform.parse(description.sdp);
  1551. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1552. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1553. // eslint-disable-next-line no-param-reassign
  1554. description = new RTCSessionDescription({
  1555. type: description.type,
  1556. sdp: transform.write(parsedSdp)
  1557. });
  1558. }
  1559. // If the browser uses unified plan, transform to it first
  1560. if (browser.usesUnifiedPlan()) {
  1561. // eslint-disable-next-line no-param-reassign
  1562. description = new RTCSessionDescription({
  1563. type: description.type,
  1564. sdp: this.rtxModifier.stripRtx(description.sdp)
  1565. });
  1566. this.trace(
  1567. 'setRemoteDescription::postTransform (stripRtx)',
  1568. dumpSDP(description));
  1569. // eslint-disable-next-line no-param-reassign
  1570. description = this.interop.toUnifiedPlan(description);
  1571. this.trace(
  1572. 'setRemoteDescription::postTransform (Plan A)',
  1573. dumpSDP(description));
  1574. if (this.isSimulcastOn()) {
  1575. // eslint-disable-next-line no-param-reassign
  1576. description = this._insertUnifiedPlanSimulcastReceive(description);
  1577. this.trace(
  1578. 'setRemoteDescription::postTransform (sim receive)',
  1579. dumpSDP(description));
  1580. }
  1581. } else {
  1582. // Plan B
  1583. // eslint-disable-next-line no-param-reassign
  1584. description = normalizePlanB(description);
  1585. }
  1586. // Safari WebRTC errors when no supported video codec is found in the offer.
  1587. // To prevent the error, inject H264 into the video mLine.
  1588. if (browser.isSafariWithWebrtc()) {
  1589. logger.debug('Maybe injecting H264 into the remote description');
  1590. // eslint-disable-next-line no-param-reassign
  1591. description = this._injectH264IfNotPresent(description);
  1592. }
  1593. return new Promise((resolve, reject) => {
  1594. this.peerconnection.setRemoteDescription(description)
  1595. .then(() => {
  1596. this.trace('setRemoteDescriptionOnSuccess');
  1597. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  1598. if (remoteUfrag !== this.remoteUfrag) {
  1599. this.remoteUfrag = remoteUfrag;
  1600. this.eventEmitter.emit(
  1601. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1602. }
  1603. resolve();
  1604. }, err => {
  1605. this.trace('setRemoteDescriptionOnFailure', err);
  1606. this.eventEmitter.emit(
  1607. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  1608. err,
  1609. this);
  1610. reject(err);
  1611. });
  1612. });
  1613. };
  1614. /**
  1615. * Inserts an H264 payload into the description if not already present. This is
  1616. * need for Safari WebRTC, which errors when no supported video codec is found
  1617. * in the offer. Related bug reports:
  1618. * https://bugs.webkit.org/show_bug.cgi?id=173141
  1619. * https://bugs.chromium.org/p/webrtc/issues/detail?id=4957
  1620. *
  1621. * @param {RTCSessionDescription} description - An RTCSessionDescription
  1622. * to inject with an H264 payload.
  1623. * @private
  1624. * @returns {RTCSessionDescription}
  1625. */
  1626. TraceablePeerConnection.prototype._injectH264IfNotPresent = function(
  1627. description) {
  1628. const parsedSdp = transform.parse(description.sdp);
  1629. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1630. if (!videoMLine) {
  1631. logger.debug('No videoMLine found, no need to inject H264.');
  1632. return description;
  1633. }
  1634. if (videoMLine.rtp.some(rtp => rtp.codec.toLowerCase() === 'h264')) {
  1635. logger.debug('H264 codec found in video mLine, no need to inject.');
  1636. return description;
  1637. }
  1638. const { fmtp, payloads, rtp } = videoMLine;
  1639. const payloadsArray = payloads.toString().split(' ');
  1640. let dummyPayloadType;
  1641. for (let i = 127; i >= 96; i--) {
  1642. if (!payloadsArray.includes(i)) {
  1643. dummyPayloadType = i;
  1644. payloadsArray.push(i);
  1645. videoMLine.payloads = payloadsArray.join(' ');
  1646. break;
  1647. }
  1648. }
  1649. if (typeof dummyPayloadType === 'undefined') {
  1650. logger.error('Could not find valid payload type to inject.');
  1651. return description;
  1652. }
  1653. rtp.push({
  1654. codec: 'H264',
  1655. payload: dummyPayloadType,
  1656. rate: 90000
  1657. });
  1658. fmtp.push({
  1659. config: 'level-asymmetry-allowed=1;'
  1660. + 'packetization-mode=1;'
  1661. + 'profile-level-id=42e01f',
  1662. payload: dummyPayloadType
  1663. });
  1664. logger.debug(
  1665. `Injecting H264 payload type ${dummyPayloadType} into video mLine.`);
  1666. return new RTCSessionDescription({
  1667. type: description.type,
  1668. sdp: transform.write(parsedSdp)
  1669. });
  1670. };
  1671. /**
  1672. * Enables/disables video media transmission on this peer connection. When
  1673. * disabled the SDP video media direction in the local SDP will be adjusted to
  1674. * 'inactive' which means that no data will be sent nor accepted, but
  1675. * the connection should be kept alive.
  1676. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  1677. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1678. * no effect.
  1679. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1680. * needs to be executed in order for the changes to take effect or
  1681. * <tt>false</tt> if the given value was the same as the previous one.
  1682. * @public
  1683. */
  1684. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  1685. logger.debug(`${this} video transfer active: ${active}`);
  1686. const changed = this.videoTransferActive !== active;
  1687. this.videoTransferActive = active;
  1688. return changed;
  1689. };
  1690. /**
  1691. * Makes the underlying TraceablePeerConnection generate new SSRC for
  1692. * the recvonly video stream.
  1693. */
  1694. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  1695. const newSSRC = SDPUtil.generateSsrc();
  1696. logger.info(`${this} generated new recvonly SSRC: ${newSSRC}`);
  1697. this.sdpConsistency.setPrimarySsrc(newSSRC);
  1698. };
  1699. /**
  1700. * Makes the underlying TraceablePeerConnection forget the current primary video
  1701. * SSRC.
  1702. */
  1703. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  1704. logger.info('Clearing primary video SSRC!');
  1705. this.sdpConsistency.clearVideoSsrcCache();
  1706. };
  1707. /**
  1708. * Closes underlying WebRTC PeerConnection instance and removes all remote
  1709. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  1710. * them.
  1711. */
  1712. TraceablePeerConnection.prototype.close = function() {
  1713. this.trace('stop');
  1714. // Off SignalingEvents
  1715. this.signalingLayer.off(
  1716. SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  1717. this.signalingLayer.off(
  1718. SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  1719. for (const peerTracks of this.remoteTracks.values()) {
  1720. for (const remoteTrack of peerTracks.values()) {
  1721. this._removeRemoteTrack(remoteTrack);
  1722. }
  1723. }
  1724. this.remoteTracks.clear();
  1725. this._addedStreams = [];
  1726. if (!this.rtc._removePeerConnection(this)) {
  1727. logger.error('RTC._removePeerConnection returned false');
  1728. }
  1729. if (this.statsinterval !== null) {
  1730. window.clearInterval(this.statsinterval);
  1731. this.statsinterval = null;
  1732. }
  1733. logger.info(`Closing ${this}...`);
  1734. this.peerconnection.close();
  1735. };
  1736. /**
  1737. * Modifies the values of the setup attributes (defined by
  1738. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  1739. * answer in order to overcome a delay of 1 second in the connection
  1740. * establishment between Chrome and Videobridge.
  1741. *
  1742. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  1743. * being prepared to respond
  1744. * @param {SDP} answer - the SDP to modify
  1745. * @private
  1746. */
  1747. const _fixAnswerRFC4145Setup = function(offer, answer) {
  1748. if (!browser.isChrome()) {
  1749. // It looks like Firefox doesn't agree with the fix (at least in its
  1750. // current implementation) because it effectively remains active even
  1751. // after we tell it to become passive. Apart from Firefox which I tested
  1752. // after the fix was deployed, I tested Chrome only. In order to prevent
  1753. // issues with other browsers, limit the fix to Chrome for the time
  1754. // being.
  1755. return;
  1756. }
  1757. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  1758. // answerer (as orchestrated by Jicofo). In accord with
  1759. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  1760. // are ICE FULL agents, Videobridge will take on the controlling role and
  1761. // WebRTC will take on the controlled role. In accord with
  1762. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  1763. // setup attribute value of setup:actpass and WebRTC will be allowed to
  1764. // choose either the setup attribute value of setup:active or
  1765. // setup:passive. Chrome will by default choose setup:active because it is
  1766. // RECOMMENDED by the respective RFC since setup:passive adds additional
  1767. // latency. The case of setup:active allows WebRTC to send a DTLS
  1768. // ClientHello as soon as an ICE connectivity check of its succeeds.
  1769. // Unfortunately, Videobridge will be unable to respond immediately because
  1770. // may not have WebRTC's answer or may have not completed the ICE
  1771. // connectivity establishment. Even more unfortunate is that in the
  1772. // described scenario Chrome's DTLS implementation will insist on
  1773. // retransmitting its ClientHello after a second (the time is in accord
  1774. // with the respective RFC) and will thus cause the whole connection
  1775. // establishment to exceed at least 1 second. To work around Chrome's
  1776. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  1777. // default choice of setup:active to setup:passive.
  1778. if (offer && answer
  1779. && offer.media && answer.media
  1780. && offer.media.length === answer.media.length) {
  1781. answer.media.forEach((a, i) => {
  1782. if (SDPUtil.findLine(
  1783. offer.media[i],
  1784. 'a=setup:actpass',
  1785. offer.session)) {
  1786. answer.media[i]
  1787. = a.replace(/a=setup:active/g, 'a=setup:passive');
  1788. }
  1789. });
  1790. answer.raw = answer.session + answer.media.join('');
  1791. }
  1792. };
  1793. TraceablePeerConnection.prototype.createAnswer = function(constraints) {
  1794. if (browser.supportsRtpSender() && this.isSimulcastOn()) {
  1795. const videoSender
  1796. = this.peerconnection.getSenders().find(sender =>
  1797. sender.track.kind === 'video');
  1798. const simParams = {
  1799. encodings: [
  1800. {
  1801. rid: SIM_LAYER_1_RID,
  1802. scaleResolutionDownBy: 4
  1803. },
  1804. {
  1805. rid: SIM_LAYER_2_RID,
  1806. scaleResolutionDownBy: 2
  1807. },
  1808. {
  1809. rid: SIM_LAYER_3_RID
  1810. }
  1811. ]
  1812. };
  1813. videoSender.setParameters(simParams);
  1814. }
  1815. return this._createOfferOrAnswer(false /* answer */, constraints);
  1816. };
  1817. TraceablePeerConnection.prototype.createOffer = function(constraints) {
  1818. return this._createOfferOrAnswer(true /* offer */, constraints);
  1819. };
  1820. TraceablePeerConnection.prototype._createOfferOrAnswer = function(
  1821. isOffer,
  1822. constraints) {
  1823. const logName = isOffer ? 'Offer' : 'Answer';
  1824. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  1825. const handleSuccess = (resultSdp, resolveFn, rejectFn) => {
  1826. try {
  1827. this.trace(
  1828. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  1829. // if we're using unified plan, transform to Plan B.
  1830. if (browser.usesUnifiedPlan()) {
  1831. // eslint-disable-next-line no-param-reassign
  1832. resultSdp = this.interop.toPlanB(resultSdp);
  1833. this.trace(
  1834. `create${logName}OnSuccess::postTransform (Plan B)`,
  1835. dumpSDP(resultSdp));
  1836. if (this.isSimulcastOn()) {
  1837. // eslint-disable-next-line no-param-reassign
  1838. resultSdp
  1839. = this._injectSsrcGroupForUnifiedSimulcast(resultSdp);
  1840. this.trace(
  1841. `create${logName}OnSuccess::postTransform`
  1842. + '(inject ssrc group)', dumpSDP(resultSdp));
  1843. }
  1844. }
  1845. /**
  1846. * We don't keep ssrcs consitent for Firefox because rewriting
  1847. * the ssrcs between createAnswer and setLocalDescription breaks
  1848. * the caching in sdp-interop (sdp-interop must know about all
  1849. * ssrcs, and it updates its cache in toPlanB so if we rewrite them
  1850. * after that, when we try and go back to unified plan it will
  1851. * complain about unmapped ssrcs)
  1852. */
  1853. if (!browser.isFirefox()) {
  1854. // If there are no local video tracks, then a "recvonly"
  1855. // SSRC needs to be generated
  1856. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  1857. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  1858. this.generateRecvonlySsrc();
  1859. }
  1860. // eslint-disable-next-line no-param-reassign
  1861. resultSdp = new RTCSessionDescription({
  1862. type: resultSdp.type,
  1863. sdp: this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  1864. resultSdp.sdp)
  1865. });
  1866. this.trace(
  1867. `create${logName}OnSuccess::postTransform `
  1868. + '(make primary audio/video ssrcs consistent)',
  1869. dumpSDP(resultSdp));
  1870. }
  1871. // Add simulcast streams if simulcast is enabled
  1872. if (this.isSimulcastOn()) {
  1873. // eslint-disable-next-line no-param-reassign
  1874. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  1875. this.trace(
  1876. `create${logName}`
  1877. + 'OnSuccess::postTransform (simulcast)',
  1878. dumpSDP(resultSdp));
  1879. }
  1880. if (!this.options.disableRtx && browser.supportsRtx()) {
  1881. // eslint-disable-next-line no-param-reassign
  1882. resultSdp = new RTCSessionDescription({
  1883. type: resultSdp.type,
  1884. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  1885. });
  1886. this.trace(
  1887. `create${logName}`
  1888. + 'OnSuccess::postTransform (rtx modifier)',
  1889. dumpSDP(resultSdp));
  1890. }
  1891. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  1892. // details)
  1893. if (!isOffer) {
  1894. const remoteDescription
  1895. = new SDP(this.remoteDescription.sdp);
  1896. const localDescription = new SDP(resultSdp.sdp);
  1897. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  1898. // eslint-disable-next-line no-param-reassign
  1899. resultSdp = new RTCSessionDescription({
  1900. type: resultSdp.type,
  1901. sdp: localDescription.raw
  1902. });
  1903. }
  1904. const ssrcMap = extractSSRCMap(resultSdp);
  1905. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  1906. this._processLocalSSRCsMap(ssrcMap);
  1907. resolveFn(resultSdp);
  1908. } catch (e) {
  1909. this.trace(`create${logName}OnError`, e);
  1910. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  1911. logger.error(`create${logName}OnError`, e, dumpSDP(resultSdp));
  1912. rejectFn(e);
  1913. }
  1914. };
  1915. const handleFailure = (err, rejectFn) => {
  1916. this.trace(`create${logName}OnFailure`, err);
  1917. const eventType
  1918. = isOffer
  1919. ? RTCEvents.CREATE_OFFER_FAILED
  1920. : RTCEvents.CREATE_ANSWER_FAILED;
  1921. this.eventEmitter.emit(eventType, err, this);
  1922. rejectFn(err);
  1923. };
  1924. return new Promise((resolve, reject) => {
  1925. let oaPromise;
  1926. if (isOffer) {
  1927. oaPromise = this.peerconnection.createOffer(constraints);
  1928. } else {
  1929. oaPromise = this.peerconnection.createAnswer(constraints);
  1930. }
  1931. oaPromise
  1932. .then(
  1933. sdp => handleSuccess(sdp, resolve, reject),
  1934. error => handleFailure(error, reject));
  1935. });
  1936. };
  1937. /**
  1938. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  1939. * @param {TrackSSRCInfo} ssrcObj
  1940. * @return {number|null} the primary SSRC or <tt>null</tt>
  1941. */
  1942. function extractPrimarySSRC(ssrcObj) {
  1943. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  1944. return ssrcObj.groups[0].ssrcs[0];
  1945. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  1946. return ssrcObj.ssrcs[0];
  1947. }
  1948. return null;
  1949. }
  1950. /**
  1951. * Goes over the SSRC map extracted from the latest local description and tries
  1952. * to match them with the local tracks (by MSID). Will update the values
  1953. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  1954. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  1955. * @private
  1956. */
  1957. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  1958. for (const track of this.localTracks.values()) {
  1959. const trackMSID = track.storedMSID;
  1960. if (ssrcMap.has(trackMSID)) {
  1961. const newSSRC = ssrcMap.get(trackMSID);
  1962. if (!newSSRC) {
  1963. logger.error(`No SSRC found for: ${trackMSID} in ${this}`);
  1964. return;
  1965. }
  1966. const oldSSRC = this.localSSRCs.get(track.rtcId);
  1967. const newSSRCNum = extractPrimarySSRC(newSSRC);
  1968. const oldSSRCNum = extractPrimarySSRC(oldSSRC);
  1969. // eslint-disable-next-line no-negated-condition
  1970. if (newSSRCNum !== oldSSRCNum) {
  1971. if (oldSSRCNum === null) {
  1972. logger.info(
  1973. `Storing new local SSRC for ${track} in ${this}`,
  1974. newSSRC);
  1975. } else {
  1976. logger.error(
  1977. `Overwriting SSRC for ${track} ${trackMSID} in ${this
  1978. } with: `, newSSRC);
  1979. }
  1980. this.localSSRCs.set(track.rtcId, newSSRC);
  1981. this.eventEmitter.emit(
  1982. RTCEvents.LOCAL_TRACK_SSRC_UPDATED, track, newSSRCNum);
  1983. } else {
  1984. logger.debug(
  1985. `The local SSRC(${newSSRCNum}) for ${track} ${trackMSID}`
  1986. + `is still up to date in ${this}`);
  1987. }
  1988. } else {
  1989. logger.warn(`No local track matched with: ${trackMSID} in ${this}`);
  1990. }
  1991. }
  1992. };
  1993. TraceablePeerConnection.prototype.addIceCandidate = function(candidate) {
  1994. this.trace('addIceCandidate', JSON.stringify({
  1995. candidate: candidate.candidate,
  1996. sdpMid: candidate.sdpMid,
  1997. sdpMLineIndex: candidate.sdpMLineIndex,
  1998. usernameFragment: candidate.usernameFragment
  1999. }, null, ' '));
  2000. return this.peerconnection.addIceCandidate(candidate);
  2001. };
  2002. /**
  2003. * Obtains call-related stats from the peer connection.
  2004. *
  2005. * @param {Function} callback - The function to invoke after successfully
  2006. * obtaining stats.
  2007. * @param {Function} errback - The function to invoke after failing to obtain
  2008. * stats.
  2009. * @returns {void}
  2010. */
  2011. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  2012. // TODO (brian): After moving all browsers to adapter, check if adapter is
  2013. // accounting for different getStats apis, making the browser-checking-if
  2014. // unnecessary.
  2015. if (browser.isSafariWithWebrtc() || browser.isFirefox()
  2016. || browser.isReactNative()) {
  2017. // uses the new Promise based getStats
  2018. this.peerconnection.getStats()
  2019. .then(callback)
  2020. .catch(errback || (() => {
  2021. // Making sure that getStats won't fail if error callback is
  2022. // not passed.
  2023. }));
  2024. } else {
  2025. this.peerconnection.getStats(callback);
  2026. }
  2027. };
  2028. /**
  2029. * Generates and stores new SSRC info object for given local track.
  2030. * The method should be called only for a video track being added to this TPC
  2031. * in the muted state (given that the current browser uses this strategy).
  2032. * @param {JitsiLocalTrack} track
  2033. * @return {TPCSSRCInfo}
  2034. */
  2035. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  2036. const rtcId = track.rtcId;
  2037. let ssrcInfo = this._getSSRC(rtcId);
  2038. if (ssrcInfo) {
  2039. logger.error(`Will overwrite local SSRCs for track ID: ${rtcId}`);
  2040. }
  2041. if (this.isSimulcastOn()) {
  2042. ssrcInfo = {
  2043. ssrcs: [],
  2044. groups: []
  2045. };
  2046. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  2047. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  2048. }
  2049. ssrcInfo.groups.push({
  2050. ssrcs: ssrcInfo.ssrcs.slice(),
  2051. semantics: 'SIM'
  2052. });
  2053. } else {
  2054. ssrcInfo = {
  2055. ssrcs: [ SDPUtil.generateSsrc() ],
  2056. groups: []
  2057. };
  2058. }
  2059. if (!this.options.disableRtx && browser.supportsRtx()) {
  2060. // Specifically use a for loop here because we'll
  2061. // be adding to the list we're iterating over, so we
  2062. // only want to iterate through the items originally
  2063. // on the list
  2064. const currNumSsrcs = ssrcInfo.ssrcs.length;
  2065. for (let i = 0; i < currNumSsrcs; ++i) {
  2066. const primarySsrc = ssrcInfo.ssrcs[i];
  2067. const rtxSsrc = SDPUtil.generateSsrc();
  2068. ssrcInfo.ssrcs.push(rtxSsrc);
  2069. ssrcInfo.groups.push({
  2070. ssrcs: [ primarySsrc, rtxSsrc ],
  2071. semantics: 'FID'
  2072. });
  2073. }
  2074. }
  2075. ssrcInfo.msid = track.storedMSID;
  2076. this.localSSRCs.set(rtcId, ssrcInfo);
  2077. return ssrcInfo;
  2078. };
  2079. const handleLayerSuspension = function(peerConnection, isSelected) {
  2080. if (!peerConnection.getSenders) {
  2081. logger.debug('Browser doesn\'t support RTPSender');
  2082. return;
  2083. }
  2084. const videoSender = peerConnection.getSenders()
  2085. .find(sender => sender.track.kind === 'video');
  2086. if (!videoSender) {
  2087. logger.warn('handleLayerSuspension unable to find video sender');
  2088. return;
  2089. }
  2090. if (!videoSender.getParameters) {
  2091. logger.debug('Browser doesn\'t support RTPSender parameters');
  2092. return;
  2093. }
  2094. const parameters = videoSender.getParameters();
  2095. if (isSelected) {
  2096. logger.debug('Currently selected, enabling all sim layers');
  2097. // Make sure all encodings are enabled
  2098. parameters.encodings.forEach(e => {
  2099. e.active = true;
  2100. });
  2101. } else {
  2102. logger.debug('Not currently selected, disabling upper layers');
  2103. // Turn off the upper simulcast layers
  2104. [ 1, 2 ].forEach(simIndex => {
  2105. if (parameters.encodings[simIndex]) {
  2106. parameters.encodings[simIndex].active = false;
  2107. }
  2108. });
  2109. }
  2110. videoSender.setParameters(parameters);
  2111. };
  2112. /**
  2113. * Set whether or not the endpoint is 'selected' by other endpoints, meaning
  2114. * it appears on their main stage
  2115. */
  2116. TraceablePeerConnection.prototype.setIsSelected = function(isSelected) {
  2117. if (this.options.enableLayerSuspension) {
  2118. logger.debug('Layer suspension enabled,'
  2119. + `currently selected? ${isSelected}`);
  2120. handleLayerSuspension(this.peerconnection, isSelected);
  2121. }
  2122. };
  2123. /**
  2124. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2125. * instance.
  2126. * @return {string}
  2127. */
  2128. TraceablePeerConnection.prototype.toString = function() {
  2129. return `TPC[${this.id},p2p:${this.isP2P}]`;
  2130. };