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

JingleSessionPC.js 83KB

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