modified lib-jitsi-meet dev repo
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 103KB

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