modified lib-jitsi-meet dev repo
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

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