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 66KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017
  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() || RTCBrowserType.isEdge()) {
  455. stream.onaddtrack = event => {
  456. this._remoteTrackAdded(stream, event.track);
  457. };
  458. stream.onremovetrack = event => {
  459. this._remoteTrackRemoved(stream, 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 && RTC.getTrackID(track);
  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. * Makes sure that both audio and video directions are configured as 'sendrecv'.
  882. * @param {Object} localDescription the SDP object as defined by WebRTC.
  883. */
  884. const enforceSendRecv = function(localDescription) {
  885. if (localDescription && localDescription.sdp) {
  886. const transformer = new SdpTransformWrap(localDescription.sdp);
  887. const audioMedia = transformer.selectMedia('audio');
  888. let changed = false;
  889. if (audioMedia && audioMedia.direction !== 'sendrecv') {
  890. audioMedia.direction = 'sendrecv';
  891. changed = true;
  892. }
  893. const videoMedia = transformer.selectMedia('video');
  894. if (videoMedia && videoMedia.direction !== 'sendrecv') {
  895. videoMedia.direction = 'sendrecv';
  896. changed = true;
  897. }
  898. if (changed) {
  899. localDescription.sdp = transformer.toRawSDP();
  900. }
  901. }
  902. };
  903. /**
  904. *
  905. * @param {JitsiLocalTrack} localTrack
  906. */
  907. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  908. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  909. return ssrcInfo && ssrcInfo.ssrcs[0];
  910. };
  911. /* eslint-disable-next-line vars-on-top */
  912. const getters = {
  913. signalingState() {
  914. return this.peerconnection.signalingState;
  915. },
  916. iceConnectionState() {
  917. return this.peerconnection.iceConnectionState;
  918. },
  919. localDescription() {
  920. let desc = this.peerconnection.localDescription;
  921. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  922. // if we're running on FF, transform to Plan B first.
  923. if (RTCBrowserType.usesUnifiedPlan()) {
  924. desc = this.interop.toPlanB(desc);
  925. this.trace('getLocalDescription::postTransform (Plan B)',
  926. dumpSDP(desc));
  927. }
  928. if (RTCBrowserType.doesVideoMuteByStreamRemove()) {
  929. this.localSdpMunger.maybeMungeLocalSdp(desc);
  930. logger.debug(
  931. 'getLocalDescription::postTransform (munge local SDP)', desc);
  932. }
  933. // What comes out of this getter will be signalled over Jingle to
  934. // the other peer, so we need to make sure the media direction is
  935. // 'sendrecv' because we won't change the direction later and don't want
  936. // the other peer to think we can't send or receive.
  937. //
  938. // Note that the description we set in chrome does have the accurate
  939. // direction (e.g. 'recvonly'), since that is technically what is
  940. // happening (check setLocalDescription impl).
  941. enforceSendRecv(desc);
  942. return desc || {};
  943. },
  944. remoteDescription() {
  945. let desc = this.peerconnection.remoteDescription;
  946. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  947. // if we're running on FF, transform to Plan B first.
  948. if (RTCBrowserType.usesUnifiedPlan()) {
  949. desc = this.interop.toPlanB(desc);
  950. this.trace(
  951. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  952. }
  953. return desc || {};
  954. }
  955. };
  956. Object.keys(getters).forEach(prop => {
  957. Object.defineProperty(
  958. TraceablePeerConnection.prototype,
  959. prop, {
  960. get: getters[prop]
  961. }
  962. );
  963. });
  964. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  965. return this.localSSRCs.get(rtcId);
  966. };
  967. /**
  968. * Add {@link JitsiLocalTrack} to this TPC.
  969. * @param {JitsiLocalTrack} track
  970. */
  971. TraceablePeerConnection.prototype.addTrack = function(track) {
  972. const rtcId = track.rtcId;
  973. logger.info(`add ${track} to: ${this}`);
  974. if (this.localTracks.has(rtcId)) {
  975. logger.error(`${track} is already in ${this}`);
  976. return;
  977. }
  978. this.localTracks.set(rtcId, track);
  979. const webrtcStream = track.getOriginalStream();
  980. if (webrtcStream) {
  981. this._addStream(webrtcStream);
  982. // It's not ok for a track to not have a WebRTC stream if:
  983. } else if (!RTCBrowserType.doesVideoMuteByStreamRemove()
  984. || track.isAudioTrack()
  985. || (track.isVideoTrack() && !track.isMuted())) {
  986. logger.error(`${this} no WebRTC stream for: ${track}`);
  987. }
  988. // Muted video tracks do not have WebRTC stream
  989. if (RTCBrowserType.doesVideoMuteByStreamRemove()
  990. && track.isVideoTrack() && track.isMuted()) {
  991. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  992. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  993. const simGroup
  994. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  995. if (simGroup) {
  996. this.simulcast.setSsrcCache(simGroup.ssrcs);
  997. }
  998. const fidGroups
  999. = ssrcInfo.groups.filter(
  1000. groupInfo => groupInfo.semantics === 'FID');
  1001. if (fidGroups) {
  1002. const rtxSsrcMapping = new Map();
  1003. fidGroups.forEach(fidGroup => {
  1004. const primarySsrc = fidGroup.ssrcs[0];
  1005. const rtxSsrc = fidGroup.ssrcs[1];
  1006. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  1007. });
  1008. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  1009. }
  1010. }
  1011. };
  1012. /**
  1013. * Adds local track as part of the unmute operation.
  1014. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  1015. * operation
  1016. * @return {boolean} <tt>true</tt> if the state of underlying PC has changed and
  1017. * the renegotiation is required or <tt>false</tt> otherwise.
  1018. */
  1019. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  1020. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  1021. // Abort
  1022. return false;
  1023. }
  1024. logger.info(`Adding ${track} as unmute to ${this}`);
  1025. const webRtcStream = track.getOriginalStream();
  1026. if (!webRtcStream) {
  1027. logger.error(
  1028. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  1029. return false;
  1030. }
  1031. this._addStream(webRtcStream);
  1032. return true;
  1033. };
  1034. /**
  1035. * Adds WebRTC media stream to the underlying PeerConnection
  1036. * @param {MediaStream} mediaStream
  1037. * @private
  1038. */
  1039. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  1040. this.peerconnection.addStream(mediaStream);
  1041. };
  1042. /**
  1043. * Removes WebRTC media stream from the underlying PeerConection
  1044. * @param {MediaStream} mediaStream
  1045. */
  1046. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  1047. if (RTCBrowserType.isFirefox()) {
  1048. this._handleFirefoxRemoveStream(mediaStream);
  1049. } else {
  1050. this.peerconnection.removeStream(mediaStream);
  1051. }
  1052. };
  1053. /**
  1054. * This method when called will check if given <tt>localTrack</tt> belongs to
  1055. * this TPC (that it has been previously added using {@link addTrack}). If the
  1056. * track does not belong an error message will be logged.
  1057. * @param {string} methodName the method name that will be logged in an error
  1058. * message
  1059. * @param {JitsiLocalTrack} localTrack
  1060. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1061. * <tt>false</tt> otherwise.
  1062. * @private
  1063. */
  1064. TraceablePeerConnection.prototype._assertTrackBelongs
  1065. = function(methodName, localTrack) {
  1066. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1067. if (!doesBelong) {
  1068. logger.error(
  1069. `${methodName}: ${localTrack} does not belong to ${this}`);
  1070. }
  1071. return doesBelong;
  1072. };
  1073. /**
  1074. * Remove local track from this TPC.
  1075. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1076. *
  1077. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1078. * The same applies to addTrack.
  1079. */
  1080. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1081. const webRtcStream = localTrack.getOriginalStream();
  1082. this.trace(
  1083. 'removeStream',
  1084. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1085. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1086. // Abort - nothing to be done here
  1087. return;
  1088. }
  1089. this.localTracks.delete(localTrack.rtcId);
  1090. this.localSSRCs.delete(localTrack.rtcId);
  1091. if (webRtcStream) {
  1092. if (RTCBrowserType.isFirefox()) {
  1093. this._handleFirefoxRemoveStream(webRtcStream);
  1094. } else {
  1095. this.peerconnection.removeStream(webRtcStream);
  1096. }
  1097. }
  1098. };
  1099. /**
  1100. * Removes local track as part of the mute operation.
  1101. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1102. * the mute operation.
  1103. * @return {boolean} <tt>true</tt> if the underlying PeerConnection's state has
  1104. * changed and the renegotiation is required or <tt>false</tt> otherwise.
  1105. */
  1106. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1107. const webRtcStream = localTrack.getOriginalStream();
  1108. this.trace(
  1109. 'removeStreamMute',
  1110. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1111. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1112. // Abort - nothing to be done here
  1113. return false;
  1114. }
  1115. if (webRtcStream) {
  1116. logger.info(
  1117. `Removing ${localTrack} as mute from ${this}`);
  1118. this._removeStream(webRtcStream);
  1119. return true;
  1120. }
  1121. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1122. return false;
  1123. };
  1124. /**
  1125. * Remove stream handling for firefox
  1126. * @param stream: webrtc media stream
  1127. */
  1128. TraceablePeerConnection.prototype._handleFirefoxRemoveStream
  1129. = function(stream) {
  1130. if (!stream) {
  1131. // There is nothing to be changed
  1132. return;
  1133. }
  1134. let sender = null;
  1135. // On Firefox we don't replace MediaStreams as this messes up the
  1136. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1137. // of complications. Instead, we use the RTPSender and remove just
  1138. // the track.
  1139. let track = null;
  1140. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  1141. track = stream.getAudioTracks()[0];
  1142. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  1143. track = stream.getVideoTracks()[0];
  1144. }
  1145. if (!track) {
  1146. logger.error('Cannot remove tracks: no tracks.');
  1147. return;
  1148. }
  1149. // Find the right sender (for audio or video)
  1150. this.peerconnection.getSenders().some(s => {
  1151. if (s.track === track) {
  1152. sender = s;
  1153. return true;
  1154. }
  1155. return false;
  1156. });
  1157. if (sender) {
  1158. this.peerconnection.removeTrack(sender);
  1159. } else {
  1160. logger.log('Cannot remove tracks: no RTPSender.');
  1161. }
  1162. };
  1163. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1164. this.trace('createDataChannel', label, opts);
  1165. return this.peerconnection.createDataChannel(label, opts);
  1166. };
  1167. /**
  1168. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1169. * in the SDP so that simulcast is properly activated.
  1170. *
  1171. * @param {Object} localSdp the WebRTC session description instance for
  1172. * the local description.
  1173. * @private
  1174. */
  1175. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast
  1176. = function(localSdp) {
  1177. let sdpStr = localSdp.sdp;
  1178. const videoStartIndex = sdpStr.indexOf('m=video');
  1179. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1180. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1181. if (simStartIndex === -1
  1182. || otherStartIndex === -1
  1183. || otherStartIndex === simStartIndex) {
  1184. return;
  1185. }
  1186. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1187. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1188. sdpStr = sdpStr.replace(simStr, '');
  1189. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1190. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1191. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1192. const simStrTrimmed = simStr.trim();
  1193. const sdpTail = sdpStr.slice(otherEndIndex);
  1194. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1195. localSdp.sdp = sdpStr;
  1196. };
  1197. /**
  1198. * Will adjust audio and video media direction in the given SDP object to
  1199. * reflect the current status of the {@link audioTransferActive} and
  1200. * {@link videoTransferActive} flags.
  1201. * @param {Object} localDescription the WebRTC session description instance for
  1202. * the local description.
  1203. * @private
  1204. */
  1205. TraceablePeerConnection.prototype._adjustLocalMediaDirection
  1206. = function(localDescription) {
  1207. const transformer = new SdpTransformWrap(localDescription.sdp);
  1208. let modifiedDirection = false;
  1209. const audioMedia = transformer.selectMedia('audio');
  1210. if (audioMedia) {
  1211. const desiredAudioDirection
  1212. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1213. if (audioMedia.direction !== desiredAudioDirection) {
  1214. audioMedia.direction = desiredAudioDirection;
  1215. logger.info(
  1216. `Adjusted local audio direction to ${desiredAudioDirection}`);
  1217. modifiedDirection = true;
  1218. }
  1219. } else {
  1220. logger.warn('No "audio" media found int the local description');
  1221. }
  1222. const videoMedia = transformer.selectMedia('video');
  1223. if (videoMedia) {
  1224. const desiredVideoDirection
  1225. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1226. if (videoMedia.direction !== desiredVideoDirection) {
  1227. videoMedia.direction = desiredVideoDirection;
  1228. logger.info(
  1229. `Adjusted local video direction to ${desiredVideoDirection}`);
  1230. modifiedDirection = true;
  1231. }
  1232. } else {
  1233. logger.warn('No "video" media found in the local description');
  1234. }
  1235. if (modifiedDirection) {
  1236. localDescription.sdp = transformer.toRawSDP();
  1237. }
  1238. };
  1239. TraceablePeerConnection.prototype.setLocalDescription
  1240. = function(description, successCallback, failureCallback) {
  1241. let localSdp = description;
  1242. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1243. this._adjustLocalMediaDirection(localSdp);
  1244. this._ensureSimulcastGroupIsLast(localSdp);
  1245. // if we're using unified plan, transform to it first.
  1246. if (RTCBrowserType.usesUnifiedPlan()) {
  1247. localSdp = this.interop.toUnifiedPlan(localSdp);
  1248. this.trace(
  1249. 'setLocalDescription::postTransform (Unified Plan)',
  1250. dumpSDP(localSdp));
  1251. }
  1252. this.peerconnection.setLocalDescription(localSdp,
  1253. () => {
  1254. this.trace('setLocalDescriptionOnSuccess');
  1255. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1256. if (localUfrag !== this.localUfrag) {
  1257. this.localUfrag = localUfrag;
  1258. this.eventEmitter.emit(
  1259. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1260. }
  1261. successCallback();
  1262. },
  1263. err => {
  1264. this.trace('setLocalDescriptionOnFailure', err);
  1265. this.eventEmitter.emit(
  1266. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1267. err, this);
  1268. failureCallback(err);
  1269. }
  1270. );
  1271. };
  1272. /**
  1273. * Enables/disables audio media transmission on this peer connection. When
  1274. * disabled the SDP audio media direction in the local SDP will be adjusted to
  1275. * 'inactive' which means that no data will be sent nor accepted, but
  1276. * the connection should be kept alive.
  1277. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  1278. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1279. * no effect.
  1280. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1281. * needs to be executed in order for the changes to take effect or
  1282. * <tt>false</tt> if the given value was the same as the previous one.
  1283. * @public
  1284. */
  1285. TraceablePeerConnection.prototype.setAudioTransferActive = function(active) {
  1286. logger.debug(`${this} audio transfer active: ${active}`);
  1287. const changed = this.audioTransferActive !== active;
  1288. this.audioTransferActive = active;
  1289. return changed;
  1290. };
  1291. TraceablePeerConnection.prototype.setRemoteDescription
  1292. = function(description, successCallback, failureCallback) {
  1293. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1294. // TODO the focus should squeze or explode the remote simulcast
  1295. // eslint-disable-next-line no-param-reassign
  1296. description = this.simulcast.mungeRemoteDescription(description);
  1297. this.trace(
  1298. 'setRemoteDescription::postTransform (simulcast)',
  1299. dumpSDP(description));
  1300. if (this.options.preferH264) {
  1301. const parsedSdp = transform.parse(description.sdp);
  1302. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1303. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1304. description.sdp = transform.write(parsedSdp);
  1305. }
  1306. // If the browser uses unified plan, transform to it first
  1307. if (RTCBrowserType.usesUnifiedPlan()) {
  1308. description.sdp = this.rtxModifier.stripRtx(description.sdp);
  1309. this.trace(
  1310. 'setRemoteDescription::postTransform (stripRtx)',
  1311. dumpSDP(description));
  1312. // eslint-disable-next-line no-param-reassign
  1313. description = this.interop.toUnifiedPlan(description);
  1314. this.trace(
  1315. 'setRemoteDescription::postTransform (Plan A)',
  1316. dumpSDP(description));
  1317. } else {
  1318. // Plan B
  1319. // eslint-disable-next-line no-param-reassign
  1320. description = normalizePlanB(description);
  1321. }
  1322. this.peerconnection.setRemoteDescription(
  1323. description,
  1324. () => {
  1325. this.trace('setRemoteDescriptionOnSuccess');
  1326. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  1327. if (remoteUfrag !== this.remoteUfrag) {
  1328. this.remoteUfrag = remoteUfrag;
  1329. this.eventEmitter.emit(
  1330. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1331. }
  1332. successCallback();
  1333. },
  1334. err => {
  1335. this.trace('setRemoteDescriptionOnFailure', err);
  1336. this.eventEmitter.emit(
  1337. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  1338. err,
  1339. this);
  1340. failureCallback(err);
  1341. });
  1342. };
  1343. /**
  1344. * Enables/disables video media transmission on this peer connection. When
  1345. * disabled the SDP video media direction in the local SDP will be adjusted to
  1346. * 'inactive' which means that no data will be sent nor accepted, but
  1347. * the connection should be kept alive.
  1348. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  1349. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1350. * no effect.
  1351. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1352. * needs to be executed in order for the changes to take effect or
  1353. * <tt>false</tt> if the given value was the same as the previous one.
  1354. * @public
  1355. */
  1356. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  1357. logger.debug(`${this} video transfer active: ${active}`);
  1358. const changed = this.videoTransferActive !== active;
  1359. this.videoTransferActive = active;
  1360. return changed;
  1361. };
  1362. /**
  1363. * Makes the underlying TraceablePeerConnection generate new SSRC for
  1364. * the recvonly video stream.
  1365. */
  1366. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  1367. const newSSRC = SDPUtil.generateSsrc();
  1368. logger.info(`${this} generated new recvonly SSRC: ${newSSRC}`);
  1369. this.sdpConsistency.setPrimarySsrc(newSSRC);
  1370. };
  1371. /**
  1372. * Makes the underlying TraceablePeerConnection forget the current primary video
  1373. * SSRC.
  1374. */
  1375. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  1376. logger.info('Clearing primary video SSRC!');
  1377. this.sdpConsistency.clearVideoSsrcCache();
  1378. };
  1379. /**
  1380. * Closes underlying WebRTC PeerConnection instance and removes all remote
  1381. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  1382. * them.
  1383. */
  1384. TraceablePeerConnection.prototype.close = function() {
  1385. this.trace('stop');
  1386. // Off SignalingEvents
  1387. this.signalingLayer.off(
  1388. SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  1389. this.signalingLayer.off(
  1390. SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  1391. for (const peerTracks of this.remoteTracks.values()) {
  1392. for (const remoteTrack of peerTracks.values()) {
  1393. this._removeRemoteTrack(remoteTrack);
  1394. }
  1395. }
  1396. this.remoteTracks.clear();
  1397. if (!this.rtc._removePeerConnection(this)) {
  1398. logger.error('RTC._removePeerConnection returned false');
  1399. }
  1400. if (this.statsinterval !== null) {
  1401. window.clearInterval(this.statsinterval);
  1402. this.statsinterval = null;
  1403. }
  1404. logger.info(`Closing ${this}...`);
  1405. this.peerconnection.close();
  1406. };
  1407. /**
  1408. * Modifies the values of the setup attributes (defined by
  1409. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  1410. * answer in order to overcome a delay of 1 second in the connection
  1411. * establishment between Chrome and Videobridge.
  1412. *
  1413. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  1414. * being prepared to respond
  1415. * @param {SDP} answer - the SDP to modify
  1416. * @private
  1417. */
  1418. const _fixAnswerRFC4145Setup = function(offer, answer) {
  1419. if (!RTCBrowserType.isChrome()) {
  1420. // It looks like Firefox doesn't agree with the fix (at least in its
  1421. // current implementation) because it effectively remains active even
  1422. // after we tell it to become passive. Apart from Firefox which I tested
  1423. // after the fix was deployed, I tested Chrome only. In order to prevent
  1424. // issues with other browsers, limit the fix to Chrome for the time
  1425. // being.
  1426. return;
  1427. }
  1428. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  1429. // answerer (as orchestrated by Jicofo). In accord with
  1430. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  1431. // are ICE FULL agents, Videobridge will take on the controlling role and
  1432. // WebRTC will take on the controlled role. In accord with
  1433. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  1434. // setup attribute value of setup:actpass and WebRTC will be allowed to
  1435. // choose either the setup attribute value of setup:active or
  1436. // setup:passive. Chrome will by default choose setup:active because it is
  1437. // RECOMMENDED by the respective RFC since setup:passive adds additional
  1438. // latency. The case of setup:active allows WebRTC to send a DTLS
  1439. // ClientHello as soon as an ICE connectivity check of its succeeds.
  1440. // Unfortunately, Videobridge will be unable to respond immediately because
  1441. // may not have WebRTC's answer or may have not completed the ICE
  1442. // connectivity establishment. Even more unfortunate is that in the
  1443. // described scenario Chrome's DTLS implementation will insist on
  1444. // retransmitting its ClientHello after a second (the time is in accord
  1445. // with the respective RFC) and will thus cause the whole connection
  1446. // establishment to exceed at least 1 second. To work around Chrome's
  1447. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  1448. // default choice of setup:active to setup:passive.
  1449. if (offer && answer
  1450. && offer.media && answer.media
  1451. && offer.media.length === answer.media.length) {
  1452. answer.media.forEach((a, i) => {
  1453. if (SDPUtil.findLine(
  1454. offer.media[i],
  1455. 'a=setup:actpass',
  1456. offer.session)) {
  1457. answer.media[i]
  1458. = a.replace(/a=setup:active/g, 'a=setup:passive');
  1459. }
  1460. });
  1461. answer.raw = answer.session + answer.media.join('');
  1462. }
  1463. };
  1464. TraceablePeerConnection.prototype.createAnswer
  1465. = function(successCallback, failureCallback, constraints) {
  1466. this._createOfferOrAnswer(
  1467. false /* answer */, successCallback, failureCallback, constraints);
  1468. };
  1469. TraceablePeerConnection.prototype.createOffer
  1470. = function(successCallback, failureCallback, constraints) {
  1471. this._createOfferOrAnswer(
  1472. true /* offer */, successCallback, failureCallback, constraints);
  1473. };
  1474. /* eslint-disable max-params */
  1475. TraceablePeerConnection.prototype._createOfferOrAnswer
  1476. = function(isOffer, successCallback, failureCallback, constraints) {
  1477. const logName = isOffer ? 'Offer' : 'Answer';
  1478. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  1479. const _successCallback = resultSdp => {
  1480. try {
  1481. this.trace(
  1482. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  1483. // if we're using unified plan, transform to Plan B.
  1484. if (RTCBrowserType.usesUnifiedPlan()) {
  1485. // eslint-disable-next-line no-param-reassign
  1486. resultSdp = this.interop.toPlanB(resultSdp);
  1487. this.trace(
  1488. `create${logName}OnSuccess::postTransform (Plan B)`,
  1489. dumpSDP(resultSdp));
  1490. }
  1491. /**
  1492. * We don't keep ssrcs consitent for Firefox because rewriting
  1493. * the ssrcs between createAnswer and setLocalDescription breaks
  1494. * the caching in sdp-interop (sdp-interop must know about all
  1495. * ssrcs, and it updates its cache in toPlanB so if we rewrite them
  1496. * after that, when we try and go back to unified plan it will
  1497. * complain about unmapped ssrcs)
  1498. */
  1499. if (!RTCBrowserType.isFirefox()) {
  1500. // If there are no local video tracks, then a "recvonly"
  1501. // SSRC needs to be generated
  1502. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  1503. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  1504. this.generateRecvonlySsrc();
  1505. }
  1506. resultSdp.sdp
  1507. = this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  1508. resultSdp.sdp);
  1509. this.trace(
  1510. `create${logName}OnSuccess::postTransform `
  1511. + '(make primary audio/video ssrcs consistent)',
  1512. dumpSDP(resultSdp));
  1513. }
  1514. // Add simulcast streams if simulcast is enabled
  1515. if (this.isSimulcastOn()) {
  1516. // eslint-disable-next-line no-param-reassign
  1517. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  1518. this.trace(
  1519. `create${logName}`
  1520. + 'OnSuccess::postTransform (simulcast)',
  1521. dumpSDP(resultSdp));
  1522. }
  1523. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  1524. resultSdp.sdp
  1525. = this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp);
  1526. this.trace(
  1527. `create${logName}`
  1528. + 'OnSuccess::postTransform (rtx modifier)',
  1529. dumpSDP(resultSdp));
  1530. }
  1531. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  1532. // details)
  1533. if (!isOffer) {
  1534. const remoteDescription
  1535. = new SDP(this.remoteDescription.sdp);
  1536. const localDescription = new SDP(resultSdp.sdp);
  1537. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  1538. resultSdp.sdp = localDescription.raw;
  1539. }
  1540. const ssrcMap = extractSSRCMap(resultSdp);
  1541. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  1542. this._processLocalSSRCsMap(ssrcMap);
  1543. successCallback(resultSdp);
  1544. } catch (e) {
  1545. this.trace(`create${logName}OnError`, e);
  1546. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  1547. logger.error(`create${logName}OnError`, e, dumpSDP(resultSdp));
  1548. failureCallback(e);
  1549. }
  1550. };
  1551. const _errorCallback = err => {
  1552. this.trace(`create${logName}OnFailure`, err);
  1553. const eventType
  1554. = isOffer
  1555. ? RTCEvents.CREATE_OFFER_FAILED
  1556. : RTCEvents.CREATE_ANSWER_FAILED;
  1557. this.eventEmitter.emit(eventType, err, this);
  1558. failureCallback(err);
  1559. };
  1560. // NOTE Temasys plugin does not support "bind" on peerconnection methods
  1561. if (isOffer) {
  1562. this.peerconnection.createOffer(
  1563. _successCallback, _errorCallback, constraints);
  1564. } else {
  1565. this.peerconnection.createAnswer(
  1566. _successCallback, _errorCallback, constraints);
  1567. }
  1568. };
  1569. /* eslint-enable max-params */
  1570. /**
  1571. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  1572. * @param {TrackSSRCInfo} ssrcObj
  1573. * @return {number|null} the primary SSRC or <tt>null</tt>
  1574. */
  1575. function extractPrimarySSRC(ssrcObj) {
  1576. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  1577. return ssrcObj.groups[0].ssrcs[0];
  1578. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  1579. return ssrcObj.ssrcs[0];
  1580. }
  1581. return null;
  1582. }
  1583. /**
  1584. * Goes over the SSRC map extracted from the latest local description and tries
  1585. * to match them with the local tracks (by MSID). Will update the values
  1586. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  1587. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  1588. * @private
  1589. */
  1590. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  1591. for (const track of this.localTracks.values()) {
  1592. const trackMSID = track.getMSID();
  1593. if (ssrcMap.has(trackMSID)) {
  1594. const newSSRC = ssrcMap.get(trackMSID);
  1595. if (!newSSRC) {
  1596. logger.error(`No SSRC found for: ${trackMSID} in ${this}`);
  1597. return;
  1598. }
  1599. const oldSSRC = this.localSSRCs.get(track.rtcId);
  1600. const newSSRCNum = extractPrimarySSRC(newSSRC);
  1601. const oldSSRCNum = extractPrimarySSRC(oldSSRC);
  1602. // eslint-disable-next-line no-negated-condition
  1603. if (newSSRCNum !== oldSSRCNum) {
  1604. if (oldSSRCNum === null) {
  1605. logger.info(
  1606. `Storing new local SSRC for ${track} in ${this}`,
  1607. newSSRC);
  1608. } else {
  1609. logger.error(
  1610. `Overwriting SSRC for ${track} ${trackMSID} in ${this
  1611. } with: `, newSSRC);
  1612. }
  1613. this.localSSRCs.set(track.rtcId, newSSRC);
  1614. } else {
  1615. logger.debug(
  1616. `The local SSRC(${newSSRCNum}) for ${track} ${trackMSID}`
  1617. + `is still up to date in ${this}`);
  1618. }
  1619. } else {
  1620. logger.warn(`No local track matched with: ${trackMSID} in ${this}`);
  1621. }
  1622. }
  1623. };
  1624. TraceablePeerConnection.prototype.addIceCandidate
  1625. = function(candidate, successCallback, failureCallback) {
  1626. // var self = this;
  1627. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  1628. this.peerconnection.addIceCandidate(
  1629. candidate, successCallback, failureCallback);
  1630. /* maybe later
  1631. this.peerconnection.addIceCandidate(candidate,
  1632. function () {
  1633. self.trace('addIceCandidateOnSuccess');
  1634. successCallback();
  1635. },
  1636. function (err) {
  1637. self.trace('addIceCandidateOnFailure', err);
  1638. failureCallback(err);
  1639. }
  1640. );
  1641. */
  1642. };
  1643. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  1644. // TODO: Is this the correct way to handle Opera, Temasys?
  1645. if (RTCBrowserType.isFirefox()
  1646. || RTCBrowserType.isTemasysPluginUsed()
  1647. || RTCBrowserType.isReactNative()) {
  1648. this.peerconnection.getStats(
  1649. null,
  1650. callback,
  1651. errback || (() => {
  1652. // Making sure that getStats won't fail if error callback is
  1653. // not passed.
  1654. }));
  1655. } else {
  1656. this.peerconnection.getStats(callback);
  1657. }
  1658. };
  1659. /**
  1660. * Generates and stores new SSRC info object for given local track.
  1661. * The method should be called only for a video track being added to this TPC
  1662. * in the muted state (given that the current browser uses this strategy).
  1663. * @param {JitsiLocalTrack} track
  1664. * @return {TPCSSRCInfo}
  1665. */
  1666. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  1667. const rtcId = track.rtcId;
  1668. let ssrcInfo = this._getSSRC(rtcId);
  1669. if (ssrcInfo) {
  1670. logger.error(`Will overwrite local SSRCs for track ID: ${rtcId}`);
  1671. }
  1672. if (this.isSimulcastOn()) {
  1673. ssrcInfo = {
  1674. ssrcs: [],
  1675. groups: []
  1676. };
  1677. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  1678. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  1679. }
  1680. ssrcInfo.groups.push({
  1681. ssrcs: ssrcInfo.ssrcs.slice(),
  1682. semantics: 'SIM'
  1683. });
  1684. } else {
  1685. ssrcInfo = {
  1686. ssrcs: [ SDPUtil.generateSsrc() ],
  1687. groups: []
  1688. };
  1689. }
  1690. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  1691. // Specifically use a for loop here because we'll
  1692. // be adding to the list we're iterating over, so we
  1693. // only want to iterate through the items originally
  1694. // on the list
  1695. const currNumSsrcs = ssrcInfo.ssrcs.length;
  1696. for (let i = 0; i < currNumSsrcs; ++i) {
  1697. const primarySsrc = ssrcInfo.ssrcs[i];
  1698. const rtxSsrc = SDPUtil.generateSsrc();
  1699. ssrcInfo.ssrcs.push(rtxSsrc);
  1700. ssrcInfo.groups.push({
  1701. ssrcs: [ primarySsrc, rtxSsrc ],
  1702. semantics: 'FID'
  1703. });
  1704. }
  1705. }
  1706. ssrcInfo.msid = track.storedMSID;
  1707. this.localSSRCs.set(rtcId, ssrcInfo);
  1708. return ssrcInfo;
  1709. };
  1710. /**
  1711. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  1712. * instance.
  1713. * @return {string}
  1714. */
  1715. TraceablePeerConnection.prototype.toString = function() {
  1716. return `TPC[${this.id},p2p:${this.isP2P}]`;
  1717. };