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 66KB

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