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

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