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

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