From 25edf87b7b43bb139ebfe308eca9625eef974c2e Mon Sep 17 00:00:00 2001
From: prog <youssef@airspy.com>
Date: Sun, 24 Jun 2018 10:48:19 +0200
Subject: [PATCH 4/7] Improved the envelope detection mechanism in the IQ
 balancer.

---
 libairspyhf/src/airspyhf.h   | 4 ++--
 libairspyhf/src/iqbalancer.c | 7 +++++--
 libairspyhf/src/iqbalancer.h | 2 ++
 3 files changed, 9 insertions(+), 4 deletions(-)

diff --git a/libairspyhf/src/airspyhf.h b/libairspyhf/src/airspyhf.h
index 06fe5b6..6447223 100644
--- a/libairspyhf/src/airspyhf.h
+++ b/libairspyhf/src/airspyhf.h
@@ -28,10 +28,10 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSI
 
 #include <stdint.h>
 
-#define AIRSPYHF_VERSION "1.1.6"
+#define AIRSPYHF_VERSION "1.1.7"
 #define AIRSPYHF_VER_MAJOR 1
 #define AIRSPYHF_VER_MINOR 1
-#define AIRSPYHF_VER_REVISION 6
+#define AIRSPYHF_VER_REVISION 7
 
 #define AIRSPYHF_ENDPOINT_IN (1)
 
diff --git a/libairspyhf/src/iqbalancer.c b/libairspyhf/src/iqbalancer.c
index 9ccecd9..3ed643b 100644
--- a/libairspyhf/src/iqbalancer.c
+++ b/libairspyhf/src/iqbalancer.c
@@ -316,8 +316,11 @@ static void adjust_phase_amplitude(iq_balancer_t *iq_balancer, airspyhf_complex_
 		re = iq[i].re * iq[i].re;
 		im = iq[i].im * iq[i].im;
 
-		iq_balancer->iampavg += BalanceTimeConst * (re - iq_balancer->iampavg);
-		iq_balancer->qampavg_pre += BalanceTimeConst * (im - iq_balancer->qampavg_pre);
+		double idelta = iq[i].re * iq[i].re - iq_balancer->iampavg;
+		iq_balancer->iampavg += (idelta > 0.0 ? BalanceAttackTimeConst : BalanceDecayTimeConst) * idelta;
+
+		double qdelta = iq[i].im * iq[i].im - iq_balancer->qampavg_pre;
+		iq_balancer->qampavg_pre += (qdelta > 0.0 ? BalanceAttackTimeConst : BalanceDecayTimeConst) * qdelta;
 
 		if (iq_balancer->qampavg_pre != 0)
 		{
diff --git a/libairspyhf/src/iqbalancer.h b/libairspyhf/src/iqbalancer.h
index 2af5423..da0ddcb 100644
--- a/libairspyhf/src/iqbalancer.h
+++ b/libairspyhf/src/iqbalancer.h
@@ -31,6 +31,8 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSI
 #define SkippedBuffers 4
 #define DcTimeConst 1e-5f
 #define BalanceTimeConst 2.5e-6f
+#define BalanceAttackTimeConst 1e-6f
+#define BalanceDecayTimeConst 1e-8f
 #define AlphaContributionScale 0.01f
 #define MinAlphaContribution 1e-8f
 #define MaxAlphaContribution 1e-3f
-- 
2.11.0

