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

JingleSessionPC.js 101KB

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