modified lib-jitsi-meet dev repo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 80KB

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