Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

TraceablePeerConnection.js 81KB

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