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

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