File: asio.cpp

package info (click to toggle)
ares 126-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 32,600 kB
  • sloc: cpp: 356,508; ansic: 20,394; makefile: 16; sh: 2
file content (297 lines) | stat: -rw-r--r-- 9,791 bytes parent folder | download | duplicates (2)
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
#include <nall/windows/registry.hpp>
#include "asio.hpp"

struct AudioASIO : AudioDriver {
  static AudioASIO* instance;
  AudioASIO& self = *this;
  AudioASIO(Audio& super) : AudioDriver(super) { instance = this; }
  ~AudioASIO() { terminate(); }

  auto create() -> bool override {
    super.setDevice(hasDevices().first());
    super.setChannels(2);
    super.setFrequency(48000);
    super.setLatency(2048);
    return initialize();
  }

  auto driver() -> string override { return "ASIO"; }
  auto ready() -> bool override { return _ready; }

  auto hasContext() -> bool override { return true; }
  auto hasBlocking() -> bool override { return true; }

  auto hasDevices() -> vector<string> override {
    self.devices.reset();
    for(auto candidate : registry::contents("HKLM\\SOFTWARE\\ASIO\\")) {
      if(auto classID = registry::read({"HKLM\\SOFTWARE\\ASIO\\", candidate, "CLSID"})) {
        self.devices.append({candidate.trimRight("\\", 1L), classID});
      }
    }

    vector<string> devices;
    for(auto& device : self.devices) devices.append(device.name);
    return devices;
  }

  auto hasChannels() -> vector<u32> override {
    return {1, 2};
  }

  auto hasFrequencies() -> vector<u32> override {
    return {self.frequency};
  }

  auto hasLatencies() -> vector<u32> override {
    vector<u32> latencies;
    u32 latencyList[] = {64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 6144};  //factors of 6144
    for(auto& latency : latencyList) {
      if(self.activeDevice) {
        if(latency < self.activeDevice.minimumBufferSize) continue;
        if(latency > self.activeDevice.maximumBufferSize) continue;
      }
      latencies.append(latency);
    }
    //it is possible that no latencies in the hard-coded list above will match; so ensure driver-declared latencies are available
    if(!latencies.find(self.activeDevice.minimumBufferSize)) latencies.append(self.activeDevice.minimumBufferSize);
    if(!latencies.find(self.activeDevice.maximumBufferSize)) latencies.append(self.activeDevice.maximumBufferSize);
    if(!latencies.find(self.activeDevice.preferredBufferSize)) latencies.append(self.activeDevice.preferredBufferSize);
    latencies.sort();
    return latencies;
  }

  auto setContext(uintptr context) -> bool override { return initialize(); }
  auto setDevice(string device) -> bool override { return initialize(); }
  auto setBlocking(bool blocking) -> bool override { return initialize(); }
  auto setChannels(u32 channels) -> bool override { return initialize(); }
  auto setLatency(u32 latency) -> bool override { return initialize(); }

  auto clear() -> void override {
    if(!ready()) return;
    for(u32 n : range(self.channels)) {
      memory::fill<u8>(_channel[n].buffers[0], self.latency * _sampleSize);
      memory::fill<u8>(_channel[n].buffers[1], self.latency * _sampleSize);
    }
    memory::fill<u8>(_queue.samples, sizeof(_queue.samples));
    _queue.read = 0;
    _queue.write = 0;
    _queue.count = 0;
  }

  auto output(const f64 samples[]) -> void override {
    if(!ready()) return;
    //defer call to IASIO::start(), because the drivers themselves will sometimes crash internally.
    //if software initializes AudioASIO but does not play music at startup, this can prevent a crash loop.
    if(!_started) {
      _started = true;
      if(_asio->start() != ASE_OK) {
        _ready = false;
        return;
      }
    }
    if(self.blocking) {
      while(_queue.count >= self.latency);
    }
    for(u32 n : range(self.channels)) {
      _queue.samples[_queue.write][n] = samples[n];
    }
    _queue.write++;
    _queue.count++;
  }

private:
  auto initialize() -> bool {
    terminate();

    hasDevices();  //this call populates self.devices
    if(!self.devices) return false;

    self.activeDevice = {};
    for(auto& device : self.devices) {
      if(self.device == device.name) {
        self.activeDevice = device;
        break;
      }
    }
    if(!self.activeDevice) {
      self.activeDevice = self.devices.first();
      self.device = self.activeDevice.name;
    }

    CLSID classID;
    if(CLSIDFromString((LPOLESTR)utf16_t(self.activeDevice.classID), (LPCLSID)&classID) != S_OK) return false;
    if(CoCreateInstance(classID, 0, CLSCTX_INPROC_SERVER, classID, (void**)&_asio) != S_OK) return false;

    if(!_asio->init((void*)self.context)) return false;
    if(_asio->getSampleRate(&self.activeDevice.sampleRate) != ASE_OK) return false;
    if(_asio->getChannels(&self.activeDevice.inputChannels, &self.activeDevice.outputChannels) != ASE_OK) return false;
    if(_asio->getBufferSize(
      &self.activeDevice.minimumBufferSize,
      &self.activeDevice.maximumBufferSize,
      &self.activeDevice.preferredBufferSize,
      &self.activeDevice.granularity
    ) != ASE_OK) return false;

    self.frequency = self.activeDevice.sampleRate;
    self.latency = self.latency < self.activeDevice.minimumBufferSize ? self.activeDevice.minimumBufferSize : self.latency;
    self.latency = self.latency > self.activeDevice.maximumBufferSize ? self.activeDevice.maximumBufferSize : self.latency;

    for(u32 n : range(self.channels)) {
      _channel[n].isInput = false;
      _channel[n].channelNum = n;
      _channel[n].buffers[0] = nullptr;
      _channel[n].buffers[1] = nullptr;
    }
    ASIOCallbacks callbacks;
    callbacks.bufferSwitch = &AudioASIO::_bufferSwitch;
    callbacks.sampleRateDidChange = &AudioASIO::_sampleRateDidChange;
    callbacks.asioMessage = &AudioASIO::_asioMessage;
    callbacks.bufferSwitchTimeInfo = &AudioASIO::_bufferSwitchTimeInfo;
    if(_asio->createBuffers(_channel, self.channels, self.latency, &callbacks) != ASE_OK) return false;
    if(_asio->getLatencies(&self.activeDevice.inputLatency, &self.activeDevice.outputLatency) != ASE_OK) return false;

    //assume for the sake of sanity that all buffers use the same sample format ...
    ASIOChannelInfo channelInformation = {};
    channelInformation.channel = 0;
    channelInformation.isInput = false;
    if(_asio->getChannelInfo(&channelInformation) != ASE_OK) return false;
    switch(_sampleFormat = channelInformation.type) {
    case ASIOSTInt16LSB: _sampleSize = 2; break;
    case ASIOSTInt24LSB: _sampleSize = 3; break;
    case ASIOSTInt32LSB: _sampleSize = 4; break;
    case ASIOSTFloat32LSB: _sampleSize = 4; break;
    case ASIOSTFloat64LSB: _sampleSize = 8; break;
    default: return false;  //unsupported sample format
    }

    _ready = true;
    _started = false;
    clear();
    return true;
  }

