Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JingleSessionPC.js 94KB

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