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

JingleSessionPC.js 117KB

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