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

JingleSessionPC.js 84KB

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