You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 84KB

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