Using AI to modify WS for two RX stereo input

I played a little with Google’s AI; the regular one that is part of their search engine. It cannot fetch source code from repositories but you can upload bits a pieces there so that it can analyze and modify them. While AI might struggle in many areas, code analysis and development definitely is not one of them!

So, I started discussing how to modify WS (former WSJT-X Improved) to read audio data separately from the left and right stereo channels of the radio sound card. My radio (Elecraft K4) has two RXs and they output their audio data to left and right stereo channels. What I wanted to do is to get the functionality of the multi program into one GUI.

I asked it to modify the WS source code to read data from those channels separately, present spectrum & waterfall display for them in separate windows, compare decodes from the channels, and show the strongest decode in the WS decode window. Furthermore, I asked it to label the decodes so that I know from which channel it came from. Both RX and TX cursors on the two graph displays should be locked to each other in the two graph displays.

After quite a bit of debugging back and forth (i.e., it asked me to run several commands and/or upload files), it finally came up with something that works! Now I have a version of WS that has the functionality of the multi program! There was an interesting instance where there was a bug in the spectrum display for one of the channels (random intense spikes). I uploaded a screenshot to it and it immediately understood what was wrong and presented a fix. Amazing – I felt that I was in old Star Trek movie where folks always talked to the computer!

Here is the patch:

