From 856c6dd552252e42632541c5109e451cca3d7a15 Mon Sep 17 00:00:00 2001
From: c vw <dl1ycf@darc.de>
Date: Tue, 4 Jan 2022 14:17:29 +0100
Subject: [PATCH] Test code for Paul to address the "Residual audio" problem,
 to be removed if issue has settled down.

---
 radio.c    |  4 ++++
 receiver.c | 17 +++++++++++++++++
 receiver.h |  2 ++
 3 files changed, 23 insertions(+)

diff --git a/radio.c b/radio.c
index 03ab357..c2fab28 100644
--- a/radio.c
+++ b/radio.c
@@ -1546,6 +1546,10 @@ static void rxtx(int state) {
         gtk_fixed_put(GTK_FIXED(fixed),receiver[i]->panel,receiver[i]->x,receiver[i]->y);
         SetChannelState(receiver[i]->id,1,0);
         set_displaying(receiver[i],1);
+        receiver[i]->rxcount=0;
+        receiver[i]->maxcount=-1;
+	// if not duplex, clear RX iq buffer
+        receiver[i]->samples=0;
       }
     }
   }
diff --git a/receiver.c b/receiver.c
index d350565..933cc5f 100644
--- a/receiver.c
+++ b/receiver.c
@@ -1238,6 +1238,8 @@ g_print("%s: rx=%p id=%d local_audio=%d\n",__FUNCTION__,rx,rx->id,rx->local_audi
 
   // defer set_agc until here, otherwise the AGC threshold is not computed correctly
   set_agc(rx, rx->agc);
+
+  rx->rxcount=99999;
   return rx;
 }
 
@@ -1250,6 +1252,7 @@ void receiver_change_sample_rate(RECEIVER *rx,int sample_rate) {
   g_mutex_lock(&rx->mutex);
 
   rx->sample_rate=sample_rate;
+  rx->samples=0;  // clear RX iq buffer
   int scale=rx->sample_rate/48000;
   rx->output_samples=rx->buffer_size/scale;
   rx->hz_per_pixel=(double)rx->sample_rate/(double)rx->width;
@@ -1496,6 +1499,20 @@ static int rx_buffer_seen=0;
 static int tx_buffer_seen=0;
 
 void add_iq_samples(RECEIVER *rx, double i_sample,double q_sample) {
+
+  if (rx->rxcount <= 20000) {
+    if (i_sample*i_sample + q_sample*q_sample > 0.01) rx->maxcount=rx->rxcount;
+    if (rx->rxcount < (int)(rx->sample_rate >> 5)) {
+      i_sample=0.0;
+      q_sample=0.0;
+    }
+    if (rx->rxcount == 20000) {
+      fprintf(stderr,"ID=%d MAXCOUNT=%d\n", rx->id, rx->maxcount);
+      rx->rxcount = 99999;
+    }
+    rx->rxcount++;
+  }
+
   rx->iq_input_buffer[rx->samples*2]=i_sample;
   rx->iq_input_buffer[(rx->samples*2)+1]=q_sample;
   rx->samples=rx->samples+1;
diff --git a/receiver.h b/receiver.h
index 5792b3c..d72b0c6 100644
--- a/receiver.h
+++ b/receiver.h
@@ -166,6 +166,8 @@ typedef struct _receiver {
 
   gint x;
   gint y;
+
+  int rxcount; int maxcount;
 } RECEIVER;
 
 extern RECEIVER *create_pure_signal_receiver(int id, int buffer_size,int sample_rate,int pixels);
-- 
2.45.2