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

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