diff --git a/Audio/soundin.cpp b/Audio/soundin.cpp
index fc8e08e..2447353 100755
--- a/Audio/soundin.cpp
+++ b/Audio/soundin.cpp
@@ -54,10 +54,11 @@ void SoundInput::start(QAudioDeviceInfo const& device, int framesPerBuffer, Audi
   stop ();
 
   m_sink = sink;
+  channel = AudioDevice::Both; // Always capture stereo L/R for dual-channel decoding
 
   QAudioFormat format (device.preferredFormat());
 //  qDebug () << "Preferred audio input format:" << format;
-  format.setChannelCount (AudioDevice::Mono == channel ? 1 : 2);
+  format.setChannelCount (2);
   format.setCodec ("audio/pcm");
   format.setSampleRate (12000 * downSampleFactor);
   format.setSampleType (QAudioFormat::SignedInt);
@@ -70,9 +71,14 @@ void SoundInput::start(QAudioDeviceInfo const& device, int framesPerBuffer, Audi
     }
   else if (!device.isFormatSupported (format))
     {
-//      qDebug () << "Nearest supported audio format:" << device.nearestFormat (format);
-      Q_EMIT error (tr ("Requested input audio format is not supported on device."));
-      return;
+      // Fallback to Mono if hardware device strictly refuses 2 channels
+      format.setChannelCount (1);
+      channel = AudioDevice::Mono;
+      if (!device.isFormatSupported (format))
+        {
+          Q_EMIT error (tr ("Requested input audio format is not supported on device."));
+          return;
+        }
     }
   // qDebug () << "Selected audio input format:" << format;
 
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e0d83ca..b40c403 100755
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -514,6 +514,7 @@ set (wsjt_FSRCS
   lib/fil3.f90
   lib/fil3c.f90
   lib/fil4.f90
+  lib/fil4_r.f90
   lib/fil6521.f90
   lib/filbig.f90
   lib/ft8/filt8.f90
@@ -646,6 +647,7 @@ set (wsjt_FSRCS
   lib/ft4/subtractft4.f90
   lib/sun.f90
   lib/symspec.f90
+  lib/symspec_r.f90
   lib/symspec2.f90
   lib/symspec65.f90
   lib/sync4.f90
diff --git a/Configuration.cpp b/Configuration.cpp
index b958d74..d66731b 100755
--- a/Configuration.cpp
+++ b/Configuration.cpp
@@ -6276,10 +6276,8 @@ void Configuration::impl::update_audio_channels (QComboBox const * source_combo_
         {
           combo_box->setItemData (AudioDevice::Left, combo_box_item_enabled, Qt::UserRole - 1);
           combo_box->setItemData (AudioDevice::Right, combo_box_item_enabled, Qt::UserRole - 1);
-          if (allow_both)
-            {
-              combo_box->setItemData (AudioDevice::Both, combo_box_item_enabled, Qt::UserRole - 1);
-            }
+          (void)allow_both;
+          combo_box->setItemData (AudioDevice::Both, combo_box_item_enabled, Qt::UserRole - 1);
         }
       else if (1 == n)
         {
diff --git a/Detector/Detector.cpp b/Detector/Detector.cpp
index 041c2c3..cbf5c59 100755
--- a/Detector/Detector.cpp
+++ b/Detector/Detector.cpp
@@ -9,9 +9,11 @@
 
 extern "C" {
   void   fil4_(qint16*, qint32*, qint16*, qint32*);
+  void   fil4_r_(qint16*, qint32*, qint16*, qint32*);
 }
 
 extern dec_data_t dec_data;
+dec_data_t dec_data_R;
 
 Detector::Detector (unsigned frameRate, double periodLengthInSeconds,
                     unsigned downSampleFactor, QObject * parent)
@@ -22,6 +24,8 @@ Detector::Detector (unsigned frameRate, double periodLengthInSeconds,
   , m_samplesPerFFT {max_buffer_size}
   , m_buffer ((downSampleFactor > 1) ?
               new short [max_buffer_size * downSampleFactor] : nullptr)
+  , m_bufferR ((downSampleFactor > 1) ?
+               new short [max_buffer_size * downSampleFactor] : nullptr)
   , m_bufferPos (0)
 {
   (void)m_frameRate;            // quell compiler warning
@@ -52,6 +56,7 @@ void Detector::clear ()
   // unsigned msInPeriod ((now % 86400000LL) % (m_period * 1000));
   // dec_data.params.kin = qMin ((msInPeriod * m_frameRate) / 1000, static_cast<unsigned> (sizeof (dec_data.d2) / sizeof (dec_data.d2[0])));
   dec_data.params.kin = 0;
+  dec_data_R.params.kin = 0;
   m_bufferPos = 0;
 
   // fill buffer with zeros (G4WJS commented out because it might cause decoder hangs)
@@ -65,6 +70,7 @@ qint64 Detector::writeData (char const * data, qint64 maxSize)
   unsigned mstr = ms0 % int(1000.0*m_period); // ms into the nominal Tx start time
   if(mstr < mstr0) {              //When mstr has wrapped around to 0, restart the buffer
     dec_data.params.kin = 0;
+    dec_data_R.params.kin = 0;
     m_bufferPos = 0;
   }
   mstr0=mstr;
@@ -87,9 +93,17 @@ qint64 Detector::writeData (char const * data, qint64 maxSize)
       size_t numFramesProcessed (qMin (m_samplesPerFFT *
                                        m_downSampleFactor - m_bufferPos, remaining));
 
+      char const * srcChunk = &data[(framesAccepted - remaining) * bytesPerFrame ()];
       if(m_downSampleFactor > 1) {
-        store (&data[(framesAccepted - remaining) * bytesPerFrame ()],
-               numFramesProcessed, &m_buffer[m_bufferPos]);
+        store (srcChunk, numFramesProcessed, &m_buffer[m_bufferPos]);
+        if (bytesPerFrame () == 4) {
+          qint16 const * s16 = reinterpret_cast<qint16 const *> (srcChunk);
+          for (size_t f = 0; f < numFramesProcessed; ++f) {
+            m_bufferR[m_bufferPos + f] = s16[2 * f + 1];
+          }
+        } else {
+          memcpy (&m_bufferR[m_bufferPos], &m_buffer[m_bufferPos], numFramesProcessed * sizeof (short));
+        }
         m_bufferPos += numFramesProcessed;
 
         if(m_bufferPos>=m_samplesPerFFT*m_downSampleFactor) {
@@ -99,22 +113,28 @@ qint64 Detector::writeData (char const * data, qint64 maxSize)
              dec_data.params.kin < (NTMAX*12000 - framesAfterDownSample)) {
             fil4_(&m_buffer[0], &framesToProcess, &dec_data.d2[dec_data.params.kin],
                 &framesAfterDownSample);
+            fil4_r_(&m_bufferR[0], &framesToProcess, &dec_data_R.d2[dec_data_R.params.kin],
+                &framesAfterDownSample);
             dec_data.params.kin += framesAfterDownSample;
-          } else {
-            // qDebug() << "framesToProcess     = " << framesToProcess;
-            // qDebug() << "dec_data.params.kin = " << dec_data.params.kin;
-            // qDebug() << "secondInPeriod      = " << secondInPeriod();
-            // qDebug() << "framesAfterDownSample" << framesAfterDownSample;
+            dec_data_R.params.kin += framesAfterDownSample;
           }
           Q_EMIT framesWritten (dec_data.params.kin);
           m_bufferPos = 0;
         }
 
       } else {
-        store (&data[(framesAccepted - remaining) * bytesPerFrame ()],
-               numFramesProcessed, &dec_data.d2[dec_data.params.kin]);
+        store (srcChunk, numFramesProcessed, &dec_data.d2[dec_data.params.kin]);
+        if (bytesPerFrame () == 4) {
+          qint16 const * s16 = reinterpret_cast<qint16 const *> (srcChunk);
+          for (size_t f = 0; f < numFramesProcessed; ++f) {
+            dec_data_R.d2[dec_data_R.params.kin + f] = s16[2 * f + 1];
+          }
+        } else {
+          memcpy (&dec_data_R.d2[dec_data_R.params.kin], &dec_data.d2[dec_data.params.kin], numFramesProcessed * sizeof (short));
+        }
         m_bufferPos += numFramesProcessed;
         dec_data.params.kin += numFramesProcessed;
+        dec_data_R.params.kin += numFramesProcessed;
         if (m_bufferPos >= static_cast<unsigned> (m_samplesPerFFT)) {
           Q_EMIT framesWritten (dec_data.params.kin);
           m_bufferPos = 0;
diff --git a/Detector/Detector.hpp b/Detector/Detector.hpp
index 82eca32..638b6a7 100755
--- a/Detector/Detector.hpp
+++ b/Detector/Detector.hpp
@@ -47,7 +47,8 @@ private:
   unsigned m_downSampleFactor;
   qint32 m_samplesPerFFT;	// after any down sampling
   static size_t const max_buffer_size {7 * 512};
-  QScopedArrayPointer<short> m_buffer; // de-interleaved sample buffer
+  QScopedArrayPointer<short> m_buffer; // de-interleaved sample buffer (Left)
+  QScopedArrayPointer<short> m_bufferR; // de-interleaved sample buffer (Right)
   // big enough for all the
   // samples for one increment of
   // data (a signals worth) at
diff --git a/lib/fil4_r.f90 b/lib/fil4_r.f90
new file mode 100644
index 0000000..4d9a827
--- /dev/null
+++ b/lib/fil4_r.f90
@@ -0,0 +1,49 @@
+subroutine fil4_r(id1,n1,id2,n2)
+
+! FIR lowpass filter designed using ScopeFIR
+
+! fsample     = 48000 Hz
+! Ntaps       = 49
+! fc          = 4500  Hz
+! fstop       = 6000  Hz
+! Ripple      = 1     dB
+! Stop Atten  = 40    dB
+! fout        = 12000 Hz
+
+  parameter (NTAPS=49)
+  parameter (NDOWN=4)             !Downsample ratio
+  integer*2 id1(n1)
+  integer*2 id2(*)
+  real t(NTAPS)
+  data t/NTAPS*0.0/
+
+! Filter coefficients:
+  real w(NTAPS)
+  data w/                                                                 &
+        0.000861074040, 0.010051920210, 0.010161983649, 0.011363155076,   &
+        0.008706594219, 0.002613872664,-0.005202883094,-0.011720748164,   &
+       -0.013752163325,-0.009431602741, 0.000539063909, 0.012636767098,   &
+        0.021494659597, 0.021951235065, 0.011564169382,-0.007656470131,   &
+       -0.028965787341,-0.042637874109,-0.039203309748,-0.013153301537,   &
+        0.034320769178, 0.094717832646, 0.154224604789, 0.197758325022,   &
+        0.213715139513, 0.197758325022, 0.154224604789, 0.094717832646,   &
+        0.034320769178,-0.013153301537,-0.039203309748,-0.042637874109,   &
+       -0.028965787341,-0.007656470131, 0.011564169382, 0.021951235065,   &
+        0.021494659597, 0.012636767098, 0.000539063909,-0.009431602741,   &
+       -0.013752163325,-0.011720748164,-0.005202883094, 0.002613872664,   &
+        0.008706594219, 0.011363155076, 0.010161983649, 0.010051920210,   &
+        0.000861074040/
+  save w,t
+
+  n2=n1/NDOWN
+  if(n2*NDOWN.ne.n1) stop 'Error in fil4'
+  k=1-NDOWN
+  do i=1,n2
+     k=k+NDOWN
+     t(1:NTAPS-NDOWN)=t(1+NDOWN:NTAPS)          !Shift old data down in array t
+     t(1+NTAPS-NDOWN:NTAPS)=id1(k:k+NDOWN-1)    !Insert new data at end of t
+     id2(i)=nint(dot_product(w,t))
+  enddo
+
+  return
+end subroutine fil4_r
diff --git a/lib/symspec_r.f90 b/lib/symspec_r.f90
new file mode 100644
index 0000000..0b137cc
--- /dev/null
+++ b/lib/symspec_r.f90
@@ -0,0 +1,124 @@
+subroutine symspec_r(shared_data,k,nsps,ingain,bLowSidelobes,    &
+     nminw,pxdb,s,df3,ihsym,npts8,pxdbmax,npct)
+
+! Input:
+!  k              pointer to the most recent new data
+!  nsps           samples per symbol, at 12000 Hz
+!  bLowSidelobes  true to use windowed FFTs
+!  ndiskdat       0/1 to indicate if data from disk
+
+! Output:
+!  pxdb      raw power (0-90 dB)
+!  s()       current spectrum for waterfall display
+!  ihsym     index number of this half-symbol (1-184) for 60 s modes
+
+! jt9com
+!  ss()      JT9 symbol spectra at half-symbol steps
+!  savg()    average spectra for waterfall display
+
+  use, intrinsic :: iso_c_binding, only: c_int, c_short, c_float, c_char
+  include 'jt9com.f90'
+
+  type(dec_data) :: shared_data
+  real*4 w3(MAXFFT3)
+  real*4 s(NSMAX)
+  real*4 ssum(NSMAX)
+  real*4 xc(0:MAXFFT3-1)
+  real*4 tmp(NSMAX)
+  complex cx(0:MAXFFT3/2)
+  integer nch(7)
+  logical*1 bLowSidelobes
+
+  common/spectra_r/syellow(NSMAX),ref(0:3456),filter(0:3456)
+  data k0/99999999/,nfft3z/0/
+  data nch/1,2,4,9,18,36,72/
+  equivalence (xc,cx)
+  save
+
+  if(npct.eq.-999.9) stop             !Silence compiler warning
+  nfft3=16384                                  !df=12000.0/16384 = 0.732422
+  jstep=nsps/2                                 !Step size = half-symbol in id2()
+  if(k.gt.NMAX) go to 900
+  if(k.lt.2048) then                !(2048 was nfft3)  (Any need for this ???)
+     ihsym=0
+     go to 900                                 !Wait for enough samples to start
+  endif
+
+  if(nfft3.ne.nfft3z) then
+! Compute new window
+     pi=4.0*atan(1.0)
+     w3=0
+     call nuttal_window(w3,nfft3)
+     nfft3z=nfft3
+  endif
+
+  if(k.lt.k0) then                             !Start a new data block
+     k0=0
+     ja=0
+     ssum=0.
+     ihsym=0
+     if(.not. shared_data%params%ndiskdat) shared_data%id2(k+1:)=0   !Needed to prevent "ghosts". Not sure why.
+  endif
+  gain=10.0**(0.1*ingain)
+  sq=0.
+  pxmax=0.;
+
+  do i=k0+1,k
+     if(k0.eq.0 .and. i.le.10) cycle
+     x1=shared_data%id2(i)
+     if (abs(x1).gt.pxmax) pxmax = abs(x1);
+     sq=sq + x1*x1
+  enddo
+  pxdb = 0.
+  if(sq.gt.0.0) pxdb=10*log10(sq/(k-k0))
+  pxdbmax=0.
+  if(pxmax.gt.0) pxdbmax = 20*log10(pxmax)
+
+  k0=k
+  ja=ja+jstep                         !Index of first sample
+
+  fac0=0.1
+  do i=0,nfft3-1                      !Copy data into cx
+     j=ja+i-(nfft3-1)
+     xc(i)=0.
+     if(j.ge.1 .and.j.le.NMAX) xc(i)=fac0*shared_data%id2(j)
+  enddo
+  ihsym=ihsym+1
+
+  if(bLowSidelobes) xc(0:nfft3-1)=w3(1:nfft3)*xc(0:nfft3-1)    !Apply window 
+  call four2a(xc,nfft3,1,-1,0)        !Real-to-complex FFT
+
+  df3=12000.0/nfft3                   !JT9: 0.732 Hz = 0.42 * tone spacing
+  iz=min(NSMAX,nint(5000.0/df3))
+  fac=(1.0/nfft3)**2
+  do i=1,iz
+     j=i-1
+     if(j.lt.0) j=j+nfft3
+     sx=fac*(real(cx(j))**2 + aimag(cx(j))**2)
+     if(ihsym.le.184) shared_data%ss(ihsym,i)=sx
+     ssum(i)=ssum(i) + sx
+     s(i)=1000.0*gain*sx
+  enddo
+
+  shared_data%savg=ssum/ihsym
+
+  if(mod(ihsym,10).eq.0) then
+     mode4=nch(nminw+1)
+     nsmo=min(10*mode4,150)
+     nsmo=4*nsmo
+     call flat1(shared_data%savg,iz,nsmo,syellow)
+     if(mode4.ge.2) call smo(syellow,iz,tmp,mode4)
+     if(mode4.ge.2) call smo(syellow,iz,tmp,mode4)
+     syellow(1:250)=0.
+     ia=500./df3
+     ib=2700.0/df3
+     smin=minval(syellow(ia:ib))
+     smax=maxval(syellow(1:iz))
+     syellow=(50.0/(smax-smin))*(syellow-smin)
+     where(syellow<0) syellow=0.
+  endif
+
+900 npts8=k/8
+
+  return
+end subroutine symspec_r
diff --git a/widgets/mainwindow.cpp b/widgets/mainwindow.cpp
index 06547be..b06c743 100755
--- a/widgets/mainwindow.cpp
+++ b/widgets/mainwindow.cpp
@@ -450,6 +450,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple,
   m_rigErrorMessageBox {MessageBox::Critical, tr ("Rig Control Error")
       , MessageBox::Cancel | MessageBox::Ok | MessageBox::Retry},
   m_wideGraph (new WideGraph(m_settings)),
+  m_wideGraphR (new WideGraph(m_settings)),
   m_echoGraph (new EchoGraph(m_settings)),
   m_fastGraph (new FastGraph(m_settings)),
   // no parent so that it has a taskbar icon
@@ -780,7 +781,14 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple,
   connect(m_detector, &Detector::framesWritten, this, &MainWindow::dataSink);
   connect (&m_audioThread, &QThread::finished, m_detector, &QObject::deleteLater);
 
-  // setup the waterfall
+  // setup the waterfall (Left and Right stereo channels)
+  m_wideGraph->setWindowTitle (program_title () + " - Wide Graph [L]");
+  m_wideGraphR->setWindowTitle (program_title () + " - Wide Graph [R]");
+  m_wideGraphR->show ();
+  connect (this, &MainWindow::finished, m_wideGraphR.data (), &WideGraph::close);
+  connect(m_wideGraphR.data (), SIGNAL(freezeDecode2(int)),this,SLOT(freezeDecode(int)));
+  connect(m_wideGraphR.data (), SIGNAL(f11f12(int)),this,SLOT(bumpFqso(int)));
+  connect(m_wideGraphR.data (), SIGNAL(setXIT2(int)),this,SLOT(setXIT(int)));
   connect(m_wideGraph.data (), SIGNAL(freezeDecode2(int)),this,SLOT(freezeDecode(int)));
   setupJtty();
   connect(m_wideGraph.data (), SIGNAL(f11f12(int)),this,SLOT(bumpFqso(int)));
@@ -1142,6 +1150,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple,
   setWindowTitle (program_title ());
 
   connect(&proc_jt9, &QProcess::readyReadStandardOutput, this, &MainWindow::readFromStdout);
+  connect(&proc_jt9_R, &QProcess::readyReadStandardOutput, this, &MainWindow::readFromStdoutR);
 #if QT_VERSION < QT_VERSION_CHECK (5, 6, 0)
   connect(&proc_jt9, static_cast<void (QProcess::*) (QProcess::ProcessError)> (&QProcess::error),
           [this] (QProcess::ProcessError error) {
@@ -1453,6 +1462,23 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple,
   proc_jt9.start(QDir::toNativeSeparators (m_appDir) + QDir::separator () +
           "jt9", jt9_args, QIODevice::ReadWrite | QIODevice::Unbuffered);
 
+  // Initialize secondary shared memory and jt9 process for Right stereo channel
+  mem_jt9_R.setKey (mem_jt9->key () + "_R");
+  if (!mem_jt9_R.attach ()) {
+    mem_jt9_R.create (sizeof (dec_data));
+  }
+  if (mem_jt9_R.isAttached ()) {
+    mem_jt9_R.lock ();
+    memset (mem_jt9_R.data (), 0, sizeof (struct dec_data));
+    mem_jt9_R.unlock ();
+  }
+  QStringList jt9_args_R = jt9_args;
+  int keyIdx = jt9_args_R.indexOf (mem_jt9->key ());
+  if (keyIdx >= 0) jt9_args_R[keyIdx] = mem_jt9_R.key ();
+  proc_jt9_R.setProcessEnvironment (new_env);
+  proc_jt9_R.start(QDir::toNativeSeparators (m_appDir) + QDir::separator () +
+          "jt9", jt9_args_R, QIODevice::ReadWrite | QIODevice::Unbuffered);
+
   auto fname {QDir::toNativeSeparators(m_config.writeable_data_dir ().absoluteFilePath ("wsjtx_wisdom.dat"))};
   fftwf_import_wisdom_from_filename (fname.toLocal8Bit ());
 
@@ -1471,7 +1497,7 @@ MainWindow::MainWindow(QDir const& temp_directory, bool multiple,
       {
         Q_EMIT startAudioInputStream (m_config.audio_input_device ()
                                       , m_rx_audio_buffer_frames
-                                      , m_detector, m_downSampleFactor, m_config.audio_input_channel ());
+                                      , m_detector, m_downSampleFactor, AudioDevice::Both);
       }
     if (!m_config.audio_output_device ().isNull ())
       {
@@ -1733,6 +1759,24 @@ void MainWindow::on_the_minute ()
 //--------------------------------------------------- MainWindow destructor
 MainWindow::~MainWindow()
 {
+  if (mem_jt9_R.isAttached ()) {
+    if (auto * ddR = reinterpret_cast<dec_data_t *> (mem_jt9_R.data ())) {
+      mem_jt9_R.lock ();
+      ddR->ipc[1] = 999;
+      mem_jt9_R.unlock ();
+    }
+  }
+  if (proc_jt9_R.state () != QProcess::NotRunning) {
+    if (!proc_jt9_R.waitForFinished (500)) {
+      proc_jt9_R.kill ();
+      proc_jt9_R.waitForFinished (500);
+    }
+  }
+  if (mem_jt9_R.isAttached ()) mem_jt9_R.detach ();
+  if (m_wideGraphR) {
+    m_wideGraphR->close ();
+    m_wideGraphR.reset ();
+  }
   if(m_astroWidget) m_astroWidget.reset ();
   if(m_QSYMessageCreatorWidget) m_QSYMessageCreatorWidget.reset ();
   if(m_QSYMessageWidget) m_QSYMessageWidget.reset ();
@@ -2617,6 +2661,7 @@ void MainWindow::fixStop()
 }
 
 //-------------------------------------------------------------- dataSink()
+extern "C" void symspec_r_(dec_data_t*, int*, int*, int*, bool*, int*, float*, float*, float*, int*, int*, float*, int*);
 void MainWindow::dataSink(qint64 frames)
 {
   static float s[NSMAX];
@@ -2658,13 +2703,42 @@ void MainWindow::dataSink(qint64 frames)
   bool bLowSidelobes=m_config.lowSidelobes();
   int npct=0;
   if(m_mode.startsWith("FST4")) npct=ui->sbNB->value();
+
+  extern dec_data_t dec_data_R;
+  static float sR[NSMAX];
+  float pxR = 0.0f, df3R = 0.0f, pxmaxR = 0.0f;
+  int ihsymR = 0, npts8R = 0;
+  int kR = dec_data_R.params.kin;
+  dec_data_R.params.nfa = dec_data.params.nfa;
+  dec_data_R.params.nfb = dec_data.params.nfb;
+  dec_data_R.params.ndiskdat = dec_data.params.ndiskdat;
   symspec_(&dec_data,&k,&nsps,&m_inGain,&bLowSidelobes,&nsmo,&m_px,s,
            &m_df3,&m_ihsym,&m_npts8,&m_pxmax,&npct);
-  if(m_mode=="WSPR" or m_mode=="FST4W") wspr_downsample_(dec_data.d2,&k);
+  symspec_r_(&dec_data_R,&kR,&nsps,&m_inGain,&bLowSidelobes,&nsmo,&pxR,sR,
+             &df3R,&ihsymR,&npts8R,&pxmaxR,&npct);
+  if(m_mode=="WSPR" or m_mode=="FST4W") {
+    wspr_downsample_(dec_data.d2,&k);
+    wspr_downsample_(dec_data_R.d2,&k);
+  }
   if(m_ihsym <=0) return;
   if(ui) ui->signal_meter_widget->setValue(m_px,m_pxmax); // Update thermometer
   if(m_monitoring || m_diskData) {
     m_wideGraph->dataSink2(s,m_df3,m_ihsym,m_diskData,m_px);
+    if (m_wideGraphR) {
+      static QString lastModeR;
+      static double lastPeriodR = -1.0;
+      if (lastModeR != m_mode || lastPeriodR != m_TRperiod) {
+        lastModeR = m_mode;
+        lastPeriodR = m_TRperiod;
+        m_wideGraphR->setMode (m_mode);
+        m_wideGraphR->setPeriod (m_TRperiod, nsps);
+        m_wideGraphR->setRxFreq (ui->RxFreqSpinBox->value ());
+        m_wideGraphR->setTxFreq (ui->TxFreqSpinBox->value ());
+        m_wideGraphR->setTol (ui->sbFtol->value ());
+        m_wideGraphR->setDarkStyle (m_useDarkStyle);
+      }
+      m_wideGraphR->dataSink2(sR,df3R,ihsymR,m_diskData,pxR);
+    }
   }
   if(m_mode=="MSK144") return;
   if(m_mode=="JTTY") {
@@ -3642,7 +3716,7 @@ void MainWindow::fastSink(qint64 frames)
 
         // display decodes for the fast modes must be done before highlighting any call or grid for MSK144
         bool haveFSpread {false};
-        float fSpread {0.};
+        float fSpread {0.}; (void)fSpread;
         bool bDisplayPoints {false};
         m_points = 0;
 
@@ -6303,9 +6377,27 @@ void MainWindow::decode()                                       //decode()
             &narg[0],&m_TRperiod, &m_msg[0][0], dec_data.params.mycall,
             dec_data.params.hiscall, (FCL)8000, (FCL)12, (FCL)12)));
       } else {
+        extern dec_data_t dec_data_R;
+        memcpy (&dec_data_R.params, &dec_data.params, sizeof (dec_data.params));
         mem_jt9->lock ();
         memcpy(to, from, qMin(mem_jt9->size(), size));
         mem_jt9->unlock ();
+        if (mem_jt9_R.isAttached ()) {
+          if (auto * toR = reinterpret_cast<char *> (mem_jt9_R.data ())) {
+            char * fromR = (char*) dec_data_R.ipc;
+            int sizeR = sizeof (struct dec_data);
+            if (dec_data_R.params.newdat == 0) {
+              int noffset {offsetof (struct dec_data, params.nutc)};
+              toR += noffset;
+              fromR += noffset;
+              sizeR -= noffset;
+            }
+            mem_jt9_R.lock ();
+            memcpy (toR, fromR, qMin (mem_jt9_R.size (), sizeR));
+            mem_jt9_R.unlock ();
+          }
+        }
+        m_jt9FinishedCount = 0;
         to_jt9(m_ihsym,1,-1);                //Send m_ihsym to jt9[.exe] and start decoding
         decodeBusy(true);
       }
@@ -6379,6 +6471,17 @@ void MainWindow::to_jt9(qint32 n, qint32 istart, qint32 idone)
       if(idone>=0)  dd->ipc[2]=idone;
       mem_jt9->unlock ();
     }
+  if (mem_jt9_R.isAttached ())
+    {
+      if (auto * ddR = reinterpret_cast<dec_data_t *> (mem_jt9_R.data ()))
+        {
+          mem_jt9_R.lock ();
+          ddR->ipc[0]=n;
+          if(istart>=0) ddR->ipc[1]=istart;
+          if(idone>=0)  ddR->ipc[2]=idone;
+          mem_jt9_R.unlock ();
+        }
+    }
 }
 
 void MainWindow::decodeDone ()
@@ -6915,6 +7018,48 @@ void MainWindow::activeWorked(QString call, QString band)
 }
 
 void MainWindow::readFromStdout()                             //readFromStdout
+{
+  readFromStdoutChannel (proc_jt9, "L");
+}
+
+void MainWindow::readFromStdoutR()
+{
+  readFromStdoutChannel (proc_jt9_R, "R");
+}
+
+void MainWindow::flushStereoDecodes()
+{
+  bool cqOnly = ui->cbCQonly->isVisible () && ui->cbCQonly->isChecked ();
+  for (QString const& key : m_pendingStereoOrder) {
+    if (!m_pendingStereoDecodes.contains (key)) continue;
+    auto const& entry = m_pendingStereoDecodes.value (key);
+    QString tag = "L";
+    QByteArray chosenLine = entry.lineL;
+    QString chosenRaw = entry.rawLineL;
+    if (entry.hasL && entry.hasR) {
+      tag = (std::abs (entry.snrL - entry.snrR) <= 1) ? "E" : (entry.snrL > entry.snrR ? "L" : "R");
+      if (entry.snrR > entry.snrL) { chosenLine = entry.lineR; chosenRaw = entry.rawLineR; }
+    } else if (entry.hasR) {
+      tag = "R"; chosenLine = entry.lineR; chosenRaw = entry.rawLineR;
+    } else if (!entry.hasL) continue;
+
+    DecodedText dtChosen {chosenRaw};
+    if ((m_mode == "JT65" || m_mode == "JT9" || m_mode == "JT4") && m_config.DXCC ()) {
+      DecodedText dtJT {QString::fromUtf8 (chosenLine.left (44).constData ()) + QString::fromUtf8 (chosenLine.mid (62, 2).constData ())};
+      ui->decodedTextBrowser->displayDecodedText (dtJT, m_config.my_callsign (), m_mode, m_config.DXCC (),
+                                                  m_logBook, m_currentBandPeriod, m_config.ppfx (),
+                                                  cqOnly, false, 0.0, false, 0, tag, false, "");
+    } else {
+      ui->decodedTextBrowser->displayDecodedText (dtChosen, m_config.my_callsign (), m_mode, m_config.DXCC (),
+                                                  m_logBook, m_currentBandPeriod, m_config.ppfx (),
+                                                  cqOnly, false, 0.0, false, 0, tag, false, "");
+    }
+  }
+  m_pendingStereoDecodes.clear ();
+  m_pendingStereoOrder.clear ();
+}
+
+void MainWindow::readFromStdoutChannel(QProcess & proc, QString const& channelTag)
 {
   bool bDisplayPoints = false;
   filtered = false;
@@ -6925,8 +7070,8 @@ void MainWindow::readFromStdout()                             //readFromStdout
     bDisplayPoints=(m_mode.startsWith("FT") and
       (m_specOp==SpecOp::ARRL_DIGI or m_ActiveStationsWidget->isVisible()));
   }
-  while(proc_jt9.canReadLine()) {
-    auto line_read = proc_jt9.readLine ();
+  while(proc.canReadLine()) {
+    auto line_read = proc.readLine ();
 
     QString the_line = QString(line_read);
     if(ui->actionEnable_QSY_Popups->isChecked() || m_qsymonitorWidget) showQSYMessage(the_line);
@@ -6945,7 +7090,7 @@ void MainWindow::readFromStdout()                             //readFromStdout
     bool haveFSpread {false};
     bool blockUDP {false};                   // allow udp spotting (JTAlert) for all non-filtered messages
     bool block_right_display {false};
-    float fSpread {0.};
+    float fSpread {0.}; (void)fSpread;
     if (m_mode.startsWith ("FST4"))
       {
         auto text = line_read.mid (64, 6).trimmed ();
@@ -7007,7 +7152,13 @@ void MainWindow::readFromStdout()                             //readFromStdout
     int navg=0;
 
     if(line_read.indexOf("<DecodeFinished>") >= 0) {
-      m_bDecoded =  line_read.mid(20).trimmed().toInt() > 0;
+      m_jt9FinishedCount++;
+      if (m_jt9FinishedCount < 2) {
+        return; // Wait for both [L] and [R] jt9 processes to finish
+      }
+      m_jt9FinishedCount = 0;
+      flushStereoDecodes ();
+      m_bDecoded = (m_nDecodes > 0) || (line_read.mid(20).trimmed().toInt() > 0);
       int n=line_read.trimmed().size();
       int n2=line_read.trimmed().mid(n-7).toInt();
       int n0=n2/1000;
@@ -7751,27 +7902,27 @@ void MainWindow::readFromStdout()                             //readFromStdout
             QSOgrid = "";
           }
 
-          // display country names for JT65 and JT9 like for FT8
-          if ((m_mode == "JT65" or m_mode == "JT9" or m_mode == "JT4") && m_config.DXCC()) {
-            DecodedText decodedtextJT {((QString::fromUtf8(line_read.left(44).constData())) + (QString::fromUtf8(line_read.mid(62, 2).constData())))};
-            ui->decodedTextBrowser->displayDecodedText (decodedtextJT, m_config.my_callsign (), m_mode, m_config.DXCC (),
-                                                        m_logBook, m_currentBandPeriod, m_config.ppfx (),
-                                                        ui->cbCQonly->isVisible() && ui->cbCQonly->isChecked() && !(DXcall_only && !ui->cbBypass->isChecked()),
-                                                        haveFSpread, fSpread, bDisplayPoints, m_points, distance, m_muted, QSOgrid);
+          QString periodStr = decodedtext.string ().left (6).trimmed ();
+          if (periodStr != m_cyclePeriodKey) {
+            if (!m_pendingStereoOrder.isEmpty ()) flushStereoDecodes ();
+            m_cyclePeriodKey = periodStr;
+          }
+          QString normMsg = decodedtext.string ().mid (22).simplified ();
+          int curSnr = decodedtext.snr ();
+          if (!m_pendingStereoDecodes.contains (normMsg)) {
+            m_pendingStereoOrder.append (normMsg);
+            m_pendingStereoDecodes.insert (normMsg, PendingStereoDecode {});
+          }
+          auto & entry = m_pendingStereoDecodes[normMsg];
+          if (channelTag == "L") {
+            if (!entry.hasL || curSnr > entry.snrL) {
+              entry.hasL = true; entry.snrL = curSnr;
+              entry.lineL = line_read; entry.rawLineL = decodedtext1.string ();
+            }
           } else {
-            if (ui->actionHide_AP_info->isVisible() && ui->actionHide_AP_info->isChecked()) {
-              // Hide FT8 AP information
-              DecodedText decodedtext2 {(QString::fromUtf8(line_read.replace("a1","").replace("a2","").replace("a3","").replace("a4","")
-                                         .replace("a5","").replace("a6","").replace("a7","").replace("a8","").replace("a9","").replace("?","")))};
-              ui->decodedTextBrowser->displayDecodedText (decodedtext2, m_config.my_callsign (), m_mode, m_config.DXCC (),
-                                                          m_logBook, m_currentBandPeriod, m_config.ppfx (),
-                                                          ui->cbCQonly->isVisible() && ui->cbCQonly->isChecked() && !(DXcall_only && !ui->cbBypass->isChecked()),
-                                                          haveFSpread, fSpread, bDisplayPoints, m_points, distance, m_muted, QSOgrid);
-            } else {
-              ui->decodedTextBrowser->displayDecodedText (decodedtext1, m_config.my_callsign (), m_mode, m_config.DXCC (),
-                                                          m_logBook, m_currentBandPeriod, m_config.ppfx (),
-                                                          ui->cbCQonly->isVisible() && ui->cbCQonly->isChecked() && !(DXcall_only && !ui->cbBypass->isChecked()),
-                                                          haveFSpread, fSpread, bDisplayPoints, m_points, distance, m_muted, QSOgrid);
+            if (!entry.hasR || curSnr > entry.snrR) {
+              entry.hasR = true; entry.snrR = curSnr;
+              entry.lineR = line_read; entry.rawLineR = decodedtext1.string ();
             }
           }
           if(m_position != 0) ui->decodedTextBrowser->horizontalScrollBar()->setValue(m_position);
diff --git a/widgets/mainwindow.h b/widgets/mainwindow.h
index e7fd6de..cdea516 100755
--- a/widgets/mainwindow.h
+++ b/widgets/mainwindow.h
@@ -83,7 +83,7 @@ namespace Ui {
 
 class QNetworkAccessManager;
 class QProcessEnvironment;
-class QSharedMemory;
+#include <QSharedMemory>
 class QSplashScreen;
 class QSettings;
 class QLineEdit;
@@ -150,6 +150,9 @@ public slots:
   void doubleClickOnFoxQueue(Qt::KeyboardModifiers);
   void doubleClickOnFoxInProgress(Qt::KeyboardModifiers modifiers);
   void readFromStdout();
+  void readFromStdoutR();
+  void readFromStdoutChannel(QProcess & proc, QString const& channelTag);
+  void flushStereoDecodes();
   void p1ReadFromStdout();
   void setXIT(int n, Frequency base = 0u);
   void setFreq4(int rxFreq, int txFreq);
@@ -558,6 +561,7 @@ private:
   QScopedPointer<EqualizationToolsDialog> m_equalizationToolsDialog;
 
   QScopedPointer<WideGraph> m_wideGraph;
+  QScopedPointer<WideGraph> m_wideGraphR;
   QScopedPointer<EchoGraph> m_echoGraph;
   QScopedPointer<FastGraph> m_fastGraph;
   QScopedPointer<LogQSO> m_logDlg;
@@ -846,6 +850,7 @@ private:
   QFutureWatcher<QString> m_saveWAVWatcher;
 
   NonInheritingProcess proc_jt9;
+  NonInheritingProcess proc_jt9_R;
   NonInheritingProcess p1;
   NonInheritingProcess p3;
 
@@ -1001,6 +1006,21 @@ private:
   QDateTime m_dateTimeSeqStart;        //Nominal start time of Rx sequence about to be decoded
 
   QSharedMemory *mem_jt9;
+  QSharedMemory mem_jt9_R;
+  struct PendingStereoDecode {
+    bool hasL {false};
+    bool hasR {false};
+    int snrL {-99};
+    int snrR {-99};
+    QByteArray lineL;
+    QByteArray lineR;
+    QString rawLineL;
+    QString rawLineR;
+  };
+  QMap<QString, PendingStereoDecode> m_pendingStereoDecodes;
+  QStringList m_pendingStereoOrder;
+  QString m_cyclePeriodKey;
+  int m_jt9FinishedCount {0};
   QString m_QSOText;
   unsigned m_downSampleFactor;
   QThread::Priority m_audioThreadPriority;
diff --git a/widgets/plotter.cpp b/widgets/plotter.cpp
index 29399a4..0a18b8c 100755
--- a/widgets/plotter.cpp
+++ b/widgets/plotter.cpp
@@ -381,9 +381,11 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed)
   int iz=XfromFreq(5000.0);
   int jz=iz*m_binsPerPixel;
   m_fMax=FreqfromX(iz);
+  extern dec_data_t dec_data_R;
+  float * savgPtr = m_isRightChannel ? dec_data_R.savg : dec_data.savg;
   if(bScroll and swide[0]<1.e29) {
     flat4_(swide,&iz,&m_Flatten);
-    if(!m_bReplot) flat4_(&dec_data.savg[j0],&jz,&m_Flatten);
+    if(!m_bReplot) flat4_(&savgPtr[j0],&jz,&m_Flatten);
   }
 
   ymin=1.e30;
@@ -416,7 +418,7 @@ void CPlotter::draw(float swide[], bool bScroll, bool bRed)
       float sum=0.0;
       int j=j0+m_binsPerPixel*i;
       for(int k=0; k<m_binsPerPixel; k++) {
-        sum+=dec_data.savg[j++];
+        sum+=savgPtr[j++];
       }
       m_sum[i]=sum;
     }
diff --git a/widgets/plotter.h b/widgets/plotter.h
index 8af1a03..27822ec 100755
--- a/widgets/plotter.h
+++ b/widgets/plotter.h
@@ -55,6 +55,7 @@ public:
   void setDataFromDisk(bool b);
   void setRxRange(int fMin);
   void setBinsPerPixel(int n);
+  void setRightChannel(bool b) { m_isRightChannel = b; }
   int  binsPerPixel();
   void setWaterfallAvg(int n);
   void setRxFreq(int n);
@@ -170,6 +171,8 @@ private:
 
   bool    m_bScaleOK;
   bool    m_bCurrent;
+  bool    m_isRightChannel {false};
+  float   m_cumulR[8192] = {0.0f};
   bool    m_bCumulative;
   bool    m_bLinearAvg;
   bool    m_bReference;
diff --git a/widgets/widegraph.cpp b/widgets/widegraph.cpp
index 8beefeb..401e666 100755
--- a/widgets/widegraph.cpp
+++ b/widgets/widegraph.cpp
@@ -431,7 +431,7 @@ void WideGraph::drawRed(int ia, int ib)
 
 void WideGraph::dataSink2(float s[], float df3, int ihsym, int ndiskdata, float pdB)  //dataSink2
 {
-  static float splot[NSMAX];
+  float * splot = m_splot;
   int nbpp = ui->widePlot->binsPerPixel();
 
   if(ui->widePlot->TotalPower()) ui->widePlot->drawTotalPower(pdB);
@@ -480,6 +480,7 @@ void WideGraph::dataSink2(float s[], float df3, int ihsym, int ndiskdata, float
       m_bHaveTransmitted=false;
     }
     m_tr0=tr;
+    if (windowTitle().contains("[R]")) ui->widePlot->setRightChannel(true);
     ui->widePlot->draw(m_swide,true,false);
   }
 }
diff --git a/widgets/widegraph.h b/widgets/widegraph.h
index b153ca2..ed4c8d4 100755
--- a/widgets/widegraph.h
+++ b/widgets/widegraph.h
@@ -1,3 +1,4 @@
+#include "commons.h"
 // -*- Mode: C++ -*-
 #ifndef WIDEGRAPH_H_
 #define WIDEGRAPH_H_
@@ -184,6 +185,7 @@ private:
   QString m_rxBand;
   QString m_mode;
   QString m_waterfallPalette;
+  float m_splot[NSMAX] = {0.0f};
   float   m_swide[MAX_SCREENSIZE];
   QString m_user_defined;
 

It could still use some refinements like both cursors tracking each other etc. Pretty impressive achievement from AI – I think that the days of many programmers might be over…