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

TraceablePeerConnection.js 73KB

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