summaryrefslogtreecommitdiff
path: root/map65/soundin.cpp
blob: ee1886e8dda13d8bf80a330282410c2ff9f64f8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#include "soundin.h"
#include "commons.h"
#include <math.h>
#include <complex>
#include "mainwindow.h"

#ifdef Q_OS_WIN32
#include <windows.h>
#else
#include <sys/socket.h>
#endif

#define FRAMES_PER_BUFFER 1024

#include <portaudio.h>
#include <QDebug>


typedef struct
{
  int kin;          //Parameters sent to/from the portaudio callback function
  int nrx;
  int dB;
  bool bzero;
  bool iqswap;
} paUserData;

//--------------------------------------------------------------- a2dCallback
extern "C" int a2dCallback(const void* inputBuffer, void* outputBuffer,
                           unsigned long framesToProcess,
                           const PaStreamCallbackTimeInfo* timeInfo,
                           PaStreamCallbackFlags statusFlags,
                           void* userData)
{
    paUserData* udata = static_cast<paUserData*>(userData);

    (void) outputBuffer;
    (void) timeInfo;
    (void) userData;

    int   nbytes,i,j;
    float d4[4 * FRAMES_PER_BUFFER];
    float d4a[4 * FRAMES_PER_BUFFER];
    float tmp;
    float fac;

    if ((statusFlags & paInputOverflow) != 0) {
        qDebug() << "Input Overflow";
    }

    if (udata->bzero) {           // Start of a new minute
        advance_live_input_generation();
        udata->kin   = 0;         // Reset buffer pointer
        udata->bzero = false;
    }

    // Bytes per frame, mirroring legacy intent but for float32
    // legacy used: nbytes = udata->nrx * 8 * framesToProcess;
    // here: nrx * 8 bytes per frame (4 floats per frame, each 4 bytes)
    nbytes = udata->nrx * 8 * framesToProcess;

    memcpy(d4, inputBuffer, nbytes);

    fac = 32767.0f * pow(10.0f, 0.05f * float(udata->dB));

    if (udata->nrx == 2) {
        // Two RF channels, r*4 data (complex I/Q for X and Y)
        for (i = 0; i < 4 * int(framesToProcess); i++) {
            d4[i] = fac * d4[i];
            j = i / 4;
            if ((j % 2) == 1) d4[i] = -d4[i];
        }

        if (!udata->iqswap) {
            for (i = 0; i < int(framesToProcess); i++) {
                j = 4 * i;
                tmp = d4[j];     d4[j] = d4[j+1];     d4[j+1] = tmp;
                tmp = d4[j+2];   d4[j+2] = d4[j+3];   d4[j+3] = tmp;
            }
        }

        memcpy(&dd[4 * udata->kin], d4, nbytes); 

    } else {
        // One RF channel
        int k = 0;
        for (i = 0; i < 2 * int(framesToProcess); i += 2) {
            j = i / 2;
            if (j % 2 == 0) {
                d4a[k++] = fac * d4[i];
                d4a[k++] = fac * d4[i+1];
            } else {
                d4a[k++] = -fac * d4[i];
                d4a[k++] = -fac * d4[i+1];
            }
            d4a[k++] = 0.0;
            d4a[k++] = 0.0;
        }

        if (!udata->iqswap) {
            for (i = 0; i < int(framesToProcess); i++) {
                j = 4 * i;
                tmp = d4a[j];     d4a[j] = d4a[j+1];     d4a[j+1] = tmp;
            }
        }

        // Legacy wrote 2*nbytes into datcom_.d8 for this case (4 floats per frame)
        memcpy(&dd[4 * udata->kin], d4a, 2 * nbytes);
    }

    udata->kin += framesToProcess;
    return paContinue;
}

namespace
{
  constexpr int symspecLookaheadSamples = 512;

  int symspecReadyPointer(int acquiredSamples)
  {
    // symspec's final 1024-sample window extends one 512-sample hop past k.
    return acquiredSamples - symspecLookaheadSamples;
  }

  struct COMWrapper
  {
    explicit COMWrapper ()
    {
#ifdef _WIN32
      CoInitializeEx (nullptr, 
         COINIT_APARTMENTTHREADED | 
         COINIT_DISABLE_OLE1DDE);
#endif
    }
    ~COMWrapper ()
    {
#ifdef _WIN32
      CoUninitialize ();
#endif
    }
  };
}

