Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JingleSessionPC.js 109KB

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