modified lib-jitsi-meet dev repo
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 83KB

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