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

JingleSessionPC.js 65KB

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