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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709
  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 ?? true
  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 connection state event is fired whenever the aggregate of underlying
  498. * transports change their state.
  499. */
  500. this.peerconnection.onconnectionstatechange = () => {
  501. const icestate = this.peerconnection.iceConnectionState;
  502. switch (this.peerconnection.connectionState) {
  503. case 'failed':
  504. // Since version 76 Chrome no longer switches ICE connection
  505. // state to failed (see
  506. // https://bugs.chromium.org/p/chromium/issues/detail?id=982793
  507. // for details) we use this workaround to recover from lost connections
  508. if (icestate === 'disconnected') {
  509. this.room.eventEmitter.emit(
  510. XMPPEvents.CONNECTION_ICE_FAILED, this);
  511. }
  512. break;
  513. }
  514. };
  515. /**
  516. * The negotiationneeded event is fired whenever we shake the media on the
  517. * RTCPeerConnection object.
  518. */
  519. this.peerconnection.onnegotiationneeded = () => {
  520. const state = this.peerconnection.signalingState;
  521. const remoteDescription = this.peerconnection.remoteDescription;
  522. if (this.usesUnifiedPlan && state === 'stable'
  523. && remoteDescription && typeof remoteDescription.sdp === 'string') {
  524. logger.debug(`${this} onnegotiationneeded fired on ${this.peerconnection} in state: ${state}`);
  525. const workFunction = finishedCallback => {
  526. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  527. this._renegotiate()
  528. .then(() => {
  529. const newSdp = new SDP(this.peerconnection.localDescription.sdp);
  530. this.notifyMySSRCUpdate(oldSdp, newSdp);
  531. finishedCallback();
  532. },
  533. finishedCallback /* will be called with en error */);
  534. };
  535. this.modificationQueue.push(
  536. workFunction,
  537. error => {
  538. if (error) {
  539. logger.error(`${this} onnegotiationneeded error`, error);
  540. } else {
  541. logger.debug(`${this} onnegotiationneeded executed - OK`);
  542. }
  543. });
  544. }
  545. };
  546. // The signaling layer will bind it's listeners at this point
  547. this.signalingLayer.setChatRoom(this.room);
  548. }
  549. /**
  550. * Remote preference for receive video max frame height.
  551. *
  552. * @returns {Number|undefined}
  553. */
  554. getRemoteRecvMaxFrameHeight() {
  555. if (this.isP2P) {
  556. return this.remoteRecvMaxFrameHeight;
  557. }
  558. return undefined;
  559. }
  560. /**
  561. * Sends given candidate in Jingle 'transport-info' message.
  562. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  563. * @private
  564. */
  565. sendIceCandidate(candidate) {
  566. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  567. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  568. const ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  569. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  570. if (!(ice && jcand)) {
  571. const errorMesssage = 'failed to get ice && jcand';
  572. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  573. logger.error(errorMesssage);
  574. return;
  575. }
  576. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  577. if (this.usedrip) {
  578. if (this.dripContainer.length === 0) {
  579. setTimeout(() => {
  580. if (this.dripContainer.length === 0) {
  581. return;
  582. }
  583. this.sendIceCandidates(this.dripContainer);
  584. this.dripContainer = [];
  585. }, ICE_CAND_GATHERING_TIMEOUT);
  586. }
  587. this.dripContainer.push(candidate);
  588. } else {
  589. this.sendIceCandidates([ candidate ]);
  590. }
  591. } else {
  592. logger.log(`${this} sendIceCandidate: last candidate`);
  593. // FIXME: remember to re-think in ICE-restart
  594. this.lasticecandidate = true;
  595. }
  596. }
  597. /**
  598. * Sends given candidates in Jingle 'transport-info' message.
  599. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE
  600. * candidate instances
  601. * @private
  602. */
  603. sendIceCandidates(candidates) {
  604. if (!this._assertNotEnded('sendIceCandidates')) {
  605. return;
  606. }
  607. logger.log(`${this} sendIceCandidates ${JSON.stringify(candidates)}`);
  608. const cand = $iq({ to: this.remoteJid,
  609. type: 'set' })
  610. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  611. action: 'transport-info',
  612. initiator: this.initiatorJid,
  613. sid: this.sid });
  614. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  615. for (let mid = 0; mid < localSDP.media.length; mid++) {
  616. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  617. const mline
  618. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  619. if (cands.length > 0) {
  620. const ice
  621. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  622. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  623. cand.c('content', {
  624. creator: this.initiatorJid === this.localJid
  625. ? 'initiator' : 'responder',
  626. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  627. }).c('transport', ice);
  628. for (let i = 0; i < cands.length; i++) {
  629. const candidate
  630. = SDPUtil.candidateToJingle(cands[i].candidate);
  631. // Mangle ICE candidate if 'failICE' test option is enabled
  632. if (this.failICE) {
  633. candidate.ip = '1.1.1.1';
  634. }
  635. cand.c('candidate', candidate).up();
  636. }
  637. // add fingerprint
  638. const fingerprintLine
  639. = SDPUtil.findLine(
  640. localSDP.media[mid],
  641. 'a=fingerprint:', localSDP.session);
  642. if (fingerprintLine) {
  643. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  644. tmp.required = true;
  645. cand.c(
  646. 'fingerprint',
  647. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  648. .t(tmp.fingerprint);
  649. delete tmp.fingerprint;
  650. cand.attrs(tmp);
  651. cand.up();
  652. }
  653. cand.up(); // transport
  654. cand.up(); // content
  655. }
  656. }
  657. // might merge last-candidate notification into this, but it is called
  658. // a lot later. See webrtc issue #2340
  659. // logger.log('was this the last candidate', this.lasticecandidate);
  660. this.connection.sendIQ(
  661. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  662. }
  663. /**
  664. * Sends Jingle 'session-info' message which includes custom Jitsi Meet
  665. * 'ice-state' element with the text value 'failed' to let Jicofo know
  666. * that the ICE connection has entered the failed state. It can then
  667. * choose to re-create JVB channels and send 'transport-replace' to
  668. * retry the connection.
  669. */
  670. sendIceFailedNotification() {
  671. const sessionInfo
  672. = $iq({
  673. to: this.remoteJid,
  674. type: 'set' })
  675. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  676. action: 'session-info',
  677. initiator: this.initiatorJid,
  678. sid: this.sid })
  679. .c('ice-state', { xmlns: 'http://jitsi.org/protocol/focus' })
  680. .t('failed')
  681. .up();
  682. this._bridgeSessionId
  683. && sessionInfo.c(
  684. 'bridge-session', {
  685. xmlns: 'http://jitsi.org/protocol/focus',
  686. id: this._bridgeSessionId
  687. });
  688. this.connection.sendIQ2(
  689. sessionInfo, {
  690. /*
  691. * This message will be often sent when there are connectivity
  692. * issues, so make it slightly longer than Prosody's default BOSH
  693. * inactivity timeout of 60 seconds.
  694. */
  695. timeout: 65
  696. })
  697. .catch(this.newJingleErrorHandler(sessionInfo));
  698. }
  699. /**
  700. * {@inheritDoc}
  701. */
  702. addIceCandidates(elem) {
  703. if (this.peerconnection.signalingState === 'closed') {
  704. logger.warn(`${this} Ignored add ICE candidate when in closed state`);
  705. return;
  706. }
  707. const iceCandidates = [];
  708. elem.find('>content>transport>candidate')
  709. .each((idx, candidate) => {
  710. let line = SDPUtil.candidateFromJingle(candidate);
  711. line = line.replace('\r\n', '').replace('a=', '');
  712. // FIXME this code does not care to handle
  713. // non-bundle transport
  714. const rtcCandidate = new RTCIceCandidate({
  715. sdpMLineIndex: 0,
  716. // FF comes up with more complex names like audio-23423,
  717. // Given that it works on both Chrome and FF without
  718. // providing it, let's leave it like this for the time
  719. // being...
  720. // sdpMid: 'audio',
  721. sdpMid: '',
  722. candidate: line
  723. });
  724. iceCandidates.push(rtcCandidate);
  725. });
  726. if (!iceCandidates.length) {
  727. logger.error(`${this} No ICE candidates to add ?`, elem[0] && elem[0].outerHTML);
  728. return;
  729. }
  730. // We want to have this task queued, so that we know it is executed,
  731. // after the initial sRD/sLD offer/answer cycle was done (based on
  732. // the assumption that candidates are spawned after the offer/answer
  733. // and XMPP preserves order).
  734. const workFunction = finishedCallback => {
  735. for (const iceCandidate of iceCandidates) {
  736. this.peerconnection.addIceCandidate(iceCandidate)
  737. .then(
  738. () => logger.debug(`${this} addIceCandidate ok!`),
  739. err => logger.error(`${this} addIceCandidate failed!`, err));
  740. }
  741. finishedCallback();
  742. logger.debug(`${this} ICE candidates task finished`);
  743. };
  744. logger.debug(`${this} Queued add (${iceCandidates.length}) ICE candidates task`);
  745. this.modificationQueue.push(workFunction);
  746. }
  747. /**
  748. *
  749. * @param contents
  750. */
  751. readSsrcInfo(contents) {
  752. const ssrcs
  753. = $(contents).find(
  754. '>description>'
  755. + 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  756. ssrcs.each((i, ssrcElement) => {
  757. const ssrc = Number(ssrcElement.getAttribute('ssrc'));
  758. if (this.isP2P) {
  759. // In P2P all SSRCs are owner by the remote peer
  760. this.signalingLayer.setSSRCOwner(
  761. ssrc, Strophe.getResourceFromJid(this.remoteJid));
  762. } else {
  763. $(ssrcElement)
  764. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  765. .each((i3, ssrcInfoElement) => {
  766. const owner = ssrcInfoElement.getAttribute('owner');
  767. if (owner && owner.length) {
  768. if (isNaN(ssrc) || ssrc < 0) {
  769. logger.warn(`${this} Invalid SSRC ${ssrc} value received for ${owner}`);
  770. } else {
  771. this.signalingLayer.setSSRCOwner(
  772. ssrc,
  773. Strophe.getResourceFromJid(owner));
  774. }
  775. }
  776. });
  777. }
  778. });
  779. }
  780. /**
  781. * Makes the underlying TraceablePeerConnection generate new SSRC for
  782. * the recvonly video stream.
  783. * @deprecated
  784. */
  785. generateRecvonlySsrc() {
  786. if (this.peerconnection) {
  787. this.peerconnection.generateRecvonlySsrc();
  788. } else {
  789. logger.error(`${this} Unable to generate recvonly SSRC - no peerconnection`);
  790. }
  791. }
  792. /**
  793. * Returns the video codec configured as the preferred codec on the peerconnection.
  794. */
  795. getConfiguredVideoCodec() {
  796. return this.peerconnection.getConfiguredVideoCodec();
  797. }
  798. /* eslint-disable max-params */
  799. /**
  800. * Accepts incoming Jingle 'session-initiate' and should send
  801. * 'session-accept' in result.
  802. * @param jingleOffer jQuery selector pointing to the jingle element of
  803. * the offer IQ
  804. * @param success callback called when we accept incoming session
  805. * successfully and receive RESULT packet to 'session-accept' sent.
  806. * @param failure function(error) called if for any reason we fail to accept
  807. * the incoming offer. 'error' argument can be used to log some details
  808. * about the error.
  809. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
  810. * the local tracks that will be added, before the offer/answer cycle
  811. * executes. We allow the localTracks to optionally be passed in so that
  812. * the addition of the local tracks and the processing of the initial offer
  813. * can all be done atomically. We want to make sure that any other
  814. * operations which originate in the XMPP Jingle messages related with
  815. * this session to be executed with an assumption that the initial
  816. * offer/answer cycle has been executed already.
  817. */
  818. acceptOffer(jingleOffer, success, failure, localTracks) {
  819. this.setOfferAnswerCycle(
  820. jingleOffer,
  821. () => {
  822. // FIXME we may not care about RESULT packet for session-accept
  823. // then we should either call 'success' here immediately or
  824. // modify sendSessionAccept method to do that
  825. this.sendSessionAccept(success, failure);
  826. },
  827. failure,
  828. localTracks);
  829. }
  830. /* eslint-enable max-params */
  831. /**
  832. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  833. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be
  834. * added, before the offer/answer cycle executes (for the local track
  835. * addition to be an atomic operation together with the offer/answer).
  836. */
  837. invite(localTracks = []) {
  838. if (!this.isInitiator) {
  839. throw new Error('Trying to invite from the responder session');
  840. }
  841. const workFunction = finishedCallback => {
  842. const addTracks = [];
  843. for (const localTrack of localTracks) {
  844. addTracks.push(this.peerconnection.addTrack(localTrack, this.isInitiator));
  845. }
  846. Promise.all(addTracks)
  847. .then(() => this.peerconnection.createOffer(this.mediaConstraints))
  848. .then(offerSdp => this.peerconnection.setLocalDescription(offerSdp))
  849. .then(() => {
  850. // NOTE that the offer is obtained from the localDescription getter as it needs to go though
  851. // the transformation chain.
  852. this.sendSessionInitiate(this.peerconnection.localDescription.sdp);
  853. })
  854. .then(() => finishedCallback(), error => finishedCallback(error));
  855. };
  856. logger.debug(`${this} Queued invite task`);
  857. this.modificationQueue.push(
  858. workFunction,
  859. error => {
  860. if (error) {
  861. logger.error(`${this} invite error`, error);
  862. } else {
  863. logger.debug(`${this} invite executed - OK`);
  864. }
  865. });
  866. }
  867. /**
  868. * Sends 'session-initiate' to the remote peer.
  869. *
  870. * NOTE this method is synchronous and we're not waiting for the RESULT
  871. * response which would delay the startup process.
  872. *
  873. * @param {string} offerSdp - The local session description which will be
  874. * used to generate an offer.
  875. * @private
  876. */
  877. sendSessionInitiate(offerSdp) {
  878. let init = $iq({
  879. to: this.remoteJid,
  880. type: 'set'
  881. }).c('jingle', {
  882. xmlns: 'urn:xmpp:jingle:1',
  883. action: 'session-initiate',
  884. initiator: this.initiatorJid,
  885. sid: this.sid
  886. });
  887. new SDP(offerSdp).toJingle(
  888. init,
  889. this.isInitiator ? 'initiator' : 'responder');
  890. init = init.tree();
  891. logger.debug(`${this} Session-initiate: `, init);
  892. this.connection.sendIQ(init,
  893. () => {
  894. logger.info(`${this} Got RESULT for "session-initiate"`);
  895. },
  896. error => {
  897. logger.error(`${this} "session-initiate" error`, error);
  898. },
  899. IQ_TIMEOUT);
  900. }
  901. /**
  902. * Sets the answer received from the remote peer.
  903. * @param jingleAnswer
  904. */
  905. setAnswer(jingleAnswer) {
  906. if (!this.isInitiator) {
  907. throw new Error('Trying to set an answer on the responder session');
  908. }
  909. this.setOfferAnswerCycle(
  910. jingleAnswer,
  911. () => {
  912. logger.info(`${this} setAnswer - succeeded`);
  913. if (this.usesUnifiedPlan && browser.isChromiumBased()) {
  914. // This hack is needed for Chrome to create a decoder for the ssrcs in the remote SDP when
  915. // the local endpoint is the offerer and starts muted.
  916. const remoteSdp = this.peerconnection.remoteDescription.sdp;
  917. const remoteDescription = new RTCSessionDescription({
  918. type: 'offer',
  919. sdp: remoteSdp
  920. });
  921. this._responderRenegotiate(remoteDescription);
  922. }
  923. },
  924. error => {
  925. logger.error(`${this} setAnswer failed: `, error);
  926. });
  927. }
  928. /* eslint-disable max-params */
  929. /**
  930. * This is a setRemoteDescription/setLocalDescription cycle which starts at
  931. * converting Strophe Jingle IQ into remote offer SDP. Once converted
  932. * setRemoteDescription, createAnswer and setLocalDescription calls follow.
  933. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element
  934. * of the offer (or answer) IQ
  935. * @param success callback called when sRD/sLD cycle finishes successfully.
  936. * @param failure callback called with an error object as an argument if we
  937. * fail at any point during setRD, createAnswer, setLD.
  938. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
  939. * the local tracks that will be added, before the offer/answer cycle
  940. * executes (for the local track addition to be an atomic operation together
  941. * with the offer/answer).
  942. */
  943. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks = []) {
  944. const workFunction = finishedCallback => {
  945. const addTracks = [];
  946. for (const track of localTracks) {
  947. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  948. }
  949. const newRemoteSdp
  950. = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  951. const oldLocalSdp
  952. = this.peerconnection.localDescription.sdp;
  953. const bridgeSession
  954. = $(jingleOfferAnswerIq)
  955. .find('>bridge-session['
  956. + 'xmlns="http://jitsi.org/protocol/focus"]');
  957. const bridgeSessionId = bridgeSession.attr('id');
  958. if (bridgeSessionId !== this._bridgeSessionId) {
  959. this._bridgeSessionId = bridgeSessionId;
  960. }
  961. Promise.all(addTracks)
  962. .then(() => this._renegotiate(newRemoteSdp.raw))
  963. .then(() => {
  964. if (this.state === JingleSessionState.PENDING) {
  965. this.state = JingleSessionState.ACTIVE;
  966. // #1 Sync up video transfer active/inactive only after
  967. // the initial O/A cycle. We want to adjust the video
  968. // media direction only in the local SDP and the Jingle
  969. // contents direction included in the initial
  970. // offer/answer is mapped to the remote SDP. Jingle
  971. // 'content-modify' IQ is processed in a way that it
  972. // will only modify local SDP when remote peer is no
  973. // longer interested in receiving video content.
  974. // Changing media direction in the remote SDP will mess
  975. // up our SDP translation chain (simulcast, video mute,
  976. // RTX etc.)
  977. //
  978. // #2 Sends the max frame height if it was set, before the session-initiate/accept
  979. if (this.isP2P
  980. && (!this._localVideoActive || this.localRecvMaxFrameHeight)) {
  981. this.sendContentModify();
  982. }
  983. }
  984. // Old local SDP will be available when we're setting answer
  985. // for the first time, but not when offer and it's fine
  986. // since we're generating an answer now it will contain all
  987. // our SSRCs
  988. if (oldLocalSdp) {
  989. const newLocalSdp
  990. = new SDP(this.peerconnection.localDescription.sdp);
  991. this.notifyMySSRCUpdate(
  992. new SDP(oldLocalSdp), newLocalSdp);
  993. }
  994. })
  995. .then(() => finishedCallback(), error => finishedCallback(error));
  996. };
  997. logger.debug(`${this} Queued setOfferAnswerCycle task`);
  998. this.modificationQueue.push(
  999. workFunction,
  1000. error => {
  1001. if (error) {
  1002. logger.error(`${this} setOfferAnswerCycle task failed: ${error}`);
  1003. failure(error);
  1004. } else {
  1005. logger.debug(`${this} setOfferAnswerCycle task done`);
  1006. success();
  1007. }
  1008. });
  1009. }
  1010. /**
  1011. * Updates the codecs on the peerconnection and initiates a renegotiation for the
  1012. * new codec config to take effect.
  1013. *
  1014. * @param {CodecMimeType} preferred the preferred codec.
  1015. * @param {CodecMimeType} disabled the codec that needs to be disabled.
  1016. */
  1017. setVideoCodecs(preferred = null, disabled = null) {
  1018. const current = this.peerconnection.getConfiguredVideoCodec();
  1019. if (this._assertNotEnded() && preferred !== current) {
  1020. logger.info(`${this} Switching video codec from ${current} to ${preferred}`);
  1021. this.peerconnection.setVideoCodecs(preferred, disabled);
  1022. // Initiate a renegotiate for the codec setting to take effect.
  1023. const workFunction = finishedCallback => {
  1024. this._renegotiate().then(
  1025. () => {
  1026. logger.debug(`${this} setVideoCodecs task is done`);
  1027. return finishedCallback();
  1028. }, error => {
  1029. logger.error(`${this} setVideoCodecs task failed: ${error}`);
  1030. return finishedCallback(error);
  1031. });
  1032. };
  1033. logger.debug(`${this} Queued setVideoCodecs task`);
  1034. // Queue and execute
  1035. this.modificationQueue.push(workFunction);
  1036. }
  1037. }
  1038. /* eslint-enable max-params */
  1039. /**
  1040. * Although it states "replace transport" it does accept full Jingle offer
  1041. * which should contain new ICE transport details.
  1042. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  1043. * transport info.
  1044. * @param success callback called when we succeed to accept new offer.
  1045. * @param failure function(error) called when we fail to accept new offer.
  1046. */
  1047. replaceTransport(jingleOfferElem, success, failure) {
  1048. if (this.options.enableForcedReload) {
  1049. const sdp = new SDP(this.peerconnection.localDescription.sdp);
  1050. this.sendTransportAccept(sdp, success, failure);
  1051. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTARTED, this);
  1052. return;
  1053. }
  1054. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  1055. // We need to first reject the 'data' section to have the SCTP stack
  1056. // cleaned up to signal the known data channel is now invalid. After
  1057. // that the original offer is set to have the SCTP connection
  1058. // established with the new bridge.
  1059. const originalOffer = jingleOfferElem.clone();
  1060. jingleOfferElem
  1061. .find('>content[name=\'data\']')
  1062. .attr('senders', 'rejected');
  1063. // Remove all remote sources in order to reset the client's state
  1064. // for the remote MediaStreams. When a conference is moved to
  1065. // another bridge it will start streaming with a sequence number
  1066. // that is not in sync with the most recently seen by the client.
  1067. // The symptoms include frozen or black video and lots of "failed to
  1068. // unprotect SRTP packets" in Chrome logs.
  1069. jingleOfferElem
  1070. .find('>content>description>source')
  1071. .remove();
  1072. jingleOfferElem
  1073. .find('>content>description>ssrc-group')
  1074. .remove();
  1075. // On the JVB it's not a real ICE restart and all layers are re-initialized from scratch as Jicofo does
  1076. // the restart by re-allocating new channels. Chrome (or WebRTC stack) needs to have the DTLS transport layer
  1077. // reset to start a new handshake with fresh DTLS transport on the bridge. Make it think that the DTLS
  1078. // fingerprint has changed by setting an all zeros key.
  1079. const newFingerprint = jingleOfferElem.find('>content>transport>fingerprint');
  1080. newFingerprint.attr('hash', 'sha-1');
  1081. newFingerprint.text('00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00');
  1082. // First set an offer with a rejected 'data' section
  1083. this.setOfferAnswerCycle(
  1084. jingleOfferElem,
  1085. () => {
  1086. // Now set the original offer(with the 'data' section)
  1087. this.setOfferAnswerCycle(
  1088. originalOffer,
  1089. () => {
  1090. const localSDP
  1091. = new SDP(this.peerconnection.localDescription.sdp);
  1092. this.sendTransportAccept(localSDP, success, failure);
  1093. this.room.eventEmitter.emit(
  1094. XMPPEvents.ICE_RESTART_SUCCESS,
  1095. this,
  1096. originalOffer);
  1097. },
  1098. failure);
  1099. },
  1100. failure
  1101. );
  1102. }
  1103. /**
  1104. * Sends Jingle 'session-accept' message.
  1105. * @param {function()} success callback called when we receive 'RESULT'
  1106. * packet for the 'session-accept'
  1107. * @param {function(error)} failure called when we receive an error response
  1108. * or when the request has timed out.
  1109. * @private
  1110. */
  1111. sendSessionAccept(success, failure) {
  1112. // NOTE: since we're just reading from it, we don't need to be within
  1113. // the modification queue to access the local description
  1114. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1115. const accept = $iq({ to: this.remoteJid,
  1116. type: 'set' })
  1117. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1118. action: 'session-accept',
  1119. initiator: this.initiatorJid,
  1120. responder: this.responderJid,
  1121. sid: this.sid });
  1122. if (this.webrtcIceTcpDisable) {
  1123. localSDP.removeTcpCandidates = true;
  1124. }
  1125. if (this.webrtcIceUdpDisable) {
  1126. localSDP.removeUdpCandidates = true;
  1127. }
  1128. if (this.failICE) {
  1129. localSDP.failICE = true;
  1130. }
  1131. localSDP.toJingle(
  1132. accept,
  1133. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  1134. logger.info(`${this} Sending session-accept`);
  1135. logger.debug(accept.tree());
  1136. this.connection.sendIQ(accept,
  1137. success,
  1138. this.newJingleErrorHandler(accept, error => {
  1139. failure(error);
  1140. // 'session-accept' is a critical timeout and we'll
  1141. // have to restart
  1142. this.room.eventEmitter.emit(
  1143. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1144. }),
  1145. IQ_TIMEOUT);
  1146. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1147. // fingerprint and setup) ASAP in order to start the connection
  1148. // establishment.
  1149. //
  1150. // FIXME Flushing the connection at this point triggers an issue with
  1151. // BOSH request handling in Prosody on slow connections.
  1152. //
  1153. // The problem is that this request will be quite large and it may take
  1154. // time before it reaches Prosody. In the meantime Strophe may decide
  1155. // to send the next one. And it was observed that a small request with
  1156. // 'transport-info' usually follows this one. It does reach Prosody
  1157. // before the previous one was completely received. 'rid' on the server
  1158. // is increased and Prosody ignores the request with 'session-accept'.
  1159. // It will never reach Jicofo and everything in the request table is
  1160. // lost. Removing the flush does not guarantee it will never happen, but
  1161. // makes it much less likely('transport-info' is bundled with
  1162. // 'session-accept' and any immediate requests).
  1163. //
  1164. // this.connection.flush();
  1165. }
  1166. /**
  1167. * Will send 'content-modify' IQ in order to ask the remote peer to
  1168. * either stop or resume sending video media or to adjust sender's video constraints.
  1169. * @private
  1170. */
  1171. sendContentModify() {
  1172. const maxFrameHeight = this.localRecvMaxFrameHeight;
  1173. const senders = this._localVideoActive ? 'both' : 'none';
  1174. let sessionModify
  1175. = $iq({
  1176. to: this.remoteJid,
  1177. type: 'set'
  1178. })
  1179. .c('jingle', {
  1180. xmlns: 'urn:xmpp:jingle:1',
  1181. action: 'content-modify',
  1182. initiator: this.initiatorJid,
  1183. sid: this.sid
  1184. })
  1185. .c('content', {
  1186. name: 'video',
  1187. senders
  1188. });
  1189. if (typeof maxFrameHeight !== 'undefined') {
  1190. sessionModify = sessionModify
  1191. .c('max-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1192. .t(maxFrameHeight);
  1193. }
  1194. logger.info(`${this} sending content-modify, video senders: ${senders}, max frame height: ${maxFrameHeight}`);
  1195. logger.debug(sessionModify.tree());
  1196. this.connection.sendIQ(
  1197. sessionModify,
  1198. null,
  1199. this.newJingleErrorHandler(sessionModify),
  1200. IQ_TIMEOUT);
  1201. }
  1202. /**
  1203. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1204. * the remote party.
  1205. *
  1206. * @param {Number} maxFrameHeight - the new value to set.
  1207. */
  1208. setReceiverVideoConstraint(maxFrameHeight) {
  1209. logger.info(`${this} setReceiverVideoConstraint - max frame height: ${maxFrameHeight}`);
  1210. this.localRecvMaxFrameHeight = maxFrameHeight;
  1211. if (this.isP2P) {
  1212. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1213. // be synced after offer/answer.
  1214. if (this.state === JingleSessionState.ACTIVE) {
  1215. this.sendContentModify();
  1216. }
  1217. } else {
  1218. this.rtc.setReceiverVideoConstraint(maxFrameHeight);
  1219. }
  1220. }
  1221. /**
  1222. * Sends Jingle 'transport-accept' message which is a response to
  1223. * 'transport-replace'.
  1224. * @param localSDP the 'SDP' object with local session description
  1225. * @param success callback called when we receive 'RESULT' packet for
  1226. * 'transport-replace'
  1227. * @param failure function(error) called when we receive an error response
  1228. * or when the request has timed out.
  1229. * @private
  1230. */
  1231. sendTransportAccept(localSDP, success, failure) {
  1232. const transportAccept = $iq({ to: this.remoteJid,
  1233. type: 'set' })
  1234. .c('jingle', {
  1235. xmlns: 'urn:xmpp:jingle:1',
  1236. action: 'transport-accept',
  1237. initiator: this.initiatorJid,
  1238. sid: this.sid
  1239. });
  1240. localSDP.media.forEach((medialines, idx) => {
  1241. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1242. transportAccept.c('content',
  1243. {
  1244. creator:
  1245. this.initiatorJid === this.localJid
  1246. ? 'initiator'
  1247. : 'responder',
  1248. name: mline.media
  1249. }
  1250. );
  1251. localSDP.transportToJingle(idx, transportAccept);
  1252. transportAccept.up();
  1253. });
  1254. logger.info(`${this} Sending transport-accept`);
  1255. logger.debug(transportAccept.tree());
  1256. this.connection.sendIQ(transportAccept,
  1257. success,
  1258. this.newJingleErrorHandler(transportAccept, failure),
  1259. IQ_TIMEOUT);
  1260. }
  1261. /**
  1262. * Sends Jingle 'transport-reject' message which is a response to
  1263. * 'transport-replace'.
  1264. * @param success callback called when we receive 'RESULT' packet for
  1265. * 'transport-replace'
  1266. * @param failure function(error) called when we receive an error response
  1267. * or when the request has timed out.
  1268. *
  1269. * FIXME method should be marked as private, but there's some spaghetti that
  1270. * needs to be fixed prior doing that
  1271. */
  1272. sendTransportReject(success, failure) {
  1273. // Send 'transport-reject', so that the focus will
  1274. // know that we've failed
  1275. const transportReject = $iq({ to: this.remoteJid,
  1276. type: 'set' })
  1277. .c('jingle', {
  1278. xmlns: 'urn:xmpp:jingle:1',
  1279. action: 'transport-reject',
  1280. initiator: this.initiatorJid,
  1281. sid: this.sid
  1282. });
  1283. logger.info(`${this} Sending 'transport-reject'`);
  1284. logger.debug(transportReject.tree());
  1285. this.connection.sendIQ(transportReject,
  1286. success,
  1287. this.newJingleErrorHandler(transportReject, failure),
  1288. IQ_TIMEOUT);
  1289. }
  1290. /**
  1291. * Sets the maximum bitrates on the local video track. Bitrate values from
  1292. * videoQuality settings in config.js will be used for configuring the sender.
  1293. * @returns {Promise<void>} promise that will be resolved when the operation is
  1294. * successful and rejected otherwise.
  1295. */
  1296. setSenderMaxBitrates() {
  1297. if (this._assertNotEnded()) {
  1298. return this.peerconnection.setMaxBitRate();
  1299. }
  1300. return Promise.resolve();
  1301. }
  1302. /**
  1303. * Sets the resolution constraint on the local camera track.
  1304. * @param {number} maxFrameHeight - The user preferred max frame height.
  1305. * @returns {Promise} promise that will be resolved when the operation is
  1306. * successful and rejected otherwise.
  1307. */
  1308. setSenderVideoConstraint(maxFrameHeight) {
  1309. if (this._assertNotEnded()) {
  1310. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}`);
  1311. // RN doesn't support RTCRtpSenders yet, aggresive layer suspension on RN is implemented
  1312. // by changing the media direction in the SDP. This is applicable to jvb sessions only.
  1313. if (!this.isP2P && browser.isReactNative() && typeof maxFrameHeight !== 'undefined') {
  1314. const videoActive = maxFrameHeight > 0;
  1315. return this.setMediaTransferActive(true, videoActive);
  1316. }
  1317. return this.peerconnection.setSenderVideoConstraint(maxFrameHeight);
  1318. }
  1319. return Promise.resolve();
  1320. }
  1321. /**
  1322. * Sets the degradation preference on the video sender. This setting determines if
  1323. * resolution or framerate will be preferred when bandwidth or cpu is constrained.
  1324. * @returns {Promise<void>} promise that will be resolved when the operation is
  1325. * successful and rejected otherwise.
  1326. */
  1327. setSenderVideoDegradationPreference() {
  1328. if (this._assertNotEnded()) {
  1329. return this.peerconnection.setSenderVideoDegradationPreference();
  1330. }
  1331. return Promise.resolve();
  1332. }
  1333. /**
  1334. * @inheritDoc
  1335. */
  1336. terminate(success, failure, options) {
  1337. if (this.state === JingleSessionState.ENDED) {
  1338. return;
  1339. }
  1340. if (!options || Boolean(options.sendSessionTerminate)) {
  1341. const sessionTerminate
  1342. = $iq({
  1343. to: this.remoteJid,
  1344. type: 'set'
  1345. })
  1346. .c('jingle', {
  1347. xmlns: 'urn:xmpp:jingle:1',
  1348. action: 'session-terminate',
  1349. initiator: this.initiatorJid,
  1350. sid: this.sid
  1351. })
  1352. .c('reason')
  1353. .c((options && options.reason) || 'success')
  1354. .up();
  1355. if (options && options.reasonDescription) {
  1356. sessionTerminate
  1357. .c('text')
  1358. .t(options.reasonDescription)
  1359. .up()
  1360. .up();
  1361. } else {
  1362. sessionTerminate.up();
  1363. }
  1364. this._bridgeSessionId
  1365. && sessionTerminate.c(
  1366. 'bridge-session', {
  1367. xmlns: 'http://jitsi.org/protocol/focus',
  1368. id: this._bridgeSessionId,
  1369. restart: options && options.requestRestart === true
  1370. }).up();
  1371. logger.info(`${this} Sending session-terminate`);
  1372. logger.debug(sessionTerminate.tree());
  1373. this.connection.sendIQ(
  1374. sessionTerminate,
  1375. success,
  1376. this.newJingleErrorHandler(sessionTerminate, failure),
  1377. IQ_TIMEOUT);
  1378. } else {
  1379. logger.info(`${this} Skipped sending session-terminate`);
  1380. }
  1381. // this should result in 'onTerminated' being called by strope.jingle.js
  1382. this.connection.jingle.terminate(this.sid);
  1383. }
  1384. /**
  1385. *
  1386. * @param reasonCondition
  1387. * @param reasonText
  1388. */
  1389. onTerminated(reasonCondition, reasonText) {
  1390. // Do something with reason and reasonCondition when we start to care
  1391. // this.reasonCondition = reasonCondition;
  1392. // this.reasonText = reasonText;
  1393. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1394. this._xmppListeners.forEach(removeListener => removeListener());
  1395. this._xmppListeners = [];
  1396. if (this._removeSenderVideoConstraintsChangeListener) {
  1397. this._removeSenderVideoConstraintsChangeListener();
  1398. }
  1399. this.close();
  1400. }
  1401. /**
  1402. * Handles XMPP connection state changes.
  1403. *
  1404. * @param {XmppConnection.Status} status - The new status.
  1405. */
  1406. onXmppStatusChanged(status) {
  1407. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1408. logger.info(`${this} Sending SSRC update on reconnect`);
  1409. this.notifyMySSRCUpdate(
  1410. this._cachedOldLocalSdp,
  1411. this._cachedNewLocalSdp);
  1412. }
  1413. }
  1414. /**
  1415. * Parse the information from the xml sourceAddElem and translate it
  1416. * into sdp lines
  1417. * @param {jquery xml element} sourceAddElem the source-add
  1418. * element from jingle
  1419. * @param {SDP object} currentRemoteSdp the current remote
  1420. * sdp (as of this new source-add)
  1421. * @returns {list} a list of SDP line strings that should
  1422. * be added to the remote SDP
  1423. */
  1424. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1425. const addSsrcInfo = [];
  1426. const self = this;
  1427. $(sourceAddElem).each((i1, content) => {
  1428. const name = $(content).attr('name');
  1429. let lines = '';
  1430. $(content)
  1431. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1432. .each(function() {
  1433. // eslint-disable-next-line no-invalid-this
  1434. const semantics = this.getAttribute('semantics');
  1435. const ssrcs
  1436. = $(this) // eslint-disable-line no-invalid-this
  1437. .find('>source')
  1438. .map(function() {
  1439. // eslint-disable-next-line no-invalid-this
  1440. return this.getAttribute('ssrc');
  1441. })
  1442. .get();
  1443. if (ssrcs.length) {
  1444. lines += `a=ssrc-group:${semantics} ${ssrcs.join(' ')}\r\n`;
  1445. }
  1446. });
  1447. // handles both >source and >description>source
  1448. const tmp
  1449. = $(content).find(
  1450. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1451. /* eslint-disable no-invalid-this */
  1452. tmp.each(function() {
  1453. const ssrc = $(this).attr('ssrc');
  1454. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1455. // Do not print the warning for unified plan p2p case since ssrcs are never removed from the SDP.
  1456. !(self.usesUnifiedPlan && self.isP2P)
  1457. && logger.warn(`${self} Source-add request for existing SSRC: ${ssrc}`);
  1458. return;
  1459. }
  1460. // eslint-disable-next-line newline-per-chained-call
  1461. $(this).find('>parameter').each(function() {
  1462. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1463. if ($(this).attr('value') && $(this).attr('value').length) {
  1464. lines += `:${$(this).attr('value')}`;
  1465. }
  1466. lines += '\r\n';
  1467. });
  1468. });
  1469. /* eslint-enable no-invalid-this */
  1470. currentRemoteSdp.media.forEach((media, i2) => {
  1471. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1472. return;
  1473. }
  1474. if (!addSsrcInfo[i2]) {
  1475. addSsrcInfo[i2] = '';
  1476. }
  1477. addSsrcInfo[i2] += lines;
  1478. });
  1479. });
  1480. return addSsrcInfo;
  1481. }
  1482. /**
  1483. * Handles a Jingle source-add message for this Jingle session.
  1484. * @param elem An array of Jingle "content" elements.
  1485. */
  1486. addRemoteStream(elem) {
  1487. this._addOrRemoveRemoteStream(true /* add */, elem);
  1488. }
  1489. /**
  1490. * Handles a Jingle source-remove message for this Jingle session.
  1491. * @param elem An array of Jingle "content" elements.
  1492. */
  1493. removeRemoteStream(elem) {
  1494. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1495. }
  1496. /**
  1497. * Handles the deletion of the remote tracks and SSRCs associated with a remote endpoint.
  1498. *
  1499. * @param {string} id Endpoint id of the participant that has left the call.
  1500. * @returns {Promise<JitsiRemoteTrack>} Promise that resolves with the tracks that are removed or error if the
  1501. * operation fails.
  1502. */
  1503. removeRemoteStreamsOnLeave(id) {
  1504. let remoteTracks = [];
  1505. const workFunction = finishCallback => {
  1506. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1507. if (removeSsrcInfo.length) {
  1508. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1509. const newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  1510. remoteTracks = this.peerconnection.removeRemoteTracks(id);
  1511. this._renegotiate(newRemoteSdp.raw)
  1512. .then(() => {
  1513. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1514. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSDP);
  1515. finishCallback();
  1516. })
  1517. .catch(err => finishCallback(err));
  1518. } else {
  1519. finishCallback();
  1520. }
  1521. };
  1522. return new Promise((resolve, reject) => {
  1523. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1524. this.modificationQueue.push(
  1525. workFunction,
  1526. error => {
  1527. if (error) {
  1528. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1529. reject(error);
  1530. } else {
  1531. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1532. resolve(remoteTracks);
  1533. }
  1534. });
  1535. });
  1536. }
  1537. /**
  1538. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1539. * Jingle session.
  1540. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1541. * otherwise.
  1542. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1543. * @private
  1544. */
  1545. _addOrRemoveRemoteStream(isAdd, elem) {
  1546. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1547. if (isAdd) {
  1548. this.readSsrcInfo(elem);
  1549. }
  1550. const workFunction = finishedCallback => {
  1551. if (!this.peerconnection.localDescription
  1552. || !this.peerconnection.localDescription.sdp) {
  1553. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1554. logger.error(errMsg);
  1555. finishedCallback(errMsg);
  1556. return;
  1557. }
  1558. logger.log(`${this} Processing ${logPrefix}`);
  1559. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1560. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1561. const addOrRemoveSsrcInfo
  1562. = isAdd
  1563. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1564. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1565. const newRemoteSdp
  1566. = isAdd
  1567. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1568. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1569. // Add a workaround for a bug in Chrome (unified plan) for p2p connection. When the media direction on
  1570. // the transceiver goes from "inactive" (both users join muted) to "recvonly" (peer unmutes), the browser
  1571. // doesn't seem to create a decoder if the signaling state changes from "have-local-offer" to "stable".
  1572. // Therefore, initiate a responder renegotiate even if the endpoint is the offerer to workaround this issue.
  1573. // TODO - open a chrome bug and update the comments.
  1574. const remoteDescription = new RTCSessionDescription({
  1575. type: 'offer',
  1576. sdp: newRemoteSdp.raw
  1577. });
  1578. const promise = isAdd && this.usesUnifiedPlan && this.isP2P && browser.isChromiumBased()
  1579. ? this._responderRenegotiate(remoteDescription)
  1580. : this._renegotiate(newRemoteSdp.raw);
  1581. promise.then(() => {
  1582. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1583. logger.log(`${this} ${logPrefix} - OK`);
  1584. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1585. finishedCallback();
  1586. }, error => {
  1587. logger.error(`${this} ${logPrefix} failed:`, error);
  1588. finishedCallback(error);
  1589. });
  1590. };
  1591. logger.debug(`${this} Queued ${logPrefix} task`);
  1592. // Queue and execute
  1593. this.modificationQueue.push(workFunction);
  1594. }
  1595. /**
  1596. * Takes in a jingle offer iq, returns the new sdp offer
  1597. * @param {jquery xml element} offerIq the incoming offer
  1598. * @returns {SDP object} the jingle offer translated to SDP
  1599. */
  1600. _processNewJingleOfferIq(offerIq) {
  1601. const remoteSdp = new SDP('');
  1602. if (this.webrtcIceTcpDisable) {
  1603. remoteSdp.removeTcpCandidates = true;
  1604. }
  1605. if (this.webrtcIceUdpDisable) {
  1606. remoteSdp.removeUdpCandidates = true;
  1607. }
  1608. if (this.failICE) {
  1609. remoteSdp.failICE = true;
  1610. }
  1611. remoteSdp.fromJingle(offerIq);
  1612. this.readSsrcInfo($(offerIq).find('>content'));
  1613. return remoteSdp;
  1614. }
  1615. /**
  1616. * Remove the given ssrc lines from the current remote sdp
  1617. * @param {list} removeSsrcInfo a list of SDP line strings that
  1618. * should be removed from the remote SDP
  1619. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1620. * in removeSsrcInfo
  1621. */
  1622. _processRemoteRemoveSource(removeSsrcInfo) {
  1623. const remoteSdp = this.usesUnifiedPlan
  1624. ? new SDP(this.peerconnection.peerconnection.remoteDescription.sdp)
  1625. : new SDP(this.peerconnection.remoteDescription.sdp);
  1626. removeSsrcInfo.forEach((lines, idx) => {
  1627. // eslint-disable-next-line no-param-reassign
  1628. lines = lines.split('\r\n');
  1629. lines.pop(); // remove empty last element;
  1630. if (this.usesUnifiedPlan) {
  1631. lines.forEach(line => {
  1632. const mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1633. if (mid > -1) {
  1634. // Remove the ssrcs from the m-line in
  1635. // 1. Plan-b mode always.
  1636. // 2. Unified mode but only for jvb connection. In p2p mode if the ssrc is removed and added
  1637. // back to the same m-line, Chrome/Safari do not render the media even if it being received
  1638. // and decoded from the remote peer. The webrtc spec is not clear about m-line re-use and
  1639. // the browser vendors have implemented this differently. Currently workaround this by changing
  1640. // the media direction, that should be enough for the browser to fire the "removetrack" event
  1641. // on the associated MediaStream.
  1642. if (!this.usesUnifiedPlan || (this.usesUnifiedPlan && !this.isP2P)) {
  1643. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1644. }
  1645. // The current direction of the transceiver for p2p will depend on whether a local sources is
  1646. // added or not. It will be 'sendrecv' if the local source is present, 'sendonly' otherwise.
  1647. if (this.isP2P) {
  1648. const mediaType = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0])?.media;
  1649. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, false);
  1650. [ MediaDirection.SENDRECV, MediaDirection.SENDONLY ].forEach(direction => {
  1651. remoteSdp.media[mid] = remoteSdp.media[mid]
  1652. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1653. });
  1654. // Jvb connections will have direction set to 'sendonly' when the remote ssrc is present.
  1655. } else {
  1656. // Change the direction to "inactive" always for jvb connection.
  1657. remoteSdp.media[mid] = remoteSdp.media[mid]
  1658. .replace(`a=${MediaDirection.SENDONLY}`, `a=${MediaDirection.INACTIVE}`);
  1659. }
  1660. }
  1661. });
  1662. } else {
  1663. lines.forEach(line => {
  1664. remoteSdp.media[idx]
  1665. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1666. });
  1667. }
  1668. });
  1669. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1670. return remoteSdp;
  1671. }
  1672. /**
  1673. * Add the given ssrc lines to the current remote sdp
  1674. * @param {list} addSsrcInfo a list of SDP line strings that
  1675. * should be added to the remote SDP
  1676. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1677. * in removeSsrcInfo
  1678. */
  1679. _processRemoteAddSource(addSsrcInfo) {
  1680. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1681. addSsrcInfo.forEach((lines, idx) => {
  1682. remoteSdp.media[idx] += lines;
  1683. // Make sure to change the direction to 'sendrecv/sendonly' only for p2p connections. For jvb connections,
  1684. // a new m-line is added for the new remote sources.
  1685. if (this.isP2P && this.usesUnifiedPlan) {
  1686. const mediaType = SDPUtil.parseMLine(remoteSdp.media[idx].split('\r\n')[0])?.media;
  1687. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, true);
  1688. [ MediaDirection.RECVONLY, MediaDirection.INACTIVE ].forEach(direction => {
  1689. remoteSdp.media[idx] = remoteSdp.media[idx]
  1690. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1691. });
  1692. }
  1693. });
  1694. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1695. return remoteSdp;
  1696. }
  1697. /**
  1698. * Do a new o/a flow using the existing remote description
  1699. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1700. * to use. If not provided, the remote sdp from the
  1701. * peerconnection will be used
  1702. * @returns {Promise} promise which resolves when the
  1703. * o/a flow is complete with no arguments or
  1704. * rejects with an error {string}
  1705. */
  1706. _renegotiate(optionalRemoteSdp) {
  1707. if (this.peerconnection.signalingState === 'closed') {
  1708. const error = new Error('Attempted to renegotiate in state closed');
  1709. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1710. return Promise.reject(error);
  1711. }
  1712. const remoteSdp
  1713. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1714. if (!remoteSdp) {
  1715. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1716. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1717. return Promise.reject(error);
  1718. }
  1719. const remoteDescription = new RTCSessionDescription({
  1720. type: this.isInitiator ? 'answer' : 'offer',
  1721. sdp: remoteSdp
  1722. });
  1723. if (this.isInitiator) {
  1724. return this._initiatorRenegotiate(remoteDescription);
  1725. }
  1726. return this._responderRenegotiate(remoteDescription);
  1727. }
  1728. /**
  1729. * Renegotiate cycle implementation for the responder case.
  1730. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1731. * which will be used as remote description in the cycle.
  1732. * @private
  1733. */
  1734. _responderRenegotiate(remoteDescription) {
  1735. logger.debug(`${this} Renegotiate: setting remote description`);
  1736. return this.peerconnection.setRemoteDescription(remoteDescription)
  1737. .then(() => {
  1738. logger.debug(`${this} Renegotiate: creating answer`);
  1739. return this.peerconnection.createAnswer(this.mediaConstraints)
  1740. .then(answer => {
  1741. logger.debug(`${this} Renegotiate: setting local description`);
  1742. return this.peerconnection.setLocalDescription(answer);
  1743. });
  1744. });
  1745. }
  1746. /**
  1747. * Renegotiate cycle implementation for the initiator's case.
  1748. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1749. * which will be used as remote description in the cycle.
  1750. * @private
  1751. */
  1752. _initiatorRenegotiate(remoteDescription) {
  1753. logger.debug(`${this} Renegotiate: creating offer`);
  1754. return this.peerconnection.createOffer(this.mediaConstraints)
  1755. .then(offer => {
  1756. logger.debug(`${this} Renegotiate: setting local description`);
  1757. return this.peerconnection.setLocalDescription(offer)
  1758. .then(() => {
  1759. logger.debug(`${this} Renegotiate: setting remote description`);
  1760. // eslint-disable-next-line max-len
  1761. return this.peerconnection.setRemoteDescription(remoteDescription);
  1762. });
  1763. });
  1764. }
  1765. /**
  1766. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1767. * offer/answer cycle after both operations are done. Either
  1768. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1769. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1770. * <tt>oldTrack</tt>
  1771. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1772. * replaced
  1773. * @param {JitsiLocalTrack|null} newTrack the new track to use
  1774. * @returns {Promise} which resolves once the replacement is complete
  1775. * with no arguments or rejects with an error {string}
  1776. */
  1777. replaceTrack(oldTrack, newTrack) {
  1778. const workFunction = finishedCallback => {
  1779. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  1780. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1781. if (!this.usesUnifiedPlan) {
  1782. // NOTE the code below assumes that no more than 1 video track
  1783. // can be added to the peer connection.
  1784. // Transition from camera to desktop share
  1785. // or transition from one camera source to another.
  1786. if (this.peerconnection.options.capScreenshareBitrate
  1787. && oldTrack && newTrack && newTrack.isVideoTrack()) {
  1788. // Clearing current primary SSRC will make
  1789. // the SdpConsistency generate a new one which will result
  1790. // with:
  1791. // 1. source-remove for the old video stream.
  1792. // 2. source-add for the new video stream.
  1793. this.peerconnection.clearRecvonlySsrc();
  1794. }
  1795. // Transition from no video to video (unmute).
  1796. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  1797. // Clearing current primary SSRC will make
  1798. // the SdpConsistency generate a new one which will result
  1799. // with:
  1800. // 1. source-remove for the recvonly
  1801. // 2. source-add for the new video stream
  1802. this.peerconnection.clearRecvonlySsrc();
  1803. // Transition from video to no video
  1804. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  1805. // Clearing current primary SSRC and generating the recvonly
  1806. // will result in:
  1807. // 1. source-remove for the old video stream
  1808. // 2. source-add for the recvonly stream
  1809. this.peerconnection.clearRecvonlySsrc();
  1810. this.peerconnection.generateRecvonlySsrc();
  1811. }
  1812. }
  1813. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1814. .then(shouldRenegotiate => {
  1815. let promise = Promise.resolve();
  1816. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  1817. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  1818. if (shouldRenegotiate
  1819. && (oldTrack || newTrack)
  1820. && this.state === JingleSessionState.ACTIVE) {
  1821. promise = this._renegotiate().then(() => {
  1822. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1823. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSDP);
  1824. });
  1825. }
  1826. return promise.then(() => {
  1827. if (newTrack && newTrack.isVideoTrack()) {
  1828. logger.debug(`${this} replaceTrack worker: configuring video stream`);
  1829. // FIXME set all sender parameters in one go?
  1830. // Set the degradation preference on the new video sender.
  1831. return this.peerconnection.setSenderVideoDegradationPreference()
  1832. .then(() => this.peerconnection.setSenderVideoConstraint())
  1833. .then(() => this.peerconnection.setMaxBitRate());
  1834. }
  1835. });
  1836. })
  1837. .then(() => finishedCallback(), error => finishedCallback(error));
  1838. };
  1839. return new Promise((resolve, reject) => {
  1840. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  1841. this.modificationQueue.push(
  1842. workFunction,
  1843. error => {
  1844. if (error) {
  1845. logger.error(`${this} Replace track error:`, error);
  1846. reject(error);
  1847. } else {
  1848. logger.info(`${this} Replace track done!`);
  1849. resolve();
  1850. }
  1851. });
  1852. });
  1853. }
  1854. /**
  1855. * Parse the information from the xml sourceRemoveElem and translate it
  1856. * into sdp lines
  1857. * @param {jquery xml element} sourceRemoveElem the source-remove
  1858. * element from jingle
  1859. * @param {SDP object} currentRemoteSdp the current remote
  1860. * sdp (as of this new source-remove)
  1861. * @returns {list} a list of SDP line strings that should
  1862. * be removed from the remote SDP
  1863. */
  1864. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  1865. const removeSsrcInfo = [];
  1866. $(sourceRemoveElem).each((i1, content) => {
  1867. const name = $(content).attr('name');
  1868. let lines = '';
  1869. $(content)
  1870. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1871. .each(function() {
  1872. /* eslint-disable no-invalid-this */
  1873. const semantics = this.getAttribute('semantics');
  1874. const ssrcs
  1875. = $(this)
  1876. .find('>source')
  1877. .map(function() {
  1878. return this.getAttribute('ssrc');
  1879. })
  1880. .get();
  1881. if (ssrcs.length) {
  1882. lines
  1883. += `a=ssrc-group:${semantics} ${
  1884. ssrcs.join(' ')}\r\n`;
  1885. }
  1886. /* eslint-enable no-invalid-this */
  1887. });
  1888. const ssrcs = [];
  1889. // handles both >source and >description>source versions
  1890. const tmp
  1891. = $(content).find(
  1892. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1893. tmp.each(function() {
  1894. // eslint-disable-next-line no-invalid-this
  1895. const ssrc = $(this).attr('ssrc');
  1896. ssrcs.push(ssrc);
  1897. });
  1898. currentRemoteSdp.media.forEach((media, i2) => {
  1899. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1900. return;
  1901. }
  1902. if (!removeSsrcInfo[i2]) {
  1903. removeSsrcInfo[i2] = '';
  1904. }
  1905. ssrcs.forEach(ssrc => {
  1906. const ssrcLines
  1907. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  1908. if (ssrcLines.length) {
  1909. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  1910. }
  1911. });
  1912. removeSsrcInfo[i2] += lines;
  1913. });
  1914. });
  1915. return removeSsrcInfo;
  1916. }
  1917. /**
  1918. * Will print an error if there is any difference, between the SSRCs given
  1919. * in the <tt>oldSDP</tt> and the ones currently described in
  1920. * the peerconnection's local description.
  1921. * @param {string} operationName the operation's name which will be printed
  1922. * in the error message.
  1923. * @param {SDP} oldSDP the old local SDP which will be compared with
  1924. * the current one.
  1925. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  1926. * otherwise.
  1927. * @private
  1928. */
  1929. _verifyNoSSRCChanged(operationName, oldSDP) {
  1930. const currentLocalSDP
  1931. = new SDP(this.peerconnection.localDescription.sdp);
  1932. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  1933. const addedMedia = sdpDiff.getNewMedia();
  1934. if (Object.keys(addedMedia).length) {
  1935. logger.error(`${this} - some SSRC were added on ${operationName}`, addedMedia);
  1936. return false;
  1937. }
  1938. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  1939. const removedMedia = sdpDiff.getNewMedia();
  1940. if (Object.keys(removedMedia).length) {
  1941. logger.error(`${this} - some SSRCs were removed on ${operationName}`, removedMedia);
  1942. return false;
  1943. }
  1944. return true;
  1945. }
  1946. /**
  1947. * Adds local track back to this session, as part of the unmute operation.
  1948. * @param {JitsiLocalTrack} track
  1949. * @return {Promise} a promise that will resolve once the local track is
  1950. * added back to this session and renegotiation succeeds. Will be rejected
  1951. * with a <tt>string</tt> that provides some error details in case something
  1952. * goes wrong.
  1953. */
  1954. addTrackAsUnmute(track) {
  1955. return this._addRemoveTrackAsMuteUnmute(
  1956. false /* add as unmute */, track)
  1957. .then(() => {
  1958. // Apply the video constraints, max bitrates and degradation preference on
  1959. // the video sender if needed.
  1960. if (track.isVideoTrack() && browser.doesVideoMuteByStreamRemove()) {
  1961. return this.setSenderMaxBitrates()
  1962. .then(() => this.setSenderVideoDegradationPreference())
  1963. .then(() => this.setSenderVideoConstraint());
  1964. }
  1965. });
  1966. }
  1967. /**
  1968. * Remove local track as part of the mute operation.
  1969. * @param {JitsiLocalTrack} track the local track to be removed
  1970. * @return {Promise} a promise which will be resolved once the local track
  1971. * is removed from this session and the renegotiation is performed.
  1972. * The promise will be rejected with a <tt>string</tt> that the describes
  1973. * the error if anything goes wrong.
  1974. */
  1975. removeTrackAsMute(track) {
  1976. return this._addRemoveTrackAsMuteUnmute(
  1977. true /* remove as mute */, track);
  1978. }
  1979. /**
  1980. * See {@link addTrackAsUnmute} and {@link removeTrackAsMute}.
  1981. * @param {boolean} isMute <tt>true</tt> for "remove as mute" or
  1982. * <tt>false</tt> for "add as unmute".
  1983. * @param {JitsiLocalTrack} track the track that will be added/removed
  1984. * @private
  1985. */
  1986. _addRemoveTrackAsMuteUnmute(isMute, track) {
  1987. if (!track) {
  1988. return Promise.reject('invalid "track" argument value');
  1989. }
  1990. const operationName = isMute ? 'removeTrackMute' : 'addTrackUnmute';
  1991. const workFunction = finishedCallback => {
  1992. const tpc = this.peerconnection;
  1993. if (!tpc) {
  1994. finishedCallback(
  1995. `Error: tried ${operationName} track with no active peer`
  1996. + 'connection');
  1997. return;
  1998. }
  1999. const oldLocalSDP = tpc.localDescription.sdp;
  2000. const operationPromise
  2001. = isMute
  2002. ? tpc.removeTrackMute(track)
  2003. : tpc.addTrackUnmute(track);
  2004. operationPromise
  2005. .then(shouldRenegotiate => {
  2006. if (shouldRenegotiate && oldLocalSDP && tpc.remoteDescription.sdp) {
  2007. this._renegotiate()
  2008. .then(() => {
  2009. // The results are ignored, as this check failure is not
  2010. // enough to fail the whole operation. It will log
  2011. // an error inside.
  2012. this._verifyNoSSRCChanged(
  2013. operationName, new SDP(oldLocalSDP));
  2014. finishedCallback();
  2015. });
  2016. } else {
  2017. finishedCallback();
  2018. }
  2019. },
  2020. finishedCallback /* will be called with an error */);
  2021. };
  2022. logger.debug(`${this} Queued ${operationName} task`);
  2023. return new Promise((resolve, reject) => {
  2024. this.modificationQueue.push(
  2025. workFunction,
  2026. error => {
  2027. if (error) {
  2028. logger.error(`${this} ${operationName} failed`);
  2029. reject(error);
  2030. } else {
  2031. logger.debug(`${this} ${operationName} done`);
  2032. resolve();
  2033. }
  2034. });
  2035. });
  2036. }
  2037. /**
  2038. * Resumes or suspends media transfer over the underlying peer connection.
  2039. * @param {boolean} audioActive <tt>true</tt> to enable audio media
  2040. * transfer or <tt>false</tt> to suspend audio media transmission.
  2041. * @param {boolean} videoActive <tt>true</tt> to enable video media
  2042. * transfer or <tt>false</tt> to suspend video media transmission.
  2043. * @return {Promise} a <tt>Promise</tt> which will resolve once
  2044. * the operation is done. It will be rejected with an error description as
  2045. * a string in case anything goes wrong.
  2046. */
  2047. setMediaTransferActive(audioActive, videoActive) {
  2048. if (!this.peerconnection) {
  2049. return Promise.reject(
  2050. 'Can not modify transfer active state,'
  2051. + ' before "initialize" is called');
  2052. }
  2053. const logAudioStr = audioActive ? 'audio active' : 'audio inactive';
  2054. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  2055. logger.info(`${this} Queued make ${logVideoStr}, ${logAudioStr} task`);
  2056. const workFunction = finishedCallback => {
  2057. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  2058. // Because the value is modified on the queue it's impossible to
  2059. // check it's final value reliably prior to submitting the task.
  2060. // The rule here is that the last submitted state counts.
  2061. // Check the values here to avoid unnecessary renegotiation cycle.
  2062. const audioActiveChanged
  2063. = this.peerconnection.setAudioTransferActive(audioActive);
  2064. if (this._localVideoActive !== videoActive) {
  2065. this._localVideoActive = videoActive;
  2066. // Do only for P2P - Jicofo will reply with 'bad-request'
  2067. // We don't want to send 'content-modify', before the initial
  2068. // O/A (state === JingleSessionState.ACTIVE), because that will
  2069. // mess up video media direction in the remote SDP.
  2070. // 'content-modify' when processed only affects the media
  2071. // direction in the local SDP. We're doing that, because setting
  2072. // 'inactive' on video media in remote SDP will mess up our SDP
  2073. // translation chain (simulcast, RTX, video mute etc.).
  2074. if (this.isP2P && isSessionActive) {
  2075. this.sendContentModify();
  2076. }
  2077. }
  2078. const pcVideoActiveChanged
  2079. = this.peerconnection.setVideoTransferActive(
  2080. this._localVideoActive && this._remoteVideoActive);
  2081. // Will do the sRD/sLD cycle to update SDPs and adjust the media
  2082. // direction
  2083. if (isSessionActive
  2084. && (audioActiveChanged || pcVideoActiveChanged)) {
  2085. this._renegotiate()
  2086. .then(
  2087. finishedCallback,
  2088. finishedCallback /* will be called with an error */);
  2089. } else {
  2090. finishedCallback();
  2091. }
  2092. };
  2093. return new Promise((resolve, reject) => {
  2094. this.modificationQueue.push(
  2095. workFunction,
  2096. error => {
  2097. if (error) {
  2098. logger.error(`${this} Make ${logVideoStr}, ${logAudioStr} task failed!`);
  2099. reject(error);
  2100. } else {
  2101. logger.debug(`${this} Make ${logVideoStr}, ${logAudioStr} task done!`);
  2102. resolve();
  2103. }
  2104. });
  2105. });
  2106. }
  2107. /**
  2108. * Will put and execute on the queue a session modify task. Currently it
  2109. * only checks the senders attribute of the video content in order to figure
  2110. * out if the remote peer has video in the inactive state (stored locally
  2111. * in {@link _remoteVideoActive} - see field description for more info).
  2112. * @param {jQuery} jingleContents jQuery selector pointing to the jingle
  2113. * element of the session modify IQ.
  2114. * @see {@link _remoteVideoActive}
  2115. * @see {@link _localVideoActive}
  2116. */
  2117. modifyContents(jingleContents) {
  2118. const newVideoSenders
  2119. = JingleSessionPC.parseVideoSenders(jingleContents);
  2120. const newMaxFrameHeight
  2121. = JingleSessionPC.parseMaxFrameHeight(jingleContents);
  2122. // frame height is optional in our content-modify protocol
  2123. if (newMaxFrameHeight) {
  2124. logger.info(`${this} received remote max frame height: ${newMaxFrameHeight}`);
  2125. this.remoteRecvMaxFrameHeight = newMaxFrameHeight;
  2126. this.eventEmitter.emit(
  2127. MediaSessionEvents.REMOTE_VIDEO_CONSTRAINTS_CHANGED, this);
  2128. }
  2129. if (newVideoSenders === null) {
  2130. logger.error(
  2131. `${this} - failed to parse video "senders" attribute in`
  2132. + '"content-modify" action');
  2133. return;
  2134. }
  2135. const workFunction = finishedCallback => {
  2136. if (this._assertNotEnded('content-modify')
  2137. && this._modifyRemoteVideoActive(newVideoSenders)) {
  2138. // Will do the sRD/sLD cycle to update SDPs and adjust
  2139. // the media direction
  2140. this._renegotiate()
  2141. .then(finishedCallback, finishedCallback /* (error) */);
  2142. } else {
  2143. finishedCallback();
  2144. }
  2145. };
  2146. logger.debug(`${this} queued "content-modify" task(video senders="${newVideoSenders}")`);
  2147. this.modificationQueue.push(
  2148. workFunction,
  2149. error => {
  2150. if (error) {
  2151. logger.error(`${this} "content-modify" failed`, error);
  2152. } else {
  2153. logger.debug(`${this} "content-modify" task(video senders="${newVideoSenders}") done`);
  2154. }
  2155. });
  2156. }
  2157. /**
  2158. * Processes new value of remote video "senders" Jingle attribute and tries
  2159. * to apply it for {@link _remoteVideoActive}.
  2160. * @param {string} remoteVideoSenders the value of "senders" attribute of
  2161. * Jingle video content element advertised by remote peer.
  2162. * @return {boolean} <tt>true</tt> if the change affected state of
  2163. * the underlying peerconnection and renegotiation is required for
  2164. * the changes to take effect.
  2165. * @private
  2166. */
  2167. _modifyRemoteVideoActive(remoteVideoSenders) {
  2168. const isRemoteVideoActive
  2169. = remoteVideoSenders === 'both'
  2170. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  2171. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  2172. if (isRemoteVideoActive !== this._remoteVideoActive) {
  2173. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  2174. this._remoteVideoActive = isRemoteVideoActive;
  2175. }
  2176. return this.peerconnection.setVideoTransferActive(
  2177. this._localVideoActive && this._remoteVideoActive);
  2178. }
  2179. /**
  2180. * Figures out added/removed ssrcs and send update IQs.
  2181. * @param oldSDP SDP object for old description.
  2182. * @param newSDP SDP object for new description.
  2183. */
  2184. notifyMySSRCUpdate(oldSDP, newSDP) {
  2185. if (this.state !== JingleSessionState.ACTIVE) {
  2186. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  2187. return;
  2188. }
  2189. if (!this.connection.connected) {
  2190. // The goal is to compare the oldest SDP with the latest one upon reconnect
  2191. if (!this._cachedOldLocalSdp) {
  2192. this._cachedOldLocalSdp = oldSDP;
  2193. }
  2194. this._cachedNewLocalSdp = newSDP;
  2195. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  2196. return;
  2197. }
  2198. this._cachedOldLocalSdp = undefined;
  2199. this._cachedNewLocalSdp = undefined;
  2200. // send source-remove IQ.
  2201. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  2202. const remove = $iq({ to: this.remoteJid,
  2203. type: 'set' })
  2204. .c('jingle', {
  2205. xmlns: 'urn:xmpp:jingle:1',
  2206. action: 'source-remove',
  2207. initiator: this.initiatorJid,
  2208. sid: this.sid
  2209. }
  2210. );
  2211. const removedAnySSRCs = sdpDiffer.toJingle(remove);
  2212. if (removedAnySSRCs) {
  2213. logger.info(`${this} Sending source-remove`);
  2214. logger.debug(remove.tree());
  2215. this.connection.sendIQ(
  2216. remove, null,
  2217. this.newJingleErrorHandler(remove), IQ_TIMEOUT);
  2218. }
  2219. // send source-add IQ.
  2220. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  2221. const add = $iq({ to: this.remoteJid,
  2222. type: 'set' })
  2223. .c('jingle', {
  2224. xmlns: 'urn:xmpp:jingle:1',
  2225. action: 'source-add',
  2226. initiator: this.initiatorJid,
  2227. sid: this.sid
  2228. }
  2229. );
  2230. const containsNewSSRCs = sdpDiffer.toJingle(add);
  2231. if (containsNewSSRCs) {
  2232. logger.info(`${this} Sending source-add`);
  2233. logger.debug(add.tree());
  2234. this.connection.sendIQ(
  2235. add, null, this.newJingleErrorHandler(add), IQ_TIMEOUT);
  2236. }
  2237. }
  2238. /**
  2239. * Method returns function(errorResponse) which is a callback to be passed
  2240. * to Strophe connection.sendIQ method. An 'error' structure is created that
  2241. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  2242. * structure is as follows:
  2243. * {
  2244. * code: {XMPP error response code}
  2245. * reason: {the name of XMPP error reason element or 'timeout' if the
  2246. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  2247. * source: {request.tree() that provides original request}
  2248. * session: {this JingleSessionPC.toString()}
  2249. * }
  2250. * @param request Strophe IQ instance which is the request to be dumped into
  2251. * the error structure
  2252. * @param failureCb function(error) called when error response was returned
  2253. * or when a timeout has occurred.
  2254. * @returns {function(this:JingleSessionPC)}
  2255. */
  2256. newJingleErrorHandler(request, failureCb) {
  2257. return errResponse => {
  2258. const error = {};
  2259. // Get XMPP error code and condition(reason)
  2260. const errorElSel = $(errResponse).find('error');
  2261. if (errorElSel.length) {
  2262. error.code = errorElSel.attr('code');
  2263. const errorReasonSel = $(errResponse).find('error :first');
  2264. if (errorReasonSel.length) {
  2265. error.reason = errorReasonSel[0].tagName;
  2266. }
  2267. const errorMsgSel = errorElSel.find('>text');
  2268. if (errorMsgSel.length) {
  2269. error.msg = errorMsgSel.text();
  2270. }
  2271. }
  2272. if (!errResponse) {
  2273. error.reason = 'timeout';
  2274. }
  2275. error.session = this.toString();
  2276. if (failureCb) {
  2277. failureCb(error);
  2278. } else if (this.state === JingleSessionState.ENDED
  2279. && error.reason === 'item-not-found') {
  2280. // When remote peer decides to terminate the session, but it
  2281. // still have few messages on the queue for processing,
  2282. // it will first send us 'session-terminate' (we enter ENDED)
  2283. // and then follow with 'item-not-found' for the queued requests
  2284. // We don't want to have that logged on error level.
  2285. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  2286. } else {
  2287. GlobalOnErrorHandler.callErrorHandler(
  2288. new Error(
  2289. `Jingle error: ${JSON.stringify(error)}`));
  2290. }
  2291. };
  2292. }
  2293. /**
  2294. * Returns the ice connection state for the peer connection.
  2295. * @returns the ice connection state for the peer connection.
  2296. */
  2297. getIceConnectionState() {
  2298. return this.peerconnection.getConnectionState();
  2299. }
  2300. /**
  2301. * Closes the peerconnection.
  2302. */
  2303. close() {
  2304. this.state = JingleSessionState.ENDED;
  2305. this.establishmentDuration = undefined;
  2306. if (this.peerconnection) {
  2307. this.peerconnection.onicecandidate = null;
  2308. this.peerconnection.oniceconnectionstatechange = null;
  2309. this.peerconnection.onnegotiationneeded = null;
  2310. this.peerconnection.onsignalingstatechange = null;
  2311. }
  2312. logger.debug(`${this} Clearing modificationQueue`);
  2313. // Remove any pending tasks from the queue
  2314. this.modificationQueue.clear();
  2315. logger.debug(`${this} Queued PC close task`);
  2316. this.modificationQueue.push(finishCallback => {
  2317. // The signaling layer will remove it's listeners
  2318. this.signalingLayer.setChatRoom(null);
  2319. // do not try to close if already closed.
  2320. this.peerconnection && this.peerconnection.close();
  2321. finishCallback();
  2322. logger.debug(`${this} PC close task done!`);
  2323. });
  2324. logger.debug(`${this} Shutdown modificationQueue!`);
  2325. // No more tasks can go in after the close task
  2326. this.modificationQueue.shutdown();
  2327. }
  2328. /**
  2329. * Converts to string with minor summary.
  2330. * @return {string}
  2331. */
  2332. toString() {
  2333. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2334. }
  2335. /**
  2336. * If the A/B test for suspend video is disabled according to the room's
  2337. * configuration, returns undefined. Otherwise returns a boolean which
  2338. * indicates whether the suspend video option should be enabled or disabled.
  2339. * @param {JingleSessionPCOptions} options - The config options.
  2340. */
  2341. _abtestSuspendVideoEnabled({ abTesting }) {
  2342. if (!abTesting || !abTesting.enableSuspendVideoTest) {
  2343. return;
  2344. }
  2345. // We want the two participants in a P2P call to agree on the value of
  2346. // the "suspend" option. We use the JID of the initiator, because it is
  2347. // both randomly selected and agreed upon by both participants.
  2348. const jid = this._getInitiatorJid();
  2349. return integerHash(jid) % 2 === 0;
  2350. }
  2351. }