  auto terminate() -> void {
    _ready = false;
    _started = false;
    self.activeDevice = {};
    if(_asio) {
      _asio->stop();
      _asio->disposeBuffers();
      _asio->Release();
      _asio = nullptr;
    }
  }

private:
  static auto _bufferSwitch(long doubleBufferInput, ASIOBool directProcess) -> void {
    return instance->bufferSwitch(doubleBufferInput, directProcess);
  }

  static auto _sampleRateDidChange(ASIOSampleRate sampleRate) -> void {
    return instance->sampleRateDidChange(sampleRate);
  }

  static auto _asioMessage(long selector, long value, void* message, double* optional) -> long {
    return instance->asioMessage(selector, value, message, optional);
  }

  static auto _bufferSwitchTimeInfo(ASIOTime* parameters, long doubleBufferIndex, ASIOBool directProcess) -> ASIOTime* {
    return instance->bufferSwitchTimeInfo(parameters, doubleBufferIndex, directProcess);
  }

  auto bufferSwitch(long doubleBufferInput, ASIOBool directProcess) -> void {
    for(u32 sampleIndex : range(self.latency)) {
      f64 samples[8] = {0};
      if(_queue.count) {
        for(u32 n : range(self.channels)) {
          samples[n] = _queue.samples[_queue.read][n];
        }
        _queue.read++;
        _queue.count--;
      }

      for(u32 n : range(self.channels)) {
        auto buffer = (u8*)_channel[n].buffers[doubleBufferInput];
        buffer += sampleIndex * _sampleSize;

        switch(_sampleFormat) {
        case ASIOSTInt16LSB: {
          *(u16*)buffer = (u16)sclamp<16>(samples[n] * (32768.0 - 1.0));
          break;
        }

        case ASIOSTInt24LSB: {
          auto value = (u32)sclamp<24>(samples[n] * (256.0 * 32768.0 - 1.0));
          buffer[0] = value >>  0;
          buffer[1] = value >>  8;
          buffer[2] = value >> 16;
          break;
        }

        case ASIOSTInt32LSB: {
          *(u32*)buffer = (u32)sclamp<32>(samples[n] * (65536.0 * 32768.0 - 1.0));
          break;
        }

        case ASIOSTFloat32LSB: {
          *(f32*)buffer = max(-1.0, min(+1.0, samples[n]));
          break;
        }

        case ASIOSTFloat64LSB: {
          *(f64*)buffer = max(-1.0, min(+1.0, samples[n]));
          break;
        }
        }
      }
    }
  }

  auto sampleRateDidChange(ASIOSampleRate sampleRate) -> void {
  }

  auto asioMessage(long selector, long value, void* message, double* optional) -> long {
    return ASE_OK;
  }

  auto bufferSwitchTimeInfo(ASIOTime* parameters, long doubleBufferIndex, ASIOBool directProcess) -> ASIOTime* {
    return nullptr;
  }

  bool _ready = false;
  bool _started = false;

  struct Queue {
    f64 samples[65536][8];
    u16 read;
    u16 write;
    std::atomic<u16> count;
  };

  struct Device {
    explicit operator bool() const { return name; }

    string name;
    string classID;

    ASIOSampleRate sampleRate;
    long inputChannels;
    long outputChannels;
    long inputLatency;
    long outputLatency;
    long minimumBufferSize;
    long maximumBufferSize;
    long preferredBufferSize;
    long granularity;
  };

  Queue _queue;
  vector<Device> devices;
  Device activeDevice;
  IASIO* _asio = nullptr;
  ASIOBufferInfo _channel[8];
  long _sampleFormat;
  long _sampleSize;
};

AudioASIO* AudioASIO::instance = nullptr;