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

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