Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 82KB

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