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

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