Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JingleSessionPC.js 90KB

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