選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JingleSessionPC.js 100KB

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