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

JingleSessionPC.js 105KB

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