Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

TraceablePeerConnection.js 61KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866
  1. /* global __filename, mozRTCPeerConnection, webkitRTCPeerConnection,
  2. RTCPeerConnection, RTCSessionDescription */
  3. import { getLogger } from 'jitsi-meet-logger';
  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 RTCBrowserType from './RTCBrowserType.js';
  10. import RTCEvents from '../../service/RTC/RTCEvents';
  11. import RtxModifier from '../xmpp/RtxModifier.js';
  12. // FIXME SDP tools should end up in some kind of util module
  13. import SDP from '../xmpp/SDP';
  14. import SdpConsistency from '../xmpp/SdpConsistency.js';
  15. import { SdpTransformWrap } from '../xmpp/SdpTransformUtil';
  16. import SDPUtil from '../xmpp/SDPUtil';
  17. import * as SignalingEvents from '../../service/RTC/SignalingEvents';
  18. import transform from 'sdp-transform';
  19. const logger = getLogger(__filename);
  20. const SIMULCAST_LAYERS = 3;
  21. /* eslint-disable max-params */
  22. /**
  23. * Creates new instance of 'TraceablePeerConnection'.
  24. *
  25. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  26. * @param {number} id the peer connection id assigned by the parent RTC module.
  27. * @param {SignalingLayer} signalingLayer the signaling layer instance
  28. * @param {object} iceConfig WebRTC 'PeerConnection' ICE config
  29. * @param {object} constraints WebRTC 'PeerConnection' constraints
  30. * @param {boolean} isP2P indicates whether or not the new instance will be used
  31. * in a peer to peer connection
  32. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  33. * @param {boolean} options.disableSimulcast if set to 'true' will disable
  34. * the simulcast
  35. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX
  36. * @param {boolean} options.preferH264 if set to 'true' H264 will be preferred
  37. * over other video codecs.
  38. *
  39. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  40. * debug the peer connection. Since many other responsibilities have been added
  41. * it would make sense to extract a separate class from it and come up with
  42. * a more suitable name.
  43. *
  44. * @constructor
  45. */
  46. function TraceablePeerConnection(
  47. rtc,
  48. id,
  49. signalingLayer,
  50. iceConfig,
  51. constraints,
  52. isP2P,
  53. options) {
  54. /**
  55. * Indicates whether or not this peer connection instance is actively
  56. * sending/receiving media. When set to <tt>false</tt> the SDP media
  57. * direction will be adjusted to 'inactive' in order to suspend media
  58. * transmission.
  59. * @type {boolean}
  60. * @private
  61. */
  62. this.mediaTransferActive = true;
  63. /**
  64. * The parent instance of RTC service which created this
  65. * <tt>TracablePeerConnection</tt>.
  66. * @type {RTC}
  67. */
  68. this.rtc = rtc;
  69. /**
  70. * The peer connection identifier assigned by the RTC module.
  71. * @type {number}
  72. */
  73. this.id = id;
  74. /**
  75. * Indicates whether or not this instance is used in a peer to peer
  76. * connection.
  77. * @type {boolean}
  78. */
  79. this.isP2P = isP2P;
  80. // FIXME: We should support multiple streams per jid.
  81. /**
  82. * The map holds remote tracks associated with this peer connection.
  83. * It maps user's JID to media type and remote track
  84. * (one track per media type per user's JID).
  85. * @type {Map<string, Map<MediaType, JitsiRemoteTrack>>}
  86. */
  87. this.remoteTracks = new Map();
  88. /**
  89. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  90. * @type {Map<number, JitsiLocalTrack>}
  91. */
  92. this.localTracks = new Map();
  93. /**
  94. * @typedef {Object} TPCGroupInfo
  95. * @property {string} semantics the SSRC groups semantics
  96. * @property {Array<number>} ssrcs group's SSRCs in order where the first
  97. * one is group's primary SSRC, the second one is secondary (RTX) and so
  98. * on...
  99. */
  100. /**
  101. * @typedef {Object} TPCSSRCInfo
  102. * @property {Array<number>} ssrcs an array which holds all track's SSRCs
  103. * @property {Array<TPCGroupInfo>} groups an array stores all track's SSRC
  104. * groups
  105. */
  106. /**
  107. * Holds the info about local track's SSRCs mapped per their
  108. * {@link JitsiLocalTrack.rtcId}
  109. * @type {Map<number, TPCSSRCInfo>}
  110. */
  111. this.localSSRCs = new Map();
  112. /**
  113. * The local ICE username fragment for this session.
  114. */
  115. this.localUfrag = null;
  116. /**
  117. * The remote ICE username fragment for this session.
  118. */
  119. this.remoteUfrag = null;
  120. /**
  121. * The signaling layer which operates this peer connection.
  122. * @type {SignalingLayer}
  123. */
  124. this.signalingLayer = signalingLayer;
  125. // SignalingLayer listeners
  126. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  127. this.signalingLayer.on(
  128. SignalingEvents.PEER_VIDEO_TYPE_CHANGED,
  129. this._peerVideoTypeChanged);
  130. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  131. this.signalingLayer.on(
  132. SignalingEvents.PEER_MUTED_CHANGED,
  133. this._peerMutedChanged);
  134. this.options = options;
  135. let RTCPeerConnectionType = null;
  136. if (RTCBrowserType.isFirefox()) {
  137. RTCPeerConnectionType = mozRTCPeerConnection;
  138. } else if (RTCBrowserType.isEdge()) {
  139. // TODO: Uncomment when done. For now use the Edge native
  140. // RTCPeerConnection.
  141. // RTCPeerConnectionType = ortcRTCPeerConnection;
  142. RTCPeerConnectionType = RTCPeerConnection;
  143. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  144. RTCPeerConnectionType = RTCPeerConnection;
  145. } else {
  146. RTCPeerConnectionType = webkitRTCPeerConnection;
  147. }
  148. this.peerconnection = new RTCPeerConnectionType(iceConfig, constraints);
  149. this.updateLog = [];
  150. this.stats = {};
  151. this.statsinterval = null;
  152. /**
  153. * @type {number}
  154. */
  155. this.maxstats = 0;
  156. const Interop = require('sdp-interop').Interop;
  157. this.interop = new Interop();
  158. const Simulcast = require('sdp-simulcast');
  159. this.simulcast = new Simulcast({ numOfLayers: SIMULCAST_LAYERS,
  160. explodeRemoteSimulcast: false });
  161. this.sdpConsistency = new SdpConsistency(this.toString());
  162. /**
  163. * Munges local SDP provided to the Jingle Session in order to prevent from
  164. * sending SSRC updates on attach/detach and mute/unmute (for video).
  165. * @type {LocalSdpMunger}
  166. */
  167. this.localSdpMunger = new LocalSdpMunger(this);
  168. /**
  169. * TracablePeerConnection uses RTC's eventEmitter
  170. * @type {EventEmitter}
  171. */
  172. this.eventEmitter = rtc.eventEmitter;
  173. this.rtxModifier = new RtxModifier();
  174. // override as desired
  175. this.trace = (what, info) => {
  176. /* logger.warn('WTRACE', what, info);
  177. if (info && RTCBrowserType.isIExplorer()) {
  178. if (info.length > 1024) {
  179. logger.warn('WTRACE', what, info.substr(1024));
  180. }
  181. if (info.length > 2048) {
  182. logger.warn('WTRACE', what, info.substr(2048));
  183. }
  184. }*/
  185. this.updateLog.push({
  186. time: new Date(),
  187. type: what,
  188. value: info || ''
  189. });
  190. };
  191. this.onicecandidate = null;
  192. this.peerconnection.onicecandidate = event => {
  193. // FIXME: this causes stack overflow with Temasys Plugin
  194. if (!RTCBrowserType.isTemasysPluginUsed()) {
  195. this.trace(
  196. 'onicecandidate',
  197. JSON.stringify(event.candidate, null, ' '));
  198. }
  199. if (this.onicecandidate !== null) {
  200. this.onicecandidate(event);
  201. }
  202. };
  203. this.onaddstream = null;
  204. this.peerconnection.onaddstream = event => {
  205. this.trace('onaddstream', event.stream.id);
  206. if (this.onaddstream !== null) {
  207. this.onaddstream(event);
  208. }
  209. };
  210. this.onremovestream = null;
  211. this.peerconnection.onremovestream = event => {
  212. this.trace('onremovestream', event.stream.id);
  213. if (this.onremovestream !== null) {
  214. this.onremovestream(event);
  215. }
  216. };
  217. this.peerconnection.onaddstream
  218. = event => this._remoteStreamAdded(event.stream);
  219. this.peerconnection.onremovestream
  220. = event => this._remoteStreamRemoved(event.stream);
  221. this.onsignalingstatechange = null;
  222. this.peerconnection.onsignalingstatechange = event => {
  223. this.trace('onsignalingstatechange', this.signalingState);
  224. if (this.onsignalingstatechange !== null) {
  225. this.onsignalingstatechange(event);
  226. }
  227. };
  228. this.oniceconnectionstatechange = null;
  229. this.peerconnection.oniceconnectionstatechange = event => {
  230. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  231. if (this.oniceconnectionstatechange !== null) {
  232. this.oniceconnectionstatechange(event);
  233. }
  234. };
  235. this.onnegotiationneeded = null;
  236. this.peerconnection.onnegotiationneeded = event => {
  237. this.trace('onnegotiationneeded');
  238. if (this.onnegotiationneeded !== null) {
  239. this.onnegotiationneeded(event);
  240. }
  241. };
  242. this.ondatachannel = null;
  243. this.peerconnection.ondatachannel = event => {
  244. this.trace('ondatachannel', event);
  245. if (this.ondatachannel !== null) {
  246. this.ondatachannel(event);
  247. }
  248. };
  249. // XXX: do all non-firefox browsers which we support also support this?
  250. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  251. this.statsinterval = window.setInterval(() => {
  252. this.peerconnection.getStats(stats => {
  253. const results = stats.result();
  254. const now = new Date();
  255. for (let i = 0; i < results.length; ++i) {
  256. results[i].names().forEach(name => {
  257. // eslint-disable-next-line no-shadow
  258. const id = `${results[i].id}-${name}`;
  259. let s = this.stats[id];
  260. if (!s) {
  261. this.stats[id] = s = {
  262. startTime: now,
  263. endTime: now,
  264. values: [],
  265. times: []
  266. };
  267. }
  268. s.values.push(results[i].stat(name));
  269. s.times.push(now.getTime());
  270. if (s.values.length > this.maxstats) {
  271. s.values.shift();
  272. s.times.shift();
  273. }
  274. s.endTime = now;
  275. });
  276. }
  277. });
  278. }, 1000);
  279. }
  280. logger.info(`Create new ${this}`);
  281. }
  282. /* eslint-enable max-params */
  283. /**
  284. * Returns a string representation of a SessionDescription object.
  285. */
  286. const dumpSDP = function(description) {
  287. if (typeof description === 'undefined' || description === null) {
  288. return '';
  289. }
  290. return `type: ${description.type}\r\n${description.sdp}`;
  291. };
  292. /**
  293. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  294. * will convert "completed" into "connected" where both mean that the ICE has
  295. * succeeded and is up and running. We never see "completed" state for
  296. * the JVB connection, but it started appearing for the P2P one. This method
  297. * allows to adapt old logic to this new situation.
  298. * @return {string}
  299. */
  300. TraceablePeerConnection.prototype.getConnectionState = function() {
  301. const state = this.peerconnection.iceConnectionState;
  302. if (state === 'completed') {
  303. return 'connected';
  304. }
  305. return state;
  306. };
  307. /**
  308. * Obtains the media direction for given {@link MediaType}. The method takes
  309. * into account whether or not there are any local tracks for media and
  310. * the {@link mediaTransferActive} flag.
  311. * @param {MediaType} mediaType
  312. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly'
  313. * etc.) which should be used when setting local description on the peer
  314. * connection.
  315. * @private
  316. */
  317. TraceablePeerConnection.prototype._getDesiredMediaDirection
  318. = function(mediaType) {
  319. if (this.mediaTransferActive) {
  320. return this.hasAnyTracksOfType(mediaType) ? 'sendrecv' : 'recvonly';
  321. }
  322. return 'inactive';
  323. };
  324. /**
  325. * Tells whether or not this TPC instance is using Simulcast.
  326. * @return {boolean} <tt>true</tt> if simulcast is enabled and active or
  327. * <tt>false</tt> if it's turned off.
  328. */
  329. TraceablePeerConnection.prototype.isSimulcastOn = function() {
  330. return !this.options.disableSimulcast
  331. && this.simulcast.isSupported()
  332. && !this.isP2P;
  333. };
  334. /**
  335. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  336. * @param {string} endpointId the video owner's ID (MUC nickname)
  337. * @param {VideoType} videoType the new value
  338. * @private
  339. */
  340. TraceablePeerConnection.prototype._peerVideoTypeChanged
  341. = function(endpointId, videoType) {
  342. // Check if endpointId has a value to avoid action on random track
  343. if (!endpointId) {
  344. logger.error(`No endpointID on peerVideoTypeChanged ${this}`);
  345. return;
  346. }
  347. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  348. if (videoTrack.length) {
  349. // NOTE 1 track per media type is assumed
  350. videoTrack[0]._setVideoType(videoType);
  351. }
  352. };
  353. /**
  354. * Handles remote track mute / unmute events.
  355. * @param {string} endpointId the track owner's identifier (MUC nickname)
  356. * @param {MediaType} mediaType "audio" or "video"
  357. * @param {boolean} isMuted the new mute state
  358. * @private
  359. */
  360. TraceablePeerConnection.prototype._peerMutedChanged
  361. = function(endpointId, mediaType, isMuted) {
  362. // Check if endpointId is a value to avoid doing action on all remote tracks
  363. if (!endpointId) {
  364. logger.error('On peerMuteChanged - no endpoint ID');
  365. return;
  366. }
  367. const track = this.getRemoteTracks(endpointId, mediaType);
  368. if (track.length) {
  369. // NOTE 1 track per media type is assumed
  370. track[0].setMute(isMuted);
  371. }
  372. };
  373. /**
  374. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  375. * argument is omitted the list of all local tracks will be returned.
  376. * @param {MediaType} [mediaType]
  377. * @return {Array<JitsiLocalTrack>}
  378. */
  379. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  380. let tracks = Array.from(this.localTracks.values());
  381. if (mediaType !== undefined) {
  382. tracks = tracks.filter(track => track.getType() === mediaType);
  383. }
  384. return tracks;
  385. };
  386. /**
  387. * Checks whether or not this {@link TraceablePeerConnection} instance contains
  388. * any local tracks for given <tt>mediaType</tt>.
  389. * @param {MediaType} mediaType
  390. * @return {boolean}
  391. */
  392. TraceablePeerConnection.prototype.hasAnyTracksOfType = function(mediaType) {
  393. if (!mediaType) {
  394. throw new Error('"mediaType" is required');
  395. }
  396. return this.getLocalTracks(mediaType).length > 0;
  397. };
  398. /**
  399. * Obtains all remote tracks currently known to this PeerConnection instance.
  400. * @param {string} [endpointId] the track owner's identifier (MUC nickname)
  401. * @param {MediaType} [mediaType] the remote tracks will be filtered
  402. * by their media type if this argument is specified.
  403. * @return {Array<JitsiRemoteTrack>}
  404. */
  405. TraceablePeerConnection.prototype.getRemoteTracks
  406. = function(endpointId, mediaType) {
  407. const remoteTracks = [];
  408. const endpoints
  409. = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  410. for (const endpoint of endpoints) {
  411. const endpointTrackMap = this.remoteTracks.get(endpoint);
  412. if (!endpointTrackMap) {
  413. // Otherwise an empty Map() would have to be allocated above
  414. // eslint-disable-next-line no-continue
  415. continue;
  416. }
  417. for (const trackMediaType of endpointTrackMap.keys()) {
  418. // per media type filtering
  419. if (!mediaType || mediaType === trackMediaType) {
  420. const mediaTrack = endpointTrackMap.get(trackMediaType);
  421. if (mediaTrack) {
  422. remoteTracks.push(mediaTrack);
  423. }
  424. }
  425. }
  426. }
  427. return remoteTracks;
  428. };
  429. /**
  430. * Called when new remote MediaStream is added to the PeerConnection.
  431. * @param {MediaStream} stream the WebRTC MediaStream for remote participant
  432. */
  433. TraceablePeerConnection.prototype._remoteStreamAdded = function(stream) {
  434. const streamId = RTC.getStreamID(stream);
  435. if (!RTC.isUserStreamById(streamId)) {
  436. logger.info(
  437. `${this} ignored remote 'stream added' event for non-user stream`
  438. + `id: ${streamId}`);
  439. return;
  440. }
  441. // Bind 'addtrack'/'removetrack' event handlers
  442. if (RTCBrowserType.isChrome() || RTCBrowserType.isNWJS()
  443. || RTCBrowserType.isElectron()) {
  444. stream.onaddtrack = event => {
  445. this._remoteTrackAdded(event.target, event.track);
  446. };
  447. stream.onremovetrack = event => {
  448. this._remoteTrackRemoved(event.target, event.track);
  449. };
  450. }
  451. // Call remoteTrackAdded for each track in the stream
  452. const streamAudioTracks = stream.getAudioTracks();
  453. for (const audioTrack of streamAudioTracks) {
  454. this._remoteTrackAdded(stream, audioTrack);
  455. }
  456. const streamVideoTracks = stream.getVideoTracks();
  457. for (const videoTrack of streamVideoTracks) {
  458. this._remoteTrackAdded(stream, videoTrack);
  459. }
  460. };
  461. /**
  462. * Called on "track added" and "stream added" PeerConnection events (because we
  463. * handle streams on per track basis). Finds the owner and the SSRC for
  464. * the track and passes that to ChatRoom for further processing.
  465. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  466. * the parent of the track
  467. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  468. * participant
  469. */
  470. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  471. const streamId = RTC.getStreamID(stream);
  472. const mediaType = track.kind;
  473. logger.info(`${this} remote track added:`, streamId, mediaType);
  474. // look up an associated JID for a stream id
  475. if (!mediaType) {
  476. GlobalOnErrorHandler.callErrorHandler(
  477. new Error(
  478. `MediaType undefined for remote track, stream id: ${streamId}`
  479. ));
  480. // Abort
  481. return;
  482. }
  483. const remoteSDP = new SDP(this.remoteDescription.sdp);
  484. const mediaLines
  485. = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  486. if (!mediaLines.length) {
  487. GlobalOnErrorHandler.callErrorHandler(
  488. new Error(
  489. `No media lines for type ${mediaType
  490. } found in remote SDP for remote track: ${streamId}`));
  491. // Abort
  492. return;
  493. }
  494. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  495. ssrcLines = ssrcLines.filter(
  496. line => {
  497. const msid
  498. = RTCBrowserType.isTemasysPluginUsed() ? 'mslabel' : 'msid';
  499. return line.indexOf(`${msid}:${streamId}`) !== -1;
  500. });
  501. if (!ssrcLines.length) {
  502. GlobalOnErrorHandler.callErrorHandler(
  503. new Error(
  504. `No SSRC lines for streamId ${streamId
  505. } for remote track, media type: ${mediaType}`));
  506. // Abort
  507. return;
  508. }
  509. // FIXME the length of ssrcLines[0] not verified, but it will fail
  510. // with global error handler anyway
  511. const trackSsrc = ssrcLines[0].substring(7).split(' ')[0];
  512. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  513. if (!ownerEndpointId) {
  514. GlobalOnErrorHandler.callErrorHandler(
  515. new Error(
  516. `No SSRC owner known for: ${trackSsrc
  517. } for remote track, msid: ${streamId
  518. } media type: ${mediaType}`));
  519. // Abort
  520. return;
  521. }
  522. logger.log(`${this} associated ssrc`, ownerEndpointId, trackSsrc);
  523. const peerMediaInfo
  524. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  525. if (!peerMediaInfo) {
  526. GlobalOnErrorHandler.callErrorHandler(
  527. new Error(
  528. `${this}: no peer media info available for ${
  529. ownerEndpointId}`));
  530. return;
  531. }
  532. const muted = peerMediaInfo.muted;
  533. const videoType = peerMediaInfo.videoType; // can be undefined
  534. this._createRemoteTrack(
  535. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  536. };
  537. // FIXME cleanup params
  538. /* eslint-disable max-params */
  539. /**
  540. * Initializes a new JitsiRemoteTrack instance with the data provided by
  541. * the signaling layer and SDP.
  542. *
  543. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  544. * @param {MediaStream} stream the WebRTC stream instance
  545. * @param {MediaStreamTrack} track the WebRTC track instance
  546. * @param {MediaType} mediaType the track's type of the media
  547. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  548. * @param {string} ssrc the track's main SSRC number
  549. * @param {boolean} muted the initial muted status
  550. */
  551. TraceablePeerConnection.prototype._createRemoteTrack
  552. = function(ownerEndpointId, stream, track, mediaType, videoType, ssrc, muted) {
  553. const remoteTrack
  554. = new JitsiRemoteTrack(
  555. this.rtc, this.rtc.conference,
  556. ownerEndpointId,
  557. stream, track, mediaType, videoType, ssrc, muted, this.isP2P);
  558. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  559. if (!remoteTracksMap) {
  560. remoteTracksMap = new Map();
  561. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  562. }
  563. if (remoteTracksMap.has(mediaType)) {
  564. logger.error(
  565. `${this} overwriting remote track! ${remoteTrack}`,
  566. ownerEndpointId, mediaType);
  567. }
  568. remoteTracksMap.set(mediaType, remoteTrack);
  569. // FIXME not cool to use RTC's eventEmitter
  570. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack);
  571. };
  572. /* eslint-enable max-params */
  573. /**
  574. * Handles remote stream removal.
  575. * @param stream the WebRTC MediaStream object which is being removed from the
  576. * PeerConnection
  577. */
  578. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  579. if (!RTC.isUserStream(stream)) {
  580. const id = RTC.getStreamID(stream);
  581. logger.info(
  582. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  583. return;
  584. }
  585. // Call remoteTrackRemoved for each track in the stream
  586. const streamVideoTracks = stream.getVideoTracks();
  587. for (const videoTrack of streamVideoTracks) {
  588. this._remoteTrackRemoved(stream, videoTrack);
  589. }
  590. const streamAudioTracks = stream.getAudioTracks();
  591. for (const audioTrack of streamAudioTracks) {
  592. this._remoteTrackRemoved(stream, audioTrack);
  593. }
  594. };
  595. /**
  596. * Handles remote media track removal.
  597. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  598. * of the track.
  599. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  600. * removed from the PeerConnection.
  601. */
  602. TraceablePeerConnection.prototype._remoteTrackRemoved
  603. = function(stream, track) {
  604. const streamId = RTC.getStreamID(stream);
  605. const trackId = track && track.id;
  606. logger.info(`${this} - remote track removed: ${streamId}, ${trackId}`);
  607. if (!streamId) {
  608. GlobalOnErrorHandler.callErrorHandler(
  609. new Error(`${this} remote track removal failed - no stream ID`));
  610. return;
  611. }
  612. if (!trackId) {
  613. GlobalOnErrorHandler.callErrorHandler(
  614. new Error(`${this} remote track removal failed - no track ID`));
  615. return;
  616. }
  617. if (!this._removeRemoteTrack(streamId, trackId)) {
  618. // NOTE this warning is always printed when user leaves the room,
  619. // because we remove remote tracks manually on MUC member left event,
  620. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  621. // ignore this warning, but still it's better to keep it printed for
  622. // debugging purposes.
  623. //
  624. // We could change the behaviour to emit track removed only from here,
  625. // but the order of the events will change and consuming apps could
  626. // behave unexpectedly (the "user left" event would come before "track
  627. // removed" events).
  628. logger.warn(
  629. `${this} Removed track not found for msid: ${streamId},
  630. track id: ${trackId}`);
  631. }
  632. };
  633. /**
  634. * Finds remote track by it's stream and track ids.
  635. * @param {string} streamId the media stream id as defined by the WebRTC
  636. * @param {string} trackId the media track id as defined by the WebRTC
  637. * @return {JitsiRemoteTrack|undefined} the track's instance or
  638. * <tt>undefined</tt> if not found.
  639. * @private
  640. */
  641. TraceablePeerConnection.prototype._getRemoteTrackById
  642. = function(streamId, trackId) {
  643. // .find will break the loop once the first match is found
  644. for (const endpointTrackMap of this.remoteTracks.values()) {
  645. for (const mediaTrack of endpointTrackMap.values()) {
  646. // FIXME verify and try to use ===
  647. /* eslint-disable eqeqeq */
  648. if (mediaTrack.getStreamId() == streamId
  649. && mediaTrack.getTrackId() == trackId) {
  650. return mediaTrack;
  651. }
  652. /* eslint-enable eqeqeq */
  653. }
  654. }
  655. return undefined;
  656. };
  657. /**
  658. * Removes all JitsiRemoteTracks associated with given MUC nickname
  659. * (resource part of the JID). Returns array of removed tracks.
  660. *
  661. * @param {string} owner - The resource part of the MUC JID.
  662. * @returns {JitsiRemoteTrack[]}
  663. */
  664. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  665. const removedTracks = [];
  666. const remoteTracksMap = this.remoteTracks.get(owner);
  667. if (remoteTracksMap) {
  668. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  669. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  670. removedAudioTrack && removedTracks.push(removedAudioTrack);
  671. removedVideoTrack && removedTracks.push(removedVideoTrack);
  672. this.remoteTracks.delete(owner);
  673. }
  674. logger.debug(
  675. `${this} removed remote tracks for ${owner
  676. } count: ${removedTracks.length}`);
  677. return removedTracks;
  678. };
  679. /**
  680. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  681. * track ids.
  682. *
  683. * @param {string} streamId the media stream id as defined by the WebRTC
  684. * @param {string} trackId the media track id as defined by the WebRTC
  685. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  686. * <tt>undefined</tt> if no track matching given stream and track ids was
  687. * found.
  688. */
  689. TraceablePeerConnection.prototype._removeRemoteTrack
  690. = function(streamId, trackId) {
  691. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  692. if (toBeRemoved) {
  693. toBeRemoved.dispose();
  694. const remoteTracksMap
  695. = this.remoteTracks.get(toBeRemoved.getParticipantId());
  696. // If _getRemoteTrackById succeeded it must be a valid value or
  697. // we're good to crash
  698. if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  699. logger.error(
  700. `Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  701. }
  702. // FIXME not cool to use RTC's eventEmitter
  703. this.rtc.eventEmitter.emit(
  704. RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  705. }
  706. return toBeRemoved;
  707. };
  708. /**
  709. * @typedef {Object} SSRCGroupInfo
  710. * @property {Array<number>} ssrcs group's SSRCs
  711. * @property {string} semantics
  712. */
  713. /**
  714. * @typedef {Object} TrackSSRCInfo
  715. * @property {Array<number>} ssrcs track's SSRCs
  716. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  717. */
  718. /**
  719. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  720. * @param {Object} desc the WebRTC SDP instance.
  721. * @return {Map<string,TrackSSRCInfo>}
  722. */
  723. function extractSSRCMap(desc) {
  724. /**
  725. * Track SSRC infos mapped by stream ID (msid)
  726. * @type {Map<string,TrackSSRCInfo>}
  727. */
  728. const ssrcMap = new Map();
  729. /**
  730. * Groups mapped by primary SSRC number
  731. * @type {Map<number,Array<SSRCGroupInfo>>}
  732. */
  733. const groupsMap = new Map();
  734. if (typeof desc !== 'object' || desc === null
  735. || typeof desc.sdp !== 'string') {
  736. logger.warn('An empty description was passed as an argument.');
  737. return ssrcMap;
  738. }
  739. const session = transform.parse(desc.sdp);
  740. if (!Array.isArray(session.media)) {
  741. return ssrcMap;
  742. }
  743. for (const mLine of session.media) {
  744. if (!Array.isArray(mLine.ssrcs)) {
  745. continue; // eslint-disable-line no-continue
  746. }
  747. if (Array.isArray(mLine.ssrcGroups)) {
  748. for (const group of mLine.ssrcGroups) {
  749. if (typeof group.semantics !== 'undefined'
  750. && typeof group.ssrcs !== 'undefined') {
  751. // Parse SSRCs and store as numbers
  752. const groupSSRCs
  753. = group.ssrcs.split(' ')
  754. .map(ssrcStr => parseInt(ssrcStr, 10));
  755. const primarySSRC = groupSSRCs[0];
  756. // Note that group.semantics is already present
  757. group.ssrcs = groupSSRCs;
  758. // eslint-disable-next-line max-depth
  759. if (!groupsMap.has(primarySSRC)) {
  760. groupsMap.set(primarySSRC, []);
  761. }
  762. groupsMap.get(primarySSRC).push(group);
  763. }
  764. }
  765. }
  766. for (const ssrc of mLine.ssrcs) {
  767. if (ssrc.attribute !== 'msid') {
  768. continue; // eslint-disable-line no-continue
  769. }
  770. const msid = ssrc.value;
  771. let ssrcInfo = ssrcMap.get(msid);
  772. if (!ssrcInfo) {
  773. ssrcInfo = {
  774. ssrcs: [],
  775. groups: [],
  776. msid
  777. };
  778. ssrcMap.set(msid, ssrcInfo);
  779. }
  780. const ssrcNumber = ssrc.id;
  781. ssrcInfo.ssrcs.push(ssrcNumber);
  782. if (groupsMap.has(ssrcNumber)) {
  783. const ssrcGroups = groupsMap.get(ssrcNumber);
  784. for (const group of ssrcGroups) {
  785. ssrcInfo.groups.push(group);
  786. }
  787. }
  788. }
  789. }
  790. return ssrcMap;
  791. }
  792. /**
  793. * Takes a SessionDescription object and returns a "normalized" version.
  794. * Currently it only takes care of ordering the a=ssrc lines.
  795. */
  796. const normalizePlanB = function(desc) {
  797. if (typeof desc !== 'object' || desc === null
  798. || typeof desc.sdp !== 'string') {
  799. logger.warn('An empty description was passed as an argument.');
  800. return desc;
  801. }
  802. // eslint-disable-next-line no-shadow
  803. const transform = require('sdp-transform');
  804. const session = transform.parse(desc.sdp);
  805. if (typeof session !== 'undefined'
  806. && typeof session.media !== 'undefined'
  807. && Array.isArray(session.media)) {
  808. session.media.forEach(mLine => {
  809. // Chrome appears to be picky about the order in which a=ssrc lines
  810. // are listed in an m-line when rtx is enabled (and thus there are
  811. // a=ssrc-group lines with FID semantics). Specifically if we have
  812. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  813. // the "a=ssrc:S1" lines, SRD fails.
  814. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  815. // first.
  816. const firstSsrcs = [];
  817. const newSsrcLines = [];
  818. if (typeof mLine.ssrcGroups !== 'undefined'
  819. && Array.isArray(mLine.ssrcGroups)) {
  820. mLine.ssrcGroups.forEach(group => {
  821. if (typeof group.semantics !== 'undefined'
  822. && group.semantics === 'FID') {
  823. if (typeof group.ssrcs !== 'undefined') {
  824. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  825. }
  826. }
  827. });
  828. }
  829. if (Array.isArray(mLine.ssrcs)) {
  830. let i;
  831. for (i = 0; i < mLine.ssrcs.length; i++) {
  832. if (typeof mLine.ssrcs[i] === 'object'
  833. && typeof mLine.ssrcs[i].id !== 'undefined'
  834. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  835. newSsrcLines.push(mLine.ssrcs[i]);
  836. delete mLine.ssrcs[i];
  837. }
  838. }
  839. for (i = 0; i < mLine.ssrcs.length; i++) {
  840. if (typeof mLine.ssrcs[i] !== 'undefined') {
  841. newSsrcLines.push(mLine.ssrcs[i]);
  842. }
  843. }
  844. mLine.ssrcs = newSsrcLines;
  845. }
  846. });
  847. }
  848. const resStr = transform.write(session);
  849. return new RTCSessionDescription({
  850. type: desc.type,
  851. sdp: resStr
  852. });
  853. };
  854. /**
  855. *
  856. * @param {JitsiLocalTrack} localTrack
  857. */
  858. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  859. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  860. return ssrcInfo && ssrcInfo.ssrcs[0];
  861. };
  862. /* eslint-disable-next-line vars-on-top */
  863. const getters = {
  864. signalingState() {
  865. return this.peerconnection.signalingState;
  866. },
  867. iceConnectionState() {
  868. return this.peerconnection.iceConnectionState;
  869. },
  870. localDescription() {
  871. let desc = this.peerconnection.localDescription;
  872. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  873. // if we're running on FF, transform to Plan B first.
  874. if (RTCBrowserType.usesUnifiedPlan()) {
  875. desc = this.interop.toPlanB(desc);
  876. this.trace('getLocalDescription::postTransform (Plan B)',
  877. dumpSDP(desc));
  878. }
  879. if (RTCBrowserType.doesVideoMuteByStreamRemove()) {
  880. this.localSdpMunger.maybeMungeLocalSdp(desc);
  881. logger.debug(
  882. 'getLocalDescription::postTransform (munge local SDP)', desc);
  883. }
  884. return desc || {};
  885. },
  886. remoteDescription() {
  887. let desc = this.peerconnection.remoteDescription;
  888. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  889. // if we're running on FF, transform to Plan B first.
  890. if (RTCBrowserType.usesUnifiedPlan()) {
  891. desc = this.interop.toPlanB(desc);
  892. this.trace(
  893. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  894. }
  895. return desc || {};
  896. }
  897. };
  898. Object.keys(getters).forEach(prop => {
  899. Object.defineProperty(
  900. TraceablePeerConnection.prototype,
  901. prop, {
  902. get: getters[prop]
  903. }
  904. );
  905. });
  906. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  907. return this.localSSRCs.get(rtcId);
  908. };
  909. /**
  910. * Add {@link JitsiLocalTrack} to this TPC.
  911. * @param {JitsiLocalTrack} track
  912. */
  913. TraceablePeerConnection.prototype.addTrack = function(track) {
  914. const rtcId = track.rtcId;
  915. logger.info(`add ${track} to: ${this}`);
  916. if (this.localTracks.has(rtcId)) {
  917. logger.error(`${track} is already in ${this}`);
  918. return;
  919. }
  920. this.localTracks.set(rtcId, track);
  921. const webrtcStream = track.getOriginalStream();
  922. if (webrtcStream) {
  923. this._addStream(webrtcStream);
  924. // It's not ok for a track to not have a WebRTC stream if:
  925. } else if (!RTCBrowserType.doesVideoMuteByStreamRemove()
  926. || track.isAudioTrack()
  927. || (track.isVideoTrack() && !track.isMuted())) {
  928. logger.error(`${this} no WebRTC stream for: ${track}`);
  929. }
  930. // Muted video tracks do not have WebRTC stream
  931. if (RTCBrowserType.doesVideoMuteByStreamRemove()
  932. && track.isVideoTrack() && track.isMuted()) {
  933. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  934. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  935. const simGroup
  936. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  937. if (simGroup) {
  938. this.simulcast.setSsrcCache(simGroup.ssrcs);
  939. }
  940. const fidGroups
  941. = ssrcInfo.groups.filter(
  942. groupInfo => groupInfo.semantics === 'FID');
  943. if (fidGroups) {
  944. const rtxSsrcMapping = new Map();
  945. fidGroups.forEach(fidGroup => {
  946. const primarySsrc = fidGroup.ssrcs[0];
  947. const rtxSsrc = fidGroup.ssrcs[1];
  948. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  949. });
  950. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  951. }
  952. }
  953. };
  954. /**
  955. * Adds local track as part of the unmute operation.
  956. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  957. * operation
  958. * @return {boolean} <tt>true</tt> if the state of underlying PC has changed and
  959. * the renegotiation is required or <tt>false</tt> otherwise.
  960. */
  961. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  962. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  963. // Abort
  964. return false;
  965. }
  966. logger.info(`Adding ${track} as unmute to ${this}`);
  967. const webRtcStream = track.getOriginalStream();
  968. if (!webRtcStream) {
  969. logger.error(
  970. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  971. return false;
  972. }
  973. this._addStream(webRtcStream);
  974. return true;
  975. };
  976. /**
  977. * Adds WebRTC media stream to the underlying PeerConnection
  978. * @param {MediaStream} mediaStream
  979. * @private
  980. */
  981. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  982. this.peerconnection.addStream(mediaStream);
  983. };
  984. /**
  985. * Removes WebRTC media stream from the underlying PeerConection
  986. * @param {MediaStream} mediaStream
  987. */
  988. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  989. if (RTCBrowserType.isFirefox()) {
  990. this._handleFirefoxRemoveStream(mediaStream);
  991. } else {
  992. this.peerconnection.removeStream(mediaStream);
  993. }
  994. };
  995. /**
  996. * This method when called will check if given <tt>localTrack</tt> belongs to
  997. * this TPC (that it has been previously added using {@link addTrack}). If the
  998. * track does not belong an error message will be logged.
  999. * @param {string} methodName the method name that will be logged in an error
  1000. * message
  1001. * @param {JitsiLocalTrack} localTrack
  1002. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1003. * <tt>false</tt> otherwise.
  1004. * @private
  1005. */
  1006. TraceablePeerConnection.prototype._assertTrackBelongs
  1007. = function(methodName, localTrack) {
  1008. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1009. if (!doesBelong) {
  1010. logger.error(
  1011. `${methodName}: ${localTrack} does not belong to ${this}`);
  1012. }
  1013. return doesBelong;
  1014. };
  1015. /**
  1016. * Remove local track from this TPC.
  1017. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1018. *
  1019. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1020. * The same applies to addTrack.
  1021. */
  1022. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1023. const webRtcStream = localTrack.getOriginalStream();
  1024. this.trace(
  1025. 'removeStream',
  1026. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1027. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1028. // Abort - nothing to be done here
  1029. return;
  1030. }
  1031. this.localTracks.delete(localTrack.rtcId);
  1032. this.localSSRCs.delete(localTrack.rtcId);
  1033. if (webRtcStream) {
  1034. if (RTCBrowserType.isFirefox()) {
  1035. this._handleFirefoxRemoveStream(webRtcStream);
  1036. } else {
  1037. this.peerconnection.removeStream(webRtcStream);
  1038. }
  1039. }
  1040. };
  1041. /**
  1042. * Removes local track as part of the mute operation.
  1043. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1044. * the mute operation.
  1045. * @return {boolean} <tt>true</tt> if the underlying PeerConnection's state has
  1046. * changed and the renegotiation is required or <tt>false</tt> otherwise.
  1047. */
  1048. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1049. const webRtcStream = localTrack.getOriginalStream();
  1050. this.trace(
  1051. 'removeStreamMute',
  1052. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1053. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1054. // Abort - nothing to be done here
  1055. return false;
  1056. }
  1057. if (webRtcStream) {
  1058. logger.info(
  1059. `Removing ${localTrack} as mute from ${this}`);
  1060. this._removeStream(webRtcStream);
  1061. return true;
  1062. }
  1063. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1064. return false;
  1065. };
  1066. /**
  1067. * Remove stream handling for firefox
  1068. * @param stream: webrtc media stream
  1069. */
  1070. TraceablePeerConnection.prototype._handleFirefoxRemoveStream
  1071. = function(stream) {
  1072. if (!stream) {
  1073. // There is nothing to be changed
  1074. return;
  1075. }
  1076. let sender = null;
  1077. // On Firefox we don't replace MediaStreams as this messes up the
  1078. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1079. // of complications. Instead, we use the RTPSender and remove just
  1080. // the track.
  1081. let track = null;
  1082. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  1083. track = stream.getAudioTracks()[0];
  1084. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  1085. track = stream.getVideoTracks()[0];
  1086. }
  1087. if (!track) {
  1088. logger.error('Cannot remove tracks: no tracks.');
  1089. return;
  1090. }
  1091. // Find the right sender (for audio or video)
  1092. this.peerconnection.getSenders().some(s => {
  1093. if (s.track === track) {
  1094. sender = s;
  1095. return true;
  1096. }
  1097. return false;
  1098. });
  1099. if (sender) {
  1100. this.peerconnection.removeTrack(sender);
  1101. } else {
  1102. logger.log('Cannot remove tracks: no RTPSender.');
  1103. }
  1104. };
  1105. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1106. this.trace('createDataChannel', label, opts);
  1107. return this.peerconnection.createDataChannel(label, opts);
  1108. };
  1109. /**
  1110. * Will adjust audio and video media direction in the given SDP object to
  1111. * reflect the current status of the {@link mediaTransferActive} flag.
  1112. * @param {Object} localDescription the WebRTC session description instance for
  1113. * the local description.
  1114. * @private
  1115. */
  1116. TraceablePeerConnection.prototype._adjustLocalMediaDirection
  1117. = function(localDescription) {
  1118. const transformer = new SdpTransformWrap(localDescription.sdp);
  1119. let modifiedDirection = false;
  1120. const audioMedia = transformer.selectMedia('audio');
  1121. if (audioMedia) {
  1122. const desiredAudioDirection
  1123. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1124. if (audioMedia.direction !== desiredAudioDirection) {
  1125. audioMedia.direction = desiredAudioDirection;
  1126. logger.info(
  1127. `Adjusted local audio direction to ${desiredAudioDirection}`);
  1128. modifiedDirection = true;
  1129. }
  1130. } else {
  1131. logger.warn('No "audio" media found int the local description');
  1132. }
  1133. const videoMedia = transformer.selectMedia('video');
  1134. if (videoMedia) {
  1135. const desiredVideoDirection
  1136. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1137. if (videoMedia.direction !== desiredVideoDirection) {
  1138. videoMedia.direction = desiredVideoDirection;
  1139. logger.info(
  1140. `Adjusted local video direction to ${desiredVideoDirection}`);
  1141. modifiedDirection = true;
  1142. }
  1143. } else {
  1144. logger.warn('No "video" media found in the local description');
  1145. }
  1146. if (modifiedDirection) {
  1147. localDescription.sdp = transformer.toRawSDP();
  1148. }
  1149. };
  1150. TraceablePeerConnection.prototype.setLocalDescription
  1151. = function(description, successCallback, failureCallback) {
  1152. let localSdp = description;
  1153. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1154. this._adjustLocalMediaDirection(localSdp);
  1155. // if we're using unified plan, transform to it first.
  1156. if (RTCBrowserType.usesUnifiedPlan()) {
  1157. localSdp = this.interop.toUnifiedPlan(localSdp);
  1158. this.trace(
  1159. 'setLocalDescription::postTransform (Unified Plan)',
  1160. dumpSDP(localSdp));
  1161. }
  1162. this.peerconnection.setLocalDescription(localSdp,
  1163. () => {
  1164. this.trace('setLocalDescriptionOnSuccess');
  1165. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1166. if (localUfrag !== this.localUfrag) {
  1167. this.localUfrag = localUfrag;
  1168. this.rtc.eventEmitter.emit(
  1169. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1170. }
  1171. successCallback();
  1172. },
  1173. err => {
  1174. this.trace('setLocalDescriptionOnFailure', err);
  1175. this.eventEmitter.emit(
  1176. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1177. err, this.peerconnection);
  1178. failureCallback(err);
  1179. }
  1180. );
  1181. };
  1182. /**
  1183. * Enables/disables media transmission on this peer connection. When disabled
  1184. * the SDP media direction in the local SDP will be adjusted to 'inactive' which
  1185. * means that no data will be received or sent, but the connection should be
  1186. * kept alive.
  1187. * @param {boolean} active <tt>true</tt> to enable the media transmission or
  1188. * <tt>false</tt> to disable.
  1189. * @public
  1190. */
  1191. TraceablePeerConnection.prototype.setMediaTransferActive = function(active) {
  1192. this.mediaTransferActive = active;
  1193. };
  1194. TraceablePeerConnection.prototype.setRemoteDescription
  1195. = function(description, successCallback, failureCallback) {
  1196. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1197. // TODO the focus should squeze or explode the remote simulcast
  1198. // eslint-disable-next-line no-param-reassign
  1199. description = this.simulcast.mungeRemoteDescription(description);
  1200. this.trace(
  1201. 'setRemoteDescription::postTransform (simulcast)',
  1202. dumpSDP(description));
  1203. if (this.options.preferH264) {
  1204. const parsedSdp = transform.parse(description.sdp);
  1205. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1206. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1207. description.sdp = transform.write(parsedSdp);
  1208. }
  1209. // If the browser uses unified plan, transform to it first
  1210. if (RTCBrowserType.usesUnifiedPlan()) {
  1211. description.sdp = this.rtxModifier.stripRtx(description.sdp);
  1212. this.trace(
  1213. 'setRemoteDescription::postTransform (stripRtx)',
  1214. dumpSDP(description));
  1215. // eslint-disable-next-line no-param-reassign
  1216. description = this.interop.toUnifiedPlan(description);
  1217. this.trace(
  1218. 'setRemoteDescription::postTransform (Plan A)',
  1219. dumpSDP(description));
  1220. } else {
  1221. // Plan B
  1222. // eslint-disable-next-line no-param-reassign
  1223. description = normalizePlanB(description);
  1224. }
  1225. this.peerconnection.setRemoteDescription(
  1226. description,
  1227. () => {
  1228. this.trace('setRemoteDescriptionOnSuccess');
  1229. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  1230. if (remoteUfrag !== this.remoteUfrag) {
  1231. this.remoteUfrag = remoteUfrag;
  1232. this.rtc.eventEmitter.emit(
  1233. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1234. }
  1235. successCallback();
  1236. },
  1237. err => {
  1238. this.trace('setRemoteDescriptionOnFailure', err);
  1239. this.eventEmitter.emit(
  1240. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  1241. err,
  1242. this.peerconnection);
  1243. failureCallback(err);
  1244. });
  1245. };
  1246. /**
  1247. * Makes the underlying TraceablePeerConnection generate new SSRC for
  1248. * the recvonly video stream.
  1249. */
  1250. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  1251. const newSSRC = SDPUtil.generateSsrc();
  1252. logger.info(`${this} generated new recvonly SSRC: ${newSSRC}`);
  1253. this.sdpConsistency.setPrimarySsrc(newSSRC);
  1254. };
  1255. /**
  1256. * Makes the underlying TraceablePeerConnection forget the current primary video
  1257. * SSRC.
  1258. */
  1259. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  1260. logger.info('Clearing primary video SSRC!');
  1261. this.sdpConsistency.clearVideoSsrcCache();
  1262. };
  1263. TraceablePeerConnection.prototype.close = function() {
  1264. this.trace('stop');
  1265. // Off SignalingEvents
  1266. this.signalingLayer.off(
  1267. SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  1268. this.signalingLayer.off(
  1269. SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  1270. if (!this.rtc._removePeerConnection(this)) {
  1271. logger.error('RTC._removePeerConnection returned false');
  1272. }
  1273. if (this.statsinterval !== null) {
  1274. window.clearInterval(this.statsinterval);
  1275. this.statsinterval = null;
  1276. }
  1277. this.peerconnection.close();
  1278. };
  1279. /**
  1280. * Modifies the values of the setup attributes (defined by
  1281. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  1282. * answer in order to overcome a delay of 1 second in the connection
  1283. * establishment between Chrome and Videobridge.
  1284. *
  1285. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  1286. * being prepared to respond
  1287. * @param {SDP} answer - the SDP to modify
  1288. * @private
  1289. */
  1290. const _fixAnswerRFC4145Setup = function(offer, answer) {
  1291. if (!RTCBrowserType.isChrome()) {
  1292. // It looks like Firefox doesn't agree with the fix (at least in its
  1293. // current implementation) because it effectively remains active even
  1294. // after we tell it to become passive. Apart from Firefox which I tested
  1295. // after the fix was deployed, I tested Chrome only. In order to prevent
  1296. // issues with other browsers, limit the fix to Chrome for the time
  1297. // being.
  1298. return;
  1299. }
  1300. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  1301. // answerer (as orchestrated by Jicofo). In accord with
  1302. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  1303. // are ICE FULL agents, Videobridge will take on the controlling role and
  1304. // WebRTC will take on the controlled role. In accord with
  1305. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  1306. // setup attribute value of setup:actpass and WebRTC will be allowed to
  1307. // choose either the setup attribute value of setup:active or
  1308. // setup:passive. Chrome will by default choose setup:active because it is
  1309. // RECOMMENDED by the respective RFC since setup:passive adds additional
  1310. // latency. The case of setup:active allows WebRTC to send a DTLS
  1311. // ClientHello as soon as an ICE connectivity check of its succeeds.
  1312. // Unfortunately, Videobridge will be unable to respond immediately because
  1313. // may not have WebRTC's answer or may have not completed the ICE
  1314. // connectivity establishment. Even more unfortunate is that in the
  1315. // described scenario Chrome's DTLS implementation will insist on
  1316. // retransmitting its ClientHello after a second (the time is in accord
  1317. // with the respective RFC) and will thus cause the whole connection
  1318. // establishment to exceed at least 1 second. To work around Chrome's
  1319. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  1320. // default choice of setup:active to setup:passive.
  1321. if (offer && answer
  1322. && offer.media && answer.media
  1323. && offer.media.length === answer.media.length) {
  1324. answer.media.forEach((a, i) => {
  1325. if (SDPUtil.findLine(
  1326. offer.media[i],
  1327. 'a=setup:actpass',
  1328. offer.session)) {
  1329. answer.media[i]
  1330. = a.replace(/a=setup:active/g, 'a=setup:passive');
  1331. }
  1332. });
  1333. answer.raw = answer.session + answer.media.join('');
  1334. }
  1335. };
  1336. TraceablePeerConnection.prototype.createAnswer
  1337. = function(successCallback, failureCallback, constraints) {
  1338. this._createOfferOrAnswer(
  1339. false /* answer */, successCallback, failureCallback, constraints);
  1340. };
  1341. TraceablePeerConnection.prototype.createOffer
  1342. = function(successCallback, failureCallback, constraints) {
  1343. this._createOfferOrAnswer(
  1344. true /* offer */, successCallback, failureCallback, constraints);
  1345. };
  1346. /* eslint-disable max-params */
  1347. TraceablePeerConnection.prototype._createOfferOrAnswer
  1348. = function(isOffer, successCallback, failureCallback, constraints) {
  1349. const logName = isOffer ? 'Offer' : 'Answer';
  1350. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  1351. const _successCallback = resultSdp => {
  1352. try {
  1353. this.trace(
  1354. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  1355. // if we're using unified plan, transform to Plan B.
  1356. if (RTCBrowserType.usesUnifiedPlan()) {
  1357. // eslint-disable-next-line no-param-reassign
  1358. resultSdp = this.interop.toPlanB(resultSdp);
  1359. this.trace(
  1360. `create${logName}OnSuccess::postTransform (Plan B)`,
  1361. dumpSDP(resultSdp));
  1362. }
  1363. /**
  1364. * We don't keep ssrcs consitent for Firefox because rewriting
  1365. * the ssrcs between createAnswer and setLocalDescription breaks
  1366. * the caching in sdp-interop (sdp-interop must know about all
  1367. * ssrcs, and it updates its cache in toPlanB so if we rewrite them
  1368. * after that, when we try and go back to unified plan it will
  1369. * complain about unmapped ssrcs)
  1370. */
  1371. if (!RTCBrowserType.isFirefox()) {
  1372. // If there are no local video tracks, then a "recvonly"
  1373. // SSRC needs to be generated
  1374. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  1375. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  1376. this.generateRecvonlySsrc();
  1377. }
  1378. resultSdp.sdp
  1379. = this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  1380. resultSdp.sdp);
  1381. this.trace(
  1382. `create${logName}OnSuccess::postTransform `
  1383. + '(make primary audio/video ssrcs consistent)',
  1384. dumpSDP(resultSdp));
  1385. }
  1386. // Add simulcast streams if simulcast is enabled
  1387. if (this.isSimulcastOn()) {
  1388. // eslint-disable-next-line no-param-reassign
  1389. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  1390. this.trace(
  1391. `create${logName}`
  1392. + 'OnSuccess::postTransform (simulcast)',
  1393. dumpSDP(resultSdp));
  1394. }
  1395. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  1396. resultSdp.sdp
  1397. = this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp);
  1398. this.trace(
  1399. `create${logName}`
  1400. + 'OnSuccess::postTransform (rtx modifier)',
  1401. dumpSDP(resultSdp));
  1402. }
  1403. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  1404. // details)
  1405. if (!isOffer) {
  1406. const remoteDescription
  1407. = new SDP(this.remoteDescription.sdp);
  1408. const localDescription = new SDP(resultSdp.sdp);
  1409. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  1410. resultSdp.sdp = localDescription.raw;
  1411. }
  1412. const ssrcMap = extractSSRCMap(resultSdp);
  1413. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  1414. this._processLocalSSRCsMap(ssrcMap);
  1415. successCallback(resultSdp);
  1416. } catch (e) {
  1417. this.trace(`create${logName}OnError`, e);
  1418. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  1419. logger.error(`create${logName}OnError`, e, dumpSDP(resultSdp));
  1420. failureCallback(e);
  1421. }
  1422. };
  1423. const _errorCallback = err => {
  1424. this.trace(`create${logName}OnFailure`, err);
  1425. const eventType
  1426. = isOffer
  1427. ? RTCEvents.CREATE_OFFER_FAILED
  1428. : RTCEvents.CREATE_ANSWER_FAILED;
  1429. this.eventEmitter.emit(eventType, err, this.peerconnection);
  1430. failureCallback(err);
  1431. };
  1432. // NOTE Temasys plugin does not support "bind" on peerconnection methods
  1433. if (isOffer) {
  1434. this.peerconnection.createOffer(
  1435. _successCallback, _errorCallback, constraints);
  1436. } else {
  1437. this.peerconnection.createAnswer(
  1438. _successCallback, _errorCallback, constraints);
  1439. }
  1440. };
  1441. /* eslint-enable max-params */
  1442. /**
  1443. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  1444. * @param {TrackSSRCInfo} ssrcObj
  1445. * @return {number|null} the primary SSRC or <tt>null</tt>
  1446. */
  1447. function extractPrimarySSRC(ssrcObj) {
  1448. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  1449. return ssrcObj.groups[0].ssrcs[0];
  1450. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  1451. return ssrcObj.ssrcs[0];
  1452. }
  1453. return null;
  1454. }
  1455. /**
  1456. * Goes over the SSRC map extracted from the latest local description and tries
  1457. * to match them with the local tracks (by MSID). Will update the values
  1458. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  1459. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  1460. * @private
  1461. */
  1462. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  1463. for (const track of this.localTracks.values()) {
  1464. const trackMSID = track.getMSID();
  1465. if (ssrcMap.has(trackMSID)) {
  1466. const newSSRC = ssrcMap.get(trackMSID);
  1467. if (!newSSRC) {
  1468. logger.error(`No SSRC found for: ${trackMSID} in ${this}`);
  1469. return;
  1470. }
  1471. const oldSSRC = this.localSSRCs.get(track.rtcId);
  1472. const newSSRCNum = extractPrimarySSRC(newSSRC);
  1473. const oldSSRCNum = extractPrimarySSRC(oldSSRC);
  1474. // eslint-disable-next-line no-negated-condition
  1475. if (newSSRCNum !== oldSSRCNum) {
  1476. if (oldSSRCNum === null) {
  1477. logger.info(
  1478. `Storing new local SSRC for ${track} in ${this}`,
  1479. newSSRC);
  1480. } else {
  1481. logger.error(
  1482. `Overwriting SSRC for ${track} ${trackMSID} in ${this
  1483. } with: `, newSSRC);
  1484. }
  1485. this.localSSRCs.set(track.rtcId, newSSRC);
  1486. } else {
  1487. logger.debug(
  1488. `The local SSRC(${newSSRCNum}) for ${track} ${trackMSID}`
  1489. + `is still up to date in ${this}`);
  1490. }
  1491. } else {
  1492. logger.warn(`No local track matched with: ${trackMSID} in ${this}`);
  1493. }
  1494. }
  1495. };
  1496. TraceablePeerConnection.prototype.addIceCandidate
  1497. = function(candidate, successCallback, failureCallback) {
  1498. // var self = this;
  1499. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  1500. this.peerconnection.addIceCandidate(
  1501. candidate, successCallback, failureCallback);
  1502. /* maybe later
  1503. this.peerconnection.addIceCandidate(candidate,
  1504. function () {
  1505. self.trace('addIceCandidateOnSuccess');
  1506. successCallback();
  1507. },
  1508. function (err) {
  1509. self.trace('addIceCandidateOnFailure', err);
  1510. failureCallback(err);
  1511. }
  1512. );
  1513. */
  1514. };
  1515. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  1516. // TODO: Is this the correct way to handle Opera, Temasys?
  1517. if (RTCBrowserType.isFirefox()
  1518. || RTCBrowserType.isTemasysPluginUsed()
  1519. || RTCBrowserType.isReactNative()) {
  1520. this.peerconnection.getStats(
  1521. null,
  1522. callback,
  1523. errback || (() => {
  1524. // Making sure that getStats won't fail if error callback is
  1525. // not passed.
  1526. }));
  1527. } else {
  1528. this.peerconnection.getStats(callback);
  1529. }
  1530. };
  1531. /**
  1532. * Generates and stores new SSRC info object for given local track.
  1533. * The method should be called only for a video track being added to this TPC
  1534. * in the muted state (given that the current browser uses this strategy).
  1535. * @param {JitsiLocalTrack} track
  1536. * @return {TPCSSRCInfo}
  1537. */
  1538. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  1539. const rtcId = track.rtcId;
  1540. let ssrcInfo = this._getSSRC(rtcId);
  1541. if (ssrcInfo) {
  1542. logger.error(`Will overwrite local SSRCs for track ID: ${rtcId}`);
  1543. }
  1544. if (this.isSimulcastOn()) {
  1545. ssrcInfo = {
  1546. ssrcs: [],
  1547. groups: []
  1548. };
  1549. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  1550. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  1551. }
  1552. ssrcInfo.groups.push({
  1553. ssrcs: ssrcInfo.ssrcs.slice(),
  1554. semantics: 'SIM'
  1555. });
  1556. } else {
  1557. ssrcInfo = {
  1558. ssrcs: [ SDPUtil.generateSsrc() ],
  1559. groups: []
  1560. };
  1561. }
  1562. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  1563. // Specifically use a for loop here because we'll
  1564. // be adding to the list we're iterating over, so we
  1565. // only want to iterate through the items originally
  1566. // on the list
  1567. const currNumSsrcs = ssrcInfo.ssrcs.length;
  1568. for (let i = 0; i < currNumSsrcs; ++i) {
  1569. const primarySsrc = ssrcInfo.ssrcs[i];
  1570. const rtxSsrc = SDPUtil.generateSsrc();
  1571. ssrcInfo.ssrcs.push(rtxSsrc);
  1572. ssrcInfo.groups.push({
  1573. ssrcs: [ primarySsrc, rtxSsrc ],
  1574. semantics: 'FID'
  1575. });
  1576. }
  1577. }
  1578. ssrcInfo.msid = track.storedMSID;
  1579. this.localSSRCs.set(rtcId, ssrcInfo);
  1580. return ssrcInfo;
  1581. };
  1582. /**
  1583. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  1584. * instance.
  1585. * @return {string}
  1586. */
  1587. TraceablePeerConnection.prototype.toString = function() {
  1588. return `TPC[${this.id},p2p:${this.isP2P}]`;
  1589. };
  1590. module.exports = TraceablePeerConnection;