Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

TraceablePeerConnection.js 93KB

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