您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TraceablePeerConnection.js 75KB

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