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

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