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

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