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

JingleSessionPC.js 68KB

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