summaryrefslogtreecommitdiff
path: root/map65/soundout.cpp
blob: baa0d129a6b3c0d9297e4b31d44f98fb61515ccc (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
#include "soundout.h"

#ifdef Q_OS_WIN32
#include <windows.h>
#endif

#include <portaudio.h>

extern float gran();
extern short int iwave[2*60*12000]; //was 11025
extern int nwave;
extern bool btxok;
extern bool bTune;
extern bool bIQxt;
extern int iqAmp;
extern int iqPhase;
extern int txPower;
extern double outputLatency;

typedef struct
{
  int nTRperiod;
  int actualChannelCount; 
  double streamSampleRate; // Added to help callback calculate pitch
} paUserData;

//--------------------------------------------------------------- d2aCallback
extern "C" int d2aCallback(const void * /*inputBuffer*/, void *outputBuffer,
                           unsigned long framesToProcess,
                           const PaStreamCallbackTimeInfo* /*timeInfo*/,
                           PaStreamCallbackFlags /*statusFlags*/,
                           void *userData )
{
  paUserData *udata = (paUserData*)userData;
  short *wptr = (short*)outputBuffer;
  int channels = udata->actualChannelCount;
  
  // step is ~0.229 for 48k ASIO, and exactly 1.0 for 11k MME
    // Calculate step once outside the loop
  double step = 11025.0 / udata->streamSampleRate;   
  const int waveCapacity = sizeof(iwave) / sizeof(iwave[0]);

  static double ic_exact = 0.0; 
  static bool btxok0 = false;
  static bool bTune0 = false;
  static int nStart = 0;
  static double phi = 0.;
  
  double tsec, tstart;
  double dphi = 0.0;
  int nsec;
  int nTRperiod = udata->nTRperiod;

  qint64 ms = QDateTime::currentMSecsSinceEpoch() % 86400000;
  tsec = 0.001 * ms;
  nsec = ms / 1000;
  
  qreal dPhase = iqPhase / 5729.57795131;
  qreal amp = 1.0 + 0.0001 * iqAmp;
  qreal xAmp = txPower * 295.00 * qSqrt(2.0 - amp * amp);
  qreal yAmp = txPower * 295.00 * amp;
  static int nsec0 = 0;

  if(bTune) {
    ic_exact = 0;
    // Use the actual stream sample rate, not 11025
    dphi = 6.28318530718 * 1270.46 / udata->streamSampleRate;
  }

  if(bTune0 && !bTune) btxok = false;
  bTune0 = bTune;
  if(nsec != nsec0) nsec0 = nsec;

  // Handle Tx Start/Restart logic
  if(btxok && !btxok0) {
    int n = nsec / nTRperiod;
    tstart = tsec - n * nTRperiod - 1.0;
    if(tstart < 1.0) {
      ic_exact = 0;
      nStart = n;
    } else {
      if(n != nStart) {
        ic_exact = (tstart * 11025.0);
        nStart = n;
      }
    }
  }
  btxok0 = btxok;


  for(unsigned int i = 0; i < framesToProcess; i++) {
    // 1. Get current fractional position
    int i0 = (int)ic_exact;
    int i1 = i0 + 1;
    double frac = ic_exact - (double)i0;

    short int i2a = 0;
    short int i2b = 0;

    int i0a = 2 * i0;
    int i0b = i0a + 1;
    int i1a = 2 * i1;
    int i1b = i1a + 1;
    bool haveWaveformSample = i1b < nwave && i1b < waveCapacity;

    if(btxok && (bTune || haveWaveformSample)) {

      if(bTune) {
        phi += dphi;
      } else {
          // 2. Linear Interpolation to clean up the noise
          // Blend current sample (i0) and next sample (i1) based on frac
          i2a = (short int)((1.0 - frac) * iwave[i0a] + frac * iwave[i1a]);
          i2b = (short int)((1.0 - frac) * iwave[i0b] + frac * iwave[i1b]);
          phi = qAtan2(qreal(i2b), qreal(i2a));
        }        
      i2a = xAmp * qCos(phi);
      i2b = yAmp * qSin(phi + dPhase);
    }

    *wptr++ = i2b; // Left
    *wptr++ = i2a; // Right

    // Pad remaining 6 channels for Voicemeeter
    for(int c = 2; c < channels; c++) {
      *wptr++ = 0;
    }

    // Advance index by the ratio (0.229)
    ic_exact += step;

    if((2 * (int)ic_exact) >= nwave) {
      btxok = false;
      ic_exact = 0;
    }
  }

  return paContinue;
}

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

void SoundOutThread::run()
{
  COMWrapper c;
  PaError paerr;
  PaStreamParameters outParam;
  PaStream *outStream;
  paUserData udata;
  quitExecution = false;

  // --- SAFETY CHECK 1: Ensure device index is valid ---
  auto device_info = Pa_GetDeviceInfo(m_nDevOut);
  if (!device_info) {
      qDebug() << "ASIO Error: Could not get info for device index" << m_nDevOut;
      return;
  }

  // --- SAFETY CHECK 2: Ensure Host API is valid ---
  auto host_api_info = Pa_GetHostApiInfo(device_info->hostApi);
  if (!host_api_info) {
      qDebug() << "ASIO Error: Could not get host API info for device" << m_nDevOut;
      return;
  }
  
  bool isASIO = (host_api_info->type == paASIO);

  // Setup defaults for non-ASIO (MME, DirectSound, etc)
  double outRate = 11025.0; 
  udata.actualChannelCount = 2;
  unsigned long framesPerBuffer = 256; 

  if(isASIO) {
      outRate = 48000.0; 
      udata.actualChannelCount = 8; 
      framesPerBuffer = paFramesPerBufferUnspecified;
  }

  udata.nTRperiod = m_TRperiod;
  udata.streamSampleRate = outRate;

  outParam.device = m_nDevOut;
  outParam.channelCount = udata.actualChannelCount;
  outParam.sampleFormat = paInt16;
  
  // --- SAFETY CHECK 3: Guard latency access ---
  outParam.suggestedLatency = device_info->defaultLowOutputLatency;
  outParam.hostApiSpecificStreamInfo = NULL;

  // ASIO Fallback Logic
  paerr = Pa_IsFormatSupported(NULL, &outParam, outRate);
  if(paerr < 0 && isASIO) {
      udata.actualChannelCount = 2;
      outParam.channelCount = 2;
      paerr = Pa_IsFormatSupported(NULL, &outParam, outRate);
  }

  // --- SAFETY CHECK 4: Final guard before opening ---
  paerr = Pa_OpenStream(&outStream, NULL, &outParam, outRate, 
                        framesPerBuffer, paClipOff, 
                        d2aCallback, &udata);

  if(paerr != paNoError) {
      qDebug() << "Pa_OpenStream failed:" << Pa_GetErrorText(paerr);
      return;
  }

  paerr = Pa_StartStream(outStream);
  if(paerr != paNoError) {
      qDebug() << "Pa_StartStream failed:" << Pa_GetErrorText(paerr);
      return;
  }

  // --- SAFETY CHECK 5: Final stream info guard ---
  const PaStreamInfo* p = Pa_GetStreamInfo(outStream);
  if (p) {
      outputLatency = p->outputLatency;
  }

  while (!quitExecution) { msleep(100); }

  Pa_StopStream(outStream);
  Pa_CloseStream(outStream);
}

void SoundOutThread::setOutputDevice(int n) { this->m_nDevOut = n; }
void SoundOutThread::setPeriod(int n) { m_TRperiod = n; }