您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 90KB

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