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

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