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

TraceablePeerConnection.js 81KB

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