Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JingleSessionPC.js 81KB

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