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

JingleSessionPC.js 85KB

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