Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

TraceablePeerConnection.js 86KB

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