您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 104KB

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