Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

TraceablePeerConnection.js 91KB

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