You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 82KB

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