You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 107KB

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