modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 103KB

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