選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

TraceablePeerConnection.js 82KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  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.isChrome() || browser.isNWJS()
  507. || browser.isElectron() || browser.isEdge()) {
  508. stream.onaddtrack = event => {
  509. this._remoteTrackAdded(stream, event.track);
  510. };
  511. stream.onremovetrack = event => {
  512. this._remoteTrackRemoved(stream, event.track);
  513. };
  514. }
  515. // Call remoteTrackAdded for each track in the stream
  516. const streamAudioTracks = stream.getAudioTracks();
  517. for (const audioTrack of streamAudioTracks) {
  518. this._remoteTrackAdded(stream, audioTrack);
  519. }
  520. const streamVideoTracks = stream.getVideoTracks();
  521. for (const videoTrack of streamVideoTracks) {
  522. this._remoteTrackAdded(stream, videoTrack);
  523. }
  524. };
  525. /**
  526. * Called on "track added" and "stream added" PeerConnection events (because we
  527. * handle streams on per track basis). Finds the owner and the SSRC for
  528. * the track and passes that to ChatRoom for further processing.
  529. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  530. * the parent of the track
  531. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  532. * participant
  533. */
  534. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  535. const streamId = RTC.getStreamID(stream);
  536. const mediaType = track.kind;
  537. logger.info(`${this} remote track added:`, streamId, mediaType);
  538. // look up an associated JID for a stream id
  539. if (!mediaType) {
  540. GlobalOnErrorHandler.callErrorHandler(
  541. new Error(
  542. `MediaType undefined for remote track, stream id: ${streamId}`
  543. ));
  544. // Abort
  545. return;
  546. }
  547. const remoteSDP = new SDP(this.remoteDescription.sdp);
  548. const mediaLines
  549. = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  550. if (!mediaLines.length) {
  551. GlobalOnErrorHandler.callErrorHandler(
  552. new Error(
  553. `No media lines for type ${
  554. mediaType} found in remote SDP for remote track: ${
  555. streamId}`));
  556. // Abort
  557. return;
  558. }
  559. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  560. ssrcLines
  561. = ssrcLines.filter(line => line.indexOf(`msid:${streamId}`) !== -1);
  562. if (!ssrcLines.length) {
  563. GlobalOnErrorHandler.callErrorHandler(
  564. new Error(
  565. `No SSRC lines for streamId ${
  566. streamId} for remote track, media type: ${mediaType}`));
  567. // Abort
  568. return;
  569. }
  570. // FIXME the length of ssrcLines[0] not verified, but it will fail
  571. // with global error handler anyway
  572. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  573. const trackSsrc = Number(ssrcStr);
  574. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  575. if (isNaN(trackSsrc) || trackSsrc < 0) {
  576. GlobalOnErrorHandler.callErrorHandler(
  577. new Error(
  578. `Invalid SSRC: ${ssrcStr} for remote track, msid: ${
  579. streamId} media type: ${mediaType}`));
  580. // Abort
  581. return;
  582. } else if (!ownerEndpointId) {
  583. GlobalOnErrorHandler.callErrorHandler(
  584. new Error(
  585. `No SSRC owner known for: ${
  586. trackSsrc} for remote track, msid: ${
  587. streamId} media type: ${mediaType}`));
  588. // Abort
  589. return;
  590. }
  591. logger.log(`${this} associated ssrc`, ownerEndpointId, trackSsrc);
  592. const peerMediaInfo
  593. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  594. if (!peerMediaInfo) {
  595. GlobalOnErrorHandler.callErrorHandler(
  596. new Error(
  597. `${this}: no peer media info available for ${
  598. ownerEndpointId}`));
  599. return;
  600. }
  601. const muted = peerMediaInfo.muted;
  602. const videoType = peerMediaInfo.videoType; // can be undefined
  603. this._createRemoteTrack(
  604. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  605. };
  606. // FIXME cleanup params
  607. /* eslint-disable max-params */
  608. /**
  609. * Initializes a new JitsiRemoteTrack instance with the data provided by
  610. * the signaling layer and SDP.
  611. *
  612. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  613. * @param {MediaStream} stream the WebRTC stream instance
  614. * @param {MediaStreamTrack} track the WebRTC track instance
  615. * @param {MediaType} mediaType the track's type of the media
  616. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  617. * @param {number} ssrc the track's main SSRC number
  618. * @param {boolean} muted the initial muted status
  619. */
  620. TraceablePeerConnection.prototype._createRemoteTrack = function(
  621. ownerEndpointId,
  622. stream,
  623. track,
  624. mediaType,
  625. videoType,
  626. ssrc,
  627. muted) {
  628. const remoteTrack
  629. = new JitsiRemoteTrack(
  630. this.rtc, this.rtc.conference,
  631. ownerEndpointId,
  632. stream, track, mediaType, videoType, ssrc, muted, this.isP2P);
  633. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  634. if (!remoteTracksMap) {
  635. remoteTracksMap = new Map();
  636. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  637. }
  638. if (remoteTracksMap.has(mediaType)) {
  639. logger.error(
  640. `${this} overwriting remote track! ${remoteTrack}`,
  641. ownerEndpointId, mediaType);
  642. }
  643. remoteTracksMap.set(mediaType, remoteTrack);
  644. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack);
  645. };
  646. /* eslint-enable max-params */
  647. /**
  648. * Handles remote stream removal.
  649. * @param stream the WebRTC MediaStream object which is being removed from the
  650. * PeerConnection
  651. */
  652. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  653. if (!RTC.isUserStream(stream)) {
  654. const id = RTC.getStreamID(stream);
  655. logger.info(
  656. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  657. return;
  658. }
  659. // Call remoteTrackRemoved for each track in the stream
  660. const streamVideoTracks = stream.getVideoTracks();
  661. for (const videoTrack of streamVideoTracks) {
  662. this._remoteTrackRemoved(stream, videoTrack);
  663. }
  664. const streamAudioTracks = stream.getAudioTracks();
  665. for (const audioTrack of streamAudioTracks) {
  666. this._remoteTrackRemoved(stream, audioTrack);
  667. }
  668. };
  669. /**
  670. * Handles remote media track removal.
  671. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  672. * of the track.
  673. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  674. * removed from the PeerConnection.
  675. */
  676. TraceablePeerConnection.prototype._remoteTrackRemoved = function(
  677. stream,
  678. track) {
  679. const streamId = RTC.getStreamID(stream);
  680. const trackId = track && RTC.getTrackID(track);
  681. logger.info(`${this} - remote track removed: ${streamId}, ${trackId}`);
  682. if (!streamId) {
  683. GlobalOnErrorHandler.callErrorHandler(
  684. new Error(`${this} remote track removal failed - no stream ID`));
  685. return;
  686. }
  687. if (!trackId) {
  688. GlobalOnErrorHandler.callErrorHandler(
  689. new Error(`${this} remote track removal failed - no track ID`));
  690. return;
  691. }
  692. if (!this._removeRemoteTrackById(streamId, trackId)) {
  693. // NOTE this warning is always printed when user leaves the room,
  694. // because we remove remote tracks manually on MUC member left event,
  695. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  696. // ignore this warning, but still it's better to keep it printed for
  697. // debugging purposes.
  698. //
  699. // We could change the behaviour to emit track removed only from here,
  700. // but the order of the events will change and consuming apps could
  701. // behave unexpectedly (the "user left" event would come before "track
  702. // removed" events).
  703. logger.warn(
  704. `${this} Removed track not found for msid: ${streamId},
  705. track id: ${trackId}`);
  706. }
  707. };
  708. /**
  709. * Finds remote track by it's stream and track ids.
  710. * @param {string} streamId the media stream id as defined by the WebRTC
  711. * @param {string} trackId the media track id as defined by the WebRTC
  712. * @return {JitsiRemoteTrack|undefined} the track's instance or
  713. * <tt>undefined</tt> if not found.
  714. * @private
  715. */
  716. TraceablePeerConnection.prototype._getRemoteTrackById = function(
  717. streamId,
  718. trackId) {
  719. // .find will break the loop once the first match is found
  720. for (const endpointTrackMap of this.remoteTracks.values()) {
  721. for (const mediaTrack of endpointTrackMap.values()) {
  722. // FIXME verify and try to use ===
  723. /* eslint-disable eqeqeq */
  724. if (mediaTrack.getStreamId() == streamId
  725. && mediaTrack.getTrackId() == trackId) {
  726. return mediaTrack;
  727. }
  728. /* eslint-enable eqeqeq */
  729. }
  730. }
  731. return undefined;
  732. };
  733. /**
  734. * Removes all JitsiRemoteTracks associated with given MUC nickname
  735. * (resource part of the JID). Returns array of removed tracks.
  736. *
  737. * @param {string} owner - The resource part of the MUC JID.
  738. * @returns {JitsiRemoteTrack[]}
  739. */
  740. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  741. const removedTracks = [];
  742. const remoteTracksMap = this.remoteTracks.get(owner);
  743. if (remoteTracksMap) {
  744. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  745. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  746. removedAudioTrack && removedTracks.push(removedAudioTrack);
  747. removedVideoTrack && removedTracks.push(removedVideoTrack);
  748. this.remoteTracks.delete(owner);
  749. }
  750. logger.debug(
  751. `${this} removed remote tracks for ${owner} count: ${
  752. removedTracks.length}`);
  753. return removedTracks;
  754. };
  755. /**
  756. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits
  757. * {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  758. * @param {JitsiRemoteTrack} toBeRemoved
  759. */
  760. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  761. toBeRemoved.dispose();
  762. const participantId = toBeRemoved.getParticipantId();
  763. const remoteTracksMap = this.remoteTracks.get(participantId);
  764. if (!remoteTracksMap) {
  765. logger.error(
  766. `removeRemoteTrack: no remote tracks map for ${participantId}`);
  767. } else if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  768. logger.error(
  769. `Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  770. }
  771. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  772. };
  773. /**
  774. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  775. * track ids.
  776. *
  777. * @param {string} streamId the media stream id as defined by the WebRTC
  778. * @param {string} trackId the media track id as defined by the WebRTC
  779. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  780. * <tt>undefined</tt> if no track matching given stream and track ids was
  781. * found.
  782. */
  783. TraceablePeerConnection.prototype._removeRemoteTrackById = function(
  784. streamId,
  785. trackId) {
  786. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  787. if (toBeRemoved) {
  788. this._removeRemoteTrack(toBeRemoved);
  789. }
  790. return toBeRemoved;
  791. };
  792. /**
  793. * @typedef {Object} SSRCGroupInfo
  794. * @property {Array<number>} ssrcs group's SSRCs
  795. * @property {string} semantics
  796. */
  797. /**
  798. * @typedef {Object} TrackSSRCInfo
  799. * @property {Array<number>} ssrcs track's SSRCs
  800. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  801. */
  802. /**
  803. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  804. * @param {Object} desc the WebRTC SDP instance.
  805. * @return {Map<string,TrackSSRCInfo>}
  806. */
  807. function extractSSRCMap(desc) {
  808. /**
  809. * Track SSRC infos mapped by stream ID (msid)
  810. * @type {Map<string,TrackSSRCInfo>}
  811. */
  812. const ssrcMap = new Map();
  813. /**
  814. * Groups mapped by primary SSRC number
  815. * @type {Map<number,Array<SSRCGroupInfo>>}
  816. */
  817. const groupsMap = new Map();
  818. if (typeof desc !== 'object' || desc === null
  819. || typeof desc.sdp !== 'string') {
  820. logger.warn('An empty description was passed as an argument.');
  821. return ssrcMap;
  822. }
  823. const session = transform.parse(desc.sdp);
  824. if (!Array.isArray(session.media)) {
  825. return ssrcMap;
  826. }
  827. for (const mLine of session.media) {
  828. if (!Array.isArray(mLine.ssrcs)) {
  829. continue; // eslint-disable-line no-continue
  830. }
  831. if (Array.isArray(mLine.ssrcGroups)) {
  832. for (const group of mLine.ssrcGroups) {
  833. if (typeof group.semantics !== 'undefined'
  834. && typeof group.ssrcs !== 'undefined') {
  835. // Parse SSRCs and store as numbers
  836. const groupSSRCs
  837. = group.ssrcs.split(' ').map(
  838. ssrcStr => parseInt(ssrcStr, 10));
  839. const primarySSRC = groupSSRCs[0];
  840. // Note that group.semantics is already present
  841. group.ssrcs = groupSSRCs;
  842. // eslint-disable-next-line max-depth
  843. if (!groupsMap.has(primarySSRC)) {
  844. groupsMap.set(primarySSRC, []);
  845. }
  846. groupsMap.get(primarySSRC).push(group);
  847. }
  848. }
  849. }
  850. for (const ssrc of mLine.ssrcs) {
  851. if (ssrc.attribute !== 'msid') {
  852. continue; // eslint-disable-line no-continue
  853. }
  854. const msid = ssrc.value;
  855. let ssrcInfo = ssrcMap.get(msid);
  856. if (!ssrcInfo) {
  857. ssrcInfo = {
  858. ssrcs: [],
  859. groups: [],
  860. msid
  861. };
  862. ssrcMap.set(msid, ssrcInfo);
  863. }
  864. const ssrcNumber = ssrc.id;
  865. ssrcInfo.ssrcs.push(ssrcNumber);
  866. if (groupsMap.has(ssrcNumber)) {
  867. const ssrcGroups = groupsMap.get(ssrcNumber);
  868. for (const group of ssrcGroups) {
  869. ssrcInfo.groups.push(group);
  870. }
  871. }
  872. }
  873. }
  874. return ssrcMap;
  875. }
  876. /**
  877. * Takes a SessionDescription object and returns a "normalized" version.
  878. * Currently it only takes care of ordering the a=ssrc lines.
  879. */
  880. const normalizePlanB = function(desc) {
  881. if (typeof desc !== 'object' || desc === null
  882. || typeof desc.sdp !== 'string') {
  883. logger.warn('An empty description was passed as an argument.');
  884. return desc;
  885. }
  886. // eslint-disable-next-line no-shadow
  887. const transform = require('sdp-transform');
  888. const session = transform.parse(desc.sdp);
  889. if (typeof session !== 'undefined'
  890. && typeof session.media !== 'undefined'
  891. && Array.isArray(session.media)) {
  892. session.media.forEach(mLine => {
  893. // Chrome appears to be picky about the order in which a=ssrc lines
  894. // are listed in an m-line when rtx is enabled (and thus there are
  895. // a=ssrc-group lines with FID semantics). Specifically if we have
  896. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  897. // the "a=ssrc:S1" lines, SRD fails.
  898. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  899. // first.
  900. const firstSsrcs = [];
  901. const newSsrcLines = [];
  902. if (typeof mLine.ssrcGroups !== 'undefined'
  903. && Array.isArray(mLine.ssrcGroups)) {
  904. mLine.ssrcGroups.forEach(group => {
  905. if (typeof group.semantics !== 'undefined'
  906. && group.semantics === 'FID') {
  907. if (typeof group.ssrcs !== 'undefined') {
  908. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  909. }
  910. }
  911. });
  912. }
  913. if (Array.isArray(mLine.ssrcs)) {
  914. let i;
  915. for (i = 0; i < mLine.ssrcs.length; i++) {
  916. if (typeof mLine.ssrcs[i] === 'object'
  917. && typeof mLine.ssrcs[i].id !== 'undefined'
  918. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  919. newSsrcLines.push(mLine.ssrcs[i]);
  920. delete mLine.ssrcs[i];
  921. }
  922. }
  923. for (i = 0; i < mLine.ssrcs.length; i++) {
  924. if (typeof mLine.ssrcs[i] !== 'undefined') {
  925. newSsrcLines.push(mLine.ssrcs[i]);
  926. }
  927. }
  928. mLine.ssrcs = newSsrcLines;
  929. }
  930. });
  931. }
  932. const resStr = transform.write(session);
  933. return new RTCSessionDescription({
  934. type: desc.type,
  935. sdp: resStr
  936. });
  937. };
  938. /**
  939. * Makes sure that both audio and video directions are configured as 'sendrecv'.
  940. * @param {Object} localDescription the SDP object as defined by WebRTC.
  941. */
  942. const enforceSendRecv = function(localDescription) {
  943. if (!localDescription) {
  944. throw new Error('No local description passed in.');
  945. }
  946. const transformer = new SdpTransformWrap(localDescription.sdp);
  947. const audioMedia = transformer.selectMedia('audio');
  948. let changed = false;
  949. if (audioMedia && audioMedia.direction !== 'sendrecv') {
  950. audioMedia.direction = 'sendrecv';
  951. changed = true;
  952. }
  953. const videoMedia = transformer.selectMedia('video');
  954. if (videoMedia && videoMedia.direction !== 'sendrecv') {
  955. videoMedia.direction = 'sendrecv';
  956. changed = true;
  957. }
  958. if (changed) {
  959. return new RTCSessionDescription({
  960. type: localDescription.type,
  961. sdp: transformer.toRawSDP()
  962. });
  963. }
  964. return localDescription;
  965. };
  966. /**
  967. *
  968. * @param {JitsiLocalTrack} localTrack
  969. */
  970. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  971. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  972. return ssrcInfo && ssrcInfo.ssrcs[0];
  973. };
  974. /**
  975. * When doing unified plan simulcast, we'll have a set of ssrcs with the
  976. * same msid but no ssrc-group, since unified plan signals the simulcast
  977. * group via the a=simulcast line. Unfortunately, Jicofo will complain
  978. * if it sees ssrcs with matching msids but no ssrc-group, so we'll inject
  979. * an ssrc-group line to make Jicofo happy.
  980. * NOTE: unlike plan B simulcast, the ssrcs in this inject ssrc-group will
  981. * NOT necessarily be in order of quality (low to high) because:
  982. * a) when translating between unified plan and plan b the order of the ssrcs
  983. * is not preserved and
  984. * b) it isn't guaranteed that firefox will give them to us in order to begin
  985. * with
  986. * @param desc A session description object (with 'type' and 'sdp' fields)
  987. * @return A session description object with its sdp field modified to
  988. * contain an inject ssrc-group for simulcast
  989. */
  990. TraceablePeerConnection.prototype._injectSsrcGroupForUnifiedSimulcast
  991. = function(desc) {
  992. const sdp = transform.parse(desc.sdp);
  993. const video = sdp.media.find(mline => mline.type === 'video');
  994. if (video.simulcast_03) {
  995. const ssrcs = [];
  996. video.ssrcs.forEach(ssrc => {
  997. if (ssrc.attribute === 'msid') {
  998. ssrcs.push(ssrc.id);
  999. }
  1000. });
  1001. video.ssrcGroups = video.ssrcGroups || [];
  1002. if (video.ssrcGroups.find(group => group.semantics === 'SIM')) {
  1003. // Group already exists, no need to do anything
  1004. return desc;
  1005. }
  1006. video.ssrcGroups.push({
  1007. semantics: 'SIM',
  1008. ssrcs: ssrcs.join(' ')
  1009. });
  1010. }
  1011. return new RTCSessionDescription({
  1012. type: desc.type,
  1013. sdp: transform.write(sdp)
  1014. });
  1015. };
  1016. /* eslint-disable-next-line vars-on-top */
  1017. const getters = {
  1018. signalingState() {
  1019. return this.peerconnection.signalingState;
  1020. },
  1021. iceConnectionState() {
  1022. return this.peerconnection.iceConnectionState;
  1023. },
  1024. localDescription() {
  1025. let desc = this.peerconnection.localDescription;
  1026. if (!desc) {
  1027. logger.debug('getLocalDescription no localDescription found');
  1028. return {};
  1029. }
  1030. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1031. // if we're running on FF, transform to Plan B first.
  1032. if (browser.usesUnifiedPlan()) {
  1033. desc = this.interop.toPlanB(desc);
  1034. this.trace('getLocalDescription::postTransform (Plan B)',
  1035. dumpSDP(desc));
  1036. desc = this._injectSsrcGroupForUnifiedSimulcast(desc);
  1037. this.trace('getLocalDescription::postTransform (inject ssrc group)',
  1038. dumpSDP(desc));
  1039. }
  1040. if (browser.doesVideoMuteByStreamRemove()) {
  1041. desc = this.localSdpMunger.maybeAddMutedLocalVideoTracksToSDP(desc);
  1042. logger.debug(
  1043. 'getLocalDescription::postTransform (munge local SDP)', desc);
  1044. }
  1045. // What comes out of this getter will be signalled over Jingle to
  1046. // the other peer, so we need to make sure the media direction is
  1047. // 'sendrecv' because we won't change the direction later and don't want
  1048. // the other peer to think we can't send or receive.
  1049. //
  1050. // Note that the description we set in chrome does have the accurate
  1051. // direction (e.g. 'recvonly'), since that is technically what is
  1052. // happening (check setLocalDescription impl).
  1053. desc = enforceSendRecv(desc);
  1054. // See the method's doc for more info about this transformation.
  1055. desc = this.localSdpMunger.transformStreamIdentifiers(desc);
  1056. return desc;
  1057. },
  1058. remoteDescription() {
  1059. let desc = this.peerconnection.remoteDescription;
  1060. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1061. // if we're running on FF, transform to Plan B first.
  1062. if (browser.usesUnifiedPlan()) {
  1063. desc = this.interop.toPlanB(desc);
  1064. this.trace(
  1065. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  1066. }
  1067. return desc || {};
  1068. }
  1069. };
  1070. Object.keys(getters).forEach(prop => {
  1071. Object.defineProperty(
  1072. TraceablePeerConnection.prototype,
  1073. prop, {
  1074. get: getters[prop]
  1075. }
  1076. );
  1077. });
  1078. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1079. return this.localSSRCs.get(rtcId);
  1080. };
  1081. /**
  1082. * Add {@link JitsiLocalTrack} to this TPC.
  1083. * @param {JitsiLocalTrack} track
  1084. */
  1085. TraceablePeerConnection.prototype.addTrack = function(track) {
  1086. const rtcId = track.rtcId;
  1087. logger.info(`add ${track} to: ${this}`);
  1088. if (this.localTracks.has(rtcId)) {
  1089. logger.error(`${track} is already in ${this}`);
  1090. return;
  1091. }
  1092. this.localTracks.set(rtcId, track);
  1093. const webrtcStream = track.getOriginalStream();
  1094. if (webrtcStream) {
  1095. this._addStream(webrtcStream);
  1096. // It's not ok for a track to not have a WebRTC stream if:
  1097. } else if (!browser.doesVideoMuteByStreamRemove()
  1098. || track.isAudioTrack()
  1099. || (track.isVideoTrack() && !track.isMuted())) {
  1100. logger.error(`${this} no WebRTC stream for: ${track}`);
  1101. }
  1102. // Muted video tracks do not have WebRTC stream
  1103. if (browser.doesVideoMuteByStreamRemove()
  1104. && track.isVideoTrack() && track.isMuted()) {
  1105. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  1106. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  1107. const simGroup
  1108. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  1109. if (simGroup) {
  1110. this.simulcast.setSsrcCache(simGroup.ssrcs);
  1111. }
  1112. const fidGroups
  1113. = ssrcInfo.groups.filter(
  1114. groupInfo => groupInfo.semantics === 'FID');
  1115. if (fidGroups) {
  1116. const rtxSsrcMapping = new Map();
  1117. fidGroups.forEach(fidGroup => {
  1118. const primarySsrc = fidGroup.ssrcs[0];
  1119. const rtxSsrc = fidGroup.ssrcs[1];
  1120. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  1121. });
  1122. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  1123. }
  1124. }
  1125. };
  1126. /**
  1127. * Adds local track as part of the unmute operation.
  1128. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  1129. * operation
  1130. * @return {boolean} <tt>true</tt> if the state of underlying PC has changed and
  1131. * the renegotiation is required or <tt>false</tt> otherwise.
  1132. */
  1133. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  1134. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  1135. // Abort
  1136. return false;
  1137. }
  1138. logger.info(`Adding ${track} as unmute to ${this}`);
  1139. const webRtcStream = track.getOriginalStream();
  1140. if (!webRtcStream) {
  1141. logger.error(
  1142. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  1143. return false;
  1144. }
  1145. this._addStream(webRtcStream);
  1146. return true;
  1147. };
  1148. /**
  1149. * Adds WebRTC media stream to the underlying PeerConnection
  1150. * @param {MediaStream} mediaStream
  1151. * @private
  1152. */
  1153. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  1154. this.peerconnection.addStream(mediaStream);
  1155. this._addedStreams.push(mediaStream);
  1156. };
  1157. /**
  1158. * Removes WebRTC media stream from the underlying PeerConection
  1159. * @param {MediaStream} mediaStream
  1160. */
  1161. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  1162. if (browser.isFirefox()) {
  1163. this._handleFirefoxRemoveStream(mediaStream);
  1164. } else {
  1165. this.peerconnection.removeStream(mediaStream);
  1166. }
  1167. this._addedStreams
  1168. = this._addedStreams.filter(stream => stream !== mediaStream);
  1169. };
  1170. /**
  1171. * This method when called will check if given <tt>localTrack</tt> belongs to
  1172. * this TPC (that it has been previously added using {@link addTrack}). If the
  1173. * track does not belong an error message will be logged.
  1174. * @param {string} methodName the method name that will be logged in an error
  1175. * message
  1176. * @param {JitsiLocalTrack} localTrack
  1177. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1178. * <tt>false</tt> otherwise.
  1179. * @private
  1180. */
  1181. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1182. methodName,
  1183. localTrack) {
  1184. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1185. if (!doesBelong) {
  1186. logger.error(
  1187. `${methodName}: ${localTrack} does not belong to ${this}`);
  1188. }
  1189. return doesBelong;
  1190. };
  1191. /**
  1192. * Tells if the given WebRTC <tt>MediaStream</tt> has been added to
  1193. * the underlying WebRTC PeerConnection.
  1194. * @param {MediaStream} mediaStream
  1195. * @returns {boolean}
  1196. */
  1197. TraceablePeerConnection.prototype.isMediaStreamInPc = function(mediaStream) {
  1198. return this._addedStreams.indexOf(mediaStream) > -1;
  1199. };
  1200. /**
  1201. * Remove local track from this TPC.
  1202. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1203. *
  1204. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1205. * The same applies to addTrack.
  1206. */
  1207. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1208. const webRtcStream = localTrack.getOriginalStream();
  1209. this.trace(
  1210. 'removeStream',
  1211. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1212. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1213. // Abort - nothing to be done here
  1214. return;
  1215. }
  1216. this.localTracks.delete(localTrack.rtcId);
  1217. this.localSSRCs.delete(localTrack.rtcId);
  1218. if (webRtcStream) {
  1219. if (browser.isFirefox()) {
  1220. this._handleFirefoxRemoveStream(webRtcStream);
  1221. } else {
  1222. this.peerconnection.removeStream(webRtcStream);
  1223. }
  1224. }
  1225. };
  1226. /**
  1227. * Returns the sender corresponding to the given MediaStream.
  1228. *
  1229. * @param {MediaStream} stream - The media stream used for the search.
  1230. * @returns {RTPSender|undefined} - The found sender or undefined if no sender
  1231. * was found.
  1232. */
  1233. TraceablePeerConnection.prototype.findSenderByStream = function(stream) {
  1234. const track = stream.getTracks()[0];
  1235. if (!track) {
  1236. logger.error('Cannot find sender: no tracks.');
  1237. return;
  1238. }
  1239. // Find the right sender (for audio or video)
  1240. return this.peerconnection.getSenders().find(s => s.track === track);
  1241. };
  1242. /**
  1243. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1244. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1245. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1246. * <tt>oldTrack</tt>
  1247. *
  1248. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be
  1249. * replaced
  1250. * @param {JitsiLocalTrack|null} newTrack - The new track to use
  1251. * @returns {Promise<boolean>} - If the promise resolves with true,
  1252. * renegotiation will be needed. Otherwise no renegotiation is needed.
  1253. */
  1254. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack) {
  1255. if (browser.isFirefox() && oldTrack && newTrack) {
  1256. // Add and than remove stream in FF leads to wrong local SDP. In order
  1257. // to workaround the issue we need to use sender.replaceTrack().
  1258. const sender = this.findSenderByStream(oldTrack.getOriginalStream());
  1259. const stream = newTrack.getOriginalStream();
  1260. if (sender && stream) {
  1261. const track = stream.getTracks()[0];
  1262. if (track) {
  1263. return sender.replaceTrack(track, stream).then(() => {
  1264. // Since there is no need to do renegotiations we need to
  1265. // fix all ssrc-msid mappings here.
  1266. // NOTE: after sender.replaceTrack the sdp will remain the
  1267. // same but the stream attach to the new JitsiLocalTrack
  1268. // will have different msid. Luckily on FF we are not doing
  1269. // all the transformations related to video mute.
  1270. const ssrc = this.localSSRCs.get(oldTrack.rtcId);
  1271. this.localTracks.delete(oldTrack.rtcId);
  1272. this.localSSRCs.delete(oldTrack.rtcId);
  1273. this._addedStreams
  1274. = this._addedStreams.filter(s => s !== stream);
  1275. this.localTracks.set(newTrack.rtcId, newTrack);
  1276. // Override the msid of JitsiLocalTrack in order to be
  1277. // consistent with the SDP values.
  1278. newTrack.storedMSID = oldTrack.storedMSID;
  1279. this._addedStreams.push(stream);
  1280. this.localSSRCs.set(newTrack.rtcId, ssrc);
  1281. this.eventEmitter.emit(
  1282. RTCEvents.LOCAL_TRACK_SSRC_UPDATED,
  1283. newTrack,
  1284. extractPrimarySSRC(ssrc));
  1285. return false;
  1286. });
  1287. }
  1288. }
  1289. }
  1290. if (oldTrack) {
  1291. this.removeTrack(oldTrack);
  1292. }
  1293. if (newTrack) {
  1294. this.addTrack(newTrack);
  1295. }
  1296. return Promise.resolve(true);
  1297. };
  1298. /**
  1299. * Removes local track as part of the mute operation.
  1300. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1301. * the mute operation.
  1302. * @return {boolean} <tt>true</tt> if the underlying PeerConnection's state has
  1303. * changed and the renegotiation is required or <tt>false</tt> otherwise.
  1304. */
  1305. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1306. const webRtcStream = localTrack.getOriginalStream();
  1307. this.trace(
  1308. 'removeStreamMute',
  1309. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1310. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1311. // Abort - nothing to be done here
  1312. return false;
  1313. }
  1314. if (webRtcStream) {
  1315. logger.info(
  1316. `Removing ${localTrack} as mute from ${this}`);
  1317. this._removeStream(webRtcStream);
  1318. return true;
  1319. }
  1320. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1321. return false;
  1322. };
  1323. /**
  1324. * Remove stream handling for firefox
  1325. * @param stream: webrtc media stream
  1326. */
  1327. TraceablePeerConnection.prototype._handleFirefoxRemoveStream = function(
  1328. stream) {
  1329. if (!stream) {
  1330. // There is nothing to be changed
  1331. return;
  1332. }
  1333. const sender = this.findSenderByStream(stream);
  1334. if (sender) {
  1335. this.peerconnection.removeTrack(sender);
  1336. } else {
  1337. logger.log('Cannot remove tracks: no RTPSender.');
  1338. }
  1339. };
  1340. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1341. this.trace('createDataChannel', label, opts);
  1342. return this.peerconnection.createDataChannel(label, opts);
  1343. };
  1344. /**
  1345. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1346. * in the SDP so that simulcast is properly activated.
  1347. *
  1348. * @param {Object} localSdp the WebRTC session description instance for
  1349. * the local description.
  1350. * @private
  1351. */
  1352. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast = function(
  1353. localSdp) {
  1354. let sdpStr = localSdp.sdp;
  1355. const videoStartIndex = sdpStr.indexOf('m=video');
  1356. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1357. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1358. if (simStartIndex === -1
  1359. || otherStartIndex === -1
  1360. || otherStartIndex === simStartIndex) {
  1361. return localSdp;
  1362. }
  1363. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1364. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1365. sdpStr = sdpStr.replace(simStr, '');
  1366. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1367. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1368. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1369. const simStrTrimmed = simStr.trim();
  1370. const sdpTail = sdpStr.slice(otherEndIndex);
  1371. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1372. return new RTCSessionDescription({
  1373. type: localSdp.type,
  1374. sdp: sdpStr
  1375. });
  1376. };
  1377. /**
  1378. * Will adjust audio and video media direction in the given SDP object to
  1379. * reflect the current status of the {@link audioTransferActive} and
  1380. * {@link videoTransferActive} flags.
  1381. * @param {Object} localDescription the WebRTC session description instance for
  1382. * the local description.
  1383. * @private
  1384. */
  1385. TraceablePeerConnection.prototype._adjustLocalMediaDirection = function(
  1386. localDescription) {
  1387. const transformer = new SdpTransformWrap(localDescription.sdp);
  1388. let modifiedDirection = false;
  1389. const audioMedia = transformer.selectMedia('audio');
  1390. if (audioMedia) {
  1391. const desiredAudioDirection
  1392. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1393. if (audioMedia.direction !== desiredAudioDirection) {
  1394. audioMedia.direction = desiredAudioDirection;
  1395. logger.info(
  1396. `Adjusted local audio direction to ${desiredAudioDirection}`);
  1397. modifiedDirection = true;
  1398. }
  1399. } else {
  1400. logger.warn('No "audio" media found int the local description');
  1401. }
  1402. const videoMedia = transformer.selectMedia('video');
  1403. if (videoMedia) {
  1404. const desiredVideoDirection
  1405. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1406. if (videoMedia.direction !== desiredVideoDirection) {
  1407. videoMedia.direction = desiredVideoDirection;
  1408. logger.info(
  1409. `Adjusted local video direction to ${desiredVideoDirection}`);
  1410. modifiedDirection = true;
  1411. }
  1412. } else {
  1413. logger.warn('No "video" media found in the local description');
  1414. }
  1415. if (modifiedDirection) {
  1416. return new RTCSessionDescription({
  1417. type: localDescription.type,
  1418. sdp: transformer.toRawSDP()
  1419. });
  1420. }
  1421. return localDescription;
  1422. };
  1423. TraceablePeerConnection.prototype.setLocalDescription = function(description) {
  1424. let localSdp = description;
  1425. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1426. if (this.options.disableH264 || this.options.preferH264) {
  1427. const parsedSdp = transform.parse(localSdp.sdp);
  1428. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1429. if (this.options.disableH264) {
  1430. SDPUtil.stripVideoCodec(videoMLine, 'h264');
  1431. } else {
  1432. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1433. }
  1434. localSdp = new RTCSessionDescription({
  1435. type: localSdp.type,
  1436. sdp: transform.write(parsedSdp)
  1437. });
  1438. this.trace('setLocalDescription::postTransform (H264)',
  1439. dumpSDP(localSdp));
  1440. }
  1441. localSdp = this._adjustLocalMediaDirection(localSdp);
  1442. localSdp = this._ensureSimulcastGroupIsLast(localSdp);
  1443. // if we're using unified plan, transform to it first.
  1444. if (browser.usesUnifiedPlan()) {
  1445. localSdp = this.interop.toUnifiedPlan(localSdp);
  1446. this.trace(
  1447. 'setLocalDescription::postTransform (Unified Plan)',
  1448. dumpSDP(localSdp));
  1449. }
  1450. return new Promise((resolve, reject) => {
  1451. this.peerconnection.setLocalDescription(localSdp)
  1452. .then(() => {
  1453. this.trace('setLocalDescriptionOnSuccess');
  1454. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1455. if (localUfrag !== this.localUfrag) {
  1456. this.localUfrag = localUfrag;
  1457. this.eventEmitter.emit(
  1458. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1459. }
  1460. resolve();
  1461. })
  1462. .catch(err => {
  1463. this.trace('setLocalDescriptionOnFailure', err);
  1464. this.eventEmitter.emit(
  1465. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1466. err, this);
  1467. reject(err);
  1468. });
  1469. });
  1470. };
  1471. /**
  1472. * Enables/disables audio media transmission on this peer connection. When
  1473. * disabled the SDP audio media direction in the local SDP will be adjusted to
  1474. * 'inactive' which means that no data will be sent nor accepted, but
  1475. * the connection should be kept alive.
  1476. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  1477. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1478. * no effect.
  1479. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1480. * needs to be executed in order for the changes to take effect or
  1481. * <tt>false</tt> if the given value was the same as the previous one.
  1482. * @public
  1483. */
  1484. TraceablePeerConnection.prototype.setAudioTransferActive = function(active) {
  1485. logger.debug(`${this} audio transfer active: ${active}`);
  1486. const changed = this.audioTransferActive !== active;
  1487. this.audioTransferActive = active;
  1488. return changed;
  1489. };
  1490. /**
  1491. * Takes in a *unified plan* offer and inserts the appropriate
  1492. * parameters for adding simulcast receive support.
  1493. * @param {Object} desc - A session description object
  1494. * @param {String} desc.type - the type (offer/answer)
  1495. * @param {String} desc.sdp - the sdp content
  1496. *
  1497. * @return {Object} A session description (same format as above) object
  1498. * with its sdp field modified to advertise simulcast receive support
  1499. */
  1500. TraceablePeerConnection.prototype._insertUnifiedPlanSimulcastReceive
  1501. = function(desc) {
  1502. const sdp = transform.parse(desc.sdp);
  1503. const video = sdp.media.find(mline => mline.type === 'video');
  1504. // In order of lowest to highest spatial quality
  1505. video.rids = [
  1506. {
  1507. id: SIM_LAYER_1_RID,
  1508. direction: 'recv'
  1509. },
  1510. {
  1511. id: SIM_LAYER_2_RID,
  1512. direction: 'recv'
  1513. },
  1514. {
  1515. id: SIM_LAYER_3_RID,
  1516. direction: 'recv'
  1517. }
  1518. ];
  1519. // eslint-disable-next-line camelcase
  1520. video.simulcast_03 = {
  1521. value: `recv rid=${SIM_LAYER_RIDS.join(';')}`
  1522. };
  1523. return new RTCSessionDescription({
  1524. type: desc.type,
  1525. sdp: transform.write(sdp)
  1526. });
  1527. };
  1528. TraceablePeerConnection.prototype.setRemoteDescription = function(description) {
  1529. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1530. // TODO the focus should squeze or explode the remote simulcast
  1531. // eslint-disable-next-line no-param-reassign
  1532. description = this.simulcast.mungeRemoteDescription(description);
  1533. this.trace(
  1534. 'setRemoteDescription::postTransform (simulcast)',
  1535. dumpSDP(description));
  1536. if (this.options.preferH264) {
  1537. const parsedSdp = transform.parse(description.sdp);
  1538. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1539. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1540. // eslint-disable-next-line no-param-reassign
  1541. description = new RTCSessionDescription({
  1542. type: description.type,
  1543. sdp: transform.write(parsedSdp)
  1544. });
  1545. }
  1546. // If the browser uses unified plan, transform to it first
  1547. if (browser.usesUnifiedPlan()) {
  1548. // eslint-disable-next-line no-param-reassign
  1549. description = new RTCSessionDescription({
  1550. type: description.type,
  1551. sdp: this.rtxModifier.stripRtx(description.sdp)
  1552. });
  1553. this.trace(
  1554. 'setRemoteDescription::postTransform (stripRtx)',
  1555. dumpSDP(description));
  1556. // eslint-disable-next-line no-param-reassign
  1557. description = this.interop.toUnifiedPlan(description);
  1558. this.trace(
  1559. 'setRemoteDescription::postTransform (Plan A)',
  1560. dumpSDP(description));
  1561. if (this.isSimulcastOn()) {
  1562. // eslint-disable-next-line no-param-reassign
  1563. description = this._insertUnifiedPlanSimulcastReceive(description);
  1564. this.trace(
  1565. 'setRemoteDescription::postTransform (sim receive)',
  1566. dumpSDP(description));
  1567. }
  1568. } else {
  1569. // Plan B
  1570. // eslint-disable-next-line no-param-reassign
  1571. description = normalizePlanB(description);
  1572. }
  1573. // Safari WebRTC errors when no supported video codec is found in the offer.
  1574. // To prevent the error, inject H264 into the video mLine.
  1575. if (browser.isSafariWithWebrtc()) {
  1576. logger.debug('Maybe injecting H264 into the remote description');
  1577. // eslint-disable-next-line no-param-reassign
  1578. description = this._injectH264IfNotPresent(description);
  1579. }
  1580. return new Promise((resolve, reject) => {
  1581. this.peerconnection.setRemoteDescription(description)
  1582. .then(() => {
  1583. this.trace('setRemoteDescriptionOnSuccess');
  1584. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  1585. if (remoteUfrag !== this.remoteUfrag) {
  1586. this.remoteUfrag = remoteUfrag;
  1587. this.eventEmitter.emit(
  1588. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1589. }
  1590. resolve();
  1591. })
  1592. .catch(err => {
  1593. this.trace('setRemoteDescriptionOnFailure', err);
  1594. this.eventEmitter.emit(
  1595. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  1596. err,
  1597. this);
  1598. reject(err);
  1599. });
  1600. });
  1601. };
  1602. /**
  1603. * Inserts an H264 payload into the description if not already present. This is
  1604. * need for Safari WebRTC, which errors when no supported video codec is found
  1605. * in the offer. Related bug reports:
  1606. * https://bugs.webkit.org/show_bug.cgi?id=173141
  1607. * https://bugs.chromium.org/p/webrtc/issues/detail?id=4957
  1608. *
  1609. * @param {RTCSessionDescription} description - An RTCSessionDescription
  1610. * to inject with an H264 payload.
  1611. * @private
  1612. * @returns {RTCSessionDescription}
  1613. */
  1614. TraceablePeerConnection.prototype._injectH264IfNotPresent = function(
  1615. description) {
  1616. const parsedSdp = transform.parse(description.sdp);
  1617. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1618. if (!videoMLine) {
  1619. logger.debug('No videoMLine found, no need to inject H264.');
  1620. return description;
  1621. }
  1622. if (videoMLine.rtp.some(rtp => rtp.codec.toLowerCase() === 'h264')) {
  1623. logger.debug('H264 codec found in video mLine, no need to inject.');
  1624. return description;
  1625. }
  1626. const { fmtp, payloads, rtp } = videoMLine;
  1627. const payloadsArray = payloads.toString().split(' ');
  1628. let dummyPayloadType;
  1629. for (let i = 127; i >= 96; i--) {
  1630. if (!payloadsArray.includes(i)) {
  1631. dummyPayloadType = i;
  1632. payloadsArray.push(i);
  1633. videoMLine.payloads = payloadsArray.join(' ');
  1634. break;
  1635. }
  1636. }
  1637. if (typeof dummyPayloadType === 'undefined') {
  1638. logger.error('Could not find valid payload type to inject.');
  1639. return description;
  1640. }
  1641. rtp.push({
  1642. codec: 'H264',
  1643. payload: dummyPayloadType,
  1644. rate: 90000
  1645. });
  1646. fmtp.push({
  1647. config: 'level-asymmetry-allowed=1;'
  1648. + 'packetization-mode=1;'
  1649. + 'profile-level-id=42e01f',
  1650. payload: dummyPayloadType
  1651. });
  1652. logger.debug(
  1653. `Injecting H264 payload type ${dummyPayloadType} into video mLine.`);
  1654. return new RTCSessionDescription({
  1655. type: description.type,
  1656. sdp: transform.write(parsedSdp)
  1657. });
  1658. };
  1659. /**
  1660. * Enables/disables video media transmission on this peer connection. When
  1661. * disabled the SDP video media direction in the local SDP will be adjusted to
  1662. * 'inactive' which means that no data will be sent nor accepted, but
  1663. * the connection should be kept alive.
  1664. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  1665. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1666. * no effect.
  1667. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1668. * needs to be executed in order for the changes to take effect or
  1669. * <tt>false</tt> if the given value was the same as the previous one.
  1670. * @public
  1671. */
  1672. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  1673. logger.debug(`${this} video transfer active: ${active}`);
  1674. const changed = this.videoTransferActive !== active;
  1675. this.videoTransferActive = active;
  1676. return changed;
  1677. };
  1678. /**
  1679. * Makes the underlying TraceablePeerConnection generate new SSRC for
  1680. * the recvonly video stream.
  1681. */
  1682. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  1683. const newSSRC = SDPUtil.generateSsrc();
  1684. logger.info(`${this} generated new recvonly SSRC: ${newSSRC}`);
  1685. this.sdpConsistency.setPrimarySsrc(newSSRC);
  1686. };
  1687. /**
  1688. * Makes the underlying TraceablePeerConnection forget the current primary video
  1689. * SSRC.
  1690. */
  1691. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  1692. logger.info('Clearing primary video SSRC!');
  1693. this.sdpConsistency.clearVideoSsrcCache();
  1694. };
  1695. /**
  1696. * Closes underlying WebRTC PeerConnection instance and removes all remote
  1697. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  1698. * them.
  1699. */
  1700. TraceablePeerConnection.prototype.close = function() {
  1701. this.trace('stop');
  1702. // Off SignalingEvents
  1703. this.signalingLayer.off(
  1704. SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  1705. this.signalingLayer.off(
  1706. SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  1707. for (const peerTracks of this.remoteTracks.values()) {
  1708. for (const remoteTrack of peerTracks.values()) {
  1709. this._removeRemoteTrack(remoteTrack);
  1710. }
  1711. }
  1712. this.remoteTracks.clear();
  1713. this._addedStreams = [];
  1714. if (!this.rtc._removePeerConnection(this)) {
  1715. logger.error('RTC._removePeerConnection returned false');
  1716. }
  1717. if (this.statsinterval !== null) {
  1718. window.clearInterval(this.statsinterval);
  1719. this.statsinterval = null;
  1720. }
  1721. logger.info(`Closing ${this}...`);
  1722. this.peerconnection.close();
  1723. };
  1724. /**
  1725. * Modifies the values of the setup attributes (defined by
  1726. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  1727. * answer in order to overcome a delay of 1 second in the connection
  1728. * establishment between Chrome and Videobridge.
  1729. *
  1730. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  1731. * being prepared to respond
  1732. * @param {SDP} answer - the SDP to modify
  1733. * @private
  1734. */
  1735. const _fixAnswerRFC4145Setup = function(offer, answer) {
  1736. if (!browser.isChrome()) {
  1737. // It looks like Firefox doesn't agree with the fix (at least in its
  1738. // current implementation) because it effectively remains active even
  1739. // after we tell it to become passive. Apart from Firefox which I tested
  1740. // after the fix was deployed, I tested Chrome only. In order to prevent
  1741. // issues with other browsers, limit the fix to Chrome for the time
  1742. // being.
  1743. return;
  1744. }
  1745. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  1746. // answerer (as orchestrated by Jicofo). In accord with
  1747. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  1748. // are ICE FULL agents, Videobridge will take on the controlling role and
  1749. // WebRTC will take on the controlled role. In accord with
  1750. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  1751. // setup attribute value of setup:actpass and WebRTC will be allowed to
  1752. // choose either the setup attribute value of setup:active or
  1753. // setup:passive. Chrome will by default choose setup:active because it is
  1754. // RECOMMENDED by the respective RFC since setup:passive adds additional
  1755. // latency. The case of setup:active allows WebRTC to send a DTLS
  1756. // ClientHello as soon as an ICE connectivity check of its succeeds.
  1757. // Unfortunately, Videobridge will be unable to respond immediately because
  1758. // may not have WebRTC's answer or may have not completed the ICE
  1759. // connectivity establishment. Even more unfortunate is that in the
  1760. // described scenario Chrome's DTLS implementation will insist on
  1761. // retransmitting its ClientHello after a second (the time is in accord
  1762. // with the respective RFC) and will thus cause the whole connection
  1763. // establishment to exceed at least 1 second. To work around Chrome's
  1764. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  1765. // default choice of setup:active to setup:passive.
  1766. if (offer && answer
  1767. && offer.media && answer.media
  1768. && offer.media.length === answer.media.length) {
  1769. answer.media.forEach((a, i) => {
  1770. if (SDPUtil.findLine(
  1771. offer.media[i],
  1772. 'a=setup:actpass',
  1773. offer.session)) {
  1774. answer.media[i]
  1775. = a.replace(/a=setup:active/g, 'a=setup:passive');
  1776. }
  1777. });
  1778. answer.raw = answer.session + answer.media.join('');
  1779. }
  1780. };
  1781. TraceablePeerConnection.prototype.createAnswer = function(constraints) {
  1782. if (browser.supportsRtpSender() && this.isSimulcastOn()) {
  1783. const videoSender
  1784. = this.peerconnection.getSenders().find(sender =>
  1785. sender.track.kind === 'video');
  1786. const simParams = {
  1787. encodings: [
  1788. {
  1789. rid: SIM_LAYER_1_RID,
  1790. scaleResolutionDownBy: 4
  1791. },
  1792. {
  1793. rid: SIM_LAYER_2_RID,
  1794. scaleResolutionDownBy: 2
  1795. },
  1796. {
  1797. rid: SIM_LAYER_3_RID
  1798. }
  1799. ]
  1800. };
  1801. videoSender.setParameters(simParams);
  1802. }
  1803. return this._createOfferOrAnswer(false /* answer */, constraints);
  1804. };
  1805. TraceablePeerConnection.prototype.createOffer = function(constraints) {
  1806. return this._createOfferOrAnswer(true /* offer */, constraints);
  1807. };
  1808. TraceablePeerConnection.prototype._createOfferOrAnswer = function(
  1809. isOffer,
  1810. constraints) {
  1811. const logName = isOffer ? 'Offer' : 'Answer';
  1812. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  1813. const handleSuccess = (resultSdp, resolveFn, rejectFn) => {
  1814. try {
  1815. this.trace(
  1816. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  1817. // if we're using unified plan, transform to Plan B.
  1818. if (browser.usesUnifiedPlan()) {
  1819. // eslint-disable-next-line no-param-reassign
  1820. resultSdp = this.interop.toPlanB(resultSdp);
  1821. this.trace(
  1822. `create${logName}OnSuccess::postTransform (Plan B)`,
  1823. dumpSDP(resultSdp));
  1824. if (this.isSimulcastOn()) {
  1825. // eslint-disable-next-line no-param-reassign
  1826. resultSdp
  1827. = this._injectSsrcGroupForUnifiedSimulcast(resultSdp);
  1828. this.trace(
  1829. `create${logName}OnSuccess::postTransform`
  1830. + '(inject ssrc group)', dumpSDP(resultSdp));
  1831. }
  1832. }
  1833. /**
  1834. * We don't keep ssrcs consitent for Firefox because rewriting
  1835. * the ssrcs between createAnswer and setLocalDescription breaks
  1836. * the caching in sdp-interop (sdp-interop must know about all
  1837. * ssrcs, and it updates its cache in toPlanB so if we rewrite them
  1838. * after that, when we try and go back to unified plan it will
  1839. * complain about unmapped ssrcs)
  1840. */
  1841. if (!browser.isFirefox()) {
  1842. // If there are no local video tracks, then a "recvonly"
  1843. // SSRC needs to be generated
  1844. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  1845. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  1846. this.generateRecvonlySsrc();
  1847. }
  1848. // eslint-disable-next-line no-param-reassign
  1849. resultSdp = new RTCSessionDescription({
  1850. type: resultSdp.type,
  1851. sdp: this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  1852. resultSdp.sdp)
  1853. });
  1854. this.trace(
  1855. `create${logName}OnSuccess::postTransform `
  1856. + '(make primary audio/video ssrcs consistent)',
  1857. dumpSDP(resultSdp));
  1858. }
  1859. // Add simulcast streams if simulcast is enabled
  1860. if (this.isSimulcastOn()) {
  1861. // eslint-disable-next-line no-param-reassign
  1862. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  1863. this.trace(
  1864. `create${logName}`
  1865. + 'OnSuccess::postTransform (simulcast)',
  1866. dumpSDP(resultSdp));
  1867. }
  1868. if (!this.options.disableRtx && browser.supportsRtx()) {
  1869. // eslint-disable-next-line no-param-reassign
  1870. resultSdp = new RTCSessionDescription({
  1871. type: resultSdp.type,
  1872. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  1873. });
  1874. this.trace(
  1875. `create${logName}`
  1876. + 'OnSuccess::postTransform (rtx modifier)',
  1877. dumpSDP(resultSdp));
  1878. }
  1879. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  1880. // details)
  1881. if (!isOffer) {
  1882. const remoteDescription
  1883. = new SDP(this.remoteDescription.sdp);
  1884. const localDescription = new SDP(resultSdp.sdp);
  1885. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  1886. // eslint-disable-next-line no-param-reassign
  1887. resultSdp = new RTCSessionDescription({
  1888. type: resultSdp.type,
  1889. sdp: localDescription.raw
  1890. });
  1891. }
  1892. const ssrcMap = extractSSRCMap(resultSdp);
  1893. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  1894. this._processLocalSSRCsMap(ssrcMap);
  1895. resolveFn(resultSdp);
  1896. } catch (e) {
  1897. this.trace(`create${logName}OnError`, e);
  1898. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  1899. logger.error(`create${logName}OnError`, e, dumpSDP(resultSdp));
  1900. rejectFn(e);
  1901. }
  1902. };
  1903. const handleFailure = (err, rejectFn) => {
  1904. this.trace(`create${logName}OnFailure`, err);
  1905. const eventType
  1906. = isOffer
  1907. ? RTCEvents.CREATE_OFFER_FAILED
  1908. : RTCEvents.CREATE_ANSWER_FAILED;
  1909. this.eventEmitter.emit(eventType, err, this);
  1910. rejectFn(err);
  1911. };
  1912. return new Promise((resolve, reject) => {
  1913. let oaPromise;
  1914. if (isOffer) {
  1915. oaPromise = this.peerconnection.createOffer(constraints);
  1916. } else {
  1917. oaPromise = this.peerconnection.createAnswer(constraints);
  1918. }
  1919. oaPromise
  1920. .then(sdp => handleSuccess(sdp, resolve, reject))
  1921. .catch(error => handleFailure(error, reject));
  1922. });
  1923. };
  1924. /**
  1925. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  1926. * @param {TrackSSRCInfo} ssrcObj
  1927. * @return {number|null} the primary SSRC or <tt>null</tt>
  1928. */
  1929. function extractPrimarySSRC(ssrcObj) {
  1930. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  1931. return ssrcObj.groups[0].ssrcs[0];
  1932. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  1933. return ssrcObj.ssrcs[0];
  1934. }
  1935. return null;
  1936. }
  1937. /**
  1938. * Goes over the SSRC map extracted from the latest local description and tries
  1939. * to match them with the local tracks (by MSID). Will update the values
  1940. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  1941. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  1942. * @private
  1943. */
  1944. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  1945. for (const track of this.localTracks.values()) {
  1946. const trackMSID = track.storedMSID;
  1947. if (ssrcMap.has(trackMSID)) {
  1948. const newSSRC = ssrcMap.get(trackMSID);
  1949. if (!newSSRC) {
  1950. logger.error(`No SSRC found for: ${trackMSID} in ${this}`);
  1951. return;
  1952. }
  1953. const oldSSRC = this.localSSRCs.get(track.rtcId);
  1954. const newSSRCNum = extractPrimarySSRC(newSSRC);
  1955. const oldSSRCNum = extractPrimarySSRC(oldSSRC);
  1956. // eslint-disable-next-line no-negated-condition
  1957. if (newSSRCNum !== oldSSRCNum) {
  1958. if (oldSSRCNum === null) {
  1959. logger.info(
  1960. `Storing new local SSRC for ${track} in ${this}`,
  1961. newSSRC);
  1962. } else {
  1963. logger.error(
  1964. `Overwriting SSRC for ${track} ${trackMSID} in ${this
  1965. } with: `, newSSRC);
  1966. }
  1967. this.localSSRCs.set(track.rtcId, newSSRC);
  1968. this.eventEmitter.emit(
  1969. RTCEvents.LOCAL_TRACK_SSRC_UPDATED, track, newSSRCNum);
  1970. } else {
  1971. logger.debug(
  1972. `The local SSRC(${newSSRCNum}) for ${track} ${trackMSID}`
  1973. + `is still up to date in ${this}`);
  1974. }
  1975. } else {
  1976. logger.warn(`No local track matched with: ${trackMSID} in ${this}`);
  1977. }
  1978. }
  1979. };
  1980. TraceablePeerConnection.prototype.addIceCandidate = function(candidate) {
  1981. this.trace('addIceCandidate', JSON.stringify({
  1982. candidate: candidate.candidate,
  1983. sdpMid: candidate.sdpMid,
  1984. sdpMLineIndex: candidate.sdpMLineIndex,
  1985. usernameFragment: candidate.usernameFragment
  1986. }, null, ' '));
  1987. return this.peerconnection.addIceCandidate(candidate);
  1988. };
  1989. /**
  1990. * Obtains call-related stats from the peer connection.
  1991. *
  1992. * @param {Function} callback - The function to invoke after successfully
  1993. * obtaining stats.
  1994. * @param {Function} errback - The function to invoke after failing to obtain
  1995. * stats.
  1996. * @returns {void}
  1997. */
  1998. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  1999. // TODO (brian): After moving all browsers to adapter, check if adapter is
  2000. // accounting for different getStats apis, making the browser-checking-if
  2001. // unnecessary.
  2002. if (browser.isReactNative()) {
  2003. this.peerconnection.getStats(
  2004. null,
  2005. callback,
  2006. errback || (() => {
  2007. // Making sure that getStats won't fail if error callback is
  2008. // not passed.
  2009. }));
  2010. } else if (browser.isSafariWithWebrtc() || browser.isFirefox()) {
  2011. // uses the new Promise based getStats
  2012. this.peerconnection.getStats()
  2013. .then(callback)
  2014. .catch(errback || (() => {
  2015. // Making sure that getStats won't fail if error callback is
  2016. // not passed.
  2017. }));
  2018. } else {
  2019. this.peerconnection.getStats(callback);
  2020. }
  2021. };
  2022. /**
  2023. * Generates and stores new SSRC info object for given local track.
  2024. * The method should be called only for a video track being added to this TPC
  2025. * in the muted state (given that the current browser uses this strategy).
  2026. * @param {JitsiLocalTrack} track
  2027. * @return {TPCSSRCInfo}
  2028. */
  2029. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  2030. const rtcId = track.rtcId;
  2031. let ssrcInfo = this._getSSRC(rtcId);
  2032. if (ssrcInfo) {
  2033. logger.error(`Will overwrite local SSRCs for track ID: ${rtcId}`);
  2034. }
  2035. if (this.isSimulcastOn()) {
  2036. ssrcInfo = {
  2037. ssrcs: [],
  2038. groups: []
  2039. };
  2040. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  2041. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  2042. }
  2043. ssrcInfo.groups.push({
  2044. ssrcs: ssrcInfo.ssrcs.slice(),
  2045. semantics: 'SIM'
  2046. });
  2047. } else {
  2048. ssrcInfo = {
  2049. ssrcs: [ SDPUtil.generateSsrc() ],
  2050. groups: []
  2051. };
  2052. }
  2053. if (!this.options.disableRtx && browser.supportsRtx()) {
  2054. // Specifically use a for loop here because we'll
  2055. // be adding to the list we're iterating over, so we
  2056. // only want to iterate through the items originally
  2057. // on the list
  2058. const currNumSsrcs = ssrcInfo.ssrcs.length;
  2059. for (let i = 0; i < currNumSsrcs; ++i) {
  2060. const primarySsrc = ssrcInfo.ssrcs[i];
  2061. const rtxSsrc = SDPUtil.generateSsrc();
  2062. ssrcInfo.ssrcs.push(rtxSsrc);
  2063. ssrcInfo.groups.push({
  2064. ssrcs: [ primarySsrc, rtxSsrc ],
  2065. semantics: 'FID'
  2066. });
  2067. }
  2068. }
  2069. ssrcInfo.msid = track.storedMSID;
  2070. this.localSSRCs.set(rtcId, ssrcInfo);
  2071. return ssrcInfo;
  2072. };
  2073. const handleLayerSuspension = function(peerConnection, isSelected) {
  2074. const videoSender = peerConnection.getSenders()
  2075. .find(sender => sender.track.kind === 'video');
  2076. if (!videoSender) {
  2077. logger.warn('handleLayerSuspension unable to find video sender');
  2078. return;
  2079. }
  2080. if (!videoSender.getParameters) {
  2081. logger.debug('Browser doesn\'t support RTPSender parameters');
  2082. return;
  2083. }
  2084. const parameters = videoSender.getParameters();
  2085. if (isSelected) {
  2086. logger.debug('Currently selected, enabling all sim layers');
  2087. // Make sure all encodings are enabled
  2088. parameters.encodings.forEach(e => {
  2089. e.active = true;
  2090. });
  2091. } else {
  2092. logger.debug('Not currently selected, disabling upper layers');
  2093. // Turn off the upper simulcast layers
  2094. [ 1, 2 ].forEach(simIndex => {
  2095. if (parameters.encodings[simIndex]) {
  2096. parameters.encodings[simIndex].active = false;
  2097. }
  2098. });
  2099. }
  2100. videoSender.setParameters(parameters);
  2101. };
  2102. /**
  2103. * Set whether or not the endpoint is 'selected' by other endpoints, meaning
  2104. * it appears on their main stage
  2105. */
  2106. TraceablePeerConnection.prototype.setIsSelected = function(isSelected) {
  2107. if (this.options.enableLayerSuspension) {
  2108. logger.debug('Layer suspension enabled,'
  2109. + `currently selected? ${isSelected}`);
  2110. handleLayerSuspension(this.peerconnection, isSelected);
  2111. }
  2112. };
  2113. /**
  2114. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2115. * instance.
  2116. * @return {string}
  2117. */
  2118. TraceablePeerConnection.prototype.toString = function() {
  2119. return `TPC[${this.id},p2p:${this.isP2P}]`;
  2120. };