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

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