Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JingleSessionPC.js 94KB

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