Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JingleSessionPC.js 85KB

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