選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JingleSessionPC.js 107KB

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