Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JingleSessionPC.js 83KB

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