summaryrefslogtreecommitdiff
path: root/Modulator/Modulator.cpp
blob: 0467a483395d652554ce63d7ed1e166a9be80315 (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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#include "Modulator.hpp"
#include <cstdint>
#include <limits>
#include <qmath.h>
#include <QDateTime>
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
#include <QRandomGenerator>
#endif
#include <QDebug>
#include "widgets/itoneAndicw.h"  //w3sz tci
//#include "widgets/mainwindow.h" // TODO: G4WJS - break this dependency //w3sz tci
#include "Audio/soundout.h"
#include "commons.h"

#include "moc_Modulator.cpp"

extern float gran();		// Noise generator (for tests only)

#define RAMP_INCREMENT 64  // MUST be an integral factor of 2^16

#if defined (WSJT_SOFT_KEYING)
# define SOFT_KEYING WSJT_SOFT_KEYING
#else
# define SOFT_KEYING 1
#endif

double constexpr Modulator::m_twoPi;

namespace
{
  TxEvidence::TxStartSnapshot txStartSnapshot (TxEvidence::TxSessionId sessionId,
                                                TxEvidence::TxGeneration generation,
                                                QString const& mode, int sampleRateHz,
                                                qint64 silentFrames, unsigned initialSample,
                                                bool tuning, bool fastMode,
                                                bool hasCwId,
                                                unsigned symbolsLength,
                                                double framesPerSymbol,
                                                double trPeriod)
  {
    TxEvidence::TxStartSnapshot snapshot;
    snapshot.session_id = sessionId;
    snapshot.generation = generation;
    snapshot.mode = mode;
    snapshot.sample_rate_hz = sampleRateHz;
    if (mode == QStringLiteral ("JTTY"))
      {
        snapshot.diagnostic = QStringLiteral ("JTTY source commits its own target.");
        return snapshot;
      }
    if (tuning)
      {
        snapshot.diagnostic = QStringLiteral ("Tune transmission has no bounded target.");
        return snapshot;
      }
    if (hasCwId)
      {
        snapshot.diagnostic = QStringLiteral ("CW ID can extend the generated target.");
        return snapshot;
      }
    if (symbolsLength == 0 || framesPerSymbol <= 0.0)
      {
        snapshot.diagnostic = QStringLiteral ("Generated target inputs are invalid.");
        return snapshot;
      }

    double const end = fastMode ? trPeriod * 48000.0 - 24000.0
                                : symbolsLength * 4.0 * framesPerSymbol;
    if (end < 0.0 || end > std::numeric_limits<unsigned>::max ())
      {
        snapshot.diagnostic = QStringLiteral ("Generated target end is invalid.");
        return snapshot;
      }
    unsigned const i1 {static_cast<unsigned> (end)};
    if (initialSample > i1)
      {
        snapshot.diagnostic = QStringLiteral ("Late start skipped the generated target.");
        return snapshot;
      }

    snapshot.target_known = true;
    snapshot.committed_end_sample = TxEvidence::boundedCommittedEndSample (
      silentFrames, initialSample, i1);
    snapshot.diagnostic = QStringLiteral ("Generated target committed.");
    return snapshot;
  }
}

//    float wpm=20.0;
//    unsigned m_nspd=1.2*48000.0/wpm;
//    m_nspd=3072;                           //18.75 WPM

Modulator::Modulator (unsigned frameRate, double periodLengthInSeconds,
                      QObject * parent)
  : AudioDevice {parent}
  , m_quickClose {false}
  , m_phi {0.0}
  , m_toneSpacing {0.0}
  , m_fSpread {0.0}
  , m_period {periodLengthInSeconds}
  , m_frameRate {frameRate}
  , m_state {Idle}
  , m_tuning {false}
  , m_cwLevel {false}
  , m_j0 {-1}
  , m_toneFrequency0 {1500.0}
{
}

void Modulator::start (TxEvidence::TxRequest request, SoundOutput * stream)
{
//  qDebug () << request.mode << request.symbols_length << request.frames_per_symbol
//            << request.frequency_hz << request.tone_spacing << request.channel
//            << request.synchronize << request.fast_mode << request.snr_db
//            << request.tr_period_s;
  Q_ASSERT (stream);
// Time according to this computer which becomes our base time
  auto const actualStartMs = QDateTime::currentMSecsSinceEpoch ();
  qint64 ms0 = actualStartMs % 86400000;
  unsigned mstr = ms0 % int(1000.0*m_period); // ms into the nominal Tx start time

  bool const constrained = request.start_window_open_ms >= 0
    && request.start_window_close_ms >= request.start_window_open_ms;
  if (constrained
      && (actualStartMs < request.start_window_open_ms
          || actualStartMs > request.start_window_close_ms))
    {
      Q_EMIT constrainedStartDecided (request.session_id.value (),
                                      request.generation.value (),
                                      request.start_window_open_ms, false,
                                      actualStartMs);
      return;
    }

  if(m_state != Idle) stop();
  m_mode = request.mode;
  m_quickClose = false;
  m_symbolsLength = request.symbols_length;
  m_isym0 = std::numeric_limits<unsigned>::max (); // big number
  m_frequency0 = 0.;
  m_phi = 0.;
  m_addNoise = request.snr_db < 0.;
  m_nsps = request.frames_per_symbol;
  m_frequency = request.frequency_hz;
  m_amp = std::numeric_limits<qint16>::max ();
  m_toneSpacing = request.tone_spacing;
  m_bFastMode=request.fast_mode;
  m_TRperiod=request.tr_period_s;
  m_tuning=request.tuning;
  m_cwId=request.cw_id;
  m_icmin=4294967295;
  m_icmax=0;
  unsigned delay_ms=1000;
  if((request.mode=="FT8" and m_nsps==1920) or (request.mode=="FST4" and m_nsps==720)) delay_ms=500;  //FT8, FST4-15
  if((request.mode=="FT8" and m_nsps==1024)) delay_ms=400;            //SuperFox Qary Polar Code transmission
  if(request.mode=="Q65" and m_nsps<=3600) delay_ms=500;              //Q65-15 and Q65-30
  if(request.mode=="FT4") delay_ms=300;                               //FT4
  if(request.mode=="JTTY")delay_ms=0;

// noise generator parameters
  if (m_addNoise) {
    m_snr = qPow (10.0, 0.05 * (request.snr_db - 6.0));
    m_fac = 3000.0;
    if (m_snr > 1.0) m_fac = 3000.0 / m_snr;
  }

  m_silentFrames = 0;
  m_ic=0;
  if (!m_tuning && !m_bFastMode)
    {
      // calculate number of silent frames to send, so that audio will
      // start at the nominal time "delay_ms" into the Tx sequence.
      if (request.synchronize)
        {
          if(delay_ms > mstr) {
            m_silentFrames =
              std::uint64_t {delay_ms - mstr} * m_frameRate / 1000;
          }
        }
 
      // adjust for late starts
      if(!m_silentFrames && mstr >= delay_ms)
        {
          auto const initialFrame =
            std::uint64_t {mstr - delay_ms} * m_frameRate / 1000;
          Q_ASSERT (initialFrame <= std::numeric_limits<unsigned>::max ());
          m_ic = static_cast<unsigned> (initialFrame);
        }
    }
  if(request.mode=="Echo" or request.mode=="JTTY") m_ic=0;

  initialize (QIODevice::ReadOnly, request.channel);
  Q_EMIT stateChanged ((m_state = (request.synchronize && m_silentFrames) ?
                        Synchronizing : Active));
//  qDebug() << "delay_ms:" << delay_ms << "mstr:" << mstr << "m_silentFrames:"
//           << m_silentFrames << "m_ic:" << m_ic << "m_state:" << m_state << synchronize;

  m_stream = stream;
  if (m_stream)
    {
      m_stream->restart (this, mstr);
    }
  else
    {
      qDebug () << "Modulator::start: no audio output stream assigned";
    }
  Q_EMIT txSourceCommitted (txStartSnapshot (request.session_id, request.generation,
                                             m_mode, m_frameRate,
                                             m_silentFrames, m_ic, m_tuning, m_bFastMode,
                                             !m_cwId.isEmpty (),
                                             m_symbolsLength, m_nsps, m_TRperiod));
  if (constrained)
    {
      Q_EMIT constrainedStartDecided (request.session_id.value (),
                                      request.generation.value (),
                                      request.start_window_open_ms, true,
                                      actualStartMs);
    }
}

void Modulator::tune (bool newState)
{
  m_tuning = newState;
  if (!m_tuning) stop (true);
}

void Modulator::stop (bool quick)
{
  m_quickClose = quick;
  close ();
}

void Modulator::close ()
{
  if (m_stream)
    {
      if (m_quickClose)
        {
          m_stream->reset ();
        }
      else
        {
          m_stream->stop ();
        }
    }
  if (m_state != Idle)
    {
      Q_EMIT stateChanged ((m_state = Idle));
    }
  AudioDevice::close ();
//  qDebug() << "zz" << m_icmin << m_icmax << m_icmax/48000.0;
}

qint64 Modulator::readData (char * data, qint64 maxSize)
{
  double toneFrequency=1500.0;
  if(m_nsps==6) {
    toneFrequency=1000.0;
    m_frequency=1000.0;
    m_frequency0=1000.0;
  }
  if(maxSize==0) return 0;
  Q_ASSERT (!(maxSize % qint64 (bytesPerFrame ()))); // no torn frames
  Q_ASSERT (isOpen ());

  qint64 numFrames (maxSize / bytesPerFrame ());
  qint16 * samples (reinterpret_cast<qint16 *> (data));
  qint16 * end (samples + numFrames * (bytesPerFrame () / sizeof (qint16)));
  qint64 framesGenerated (0);

//  if(m_ic==0) qDebug() << "aa" << 0.001*(QDateTime::currentMSecsSinceEpoch() % qint64(1000*m_TRperiod))
//                       << m_state << m_TRperiod << m_silentFrames << m_ic << foxcom_.wave[m_ic];

  switch (m_state)
    {
    case Synchronizing:
      {
        if (m_silentFrames)	{  // send silence up to end of start delay
          framesGenerated = qMin (m_silentFrames, numFrames);
          do
            {
              samples = load (0, samples); // silence
            } while (--m_silentFrames && samples != end);
          if (!m_silentFrames)
            {
              Q_EMIT stateChanged ((m_state = Active));
            }
        }

        m_cwLevel = false;
        m_ramp = 0;		// prepare for CW wave shaping
      }
      // fall through

    case Active:
      {
        unsigned int isym=0;

        if(!m_tuning) isym=m_ic/(4.0*m_nsps);            // Actual fsample=48000
        bool slowCwId=((isym >= m_symbolsLength) && !m_cwId.isEmpty ()) && (!m_bFastMode);
        if(m_TRperiod==3.0) slowCwId=false;
        bool fastCwId=false;
        static bool bCwId=false;
        qint64 ms = QDateTime::currentMSecsSinceEpoch();
        float tsec=0.001*(ms % int(1000*m_TRperiod));
        if(m_bFastMode and !m_cwId.isEmpty () and (tsec > (m_TRperiod-5.0))) fastCwId=true;
        if(!m_bFastMode) m_nspd=2560;                 // 22.5 WPM


        if(slowCwId or fastCwId) {     // Transmit CW ID?
          m_dphi = m_twoPi*m_frequency/m_frameRate;
          if(m_bFastMode and !bCwId) {
            m_frequency=1500;          // Set params for CW ID
            m_dphi = m_twoPi*m_frequency/m_frameRate;
            m_symbolsLength=126;
            m_nsps=4096.0*12000.0/11025.0;
            m_ic=2246949;
            m_nspd=2560;               // 22.5 WPM
            if(m_cwId.size ()*m_nspd/48000.0 > 4.0) m_nspd=4.0*48000.0/m_cwId.size ();  //Faster CW for long calls
          }
          bCwId=true;
          unsigned ic0 = m_symbolsLength * 4 * m_nsps;
          unsigned j(0);

          while (samples != end) {
            j = (m_ic - ic0)/m_nspd + 1; // symbol of this sample
            if (j == 0 || j > static_cast<unsigned> (m_cwId.size ()))
              {
                Q_EMIT stateChanged ((m_state = Idle));
                return framesGenerated * bytesPerFrame ();
              }
            bool level {bool (m_cwId.at (j - 1))};
            m_phi += m_dphi;
            if (m_phi > m_twoPi) m_phi -= m_twoPi;
            qint16 sample=0;
            float amp=32767.0;
            float x=0;
            if(m_ramp!=0) {
              x=qSin(float(m_phi));
              if(SOFT_KEYING) {
                amp=qAbs(qint32(m_ramp));
                if(amp>32767.0) amp=32767.0;
              }
              sample=round(amp*x);
            }
            if(m_bFastMode) {
              sample=0;
              if(level) sample=32767.0*x;
            }
            samples = load (postProcessSample (sample), samples);
            ++framesGenerated;
            ++m_ic;

            // adjust ramp
            if ((m_ramp != 0 && m_ramp != std::numeric_limits<qint16>::min ()) || level != m_cwLevel) {
              // either ramp has terminated at max/min or direction has changed
              m_ramp += RAMP_INCREMENT; // ramp
            }
            m_cwLevel = level;
          }
          return framesGenerated * bytesPerFrame ();
        } else {
          bCwId=false;
        } //End of code for CW ID

        double const baud (12000.0 / m_nsps);
        // fade out parameters (no fade out for tuning)
        unsigned int i0,i1;
        if(m_tuning) {
          i1 = i0 = (m_bFastMode ? 999999 : 9999) * m_nsps;
        } else {
          i0=(m_symbolsLength - 0.017) * 4.0 * m_nsps;
          i1= m_symbolsLength * 4.0 * m_nsps;
        }
        if(m_bFastMode and !m_tuning) {
          i1=m_TRperiod*48000.0 - 24000.0;
          i0=i1-816;
        }

        qint16 sample;

        while (samples != end && m_ic <= i1) {
          isym=0;
          if(!m_tuning and m_TRperiod!=3.0) isym=m_ic/(4.0*m_nsps);   //Actual fsample=48000
          if(m_bFastMode) isym=isym%m_symbolsLength;
          if (isym != m_isym0 || m_frequency != m_frequency0) {
            if(itone[0]>=100) {
              m_toneFrequency0=itone[0];
            } else {
              if(m_toneSpacing==0.0) {
                m_toneFrequency0=m_frequency + itone[isym]*baud;
              } else {
                m_toneFrequency0=m_frequency + itone[isym]*m_toneSpacing;
              }
            }
            m_dphi = m_twoPi * m_toneFrequency0 / m_frameRate;
            m_isym0 = isym;
            m_frequency0 = m_frequency;         //???
          }

          int j=m_ic/480;
          if(m_fSpread>0.0 and j!=m_j0) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
            float x1=QRandomGenerator::global ()->generateDouble ();
            float x2=QRandomGenerator::global ()->generateDouble ();
#else
            float x1=(float)qrand()/RAND_MAX;
            float x2=(float)qrand()/RAND_MAX;
#endif
            toneFrequency = m_toneFrequency0 + 0.5*m_fSpread*(x1+x2-1.0);
            m_dphi = m_twoPi * toneFrequency / m_frameRate;
            m_j0=j;
          }

          m_phi += m_dphi;
          if (m_phi > m_twoPi) m_phi -= m_twoPi;
          if (m_ic > i0) m_amp = 0.98 * m_amp;
          if (m_ic > i1) m_amp = 0.0;

          sample=qRound(m_amp*qSin(m_phi));

//Here's where we transmit from a precomputed wave[] array:
          if(!m_tuning and (m_toneSpacing < 0) and (itone[0]<100)) {
            m_amp=32767.0;
            sample=qRound(m_amp*foxcom_.wave[m_ic]);
            m_icmin=qMin(m_ic,m_icmin);
            m_icmax=qMax(m_ic,m_icmax);
          }
/*
          if((m_ic<1000 or (4*m_symbolsLength*m_nsps - m_ic) < 1000) and (m_ic%10)==0) {
            qDebug() << "cc" << QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz") << m_ic << sample;
          }
*/
          samples = load(postProcessSample(sample), samples);
          ++framesGenerated;
          ++m_ic;
        }

        if((m_TRperiod==3 or m_mode=="JTTY") and m_ic >i1) {
          Q_EMIT stateChanged ((m_state = Idle));
          return framesGenerated * bytesPerFrame ();
        }

//        qDebug() << "dd" << m_mode << QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz")
//                 << tsec << m_TRperiod << m_ic << i1;

        if (m_amp == 0.0) { // TODO G4WJS: compare double with zero might not be wise
          if (m_cwId.isEmpty ()) {
            // no CW ID to send
            Q_EMIT stateChanged ((m_state = Idle));
            return framesGenerated * bytesPerFrame ();
          }
          m_phi = 0.0;
        }

        m_frequency0 = m_frequency;
// done for this chunk - continue on next call

//        qDebug() << "Mod B" << m_ic << i1 << 0.001*(QDateTime::currentMSecsSinceEpoch() % (1000*m_TRperiod));

        while (samples != end)  // pad block with silence
          {
            samples = load (0, samples);
            ++framesGenerated;
          }
//        if(tsec<0.5) qDebug() << "ee" << QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz")
//                 << tsec << m_ic << i1 << m_icmin << m_icmax;
        return framesGenerated * bytesPerFrame ();
      }
      // fall through

    case Idle:
      break;
    }

  Q_ASSERT (Idle == m_state);
  return 0;
}

qint16 Modulator::postProcessSample (qint16 sample) const
{
  if (m_addNoise) {  // Test frame, we'll add noise
    qint32 s = m_fac * (gran () + sample * m_snr / 32768.0);
    if (s > std::numeric_limits<qint16>::max ()) {
      s = std::numeric_limits<qint16>::max ();
    }
    if (s < std::numeric_limits<qint16>::min ()) {
      s = std::numeric_limits<qint16>::min ();
    }
    sample = s;
  }
  return sample;
}