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 71KB

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