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

TraceablePeerConnection.js 93KB

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