//SoundInThread::SoundInThread(MainWindow* mw, QObject* parent)
//   : QThread(parent), m_mainWindow(mw) {}

void SoundInThread::run()                           //SoundInThread::run()
{
  quitExecution = false;
    
  if (m_net) {
//    qDebug() << "Start inputUDP()";
    inputUDP();
    return;

//    qDebug() << "Finished inputUDP()";
    return;
  }

  COMWrapper c;

  //---------------------------------------------------- Soundcard Setup
  qDebug() << "START SOUNDCARD INPUT ";

  PaError paerr;
  PaStreamParameters inParam;
  PaStream *inStream;
  paUserData udata;
  
  udata.kin=0;                              //Buffer pointer
  udata.bzero=false;                        //Flag to request reset of kin
  udata.nrx=m_nrx;                          //Number of polarizations
  udata.iqswap=m_IQswap;
  udata.dB=m_dB;

  auto device_info = Pa_GetDeviceInfo (m_nDevIn);

  inParam.device=m_nDevIn;                  //### Input Device Number ###
  inParam.channelCount=2*m_nrx;             //Number of analog channels
  inParam.sampleFormat=paFloat32;           //Get floats from Portaudio
  inParam.suggestedLatency=device_info->defaultHighInputLatency;
  inParam.hostApiSpecificStreamInfo=NULL;

  paerr=Pa_IsFormatSupported(&inParam,NULL,double(g_sampleRate));
  if(paerr<0) {
    QString error_message;
    if (paUnanticipatedHostError == paerr)
      {
        auto const * last_host_error = Pa_GetLastHostErrorInfo ();
        error_message = QString {"PortAudio Host API error: %1"}.arg (last_host_error->errorText);
      }
    else
      {
        error_message = "PortAudio says requested soundcard format not supported.";
      }
    emit error(error_message);
  }
 paerr = Pa_OpenStream(
    &inStream,
    &inParam,
    NULL,
    double(g_sampleRate),
    FRAMES_PER_BUFFER,
    paClipOff,
    a2dCallback,
    &udata);

    paerr=Pa_StartStream(inStream);
    if(paerr<0) {
      emit error("Failed to start audio input stream.");
      return;
    }

  bool qe = quitExecution;
  int ntr0=99;
  int k=0;
  int nsec;
  int ntr;
  Map65HalfSymbolScheduler spectrumScheduler;

//---------------------------------------------- Soundcard input loop
  while (!qe) {
    qe = quitExecution;
    if (qe) break;

    qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000;
    nsec = ms/1000;
    ntr = nsec % m_TRperiod;

    if(ntr < ntr0 or !m_monitoring or m_TRperiod!=m_TRperiod0) {
      spectrumScheduler.reset ();
      udata.bzero=true;
      m_TRperiod0=m_TRperiod;
    }

    k=udata.kin;

    udata.iqswap= (m_IQswap != 0);
    udata.dB=m_dB;

    if(m_monitoring) {
        double fcenter = m_bForceCenterFreq ? m_dForceCenterFreq : 144.125;
      set_fcenter(fcenter);

      int const fftPointer=symspecReadyPointer(k);
      m_hsym=(fftPointer-2048)*11025.0/(2048.0*m_rate);

      if (spectrumScheduler.claim_next (m_hsym, m_dataSinkBusy)) {
        emit readyForFFT(fftPointer);
      }
    }

    msleep(100);
    ntr0=ntr;
  }

  Pa_StopStream(inStream);
  Pa_CloseStream(inStream);
}

void SoundInThread::setSwapIQ(bool b)
{
  m_IQswap=b;
}

void SoundInThread::setScale(qint32 n)
{
  m_dB=n;
}
void SoundInThread::setPort(int n)                              //setPort()
{
  if (isRunning()) return;
  this->m_udpPort=n;
}

void SoundInThread::setInputDevice(int n)                  //setInputDevice()
{
  if (isRunning()) return;
  this->m_nDevIn=n;
}

void SoundInThread::setRate(double rate)                         //setRate()
{
  if (isRunning()) return;
  this->m_rate = rate;
}

void SoundInThread::setBufSize(unsigned n)                      //setBufSize()
{
  if (isRunning()) return;
  this->bufSize = n;
}

