Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JingleSessionPC.js 99KB

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