Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JingleSessionPC.js 81KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184
  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,
  584. Strophe.getResourceFromJid(owner));
  585. }
  586. }
  587. });
  588. }
  589. });
  590. }
  591. /**
  592. * Makes the underlying TraceablePeerConnection generate new SSRC for
  593. * the recvonly video stream.
  594. * @deprecated
  595. */
  596. generateRecvonlySsrc() {
  597. if (this.peerconnection) {
  598. this.peerconnection.generateRecvonlySsrc();
  599. } else {
  600. logger.error(
  601. 'Unable to generate recvonly SSRC - no peerconnection');
  602. }
  603. }
  604. /* eslint-disable max-params */
  605. /**
  606. * Accepts incoming Jingle 'session-initiate' and should send
  607. * 'session-accept' in result.
  608. * @param jingleOffer jQuery selector pointing to the jingle element of
  609. * the offer IQ
  610. * @param success callback called when we accept incoming session
  611. * successfully and receive RESULT packet to 'session-accept' sent.
  612. * @param failure function(error) called if for any reason we fail to accept
  613. * the incoming offer. 'error' argument can be used to log some details
  614. * about the error.
  615. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
  616. * the local tracks that will be added, before the offer/answer cycle
  617. * executes. We allow the localTracks to optionally be passed in so that
  618. * the addition of the local tracks and the processing of the initial offer
  619. * can all be done atomically. We want to make sure that any other
  620. * operations which originate in the XMPP Jingle messages related with
  621. * this session to be executed with an assumption that the initial
  622. * offer/answer cycle has been executed already.
  623. */
  624. acceptOffer(jingleOffer, success, failure, localTracks) {
  625. this.setOfferAnswerCycle(
  626. jingleOffer,
  627. () => {
  628. // FIXME we may not care about RESULT packet for session-accept
  629. // then we should either call 'success' here immediately or
  630. // modify sendSessionAccept method to do that
  631. this.sendSessionAccept(success, failure);
  632. },
  633. failure,
  634. localTracks);
  635. }
  636. /* eslint-enable max-params */
  637. /**
  638. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  639. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be
  640. * added, before the offer/answer cycle executes (for the local track
  641. * addition to be an atomic operation together with the offer/answer).
  642. */
  643. invite(localTracks) {
  644. if (!this.isInitiator) {
  645. throw new Error('Trying to invite from the responder session');
  646. }
  647. const workFunction = finishedCallback => {
  648. for (const localTrack of localTracks) {
  649. this.peerconnection.addTrack(localTrack);
  650. }
  651. this.peerconnection.createOffer(
  652. offerSdp => {
  653. this.peerconnection.setLocalDescription(
  654. offerSdp,
  655. () => {
  656. // NOTE that the offer is obtained from
  657. // the localDescription getter as it needs to go
  658. // though the transformation chain.
  659. this.sendSessionInitiate(
  660. this.peerconnection.localDescription.sdp);
  661. finishedCallback();
  662. },
  663. error => {
  664. logger.error(
  665. 'Failed to set local SDP', error, offerSdp);
  666. finishedCallback(error);
  667. });
  668. },
  669. error => {
  670. logger.error(
  671. 'Failed to create an offer',
  672. error,
  673. this.mediaConstraints);
  674. finishedCallback(error);
  675. },
  676. this.mediaConstraints);
  677. };
  678. this.modificationQueue.push(
  679. workFunction,
  680. error => {
  681. if (error) {
  682. logger.error('invite error', error);
  683. } else {
  684. logger.debug('invite executed - OK');
  685. }
  686. });
  687. }
  688. /**
  689. * Sends 'session-initiate' to the remote peer.
  690. *
  691. * NOTE this method is synchronous and we're not waiting for the RESULT
  692. * response which would delay the startup process.
  693. *
  694. * @param {string} offerSdp - The local session description which will be
  695. * used to generate an offer.
  696. * @private
  697. */
  698. sendSessionInitiate(offerSdp) {
  699. let init = $iq({
  700. to: this.peerjid,
  701. type: 'set'
  702. }).c('jingle', {
  703. xmlns: 'urn:xmpp:jingle:1',
  704. action: 'session-initiate',
  705. initiator: this.initiator,
  706. sid: this.sid
  707. });
  708. new SDP(offerSdp).toJingle(
  709. init,
  710. this.initiator === this.me ? 'initiator' : 'responder');
  711. init = init.tree();
  712. logger.info('Session-initiate: ', init);
  713. this.connection.sendIQ(init,
  714. () => {
  715. logger.info('Got RESULT for "session-initiate"');
  716. },
  717. error => {
  718. logger.error('"session-initiate" error', error);
  719. },
  720. IQ_TIMEOUT);
  721. }
  722. /**
  723. * Sets the answer received from the remote peer.
  724. * @param jingleAnswer
  725. */
  726. setAnswer(jingleAnswer) {
  727. if (!this.isInitiator) {
  728. throw new Error('Trying to set an answer on the responder session');
  729. }
  730. this.setOfferAnswerCycle(
  731. jingleAnswer,
  732. () => {
  733. logger.info('setAnswer - succeeded');
  734. },
  735. error => {
  736. logger.error('setAnswer failed: ', error);
  737. });
  738. }
  739. /* eslint-disable max-params */
  740. /**
  741. * This is a setRemoteDescription/setLocalDescription cycle which starts at
  742. * converting Strophe Jingle IQ into remote offer SDP. Once converted
  743. * setRemoteDescription, createAnswer and setLocalDescription calls follow.
  744. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element
  745. * of the offer (or answer) IQ
  746. * @param success callback called when sRD/sLD cycle finishes successfully.
  747. * @param failure callback called with an error object as an argument if we
  748. * fail at any point during setRD, createAnswer, setLD.
  749. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
  750. * the local tracks that will be added, before the offer/answer cycle
  751. * executes (for the local track addition to be an atomic operation together
  752. * with the offer/answer).
  753. */
  754. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks) {
  755. const workFunction = finishedCallback => {
  756. if (localTracks) {
  757. for (const track of localTracks) {
  758. this.peerconnection.addTrack(track);
  759. }
  760. }
  761. const newRemoteSdp
  762. = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  763. const oldLocalSdp
  764. = this.peerconnection.localDescription.sdp;
  765. this._renegotiate(newRemoteSdp.raw)
  766. .then(() => {
  767. if (this.state === JingleSessionState.PENDING) {
  768. this.state = JingleSessionState.ACTIVE;
  769. // Sync up video transfer active/inactive only after
  770. // the initial O/A cycle. We want to adjust the video
  771. // media direction only in the local SDP and the Jingle
  772. // contents direction included in the initial
  773. // offer/answer is mapped to the remote SDP. Jingle
  774. // 'content-modify' IQ is processed in a way that it
  775. // will only modify local SDP when remote peer is no
  776. // longer interested in receiving video content.
  777. // Changing media direction in the remote SDP will mess
  778. // up our SDP translation chain (simulcast, video mute,
  779. // RTX etc.)
  780. if (this.isP2P && !this._localVideoActive) {
  781. this.sendContentModify(this._localVideoActive);
  782. }
  783. }
  784. // Old local SDP will be available when we're setting answer
  785. // for the first time, but not when offer and it's fine
  786. // since we're generating an answer now it will contain all
  787. // our SSRCs
  788. if (oldLocalSdp) {
  789. const newLocalSdp
  790. = new SDP(this.peerconnection.localDescription.sdp);
  791. this.notifyMySSRCUpdate(
  792. new SDP(oldLocalSdp), newLocalSdp);
  793. }
  794. finishedCallback();
  795. }, error => {
  796. logger.error(
  797. `Error renegotiating after setting new remote ${
  798. this.isInitiator ? 'answer: ' : 'offer: '}${error}`,
  799. newRemoteSdp);
  800. JingleSessionPC.onJingleFatalError(this, error);
  801. finishedCallback(error);
  802. });
  803. };
  804. this.modificationQueue.push(
  805. workFunction,
  806. error => {
  807. error ? failure(error) : success();
  808. });
  809. }
  810. /* eslint-enable max-params */
  811. /**
  812. * Although it states "replace transport" it does accept full Jingle offer
  813. * which should contain new ICE transport details.
  814. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  815. * transport info.
  816. * @param success callback called when we succeed to accept new offer.
  817. * @param failure function(error) called when we fail to accept new offer.
  818. */
  819. replaceTransport(jingleOfferElem, success, failure) {
  820. // We need to first set an offer without the 'data' section to have the
  821. // SCTP stack cleaned up. After that the original offer is set to have
  822. // the SCTP connection established with the new bridge.
  823. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  824. const originalOffer = jingleOfferElem.clone();
  825. jingleOfferElem.find('>content[name=\'data\']').remove();
  826. // First set an offer without the 'data' section
  827. this.setOfferAnswerCycle(
  828. jingleOfferElem,
  829. () => {
  830. // Now set the original offer(with the 'data' section)
  831. this.setOfferAnswerCycle(
  832. originalOffer,
  833. () => {
  834. const localSDP
  835. = new SDP(this.peerconnection.localDescription.sdp);
  836. this.sendTransportAccept(localSDP, success, failure);
  837. },
  838. failure);
  839. },
  840. failure
  841. );
  842. }
  843. /**
  844. * Sends Jingle 'session-accept' message.
  845. * @param {function()} success callback called when we receive 'RESULT'
  846. * packet for the 'session-accept'
  847. * @param {function(error)} failure called when we receive an error response
  848. * or when the request has timed out.
  849. * @private
  850. */
  851. sendSessionAccept(success, failure) {
  852. // NOTE: since we're just reading from it, we don't need to be within
  853. // the modification queue to access the local description
  854. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  855. let accept = $iq({ to: this.peerjid,
  856. type: 'set' })
  857. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  858. action: 'session-accept',
  859. initiator: this.initiator,
  860. responder: this.responder,
  861. sid: this.sid });
  862. if (this.webrtcIceTcpDisable) {
  863. localSDP.removeTcpCandidates = true;
  864. }
  865. if (this.webrtcIceUdpDisable) {
  866. localSDP.removeUdpCandidates = true;
  867. }
  868. if (this.failICE) {
  869. localSDP.failICE = true;
  870. }
  871. localSDP.toJingle(
  872. accept,
  873. this.initiator === this.localJid ? 'initiator' : 'responder',
  874. null);
  875. // Calling tree() to print something useful
  876. accept = accept.tree();
  877. logger.info('Sending session-accept', accept);
  878. this.connection.sendIQ(accept,
  879. success,
  880. this.newJingleErrorHandler(accept, error => {
  881. failure(error);
  882. // 'session-accept' is a critical timeout and we'll
  883. // have to restart
  884. this.room.eventEmitter.emit(
  885. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  886. }),
  887. IQ_TIMEOUT);
  888. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  889. // fingerprint and setup) ASAP in order to start the connection
  890. // establishment.
  891. //
  892. // FIXME Flushing the connection at this point triggers an issue with
  893. // BOSH request handling in Prosody on slow connections.
  894. //
  895. // The problem is that this request will be quite large and it may take
  896. // time before it reaches Prosody. In the meantime Strophe may decide
  897. // to send the next one. And it was observed that a small request with
  898. // 'transport-info' usually follows this one. It does reach Prosody
  899. // before the previous one was completely received. 'rid' on the server
  900. // is increased and Prosody ignores the request with 'session-accept'.
  901. // It will never reach Jicofo and everything in the request table is
  902. // lost. Removing the flush does not guarantee it will never happen, but
  903. // makes it much less likely('transport-info' is bundled with
  904. // 'session-accept' and any immediate requests).
  905. //
  906. // this.connection.flush();
  907. }
  908. /**
  909. * Will send 'content-modify' IQ in order to ask the remote peer to
  910. * either stop or resume sending video media.
  911. * @param {boolean} videoTransferActive <tt>false</tt> to let the other peer
  912. * know that we're not sending nor interested in receiving video contents.
  913. * When set to <tt>true</tt> remote peer will be asked to resume video
  914. * transfer.
  915. * @private
  916. */
  917. sendContentModify(videoTransferActive) {
  918. const newSendersValue = videoTransferActive ? 'both' : 'none';
  919. const sessionModify
  920. = $iq({
  921. to: this.peerjid,
  922. type: 'set'
  923. })
  924. .c('jingle', {
  925. xmlns: 'urn:xmpp:jingle:1',
  926. action: 'content-modify',
  927. initiator: this.initiator,
  928. sid: this.sid
  929. })
  930. .c('content', {
  931. name: 'video',
  932. senders: newSendersValue
  933. });
  934. logger.info(
  935. `Sending content-modify, video senders: ${newSendersValue}`);
  936. this.connection.sendIQ(
  937. sessionModify,
  938. null,
  939. this.newJingleErrorHandler(sessionModify),
  940. IQ_TIMEOUT);
  941. }
  942. /**
  943. * Sends Jingle 'transport-accept' message which is a response to
  944. * 'transport-replace'.
  945. * @param localSDP the 'SDP' object with local session description
  946. * @param success callback called when we receive 'RESULT' packet for
  947. * 'transport-replace'
  948. * @param failure function(error) called when we receive an error response
  949. * or when the request has timed out.
  950. * @private
  951. */
  952. sendTransportAccept(localSDP, success, failure) {
  953. let transportAccept = $iq({ to: this.peerjid,
  954. type: 'set' })
  955. .c('jingle', {
  956. xmlns: 'urn:xmpp:jingle:1',
  957. action: 'transport-accept',
  958. initiator: this.initiator,
  959. sid: this.sid
  960. });
  961. localSDP.media.forEach((medialines, idx) => {
  962. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  963. transportAccept.c('content',
  964. {
  965. creator:
  966. this.initiator === this.localJid
  967. ? 'initiator'
  968. : 'responder',
  969. name: mline.media
  970. }
  971. );
  972. localSDP.transportToJingle(idx, transportAccept);
  973. transportAccept.up();
  974. });
  975. // Calling tree() to print something useful to the logger
  976. transportAccept = transportAccept.tree();
  977. logger.info('Sending transport-accept: ', transportAccept);
  978. this.connection.sendIQ(transportAccept,
  979. success,
  980. this.newJingleErrorHandler(transportAccept, failure),
  981. IQ_TIMEOUT);
  982. }
  983. /**
  984. * Sends Jingle 'transport-reject' message which is a response to
  985. * 'transport-replace'.
  986. * @param success callback called when we receive 'RESULT' packet for
  987. * 'transport-replace'
  988. * @param failure function(error) called when we receive an error response
  989. * or when the request has timed out.
  990. *
  991. * FIXME method should be marked as private, but there's some spaghetti that
  992. * needs to be fixed prior doing that
  993. */
  994. sendTransportReject(success, failure) {
  995. // Send 'transport-reject', so that the focus will
  996. // know that we've failed
  997. let transportReject = $iq({ to: this.peerjid,
  998. type: 'set' })
  999. .c('jingle', {
  1000. xmlns: 'urn:xmpp:jingle:1',
  1001. action: 'transport-reject',
  1002. initiator: this.initiator,
  1003. sid: this.sid
  1004. });
  1005. transportReject = transportReject.tree();
  1006. logger.info('Sending \'transport-reject', transportReject);
  1007. this.connection.sendIQ(transportReject,
  1008. success,
  1009. this.newJingleErrorHandler(transportReject, failure),
  1010. IQ_TIMEOUT);
  1011. }
  1012. /**
  1013. * @inheritDoc
  1014. */
  1015. terminate(success, failure, options) {
  1016. if (this.state === JingleSessionState.ENDED) {
  1017. return;
  1018. }
  1019. if (!options || Boolean(options.sendSessionTerminate)) {
  1020. let sessionTerminate
  1021. = $iq({
  1022. to: this.peerjid,
  1023. type: 'set'
  1024. })
  1025. .c('jingle', {
  1026. xmlns: 'urn:xmpp:jingle:1',
  1027. action: 'session-terminate',
  1028. initiator: this.initiator,
  1029. sid: this.sid
  1030. })
  1031. .c('reason')
  1032. .c((options && options.reason) || 'success');
  1033. if (options && options.reasonDescription) {
  1034. sessionTerminate.up()
  1035. .c('text')
  1036. .t(options.reasonDescription);
  1037. }
  1038. // Calling tree() to print something useful
  1039. sessionTerminate = sessionTerminate.tree();
  1040. logger.info('Sending session-terminate', sessionTerminate);
  1041. this.connection.sendIQ(
  1042. sessionTerminate,
  1043. success,
  1044. this.newJingleErrorHandler(sessionTerminate, failure),
  1045. IQ_TIMEOUT);
  1046. } else {
  1047. logger.info(`Skipped sending session-terminate for ${this}`);
  1048. }
  1049. // this should result in 'onTerminated' being called by strope.jingle.js
  1050. this.connection.jingle.terminate(this.sid);
  1051. }
  1052. /**
  1053. *
  1054. * @param reasonCondition
  1055. * @param reasonText
  1056. */
  1057. onTerminated(reasonCondition, reasonText) {
  1058. this.state = JingleSessionState.ENDED;
  1059. this.establishmentDuration = undefined;
  1060. // Do something with reason and reasonCondition when we start to care
  1061. // this.reasonCondition = reasonCondition;
  1062. // this.reasonText = reasonText;
  1063. logger.info(`Session terminated ${this}`, reasonCondition, reasonText);
  1064. this.close();
  1065. }
  1066. /**
  1067. * Parse the information from the xml sourceAddElem and translate it
  1068. * into sdp lines
  1069. * @param {jquery xml element} sourceAddElem the source-add
  1070. * element from jingle
  1071. * @param {SDP object} currentRemoteSdp the current remote
  1072. * sdp (as of this new source-add)
  1073. * @returns {list} a list of SDP line strings that should
  1074. * be added to the remote SDP
  1075. */
  1076. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1077. const addSsrcInfo = [];
  1078. $(sourceAddElem).each((i1, content) => {
  1079. const name = $(content).attr('name');
  1080. let lines = '';
  1081. $(content)
  1082. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1083. .each(function() {
  1084. // eslint-disable-next-line no-invalid-this
  1085. const semantics = this.getAttribute('semantics');
  1086. const ssrcs
  1087. = $(this) // eslint-disable-line no-invalid-this
  1088. .find('>source')
  1089. .map(function() {
  1090. // eslint-disable-next-line no-invalid-this
  1091. return this.getAttribute('ssrc');
  1092. })
  1093. .get();
  1094. if (ssrcs.length) {
  1095. lines
  1096. += `a=ssrc-group:${semantics} ${
  1097. ssrcs.join(' ')}\r\n`;
  1098. }
  1099. });
  1100. // handles both >source and >description>source
  1101. const tmp
  1102. = $(content).find(
  1103. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1104. /* eslint-disable no-invalid-this */
  1105. tmp.each(function() {
  1106. const ssrc = $(this).attr('ssrc');
  1107. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1108. logger.warn(
  1109. `Source-add request for existing SSRC: ${ssrc}`);
  1110. return;
  1111. }
  1112. // eslint-disable-next-line newline-per-chained-call
  1113. $(this).find('>parameter').each(function() {
  1114. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1115. if ($(this).attr('value') && $(this).attr('value').length) {
  1116. lines += `:${$(this).attr('value')}`;
  1117. }
  1118. lines += '\r\n';
  1119. });
  1120. });
  1121. /* eslint-enable no-invalid-this */
  1122. currentRemoteSdp.media.forEach((media, i2) => {
  1123. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1124. return;
  1125. }
  1126. if (!addSsrcInfo[i2]) {
  1127. addSsrcInfo[i2] = '';
  1128. }
  1129. addSsrcInfo[i2] += lines;
  1130. });
  1131. });
  1132. return addSsrcInfo;
  1133. }
  1134. /**
  1135. * Handles a Jingle source-add message for this Jingle session.
  1136. * @param elem An array of Jingle "content" elements.
  1137. */
  1138. addRemoteStream(elem) {
  1139. this._addOrRemoveRemoteStream(true /* add */, elem);
  1140. }
  1141. /**
  1142. * Handles a Jingle source-remove message for this Jingle session.
  1143. * @param elem An array of Jingle "content" elements.
  1144. */
  1145. removeRemoteStream(elem) {
  1146. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1147. }
  1148. /**
  1149. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1150. * Jingle session.
  1151. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1152. * otherwise.
  1153. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1154. * @private
  1155. */
  1156. _addOrRemoveRemoteStream(isAdd, elem) {
  1157. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1158. if (isAdd) {
  1159. this.readSsrcInfo(elem);
  1160. }
  1161. const workFunction = finishedCallback => {
  1162. if (!this.peerconnection.localDescription
  1163. || !this.peerconnection.localDescription.sdp) {
  1164. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1165. logger.error(errMsg);
  1166. finishedCallback(errMsg);
  1167. return;
  1168. }
  1169. logger.log(`Processing ${logPrefix}`);
  1170. logger.log(
  1171. 'ICE connection state: ',
  1172. this.peerconnection.iceConnectionState);
  1173. const oldLocalSdp
  1174. = new SDP(this.peerconnection.localDescription.sdp);
  1175. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1176. const addOrRemoveSsrcInfo
  1177. = isAdd
  1178. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1179. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1180. const newRemoteSdp
  1181. = isAdd
  1182. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1183. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1184. this._renegotiate(newRemoteSdp.raw)
  1185. .then(() => {
  1186. const newLocalSdp
  1187. = new SDP(this.peerconnection.localDescription.sdp);
  1188. logger.log(
  1189. `${logPrefix} - OK, SDPs: `, oldLocalSdp, newLocalSdp);
  1190. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1191. finishedCallback();
  1192. }, error => {
  1193. logger.error(`${logPrefix} failed:`, error);
  1194. finishedCallback(error);
  1195. });
  1196. };
  1197. // Queue and execute
  1198. this.modificationQueue.push(workFunction);
  1199. }
  1200. /**
  1201. * The 'task' function will be given a callback it MUST call with either:
  1202. * 1) No arguments if it was successful or
  1203. * 2) An error argument if there was an error
  1204. * If the task wants to process the success or failure of the task, it
  1205. * should pass a handler to the .push function, e.g.:
  1206. * queue.push(task, (err) => {
  1207. * if (err) {
  1208. * // error handling
  1209. * } else {
  1210. * // success handling
  1211. * }
  1212. * });
  1213. */
  1214. _processQueueTasks(task, finishedCallback) {
  1215. task(finishedCallback);
  1216. }
  1217. /**
  1218. * Takes in a jingle offer iq, returns the new sdp offer
  1219. * @param {jquery xml element} offerIq the incoming offer
  1220. * @returns {SDP object} the jingle offer translated to SDP
  1221. */
  1222. _processNewJingleOfferIq(offerIq) {
  1223. const remoteSdp = new SDP('');
  1224. if (this.webrtcIceTcpDisable) {
  1225. remoteSdp.removeTcpCandidates = true;
  1226. }
  1227. if (this.webrtcIceUdpDisable) {
  1228. remoteSdp.removeUdpCandidates = true;
  1229. }
  1230. if (this.failICE) {
  1231. remoteSdp.failICE = true;
  1232. }
  1233. remoteSdp.fromJingle(offerIq);
  1234. this.readSsrcInfo($(offerIq).find('>content'));
  1235. return remoteSdp;
  1236. }
  1237. /**
  1238. * Remove the given ssrc lines from the current remote sdp
  1239. * @param {list} removeSsrcInfo a list of SDP line strings that
  1240. * should be removed from the remote SDP
  1241. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1242. * in removeSsrcInfo
  1243. */
  1244. _processRemoteRemoveSource(removeSsrcInfo) {
  1245. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1246. removeSsrcInfo.forEach((lines, idx) => {
  1247. // eslint-disable-next-line no-param-reassign
  1248. lines = lines.split('\r\n');
  1249. lines.pop(); // remove empty last element;
  1250. lines.forEach(line => {
  1251. remoteSdp.media[idx]
  1252. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1253. });
  1254. });
  1255. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1256. return remoteSdp;
  1257. }
  1258. /**
  1259. * Add the given ssrc lines to the current remote sdp
  1260. * @param {list} addSsrcInfo a list of SDP line strings that
  1261. * should be added to the remote SDP
  1262. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1263. * in removeSsrcInfo
  1264. */
  1265. _processRemoteAddSource(addSsrcInfo) {
  1266. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1267. addSsrcInfo.forEach((lines, idx) => {
  1268. remoteSdp.media[idx] += lines;
  1269. });
  1270. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1271. return remoteSdp;
  1272. }
  1273. /**
  1274. * Do a new o/a flow using the existing remote description
  1275. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1276. * to use. If not provided, the remote sdp from the
  1277. * peerconnection will be used
  1278. * @returns {Promise} promise which resolves when the
  1279. * o/a flow is complete with no arguments or
  1280. * rejects with an error {string}
  1281. */
  1282. _renegotiate(optionalRemoteSdp) {
  1283. const remoteSdp
  1284. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1285. if (!remoteSdp) {
  1286. return Promise.reject(
  1287. 'Can not renegotiate without remote description,'
  1288. + `- current state: ${this.state}`);
  1289. }
  1290. const remoteDescription = new RTCSessionDescription({
  1291. type: this.isInitiator ? 'answer' : 'offer',
  1292. sdp: remoteSdp
  1293. });
  1294. return new Promise((resolve, reject) => {
  1295. if (this.peerconnection.signalingState === 'closed') {
  1296. reject('Attempted to renegotiate in state closed');
  1297. return;
  1298. }
  1299. if (this.isInitiator) {
  1300. this._initiatorRenegotiate(remoteDescription, resolve, reject);
  1301. } else {
  1302. this._responderRenegotiate(remoteDescription, resolve, reject);
  1303. }
  1304. });
  1305. }
  1306. /**
  1307. * Renegotiate cycle implementation for the responder case.
  1308. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1309. * which will be used as remote description in the cycle.
  1310. * @param {function} resolve the success callback
  1311. * @param {function} reject the failure callback
  1312. * @private
  1313. */
  1314. _responderRenegotiate(remoteDescription, resolve, reject) {
  1315. // FIXME use WebRTC promise API to simplify things
  1316. logger.debug('Renegotiate: setting remote description');
  1317. this.peerconnection.setRemoteDescription(
  1318. remoteDescription,
  1319. () => {
  1320. logger.debug('Renegotiate: creating answer');
  1321. this.peerconnection.createAnswer(
  1322. answer => {
  1323. logger.debug('Renegotiate: setting local description');
  1324. this.peerconnection.setLocalDescription(
  1325. answer,
  1326. () => {
  1327. resolve();
  1328. },
  1329. error => {
  1330. reject(
  1331. `setLocalDescription failed: ${error}`);
  1332. }
  1333. );
  1334. },
  1335. error => reject(`createAnswer failed: ${error}`),
  1336. this.mediaConstraints
  1337. );
  1338. },
  1339. error => reject(`setRemoteDescription failed: ${error}`)
  1340. );
  1341. }
  1342. /**
  1343. * Renegotiate cycle implementation for the initiator's case.
  1344. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1345. * which will be used as remote description in the cycle.
  1346. * @param {function} resolve the success callback
  1347. * @param {function} reject the failure callback
  1348. * @private
  1349. */
  1350. _initiatorRenegotiate(remoteDescription, resolve, reject) {
  1351. // FIXME use WebRTC promise API to simplify things
  1352. if (this.peerconnection.signalingState === 'have-local-offer') {
  1353. // Skip createOffer and setLocalDescription or FF will fail
  1354. logger.debug(
  1355. 'Renegotiate: setting remote description');
  1356. this.peerconnection.setRemoteDescription(
  1357. remoteDescription,
  1358. () => {
  1359. // In case when the answer is being set for the first time,
  1360. // full sRD/sLD cycle is required to have the local
  1361. // description updated and SSRCs synchronized correctly.
  1362. // Otherwise SSRCs for streams added after invite, but
  1363. // before the answer was accepted will not be detected.
  1364. // The reason for that is that renegotiate can not be called
  1365. // when adding tracks and they will not be reflected in
  1366. // the local SDP.
  1367. this._initiatorRenegotiate(
  1368. remoteDescription, resolve, reject);
  1369. },
  1370. error => reject(`setRemoteDescription failed: ${error}`)
  1371. );
  1372. } else {
  1373. logger.debug('Renegotiate: creating offer');
  1374. this.peerconnection.createOffer(
  1375. offer => {
  1376. logger.debug('Renegotiate: setting local description');
  1377. this.peerconnection.setLocalDescription(offer,
  1378. () => {
  1379. logger.debug(
  1380. 'Renegotiate: setting remote description');
  1381. this.peerconnection.setRemoteDescription(
  1382. remoteDescription,
  1383. () => {
  1384. resolve();
  1385. },
  1386. error => reject(
  1387. `setRemoteDescription failed: ${error}`)
  1388. );
  1389. },
  1390. error => {
  1391. reject('setLocalDescription failed: ', error);
  1392. });
  1393. },
  1394. error => reject(`createOffer failed: ${error}`),
  1395. this.mediaConstraints);
  1396. }
  1397. }
  1398. /**
  1399. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1400. * offer/answer cycle after both operations are done. Either
  1401. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1402. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1403. * <tt>oldTrack</tt>
  1404. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1405. * replaced
  1406. * @param {JitsiLocalTrack|null} newTrack the new track to use
  1407. * @returns {Promise} which resolves once the replacement is complete
  1408. * with no arguments or rejects with an error {string}
  1409. */
  1410. replaceTrack(oldTrack, newTrack) {
  1411. const workFunction = finishedCallback => {
  1412. // Check if the connection was closed and pretend everything is OK.
  1413. // This can happen if a track removal is scheduled but takes place
  1414. // after the connection is closed.
  1415. if (this.peerconnection.signalingState === 'closed'
  1416. || this.peerconnection.connectionState === 'closed'
  1417. || this.closed) {
  1418. finishedCallback();
  1419. return;
  1420. }
  1421. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1422. // NOTE the code below assumes that no more than 1 video track
  1423. // can be added to the peer connection.
  1424. // Transition from no video to video (possibly screen sharing)
  1425. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  1426. // Clearing current primary SSRC will make
  1427. // the SdpConsistency generate a new one which will result
  1428. // with:
  1429. // 1. source-remove for the recvonly
  1430. // 2. source-add for the new video stream
  1431. this.peerconnection.clearRecvonlySsrc();
  1432. // Transition from video to no video
  1433. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  1434. // Clearing current primary SSRC and generating the recvonly
  1435. // will result in:
  1436. // 1. source-remove for the old video stream
  1437. // 2. source-add for the recvonly stream
  1438. this.peerconnection.clearRecvonlySsrc();
  1439. this.peerconnection.generateRecvonlySsrc();
  1440. }
  1441. if (oldTrack) {
  1442. this.peerconnection.removeTrack(oldTrack);
  1443. }
  1444. if (newTrack) {
  1445. this.peerconnection.addTrack(newTrack);
  1446. }
  1447. if ((oldTrack || newTrack)
  1448. && this.state === JingleSessionState.ACTIVE) {
  1449. this._renegotiate()
  1450. .then(() => {
  1451. const newLocalSDP
  1452. = new SDP(
  1453. this.peerconnection.localDescription.sdp);
  1454. this.notifyMySSRCUpdate(
  1455. new SDP(oldLocalSdp), newLocalSDP);
  1456. finishedCallback();
  1457. },
  1458. finishedCallback /* will be called with en error */);
  1459. } else {
  1460. finishedCallback();
  1461. }
  1462. };
  1463. this.modificationQueue.push(
  1464. workFunction,
  1465. error => {
  1466. if (error) {
  1467. logger.error('Replace track error:', error);
  1468. } else {
  1469. logger.info('Replace track done!');
  1470. }
  1471. });
  1472. }
  1473. /**
  1474. * Parse the information from the xml sourceRemoveElem and translate it
  1475. * into sdp lines
  1476. * @param {jquery xml element} sourceRemoveElem the source-remove
  1477. * element from jingle
  1478. * @param {SDP object} currentRemoteSdp the current remote
  1479. * sdp (as of this new source-remove)
  1480. * @returns {list} a list of SDP line strings that should
  1481. * be removed from the remote SDP
  1482. */
  1483. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  1484. const removeSsrcInfo = [];
  1485. $(sourceRemoveElem).each((i1, content) => {
  1486. const name = $(content).attr('name');
  1487. let lines = '';
  1488. $(content)
  1489. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1490. .each(function() {
  1491. /* eslint-disable no-invalid-this */
  1492. const semantics = this.getAttribute('semantics');
  1493. const ssrcs
  1494. = $(this)
  1495. .find('>source')
  1496. .map(function() {
  1497. return this.getAttribute('ssrc');
  1498. })
  1499. .get();
  1500. if (ssrcs.length) {
  1501. lines
  1502. += `a=ssrc-group:${semantics} ${
  1503. ssrcs.join(' ')}\r\n`;
  1504. }
  1505. /* eslint-enable no-invalid-this */
  1506. });
  1507. const ssrcs = [];
  1508. // handles both >source and >description>source versions
  1509. const tmp
  1510. = $(content).find(
  1511. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1512. tmp.each(function() {
  1513. // eslint-disable-next-line no-invalid-this
  1514. const ssrc = $(this).attr('ssrc');
  1515. ssrcs.push(ssrc);
  1516. });
  1517. currentRemoteSdp.media.forEach((media, i2) => {
  1518. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1519. return;
  1520. }
  1521. if (!removeSsrcInfo[i2]) {
  1522. removeSsrcInfo[i2] = '';
  1523. }
  1524. ssrcs.forEach(ssrc => {
  1525. const ssrcLines
  1526. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  1527. if (ssrcLines.length) {
  1528. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  1529. }
  1530. });
  1531. removeSsrcInfo[i2] += lines;
  1532. });
  1533. });
  1534. return removeSsrcInfo;
  1535. }
  1536. /**
  1537. * Will print an error if there is any difference, between the SSRCs given
  1538. * in the <tt>oldSDP</tt> and the ones currently described in
  1539. * the peerconnection's local description.
  1540. * @param {string} operationName the operation's name which will be printed
  1541. * in the error message.
  1542. * @param {SDP} oldSDP the old local SDP which will be compared with
  1543. * the current one.
  1544. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  1545. * otherwise.
  1546. * @private
  1547. */
  1548. _verifyNoSSRCChanged(operationName, oldSDP) {
  1549. const currentLocalSDP
  1550. = new SDP(this.peerconnection.localDescription.sdp);
  1551. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  1552. const addedMedia = sdpDiff.getNewMedia();
  1553. if (Object.keys(addedMedia).length) {
  1554. logger.error(
  1555. `${this} - some SSRC were added on ${operationName}`,
  1556. addedMedia);
  1557. return false;
  1558. }
  1559. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  1560. const removedMedia = sdpDiff.getNewMedia();
  1561. if (Object.keys(removedMedia).length) {
  1562. logger.error(
  1563. `${this} - some SSRCs were removed on ${operationName}`,
  1564. removedMedia);
  1565. return false;
  1566. }
  1567. return true;
  1568. }
  1569. /**
  1570. * Adds local track back to this session, as part of the unmute operation.
  1571. * @param {JitsiLocalTrack} track
  1572. * @return {Promise} a promise that will resolve once the local track is
  1573. * added back to this session and renegotiation succeeds. Will be rejected
  1574. * with a <tt>string</tt> that provides some error details in case something
  1575. * goes wrong.
  1576. */
  1577. addTrackAsUnmute(track) {
  1578. return this._addRemoveTrackAsMuteUnmute(
  1579. false /* add as unmute */, track);
  1580. }
  1581. /**
  1582. * Remove local track as part of the mute operation.
  1583. * @param {JitsiLocalTrack} track the local track to be removed
  1584. * @return {Promise} a promise which will be resolved once the local track
  1585. * is removed from this session and the renegotiation is performed.
  1586. * The promise will be rejected with a <tt>string</tt> that the describes
  1587. * the error if anything goes wrong.
  1588. */
  1589. removeTrackAsMute(track) {
  1590. return this._addRemoveTrackAsMuteUnmute(
  1591. true /* remove as mute */, track);
  1592. }
  1593. /**
  1594. * See {@link addTrackAsUnmute} and {@link removeTrackAsMute}.
  1595. * @param {boolean} isMute <tt>true</tt> for "remove as mute" or
  1596. * <tt>false</tt> for "add as unmute".
  1597. * @param {JitsiLocalTrack} track the track that will be added/removed
  1598. * @private
  1599. */
  1600. _addRemoveTrackAsMuteUnmute(isMute, track) {
  1601. if (!track) {
  1602. return Promise.reject('invalid "track" argument value');
  1603. }
  1604. const operationName = isMute ? 'removeTrackMute' : 'addTrackUnmute';
  1605. const workFunction = finishedCallback => {
  1606. const tpc = this.peerconnection;
  1607. if (!tpc) {
  1608. finishedCallback(
  1609. `Error: tried ${operationName} track with no active peer`
  1610. + 'connection');
  1611. return;
  1612. }
  1613. const oldLocalSDP = tpc.localDescription.sdp;
  1614. const tpcOperation
  1615. = isMute
  1616. ? tpc.removeTrackMute.bind(tpc, track)
  1617. : tpc.addTrackUnmute.bind(tpc, track);
  1618. if (!tpcOperation()) {
  1619. finishedCallback(`${operationName} failed!`);
  1620. } else if (!oldLocalSDP || !tpc.remoteDescription.sdp) {
  1621. finishedCallback();
  1622. } else {
  1623. this._renegotiate()
  1624. .then(() => {
  1625. // The results are ignored, as this check failure is not
  1626. // enough to fail the whole operation. It will log
  1627. // an error inside.
  1628. this._verifyNoSSRCChanged(
  1629. operationName, new SDP(oldLocalSDP));
  1630. finishedCallback();
  1631. },
  1632. finishedCallback /* will be called with an error */);
  1633. }
  1634. };
  1635. return new Promise((resolve, reject) => {
  1636. this.modificationQueue.push(
  1637. workFunction,
  1638. error => {
  1639. if (error) {
  1640. reject(error);
  1641. } else {
  1642. resolve();
  1643. }
  1644. });
  1645. });
  1646. }
  1647. /**
  1648. * Resumes or suspends media transfer over the underlying peer connection.
  1649. * @param {boolean} audioActive <tt>true</tt> to enable audio media
  1650. * transfer or <tt>false</tt> to suspend audio media transmission.
  1651. * @param {boolean} videoActive <tt>true</tt> to enable video media
  1652. * transfer or <tt>false</tt> to suspend video media transmission.
  1653. * @return {Promise} a <tt>Promise</tt> which will resolve once
  1654. * the operation is done. It will be rejected with an error description as
  1655. * a string in case anything goes wrong.
  1656. */
  1657. setMediaTransferActive(audioActive, videoActive) {
  1658. if (!this.peerconnection) {
  1659. return Promise.reject(
  1660. 'Can not modify transfer active state,'
  1661. + ' before "initialize" is called');
  1662. }
  1663. const logAudioStr = audioActive ? 'audio active' : 'audio inactive';
  1664. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  1665. logger.info(`Queued make ${logVideoStr}, ${logAudioStr} task...`);
  1666. const workFunction = finishedCallback => {
  1667. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  1668. // Because the value is modified on the queue it's impossible to
  1669. // check it's final value reliably prior to submitting the task.
  1670. // The rule here is that the last submitted state counts.
  1671. // Check the values here to avoid unnecessary renegotiation cycle.
  1672. const audioActiveChanged
  1673. = this.peerconnection.setAudioTransferActive(audioActive);
  1674. if (this._localVideoActive !== videoActive) {
  1675. this._localVideoActive = videoActive;
  1676. // Do only for P2P - Jicofo will reply with 'bad-request'
  1677. // We don't want to send 'content-modify', before the initial
  1678. // O/A (state === JingleSessionState.ACTIVE), because that will
  1679. // mess up video media direction in the remote SDP.
  1680. // 'content-modify' when processed only affects the media
  1681. // direction in the local SDP. We're doing that, because setting
  1682. // 'inactive' on video media in remote SDP will mess up our SDP
  1683. // translation chain (simulcast, RTX, video mute etc.).
  1684. if (this.isP2P && isSessionActive) {
  1685. this.sendContentModify(videoActive);
  1686. }
  1687. }
  1688. const pcVideoActiveChanged
  1689. = this.peerconnection.setVideoTransferActive(
  1690. this._localVideoActive && this._remoteVideoActive);
  1691. // Will do the sRD/sLD cycle to update SDPs and adjust the media
  1692. // direction
  1693. if (isSessionActive
  1694. && (audioActiveChanged || pcVideoActiveChanged)) {
  1695. this._renegotiate()
  1696. .then(
  1697. finishedCallback,
  1698. finishedCallback /* will be called with an error */);
  1699. } else {
  1700. finishedCallback();
  1701. }
  1702. };
  1703. return new Promise((resolve, reject) => {
  1704. this.modificationQueue.push(
  1705. workFunction,
  1706. error => {
  1707. if (error) {
  1708. reject(error);
  1709. } else {
  1710. resolve();
  1711. }
  1712. });
  1713. });
  1714. }
  1715. /**
  1716. * Will put and execute on the queue a session modify task. Currently it
  1717. * only checks the senders attribute of the video content in order to figure
  1718. * out if the remote peer has video in the inactive state (stored locally
  1719. * in {@link _remoteVideoActive} - see field description for more info).
  1720. * @param {jQuery} jingleContents jQuery selector pointing to the jingle
  1721. * element of the session modify IQ.
  1722. * @see {@link _remoteVideoActive}
  1723. * @see {@link _localVideoActive}
  1724. */
  1725. modifyContents(jingleContents) {
  1726. const newVideoSenders
  1727. = JingleSessionPC.parseVideoSenders(jingleContents);
  1728. if (newVideoSenders === null) {
  1729. logger.error(
  1730. `${this} - failed to parse video "senders" attribute in`
  1731. + '"content-modify" action');
  1732. return;
  1733. }
  1734. const workFunction = finishedCallback => {
  1735. if (this._assertNotEnded('content-modify')
  1736. && this._modifyRemoteVideoActive(newVideoSenders)) {
  1737. // Will do the sRD/sLD cycle to update SDPs and adjust
  1738. // the media direction
  1739. this._renegotiate()
  1740. .then(finishedCallback, finishedCallback /* (error) */);
  1741. } else {
  1742. finishedCallback();
  1743. }
  1744. };
  1745. logger.debug(
  1746. `${this} queued "content-modify" task`
  1747. + `(video senders="${newVideoSenders}")`);
  1748. this.modificationQueue.push(
  1749. workFunction,
  1750. error => {
  1751. if (error) {
  1752. logger.error('"content-modify" failed', error);
  1753. }
  1754. });
  1755. }
  1756. /**
  1757. * Processes new value of remote video "senders" Jingle attribute and tries
  1758. * to apply it for {@link _remoteVideoActive}.
  1759. * @param {string} remoteVideoSenders the value of "senders" attribute of
  1760. * Jingle video content element advertised by remote peer.
  1761. * @return {boolean} <tt>true</tt> if the change affected state of
  1762. * the underlying peerconnection and renegotiation is required for
  1763. * the changes to take effect.
  1764. * @private
  1765. */
  1766. _modifyRemoteVideoActive(remoteVideoSenders) {
  1767. const isRemoteVideoActive
  1768. = remoteVideoSenders === 'both'
  1769. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  1770. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  1771. if (isRemoteVideoActive !== this._remoteVideoActive) {
  1772. logger.debug(
  1773. `${this} new remote video active: ${isRemoteVideoActive}`);
  1774. this._remoteVideoActive = isRemoteVideoActive;
  1775. }
  1776. return this.peerconnection.setVideoTransferActive(
  1777. this._localVideoActive && this._remoteVideoActive);
  1778. }
  1779. /**
  1780. * Figures out added/removed ssrcs and send update IQs.
  1781. * @param oldSDP SDP object for old description.
  1782. * @param newSDP SDP object for new description.
  1783. */
  1784. notifyMySSRCUpdate(oldSDP, newSDP) {
  1785. if (this.state !== JingleSessionState.ACTIVE) {
  1786. logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
  1787. return;
  1788. }
  1789. // send source-remove IQ.
  1790. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  1791. const remove = $iq({ to: this.peerjid,
  1792. type: 'set' })
  1793. .c('jingle', {
  1794. xmlns: 'urn:xmpp:jingle:1',
  1795. action: 'source-remove',
  1796. initiator: this.initiator,
  1797. sid: this.sid
  1798. }
  1799. );
  1800. const removedAnySSRCs = sdpDiffer.toJingle(remove);
  1801. if (removedAnySSRCs) {
  1802. logger.info('Sending source-remove', remove.tree());
  1803. this.connection.sendIQ(
  1804. remove, null,
  1805. this.newJingleErrorHandler(remove, error => {
  1806. GlobalOnErrorHandler.callErrorHandler(
  1807. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1808. }), IQ_TIMEOUT);
  1809. } else {
  1810. logger.log('removal not necessary');
  1811. }
  1812. // send source-add IQ.
  1813. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  1814. const add = $iq({ to: this.peerjid,
  1815. type: 'set' })
  1816. .c('jingle', {
  1817. xmlns: 'urn:xmpp:jingle:1',
  1818. action: 'source-add',
  1819. initiator: this.initiator,
  1820. sid: this.sid
  1821. }
  1822. );
  1823. const containsNewSSRCs = sdpDiffer.toJingle(add);
  1824. if (containsNewSSRCs) {
  1825. logger.info('Sending source-add', add.tree());
  1826. this.connection.sendIQ(
  1827. add, null, this.newJingleErrorHandler(add, error => {
  1828. GlobalOnErrorHandler.callErrorHandler(
  1829. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1830. }), IQ_TIMEOUT);
  1831. } else {
  1832. logger.log('addition not necessary');
  1833. }
  1834. }
  1835. /**
  1836. * Method returns function(errorResponse) which is a callback to be passed
  1837. * to Strophe connection.sendIQ method. An 'error' structure is created that
  1838. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1839. * structure is as follows:
  1840. * {
  1841. * code: {XMPP error response code}
  1842. * reason: {the name of XMPP error reason element or 'timeout' if the
  1843. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1844. * source: {request.tree() that provides original request}
  1845. * session: {this JingleSessionPC.toString()}
  1846. * }
  1847. * @param request Strophe IQ instance which is the request to be dumped into
  1848. * the error structure
  1849. * @param failureCb function(error) called when error response was returned
  1850. * or when a timeout has occurred.
  1851. * @returns {function(this:JingleSessionPC)}
  1852. */
  1853. newJingleErrorHandler(request, failureCb) {
  1854. return errResponse => {
  1855. const error = {};
  1856. // Get XMPP error code and condition(reason)
  1857. const errorElSel = $(errResponse).find('error');
  1858. if (errorElSel.length) {
  1859. error.code = errorElSel.attr('code');
  1860. const errorReasonSel = $(errResponse).find('error :first');
  1861. if (errorReasonSel.length) {
  1862. error.reason = errorReasonSel[0].tagName;
  1863. }
  1864. }
  1865. if (!errResponse) {
  1866. error.reason = 'timeout';
  1867. }
  1868. error.source = request;
  1869. if (request && typeof request.tree === 'function') {
  1870. error.source = request.tree();
  1871. }
  1872. if (error.source && error.source.outerHTML) {
  1873. error.source = error.source.outerHTML;
  1874. }
  1875. error.session = this.toString();
  1876. if (failureCb) {
  1877. failureCb(error);
  1878. } else if (this.state === JingleSessionState.ENDED
  1879. && error.reason === 'item-not-found') {
  1880. // When remote peer decides to terminate the session, but it
  1881. // still have few messages on the queue for processing,
  1882. // it will first send us 'session-terminate' (we enter ENDED)
  1883. // and then follow with 'item-not-found' for the queued requests
  1884. // We don't want to have that logged on error level.
  1885. logger.debug('Jingle error', error);
  1886. } else {
  1887. GlobalOnErrorHandler.callErrorHandler(
  1888. new Error(`Jingle error: ${JSON.stringify(error)}`));
  1889. }
  1890. };
  1891. }
  1892. /**
  1893. *
  1894. * @param session
  1895. * @param error
  1896. */
  1897. static onJingleFatalError(session, error) {
  1898. if (this.room) {
  1899. this.room.eventEmitter.emit(
  1900. XMPPEvents.CONFERENCE_SETUP_FAILED, session, error);
  1901. this.room.eventEmitter.emit(
  1902. XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1903. }
  1904. }
  1905. /**
  1906. * Returns the ice connection state for the peer connection.
  1907. * @returns the ice connection state for the peer connection.
  1908. */
  1909. getIceConnectionState() {
  1910. return this.peerconnection.iceConnectionState;
  1911. }
  1912. /**
  1913. * Closes the peerconnection.
  1914. */
  1915. close() {
  1916. this.closed = true;
  1917. // The signaling layer will remove it's listeners
  1918. this.signalingLayer.setChatRoom(null);
  1919. // do not try to close if already closed.
  1920. this.peerconnection
  1921. && ((this.peerconnection.signalingState
  1922. && this.peerconnection.signalingState !== 'closed')
  1923. || (this.peerconnection.connectionState
  1924. && this.peerconnection.connectionState !== 'closed'))
  1925. && this.peerconnection.close();
  1926. }
  1927. /**
  1928. * Converts to string with minor summary.
  1929. * @return {string}
  1930. */
  1931. toString() {
  1932. return `JingleSessionPC[p2p=${this.isP2P},`
  1933. + `initiator=${this.isInitiator},sid=${this.sid}]`;
  1934. }
  1935. }