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

JingleSessionPC.js 116KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957
  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 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. this._renegotiate()
  581. .then(() => finishedCallback(), error => finishedCallback(error));
  582. };
  583. this.modificationQueue.push(
  584. workFunction,
  585. error => {
  586. if (error) {
  587. logger.error(`${this} onnegotiationneeded error`, error);
  588. } else {
  589. logger.debug(`${this} onnegotiationneeded executed - OK`);
  590. }
  591. });
  592. }
  593. };
  594. }
  595. /**
  596. * Remote preference for receive video max frame height.
  597. *
  598. * @returns {Number|undefined}
  599. */
  600. getRemoteRecvMaxFrameHeight() {
  601. if (this.isP2P) {
  602. return this.remoteRecvMaxFrameHeight;
  603. }
  604. return undefined;
  605. }
  606. /**
  607. * Remote preference for receive video max frame heights when source-name signaling is enabled.
  608. *
  609. * @returns {Map<string, number>|undefined}
  610. */
  611. getRemoteSourcesRecvMaxFrameHeight() {
  612. if (this.isP2P) {
  613. return this.remoteSourceMaxFrameHeights;
  614. }
  615. return undefined;
  616. }
  617. /**
  618. * Sends given candidate in Jingle 'transport-info' message.
  619. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  620. * @private
  621. */
  622. sendIceCandidate(candidate) {
  623. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  624. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  625. const ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  626. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  627. if (!(ice && jcand)) {
  628. const errorMesssage = 'failed to get ice && jcand';
  629. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  630. logger.error(errorMesssage);
  631. return;
  632. }
  633. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  634. if (this.usedrip) {
  635. if (this.dripContainer.length === 0) {
  636. setTimeout(() => {
  637. if (this.dripContainer.length === 0) {
  638. return;
  639. }
  640. this.sendIceCandidates(this.dripContainer);
  641. this.dripContainer = [];
  642. }, ICE_CAND_GATHERING_TIMEOUT);
  643. }
  644. this.dripContainer.push(candidate);
  645. } else {
  646. this.sendIceCandidates([ candidate ]);
  647. }
  648. } else {
  649. logger.log(`${this} sendIceCandidate: last candidate`);
  650. // FIXME: remember to re-think in ICE-restart
  651. this.lasticecandidate = true;
  652. }
  653. }
  654. /**
  655. * Sends given candidates in Jingle 'transport-info' message.
  656. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE
  657. * candidate instances
  658. * @private
  659. */
  660. sendIceCandidates(candidates) {
  661. if (!this._assertNotEnded('sendIceCandidates')) {
  662. return;
  663. }
  664. logger.log(`${this} sendIceCandidates ${JSON.stringify(candidates)}`);
  665. const cand = $iq({ to: this.remoteJid,
  666. type: 'set' })
  667. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  668. action: 'transport-info',
  669. initiator: this.initiatorJid,
  670. sid: this.sid });
  671. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  672. for (let mid = 0; mid < localSDP.media.length; mid++) {
  673. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  674. const mline
  675. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  676. if (cands.length > 0) {
  677. const ice
  678. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  679. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  680. cand.c('content', {
  681. creator: this.initiatorJid === this.localJid
  682. ? 'initiator' : 'responder',
  683. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  684. }).c('transport', ice);
  685. for (let i = 0; i < cands.length; i++) {
  686. const candidate
  687. = SDPUtil.candidateToJingle(cands[i].candidate);
  688. // Mangle ICE candidate if 'failICE' test option is enabled
  689. if (this.failICE) {
  690. candidate.ip = '1.1.1.1';
  691. }
  692. cand.c('candidate', candidate).up();
  693. }
  694. // add fingerprint
  695. const fingerprintLine
  696. = SDPUtil.findLine(
  697. localSDP.media[mid],
  698. 'a=fingerprint:', localSDP.session);
  699. if (fingerprintLine) {
  700. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  701. tmp.required = true;
  702. cand.c(
  703. 'fingerprint',
  704. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  705. .t(tmp.fingerprint);
  706. delete tmp.fingerprint;
  707. cand.attrs(tmp);
  708. cand.up();
  709. }
  710. cand.up(); // transport
  711. cand.up(); // content
  712. }
  713. }
  714. // might merge last-candidate notification into this, but it is called
  715. // a lot later. See webrtc issue #2340
  716. // logger.log('was this the last candidate', this.lasticecandidate);
  717. this.connection.sendIQ(
  718. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  719. }
  720. /**
  721. * Sends Jingle 'session-info' message which includes custom Jitsi Meet
  722. * 'ice-state' element with the text value 'failed' to let Jicofo know
  723. * that the ICE connection has entered the failed state. It can then
  724. * choose to re-create JVB channels and send 'transport-replace' to
  725. * retry the connection.
  726. */
  727. sendIceFailedNotification() {
  728. const sessionInfo
  729. = $iq({
  730. to: this.remoteJid,
  731. type: 'set' })
  732. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  733. action: 'session-info',
  734. initiator: this.initiatorJid,
  735. sid: this.sid })
  736. .c('ice-state', { xmlns: 'http://jitsi.org/protocol/focus' })
  737. .t('failed')
  738. .up();
  739. this._bridgeSessionId
  740. && sessionInfo.c(
  741. 'bridge-session', {
  742. xmlns: 'http://jitsi.org/protocol/focus',
  743. id: this._bridgeSessionId
  744. });
  745. this.connection.sendIQ2(
  746. sessionInfo, {
  747. /*
  748. * This message will be often sent when there are connectivity
  749. * issues, so make it slightly longer than Prosody's default BOSH
  750. * inactivity timeout of 60 seconds.
  751. */
  752. timeout: 65
  753. })
  754. .catch(this.newJingleErrorHandler(sessionInfo));
  755. }
  756. /**
  757. * {@inheritDoc}
  758. */
  759. addIceCandidates(elem) {
  760. if (this.peerconnection.signalingState === 'closed') {
  761. logger.warn(`${this} Ignored add ICE candidate when in closed state`);
  762. return;
  763. }
  764. const iceCandidates = [];
  765. elem.find('>content>transport>candidate')
  766. .each((idx, candidate) => {
  767. let line = SDPUtil.candidateFromJingle(candidate);
  768. line = line.replace('\r\n', '').replace('a=', '');
  769. // FIXME this code does not care to handle
  770. // non-bundle transport
  771. const rtcCandidate = new RTCIceCandidate({
  772. sdpMLineIndex: 0,
  773. // FF comes up with more complex names like audio-23423,
  774. // Given that it works on both Chrome and FF without
  775. // providing it, let's leave it like this for the time
  776. // being...
  777. // sdpMid: 'audio',
  778. sdpMid: '',
  779. candidate: line
  780. });
  781. iceCandidates.push(rtcCandidate);
  782. });
  783. if (!iceCandidates.length) {
  784. logger.error(`${this} No ICE candidates to add ?`, elem[0] && elem[0].outerHTML);
  785. return;
  786. }
  787. // We want to have this task queued, so that we know it is executed,
  788. // after the initial sRD/sLD offer/answer cycle was done (based on
  789. // the assumption that candidates are spawned after the offer/answer
  790. // and XMPP preserves order).
  791. const workFunction = finishedCallback => {
  792. for (const iceCandidate of iceCandidates) {
  793. this.peerconnection.addIceCandidate(iceCandidate)
  794. .then(
  795. () => logger.debug(`${this} addIceCandidate ok!`),
  796. err => logger.error(`${this} addIceCandidate failed!`, err));
  797. }
  798. finishedCallback();
  799. logger.debug(`${this} ICE candidates task finished`);
  800. };
  801. logger.debug(`${this} Queued add (${iceCandidates.length}) ICE candidates task`);
  802. this.modificationQueue.push(workFunction);
  803. }
  804. /**
  805. *
  806. * @param contents
  807. */
  808. readSsrcInfo(contents) {
  809. const ssrcs = $(contents).find('>description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  810. ssrcs.each((i, ssrcElement) => {
  811. const ssrc = Number(ssrcElement.getAttribute('ssrc'));
  812. if (ssrcElement.hasAttribute('name')) {
  813. const sourceName = ssrcElement.getAttribute('name');
  814. this._signalingLayer.setTrackSourceName(ssrc, sourceName);
  815. }
  816. if (this.isP2P) {
  817. // In P2P all SSRCs are owner by the remote peer
  818. this._signalingLayer.setSSRCOwner(ssrc, Strophe.getResourceFromJid(this.remoteJid));
  819. } else {
  820. $(ssrcElement)
  821. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  822. .each((i3, ssrcInfoElement) => {
  823. const owner = ssrcInfoElement.getAttribute('owner');
  824. if (owner?.length) {
  825. if (isNaN(ssrc) || ssrc < 0) {
  826. logger.warn(`${this} Invalid SSRC ${ssrc} value received for ${owner}`);
  827. } else {
  828. this._signalingLayer.setSSRCOwner(ssrc, getEndpointId(owner));
  829. }
  830. }
  831. });
  832. }
  833. });
  834. }
  835. /**
  836. * Makes the underlying TraceablePeerConnection generate new SSRC for
  837. * the recvonly video stream.
  838. * @deprecated
  839. */
  840. generateRecvonlySsrc() {
  841. if (this.peerconnection) {
  842. this.peerconnection.generateRecvonlySsrc();
  843. } else {
  844. logger.error(`${this} Unable to generate recvonly SSRC - no peerconnection`);
  845. }
  846. }
  847. /**
  848. * Returns the video codec configured as the preferred codec on the peerconnection.
  849. */
  850. getConfiguredVideoCodec() {
  851. return this.peerconnection.getConfiguredVideoCodec();
  852. }
  853. /**
  854. * Accepts incoming Jingle 'session-initiate' and should send 'session-accept' in result.
  855. *
  856. * @param jingleOffer jQuery selector pointing to the jingle element of the offer IQ
  857. * @param success callback called when we accept incoming session successfully and receive RESULT packet to
  858. * 'session-accept' sent.
  859. * @param failure function(error) called if for any reason we fail to accept the incoming offer. 'error' argument
  860. * can be used to log some details about the error.
  861. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  862. * the offer/answer cycle executes. We allow the localTracks to optionally be passed in so that the addition of the
  863. * local tracks and the processing of the initial offer can all be done atomically. We want to make sure that any
  864. * other operations which originate in the XMPP Jingle messages related with this session to be executed with an
  865. * assumption that the initial offer/answer cycle has been executed already.
  866. */
  867. acceptOffer(jingleOffer, success, failure, localTracks) {
  868. this.setOfferAnswerCycle(
  869. jingleOffer,
  870. () => {
  871. // FIXME we may not care about RESULT packet for session-accept
  872. // then we should either call 'success' here immediately or
  873. // modify sendSessionAccept method to do that
  874. this.sendSessionAccept(() => {
  875. // Start processing tasks on the modification queue.
  876. logger.debug('Resuming the modification queue after session is established!');
  877. this.modificationQueue.resume();
  878. success();
  879. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT, this);
  880. // The first video track is added to the peerconnection and signaled as part of the session-accept.
  881. // Add secondary video tracks (that were already added to conference) to the peerconnection here.
  882. // This will happen when someone shares a secondary source to a two people call, the other user
  883. // leaves and joins the call again, a new peerconnection is created for p2p/jvb connection. At this
  884. // point, there are 2 video tracks which need to be signaled to the remote peer.
  885. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  886. videoTracks.length && videoTracks.splice(0, 1);
  887. if (FeatureFlags.isMultiStreamSendSupportEnabled() && videoTracks.length) {
  888. this.addTracks(videoTracks);
  889. }
  890. },
  891. error => {
  892. failure(error);
  893. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_ERROR, this, error);
  894. });
  895. },
  896. failure,
  897. localTracks);
  898. }
  899. /**
  900. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  901. *
  902. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be added, before the offer/answer cycle
  903. * executes (for the local track addition to be an atomic operation together with the offer/answer).
  904. */
  905. invite(localTracks = []) {
  906. if (!this.isInitiator) {
  907. throw new Error('Trying to invite from the responder session');
  908. }
  909. logger.debug(`${this} Executing invite task`);
  910. const addTracks = [];
  911. for (const track of localTracks) {
  912. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  913. }
  914. Promise.all(addTracks)
  915. .then(() => this.peerconnection.createOffer(this.mediaConstraints))
  916. .then(offerSdp => this.peerconnection.setLocalDescription(offerSdp))
  917. .then(() => {
  918. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  919. let localDescription = this.peerconnection.localDescription;
  920. // Munge the codec order on the outgoing offer for clients that don't support
  921. // RTCRtpTransceiver#setCodecPreferences.
  922. if (!browser.supportsCodecPreferences()) {
  923. localDescription = this.peerconnection._mungeCodecOrder(localDescription);
  924. }
  925. this.sendSessionInitiate(localDescription.sdp);
  926. })
  927. .then(() => {
  928. logger.debug(`${this} invite executed - OK`);
  929. })
  930. .catch(error => {
  931. logger.error(`${this} invite error`, error);
  932. });
  933. }
  934. /**
  935. * Sends 'session-initiate' to the remote peer.
  936. *
  937. * NOTE this method is synchronous and we're not waiting for the RESULT
  938. * response which would delay the startup process.
  939. *
  940. * @param {string} offerSdp - The local session description which will be
  941. * used to generate an offer.
  942. * @private
  943. */
  944. sendSessionInitiate(offerSdp) {
  945. let init = $iq({
  946. to: this.remoteJid,
  947. type: 'set'
  948. }).c('jingle', {
  949. xmlns: 'urn:xmpp:jingle:1',
  950. action: 'session-initiate',
  951. initiator: this.initiatorJid,
  952. sid: this.sid
  953. });
  954. new SDP(offerSdp).toJingle(
  955. init,
  956. this.isInitiator ? 'initiator' : 'responder');
  957. init = init.tree();
  958. logger.debug(`${this} Session-initiate: `, init);
  959. this.connection.sendIQ(init,
  960. () => {
  961. logger.info(`${this} Got RESULT for "session-initiate"`);
  962. },
  963. error => {
  964. logger.error(`${this} "session-initiate" error`, error);
  965. },
  966. IQ_TIMEOUT);
  967. }
  968. /**
  969. * Sets the answer received from the remote peer as the remote description.
  970. *
  971. * @param jingleAnswer
  972. */
  973. setAnswer(jingleAnswer) {
  974. if (!this.isInitiator) {
  975. throw new Error('Trying to set an answer on the responder session');
  976. }
  977. logger.debug(`${this} Executing setAnswer task`);
  978. const newRemoteSdp = this._processNewJingleOfferIq(jingleAnswer);
  979. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  980. const remoteDescription = new RTCSessionDescription({
  981. type: 'answer',
  982. sdp: newRemoteSdp.raw
  983. });
  984. this.peerconnection.setRemoteDescription(remoteDescription)
  985. .then(() => {
  986. if (this.state === JingleSessionState.PENDING) {
  987. this.state = JingleSessionState.ACTIVE;
  988. // Start processing tasks on the modification queue.
  989. logger.debug('Resuming the modification queue after session is established!');
  990. this.modificationQueue.resume();
  991. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  992. this.sendContentModify();
  993. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  994. }
  995. })
  996. .then(() => {
  997. logger.debug(`${this} setAnswer task done`);
  998. })
  999. .catch(error => {
  1000. logger.error(`${this} setAnswer task failed: ${error}`);
  1001. });
  1002. }
  1003. /**
  1004. * This is a setRemoteDescription/setLocalDescription cycle which starts at converting Strophe Jingle IQ into
  1005. * remote offer SDP. Once converted, setRemoteDescription, createAnswer and setLocalDescription calls follow.
  1006. *
  1007. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element of the offer (or answer) IQ
  1008. * @param success callback called when sRD/sLD cycle finishes successfully.
  1009. * @param failure callback called with an error object as an argument if we fail at any point during setRD,
  1010. * createAnswer, setLD.
  1011. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  1012. * the offer/answer cycle executes (for the local track addition to be an atomic operation together with the
  1013. * offer/answer).
  1014. */
  1015. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks = []) {
  1016. logger.debug(`${this} Executing setOfferAnswerCycle task`);
  1017. const addTracks = [];
  1018. const audioTracks = localTracks.filter(track => track.getType() === MediaType.AUDIO);
  1019. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  1020. let tracks = localTracks;
  1021. // Add only 1 video track at a time. Adding 2 or more video tracks to the peerconnection at the same time
  1022. // makes the browser go into a renegotiation loop by firing 'negotiationneeded' event after every
  1023. // renegotiation.
  1024. if (FeatureFlags.isMultiStreamSendSupportEnabled() && videoTracks.length > 1) {
  1025. tracks = [ ...audioTracks, videoTracks[0] ];
  1026. }
  1027. for (const track of tracks) {
  1028. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  1029. }
  1030. const newRemoteSdp = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  1031. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1032. const bridgeSession = $(jingleOfferAnswerIq).find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]');
  1033. const bridgeSessionId = bridgeSession.attr('id');
  1034. if (bridgeSessionId !== this._bridgeSessionId) {
  1035. this._bridgeSessionId = bridgeSessionId;
  1036. }
  1037. const remoteDescription = new RTCSessionDescription({
  1038. type: 'offer',
  1039. sdp: newRemoteSdp.raw
  1040. });
  1041. Promise.all(addTracks)
  1042. .then(() => this._responderRenegotiate(remoteDescription))
  1043. .then(() => {
  1044. this.peerconnection.processLocalSdpForTransceiverInfo(tracks);
  1045. if (this.state === JingleSessionState.PENDING) {
  1046. this.state = JingleSessionState.ACTIVE;
  1047. // #1 Sync up video transfer active/inactive only after the initial O/A cycle. We want to
  1048. // adjust the video media direction only in the local SDP and the Jingle contents direction
  1049. // included in the initial offer/answer is mapped to the remote SDP. Jingle 'content-modify'
  1050. // IQ is processed in a way that it will only modify local SDP when remote peer is no longer
  1051. // interested in receiving video content. Changing media direction in the remote SDP will mess
  1052. // up our SDP translation chain (simulcast, video mute, RTX etc.)
  1053. // #2 Sends the max frame height if it was set, before the session-initiate/accept
  1054. if (this.isP2P
  1055. && (!this._localVideoActive || this._sourceReceiverConstraints)) {
  1056. this.sendContentModify();
  1057. }
  1058. }
  1059. // Old local SDP will be available when we're setting answer for the first time, but not when offer
  1060. // and it's fine since we're generating an answer now it will contain all our SSRCs.
  1061. if (oldLocalSdp) {
  1062. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1063. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSdp);
  1064. }
  1065. })
  1066. .then(() => {
  1067. logger.debug(`${this} setOfferAnswerCycle task done`);
  1068. success();
  1069. })
  1070. .catch(error => {
  1071. logger.error(`${this} setOfferAnswerCycle task failed: ${error}`);
  1072. failure(error);
  1073. });
  1074. }
  1075. /**
  1076. * Updates the codecs on the peerconnection and initiates a renegotiation for the
  1077. * new codec config to take effect.
  1078. *
  1079. * @param {CodecMimeType} preferred the preferred codec.
  1080. * @param {CodecMimeType} disabled the codec that needs to be disabled.
  1081. */
  1082. setVideoCodecs(codecList) {
  1083. if (this._assertNotEnded()) {
  1084. logger.info(`${this} setVideoCodecs: ${codecList}`);
  1085. this.peerconnection.setVideoCodecs(codecList);
  1086. // Initiate a renegotiate for the codec setting to take effect.
  1087. const workFunction = finishedCallback => {
  1088. this._renegotiate().then(
  1089. () => {
  1090. logger.debug(`${this} setVideoCodecs task is done`);
  1091. return finishedCallback();
  1092. }, error => {
  1093. logger.error(`${this} setVideoCodecs task failed: ${error}`);
  1094. return finishedCallback(error);
  1095. });
  1096. };
  1097. logger.debug(`${this} Queued setVideoCodecs task`);
  1098. // Queue and execute
  1099. this.modificationQueue.push(workFunction);
  1100. }
  1101. }
  1102. /* eslint-enable max-params */
  1103. /**
  1104. * Although it states "replace transport" it does accept full Jingle offer
  1105. * which should contain new ICE transport details.
  1106. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  1107. * transport info.
  1108. * @param success callback called when we succeed to accept new offer.
  1109. * @param failure function(error) called when we fail to accept new offer.
  1110. */
  1111. replaceTransport(jingleOfferElem, success, failure) {
  1112. if (this.options.enableForcedReload) {
  1113. const sdp = new SDP(this.peerconnection.localDescription.sdp);
  1114. this.sendTransportAccept(sdp, success, failure);
  1115. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTARTED, this);
  1116. return;
  1117. }
  1118. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  1119. // We need to first reject the 'data' section to have the SCTP stack
  1120. // cleaned up to signal the known data channel is now invalid. After
  1121. // that the original offer is set to have the SCTP connection
  1122. // established with the new bridge.
  1123. const originalOffer = jingleOfferElem.clone();
  1124. jingleOfferElem
  1125. .find('>content[name=\'data\']')
  1126. .attr('senders', 'rejected');
  1127. // Remove all remote sources in order to reset the client's state
  1128. // for the remote MediaStreams. When a conference is moved to
  1129. // another bridge it will start streaming with a sequence number
  1130. // that is not in sync with the most recently seen by the client.
  1131. // The symptoms include frozen or black video and lots of "failed to
  1132. // unprotect SRTP packets" in Chrome logs.
  1133. jingleOfferElem
  1134. .find('>content>description>source')
  1135. .remove();
  1136. jingleOfferElem
  1137. .find('>content>description>ssrc-group')
  1138. .remove();
  1139. // On the JVB it's not a real ICE restart and all layers are re-initialized from scratch as Jicofo does
  1140. // the restart by re-allocating new channels. Chrome (or WebRTC stack) needs to have the DTLS transport layer
  1141. // reset to start a new handshake with fresh DTLS transport on the bridge. Make it think that the DTLS
  1142. // fingerprint has changed by setting an all zeros key.
  1143. const newFingerprint = jingleOfferElem.find('>content>transport>fingerprint');
  1144. newFingerprint.attr('hash', 'sha-1');
  1145. newFingerprint.text('00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00');
  1146. const workFunction = finishedCallback => {
  1147. // First set an offer with a rejected 'data' section
  1148. this.setOfferAnswerCycle(
  1149. jingleOfferElem,
  1150. () => {
  1151. // Now set the original offer(with the 'data' section)
  1152. this.setOfferAnswerCycle(
  1153. originalOffer,
  1154. () => {
  1155. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1156. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1157. localSDP.initialLastN = this.options.channelLastN;
  1158. }
  1159. this.sendTransportAccept(localSDP, success, failure);
  1160. this.room.eventEmitter.emit(
  1161. XMPPEvents.ICE_RESTART_SUCCESS,
  1162. this,
  1163. originalOffer);
  1164. finishedCallback();
  1165. }, error => finishedCallback(error)
  1166. );
  1167. }, error => finishedCallback(error)
  1168. );
  1169. };
  1170. logger.debug(`${this} Queued ICE restart task`);
  1171. // Queue and execute
  1172. this.modificationQueue.push(
  1173. workFunction,
  1174. error => {
  1175. if (error) {
  1176. logger.error(`${this} ICE restart task failed: ${error}`);
  1177. failure(error);
  1178. } else {
  1179. logger.debug(`${this} ICE restart task done`);
  1180. success();
  1181. }
  1182. });
  1183. }
  1184. /**
  1185. * Sends Jingle 'session-accept' message.
  1186. * @param {function()} success callback called when we receive 'RESULT'
  1187. * packet for the 'session-accept'
  1188. * @param {function(error)} failure called when we receive an error response
  1189. * or when the request has timed out.
  1190. * @private
  1191. */
  1192. sendSessionAccept(success, failure) {
  1193. // NOTE: since we're just reading from it, we don't need to be within
  1194. // the modification queue to access the local description
  1195. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1196. const accept = $iq({ to: this.remoteJid,
  1197. type: 'set' })
  1198. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1199. action: 'session-accept',
  1200. initiator: this.initiatorJid,
  1201. responder: this.responderJid,
  1202. sid: this.sid });
  1203. if (this.webrtcIceTcpDisable) {
  1204. localSDP.removeTcpCandidates = true;
  1205. }
  1206. if (this.webrtcIceUdpDisable) {
  1207. localSDP.removeUdpCandidates = true;
  1208. }
  1209. if (this.failICE) {
  1210. localSDP.failICE = true;
  1211. }
  1212. if (typeof this.options.channelLastN === 'number' && this.options.channelLastN >= 0) {
  1213. localSDP.initialLastN = this.options.channelLastN;
  1214. }
  1215. localSDP.toJingle(
  1216. accept,
  1217. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  1218. logger.info(`${this} Sending session-accept`);
  1219. logger.debug(accept.tree());
  1220. this.connection.sendIQ(accept,
  1221. success,
  1222. this.newJingleErrorHandler(accept, error => {
  1223. failure(error);
  1224. // 'session-accept' is a critical timeout and we'll
  1225. // have to restart
  1226. this.room.eventEmitter.emit(
  1227. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1228. }),
  1229. IQ_TIMEOUT);
  1230. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1231. // fingerprint and setup) ASAP in order to start the connection
  1232. // establishment.
  1233. //
  1234. // FIXME Flushing the connection at this point triggers an issue with
  1235. // BOSH request handling in Prosody on slow connections.
  1236. //
  1237. // The problem is that this request will be quite large and it may take
  1238. // time before it reaches Prosody. In the meantime Strophe may decide
  1239. // to send the next one. And it was observed that a small request with
  1240. // 'transport-info' usually follows this one. It does reach Prosody
  1241. // before the previous one was completely received. 'rid' on the server
  1242. // is increased and Prosody ignores the request with 'session-accept'.
  1243. // It will never reach Jicofo and everything in the request table is
  1244. // lost. Removing the flush does not guarantee it will never happen, but
  1245. // makes it much less likely('transport-info' is bundled with
  1246. // 'session-accept' and any immediate requests).
  1247. //
  1248. // this.connection.flush();
  1249. }
  1250. /**
  1251. * Will send 'content-modify' IQ in order to ask the remote peer to
  1252. * either stop or resume sending video media or to adjust sender's video constraints.
  1253. * @private
  1254. */
  1255. sendContentModify() {
  1256. const senders = this._localVideoActive ? 'both' : 'none';
  1257. const sessionModify
  1258. = $iq({
  1259. to: this.remoteJid,
  1260. type: 'set'
  1261. })
  1262. .c('jingle', {
  1263. xmlns: 'urn:xmpp:jingle:1',
  1264. action: 'content-modify',
  1265. initiator: this.initiatorJid,
  1266. sid: this.sid
  1267. })
  1268. .c('content', {
  1269. name: MediaType.VIDEO,
  1270. senders
  1271. });
  1272. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  1273. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  1274. sessionModify
  1275. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1276. .attrs({
  1277. sourceName,
  1278. maxHeight
  1279. });
  1280. sessionModify.up();
  1281. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  1282. });
  1283. }
  1284. logger.debug(sessionModify.tree());
  1285. this.connection.sendIQ(
  1286. sessionModify,
  1287. null,
  1288. this.newJingleErrorHandler(sessionModify),
  1289. IQ_TIMEOUT);
  1290. }
  1291. /**
  1292. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1293. * the remote p2p peer.
  1294. *
  1295. * @param {Map<string, number>} sourceReceiverConstraints - The receiver constraints per source.
  1296. */
  1297. setReceiverVideoConstraint(sourceReceiverConstraints) {
  1298. logger.info(`${this} setReceiverVideoConstraint - constraints: ${JSON.stringify(sourceReceiverConstraints)}`);
  1299. this._sourceReceiverConstraints = sourceReceiverConstraints;
  1300. if (this.isP2P) {
  1301. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1302. // be synced after offer/answer.
  1303. if (this.state === JingleSessionState.ACTIVE) {
  1304. this.sendContentModify();
  1305. }
  1306. }
  1307. }
  1308. /**
  1309. * Sends Jingle 'transport-accept' message which is a response to
  1310. * 'transport-replace'.
  1311. * @param localSDP the 'SDP' object with local session description
  1312. * @param success callback called when we receive 'RESULT' packet for
  1313. * 'transport-replace'
  1314. * @param failure function(error) called when we receive an error response
  1315. * or when the request has timed out.
  1316. * @private
  1317. */
  1318. sendTransportAccept(localSDP, success, failure) {
  1319. const transportAccept = $iq({ to: this.remoteJid,
  1320. type: 'set' })
  1321. .c('jingle', {
  1322. xmlns: 'urn:xmpp:jingle:1',
  1323. action: 'transport-accept',
  1324. initiator: this.initiatorJid,
  1325. sid: this.sid
  1326. });
  1327. localSDP.media.forEach((medialines, idx) => {
  1328. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1329. transportAccept.c('content',
  1330. {
  1331. creator:
  1332. this.initiatorJid === this.localJid
  1333. ? 'initiator'
  1334. : 'responder',
  1335. name: mline.media
  1336. }
  1337. );
  1338. localSDP.transportToJingle(idx, transportAccept);
  1339. transportAccept.up();
  1340. });
  1341. logger.info(`${this} Sending transport-accept`);
  1342. logger.debug(transportAccept.tree());
  1343. this.connection.sendIQ(transportAccept,
  1344. success,
  1345. this.newJingleErrorHandler(transportAccept, failure),
  1346. IQ_TIMEOUT);
  1347. }
  1348. /**
  1349. * Sends Jingle 'transport-reject' message which is a response to
  1350. * 'transport-replace'.
  1351. * @param success callback called when we receive 'RESULT' packet for
  1352. * 'transport-replace'
  1353. * @param failure function(error) called when we receive an error response
  1354. * or when the request has timed out.
  1355. *
  1356. * FIXME method should be marked as private, but there's some spaghetti that
  1357. * needs to be fixed prior doing that
  1358. */
  1359. sendTransportReject(success, failure) {
  1360. // Send 'transport-reject', so that the focus will
  1361. // know that we've failed
  1362. const transportReject = $iq({ to: this.remoteJid,
  1363. type: 'set' })
  1364. .c('jingle', {
  1365. xmlns: 'urn:xmpp:jingle:1',
  1366. action: 'transport-reject',
  1367. initiator: this.initiatorJid,
  1368. sid: this.sid
  1369. });
  1370. logger.info(`${this} Sending 'transport-reject'`);
  1371. logger.debug(transportReject.tree());
  1372. this.connection.sendIQ(transportReject,
  1373. success,
  1374. this.newJingleErrorHandler(transportReject, failure),
  1375. IQ_TIMEOUT);
  1376. }
  1377. /**
  1378. * Sets the resolution constraint on the local camera track.
  1379. * @param {number} maxFrameHeight - The user preferred max frame height.
  1380. * @param {string} sourceName - The source name of the track.
  1381. * @returns {Promise} promise that will be resolved when the operation is
  1382. * successful and rejected otherwise.
  1383. */
  1384. setSenderVideoConstraint(maxFrameHeight, sourceName = null) {
  1385. if (this._assertNotEnded()) {
  1386. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}, sourceName: ${sourceName}`);
  1387. const jitsiLocalTrack = sourceName
  1388. ? this.rtc.getLocalVideoTracks().find(track => track.getSourceName() === sourceName)
  1389. : this.rtc.getLocalVideoTrack();
  1390. return this.peerconnection.setSenderVideoConstraints(maxFrameHeight, jitsiLocalTrack);
  1391. }
  1392. return Promise.resolve();
  1393. }
  1394. /**
  1395. * @inheritDoc
  1396. */
  1397. terminate(success, failure, options) {
  1398. if (this.state === JingleSessionState.ENDED) {
  1399. return;
  1400. }
  1401. if (!options || Boolean(options.sendSessionTerminate)) {
  1402. const sessionTerminate
  1403. = $iq({
  1404. to: this.remoteJid,
  1405. type: 'set'
  1406. })
  1407. .c('jingle', {
  1408. xmlns: 'urn:xmpp:jingle:1',
  1409. action: 'session-terminate',
  1410. initiator: this.initiatorJid,
  1411. sid: this.sid
  1412. })
  1413. .c('reason')
  1414. .c((options && options.reason) || 'success')
  1415. .up();
  1416. if (options && options.reasonDescription) {
  1417. sessionTerminate
  1418. .c('text')
  1419. .t(options.reasonDescription)
  1420. .up()
  1421. .up();
  1422. } else {
  1423. sessionTerminate.up();
  1424. }
  1425. this._bridgeSessionId
  1426. && sessionTerminate.c(
  1427. 'bridge-session', {
  1428. xmlns: 'http://jitsi.org/protocol/focus',
  1429. id: this._bridgeSessionId,
  1430. restart: options && options.requestRestart === true
  1431. }).up();
  1432. logger.info(`${this} Sending session-terminate`);
  1433. logger.debug(sessionTerminate.tree());
  1434. this.connection.sendIQ(
  1435. sessionTerminate,
  1436. success,
  1437. this.newJingleErrorHandler(sessionTerminate, failure),
  1438. IQ_TIMEOUT);
  1439. } else {
  1440. logger.info(`${this} Skipped sending session-terminate`);
  1441. }
  1442. // this should result in 'onTerminated' being called by strope.jingle.js
  1443. this.connection.jingle.terminate(this.sid);
  1444. }
  1445. /**
  1446. *
  1447. * @param reasonCondition
  1448. * @param reasonText
  1449. */
  1450. onTerminated(reasonCondition, reasonText) {
  1451. // Do something with reason and reasonCondition when we start to care
  1452. // this.reasonCondition = reasonCondition;
  1453. // this.reasonText = reasonText;
  1454. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1455. this._xmppListeners.forEach(removeListener => removeListener());
  1456. this._xmppListeners = [];
  1457. if (this._removeSenderVideoConstraintsChangeListener) {
  1458. this._removeSenderVideoConstraintsChangeListener();
  1459. }
  1460. if (FeatureFlags.isSsrcRewritingSupported() && this.peerconnection) {
  1461. this.peerconnection.getRemoteTracks().forEach(track => {
  1462. this.room.eventEmitter.emit(JitsiTrackEvents.TRACK_REMOVED, track);
  1463. });
  1464. }
  1465. this.close();
  1466. }
  1467. /**
  1468. * Handles XMPP connection state changes.
  1469. *
  1470. * @param {XmppConnection.Status} status - The new status.
  1471. */
  1472. onXmppStatusChanged(status) {
  1473. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1474. logger.info(`${this} Sending SSRC update on reconnect`);
  1475. this.notifyMySSRCUpdate(
  1476. this._cachedOldLocalSdp,
  1477. this._cachedNewLocalSdp);
  1478. }
  1479. }
  1480. /**
  1481. * Parse the information from the xml sourceAddElem and translate it
  1482. * into sdp lines
  1483. * @param {jquery xml element} sourceAddElem the source-add
  1484. * element from jingle
  1485. * @param {SDP object} currentRemoteSdp the current remote
  1486. * sdp (as of this new source-add)
  1487. * @returns {list} a list of SDP line strings that should
  1488. * be added to the remote SDP
  1489. */
  1490. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1491. const addSsrcInfo = [];
  1492. const self = this;
  1493. $(sourceAddElem).each((i1, content) => {
  1494. const name = $(content).attr('name');
  1495. let lines = '';
  1496. $(content)
  1497. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1498. .each(function() {
  1499. // eslint-disable-next-line no-invalid-this
  1500. const semantics = this.getAttribute('semantics');
  1501. const ssrcs
  1502. = $(this) // eslint-disable-line no-invalid-this
  1503. .find('>source')
  1504. .map(function() {
  1505. // eslint-disable-next-line no-invalid-this
  1506. return this.getAttribute('ssrc');
  1507. })
  1508. .get();
  1509. if (ssrcs.length) {
  1510. lines += `a=ssrc-group:${semantics} ${ssrcs.join(' ')}\r\n`;
  1511. }
  1512. });
  1513. // handles both >source and >description>source
  1514. const tmp
  1515. = $(content).find(
  1516. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1517. /* eslint-disable no-invalid-this */
  1518. tmp.each(function() {
  1519. const ssrc = $(this).attr('ssrc');
  1520. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1521. // Do not print the warning for unified plan p2p case since ssrcs are never removed from the SDP.
  1522. !(self.usesUnifiedPlan && self.isP2P)
  1523. && logger.warn(`${self} Source-add request for existing SSRC: ${ssrc}`);
  1524. return;
  1525. }
  1526. // eslint-disable-next-line newline-per-chained-call
  1527. $(this).find('>parameter').each(function() {
  1528. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1529. if ($(this).attr('value') && $(this).attr('value').length) {
  1530. lines += `:${$(this).attr('value')}`;
  1531. }
  1532. lines += '\r\n';
  1533. });
  1534. });
  1535. let midFound = false;
  1536. /* eslint-enable no-invalid-this */
  1537. currentRemoteSdp.media.forEach((media, i2) => {
  1538. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1539. return;
  1540. }
  1541. if (!addSsrcInfo[i2]) {
  1542. addSsrcInfo[i2] = '';
  1543. }
  1544. addSsrcInfo[i2] += lines;
  1545. midFound = true;
  1546. });
  1547. // In p2p unified mode with multi-stream enabled, the new sources will have content name that doesn't exist
  1548. // in the current remote description. Add a new m-line for this newly signaled source.
  1549. if (!midFound && this.isP2P) {
  1550. addSsrcInfo[name] = lines;
  1551. }
  1552. });
  1553. return addSsrcInfo;
  1554. }
  1555. /**
  1556. * Handles a Jingle source-add message for this Jingle session.
  1557. * @param elem An array of Jingle "content" elements.
  1558. */
  1559. addRemoteStream(elem) {
  1560. this._addOrRemoveRemoteStream(true /* add */, elem);
  1561. }
  1562. /**
  1563. * Handles a Jingle source-remove message for this Jingle session.
  1564. * @param elem An array of Jingle "content" elements.
  1565. */
  1566. removeRemoteStream(elem) {
  1567. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1568. }
  1569. /**
  1570. * Processes the source map message received from the bridge and creates a new remote track for newly signaled
  1571. * SSRCs or updates the source-name and owner on the remote track for an existing SSRC.
  1572. *
  1573. * @param {Object} message - The source map message.
  1574. * @param {string} mediaType - The media type, 'audio' or 'video'.
  1575. * @returns {void}
  1576. */
  1577. processSourceMap(message, mediaType) {
  1578. const newSsrcs = [];
  1579. for (const src of message.mappedSources) {
  1580. // eslint-disable-next-line prefer-const
  1581. let { owner, source, ssrc, videoType } = src;
  1582. const isNewSsrc = this.peerconnection.addRemoteSsrc(ssrc, source);
  1583. let lookupSsrc = ssrc;
  1584. if (isNewSsrc) {
  1585. newSsrcs.push(src);
  1586. // Check if there is an old mapping for the given source and clear the owner on the associated track.
  1587. const oldSsrc = this.peerconnection.remoteSources.get(source);
  1588. if (oldSsrc) {
  1589. lookupSsrc = oldSsrc;
  1590. owner = undefined;
  1591. source = undefined;
  1592. }
  1593. }
  1594. const track = this.peerconnection.getTrackBySSRC(lookupSsrc);
  1595. if (track) {
  1596. logger.debug(`Existing SSRC ${ssrc}: new owner=${owner}, source-name=${source}`);
  1597. // Update the SSRC owner.
  1598. this._signalingLayer.setSSRCOwner(ssrc, owner);
  1599. // Update the track with all the relevant info.
  1600. track.setSourceName(source);
  1601. track.setOwner(owner);
  1602. if (mediaType === MediaType.VIDEO) {
  1603. const type = videoType === 'CAMERA' ? VideoType.CAMERA : VideoType.DESKTOP;
  1604. track._setVideoType(type);
  1605. }
  1606. // Update the muted state on the track since the presence for this track could have been received
  1607. // before the updated source map is received on the bridge channel.
  1608. const peerMediaInfo = this._signalingLayer.getPeerMediaInfo(owner, mediaType, source);
  1609. peerMediaInfo && this.peerconnection._sourceMutedChanged(source, peerMediaInfo.muted);
  1610. }
  1611. }
  1612. // Add the new SSRCs to the remote description by generating a source message.
  1613. if (newSsrcs.length) {
  1614. let node = $build('content', {
  1615. xmlns: 'urn:xmpp:jingle:1',
  1616. name: mediaType
  1617. }).c('description', {
  1618. xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  1619. media: mediaType
  1620. });
  1621. for (const src of newSsrcs) {
  1622. const { rtx, ssrc, source } = src;
  1623. let msid;
  1624. if (mediaType === MediaType.VIDEO) {
  1625. const idx = ++this.numRemoteVideoSources;
  1626. msid = `remote-video-${idx} remote-video-${idx}`;
  1627. if (rtx !== '-1') {
  1628. _addSourceElement(node, src, rtx, msid);
  1629. node.c('ssrc-group', {
  1630. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1631. semantics: 'FID'
  1632. })
  1633. .c('source', {
  1634. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1635. ssrc
  1636. })
  1637. .up()
  1638. .c('source', {
  1639. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  1640. ssrc: rtx
  1641. })
  1642. .up()
  1643. .up();
  1644. }
  1645. } else {
  1646. const idx = ++this.numRemoteAudioSources;
  1647. msid = `remote-audio-${idx} remote-audio-${idx}`;
  1648. }
  1649. _addSourceElement(node, src, ssrc, msid);
  1650. this.peerconnection.remoteSources.set(source, ssrc);
  1651. }
  1652. node = node.up();
  1653. this._addOrRemoveRemoteStream(true /* add */, node.node);
  1654. }
  1655. }
  1656. /**
  1657. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1658. *
  1659. * @param {string} id Endpoint id of the participant that has left the call.
  1660. * @returns {void}
  1661. */
  1662. removeRemoteStreamsOnLeave(id) {
  1663. const workFunction = finishCallback => {
  1664. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1665. if (removeSsrcInfo.length) {
  1666. const newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  1667. this._renegotiate(newRemoteSdp.raw)
  1668. .then(() => finishCallback(), error => finishCallback(error));
  1669. } else {
  1670. finishCallback();
  1671. }
  1672. };
  1673. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1674. this.modificationQueue.push(
  1675. workFunction,
  1676. error => {
  1677. if (error) {
  1678. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1679. } else {
  1680. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1681. }
  1682. });
  1683. }
  1684. /**
  1685. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1686. * Jingle session.
  1687. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1688. * otherwise.
  1689. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1690. * @private
  1691. */
  1692. _addOrRemoveRemoteStream(isAdd, elem) {
  1693. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1694. if (isAdd) {
  1695. this.readSsrcInfo(elem);
  1696. }
  1697. const workFunction = finishedCallback => {
  1698. if (!this.peerconnection.localDescription
  1699. || !this.peerconnection.localDescription.sdp) {
  1700. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1701. logger.error(errMsg);
  1702. finishedCallback(errMsg);
  1703. return;
  1704. }
  1705. logger.log(`${this} Processing ${logPrefix}`);
  1706. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1707. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1708. const addOrRemoveSsrcInfo
  1709. = isAdd
  1710. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1711. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1712. const newRemoteSdp
  1713. = isAdd
  1714. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1715. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1716. const remoteDescription = new RTCSessionDescription({
  1717. type: 'offer',
  1718. sdp: newRemoteSdp.raw
  1719. });
  1720. // Always initiate a sRD->cA->sLD cycle when a remote source is added or removed irrespective of whether
  1721. // the local endpoint is an initiator or responder. Fixes bugs on Chromium where decoders are not created
  1722. // when sLD->cO->sRD cycle is initiated for p2p cases when remote sources are received.
  1723. this._responderRenegotiate(remoteDescription).then(() => {
  1724. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1725. logger.log(`${this} ${logPrefix} - OK`);
  1726. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1727. finishedCallback();
  1728. }, error => {
  1729. logger.error(`${this} ${logPrefix} failed:`, error);
  1730. finishedCallback(error);
  1731. });
  1732. };
  1733. logger.debug(`${this} Queued ${logPrefix} task`);
  1734. // Queue and execute
  1735. this.modificationQueue.push(workFunction);
  1736. }
  1737. /**
  1738. * Takes in a jingle offer iq, returns the new sdp offer
  1739. * @param {jquery xml element} offerIq the incoming offer
  1740. * @returns {SDP object} the jingle offer translated to SDP
  1741. */
  1742. _processNewJingleOfferIq(offerIq) {
  1743. const remoteSdp = new SDP('');
  1744. if (this.webrtcIceTcpDisable) {
  1745. remoteSdp.removeTcpCandidates = true;
  1746. }
  1747. if (this.webrtcIceUdpDisable) {
  1748. remoteSdp.removeUdpCandidates = true;
  1749. }
  1750. if (this.failICE) {
  1751. remoteSdp.failICE = true;
  1752. }
  1753. remoteSdp.fromJingle(offerIq);
  1754. this.readSsrcInfo($(offerIq).find('>content'));
  1755. return remoteSdp;
  1756. }
  1757. /**
  1758. * Remove the given ssrc lines from the current remote sdp
  1759. * @param {list} removeSsrcInfo a list of SDP line strings that
  1760. * should be removed from the remote SDP
  1761. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1762. * in removeSsrcInfo
  1763. */
  1764. _processRemoteRemoveSource(removeSsrcInfo) {
  1765. const remoteSdp = this.usesUnifiedPlan
  1766. ? new SDP(this.peerconnection.peerconnection.remoteDescription.sdp)
  1767. : new SDP(this.peerconnection.remoteDescription.sdp);
  1768. let ssrcs;
  1769. removeSsrcInfo.forEach((lines, idx) => {
  1770. // eslint-disable-next-line no-param-reassign
  1771. lines = lines.split('\r\n');
  1772. lines.pop(); // remove empty last element;
  1773. ssrcs = lines.map(line => Number(line.split('a=ssrc:')[1]?.split(' ')[0]));
  1774. if (this.usesUnifiedPlan) {
  1775. let mid;
  1776. lines.forEach(line => {
  1777. mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1778. if (mid > -1) {
  1779. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1780. if (this.isP2P) {
  1781. const mediaType = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0])?.media;
  1782. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, false);
  1783. [ MediaDirection.SENDRECV, MediaDirection.SENDONLY ].forEach(direction => {
  1784. remoteSdp.media[mid] = remoteSdp.media[mid]
  1785. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1786. });
  1787. } else {
  1788. // Jvb connections will have direction set to 'sendonly' for the remote sources.
  1789. remoteSdp.media[mid] = remoteSdp.media[mid]
  1790. .replace(`a=${MediaDirection.SENDONLY}`, `a=${MediaDirection.INACTIVE}`);
  1791. // Reject the m-line so that the browser removes the associated transceiver from the list
  1792. // of available transceivers. This will prevent the client from trying to re-use these
  1793. // inactive transceivers when additional video sources are added to the peerconnection.
  1794. const { media, port } = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0]);
  1795. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`m=${media} ${port}`, `m=${media} 0`);
  1796. }
  1797. }
  1798. });
  1799. } else {
  1800. lines.forEach(line => {
  1801. remoteSdp.media[idx] = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1802. });
  1803. }
  1804. });
  1805. // Update the ssrc owners list.
  1806. ssrcs?.length && this._signalingLayer.removeSSRCOwners(ssrcs);
  1807. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1808. return remoteSdp;
  1809. }
  1810. /**
  1811. * Add the given ssrc lines to the current remote sdp
  1812. * @param {list} addSsrcInfo a list of SDP line strings that
  1813. * should be added to the remote SDP
  1814. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1815. * in removeSsrcInfo
  1816. */
  1817. _processRemoteAddSource(addSsrcInfo) {
  1818. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1819. // Add a new m-line in the remote description if the source info for a secondary video source is recceived from
  1820. // the remote p2p peer when multi-stream support is enabled.
  1821. if (addSsrcInfo.length > remoteSdp.media.length
  1822. && this.isP2P
  1823. && this.usesUnifiedPlan) {
  1824. remoteSdp.addMlineForNewLocalSource(MediaType.VIDEO);
  1825. remoteSdp = new SDP(remoteSdp.raw);
  1826. }
  1827. addSsrcInfo.forEach((lines, idx) => {
  1828. remoteSdp.media[idx] += lines;
  1829. // Make sure to change the direction to 'sendrecv/sendonly' only for p2p connections. For jvb connections,
  1830. // a new m-line is added for the new remote sources.
  1831. if (this.isP2P && this.usesUnifiedPlan) {
  1832. const mediaType = SDPUtil.parseMLine(remoteSdp.media[idx].split('\r\n')[0])?.media;
  1833. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, true);
  1834. [ MediaDirection.RECVONLY, MediaDirection.INACTIVE ].forEach(direction => {
  1835. remoteSdp.media[idx] = remoteSdp.media[idx]
  1836. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1837. });
  1838. }
  1839. });
  1840. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1841. return remoteSdp;
  1842. }
  1843. /**
  1844. * Do a new o/a flow using the existing remote description
  1845. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1846. * to use. If not provided, the remote sdp from the
  1847. * peerconnection will be used
  1848. * @returns {Promise} promise which resolves when the
  1849. * o/a flow is complete with no arguments or
  1850. * rejects with an error {string}
  1851. */
  1852. _renegotiate(optionalRemoteSdp) {
  1853. if (this.peerconnection.signalingState === 'closed') {
  1854. const error = new Error('Attempted to renegotiate in state closed');
  1855. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1856. return Promise.reject(error);
  1857. }
  1858. const remoteSdp
  1859. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1860. if (!remoteSdp) {
  1861. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1862. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1863. return Promise.reject(error);
  1864. }
  1865. const remoteDescription = new RTCSessionDescription({
  1866. type: this.isInitiator ? 'answer' : 'offer',
  1867. sdp: remoteSdp
  1868. });
  1869. const promise = this.isInitiator
  1870. ? this._initiatorRenegotiate(remoteDescription)
  1871. : this._responderRenegotiate(remoteDescription);
  1872. const oldLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1873. return promise.then(() => {
  1874. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1875. // Send the source updates after every renegotiation cycle.
  1876. oldLocalSDP && this.notifyMySSRCUpdate(oldLocalSDP, newLocalSDP);
  1877. });
  1878. }
  1879. /**
  1880. * Renegotiate cycle implementation for the responder case.
  1881. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1882. * which will be used as remote description in the cycle.
  1883. * @private
  1884. */
  1885. _responderRenegotiate(remoteDescription) {
  1886. logger.debug(`${this} Renegotiate: setting remote description`);
  1887. return this.peerconnection.setRemoteDescription(remoteDescription)
  1888. .then(() => {
  1889. logger.debug(`${this} Renegotiate: creating answer`);
  1890. return this.peerconnection.createAnswer(this.mediaConstraints)
  1891. .then(answer => {
  1892. logger.debug(`${this} Renegotiate: setting local description`);
  1893. return this.peerconnection.setLocalDescription(answer);
  1894. });
  1895. });
  1896. }
  1897. /**
  1898. * Renegotiate cycle implementation for the initiator's case.
  1899. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1900. * which will be used as remote description in the cycle.
  1901. * @private
  1902. */
  1903. _initiatorRenegotiate(remoteDescription) {
  1904. logger.debug(`${this} Renegotiate: creating offer`);
  1905. return this.peerconnection.createOffer(this.mediaConstraints)
  1906. .then(offer => {
  1907. logger.debug(`${this} Renegotiate: setting local description`);
  1908. return this.peerconnection.setLocalDescription(offer)
  1909. .then(() => {
  1910. logger.debug(`${this} Renegotiate: setting remote description`);
  1911. // eslint-disable-next-line max-len
  1912. return this.peerconnection.setRemoteDescription(remoteDescription);
  1913. });
  1914. });
  1915. }
  1916. /**
  1917. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  1918. * being added to the peerconnection for the first time.
  1919. *
  1920. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  1921. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  1922. * otherwise.
  1923. */
  1924. addTracks(localTracks = null) {
  1925. if (!FeatureFlags.isMultiStreamSendSupportEnabled()
  1926. || !localTracks?.length
  1927. || localTracks.find(track => track.getType() !== MediaType.VIDEO)) {
  1928. return Promise.reject(new Error('Multiple tracks of the given media type are not supported'));
  1929. }
  1930. const replaceTracks = [];
  1931. const workFunction = finishedCallback => {
  1932. const remoteSdp = new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1933. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  1934. .find(t => t.receiver.track.kind === MediaType.VIDEO
  1935. && t.direction === MediaDirection.RECVONLY
  1936. && t.currentDirection === MediaDirection.RECVONLY);
  1937. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  1938. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  1939. // existing one in that case.
  1940. for (const track of localTracks) {
  1941. if (!this.isP2P || !recvOnlyTransceiver) {
  1942. remoteSdp.addMlineForNewLocalSource(track.getType());
  1943. }
  1944. }
  1945. const remoteDescription = new RTCSessionDescription({
  1946. type: 'offer',
  1947. sdp: remoteSdp.raw
  1948. });
  1949. // Always initiate a responder renegotiate since the new m-line is added to remote SDP.
  1950. this._responderRenegotiate(remoteDescription)
  1951. .then(() => {
  1952. // Replace the tracks on the newly generated transceivers.
  1953. for (const track of localTracks) {
  1954. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  1955. }
  1956. return Promise.all(replaceTracks);
  1957. })
  1958. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  1959. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  1960. .then(() => this._renegotiate())
  1961. .then(() => finishedCallback(), error => finishedCallback(error));
  1962. };
  1963. return new Promise((resolve, reject) => {
  1964. logger.debug(`${this} Queued renegotiation after addTrack`);
  1965. this.modificationQueue.push(
  1966. workFunction,
  1967. error => {
  1968. if (error) {
  1969. logger.error(`${this} renegotiation after addTrack error`, error);
  1970. reject(error);
  1971. } else {
  1972. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  1973. resolve();
  1974. }
  1975. });
  1976. });
  1977. }
  1978. /**
  1979. * Resumes or suspends media transfer over the underlying peer connection.
  1980. *
  1981. * @param {boolean} active - <tt>true</tt> to enable media transfer or <tt>false</tt> to suspend media transmission
  1982. * @returns {Promise}
  1983. */
  1984. setMediaTransferActive(active) {
  1985. return this.peerconnection.tpcUtils.setMediaTransferActive(active)
  1986. .then(() => {
  1987. this.peerconnection.audioTransferActive = active;
  1988. this.peerconnection.videoTransferActive = active;
  1989. // Reconfigure the video tracks so that only the correct encodings are active.
  1990. const promises = [];
  1991. for (const track of this.rtc.getLocalVideoTracks()) {
  1992. promises.push(this.peerconnection.configureSenderVideoEncodings(track));
  1993. }
  1994. return Promise.allSettled(promises);
  1995. });
  1996. }
  1997. /**
  1998. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1999. * offer/answer cycle after both operations are done. Either
  2000. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  2001. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  2002. * <tt>oldTrack</tt>
  2003. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  2004. * replaced
  2005. * @param {JitsiLocalTrack|null} newTrack the new track to use
  2006. * @returns {Promise} which resolves once the replacement is complete
  2007. * with no arguments or rejects with an error {string}
  2008. */
  2009. replaceTrack(oldTrack, newTrack) {
  2010. const workFunction = finishedCallback => {
  2011. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  2012. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  2013. if (!this.usesUnifiedPlan) {
  2014. // NOTE the code below assumes that no more than 1 video track
  2015. // can be added to the peer connection.
  2016. // Transition from camera to desktop share
  2017. // or transition from one camera source to another.
  2018. if (this.peerconnection.options.capScreenshareBitrate
  2019. && oldTrack && newTrack && newTrack.isVideoTrack()) {
  2020. // Clearing current primary SSRC will make
  2021. // the SdpConsistency generate a new one which will result
  2022. // with:
  2023. // 1. source-remove for the old video stream.
  2024. // 2. source-add for the new video stream.
  2025. this.peerconnection.clearRecvonlySsrc();
  2026. }
  2027. // Transition from no video to video (unmute).
  2028. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  2029. // Clearing current primary SSRC will make
  2030. // the SdpConsistency generate a new one which will result
  2031. // with:
  2032. // 1. source-remove for the recvonly
  2033. // 2. source-add for the new video stream
  2034. this.peerconnection.clearRecvonlySsrc();
  2035. // Transition from video to no video
  2036. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  2037. // Clearing current primary SSRC and generating the recvonly
  2038. // will result in:
  2039. // 1. source-remove for the old video stream
  2040. // 2. source-add for the recvonly stream
  2041. this.peerconnection.clearRecvonlySsrc();
  2042. this.peerconnection.generateRecvonlySsrc();
  2043. }
  2044. }
  2045. this.peerconnection.replaceTrack(oldTrack, newTrack)
  2046. .then(shouldRenegotiate => {
  2047. let promise = Promise.resolve();
  2048. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  2049. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  2050. if (shouldRenegotiate
  2051. && (oldTrack || newTrack)
  2052. && this.state === JingleSessionState.ACTIVE) {
  2053. const remoteSdp = this.peerconnection.remoteDescription.sdp;
  2054. const remoteDescription = new RTCSessionDescription({
  2055. type: 'offer',
  2056. sdp: remoteSdp
  2057. });
  2058. // Always initiate a sRD->cA->sLD cycle since renegotiation fails in the following scenario.
  2059. // In a p2p call when channelLastN=0, the direction on the video tranceiver is set to
  2060. // 'inactive'. At this point, if the user unmutes, the track is replaced on the video sender.
  2061. // If a cO->sLD->sRD is triggered, the browser adds a third m-line which isn't expected and
  2062. // possibly is a bug. All renegotiations fail as a result. However, the browser does not add a
  2063. // third m-line in the answer it generates and renegotiation succeeds.
  2064. promise = this._responderRenegotiate(remoteDescription).then(() => {
  2065. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  2066. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSDP);
  2067. });
  2068. }
  2069. return promise.then(() => {
  2070. // Set the source name of the new track.
  2071. if (oldTrack
  2072. && newTrack
  2073. && oldTrack.isVideoTrack()) {
  2074. newTrack.setSourceName(oldTrack.getSourceName());
  2075. }
  2076. });
  2077. })
  2078. .then(() => finishedCallback(), error => finishedCallback(error));
  2079. };
  2080. return new Promise((resolve, reject) => {
  2081. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  2082. this.modificationQueue.push(
  2083. workFunction,
  2084. error => {
  2085. if (error) {
  2086. logger.error(`${this} Replace track error:`, error);
  2087. reject(error);
  2088. } else {
  2089. logger.info(`${this} Replace track done!`);
  2090. resolve();
  2091. }
  2092. });
  2093. });
  2094. }
  2095. /**
  2096. * Parse the information from the xml sourceRemoveElem and translate it
  2097. * into sdp lines
  2098. * @param {jquery xml element} sourceRemoveElem the source-remove
  2099. * element from jingle
  2100. * @param {SDP object} currentRemoteSdp the current remote
  2101. * sdp (as of this new source-remove)
  2102. * @returns {list} a list of SDP line strings that should
  2103. * be removed from the remote SDP
  2104. */
  2105. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  2106. const removeSsrcInfo = [];
  2107. $(sourceRemoveElem).each((i1, content) => {
  2108. const name = $(content).attr('name');
  2109. let lines = '';
  2110. $(content)
  2111. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  2112. .each(function() {
  2113. /* eslint-disable no-invalid-this */
  2114. const semantics = this.getAttribute('semantics');
  2115. const ssrcs
  2116. = $(this)
  2117. .find('>source')
  2118. .map(function() {
  2119. return this.getAttribute('ssrc');
  2120. })
  2121. .get();
  2122. if (ssrcs.length) {
  2123. lines
  2124. += `a=ssrc-group:${semantics} ${
  2125. ssrcs.join(' ')}\r\n`;
  2126. }
  2127. /* eslint-enable no-invalid-this */
  2128. });
  2129. const ssrcs = [];
  2130. // handles both >source and >description>source versions
  2131. const tmp
  2132. = $(content).find(
  2133. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  2134. tmp.each(function() {
  2135. // eslint-disable-next-line no-invalid-this
  2136. const ssrc = $(this).attr('ssrc');
  2137. ssrcs.push(ssrc);
  2138. });
  2139. currentRemoteSdp.media.forEach((media, i2) => {
  2140. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  2141. return;
  2142. }
  2143. if (!removeSsrcInfo[i2]) {
  2144. removeSsrcInfo[i2] = '';
  2145. }
  2146. ssrcs.forEach(ssrc => {
  2147. const ssrcLines
  2148. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  2149. if (ssrcLines.length) {
  2150. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  2151. }
  2152. });
  2153. removeSsrcInfo[i2] += lines;
  2154. });
  2155. });
  2156. return removeSsrcInfo;
  2157. }
  2158. /**
  2159. * Will print an error if there is any difference, between the SSRCs given
  2160. * in the <tt>oldSDP</tt> and the ones currently described in
  2161. * the peerconnection's local description.
  2162. * @param {string} operationName the operation's name which will be printed
  2163. * in the error message.
  2164. * @param {SDP} oldSDP the old local SDP which will be compared with
  2165. * the current one.
  2166. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  2167. * otherwise.
  2168. * @private
  2169. */
  2170. _verifyNoSSRCChanged(operationName, oldSDP) {
  2171. const currentLocalSDP
  2172. = new SDP(this.peerconnection.localDescription.sdp);
  2173. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  2174. const addedMedia = sdpDiff.getNewMedia();
  2175. if (Object.keys(addedMedia).length) {
  2176. logger.error(`${this} - some SSRC were added on ${operationName}`, addedMedia);
  2177. return false;
  2178. }
  2179. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  2180. const removedMedia = sdpDiff.getNewMedia();
  2181. if (Object.keys(removedMedia).length) {
  2182. logger.error(`${this} - some SSRCs were removed on ${operationName}`, removedMedia);
  2183. return false;
  2184. }
  2185. return true;
  2186. }
  2187. /**
  2188. * Adds local track back to the peerconnection associated with this session.
  2189. * @param {JitsiLocalTrack} track
  2190. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  2191. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  2192. * details in case something goes wrong.
  2193. */
  2194. addTrackToPc(track) {
  2195. return this._addRemoveTrack(false /* add */, track)
  2196. .then(() => {
  2197. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  2198. // unmutes it the first time, all the parameters need to be configured.
  2199. if (track.isVideoTrack()) {
  2200. return this.peerconnection.configureSenderVideoEncodings(track);
  2201. }
  2202. });
  2203. }
  2204. /**
  2205. * Remove local track as part of the mute operation.
  2206. * @param {JitsiLocalTrack} track the local track to be removed
  2207. * @return {Promise} a promise which will be resolved once the local track
  2208. * is removed from this session and the renegotiation is performed.
  2209. * The promise will be rejected with a <tt>string</tt> that the describes
  2210. * the error if anything goes wrong.
  2211. */
  2212. removeTrackFromPc(track) {
  2213. return this._addRemoveTrack(true /* remove */, track);
  2214. }
  2215. /**
  2216. * See {@link addTrackToPc} and {@link removeTrackFromPc}.
  2217. * @param {boolean} isRemove <tt>true</tt> for "remove" operation or <tt>false</tt> for "add" operation.
  2218. * @param {JitsiLocalTrack} track the track that will be added/removed
  2219. * @private
  2220. */
  2221. _addRemoveTrack(isRemove, track) {
  2222. if (!track) {
  2223. return Promise.reject('invalid "track" argument value');
  2224. }
  2225. const operationName = isRemove ? 'removeTrack' : 'addTrack';
  2226. const workFunction = finishedCallback => {
  2227. const tpc = this.peerconnection;
  2228. if (!tpc) {
  2229. finishedCallback(`Error: tried ${operationName} track with no active peer connection`);
  2230. return;
  2231. }
  2232. const oldLocalSDP = tpc.localDescription.sdp;
  2233. const operationPromise
  2234. = isRemove
  2235. ? tpc.removeTrackFromPc(track)
  2236. : tpc.addTrackToPc(track);
  2237. operationPromise
  2238. .then(shouldRenegotiate => {
  2239. if (shouldRenegotiate && oldLocalSDP && tpc.remoteDescription.sdp) {
  2240. this._renegotiate()
  2241. .then(() => {
  2242. // The results are ignored, as this check failure is not enough to fail the whole
  2243. // operation. It will log an error inside for plan-b.
  2244. !this.usesUnifiedPlan && this._verifyNoSSRCChanged(operationName, new SDP(oldLocalSDP));
  2245. finishedCallback();
  2246. });
  2247. } else {
  2248. finishedCallback();
  2249. }
  2250. },
  2251. finishedCallback /* will be called with an error */);
  2252. };
  2253. logger.debug(`${this} Queued ${operationName} task`);
  2254. return new Promise((resolve, reject) => {
  2255. this.modificationQueue.push(
  2256. workFunction,
  2257. error => {
  2258. if (error) {
  2259. logger.error(`${this} ${operationName} failed`);
  2260. reject(error);
  2261. } else {
  2262. logger.debug(`${this} ${operationName} done`);
  2263. resolve();
  2264. }
  2265. });
  2266. });
  2267. }
  2268. /**
  2269. * Resumes or suspends video media transfer over the p2p peer connection.
  2270. *
  2271. * @param {boolean} videoActive <tt>true</tt> to enable video media transfer or <tt>false</tt> to suspend video
  2272. * media transmission.
  2273. * @return {Promise} a <tt>Promise</tt> which will resolve once the operation is done. It will be rejected with
  2274. * an error description as a string in case anything goes wrong.
  2275. */
  2276. setP2pVideoTransferActive(videoActive) {
  2277. if (!this.peerconnection) {
  2278. return Promise.reject('Can not modify video transfer active state,'
  2279. + ' before "initialize" is called');
  2280. }
  2281. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  2282. logger.info(`${this} Queued make ${logVideoStr} task`);
  2283. const workFunction = finishedCallback => {
  2284. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  2285. if (this._localVideoActive !== videoActive) {
  2286. this._localVideoActive = videoActive;
  2287. if (this.isP2P && isSessionActive) {
  2288. this.sendContentModify();
  2289. }
  2290. }
  2291. this.peerconnection.setVideoTransferActive(this._localVideoActive && this._remoteVideoActive);
  2292. // Always initiate a renegotiation cycle for p2p connection when the media direction is changed.
  2293. this._renegotiate()
  2294. .then(() => finishedCallback())
  2295. .catch(error => finishedCallback(error));
  2296. };
  2297. return new Promise((resolve, reject) => {
  2298. this.modificationQueue.push(
  2299. workFunction,
  2300. error => {
  2301. if (error) {
  2302. logger.error(`${this} Make ${logVideoStr} task failed!`);
  2303. reject(error);
  2304. } else {
  2305. logger.debug(`${this} Make ${logVideoStr} task done!`);
  2306. resolve();
  2307. }
  2308. });
  2309. });
  2310. }
  2311. /**
  2312. * Will put and execute on the queue a session modify task. It checks if the sourceMaxFrameHeight (as requested by
  2313. * the p2p peer) or the senders attribute of the video content has changed and modifies the local video sources
  2314. * accordingly.
  2315. */
  2316. modifyContents(jingleContents) {
  2317. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  2318. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  2319. if (sourceMaxFrameHeights) {
  2320. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  2321. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  2322. }
  2323. if (newVideoSenders === null) {
  2324. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  2325. return;
  2326. }
  2327. const workFunction = finishedCallback => {
  2328. if (this._assertNotEnded() && this._modifyRemoteVideoActive(newVideoSenders)) {
  2329. // Will do the sRD/sLD cycle to update SDPs and adjust the media direction.
  2330. this._renegotiate()
  2331. .then(finishedCallback, finishedCallback /* (error) */);
  2332. } else {
  2333. finishedCallback();
  2334. }
  2335. };
  2336. logger.debug(`${this} queued "content-modify" task(video senders="${newVideoSenders}")`);
  2337. this.modificationQueue.push(
  2338. workFunction,
  2339. error => {
  2340. if (error) {
  2341. logger.error(`${this} "content-modify" failed`, error);
  2342. } else {
  2343. logger.debug(`${this} "content-modify" task(video senders="${newVideoSenders}") done`);
  2344. }
  2345. });
  2346. }
  2347. /**
  2348. * Processes new value of remote video "senders" Jingle attribute and tries to apply it for
  2349. * {@link _remoteVideoActive}.
  2350. * @param {string} remoteVideoSenders the value of "senders" attribute of Jingle video content element advertised
  2351. * by remote peer.
  2352. * @return {boolean} <tt>true</tt> if the change affected state of the underlying peerconnection and renegotiation
  2353. * is required for the changes to take effect.
  2354. * @private
  2355. */
  2356. _modifyRemoteVideoActive(remoteVideoSenders) {
  2357. const isRemoteVideoActive
  2358. = remoteVideoSenders === 'both'
  2359. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  2360. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  2361. if (isRemoteVideoActive !== this._remoteVideoActive) {
  2362. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  2363. this._remoteVideoActive = isRemoteVideoActive;
  2364. return this.peerconnection.setVideoTransferActive(this._localVideoActive && this._remoteVideoActive);
  2365. }
  2366. return false;
  2367. }
  2368. /**
  2369. * Figures out added/removed ssrcs and send update IQs.
  2370. * @param oldSDP SDP object for old description.
  2371. * @param newSDP SDP object for new description.
  2372. */
  2373. notifyMySSRCUpdate(oldSDP, newSDP) {
  2374. if (this.state !== JingleSessionState.ACTIVE) {
  2375. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  2376. return;
  2377. }
  2378. if (!this.connection.connected) {
  2379. // The goal is to compare the oldest SDP with the latest one upon reconnect
  2380. if (!this._cachedOldLocalSdp) {
  2381. this._cachedOldLocalSdp = oldSDP;
  2382. }
  2383. this._cachedNewLocalSdp = newSDP;
  2384. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  2385. return;
  2386. }
  2387. this._cachedOldLocalSdp = undefined;
  2388. this._cachedNewLocalSdp = undefined;
  2389. const getSignaledSourceInfo = sdpDiffer => {
  2390. const newMedia = sdpDiffer.getNewMedia();
  2391. let ssrcs = [];
  2392. let mediaType = null;
  2393. // It is assumed that sources are signaled one at a time.
  2394. Object.keys(newMedia).forEach(mediaIndex => {
  2395. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  2396. mediaType = newMedia[mediaIndex].mid;
  2397. if (signaledSsrcs?.length) {
  2398. ssrcs = ssrcs.concat(signaledSsrcs);
  2399. }
  2400. });
  2401. return {
  2402. mediaType,
  2403. ssrcs
  2404. };
  2405. };
  2406. // send source-remove IQ.
  2407. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  2408. const remove = $iq({ to: this.remoteJid,
  2409. type: 'set' })
  2410. .c('jingle', {
  2411. xmlns: 'urn:xmpp:jingle:1',
  2412. action: 'source-remove',
  2413. initiator: this.initiatorJid,
  2414. sid: this.sid
  2415. }
  2416. );
  2417. sdpDiffer.toJingle(remove);
  2418. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  2419. // need to
  2420. const ctx = {};
  2421. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2422. if (removedSsrcInfo.ssrcs.length) {
  2423. // Log only the SSRCs instead of the full IQ.
  2424. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  2425. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  2426. this.connection.sendIQ(
  2427. remove,
  2428. () => {
  2429. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  2430. },
  2431. this.newJingleErrorHandler(remove, error => {
  2432. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  2433. }),
  2434. IQ_TIMEOUT);
  2435. }
  2436. // send source-add IQ.
  2437. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  2438. const add = $iq({ to: this.remoteJid,
  2439. type: 'set' })
  2440. .c('jingle', {
  2441. xmlns: 'urn:xmpp:jingle:1',
  2442. action: 'source-add',
  2443. initiator: this.initiatorJid,
  2444. sid: this.sid
  2445. }
  2446. );
  2447. sdpDiffer.toJingle(add);
  2448. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2449. if (addedSsrcInfo.ssrcs.length) {
  2450. // Log only the SSRCs instead of the full IQ.
  2451. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  2452. this.connection.sendIQ(
  2453. add,
  2454. () => {
  2455. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  2456. },
  2457. this.newJingleErrorHandler(add, error => {
  2458. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  2459. }),
  2460. IQ_TIMEOUT);
  2461. }
  2462. }
  2463. /**
  2464. * Method returns function(errorResponse) which is a callback to be passed
  2465. * to Strophe connection.sendIQ method. An 'error' structure is created that
  2466. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  2467. * structure is as follows:
  2468. * {
  2469. * code: {XMPP error response code}
  2470. * reason: {the name of XMPP error reason element or 'timeout' if the
  2471. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  2472. * source: {request.tree() that provides original request}
  2473. * session: {this JingleSessionPC.toString()}
  2474. * }
  2475. * @param request Strophe IQ instance which is the request to be dumped into
  2476. * the error structure
  2477. * @param failureCb function(error) called when error response was returned
  2478. * or when a timeout has occurred.
  2479. * @returns {function(this:JingleSessionPC)}
  2480. */
  2481. newJingleErrorHandler(request, failureCb) {
  2482. return errResponse => {
  2483. const error = {};
  2484. // Get XMPP error code and condition(reason)
  2485. const errorElSel = $(errResponse).find('error');
  2486. if (errorElSel.length) {
  2487. error.code = errorElSel.attr('code');
  2488. const errorReasonSel = $(errResponse).find('error :first');
  2489. if (errorReasonSel.length) {
  2490. error.reason = errorReasonSel[0].tagName;
  2491. }
  2492. const errorMsgSel = errorElSel.find('>text');
  2493. if (errorMsgSel.length) {
  2494. error.msg = errorMsgSel.text();
  2495. }
  2496. }
  2497. if (!errResponse) {
  2498. error.reason = 'timeout';
  2499. }
  2500. error.session = this.toString();
  2501. if (failureCb) {
  2502. failureCb(error);
  2503. } else if (this.state === JingleSessionState.ENDED
  2504. && error.reason === 'item-not-found') {
  2505. // When remote peer decides to terminate the session, but it
  2506. // still have few messages on the queue for processing,
  2507. // it will first send us 'session-terminate' (we enter ENDED)
  2508. // and then follow with 'item-not-found' for the queued requests
  2509. // We don't want to have that logged on error level.
  2510. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  2511. } else {
  2512. GlobalOnErrorHandler.callErrorHandler(
  2513. new Error(
  2514. `Jingle error: ${JSON.stringify(error)}`));
  2515. }
  2516. };
  2517. }
  2518. /**
  2519. * Returns the ice connection state for the peer connection.
  2520. * @returns the ice connection state for the peer connection.
  2521. */
  2522. getIceConnectionState() {
  2523. return this.peerconnection.getConnectionState();
  2524. }
  2525. /**
  2526. * Closes the peerconnection.
  2527. */
  2528. close() {
  2529. this.state = JingleSessionState.ENDED;
  2530. this.establishmentDuration = undefined;
  2531. if (this.peerconnection) {
  2532. this.peerconnection.onicecandidate = null;
  2533. this.peerconnection.oniceconnectionstatechange = null;
  2534. this.peerconnection.onnegotiationneeded = null;
  2535. this.peerconnection.onsignalingstatechange = null;
  2536. }
  2537. logger.debug(`${this} Clearing modificationQueue`);
  2538. // Remove any pending tasks from the queue
  2539. this.modificationQueue.clear();
  2540. logger.debug(`${this} Queued PC close task`);
  2541. this.modificationQueue.push(finishCallback => {
  2542. // do not try to close if already closed.
  2543. this.peerconnection && this.peerconnection.close();
  2544. finishCallback();
  2545. logger.debug(`${this} PC close task done!`);
  2546. });
  2547. logger.debug(`${this} Shutdown modificationQueue!`);
  2548. // No more tasks can go in after the close task
  2549. this.modificationQueue.shutdown();
  2550. }
  2551. /**
  2552. * Converts to string with minor summary.
  2553. * @return {string}
  2554. */
  2555. toString() {
  2556. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2557. }
  2558. }