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

JingleSessionPC.js 90KB

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