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

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