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

JingleSessionPC.js 84KB

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