Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 83KB

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