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

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