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 86KB

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