modified lib-jitsi-meet dev repo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 105KB

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