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 101KB

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