Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

TraceablePeerConnection.js 71KB

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