You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TraceablePeerConnection.js 78KB

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