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.

JingleSessionPC.js 90KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388
  1. /* global __filename, $ */
  2. import {
  3. ICE_DURATION,
  4. ICE_STATE_CHANGED
  5. } from '../../service/statistics/AnalyticsEvents';
  6. import { getLogger } from 'jitsi-meet-logger';
  7. import { $iq, Strophe } from 'strophe.js';
  8. import { integerHash } from '../util/StringUtils';
  9. import browser from './../browser';
  10. import JingleSession from './JingleSession';
  11. import * as JingleSessionState from './JingleSessionState';
  12. import SDP from './SDP';
  13. import SDPDiffer from './SDPDiffer';
  14. import SDPUtil from './SDPUtil';
  15. import SignalingLayerImpl from './SignalingLayerImpl';
  16. import RTCEvents from '../../service/RTC/RTCEvents';
  17. import Statistics from '../statistics/statistics';
  18. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  19. import AsyncQueue from '../util/AsyncQueue';
  20. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  21. import XmppConnection from './XmppConnection';
  22. const logger = getLogger(__filename);
  23. /**
  24. * Constant tells how long we're going to wait for IQ response, before timeout
  25. * error is triggered.
  26. * @type {number}
  27. */
  28. const IQ_TIMEOUT = 10000;
  29. /*
  30. * The default number of samples (per stat) to keep when webrtc stats gathering
  31. * is enabled in TraceablePeerConnection.
  32. */
  33. const DEFAULT_MAX_STATS = 300;
  34. /**
  35. * @typedef {Object} JingleSessionPCOptions
  36. * @property {Object} abTesting - A/B testing related options (ask George).
  37. * @property {boolean} abTesting.enableSuspendVideoTest - enables the suspend
  38. * video test ?(ask George).
  39. * @property {boolean} disableH264 - Described in the config.js[1].
  40. * @property {boolean} disableRtx - Described in the config.js[1].
  41. * @property {boolean} disableSimulcast - Described in the config.js[1].
  42. * @property {boolean} enableLayerSuspension - Described in the config.js[1].
  43. * @property {boolean} failICE - it's an option used in the tests. Set to
  44. * <tt>true</tt> to block any real candidates and make the ICE fail.
  45. * @property {boolean} gatherStats - Described in the config.js[1].
  46. * @property {object} p2p - Peer to peer related options (FIXME those could be
  47. * fetched from config.p2p on the upper level).
  48. * @property {boolean} p2p.disableH264 - Described in the config.js[1].
  49. * @property {boolean} p2p.preferH264 - Described in the config.js[1].
  50. * @property {boolean} preferH264 - Described in the config.js[1].
  51. * @property {Object} testing - Testing and/or experimental options.
  52. * @property {boolean} testing.enableFirefoxSimulcast - Described in the
  53. * config.js[1].
  54. * @property {boolean} webrtcIceUdpDisable - Described in the config.js[1].
  55. * @property {boolean} webrtcIceTcpDisable - Described in the config.js[1].
  56. *
  57. * [1]: https://github.com/jitsi/jitsi-meet/blob/master/config.js
  58. */
  59. /**
  60. *
  61. */
  62. export default class JingleSessionPC extends JingleSession {
  63. /**
  64. * Parses 'senders' attribute of the video content.
  65. * @param {jQuery} jingleContents
  66. * @return {string|null} one of the values of content "senders" attribute
  67. * defined by Jingle. If there is no "senders" attribute or if the value is
  68. * invalid then <tt>null</tt> will be returned.
  69. * @private
  70. */
  71. static parseVideoSenders(jingleContents) {
  72. const videoContents = jingleContents.find('>content[name="video"]');
  73. if (videoContents.length) {
  74. const senders = videoContents[0].getAttribute('senders');
  75. if (senders === 'both'
  76. || senders === 'initiator'
  77. || senders === 'responder'
  78. || senders === 'none') {
  79. return senders;
  80. }
  81. }
  82. return null;
  83. }
  84. /* eslint-disable max-params */
  85. /**
  86. * Creates new <tt>JingleSessionPC</tt>
  87. * @param {string} sid the Jingle Session ID - random string which
  88. * identifies the session
  89. * @param {string} localJid our JID
  90. * @param {string} remoteJid remote peer JID
  91. * @param {XmppConnection} connection - The XMPP connection instance.
  92. * @param mediaConstraints the media constraints object passed to
  93. * createOffer/Answer, as defined by the WebRTC standard
  94. * @param iceConfig the ICE servers config object as defined by the WebRTC
  95. * standard.
  96. * @param {boolean} isP2P indicates whether this instance is
  97. * meant to be used in a direct, peer to peer connection or <tt>false</tt>
  98. * if it's a JVB connection.
  99. * @param {boolean} isInitiator indicates if it will be the side which
  100. * initiates the session.
  101. * @constructor
  102. *
  103. * @implements {SignalingLayer}
  104. */
  105. constructor(
  106. sid,
  107. localJid,
  108. remoteJid,
  109. connection,
  110. mediaConstraints,
  111. iceConfig,
  112. isP2P,
  113. isInitiator) {
  114. super(
  115. sid,
  116. localJid,
  117. remoteJid, connection, mediaConstraints, iceConfig, isInitiator);
  118. /**
  119. * The bridge session's identifier. One Jingle session can during
  120. * it's lifetime participate in multiple bridge sessions managed by
  121. * Jicofo. A new bridge session is started whenever Jicofo sends
  122. * 'session-initiate' or 'transport-replace'.
  123. *
  124. * @type {?string}
  125. * @private
  126. */
  127. this._bridgeSessionId = null;
  128. /**
  129. * The oldest SDP passed to {@link notifyMySSRCUpdate} while the XMPP connection was offline that will be
  130. * used to update Jicofo once the XMPP connection goes back online.
  131. * @type {SDP|undefined}
  132. * @private
  133. */
  134. this._cachedOldLocalSdp = undefined;
  135. /**
  136. * The latest SDP passed to {@link notifyMySSRCUpdate} while the XMPP connection was offline that will be
  137. * used to update Jicofo once the XMPP connection goes back online.
  138. * @type {SDP|undefined}
  139. * @private
  140. */
  141. this._cachedNewLocalSdp = undefined;
  142. /**
  143. * Stores result of {@link window.performance.now()} at the time when
  144. * ICE enters 'checking' state.
  145. * @type {number|null} null if no value has been stored yet
  146. * @private
  147. */
  148. this._iceCheckingStartedTimestamp = null;
  149. /**
  150. * Stores result of {@link window.performance.now()} at the time when
  151. * first ICE candidate is spawned by the peerconnection to mark when
  152. * ICE gathering started. That's, because ICE gathering state changed
  153. * events are not supported by most of the browsers, so we try something
  154. * that will work everywhere. It may not be as accurate, but given that
  155. * 'host' candidate usually comes first, the delay should be minimal.
  156. * @type {number|null} null if no value has been stored yet
  157. * @private
  158. */
  159. this._gatheringStartedTimestamp = null;
  160. /**
  161. * Indicates whether or not this session is willing to send/receive
  162. * video media. When set to <tt>false</tt> the underlying peer
  163. * connection will disable local video transfer and the remote peer will
  164. * be will be asked to stop sending video via 'content-modify' IQ
  165. * (the senders attribute of video contents will be adjusted
  166. * accordingly). Note that this notification is sent only in P2P
  167. * session, because Jicofo does not support it yet. Obviously when
  168. * the value is changed from <tt>false</tt> to <tt>true</tt> another
  169. * notification will be sent to resume video transfer on the remote
  170. * side.
  171. * @type {boolean}
  172. * @private
  173. */
  174. this._localVideoActive = true;
  175. /**
  176. * Indicates whether or not the remote peer has video transfer active.
  177. * When set to <tt>true</tt> it means that remote peer is neither
  178. * sending nor willing to receive video. In such case we'll ask
  179. * our peerconnection to stop sending video by calling
  180. * {@link TraceablePeerConnection.setVideoTransferActive} with
  181. * <tt>false</tt>.
  182. * @type {boolean}
  183. * @private
  184. */
  185. this._remoteVideoActive = true;
  186. /**
  187. * Marks that ICE gathering duration has been reported already. That
  188. * prevents reporting it again, after eventual 'transport-replace' (JVB
  189. * conference migration/ICE restart).
  190. * @type {boolean}
  191. * @private
  192. */
  193. this._gatheringReported = false;
  194. this.lasticecandidate = false;
  195. this.closed = false;
  196. /**
  197. * Indicates whether or not this <tt>JingleSessionPC</tt> is used in
  198. * a peer to peer type of session.
  199. * @type {boolean} <tt>true</tt> if it's a peer to peer
  200. * session or <tt>false</tt> if it's a JVB session
  201. */
  202. this.isP2P = isP2P;
  203. /**
  204. * The signaling layer implementation.
  205. * @type {SignalingLayerImpl}
  206. */
  207. this.signalingLayer = new SignalingLayerImpl();
  208. /**
  209. * The queue used to serialize operations done on the peerconnection.
  210. *
  211. * @type {AsyncQueue}
  212. */
  213. this.modificationQueue = new AsyncQueue();
  214. /**
  215. * Flag used to guarantee that the connection established event is
  216. * triggered just once.
  217. * @type {boolean}
  218. */
  219. this.wasConnected = false;
  220. /**
  221. * Keeps track of how long (in ms) it took from ICE start to ICE
  222. * connect.
  223. *
  224. * @type {number}
  225. */
  226. this.establishmentDuration = undefined;
  227. this._xmppListeners = [];
  228. this._xmppListeners.push(
  229. connection.addEventListener(
  230. XmppConnection.Events.CONN_STATUS_CHANGED,
  231. this.onXmppStatusChanged.bind(this))
  232. );
  233. }
  234. /* eslint-enable max-params */
  235. /**
  236. * Checks whether or not this session instance is still operational.
  237. * @private
  238. * @returns {boolean} {@code true} if operation or {@code false} otherwise.
  239. */
  240. _assertNotEnded() {
  241. return this.state !== JingleSessionState.ENDED;
  242. }
  243. /**
  244. * @inheritDoc
  245. * @param {JingleSessionPCOptions} options - a set of config options.
  246. */
  247. doInitialize(options) {
  248. this.failICE = Boolean(options.failICE);
  249. this.lasticecandidate = false;
  250. this.options = options;
  251. /**
  252. * {@code true} if reconnect is in progress.
  253. * @type {boolean}
  254. */
  255. this.isReconnect = false;
  256. /**
  257. * Set to {@code true} if the connection was ever stable
  258. * @type {boolean}
  259. */
  260. this.wasstable = false;
  261. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  262. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  263. const pcOptions = { disableRtx: options.disableRtx };
  264. if (options.gatherStats) {
  265. pcOptions.maxstats = DEFAULT_MAX_STATS;
  266. }
  267. pcOptions.capScreenshareBitrate = false;
  268. if (this.isP2P) {
  269. // simulcast needs to be disabled for P2P (121) calls
  270. pcOptions.disableSimulcast = true;
  271. pcOptions.disableH264 = options.p2p && options.p2p.disableH264;
  272. pcOptions.preferH264 = options.p2p && options.p2p.preferH264;
  273. const abtestSuspendVideo = this._abtestSuspendVideoEnabled(options);
  274. if (typeof abtestSuspendVideo !== 'undefined') {
  275. pcOptions.abtestSuspendVideo = abtestSuspendVideo;
  276. }
  277. } else {
  278. // H264 does not support simulcast, so it needs to be disabled.
  279. pcOptions.disableSimulcast
  280. = options.disableSimulcast
  281. || (options.preferH264 && !options.disableH264);
  282. pcOptions.preferH264 = options.preferH264;
  283. pcOptions.enableFirefoxSimulcast
  284. = options.testing && options.testing.enableFirefoxSimulcast;
  285. pcOptions.enableLayerSuspension = options.enableLayerSuspension;
  286. // disable simulcast for screenshare and set the max bitrate to
  287. // 500Kbps if the testing flag is present in config.js.
  288. if (options.testing
  289. && options.testing.capScreenshareBitrate
  290. && typeof options.testing.capScreenshareBitrate === 'number') {
  291. pcOptions.capScreenshareBitrate
  292. = Math.random()
  293. < options.testing.capScreenshareBitrate;
  294. // add the capScreenshareBitrate to the permanent properties so
  295. // that it's included with every event that we send to the
  296. // analytics backend.
  297. Statistics.analytics.addPermanentProperties({ capScreenshareBitrate: pcOptions.capScreenshareBitrate });
  298. }
  299. }
  300. if (options.startSilent) {
  301. pcOptions.startSilent = true;
  302. }
  303. this.peerconnection
  304. = this.rtc.createPeerConnection(
  305. this.signalingLayer,
  306. this.iceConfig,
  307. this.isP2P,
  308. pcOptions);
  309. this.peerconnection.onicecandidate = ev => {
  310. if (!ev) {
  311. // There was an incomplete check for ev before which left
  312. // the last line of the function unprotected from a potential
  313. // throw of an exception. Consequently, it may be argued that
  314. // the check is unnecessary. Anyway, I'm leaving it and making
  315. // the check complete.
  316. return;
  317. }
  318. // XXX this is broken, candidate is not parsed.
  319. const candidate = ev.candidate;
  320. const now = window.performance.now();
  321. if (candidate) {
  322. if (this._gatheringStartedTimestamp === null) {
  323. this._gatheringStartedTimestamp = now;
  324. }
  325. // Discard candidates of disabled protocols.
  326. let protocol = candidate.protocol;
  327. if (typeof protocol === 'string') {
  328. protocol = protocol.toLowerCase();
  329. if (protocol === 'tcp' || protocol === 'ssltcp') {
  330. if (this.webrtcIceTcpDisable) {
  331. return;
  332. }
  333. } else if (protocol === 'udp') {
  334. if (this.webrtcIceUdpDisable) {
  335. return;
  336. }
  337. }
  338. }
  339. } else if (!this._gatheringReported) {
  340. // End of gathering
  341. Statistics.sendAnalytics(
  342. ICE_DURATION,
  343. {
  344. phase: 'gathering',
  345. value: now - this._gatheringStartedTimestamp,
  346. p2p: this.isP2P,
  347. initiator: this.isInitiator
  348. });
  349. this._gatheringReported = true;
  350. }
  351. this.sendIceCandidate(candidate);
  352. };
  353. // Note there is a change in the spec about closed:
  354. // This value moved into the RTCPeerConnectionState enum in
  355. // the May 13, 2016 draft of the specification, as it reflects the state
  356. // of the RTCPeerConnection, not the signaling connection. You now
  357. // detect a closed connection by checking for connectionState to be
  358. // "closed" instead.
  359. // I suppose at some point this will be moved to onconnectionstatechange
  360. this.peerconnection.onsignalingstatechange = () => {
  361. if (this.peerconnection.signalingState === 'stable') {
  362. this.wasstable = true;
  363. } else if (this.peerconnection.signalingState === 'closed'
  364. || this.peerconnection.connectionState === 'closed') {
  365. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
  366. }
  367. };
  368. /**
  369. * The oniceconnectionstatechange event handler contains the code to
  370. * execute when the iceconnectionstatechange event, of type Event,
  371. * is received by this RTCPeerConnection. Such an event is sent when
  372. * the value of RTCPeerConnection.iceConnectionState changes.
  373. */
  374. this.peerconnection.oniceconnectionstatechange = () => {
  375. const now = window.performance.now();
  376. if (!this.isP2P) {
  377. this.room.connectionTimes[
  378. `ice.state.${this.peerconnection.iceConnectionState}`]
  379. = now;
  380. }
  381. logger.log(
  382. `(TIME) ICE ${this.peerconnection.iceConnectionState}`
  383. + ` P2P? ${this.isP2P}:\t`,
  384. now);
  385. Statistics.sendAnalytics(
  386. ICE_STATE_CHANGED,
  387. {
  388. p2p: this.isP2P,
  389. state: this.peerconnection.iceConnectionState,
  390. 'signaling_state': this.peerconnection.signalingState,
  391. reconnect: this.isReconnect,
  392. value: now
  393. });
  394. this.room.eventEmitter.emit(
  395. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  396. this,
  397. this.peerconnection.iceConnectionState);
  398. switch (this.peerconnection.iceConnectionState) {
  399. case 'checking':
  400. this._iceCheckingStartedTimestamp = now;
  401. break;
  402. case 'connected':
  403. // Informs interested parties that the connection has been
  404. // restored.
  405. if (this.peerconnection.signalingState === 'stable') {
  406. if (this.isReconnect) {
  407. this.room.eventEmitter.emit(
  408. XMPPEvents.CONNECTION_RESTORED, this);
  409. }
  410. }
  411. if (!this.wasConnected && this.wasstable) {
  412. Statistics.sendAnalytics(
  413. ICE_DURATION,
  414. {
  415. phase: 'checking',
  416. value: now - this._iceCheckingStartedTimestamp,
  417. p2p: this.isP2P,
  418. initiator: this.isInitiator
  419. });
  420. // Switch between ICE gathering and ICE checking whichever
  421. // started first (scenarios are different for initiator
  422. // vs responder)
  423. const iceStarted
  424. = Math.min(
  425. this._iceCheckingStartedTimestamp,
  426. this._gatheringStartedTimestamp);
  427. this.establishmentDuration = now - iceStarted;
  428. Statistics.sendAnalytics(
  429. ICE_DURATION,
  430. {
  431. phase: 'establishment',
  432. value: this.establishmentDuration,
  433. p2p: this.isP2P,
  434. initiator: this.isInitiator
  435. });
  436. this.wasConnected = true;
  437. this.room.eventEmitter.emit(
  438. XMPPEvents.CONNECTION_ESTABLISHED, this);
  439. }
  440. this.isReconnect = false;
  441. break;
  442. case 'disconnected':
  443. this.isReconnect = true;
  444. // Informs interested parties that the connection has been
  445. // interrupted.
  446. if (this.wasstable) {
  447. this.room.eventEmitter.emit(
  448. XMPPEvents.CONNECTION_INTERRUPTED, this);
  449. }
  450. break;
  451. case 'failed':
  452. this.room.eventEmitter.emit(
  453. XMPPEvents.CONNECTION_ICE_FAILED, this);
  454. break;
  455. }
  456. };
  457. /**
  458. * The negotiationneeded event is fired whenever we shake the media on the
  459. * RTCPeerConnection object.
  460. */
  461. this.peerconnection.onnegotiationneeded = () => {
  462. const state = this.peerconnection.signalingState;
  463. const remoteDescription = this.peerconnection.remoteDescription;
  464. this.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, this);
  465. if (browser.usesUnifiedPlan() && state === 'stable'
  466. && remoteDescription && typeof remoteDescription.sdp === 'string') {
  467. logger.debug(`onnegotiationneeded fired on ${this.peerconnection} in state: ${state}`);
  468. const workFunction = finishedCallback => {
  469. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  470. this._renegotiate()
  471. .then(() => {
  472. const newSdp = new SDP(this.peerconnection.localDescription.sdp);
  473. this.notifyMySSRCUpdate(oldSdp, newSdp);
  474. finishedCallback();
  475. },
  476. finishedCallback /* will be called with en error */);
  477. };
  478. this.modificationQueue.push(
  479. workFunction,
  480. error => {
  481. if (error) {
  482. logger.error('onnegotiationneeded error', error);
  483. } else {
  484. logger.debug('onnegotiationneeded executed - OK');
  485. }
  486. });
  487. }
  488. };
  489. // The signaling layer will bind it's listeners at this point
  490. this.signalingLayer.setChatRoom(this.room);
  491. if (!this.isP2P && options.enableLayerSuspension) {
  492. // If this is the bridge session, we'll listen for
  493. // IS_SELECTED_CHANGED events and notify the peer connection
  494. this.rtc.addListener(RTCEvents.IS_SELECTED_CHANGED,
  495. isSelected => {
  496. this.peerconnection.setIsSelected(isSelected);
  497. logger.info('Doing local O/A due to '
  498. + 'IS_SELECTED_CHANGED event');
  499. this.modificationQueue.push(finishedCallback => {
  500. this._renegotiate()
  501. .then(finishedCallback)
  502. .catch(finishedCallback);
  503. });
  504. }
  505. );
  506. }
  507. }
  508. /**
  509. * Sends given candidate in Jingle 'transport-info' message.
  510. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  511. * @private
  512. */
  513. sendIceCandidate(candidate) {
  514. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  515. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  516. const ice
  517. = SDPUtil.iceparams(
  518. localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  519. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  520. if (!(ice && jcand)) {
  521. const errorMesssage = 'failed to get ice && jcand';
  522. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  523. logger.error(errorMesssage);
  524. return;
  525. }
  526. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  527. if (this.usedrip) {
  528. if (this.dripContainer.length === 0) {
  529. // start 20ms callout
  530. setTimeout(() => {
  531. if (this.dripContainer.length === 0) {
  532. return;
  533. }
  534. this.sendIceCandidates(this.dripContainer);
  535. this.dripContainer = [];
  536. }, 20);
  537. }
  538. this.dripContainer.push(candidate);
  539. } else {
  540. this.sendIceCandidates([ candidate ]);
  541. }
  542. } else {
  543. logger.log('sendIceCandidate: last candidate.');
  544. // FIXME: remember to re-think in ICE-restart
  545. this.lasticecandidate = true;
  546. }
  547. }
  548. /**
  549. * Sends given candidates in Jingle 'transport-info' message.
  550. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE
  551. * candidate instances
  552. * @private
  553. */
  554. sendIceCandidates(candidates) {
  555. if (!this._assertNotEnded('sendIceCandidates')) {
  556. return;
  557. }
  558. logger.log('sendIceCandidates', candidates);
  559. const cand = $iq({ to: this.remoteJid,
  560. type: 'set' })
  561. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  562. action: 'transport-info',
  563. initiator: this.initiatorJid,
  564. sid: this.sid });
  565. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  566. for (let mid = 0; mid < localSDP.media.length; mid++) {
  567. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  568. const mline
  569. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  570. if (cands.length > 0) {
  571. const ice
  572. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  573. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  574. cand.c('content', {
  575. creator: this.initiatorJid === this.localJid
  576. ? 'initiator' : 'responder',
  577. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  578. }).c('transport', ice);
  579. for (let i = 0; i < cands.length; i++) {
  580. const candidate
  581. = SDPUtil.candidateToJingle(cands[i].candidate);
  582. // Mangle ICE candidate if 'failICE' test option is enabled
  583. if (this.failICE) {
  584. candidate.ip = '1.1.1.1';
  585. }
  586. cand.c('candidate', candidate).up();
  587. }
  588. // add fingerprint
  589. const fingerprintLine
  590. = SDPUtil.findLine(
  591. localSDP.media[mid],
  592. 'a=fingerprint:', localSDP.session);
  593. if (fingerprintLine) {
  594. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  595. tmp.required = true;
  596. cand.c(
  597. 'fingerprint',
  598. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  599. .t(tmp.fingerprint);
  600. delete tmp.fingerprint;
  601. cand.attrs(tmp);
  602. cand.up();
  603. }
  604. cand.up(); // transport
  605. cand.up(); // content
  606. }
  607. }
  608. // might merge last-candidate notification into this, but it is called
  609. // a lot later. See webrtc issue #2340
  610. // logger.log('was this the last candidate', this.lasticecandidate);
  611. this.connection.sendIQ(
  612. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  613. }
  614. /**
  615. * Sends Jingle 'session-info' message which includes custom Jitsi Meet
  616. * 'ice-state' element with the text value 'failed' to let Jicofo know
  617. * that the ICE connection has entered the failed state. It can then
  618. * choose to re-create JVB channels and send 'transport-replace' to
  619. * retry the connection.
  620. */
  621. sendIceFailedNotification() {
  622. const sessionInfo
  623. = $iq({
  624. to: this.remoteJid,
  625. type: 'set' })
  626. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  627. action: 'session-info',
  628. initiator: this.initiatorJid,
  629. sid: this.sid })
  630. .c('ice-state', { xmlns: 'http://jitsi.org/protocol/focus' })
  631. .t('failed')
  632. .up();
  633. this._bridgeSessionId
  634. && sessionInfo.c(
  635. 'bridge-session', {
  636. xmlns: 'http://jitsi.org/protocol/focus',
  637. id: this._bridgeSessionId
  638. });
  639. this.connection.sendIQ(
  640. sessionInfo,
  641. null,
  642. this.newJingleErrorHandler(sessionInfo),
  643. /*
  644. * This message will be often sent when there are connectivity
  645. * issues, so make it slightly longer than Prosody's default BOSH
  646. * inactivity timeout of 60 seconds.
  647. */ 65);
  648. }
  649. /**
  650. * {@inheritDoc}
  651. */
  652. addIceCandidates(elem) {
  653. if (this.peerconnection.signalingState === 'closed') {
  654. logger.warn('Ignored add ICE candidate when in closed state');
  655. return;
  656. }
  657. const iceCandidates = [];
  658. elem.find('>content>transport>candidate')
  659. .each((idx, candidate) => {
  660. let line = SDPUtil.candidateFromJingle(candidate);
  661. line = line.replace('\r\n', '').replace('a=', '');
  662. // FIXME this code does not care to handle
  663. // non-bundle transport
  664. const rtcCandidate = new RTCIceCandidate({
  665. sdpMLineIndex: 0,
  666. // FF comes up with more complex names like audio-23423,
  667. // Given that it works on both Chrome and FF without
  668. // providing it, let's leave it like this for the time
  669. // being...
  670. // sdpMid: 'audio',
  671. sdpMid: '',
  672. candidate: line
  673. });
  674. iceCandidates.push(rtcCandidate);
  675. });
  676. if (!iceCandidates.length) {
  677. logger.error(
  678. 'No ICE candidates to add ?', elem[0] && elem[0].outerHTML);
  679. return;
  680. }
  681. // We want to have this task queued, so that we know it is executed,
  682. // after the initial sRD/sLD offer/answer cycle was done (based on
  683. // the assumption that candidates are spawned after the offer/answer
  684. // and XMPP preserves order).
  685. const workFunction = finishedCallback => {
  686. for (const iceCandidate of iceCandidates) {
  687. this.peerconnection.addIceCandidate(iceCandidate)
  688. .then(
  689. () => logger.debug('addIceCandidate ok!'),
  690. err => logger.error('addIceCandidate failed!', err));
  691. }
  692. finishedCallback();
  693. };
  694. logger.debug(
  695. `Queued add (${iceCandidates.length}) ICE candidates task...`);
  696. this.modificationQueue.push(workFunction);
  697. }
  698. /**
  699. *
  700. * @param contents
  701. */
  702. readSsrcInfo(contents) {
  703. const ssrcs
  704. = $(contents).find(
  705. '>description>'
  706. + 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  707. ssrcs.each((i, ssrcElement) => {
  708. const ssrc = Number(ssrcElement.getAttribute('ssrc'));
  709. if (this.isP2P) {
  710. // In P2P all SSRCs are owner by the remote peer
  711. this.signalingLayer.setSSRCOwner(
  712. ssrc, Strophe.getResourceFromJid(this.remoteJid));
  713. } else {
  714. $(ssrcElement)
  715. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  716. .each((i3, ssrcInfoElement) => {
  717. const owner = ssrcInfoElement.getAttribute('owner');
  718. if (owner && owner.length) {
  719. if (isNaN(ssrc) || ssrc < 0) {
  720. logger.warn(
  721. `Invalid SSRC ${ssrc} value received`
  722. + ` for ${owner}`);
  723. } else {
  724. this.signalingLayer.setSSRCOwner(
  725. ssrc,
  726. Strophe.getResourceFromJid(owner));
  727. }
  728. }
  729. });
  730. }
  731. });
  732. }
  733. /**
  734. * Makes the underlying TraceablePeerConnection generate new SSRC for
  735. * the recvonly video stream.
  736. * @deprecated
  737. */
  738. generateRecvonlySsrc() {
  739. if (this.peerconnection) {
  740. this.peerconnection.generateRecvonlySsrc();
  741. } else {
  742. logger.error(
  743. 'Unable to generate recvonly SSRC - no peerconnection');
  744. }
  745. }
  746. /* eslint-disable max-params */
  747. /**
  748. * Accepts incoming Jingle 'session-initiate' and should send
  749. * 'session-accept' in result.
  750. * @param jingleOffer jQuery selector pointing to the jingle element of
  751. * the offer IQ
  752. * @param success callback called when we accept incoming session
  753. * successfully and receive RESULT packet to 'session-accept' sent.
  754. * @param failure function(error) called if for any reason we fail to accept
  755. * the incoming offer. 'error' argument can be used to log some details
  756. * about the error.
  757. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
  758. * the local tracks that will be added, before the offer/answer cycle
  759. * executes. We allow the localTracks to optionally be passed in so that
  760. * the addition of the local tracks and the processing of the initial offer
  761. * can all be done atomically. We want to make sure that any other
  762. * operations which originate in the XMPP Jingle messages related with
  763. * this session to be executed with an assumption that the initial
  764. * offer/answer cycle has been executed already.
  765. */
  766. acceptOffer(jingleOffer, success, failure, localTracks) {
  767. this.setOfferAnswerCycle(
  768. jingleOffer,
  769. () => {
  770. // FIXME we may not care about RESULT packet for session-accept
  771. // then we should either call 'success' here immediately or
  772. // modify sendSessionAccept method to do that
  773. this.sendSessionAccept(success, failure);
  774. },
  775. failure,
  776. localTracks);
  777. }
  778. /* eslint-enable max-params */
  779. /**
  780. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  781. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be
  782. * added, before the offer/answer cycle executes (for the local track
  783. * addition to be an atomic operation together with the offer/answer).
  784. */
  785. invite(localTracks) {
  786. if (!this.isInitiator) {
  787. throw new Error('Trying to invite from the responder session');
  788. }
  789. const workFunction = finishedCallback => {
  790. for (const localTrack of localTracks) {
  791. this.peerconnection.addTrack(localTrack, true /* isInitiator */);
  792. }
  793. this.peerconnection.createOffer(this.mediaConstraints)
  794. .then(offerSdp => {
  795. this.peerconnection.setLocalDescription(offerSdp)
  796. .then(() => {
  797. // NOTE that the offer is obtained from
  798. // the localDescription getter as it needs to go
  799. // though the transformation chain.
  800. this.sendSessionInitiate(
  801. this.peerconnection.localDescription.sdp);
  802. finishedCallback();
  803. }, error => {
  804. logger.error(
  805. 'Failed to set local SDP', error, offerSdp);
  806. finishedCallback(error);
  807. });
  808. }, error => {
  809. logger.error(
  810. 'Failed to create an offer',
  811. error,
  812. this.mediaConstraints);
  813. finishedCallback(error);
  814. });
  815. };
  816. this.modificationQueue.push(
  817. workFunction,
  818. error => {
  819. if (error) {
  820. logger.error('invite error', error);
  821. } else {
  822. logger.debug('invite executed - OK');
  823. }
  824. });
  825. }
  826. /**
  827. * Sends 'session-initiate' to the remote peer.
  828. *
  829. * NOTE this method is synchronous and we're not waiting for the RESULT
  830. * response which would delay the startup process.
  831. *
  832. * @param {string} offerSdp - The local session description which will be
  833. * used to generate an offer.
  834. * @private
  835. */
  836. sendSessionInitiate(offerSdp) {
  837. let init = $iq({
  838. to: this.remoteJid,
  839. type: 'set'
  840. }).c('jingle', {
  841. xmlns: 'urn:xmpp:jingle:1',
  842. action: 'session-initiate',
  843. initiator: this.initiatorJid,
  844. sid: this.sid
  845. });
  846. new SDP(offerSdp).toJingle(
  847. init,
  848. this.isInitiator ? 'initiator' : 'responder');
  849. init = init.tree();
  850. logger.info('Session-initiate: ', init);
  851. this.connection.sendIQ(init,
  852. () => {
  853. logger.info('Got RESULT for "session-initiate"');
  854. },
  855. error => {
  856. logger.error('"session-initiate" error', error);
  857. },
  858. IQ_TIMEOUT);
  859. }
  860. /**
  861. * Sets the answer received from the remote peer.
  862. * @param jingleAnswer
  863. */
  864. setAnswer(jingleAnswer) {
  865. if (!this.isInitiator) {
  866. throw new Error('Trying to set an answer on the responder session');
  867. }
  868. this.setOfferAnswerCycle(
  869. jingleAnswer,
  870. () => {
  871. logger.info('setAnswer - succeeded');
  872. },
  873. error => {
  874. logger.error('setAnswer failed: ', error);
  875. });
  876. }
  877. /* eslint-disable max-params */
  878. /**
  879. * This is a setRemoteDescription/setLocalDescription cycle which starts at
  880. * converting Strophe Jingle IQ into remote offer SDP. Once converted
  881. * setRemoteDescription, createAnswer and setLocalDescription calls follow.
  882. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element
  883. * of the offer (or answer) IQ
  884. * @param success callback called when sRD/sLD cycle finishes successfully.
  885. * @param failure callback called with an error object as an argument if we
  886. * fail at any point during setRD, createAnswer, setLD.
  887. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
  888. * the local tracks that will be added, before the offer/answer cycle
  889. * executes (for the local track addition to be an atomic operation together
  890. * with the offer/answer).
  891. */
  892. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks) {
  893. const workFunction = finishedCallback => {
  894. if (localTracks) {
  895. for (const track of localTracks) {
  896. this.peerconnection.addTrack(track);
  897. }
  898. }
  899. const newRemoteSdp
  900. = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  901. const oldLocalSdp
  902. = this.peerconnection.localDescription.sdp;
  903. const bridgeSession
  904. = $(jingleOfferAnswerIq)
  905. .find('>bridge-session['
  906. + 'xmlns="http://jitsi.org/protocol/focus"]');
  907. const bridgeSessionId = bridgeSession.attr('id');
  908. if (bridgeSessionId !== this._bridgeSessionId) {
  909. this._bridgeSessionId = bridgeSessionId;
  910. }
  911. this._renegotiate(newRemoteSdp.raw)
  912. .then(() => {
  913. if (this.state === JingleSessionState.PENDING) {
  914. this.state = JingleSessionState.ACTIVE;
  915. // Sync up video transfer active/inactive only after
  916. // the initial O/A cycle. We want to adjust the video
  917. // media direction only in the local SDP and the Jingle
  918. // contents direction included in the initial
  919. // offer/answer is mapped to the remote SDP. Jingle
  920. // 'content-modify' IQ is processed in a way that it
  921. // will only modify local SDP when remote peer is no
  922. // longer interested in receiving video content.
  923. // Changing media direction in the remote SDP will mess
  924. // up our SDP translation chain (simulcast, video mute,
  925. // RTX etc.)
  926. if (this.isP2P && !this._localVideoActive) {
  927. this.sendContentModify(this._localVideoActive);
  928. }
  929. }
  930. // Old local SDP will be available when we're setting answer
  931. // for the first time, but not when offer and it's fine
  932. // since we're generating an answer now it will contain all
  933. // our SSRCs
  934. if (oldLocalSdp) {
  935. const newLocalSdp
  936. = new SDP(this.peerconnection.localDescription.sdp);
  937. this.notifyMySSRCUpdate(
  938. new SDP(oldLocalSdp), newLocalSdp);
  939. }
  940. finishedCallback();
  941. }, error => {
  942. logger.error(
  943. `Error renegotiating after setting new remote ${
  944. this.isInitiator ? 'answer: ' : 'offer: '}${error}`,
  945. newRemoteSdp);
  946. finishedCallback(error);
  947. });
  948. };
  949. this.modificationQueue.push(
  950. workFunction,
  951. error => {
  952. error ? failure(error) : success();
  953. });
  954. }
  955. /* eslint-enable max-params */
  956. /**
  957. * Although it states "replace transport" it does accept full Jingle offer
  958. * which should contain new ICE transport details.
  959. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  960. * transport info.
  961. * @param success callback called when we succeed to accept new offer.
  962. * @param failure function(error) called when we fail to accept new offer.
  963. */
  964. replaceTransport(jingleOfferElem, success, failure) {
  965. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  966. // We need to first reject the 'data' section to have the SCTP stack
  967. // cleaned up to signal the known data channel is now invalid. After
  968. // that the original offer is set to have the SCTP connection
  969. // established with the new bridge.
  970. const originalOffer = jingleOfferElem.clone();
  971. jingleOfferElem
  972. .find('>content[name=\'data\']')
  973. .attr('senders', 'rejected');
  974. // Remove all remote sources in order to reset the client's state
  975. // for the remote MediaStreams. When a conference is moved to
  976. // another bridge it will start streaming with a sequence number
  977. // that is not in sync with the most recently seen by the client.
  978. // The symptoms include frozen or black video and lots of "failed to
  979. // unprotect SRTP packets" in Chrome logs.
  980. jingleOfferElem
  981. .find('>content>description>source')
  982. .remove();
  983. jingleOfferElem
  984. .find('>content>description>ssrc-group')
  985. .remove();
  986. // On the JVB it's not a real ICE restart and all layers are re-initialized from scratch as Jicofo does
  987. // the restart by re-allocating new channels. Chrome (or WebRTC stack) needs to have the DTLS transport layer
  988. // reset to start a new handshake with fresh DTLS transport on the bridge. Make it think that the DTLS
  989. // fingerprint has changed by setting an all zeros key.
  990. const newFingerprint = jingleOfferElem.find('>content>transport>fingerprint');
  991. newFingerprint.attr('hash', 'sha-1');
  992. newFingerprint.text('00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00');
  993. // First set an offer with a rejected 'data' section
  994. this.setOfferAnswerCycle(
  995. jingleOfferElem,
  996. () => {
  997. // Now set the original offer(with the 'data' section)
  998. this.setOfferAnswerCycle(
  999. originalOffer,
  1000. () => {
  1001. const localSDP
  1002. = new SDP(this.peerconnection.localDescription.sdp);
  1003. this.sendTransportAccept(localSDP, success, failure);
  1004. this.room.eventEmitter.emit(
  1005. XMPPEvents.ICE_RESTART_SUCCESS,
  1006. this,
  1007. originalOffer);
  1008. },
  1009. failure);
  1010. },
  1011. failure
  1012. );
  1013. }
  1014. /**
  1015. * Sends Jingle 'session-accept' message.
  1016. * @param {function()} success callback called when we receive 'RESULT'
  1017. * packet for the 'session-accept'
  1018. * @param {function(error)} failure called when we receive an error response
  1019. * or when the request has timed out.
  1020. * @private
  1021. */
  1022. sendSessionAccept(success, failure) {
  1023. // NOTE: since we're just reading from it, we don't need to be within
  1024. // the modification queue to access the local description
  1025. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1026. let accept = $iq({ to: this.remoteJid,
  1027. type: 'set' })
  1028. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1029. action: 'session-accept',
  1030. initiator: this.initiatorJid,
  1031. responder: this.responderJid,
  1032. sid: this.sid });
  1033. if (this.webrtcIceTcpDisable) {
  1034. localSDP.removeTcpCandidates = true;
  1035. }
  1036. if (this.webrtcIceUdpDisable) {
  1037. localSDP.removeUdpCandidates = true;
  1038. }
  1039. if (this.failICE) {
  1040. localSDP.failICE = true;
  1041. }
  1042. localSDP.toJingle(
  1043. accept,
  1044. this.initiatorJid === this.localJid ? 'initiator' : 'responder',
  1045. null);
  1046. // Calling tree() to print something useful
  1047. accept = accept.tree();
  1048. logger.info('Sending session-accept', accept);
  1049. this.connection.sendIQ(accept,
  1050. success,
  1051. this.newJingleErrorHandler(accept, error => {
  1052. failure(error);
  1053. // 'session-accept' is a critical timeout and we'll
  1054. // have to restart
  1055. this.room.eventEmitter.emit(
  1056. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1057. }),
  1058. IQ_TIMEOUT);
  1059. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1060. // fingerprint and setup) ASAP in order to start the connection
  1061. // establishment.
  1062. //
  1063. // FIXME Flushing the connection at this point triggers an issue with
  1064. // BOSH request handling in Prosody on slow connections.
  1065. //
  1066. // The problem is that this request will be quite large and it may take
  1067. // time before it reaches Prosody. In the meantime Strophe may decide
  1068. // to send the next one. And it was observed that a small request with
  1069. // 'transport-info' usually follows this one. It does reach Prosody
  1070. // before the previous one was completely received. 'rid' on the server
  1071. // is increased and Prosody ignores the request with 'session-accept'.
  1072. // It will never reach Jicofo and everything in the request table is
  1073. // lost. Removing the flush does not guarantee it will never happen, but
  1074. // makes it much less likely('transport-info' is bundled with
  1075. // 'session-accept' and any immediate requests).
  1076. //
  1077. // this.connection.flush();
  1078. }
  1079. /**
  1080. * Will send 'content-modify' IQ in order to ask the remote peer to
  1081. * either stop or resume sending video media.
  1082. * @param {boolean} videoTransferActive <tt>false</tt> to let the other peer
  1083. * know that we're not sending nor interested in receiving video contents.
  1084. * When set to <tt>true</tt> remote peer will be asked to resume video
  1085. * transfer.
  1086. * @private
  1087. */
  1088. sendContentModify(videoTransferActive) {
  1089. const newSendersValue = videoTransferActive ? 'both' : 'none';
  1090. const sessionModify
  1091. = $iq({
  1092. to: this.remoteJid,
  1093. type: 'set'
  1094. })
  1095. .c('jingle', {
  1096. xmlns: 'urn:xmpp:jingle:1',
  1097. action: 'content-modify',
  1098. initiator: this.initiatorJid,
  1099. sid: this.sid
  1100. })
  1101. .c('content', {
  1102. name: 'video',
  1103. senders: newSendersValue
  1104. });
  1105. logger.info(
  1106. `Sending content-modify, video senders: ${newSendersValue}`);
  1107. this.connection.sendIQ(
  1108. sessionModify,
  1109. null,
  1110. this.newJingleErrorHandler(sessionModify),
  1111. IQ_TIMEOUT);
  1112. }
  1113. /**
  1114. * Sends Jingle 'transport-accept' message which is a response to
  1115. * 'transport-replace'.
  1116. * @param localSDP the 'SDP' object with local session description
  1117. * @param success callback called when we receive 'RESULT' packet for
  1118. * 'transport-replace'
  1119. * @param failure function(error) called when we receive an error response
  1120. * or when the request has timed out.
  1121. * @private
  1122. */
  1123. sendTransportAccept(localSDP, success, failure) {
  1124. let transportAccept = $iq({ to: this.remoteJid,
  1125. type: 'set' })
  1126. .c('jingle', {
  1127. xmlns: 'urn:xmpp:jingle:1',
  1128. action: 'transport-accept',
  1129. initiator: this.initiatorJid,
  1130. sid: this.sid
  1131. });
  1132. localSDP.media.forEach((medialines, idx) => {
  1133. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1134. transportAccept.c('content',
  1135. {
  1136. creator:
  1137. this.initiatorJid === this.localJid
  1138. ? 'initiator'
  1139. : 'responder',
  1140. name: mline.media
  1141. }
  1142. );
  1143. localSDP.transportToJingle(idx, transportAccept);
  1144. transportAccept.up();
  1145. });
  1146. // Calling tree() to print something useful to the logger
  1147. transportAccept = transportAccept.tree();
  1148. logger.info('Sending transport-accept: ', transportAccept);
  1149. this.connection.sendIQ(transportAccept,
  1150. success,
  1151. this.newJingleErrorHandler(transportAccept, failure),
  1152. IQ_TIMEOUT);
  1153. }
  1154. /**
  1155. * Sends Jingle 'transport-reject' message which is a response to
  1156. * 'transport-replace'.
  1157. * @param success callback called when we receive 'RESULT' packet for
  1158. * 'transport-replace'
  1159. * @param failure function(error) called when we receive an error response
  1160. * or when the request has timed out.
  1161. *
  1162. * FIXME method should be marked as private, but there's some spaghetti that
  1163. * needs to be fixed prior doing that
  1164. */
  1165. sendTransportReject(success, failure) {
  1166. // Send 'transport-reject', so that the focus will
  1167. // know that we've failed
  1168. let transportReject = $iq({ to: this.remoteJid,
  1169. type: 'set' })
  1170. .c('jingle', {
  1171. xmlns: 'urn:xmpp:jingle:1',
  1172. action: 'transport-reject',
  1173. initiator: this.initiatorJid,
  1174. sid: this.sid
  1175. });
  1176. transportReject = transportReject.tree();
  1177. logger.info('Sending \'transport-reject', transportReject);
  1178. this.connection.sendIQ(transportReject,
  1179. success,
  1180. this.newJingleErrorHandler(transportReject, failure),
  1181. IQ_TIMEOUT);
  1182. }
  1183. /**
  1184. * @inheritDoc
  1185. */
  1186. terminate(success, failure, options) {
  1187. if (this.state === JingleSessionState.ENDED) {
  1188. return;
  1189. }
  1190. if (!options || Boolean(options.sendSessionTerminate)) {
  1191. let sessionTerminate
  1192. = $iq({
  1193. to: this.remoteJid,
  1194. type: 'set'
  1195. })
  1196. .c('jingle', {
  1197. xmlns: 'urn:xmpp:jingle:1',
  1198. action: 'session-terminate',
  1199. initiator: this.initiatorJid,
  1200. sid: this.sid
  1201. })
  1202. .c('reason')
  1203. .c((options && options.reason) || 'success');
  1204. if (options && options.reasonDescription) {
  1205. sessionTerminate.up()
  1206. .c('text')
  1207. .t(options.reasonDescription);
  1208. }
  1209. // Calling tree() to print something useful
  1210. sessionTerminate = sessionTerminate.tree();
  1211. logger.info('Sending session-terminate', sessionTerminate);
  1212. this.connection.sendIQ(
  1213. sessionTerminate,
  1214. success,
  1215. this.newJingleErrorHandler(sessionTerminate, failure),
  1216. IQ_TIMEOUT);
  1217. } else {
  1218. logger.info(`Skipped sending session-terminate for ${this}`);
  1219. }
  1220. // this should result in 'onTerminated' being called by strope.jingle.js
  1221. this.connection.jingle.terminate(this.sid);
  1222. }
  1223. /**
  1224. *
  1225. * @param reasonCondition
  1226. * @param reasonText
  1227. */
  1228. onTerminated(reasonCondition, reasonText) {
  1229. // Do something with reason and reasonCondition when we start to care
  1230. // this.reasonCondition = reasonCondition;
  1231. // this.reasonText = reasonText;
  1232. logger.info(`Session terminated ${this}`, reasonCondition, reasonText);
  1233. this._xmppListeners.forEach(removeListener => removeListener());
  1234. this._xmppListeners = [];
  1235. this.close();
  1236. }
  1237. /**
  1238. * Handles XMPP connection state changes.
  1239. *
  1240. * @param {XmppConnection.Status} status - The new status.
  1241. */
  1242. onXmppStatusChanged(status) {
  1243. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1244. logger.info('Sending SSRC update on reconnect');
  1245. this.notifyMySSRCUpdate(
  1246. this._cachedOldLocalSdp,
  1247. this._cachedNewLocalSdp);
  1248. }
  1249. }
  1250. /**
  1251. * Parse the information from the xml sourceAddElem and translate it
  1252. * into sdp lines
  1253. * @param {jquery xml element} sourceAddElem the source-add
  1254. * element from jingle
  1255. * @param {SDP object} currentRemoteSdp the current remote
  1256. * sdp (as of this new source-add)
  1257. * @returns {list} a list of SDP line strings that should
  1258. * be added to the remote SDP
  1259. */
  1260. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1261. const addSsrcInfo = [];
  1262. $(sourceAddElem).each((i1, content) => {
  1263. const name = $(content).attr('name');
  1264. let lines = '';
  1265. $(content)
  1266. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1267. .each(function() {
  1268. // eslint-disable-next-line no-invalid-this
  1269. const semantics = this.getAttribute('semantics');
  1270. const ssrcs
  1271. = $(this) // eslint-disable-line no-invalid-this
  1272. .find('>source')
  1273. .map(function() {
  1274. // eslint-disable-next-line no-invalid-this
  1275. return this.getAttribute('ssrc');
  1276. })
  1277. .get();
  1278. if (ssrcs.length) {
  1279. lines
  1280. += `a=ssrc-group:${semantics} ${
  1281. ssrcs.join(' ')}\r\n`;
  1282. }
  1283. });
  1284. // handles both >source and >description>source
  1285. const tmp
  1286. = $(content).find(
  1287. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1288. /* eslint-disable no-invalid-this */
  1289. tmp.each(function() {
  1290. const ssrc = $(this).attr('ssrc');
  1291. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1292. logger.warn(
  1293. `Source-add request for existing SSRC: ${ssrc}`);
  1294. return;
  1295. }
  1296. // eslint-disable-next-line newline-per-chained-call
  1297. $(this).find('>parameter').each(function() {
  1298. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1299. if ($(this).attr('value') && $(this).attr('value').length) {
  1300. lines += `:${$(this).attr('value')}`;
  1301. }
  1302. lines += '\r\n';
  1303. });
  1304. });
  1305. /* eslint-enable no-invalid-this */
  1306. currentRemoteSdp.media.forEach((media, i2) => {
  1307. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1308. return;
  1309. }
  1310. if (!addSsrcInfo[i2]) {
  1311. addSsrcInfo[i2] = '';
  1312. }
  1313. addSsrcInfo[i2] += lines;
  1314. });
  1315. });
  1316. return addSsrcInfo;
  1317. }
  1318. /**
  1319. * Handles a Jingle source-add message for this Jingle session.
  1320. * @param elem An array of Jingle "content" elements.
  1321. */
  1322. addRemoteStream(elem) {
  1323. this._addOrRemoveRemoteStream(true /* add */, elem);
  1324. }
  1325. /**
  1326. * Handles a Jingle source-remove message for this Jingle session.
  1327. * @param elem An array of Jingle "content" elements.
  1328. */
  1329. removeRemoteStream(elem) {
  1330. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1331. }
  1332. /**
  1333. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1334. * Jingle session.
  1335. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1336. * otherwise.
  1337. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1338. * @private
  1339. */
  1340. _addOrRemoveRemoteStream(isAdd, elem) {
  1341. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1342. if (isAdd) {
  1343. this.readSsrcInfo(elem);
  1344. }
  1345. const workFunction = finishedCallback => {
  1346. if (!this.peerconnection.localDescription
  1347. || !this.peerconnection.localDescription.sdp) {
  1348. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1349. logger.error(errMsg);
  1350. finishedCallback(errMsg);
  1351. return;
  1352. }
  1353. logger.log(`Processing ${logPrefix}`);
  1354. logger.log(
  1355. 'ICE connection state: ',
  1356. this.peerconnection.iceConnectionState);
  1357. const oldLocalSdp
  1358. = new SDP(this.peerconnection.localDescription.sdp);
  1359. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1360. const addOrRemoveSsrcInfo
  1361. = isAdd
  1362. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1363. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1364. const newRemoteSdp
  1365. = isAdd
  1366. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1367. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1368. this._renegotiate(newRemoteSdp.raw)
  1369. .then(() => {
  1370. const newLocalSdp
  1371. = new SDP(this.peerconnection.localDescription.sdp);
  1372. logger.log(
  1373. `${logPrefix} - OK, SDPs: `, oldLocalSdp, newLocalSdp);
  1374. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1375. finishedCallback();
  1376. }, error => {
  1377. logger.error(`${logPrefix} failed:`, error);
  1378. finishedCallback(error);
  1379. });
  1380. };
  1381. // Queue and execute
  1382. this.modificationQueue.push(workFunction);
  1383. }
  1384. /**
  1385. * Takes in a jingle offer iq, returns the new sdp offer
  1386. * @param {jquery xml element} offerIq the incoming offer
  1387. * @returns {SDP object} the jingle offer translated to SDP
  1388. */
  1389. _processNewJingleOfferIq(offerIq) {
  1390. const remoteSdp = new SDP('');
  1391. if (this.webrtcIceTcpDisable) {
  1392. remoteSdp.removeTcpCandidates = true;
  1393. }
  1394. if (this.webrtcIceUdpDisable) {
  1395. remoteSdp.removeUdpCandidates = true;
  1396. }
  1397. if (this.failICE) {
  1398. remoteSdp.failICE = true;
  1399. }
  1400. remoteSdp.fromJingle(offerIq);
  1401. this.readSsrcInfo($(offerIq).find('>content'));
  1402. return remoteSdp;
  1403. }
  1404. /**
  1405. * Remove the given ssrc lines from the current remote sdp
  1406. * @param {list} removeSsrcInfo a list of SDP line strings that
  1407. * should be removed from the remote SDP
  1408. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1409. * in removeSsrcInfo
  1410. */
  1411. _processRemoteRemoveSource(removeSsrcInfo) {
  1412. const remoteSdp = browser.usesPlanB()
  1413. ? new SDP(this.peerconnection.remoteDescription.sdp)
  1414. : new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1415. removeSsrcInfo.forEach((lines, idx) => {
  1416. // eslint-disable-next-line no-param-reassign
  1417. lines = lines.split('\r\n');
  1418. lines.pop(); // remove empty last element;
  1419. if (browser.usesPlanB()) {
  1420. lines.forEach(line => {
  1421. remoteSdp.media[idx]
  1422. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1423. });
  1424. } else {
  1425. lines.forEach(line => {
  1426. const mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1427. if (mid > -1) {
  1428. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1429. // Change the direction to "inactive".
  1430. remoteSdp.media[mid] = remoteSdp.media[mid].replace('a=sendonly', 'a=inactive');
  1431. }
  1432. });
  1433. }
  1434. });
  1435. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1436. return remoteSdp;
  1437. }
  1438. /**
  1439. * Add the given ssrc lines to the current remote sdp
  1440. * @param {list} addSsrcInfo a list of SDP line strings that
  1441. * should be added to the remote SDP
  1442. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1443. * in removeSsrcInfo
  1444. */
  1445. _processRemoteAddSource(addSsrcInfo) {
  1446. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1447. addSsrcInfo.forEach((lines, idx) => {
  1448. remoteSdp.media[idx] += lines;
  1449. });
  1450. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1451. return remoteSdp;
  1452. }
  1453. /**
  1454. * Do a new o/a flow using the existing remote description
  1455. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1456. * to use. If not provided, the remote sdp from the
  1457. * peerconnection will be used
  1458. * @returns {Promise} promise which resolves when the
  1459. * o/a flow is complete with no arguments or
  1460. * rejects with an error {string}
  1461. */
  1462. _renegotiate(optionalRemoteSdp) {
  1463. if (this.peerconnection.signalingState === 'closed') {
  1464. const error = new Error('Attempted to renegotiate in state closed');
  1465. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1466. return Promise.reject(error);
  1467. }
  1468. const remoteSdp
  1469. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1470. if (!remoteSdp) {
  1471. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1472. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1473. return Promise.reject(error);
  1474. }
  1475. const remoteDescription = new RTCSessionDescription({
  1476. type: this.isInitiator ? 'answer' : 'offer',
  1477. sdp: remoteSdp
  1478. });
  1479. if (this.isInitiator) {
  1480. return this._initiatorRenegotiate(remoteDescription);
  1481. }
  1482. return this._responderRenegotiate(remoteDescription);
  1483. }
  1484. /**
  1485. * Renegotiate cycle implementation for the responder case.
  1486. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1487. * which will be used as remote description in the cycle.
  1488. * @private
  1489. */
  1490. _responderRenegotiate(remoteDescription) {
  1491. logger.debug('Renegotiate: setting remote description');
  1492. return this.peerconnection.setRemoteDescription(remoteDescription)
  1493. .then(() => {
  1494. logger.debug('Renegotiate: creating answer');
  1495. return this.peerconnection.createAnswer(this.mediaConstraints)
  1496. .then(answer => {
  1497. logger.debug('Renegotiate: setting local description');
  1498. return this.peerconnection.setLocalDescription(answer);
  1499. });
  1500. });
  1501. }
  1502. /**
  1503. * Renegotiate cycle implementation for the initiator's case.
  1504. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1505. * which will be used as remote description in the cycle.
  1506. * @private
  1507. */
  1508. _initiatorRenegotiate(remoteDescription) {
  1509. logger.debug('Renegotiate: creating offer');
  1510. return this.peerconnection.createOffer(this.mediaConstraints)
  1511. .then(offer => {
  1512. logger.debug('Renegotiate: setting local description');
  1513. return this.peerconnection.setLocalDescription(offer)
  1514. .then(() => {
  1515. logger.debug(
  1516. 'Renegotiate: setting remote description');
  1517. // eslint-disable-next-line max-len
  1518. return this.peerconnection.setRemoteDescription(remoteDescription);
  1519. });
  1520. });
  1521. }
  1522. /**
  1523. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1524. * offer/answer cycle after both operations are done. Either
  1525. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1526. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1527. * <tt>oldTrack</tt>
  1528. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1529. * replaced
  1530. * @param {JitsiLocalTrack|null} newTrack the new track to use
  1531. * @returns {Promise} which resolves once the replacement is complete
  1532. * with no arguments or rejects with an error {string}
  1533. */
  1534. replaceTrack(oldTrack, newTrack) {
  1535. const workFunction = finishedCallback => {
  1536. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1537. if (browser.usesPlanB()) {
  1538. // NOTE the code below assumes that no more than 1 video track
  1539. // can be added to the peer connection.
  1540. // Transition from camera to desktop share
  1541. // or transition from one camera source to another.
  1542. if (this.peerconnection.options.capScreenshareBitrate
  1543. && oldTrack && newTrack && newTrack.isVideoTrack()) {
  1544. // Clearing current primary SSRC will make
  1545. // the SdpConsistency generate a new one which will result
  1546. // with:
  1547. // 1. source-remove for the old video stream.
  1548. // 2. source-add for the new video stream.
  1549. this.peerconnection.clearRecvonlySsrc();
  1550. }
  1551. // Transition from no video to video (unmute).
  1552. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  1553. // Clearing current primary SSRC will make
  1554. // the SdpConsistency generate a new one which will result
  1555. // with:
  1556. // 1. source-remove for the recvonly
  1557. // 2. source-add for the new video stream
  1558. this.peerconnection.clearRecvonlySsrc();
  1559. // Transition from video to no video
  1560. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  1561. // Clearing current primary SSRC and generating the recvonly
  1562. // will result in:
  1563. // 1. source-remove for the old video stream
  1564. // 2. source-add for the recvonly stream
  1565. this.peerconnection.clearRecvonlySsrc();
  1566. this.peerconnection.generateRecvonlySsrc();
  1567. }
  1568. }
  1569. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1570. .then(shouldRenegotiate => {
  1571. let promise = Promise.resolve();
  1572. if (shouldRenegotiate
  1573. && (oldTrack || newTrack)
  1574. && this.state === JingleSessionState.ACTIVE) {
  1575. promise = this._renegotiate().then(() => {
  1576. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1577. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSDP);
  1578. },
  1579. finishedCallback /* will be called with en error */);
  1580. }
  1581. // Wait for the renegotation to be done if needed (plan-b) before adjusting
  1582. // the max bitrates on the video sender.
  1583. promise.then(() => {
  1584. // configure max bitrate only when media is routed
  1585. // through JVB. For p2p case, browser takes care of
  1586. // adjusting the uplink based on the feedback it
  1587. // gets from the peer.
  1588. if (newTrack && !this.isP2P) {
  1589. this.peerconnection.setMaxBitRate(newTrack);
  1590. }
  1591. finishedCallback();
  1592. }, finishedCallback /* will be called with en error */);
  1593. })
  1594. .catch(err => {
  1595. finishedCallback(err);
  1596. });
  1597. };
  1598. return new Promise((resolve, reject) => {
  1599. this.modificationQueue.push(
  1600. workFunction,
  1601. error => {
  1602. if (error) {
  1603. logger.error('Replace track error:', error);
  1604. reject(error);
  1605. } else {
  1606. logger.info('Replace track done!');
  1607. resolve();
  1608. }
  1609. });
  1610. });
  1611. }
  1612. /**
  1613. * Parse the information from the xml sourceRemoveElem and translate it
  1614. * into sdp lines
  1615. * @param {jquery xml element} sourceRemoveElem the source-remove
  1616. * element from jingle
  1617. * @param {SDP object} currentRemoteSdp the current remote
  1618. * sdp (as of this new source-remove)
  1619. * @returns {list} a list of SDP line strings that should
  1620. * be removed from the remote SDP
  1621. */
  1622. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  1623. const removeSsrcInfo = [];
  1624. $(sourceRemoveElem).each((i1, content) => {
  1625. const name = $(content).attr('name');
  1626. let lines = '';
  1627. $(content)
  1628. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1629. .each(function() {
  1630. /* eslint-disable no-invalid-this */
  1631. const semantics = this.getAttribute('semantics');
  1632. const ssrcs
  1633. = $(this)
  1634. .find('>source')
  1635. .map(function() {
  1636. return this.getAttribute('ssrc');
  1637. })
  1638. .get();
  1639. if (ssrcs.length) {
  1640. lines
  1641. += `a=ssrc-group:${semantics} ${
  1642. ssrcs.join(' ')}\r\n`;
  1643. }
  1644. /* eslint-enable no-invalid-this */
  1645. });
  1646. const ssrcs = [];
  1647. // handles both >source and >description>source versions
  1648. const tmp
  1649. = $(content).find(
  1650. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1651. tmp.each(function() {
  1652. // eslint-disable-next-line no-invalid-this
  1653. const ssrc = $(this).attr('ssrc');
  1654. ssrcs.push(ssrc);
  1655. });
  1656. currentRemoteSdp.media.forEach((media, i2) => {
  1657. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1658. return;
  1659. }
  1660. if (!removeSsrcInfo[i2]) {
  1661. removeSsrcInfo[i2] = '';
  1662. }
  1663. ssrcs.forEach(ssrc => {
  1664. const ssrcLines
  1665. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  1666. if (ssrcLines.length) {
  1667. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  1668. }
  1669. });
  1670. removeSsrcInfo[i2] += lines;
  1671. });
  1672. });
  1673. return removeSsrcInfo;
  1674. }
  1675. /**
  1676. * Will print an error if there is any difference, between the SSRCs given
  1677. * in the <tt>oldSDP</tt> and the ones currently described in
  1678. * the peerconnection's local description.
  1679. * @param {string} operationName the operation's name which will be printed
  1680. * in the error message.
  1681. * @param {SDP} oldSDP the old local SDP which will be compared with
  1682. * the current one.
  1683. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  1684. * otherwise.
  1685. * @private
  1686. */
  1687. _verifyNoSSRCChanged(operationName, oldSDP) {
  1688. const currentLocalSDP
  1689. = new SDP(this.peerconnection.localDescription.sdp);
  1690. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  1691. const addedMedia = sdpDiff.getNewMedia();
  1692. if (Object.keys(addedMedia).length) {
  1693. logger.error(
  1694. `${this} - some SSRC were added on ${operationName}`,
  1695. addedMedia);
  1696. return false;
  1697. }
  1698. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  1699. const removedMedia = sdpDiff.getNewMedia();
  1700. if (Object.keys(removedMedia).length) {
  1701. logger.error(
  1702. `${this} - some SSRCs were removed on ${operationName}`,
  1703. removedMedia);
  1704. return false;
  1705. }
  1706. return true;
  1707. }
  1708. /**
  1709. * Adds local track back to this session, as part of the unmute operation.
  1710. * @param {JitsiLocalTrack} track
  1711. * @return {Promise} a promise that will resolve once the local track is
  1712. * added back to this session and renegotiation succeeds. Will be rejected
  1713. * with a <tt>string</tt> that provides some error details in case something
  1714. * goes wrong.
  1715. */
  1716. addTrackAsUnmute(track) {
  1717. return this._addRemoveTrackAsMuteUnmute(
  1718. false /* add as unmute */, track);
  1719. }
  1720. /**
  1721. * Remove local track as part of the mute operation.
  1722. * @param {JitsiLocalTrack} track the local track to be removed
  1723. * @return {Promise} a promise which will be resolved once the local track
  1724. * is removed from this session and the renegotiation is performed.
  1725. * The promise will be rejected with a <tt>string</tt> that the describes
  1726. * the error if anything goes wrong.
  1727. */
  1728. removeTrackAsMute(track) {
  1729. return this._addRemoveTrackAsMuteUnmute(
  1730. true /* remove as mute */, track);
  1731. }
  1732. /**
  1733. * See {@link addTrackAsUnmute} and {@link removeTrackAsMute}.
  1734. * @param {boolean} isMute <tt>true</tt> for "remove as mute" or
  1735. * <tt>false</tt> for "add as unmute".
  1736. * @param {JitsiLocalTrack} track the track that will be added/removed
  1737. * @private
  1738. */
  1739. _addRemoveTrackAsMuteUnmute(isMute, track) {
  1740. if (!track) {
  1741. return Promise.reject('invalid "track" argument value');
  1742. }
  1743. const operationName = isMute ? 'removeTrackMute' : 'addTrackUnmute';
  1744. const workFunction = finishedCallback => {
  1745. const tpc = this.peerconnection;
  1746. if (!tpc) {
  1747. finishedCallback(
  1748. `Error: tried ${operationName} track with no active peer`
  1749. + 'connection');
  1750. return;
  1751. }
  1752. const oldLocalSDP = tpc.localDescription.sdp;
  1753. const tpcOperation
  1754. = isMute
  1755. ? tpc.removeTrackMute.bind(tpc, track)
  1756. : tpc.addTrackUnmute.bind(tpc, track);
  1757. if (!tpcOperation()) {
  1758. finishedCallback(`${operationName} failed!`);
  1759. // Do not renegotiate when browser is running in Unified-plan mode.
  1760. } else if (!oldLocalSDP || !tpc.remoteDescription.sdp || browser.usesUnifiedPlan()) {
  1761. finishedCallback();
  1762. } else {
  1763. this._renegotiate()
  1764. .then(() => {
  1765. // The results are ignored, as this check failure is not
  1766. // enough to fail the whole operation. It will log
  1767. // an error inside.
  1768. this._verifyNoSSRCChanged(
  1769. operationName, new SDP(oldLocalSDP));
  1770. finishedCallback();
  1771. },
  1772. finishedCallback /* will be called with an error */);
  1773. }
  1774. };
  1775. return new Promise((resolve, reject) => {
  1776. this.modificationQueue.push(
  1777. workFunction,
  1778. error => {
  1779. if (error) {
  1780. reject(error);
  1781. } else {
  1782. resolve();
  1783. }
  1784. });
  1785. });
  1786. }
  1787. /**
  1788. * Resumes or suspends media transfer over the underlying peer connection.
  1789. * @param {boolean} audioActive <tt>true</tt> to enable audio media
  1790. * transfer or <tt>false</tt> to suspend audio media transmission.
  1791. * @param {boolean} videoActive <tt>true</tt> to enable video media
  1792. * transfer or <tt>false</tt> to suspend video media transmission.
  1793. * @return {Promise} a <tt>Promise</tt> which will resolve once
  1794. * the operation is done. It will be rejected with an error description as
  1795. * a string in case anything goes wrong.
  1796. */
  1797. setMediaTransferActive(audioActive, videoActive) {
  1798. if (!this.peerconnection) {
  1799. return Promise.reject(
  1800. 'Can not modify transfer active state,'
  1801. + ' before "initialize" is called');
  1802. }
  1803. const logAudioStr = audioActive ? 'audio active' : 'audio inactive';
  1804. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  1805. logger.info(`Queued make ${logVideoStr}, ${logAudioStr} task...`);
  1806. const workFunction = finishedCallback => {
  1807. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  1808. // Because the value is modified on the queue it's impossible to
  1809. // check it's final value reliably prior to submitting the task.
  1810. // The rule here is that the last submitted state counts.
  1811. // Check the values here to avoid unnecessary renegotiation cycle.
  1812. const audioActiveChanged
  1813. = this.peerconnection.setAudioTransferActive(audioActive);
  1814. if (this._localVideoActive !== videoActive) {
  1815. this._localVideoActive = videoActive;
  1816. // Do only for P2P - Jicofo will reply with 'bad-request'
  1817. // We don't want to send 'content-modify', before the initial
  1818. // O/A (state === JingleSessionState.ACTIVE), because that will
  1819. // mess up video media direction in the remote SDP.
  1820. // 'content-modify' when processed only affects the media
  1821. // direction in the local SDP. We're doing that, because setting
  1822. // 'inactive' on video media in remote SDP will mess up our SDP
  1823. // translation chain (simulcast, RTX, video mute etc.).
  1824. if (this.isP2P && isSessionActive) {
  1825. this.sendContentModify(videoActive);
  1826. }
  1827. }
  1828. const pcVideoActiveChanged
  1829. = this.peerconnection.setVideoTransferActive(
  1830. this._localVideoActive && this._remoteVideoActive);
  1831. // Will do the sRD/sLD cycle to update SDPs and adjust the media
  1832. // direction
  1833. if (isSessionActive
  1834. && (audioActiveChanged || pcVideoActiveChanged)) {
  1835. this._renegotiate()
  1836. .then(
  1837. finishedCallback,
  1838. finishedCallback /* will be called with an error */);
  1839. } else {
  1840. finishedCallback();
  1841. }
  1842. };
  1843. return new Promise((resolve, reject) => {
  1844. this.modificationQueue.push(
  1845. workFunction,
  1846. error => {
  1847. if (error) {
  1848. reject(error);
  1849. } else {
  1850. resolve();
  1851. }
  1852. });
  1853. });
  1854. }
  1855. /**
  1856. * Will put and execute on the queue a session modify task. Currently it
  1857. * only checks the senders attribute of the video content in order to figure
  1858. * out if the remote peer has video in the inactive state (stored locally
  1859. * in {@link _remoteVideoActive} - see field description for more info).
  1860. * @param {jQuery} jingleContents jQuery selector pointing to the jingle
  1861. * element of the session modify IQ.
  1862. * @see {@link _remoteVideoActive}
  1863. * @see {@link _localVideoActive}
  1864. */
  1865. modifyContents(jingleContents) {
  1866. const newVideoSenders
  1867. = JingleSessionPC.parseVideoSenders(jingleContents);
  1868. if (newVideoSenders === null) {
  1869. logger.error(
  1870. `${this} - failed to parse video "senders" attribute in`
  1871. + '"content-modify" action');
  1872. return;
  1873. }
  1874. const workFunction = finishedCallback => {
  1875. if (this._assertNotEnded('content-modify')
  1876. && this._modifyRemoteVideoActive(newVideoSenders)) {
  1877. // Will do the sRD/sLD cycle to update SDPs and adjust
  1878. // the media direction
  1879. this._renegotiate()
  1880. .then(finishedCallback, finishedCallback /* (error) */);
  1881. } else {
  1882. finishedCallback();
  1883. }
  1884. };
  1885. logger.debug(
  1886. `${this} queued "content-modify" task`
  1887. + `(video senders="${newVideoSenders}")`);
  1888. this.modificationQueue.push(
  1889. workFunction,
  1890. error => {
  1891. if (error) {
  1892. logger.error('"content-modify" failed', error);
  1893. }
  1894. });
  1895. }
  1896. /**
  1897. * Processes new value of remote video "senders" Jingle attribute and tries
  1898. * to apply it for {@link _remoteVideoActive}.
  1899. * @param {string} remoteVideoSenders the value of "senders" attribute of
  1900. * Jingle video content element advertised by remote peer.
  1901. * @return {boolean} <tt>true</tt> if the change affected state of
  1902. * the underlying peerconnection and renegotiation is required for
  1903. * the changes to take effect.
  1904. * @private
  1905. */
  1906. _modifyRemoteVideoActive(remoteVideoSenders) {
  1907. const isRemoteVideoActive
  1908. = remoteVideoSenders === 'both'
  1909. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  1910. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  1911. if (isRemoteVideoActive !== this._remoteVideoActive) {
  1912. logger.debug(
  1913. `${this} new remote video active: ${isRemoteVideoActive}`);
  1914. this._remoteVideoActive = isRemoteVideoActive;
  1915. }
  1916. return this.peerconnection.setVideoTransferActive(
  1917. this._localVideoActive && this._remoteVideoActive);
  1918. }
  1919. /**
  1920. * Figures out added/removed ssrcs and send update IQs.
  1921. * @param oldSDP SDP object for old description.
  1922. * @param newSDP SDP object for new description.
  1923. */
  1924. notifyMySSRCUpdate(oldSDP, newSDP) {
  1925. if (this.state !== JingleSessionState.ACTIVE) {
  1926. logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
  1927. return;
  1928. }
  1929. if (!this.connection.connected) {
  1930. // The goal is to compare the oldest SDP with the latest one upon reconnect
  1931. if (!this._cachedOldLocalSdp) {
  1932. this._cachedOldLocalSdp = oldSDP;
  1933. }
  1934. this._cachedNewLocalSdp = newSDP;
  1935. logger.warn('Not sending SSRC update while the signaling is disconnected');
  1936. return;
  1937. }
  1938. this._cachedOldLocalSdp = undefined;
  1939. this._cachedNewLocalSdp = undefined;
  1940. // send source-remove IQ.
  1941. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  1942. const remove = $iq({ to: this.remoteJid,
  1943. type: 'set' })
  1944. .c('jingle', {
  1945. xmlns: 'urn:xmpp:jingle:1',
  1946. action: 'source-remove',
  1947. initiator: this.initiatorJid,
  1948. sid: this.sid
  1949. }
  1950. );
  1951. const removedAnySSRCs = sdpDiffer.toJingle(remove);
  1952. if (removedAnySSRCs) {
  1953. logger.info('Sending source-remove', remove.tree());
  1954. this.connection.sendIQ(
  1955. remove, null,
  1956. this.newJingleErrorHandler(remove), IQ_TIMEOUT);
  1957. } else {
  1958. logger.log('removal not necessary');
  1959. }
  1960. // send source-add IQ.
  1961. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  1962. const add = $iq({ to: this.remoteJid,
  1963. type: 'set' })
  1964. .c('jingle', {
  1965. xmlns: 'urn:xmpp:jingle:1',
  1966. action: 'source-add',
  1967. initiator: this.initiatorJid,
  1968. sid: this.sid
  1969. }
  1970. );
  1971. const containsNewSSRCs = sdpDiffer.toJingle(add);
  1972. if (containsNewSSRCs) {
  1973. logger.info('Sending source-add', add.tree());
  1974. this.connection.sendIQ(
  1975. add, null, this.newJingleErrorHandler(add), IQ_TIMEOUT);
  1976. } else {
  1977. logger.log('addition not necessary');
  1978. }
  1979. }
  1980. /**
  1981. * Method returns function(errorResponse) which is a callback to be passed
  1982. * to Strophe connection.sendIQ method. An 'error' structure is created that
  1983. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1984. * structure is as follows:
  1985. * {
  1986. * code: {XMPP error response code}
  1987. * reason: {the name of XMPP error reason element or 'timeout' if the
  1988. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1989. * source: {request.tree() that provides original request}
  1990. * session: {this JingleSessionPC.toString()}
  1991. * }
  1992. * @param request Strophe IQ instance which is the request to be dumped into
  1993. * the error structure
  1994. * @param failureCb function(error) called when error response was returned
  1995. * or when a timeout has occurred.
  1996. * @returns {function(this:JingleSessionPC)}
  1997. */
  1998. newJingleErrorHandler(request, failureCb) {
  1999. return errResponse => {
  2000. const error = {};
  2001. // Get XMPP error code and condition(reason)
  2002. const errorElSel = $(errResponse).find('error');
  2003. if (errorElSel.length) {
  2004. error.code = errorElSel.attr('code');
  2005. const errorReasonSel = $(errResponse).find('error :first');
  2006. if (errorReasonSel.length) {
  2007. error.reason = errorReasonSel[0].tagName;
  2008. }
  2009. const errorMsgSel = errorElSel.find('>text');
  2010. if (errorMsgSel.length) {
  2011. error.msg = errorMsgSel.text();
  2012. }
  2013. }
  2014. if (!errResponse) {
  2015. error.reason = 'timeout';
  2016. }
  2017. error.session = this.toString();
  2018. if (failureCb) {
  2019. failureCb(error);
  2020. } else if (this.state === JingleSessionState.ENDED
  2021. && error.reason === 'item-not-found') {
  2022. // When remote peer decides to terminate the session, but it
  2023. // still have few messages on the queue for processing,
  2024. // it will first send us 'session-terminate' (we enter ENDED)
  2025. // and then follow with 'item-not-found' for the queued requests
  2026. // We don't want to have that logged on error level.
  2027. logger.debug(`Jingle error: ${JSON.stringify(error)}`);
  2028. } else {
  2029. GlobalOnErrorHandler.callErrorHandler(
  2030. new Error(
  2031. `Jingle error: ${JSON.stringify(error)}`));
  2032. }
  2033. };
  2034. }
  2035. /**
  2036. * Returns the ice connection state for the peer connection.
  2037. * @returns the ice connection state for the peer connection.
  2038. */
  2039. getIceConnectionState() {
  2040. return this.peerconnection.iceConnectionState;
  2041. }
  2042. /**
  2043. * Closes the peerconnection.
  2044. */
  2045. close() {
  2046. this.state = JingleSessionState.ENDED;
  2047. this.establishmentDuration = undefined;
  2048. if (this.peerconnection) {
  2049. this.peerconnection.onicecandidate = null;
  2050. this.peerconnection.oniceconnectionstatechange = null;
  2051. this.peerconnection.onnegotiationneeded = null;
  2052. this.peerconnection.onsignalingstatechange = null;
  2053. }
  2054. // Remove any pending tasks from the queue
  2055. this.modificationQueue.clear();
  2056. this.modificationQueue.push(finishCallback => {
  2057. // The signaling layer will remove it's listeners
  2058. this.signalingLayer.setChatRoom(null);
  2059. // do not try to close if already closed.
  2060. this.peerconnection && this.peerconnection.close();
  2061. finishCallback();
  2062. });
  2063. // No more tasks can go in after the close task
  2064. this.modificationQueue.shutdown();
  2065. }
  2066. /**
  2067. * Converts to string with minor summary.
  2068. * @return {string}
  2069. */
  2070. toString() {
  2071. return `JingleSessionPC[p2p=${this.isP2P},`
  2072. + `initiator=${this.isInitiator},sid=${this.sid}]`;
  2073. }
  2074. /**
  2075. * If the A/B test for suspend video is disabled according to the room's
  2076. * configuration, returns undefined. Otherwise returns a boolean which
  2077. * indicates whether the suspend video option should be enabled or disabled.
  2078. * @param {JingleSessionPCOptions} options - The config options.
  2079. */
  2080. _abtestSuspendVideoEnabled({ abTesting }) {
  2081. if (!abTesting || !abTesting.enableSuspendVideoTest) {
  2082. return;
  2083. }
  2084. // We want the two participants in a P2P call to agree on the value of
  2085. // the "suspend" option. We use the JID of the initiator, because it is
  2086. // both randomly selected and agreed upon by both participants.
  2087. const jid = this._getInitiatorJid();
  2088. return integerHash(jid) % 2 === 0;
  2089. }
  2090. }