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

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