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 109KB

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