您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TraceablePeerConnection.js 91KB

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