modified lib-jitsi-meet dev repo
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 82KB

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