modified lib-jitsi-meet dev repo
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 97KB

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