modified lib-jitsi-meet dev repo
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 69KB

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