modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 100KB

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