You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TraceablePeerConnection.js 92KB

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