modified lib-jitsi-meet dev repo
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TraceablePeerConnection.js 62KB

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