Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JingleSessionPC.js 65KB

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