You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 71KB

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