You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TraceablePeerConnection.js 61KB

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