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

TraceablePeerConnection.js 92KB

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