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

TraceablePeerConnection.js 89KB

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