You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 101KB

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