modified lib-jitsi-meet dev repo
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 65KB

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