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

JingleSessionPC.js 104KB

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