void SoundInThread::setFadd(double x)
{
  m_fAdd=x;
}

void SoundInThread::quit()                                       //quit()
{
  quitExecution = true;
}

void SoundInThread::setNetwork(bool b)                          //setNetwork()
{
  m_net = b;
}

void SoundInThread::setMonitoring(bool b)                    //setMonitoring()
{
  m_monitoring = b;
  qDebug() << "m_monitoring set to" << m_monitoring << "at" << Q_FUNC_INFO;

}

void SoundInThread::setForceCenterFreqBool(bool b)
{
  m_bForceCenterFreq=b;


}

void SoundInThread::setForceCenterFreqMHz(double d)
{
  m_dForceCenterFreq=d;
}

void SoundInThread::setNrx(int n)                              //setNrx()
{
  m_nrx = n;
  //qDebug() << "soundin line 333 SET m_nrx = " << n;
}

int SoundInThread::nrx()
{
  //qDebug() << "soundin line 338 RETURNED m_nrx = " << m_nrx;
  return m_nrx;
}

int SoundInThread::mhsym()
{
  return m_hsym;
}

void SoundInThread::setPeriod(int n)
{
  m_TRperiod=n;
}

//--------------------------------------------------------------- inputUDP()
void SoundInThread::inputUDP()
{
  udpSocket = new QUdpSocket();
  if(!udpSocket->bind(m_udpPort,QUdpSocket::ShareAddress) )
  {
    emit error(tr("UDP Socket bind failed."));
    return;
  }

  // Set this socket's total buffer space for received UDP packets
  udpSocket->setSocketOption (QUdpSocket::ReceiveBufferSizeSocketOption, 141600);

  bool qe = quitExecution;
  struct linradBuffer {
    double cfreq;
    int msec;
    float userfreq;
    int iptr;
    quint16 iblk;  //was quint16
    qint8 nrx;
    char iusb;
    double d8[174];
  } b;

  int ntr0=99;
  int k=0;
  int nsec;
  int ntr;
  Map65HalfSymbolScheduler spectrumScheduler;
  int iz=174;

  // Main loop for input of UDP packets over the network:
  while (!qe) {
    qe = quitExecution;
    if (qe) break;
    if (!udpSocket->hasPendingDatagrams()) {
      msleep(2);                  // Sleep if no packet available
    } else {
      int nBytesRead = udpSocket->readDatagram(reinterpret_cast<char*>(&b), 1416);
            if (nBytesRead != 1416) {
                qDebug() << "UDP Read Error:" << nBytesRead;
            }


      qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000;
      nsec = ms/1000;             // Time according to this computer
      ntr = nsec % m_TRperiod;

// Reset buffer pointer and symbol number at start of minute
      if(ntr < ntr0 or !m_monitoring or m_TRperiod!=m_TRperiod0) {
        advance_live_input_generation();
        k=0;
        spectrumScheduler.reset ();
        m_TRperiod0=m_TRperiod;
      }
      ntr0=ntr;

      if(m_monitoring) {
        m_nrx=b.nrx;
        if(m_nrx == +1) iz=348;                 //One RF channel, i*2 data
        if(m_nrx == -1 or m_nrx == +2) iz=174;  //One Rf channel, r*4 data
                                                // or 2 RF channels, i*2 data
        if(m_nrx == -2) iz=87;                  // Two RF channels, r*4 data

        // If buffer will not overflow, move data into datcom_
        if ((k + iz) <= 60 * m_rate) {
          int nsam=-1;
          recvpkt_(&nsam, &b.iblk, &b.nrx, &k, b.d8, b.d8, b.d8);
          double fcenter;
          if(m_bForceCenterFreq) {
            fcenter = m_dForceCenterFreq;
          } else {
            fcenter = b.cfreq + m_fAdd;
          }
          set_fcenter(fcenter);
        }

double hsym = 2048.0 * m_rate / 11025.0;
int const fftPointer=symspecReadyPointer(k);
m_hsym = (fftPointer - 2048) / hsym;
if (spectrumScheduler.claim_next (m_hsym, m_dataSinkBusy)) {
    emit readyForFFT(fftPointer);
}

      }
    }
  }
  delete udpSocket;
  udpSocket =  nullptr;
}