modified lib-jitsi-meet dev repo
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JingleSessionPC.js 68KB

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