您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 80KB

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