LynxAsio.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937
  1. // LYNX ASIO — a universal ASIO driver on top of Windows Audio (WASAPI), REA round 97.
  2. //
  3. // An in-process COM server implementing Steinberg's IASIO interface. It works with any playback/recording device:
  4. // * Shared mode: other programs keep their sound. The stream asks Windows for the shortest engine period the device
  5. // supports (IAudioClient3), falling back to the classic period (10 ms on most devices). The ASIO block size is
  6. // free: a small FIFO decouples the host's blocks from the device's periods.
  7. // * Exclusive mode: LYNX ASIO alone on the device, event-driven at the ASIO block size (down to the device's
  8. // minimum period, often 3 ms), in the best integer/float format the device accepts.
  9. // The host always sees 32-bit float channels. Settings live in %APPDATA%\LYNX\lynx-asio.ini (no registry use except
  10. // DllRegisterServer/DllUnregisterServer, which a user runs once through regsvr32 as administrator).
  11. //
  12. // Clean-room: written from Microsoft's WASAPI documentation and the ASIO SDK interface headers (GPLv3 option). FL Studio
  13. // ASIO was only observed for its general architecture (docs/analise/REA_rodada97.md); none of its code is used.
  14. //
  15. // Build: scripts/build-lynx-asio.sh (Zig/MinGW, x86_64-windows-gnu) -> lynx-asio.dll
  16. #include <windows.h>
  17. #include <objbase.h>
  18. #include <initguid.h>
  19. #include <mmdeviceapi.h>
  20. #include <audioclient.h>
  21. #include <functiondiscoverykeys_devpkey.h>
  22. #include <avrt.h>
  23. #include <ks.h>
  24. #include <ksmedia.h>
  25. #include <algorithm>
  26. #include <atomic>
  27. #include <cmath>
  28. #include <cstdarg>
  29. #include <cstdio>
  30. #include <cstring>
  31. #include <string>
  32. #include <vector>
  33. #include "asiosys.h"
  34. #include "asio.h"
  35. #include "iasiodrv.h"
  36. #include "InputDrift.h"
  37. // {E987C593-898E-4557-BFE3-4288B0228718} — LYNX ASIO's own class id (hosts also use it as the interface id)
  38. DEFINE_GUID (CLSID_LynxAsio, 0xe987c593, 0x898e, 0x4557, 0xbf, 0xe3, 0x42, 0x88, 0xb0, 0x22, 0x87, 0x18);
  39. namespace
  40. {
  41. constexpr const char* driverName = "LYNX ASIO";
  42. constexpr const wchar_t* driverNameW = L"LYNX ASIO";
  43. constexpr long driverVersion = 1;
  44. HINSTANCE moduleHandle = nullptr;
  45. std::atomic<long> serverLocks { 0 }, liveObjects { 0 };
  46. //==============================================================================================================
  47. // Small helpers
  48. template <class T>
  49. void releaseCom (T*& p)
  50. {
  51. if (p != nullptr)
  52. p->Release();
  53. p = nullptr;
  54. }
  55. double nowMs()
  56. {
  57. static const double toMs = []
  58. {
  59. LARGE_INTEGER f;
  60. QueryPerformanceFrequency (&f);
  61. return 1000.0 / (double) f.QuadPart;
  62. }();
  63. LARGE_INTEGER c;
  64. QueryPerformanceCounter (&c);
  65. return (double) c.QuadPart * toMs;
  66. }
  67. bool portugueseUi() { return PRIMARYLANGID (GetUserDefaultUILanguage()) == LANG_PORTUGUESE; }
  68. // English text, or its pt-BR translation when Windows speaks Portuguese.
  69. const wchar_t* tr (const wchar_t* en, const wchar_t* pt) { return portugueseUi() ? pt : en; }
  70. std::string narrow (const std::wstring& w)
  71. {
  72. if (w.empty())
  73. return {};
  74. const int n = WideCharToMultiByte (CP_ACP, 0, w.c_str(), (int) w.size(), nullptr, 0, nullptr, nullptr);
  75. std::string s ((size_t) n, '\0');
  76. WideCharToMultiByte (CP_ACP, 0, w.c_str(), (int) w.size(), s.data(), n, nullptr, nullptr);
  77. return s;
  78. }
  79. // Runs `f` on a fresh thread inside the multithreaded COM apartment and waits for it: every WASAPI object of this
  80. // driver lives in the MTA, whatever apartment the host calls from.
  81. template <class F>
  82. DWORD WINAPI mtaThreadMain (LPVOID p) // WINAPI: thread entry points are __stdcall on 32-bit Windows
  83. {
  84. const auto hr = CoInitializeEx (nullptr, COINIT_MULTITHREADED);
  85. (*(F*) p)();
  86. if (SUCCEEDED (hr))
  87. CoUninitialize();
  88. return 0;
  89. }
  90. template <class F>
  91. void onMtaThread (F& f)
  92. {
  93. HANDLE t = CreateThread (nullptr, 0, &mtaThreadMain<F>, &f, 0, nullptr);
  94. if (t != nullptr)
  95. {
  96. WaitForSingleObject (t, INFINITE);
  97. CloseHandle (t);
  98. }
  99. }
  100. //==============================================================================================================
  101. // Settings (%APPDATA%\LYNX\lynx-asio.ini; LYNX_ASIO_INI overrides the path for tests)
  102. enum class Mode
  103. {
  104. shared = 0,
  105. exclusive = 1
  106. };
  107. struct Settings
  108. {
  109. Mode mode = Mode::shared;
  110. int bufferSize = 0; // the preferred ASIO block in frames; 0 = automatic
  111. int safety = 2; // shared mode: 0 = one engine period queued, 1 = 1.5 periods, 2 = two periods
  112. std::wstring output; // endpoint id; empty = Windows' default device
  113. std::wstring input; // endpoint id; empty = default; "-" = no input
  114. static std::wstring path()
  115. {
  116. wchar_t buf[MAX_PATH * 2] {};
  117. if (GetEnvironmentVariableW (L"LYNX_ASIO_INI", buf, MAX_PATH * 2) > 0)
  118. return buf;
  119. if (GetEnvironmentVariableW (L"APPDATA", buf, MAX_PATH * 2) == 0)
  120. return {};
  121. std::wstring dir = std::wstring (buf) + L"\\LYNX";
  122. CreateDirectoryW (dir.c_str(), nullptr);
  123. return dir + L"\\lynx-asio.ini";
  124. }
  125. static Settings load()
  126. {
  127. Settings s;
  128. const auto file = path();
  129. if (file.empty())
  130. return s;
  131. const auto* f = file.c_str();
  132. s.mode = GetPrivateProfileIntW (L"LYNX ASIO", L"mode", 0, f) == 1 ? Mode::exclusive : Mode::shared;
  133. s.bufferSize = std::clamp ((int) GetPrivateProfileIntW (L"LYNX ASIO", L"bufferSize", 0, f), 0, 8192);
  134. s.safety = std::clamp ((int) GetPrivateProfileIntW (L"LYNX ASIO", L"safety", 2, f), 0, 2);
  135. wchar_t buf[512] {};
  136. GetPrivateProfileStringW (L"LYNX ASIO", L"output", L"", buf, 512, f);
  137. s.output = buf;
  138. GetPrivateProfileStringW (L"LYNX ASIO", L"input", L"", buf, 512, f);
  139. s.input = buf;
  140. return s;
  141. }
  142. void save() const
  143. {
  144. const auto file = path();
  145. if (file.empty())
  146. return;
  147. const auto* f = file.c_str();
  148. WritePrivateProfileStringW (L"LYNX ASIO", L"mode", mode == Mode::exclusive ? L"1" : L"0", f);
  149. WritePrivateProfileStringW (L"LYNX ASIO", L"bufferSize", std::to_wstring (bufferSize).c_str(), f);
  150. WritePrivateProfileStringW (L"LYNX ASIO", L"safety", std::to_wstring (safety).c_str(), f);
  151. WritePrivateProfileStringW (L"LYNX ASIO", L"output", output.c_str(), f);
  152. WritePrivateProfileStringW (L"LYNX ASIO", L"input", input.c_str(), f);
  153. }
  154. bool operator== (const Settings& o) const
  155. {
  156. return mode == o.mode && bufferSize == o.bufferSize && safety == o.safety && output == o.output && input == o.input;
  157. }
  158. };
  159. // Optional log (LYNX_ASIO_LOG = file path): what was opened and the stream statistics. Never on the audio path.
  160. void logLine (const char* fmt, ...)
  161. {
  162. wchar_t path[MAX_PATH * 2] {};
  163. if (GetEnvironmentVariableW (L"LYNX_ASIO_LOG", path, MAX_PATH * 2) == 0)
  164. return;
  165. char text[1024];
  166. va_list args;
  167. va_start (args, fmt);
  168. vsnprintf (text, sizeof (text), fmt, args);
  169. va_end (args);
  170. if (FILE* f = _wfopen (path, L"a"))
  171. {
  172. fprintf (f, "%s\n", text);
  173. fclose (f);
  174. }
  175. }
  176. //==============================================================================================================
  177. // Endpoints and formats
  178. struct Endpoint
  179. {
  180. std::wstring id, name;
  181. };
  182. std::vector<Endpoint> listEndpoints (EDataFlow flow)
  183. {
  184. std::vector<Endpoint> result;
  185. IMMDeviceEnumerator* en = nullptr;
  186. if (FAILED (CoCreateInstance (__uuidof (MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof (IMMDeviceEnumerator), (void**) &en)))
  187. return result;
  188. IMMDeviceCollection* all = nullptr;
  189. if (SUCCEEDED (en->EnumAudioEndpoints (flow, DEVICE_STATE_ACTIVE, &all)))
  190. {
  191. UINT n = 0;
  192. all->GetCount (&n);
  193. for (UINT i = 0; i < n; ++i)
  194. {
  195. IMMDevice* d = nullptr;
  196. if (FAILED (all->Item (i, &d)))
  197. continue;
  198. Endpoint e;
  199. LPWSTR id = nullptr;
  200. if (SUCCEEDED (d->GetId (&id)))
  201. {
  202. e.id = id;
  203. CoTaskMemFree (id);
  204. }
  205. IPropertyStore* props = nullptr;
  206. if (SUCCEEDED (d->OpenPropertyStore (STGM_READ, &props)))
  207. {
  208. PROPVARIANT v;
  209. PropVariantInit (&v);
  210. if (SUCCEEDED (props->GetValue (PKEY_Device_FriendlyName, &v)) && v.vt == VT_LPWSTR)
  211. e.name = v.pwszVal;
  212. PropVariantClear (&v);
  213. props->Release();
  214. }
  215. result.push_back (e);
  216. d->Release();
  217. }
  218. all->Release();
  219. }
  220. en->Release();
  221. return result;
  222. }
  223. // The chosen endpoint (empty id = Windows' default device for that direction); nullptr when it is gone.
  224. IMMDevice* openEndpoint (EDataFlow flow, const std::wstring& id)
  225. {
  226. IMMDeviceEnumerator* en = nullptr;
  227. if (FAILED (CoCreateInstance (__uuidof (MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof (IMMDeviceEnumerator), (void**) &en)))
  228. return nullptr;
  229. IMMDevice* d = nullptr;
  230. if (! id.empty())
  231. en->GetDevice (id.c_str(), &d);
  232. if (d == nullptr)
  233. en->GetDefaultAudioEndpoint (flow, eConsole, &d);
  234. en->Release();
  235. return d;
  236. }
  237. std::wstring endpointName (IMMDevice* d)
  238. {
  239. std::wstring name;
  240. IPropertyStore* props = nullptr;
  241. if (d != nullptr && SUCCEEDED (d->OpenPropertyStore (STGM_READ, &props)))
  242. {
  243. PROPVARIANT v;
  244. PropVariantInit (&v);
  245. if (SUCCEEDED (props->GetValue (PKEY_Device_FriendlyName, &v)) && v.vt == VT_LPWSTR)
  246. name = v.pwszVal;
  247. PropVariantClear (&v);
  248. props->Release();
  249. }
  250. return name;
  251. }
  252. enum class SampleKind
  253. {
  254. float32,
  255. int32,
  256. int24,
  257. int16
  258. };
  259. struct StreamFormat
  260. {
  261. WAVEFORMATEXTENSIBLE wf {};
  262. SampleKind kind = SampleKind::float32;
  263. int channels = 2;
  264. int bytesPerFrame = 8;
  265. };
  266. StreamFormat makeFormat (int channels, int rate, SampleKind kind, DWORD channelMask)
  267. {
  268. StreamFormat f;
  269. f.kind = kind;
  270. f.channels = channels;
  271. const int container = kind == SampleKind::int16 ? 16 : kind == SampleKind::int24 ? 24 : 32;
  272. const int valid = kind == SampleKind::int16 ? 16 : kind == SampleKind::int24 ? 24 : 32;
  273. auto& w = f.wf;
  274. w.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  275. w.Format.nChannels = (WORD) channels;
  276. w.Format.nSamplesPerSec = (DWORD) rate;
  277. w.Format.wBitsPerSample = (WORD) container;
  278. w.Format.nBlockAlign = (WORD) (channels * container / 8);
  279. w.Format.nAvgBytesPerSec = w.Format.nBlockAlign * (DWORD) rate;
  280. w.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  281. w.Samples.wValidBitsPerSample = (WORD) valid;
  282. w.dwChannelMask = channelMask;
  283. w.SubFormat = kind == SampleKind::float32 ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  284. f.bytesPerFrame = w.Format.nBlockAlign;
  285. return f;
  286. }
  287. DWORD maskOf (const WAVEFORMATEX* w)
  288. {
  289. if (w->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
  290. return ((const WAVEFORMATEXTENSIBLE*) w)->dwChannelMask;
  291. return w->nChannels == 1 ? SPEAKER_FRONT_CENTER : w->nChannels == 2 ? (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT) : 0;
  292. }
  293. const char* kindName (SampleKind k)
  294. {
  295. switch (k)
  296. {
  297. case SampleKind::float32: return "float32";
  298. case SampleKind::int32: return "int32";
  299. case SampleKind::int24: return "int24";
  300. case SampleKind::int16: return "int16";
  301. }
  302. return "?";
  303. }
  304. // interleaved float frames -> device bytes
  305. void writeSamples (const float* src, BYTE* dst, int samples, SampleKind kind)
  306. {
  307. switch (kind)
  308. {
  309. case SampleKind::float32:
  310. std::memcpy (dst, src, (size_t) samples * 4);
  311. break;
  312. case SampleKind::int32:
  313. for (int i = 0; i < samples; ++i)
  314. {
  315. const double v = std::clamp ((double) src[i], -1.0, 1.0) * 2147483647.0;
  316. ((int32_t*) dst)[i] = (int32_t) std::lrint (v);
  317. }
  318. break;
  319. case SampleKind::int24:
  320. for (int i = 0; i < samples; ++i)
  321. {
  322. const auto v = (int32_t) std::lrint (std::clamp (src[i], -1.0f, 1.0f) * 8388607.0f);
  323. dst[3 * i] = (BYTE) (v & 0xff);
  324. dst[3 * i + 1] = (BYTE) ((v >> 8) & 0xff);
  325. dst[3 * i + 2] = (BYTE) ((v >> 16) & 0xff);
  326. }
  327. break;
  328. case SampleKind::int16:
  329. for (int i = 0; i < samples; ++i)
  330. ((int16_t*) dst)[i] = (int16_t) std::lrint (std::clamp (src[i], -1.0f, 1.0f) * 32767.0f);
  331. break;
  332. }
  333. }
  334. // device bytes -> interleaved float frames
  335. void readSamples (const BYTE* src, float* dst, int samples, SampleKind kind)
  336. {
  337. switch (kind)
  338. {
  339. case SampleKind::float32:
  340. std::memcpy (dst, src, (size_t) samples * 4);
  341. break;
  342. case SampleKind::int32:
  343. for (int i = 0; i < samples; ++i)
  344. dst[i] = (float) (((const int32_t*) src)[i] / 2147483648.0);
  345. break;
  346. case SampleKind::int24:
  347. for (int i = 0; i < samples; ++i)
  348. {
  349. const int32_t v = (int32_t) ((uint32_t) src[3 * i] << 8 | (uint32_t) src[3 * i + 1] << 16 | (uint32_t) src[3 * i + 2] << 24) >> 8;
  350. dst[i] = (float) v / 8388608.0f;
  351. }
  352. break;
  353. case SampleKind::int16:
  354. for (int i = 0; i < samples; ++i)
  355. dst[i] = (float) ((const int16_t*) src)[i] / 32768.0f;
  356. break;
  357. }
  358. }
  359. REFERENCE_TIME framesToRefTime (int frames, double rate) { return (REFERENCE_TIME) std::llround (frames * 1.0e7 / rate); }
  360. int refTimeToFrames (REFERENCE_TIME t, double rate) { return (int) std::llround ((double) t * rate / 1.0e7); }
  361. const double standardRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  362. // What a device offers (probed in init and by the panel).
  363. struct DeviceInfo
  364. {
  365. bool ok = false;
  366. std::wstring name;
  367. int channels = 2;
  368. double mixRate = 48000.0;
  369. DWORD channelMask = 0;
  370. int sharedPeriod = 480; // frames at mixRate: the shortest shared engine period
  371. int classicPeriod = 480; // frames: Windows' default device period
  372. int exclusiveMinPeriod = 0; // frames at mixRate (0 = exclusive mode unavailable)
  373. std::vector<double> exclusiveRates;
  374. };
  375. // Exclusive-mode format for `rate`, best first; false when the device takes none.
  376. bool exclusiveFormat (IMMDevice* d, int channels, int rate, DWORD mask, StreamFormat& out)
  377. {
  378. IAudioClient* c = nullptr;
  379. if (FAILED (d->Activate (__uuidof (IAudioClient), CLSCTX_ALL, nullptr, (void**) &c)))
  380. return false;
  381. bool found = false;
  382. for (auto kind : { SampleKind::float32, SampleKind::int32, SampleKind::int24, SampleKind::int16 })
  383. {
  384. auto f = makeFormat (channels, rate, kind, mask);
  385. if (c->IsFormatSupported (AUDCLNT_SHAREMODE_EXCLUSIVE, &f.wf.Format, nullptr) == S_OK)
  386. {
  387. out = f;
  388. found = true;
  389. break;
  390. }
  391. if (kind == SampleKind::int32) // 24 valid bits in a 32-bit container
  392. {
  393. f.wf.Samples.wValidBitsPerSample = 24;
  394. if (c->IsFormatSupported (AUDCLNT_SHAREMODE_EXCLUSIVE, &f.wf.Format, nullptr) == S_OK)
  395. {
  396. out = f;
  397. found = true;
  398. break;
  399. }
  400. }
  401. }
  402. c->Release();
  403. return found;
  404. }
  405. DeviceInfo probeDevice (EDataFlow flow, const std::wstring& id)
  406. {
  407. DeviceInfo info;
  408. IMMDevice* d = openEndpoint (flow, id);
  409. if (d == nullptr)
  410. return info;
  411. info.name = endpointName (d);
  412. IAudioClient* c = nullptr;
  413. if (SUCCEEDED (d->Activate (__uuidof (IAudioClient), CLSCTX_ALL, nullptr, (void**) &c)))
  414. {
  415. WAVEFORMATEX* mix = nullptr;
  416. if (SUCCEEDED (c->GetMixFormat (&mix)))
  417. {
  418. info.ok = true;
  419. info.channels = mix->nChannels;
  420. info.mixRate = mix->nSamplesPerSec;
  421. info.channelMask = maskOf (mix);
  422. REFERENCE_TIME def = 0, mn = 0;
  423. if (SUCCEEDED (c->GetDevicePeriod (&def, &mn)))
  424. {
  425. info.classicPeriod = info.sharedPeriod = refTimeToFrames (def, info.mixRate);
  426. info.exclusiveMinPeriod = refTimeToFrames (mn, info.mixRate);
  427. }
  428. IAudioClient3* c3 = nullptr;
  429. if (SUCCEEDED (c->QueryInterface (__uuidof (IAudioClient3), (void**) &c3)))
  430. {
  431. UINT32 dp = 0, fp = 0, lo = 0, hi = 0;
  432. if (SUCCEEDED (c3->GetSharedModeEnginePeriod (mix, &dp, &fp, &lo, &hi)) && lo > 0)
  433. info.sharedPeriod = (int) lo;
  434. c3->Release();
  435. }
  436. CoTaskMemFree (mix);
  437. }
  438. c->Release();
  439. }
  440. if (info.ok) // exclusive mode: the rates (and the minimum period) of the playback and of the recording device
  441. {
  442. StreamFormat f;
  443. for (auto r : standardRates)
  444. if (exclusiveFormat (d, info.channels, (int) r, info.channelMask, f))
  445. info.exclusiveRates.push_back (r);
  446. if (info.exclusiveRates.empty())
  447. info.exclusiveMinPeriod = 0;
  448. }
  449. d->Release();
  450. return info;
  451. }
  452. //==============================================================================================================
  453. // Interleaved float FIFO (used by the audio thread only)
  454. struct Fifo
  455. {
  456. std::vector<float> data;
  457. int channels = 0, capacity = 0, head = 0, count = 0;
  458. void reset (int ch, int frames)
  459. {
  460. channels = ch;
  461. capacity = std::max (1, frames);
  462. data.assign ((size_t) (capacity * std::max (1, ch)), 0.0f);
  463. head = count = 0;
  464. }
  465. int space() const { return capacity - count; }
  466. void push (const float* src, int frames) // drops the oldest frames on overflow
  467. {
  468. for (int i = 0; i < frames; ++i)
  469. {
  470. if (count == capacity)
  471. {
  472. head = (head + 1) % capacity;
  473. --count;
  474. }
  475. const int at = (head + count) % capacity;
  476. std::memcpy (&data[(size_t) (at * channels)], src + (size_t) i * channels, sizeof (float) * (size_t) channels);
  477. ++count;
  478. }
  479. }
  480. void pushSilence (int frames)
  481. {
  482. std::vector<float> zero ((size_t) (frames * channels), 0.0f);
  483. push (zero.data(), frames);
  484. }
  485. int pop (float* dst, int frames) // returns the frames really taken; the rest of dst is zeroed
  486. {
  487. const int n = std::min (frames, count);
  488. for (int i = 0; i < n; ++i)
  489. {
  490. std::memcpy (dst + (size_t) i * channels, &data[(size_t) (head * channels)], sizeof (float) * (size_t) channels);
  491. head = (head + 1) % capacity;
  492. }
  493. count -= n;
  494. if (n < frames)
  495. std::memset (dst + (size_t) n * channels, 0, sizeof (float) * (size_t) ((frames - n) * channels));
  496. return n;
  497. }
  498. void drop (int frames)
  499. {
  500. const int n = std::min (frames, count);
  501. head = (head + n) % capacity;
  502. count -= n;
  503. }
  504. };
  505. //==============================================================================================================
  506. class LynxAsio;
  507. INT_PTR showPanel (LynxAsio& driver, HWND owner);
  508. class LynxAsio final : public IASIO
  509. {
  510. public:
  511. LynxAsio() { ++liveObjects; }
  512. ~LynxAsio()
  513. {
  514. disposeBuffers();
  515. --liveObjects;
  516. }
  517. // IUnknown --------------------------------------------------------------------------------------------------
  518. HRESULT STDMETHODCALLTYPE QueryInterface (REFIID iid, void** out) override
  519. {
  520. if (out == nullptr)
  521. return E_POINTER;
  522. // ASIO hosts ask for the driver's own CLSID as the interface id
  523. if (IsEqualIID (iid, IID_IUnknown) || IsEqualIID (iid, CLSID_LynxAsio))
  524. {
  525. *out = static_cast<IASIO*> (this);
  526. AddRef();
  527. return S_OK;
  528. }
  529. *out = nullptr;
  530. return E_NOINTERFACE;
  531. }
  532. ULONG STDMETHODCALLTYPE AddRef() override { return (ULONG) ++refs; }
  533. ULONG STDMETHODCALLTYPE Release() override
  534. {
  535. const auto n = --refs;
  536. if (n == 0)
  537. delete this;
  538. return (ULONG) n;
  539. }
  540. // IASIO -----------------------------------------------------------------------------------------------------
  541. ASIOBool init (void* sysHandle) override
  542. {
  543. owner = (HWND) sysHandle;
  544. settings = Settings::load();
  545. probe();
  546. if (! render.ok)
  547. {
  548. setError ("No playback device is available.");
  549. return ASIOFalse;
  550. }
  551. sampleRate = settings.mode == Mode::exclusive && ! render.exclusiveRates.empty()
  552. && std::find (render.exclusiveRates.begin(), render.exclusiveRates.end(), render.mixRate) == render.exclusiveRates.end()
  553. ? render.exclusiveRates.front() : render.mixRate;
  554. initialised = true;
  555. return ASIOTrue;
  556. }
  557. void getDriverName (char* name) override { std::strcpy (name, driverName); }
  558. long getDriverVersion() override { return driverVersion; }
  559. void getErrorMessage (char* text) override { std::strncpy (text, error, 123); text[123] = 0; }
  560. ASIOError start() override
  561. {
  562. if (thread == nullptr)
  563. return ASE_NotPresent;
  564. if (running)
  565. return ASE_OK;
  566. return command (Command::start) ? (running = true, ASE_OK) : ASE_HWMalfunction;
  567. }
  568. ASIOError stop() override
  569. {
  570. if (thread == nullptr)
  571. return ASE_NotPresent;
  572. if (running)
  573. command (Command::stop);
  574. running = false;
  575. return ASE_OK;
  576. }
  577. ASIOError getChannels (long* numIn, long* numOut) override
  578. {
  579. if (! initialised)
  580. return ASE_NotPresent;
  581. *numIn = inputCount();
  582. *numOut = render.channels;
  583. return ASE_OK;
  584. }
  585. ASIOError getLatencies (long* in, long* out) override
  586. {
  587. if (! initialised)
  588. return ASE_NotPresent;
  589. const auto l = latencies (blockSize > 0 ? blockSize : preferredBlock());
  590. *in = l.input;
  591. *out = l.output;
  592. return ASE_OK;
  593. }
  594. ASIOError getBufferSize (long* minSize, long* maxSize, long* preferred, long* granularity) override
  595. {
  596. if (! initialised)
  597. return ASE_NotPresent;
  598. *minSize = exclusiveActive() ? std::max (16, render.exclusiveMinPeriod) : 32;
  599. *maxSize = 4096;
  600. *preferred = preferredBlock();
  601. *granularity = -1; // powers of two (and the preferred size)
  602. return ASE_OK;
  603. }
  604. ASIOError canSampleRate (ASIOSampleRate rate) override
  605. {
  606. if (! initialised)
  607. return ASE_NotPresent;
  608. if (exclusiveActive())
  609. return std::find (render.exclusiveRates.begin(), render.exclusiveRates.end(), rate) != render.exclusiveRates.end() ? ASE_OK : ASE_NoClock;
  610. // shared: Windows converts to the mix rate when it differs
  611. return std::find (std::begin (standardRates), std::end (standardRates), rate) != std::end (standardRates) ? ASE_OK : ASE_NoClock;
  612. }
  613. ASIOError getSampleRate (ASIOSampleRate* rate) override
  614. {
  615. if (! initialised)
  616. return ASE_NotPresent;
  617. *rate = sampleRate;
  618. return ASE_OK;
  619. }
  620. ASIOError setSampleRate (ASIOSampleRate rate) override
  621. {
  622. if (canSampleRate (rate) != ASE_OK)
  623. return ASE_NoClock;
  624. if (rate != sampleRate)
  625. {
  626. sampleRate = rate;
  627. if (callbacks != nullptr) // buffers exist: the host has to rebuild them at the new rate
  628. callbacks->asioMessage (kAsioResetRequest, 0, nullptr, nullptr);
  629. }
  630. return ASE_OK;
  631. }
  632. ASIOError getClockSources (ASIOClockSource* clocks, long* count) override
  633. {
  634. if (clocks == nullptr || count == nullptr || *count < 1)
  635. return ASE_InvalidParameter;
  636. clocks[0].index = 0;
  637. clocks[0].associatedChannel = -1;
  638. clocks[0].associatedGroup = -1;
  639. clocks[0].isCurrentSource = ASIOTrue;
  640. std::strcpy (clocks[0].name, "Internal");
  641. *count = 1;
  642. return ASE_OK;
  643. }
  644. ASIOError setClockSource (long reference) override { return reference == 0 ? ASE_OK : ASE_InvalidParameter; }
  645. ASIOError getSamplePosition (ASIOSamples* pos, ASIOTimeStamp* stamp) override
  646. {
  647. if (thread == nullptr)
  648. return ASE_NotPresent;
  649. const auto frames = (unsigned long long) lastPosition.load();
  650. const auto ns = (unsigned long long) lastSystemNs.load();
  651. pos->hi = (unsigned long) (frames >> 32);
  652. pos->lo = (unsigned long) (frames & 0xffffffffu);
  653. stamp->hi = (unsigned long) (ns >> 32);
  654. stamp->lo = (unsigned long) (ns & 0xffffffffu);
  655. return ASE_OK;
  656. }
  657. ASIOError getChannelInfo (ASIOChannelInfo* info) override
  658. {
  659. if (! initialised)
  660. return ASE_NotPresent;
  661. const long count = info->isInput ? inputCount() : render.channels;
  662. if (info->channel < 0 || info->channel >= count)
  663. return ASE_InvalidParameter;
  664. info->isActive = ASIOFalse;
  665. for (auto& c : channels)
  666. if (c.isInput == (info->isInput != ASIOFalse) && c.index == info->channel)
  667. info->isActive = ASIOTrue;
  668. info->channelGroup = 0;
  669. info->type = ASIOSTFloat32LSB;
  670. const auto& dev = info->isInput ? capture : render;
  671. auto label = narrow (dev.name);
  672. if (label.size() > 20)
  673. label.resize (20);
  674. std::snprintf (info->name, sizeof (info->name), "%s %ld", label.empty() ? (info->isInput ? "In" : "Out") : label.c_str(), info->channel + 1);
  675. return ASE_OK;
  676. }
  677. ASIOError createBuffers (ASIOBufferInfo* infos, long count, long size, ASIOCallbacks* cbs) override
  678. {
  679. if (! initialised)
  680. return ASE_NotPresent;
  681. if (thread != nullptr)
  682. disposeBuffers();
  683. if (infos == nullptr || cbs == nullptr || size < 16 || size > 8192)
  684. return ASE_InvalidMode;
  685. channels.clear();
  686. for (long i = 0; i < count; ++i)
  687. {
  688. const bool isInput = infos[i].isInput != ASIOFalse;
  689. if (infos[i].channelNum < 0 || infos[i].channelNum >= (isInput ? inputCount() : render.channels))
  690. return ASE_InvalidParameter;
  691. channels.push_back ({ isInput, infos[i].channelNum });
  692. }
  693. blockSize = (int) size;
  694. memory.assign ((size_t) (count * 2 * size), 0.0f);
  695. for (long i = 0; i < count; ++i)
  696. {
  697. channels[(size_t) i].buffers[0] = &memory[(size_t) (i * 2 * size)];
  698. channels[(size_t) i].buffers[1] = &memory[(size_t) (i * 2 * size + size)];
  699. infos[i].buffers[0] = channels[(size_t) i].buffers[0];
  700. infos[i].buffers[1] = channels[(size_t) i].buffers[1];
  701. }
  702. callbacks = cbs;
  703. useTimeInfo = callbacks->asioMessage (kAsioSelectorSupported, kAsioSupportsTimeInfo, nullptr, nullptr) == 1
  704. && callbacks->asioMessage (kAsioSupportsTimeInfo, 0, nullptr, nullptr) == 1;
  705. hostKnowsLatencyChanges = callbacks->asioMessage (kAsioSelectorSupported, kAsioLatenciesChanged, nullptr, nullptr) == 1;
  706. // the audio thread opens the devices now (so getLatencies is exact) and waits for start()
  707. wakeEvent = CreateEventW (nullptr, FALSE, FALSE, nullptr);
  708. doneEvent = CreateEventW (nullptr, FALSE, FALSE, nullptr);
  709. thread = CreateThread (nullptr, 0, &audioThreadMain, this, 0, nullptr);
  710. WaitForSingleObject (doneEvent, 10000);
  711. if (! openOk)
  712. {
  713. disposeBuffers();
  714. return ASE_HWMalfunction;
  715. }
  716. return ASE_OK;
  717. }
  718. ASIOError disposeBuffers() override
  719. {
  720. if (thread != nullptr)
  721. {
  722. stop();
  723. command (Command::quit);
  724. WaitForSingleObject (thread, 5000);
  725. CloseHandle (thread);
  726. thread = nullptr;
  727. }
  728. for (auto* h : { &wakeEvent, &doneEvent })
  729. if (*h != nullptr)
  730. {
  731. CloseHandle (*h);
  732. *h = nullptr;
  733. }
  734. callbacks = nullptr;
  735. channels.clear();
  736. memory.clear();
  737. blockSize = 0;
  738. deviceQueue = 0;
  739. return ASE_OK;
  740. }
  741. ASIOError controlPanel() override
  742. {
  743. const auto before = settings;
  744. showPanel (*this, owner);
  745. if (! (settings == before))
  746. {
  747. settings.save();
  748. probe();
  749. if (callbacks != nullptr)
  750. callbacks->asioMessage (kAsioResetRequest, 0, nullptr, nullptr);
  751. }
  752. return ASE_OK;
  753. }
  754. ASIOError future (long selector, void*) override
  755. {
  756. switch (selector)
  757. {
  758. case kAsioCanTimeInfo:
  759. return ASE_SUCCESS;
  760. default:
  761. return ASE_NotPresent;
  762. }
  763. }
  764. ASIOError outputReady() override { return ASE_NotPresent; }
  765. // for the panel ----------------------------------------------------------------------------------------------
  766. Settings settings;
  767. DeviceInfo render, capture;
  768. void probe()
  769. {
  770. auto work = [this]
  771. {
  772. render = probeDevice (eRender, settings.output);
  773. capture = settings.input == L"-" ? DeviceInfo {} : probeDevice (eCapture, settings.input);
  774. };
  775. onMtaThread (work);
  776. }
  777. int preferredBlock() const
  778. {
  779. if (settings.bufferSize > 0)
  780. return exclusiveActive() ? std::max (settings.bufferSize, render.exclusiveMinPeriod) : settings.bufferSize;
  781. if (exclusiveActive())
  782. return std::max (render.exclusiveMinPeriod, 128);
  783. return std::max (32, render.sharedPeriod);
  784. }
  785. int sharedTarget (int period) const { return period + (settings.safety == 0 ? 0 : settings.safety == 1 ? period / 2 : period); }
  786. // The input FIFO's level after a host block (frames). The recorded packets (`capture` frames) and the playback
  787. // bursts (whole blocks covering one device period) come at unrelated moments; just before a burst the FIFO must
  788. // still hold the whole burst plus the interpolator's look-ahead, whatever the phase between the two. Worst case:
  789. // target + (burst + block) / 2 - capture >= burst + look-ahead, plus a margin for late packets that follows the
  790. // safety setting. Measured (round 106, USB codec): packets of a 6 ms exclusive stream came up to 11.8 ms apart,
  791. // of the 10 ms shared stream up to 16.6 ms apart, so "normal" allows one period (at least 6 ms) of lateness.
  792. // A device that is later still raises the target once (InputDrift, at most 2x).
  793. int inputTargetFor (int capturePacket, int period, int block) const
  794. {
  795. const int b = std::max (1, block);
  796. const int burst = (std::max (period, b) + b - 1) / b * b;
  797. const int p = std::max (capturePacket, burst);
  798. const double ms = sampleRate / 1000.0;
  799. const int late = settings.safety == 0 ? std::max (p / 4, (int) (2 * ms))
  800. : settings.safety == 1 ? std::max (p / 2, (int) (4 * ms))
  801. : std::max (p, (int) (6 * ms));
  802. return capturePacket + burst / 2 - b / 2 + lynxasio::InputDrift::half + 32 + late;
  803. }
  804. // Exclusive recording period: the playback period, but not below twice the device's minimum. Measured on a USB
  805. // class-driver codec (REA round 106): at its 3 ms minimum the capture events arrive up to 8 ms apart now and
  806. // then and the device drops a packet each time (about one per second); from 6 ms on there were none.
  807. int exclusiveCapturePeriod (int playbackPeriod) const { return std::max (playbackPeriod, 2 * capture.exclusiveMinPeriod); }
  808. struct Latencies
  809. {
  810. int block = 0, input = 0, output = 0, period = 0, capturePeriod = 0;
  811. bool open = false, exclusive = false, captureExclusive = false, hasInput = false;
  812. };
  813. // ASIO latencies for `block`: of the open stream when there is one, else what the settings would give.
  814. // Output: what is queued ahead of the device (the shared target or the exclusive period) plus the block waiting
  815. // in the FIFO. Input: the FIFO level when the host reads a block (target + block), plus half a capture packet
  816. // (the average age of the newest frame) and the interpolator's look-ahead.
  817. Latencies latencies (int block, bool ofOpenStream = true) const
  818. {
  819. Latencies l;
  820. l.block = block;
  821. if (ofOpenStream && thread != nullptr && openOk)
  822. {
  823. l.open = true;
  824. l.exclusive = streamExclusive;
  825. l.period = devicePeriod;
  826. l.output = deviceQueue + blockSize;
  827. l.block = blockSize;
  828. l.hasInput = captureService != nullptr;
  829. if (l.hasInput)
  830. {
  831. l.captureExclusive = captureExclusive;
  832. l.capturePeriod = capturePeriod;
  833. l.input = std::max (inputTarget, inFifo.target()) + blockSize + capturePeriod / 2 + lynxasio::InputDrift::half;
  834. }
  835. return l;
  836. }
  837. l.exclusive = exclusiveActive();
  838. l.period = l.exclusive ? std::max (block, render.exclusiveMinPeriod) : render.sharedPeriod;
  839. l.output = (l.exclusive ? l.period : sharedTarget (l.period)) + block;
  840. l.hasInput = capture.ok;
  841. if (capture.ok)
  842. {
  843. l.captureExclusive = l.exclusive && capture.exclusiveMinPeriod > 0;
  844. l.capturePeriod = l.captureExclusive ? exclusiveCapturePeriod (l.period) : capture.sharedPeriod;
  845. l.input = inputTargetFor (l.capturePeriod, l.period, block) + block + l.capturePeriod / 2 + lynxasio::InputDrift::half;
  846. }
  847. return l;
  848. }
  849. bool exclusiveActive() const { return settings.mode == Mode::exclusive && render.exclusiveMinPeriod > 0; }
  850. private:
  851. enum class Command
  852. {
  853. none,
  854. start,
  855. stop,
  856. quit
  857. };
  858. struct Channel
  859. {
  860. bool isInput = false;
  861. long index = 0;
  862. float* buffers[2] { nullptr, nullptr };
  863. };
  864. long inputCount() const { return capture.ok ? capture.channels : 0; }
  865. void setError (const char* text)
  866. {
  867. std::strncpy (error, text, sizeof (error) - 1);
  868. logLine ("error: %s", text);
  869. }
  870. bool command (Command c)
  871. {
  872. pending = c;
  873. commandOk = false;
  874. SetEvent (wakeEvent);
  875. return WaitForSingleObject (doneEvent, 5000) == WAIT_OBJECT_0 && commandOk;
  876. }
  877. // ---------------------------------------------------------------------------------------------------------
  878. // Audio thread: opens the clients, then serves start/stop/quit and the device events.
  879. IAudioClient* renderClient = nullptr;
  880. IAudioRenderClient* renderService = nullptr;
  881. IAudioClient* captureClient = nullptr;
  882. IAudioCaptureClient* captureService = nullptr;
  883. HANDLE renderEvent = nullptr, captureEvent = nullptr;
  884. StreamFormat renderFormat, captureFormat;
  885. UINT32 renderFrames = 0; // the render buffer
  886. int devicePeriod = 0; // frames between two device events
  887. Fifo outFifo;
  888. lynxasio::InputDrift inFifo; // captured frames -> host blocks, following the capture clock
  889. std::vector<float> scratch, blockIn, blockOut;
  890. int bufferIndex = 0;
  891. long long position = 0;
  892. // statistics (LYNX_ASIO_LOG)
  893. long long events = 0, hostBlocks = 0, lateEvents = 0, slowBursts = 0, captureEvents = 0, captureGaps = 0;
  894. long long inputShortBefore = 0;
  895. double startMs = 0.0, lastEventMs = 0.0, maxGapMs = 0.0, maxBurstMs = 0.0;
  896. struct TracePoint
  897. {
  898. float level, ppm;
  899. int underflows, gaps;
  900. };
  901. TracePoint trace[240] {}; // input state once per second (first 4 minutes), written to the log at stop
  902. int traced = 0;
  903. struct GapNote
  904. {
  905. float atMs, sinceDrainMs;
  906. int frames, packetIndex;
  907. };
  908. GapNote gapNotes[8] {};
  909. double lastDrainMs = 0.0, maxCaptureGapMs = 0.0;
  910. long long nextCapturePosition = -1, lostFrames = 0;
  911. int settledSteps = 0;
  912. int packetsThisDrain = 0;
  913. // Opens an exclusive event-driven stream of `period` frames (re-initialised with the aligned size when the
  914. // device asks for it). Returns the HRESULT.
  915. static HRESULT initExclusive (IMMDevice* d, IAudioClient*& client, const StreamFormat& format, int period, double rate)
  916. {
  917. auto t = framesToRefTime (period, rate);
  918. HRESULT hr = client->Initialize (AUDCLNT_SHAREMODE_EXCLUSIVE, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, t, t, &format.wf.Format, nullptr);
  919. if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED)
  920. {
  921. UINT32 aligned = 0;
  922. client->GetBufferSize (&aligned);
  923. releaseCom (client);
  924. if (FAILED (d->Activate (__uuidof (IAudioClient), CLSCTX_ALL, nullptr, (void**) &client)))
  925. return E_FAIL;
  926. t = framesToRefTime ((int) aligned, rate);
  927. hr = client->Initialize (AUDCLNT_SHAREMODE_EXCLUSIVE, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, t, t, &format.wf.Format, nullptr);
  928. }
  929. return hr;
  930. }
  931. // Shared event-driven stream; the IAudioClient3 low-latency period when the device has one shorter than its
  932. // default and no rate conversion is needed. Returns the period in frames (0 = failed).
  933. static int initShared (IAudioClient* client, const StreamFormat& format, double rate, double mixRate, REFERENCE_TIME buffer)
  934. {
  935. const bool atMixRate = rate == mixRate;
  936. IAudioClient3* c3 = nullptr;
  937. int period = 0;
  938. if (atMixRate && SUCCEEDED (client->QueryInterface (__uuidof (IAudioClient3), (void**) &c3)))
  939. {
  940. UINT32 dp = 0, fp = 0, lo = 0, hi = 0;
  941. if (SUCCEEDED (c3->GetSharedModeEnginePeriod (&format.wf.Format, &dp, &fp, &lo, &hi)) && lo > 0 && lo < dp
  942. && SUCCEEDED (c3->InitializeSharedAudioStream (AUDCLNT_STREAMFLAGS_EVENTCALLBACK, lo, &format.wf.Format, nullptr)))
  943. period = (int) lo;
  944. c3->Release();
  945. }
  946. if (period == 0) // the classic shared stream (also converts other rates to the mix rate)
  947. {
  948. DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  949. if (! atMixRate)
  950. flags |= AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
  951. if (FAILED (client->Initialize (AUDCLNT_SHAREMODE_SHARED, flags, buffer, 0, &format.wf.Format, nullptr)))
  952. return 0;
  953. REFERENCE_TIME def = 0, mn = 0;
  954. client->GetDevicePeriod (&def, &mn);
  955. period = std::max (16, refTimeToFrames (def, rate));
  956. }
  957. return period;
  958. }
  959. bool openRender (IMMDevice* d)
  960. {
  961. const bool exclusive = streamExclusive = exclusiveActive(); // fixed for this stream (the panel may change the settings)
  962. devicePeriod = 0;
  963. renderFrames = 0;
  964. if (FAILED (d->Activate (__uuidof (IAudioClient), CLSCTX_ALL, nullptr, (void**) &renderClient)))
  965. return setError ("Could not open the playback device."), false;
  966. if (exclusive)
  967. {
  968. if (! exclusiveFormat (d, render.channels, (int) sampleRate, render.channelMask, renderFormat))
  969. return setError ("The playback device takes no exclusive format at this sample rate."), false;
  970. const HRESULT hr = initExclusive (d, renderClient, renderFormat, std::max (blockSize, render.exclusiveMinPeriod), sampleRate);
  971. if (hr == AUDCLNT_E_DEVICE_IN_USE)
  972. return setError ("Another program is using the playback device in exclusive mode."), false;
  973. if (FAILED (hr))
  974. return setError ("The playback device refused exclusive mode."), false;
  975. renderClient->GetBufferSize (&renderFrames);
  976. devicePeriod = (int) renderFrames;
  977. }
  978. else
  979. {
  980. renderFormat = makeFormat (render.channels, (int) sampleRate, SampleKind::float32, render.channelMask);
  981. devicePeriod = initShared (renderClient, renderFormat, sampleRate, render.mixRate, 0);
  982. if (devicePeriod == 0)
  983. return setError ("The playback device refused the shared stream."), false;
  984. renderClient->GetBufferSize (&renderFrames);
  985. }
  986. renderEvent = CreateEventW (nullptr, FALSE, FALSE, nullptr);
  987. renderClient->SetEventHandle (renderEvent);
  988. if (FAILED (renderClient->GetService (__uuidof (IAudioRenderClient), (void**) &renderService)))
  989. return setError ("The playback device has no render service."), false;
  990. deviceQueue = exclusive ? (int) renderFrames : std::min ((int) renderFrames, sharedTarget (devicePeriod));
  991. REFERENCE_TIME lat = 0;
  992. renderClient->GetStreamLatency (&lat);
  993. renderLatency = refTimeToFrames (lat, sampleRate);
  994. logLine ("render: %s mode, %s %d ch @ %.0f Hz, period %d, buffer %u, queue %d, stream latency %d, ASIO block %d",
  995. exclusive ? "exclusive" : "shared", kindName (renderFormat.kind), renderFormat.channels, sampleRate, devicePeriod,
  996. renderFrames, deviceQueue, renderLatency, blockSize);
  997. return true;
  998. }
  999. // The recording stream: exclusive (event-driven, same period as the playback when the device allows it) when
  1000. // LYNX ASIO runs exclusive, else shared. Either way it has its own event and clock; InputDrift follows it.
  1001. void openCapture()
  1002. {
  1003. captureExclusive = false;
  1004. capturePeriod = 0;
  1005. if (! capture.ok)
  1006. return;
  1007. IMMDevice* d = openEndpoint (eCapture, settings.input);
  1008. if (d == nullptr)
  1009. return;
  1010. if (streamExclusive && capture.exclusiveMinPeriod > 0
  1011. && exclusiveFormat (d, capture.channels, (int) sampleRate, capture.channelMask, captureFormat)
  1012. && SUCCEEDED (d->Activate (__uuidof (IAudioClient), CLSCTX_ALL, nullptr, (void**) &captureClient)))
  1013. {
  1014. const HRESULT hr = initExclusive (d, captureClient, captureFormat, exclusiveCapturePeriod (devicePeriod), sampleRate);
  1015. UINT32 frames = 0;
  1016. if (SUCCEEDED (hr) && SUCCEEDED (captureClient->GetBufferSize (&frames)))
  1017. {
  1018. captureExclusive = true;
  1019. capturePeriod = (int) frames;
  1020. }
  1021. else
  1022. {
  1023. logLine ("capture: exclusive refused (0x%08lx), using the shared stream", (unsigned long) hr);
  1024. releaseCom (captureClient);
  1025. }
  1026. }
  1027. if (! captureExclusive && SUCCEEDED (d->Activate (__uuidof (IAudioClient), CLSCTX_ALL, nullptr, (void**) &captureClient)))
  1028. {
  1029. captureFormat = makeFormat (capture.channels, (int) sampleRate, SampleKind::float32, capture.channelMask);
  1030. capturePeriod = initShared (captureClient, captureFormat, sampleRate, capture.mixRate, 1000000); // 100 ms of slack
  1031. if (capturePeriod == 0)
  1032. releaseCom (captureClient);
  1033. }
  1034. if (captureClient != nullptr)
  1035. {
  1036. captureEvent = CreateEventW (nullptr, FALSE, FALSE, nullptr);
  1037. if (FAILED (captureClient->SetEventHandle (captureEvent))
  1038. || FAILED (captureClient->GetService (__uuidof (IAudioCaptureClient), (void**) &captureService)))
  1039. {
  1040. releaseCom (captureService);
  1041. releaseCom (captureClient);
  1042. CloseHandle (captureEvent);
  1043. captureEvent = nullptr;
  1044. }
  1045. }
  1046. if (captureClient != nullptr)
  1047. {
  1048. REFERENCE_TIME lat = 0;
  1049. captureClient->GetStreamLatency (&lat);
  1050. captureLatency = refTimeToFrames (lat, sampleRate);
  1051. inputTarget = inputTargetFor (capturePeriod, devicePeriod, blockSize);
  1052. logLine ("capture: %s mode, %s %d ch @ %.0f Hz, period %d, stream latency %d, FIFO target %d",
  1053. captureExclusive ? "exclusive" : "shared", kindName (captureFormat.kind), captureFormat.channels, sampleRate,
  1054. capturePeriod, captureLatency, inputTarget);
  1055. }
  1056. else
  1057. logLine ("capture: could not open \"%s\"", narrow (capture.name).c_str());
  1058. d->Release();
  1059. }
  1060. void closeDevices()
  1061. {
  1062. if (renderClient != nullptr)
  1063. renderClient->Stop();
  1064. if (captureClient != nullptr)
  1065. captureClient->Stop();
  1066. releaseCom (renderService);
  1067. releaseCom (renderClient);
  1068. releaseCom (captureService);
  1069. releaseCom (captureClient);
  1070. for (auto* h : { &renderEvent, &captureEvent })
  1071. if (*h != nullptr)
  1072. {
  1073. CloseHandle (*h);
  1074. *h = nullptr;
  1075. }
  1076. }
  1077. // Moves every captured packet into the input FIFO (stamped with the time it was taken).
  1078. void drainCapture()
  1079. {
  1080. if (captureService == nullptr)
  1081. return;
  1082. packetsThisDrain = 0;
  1083. for (;;)
  1084. {
  1085. UINT32 packet = 0;
  1086. const HRESULT hr = captureService->GetNextPacketSize (&packet);
  1087. if (FAILED (hr))
  1088. {
  1089. if (hr == AUDCLNT_E_DEVICE_INVALIDATED)
  1090. deviceLost = true;
  1091. break;
  1092. }
  1093. if (packet == 0)
  1094. break;
  1095. BYTE* data = nullptr;
  1096. UINT32 frames = 0;
  1097. DWORD flags = 0;
  1098. UINT64 devicePosition = 0, captureTime = 0;
  1099. if (FAILED (captureService->GetBuffer (&data, &frames, &flags, &devicePosition, &captureTime)))
  1100. break;
  1101. // Frames the device lost (it was late, or we were) are replaced by silence of the same length, so the
  1102. // recording stays in time with the playback; the device position says how many.
  1103. if (nextCapturePosition >= 0 && (long long) devicePosition > nextCapturePosition)
  1104. {
  1105. const auto lost = (long long) devicePosition - nextCapturePosition;
  1106. if (lost < (long long) sampleRate) // not a reset of the position
  1107. {
  1108. inFifo.pushSilence ((int) lost);
  1109. lostFrames += lost;
  1110. }
  1111. }
  1112. nextCapturePosition = (long long) devicePosition + frames;
  1113. scratch.resize ((size_t) frames * (size_t) captureFormat.channels);
  1114. if ((flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0)
  1115. std::fill (scratch.begin(), scratch.end(), 0.0f);
  1116. else
  1117. readSamples (data, scratch.data(), (int) frames * captureFormat.channels, captureFormat.kind);
  1118. if ((flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0 && now() - startMs > 200.0)
  1119. {
  1120. ++captureGaps; // we were too late and the device dropped frames
  1121. if (captureGaps <= 8)
  1122. gapNotes[captureGaps - 1] = { (float) (now() - startMs), (float) (now() - lastDrainMs), (int) frames, (int) packetsThisDrain };
  1123. }
  1124. ++packetsThisDrain;
  1125. if (traced < 240 && now() - startMs >= 1000.0 * (traced + 1))
  1126. trace[traced++] = { (float) inFifo.averageFill(), (float) ((inFifo.ratio() - 1.0) * 1.0e6), (int) inFifo.underflows, (int) captureGaps };
  1127. // stamped with when its last frame was recorded (the capture time is in 100 ns units of the
  1128. // performance counter), so the level estimate does not move with the delivery jitter
  1129. const double recorded = captureTime != 0 ? captureTime * 1.0e-7 + frames / sampleRate : now() / 1000.0;
  1130. inFifo.push (scratch.data(), (int) frames, recorded);
  1131. captureService->ReleaseBuffer (frames);
  1132. }
  1133. if (packetsThisDrain > 0)
  1134. {
  1135. const double t = now();
  1136. if (lastDrainMs > 0.0 && t - startMs > 500.0)
  1137. maxCaptureGapMs = std::max (maxCaptureGapMs, t - lastDrainMs);
  1138. lastDrainMs = t;
  1139. }
  1140. }
  1141. static double now() { return nowMs(); }
  1142. // One host block: input FIFO -> ASIO input buffers, bufferSwitch, ASIO output buffers -> output FIFO.
  1143. void runHostBlock()
  1144. {
  1145. const int b = blockSize;
  1146. if (captureService != nullptr)
  1147. {
  1148. // devices deliver irregularly while they start: the level is set to the target at 0.3 s and once more
  1149. // at 1.5 s (before anyone records), then only the drift control moves it
  1150. if (settledSteps < 2 && now() - startMs > (settledSteps == 0 ? 300.0 : 1500.0))
  1151. {
  1152. ++settledSteps;
  1153. inFifo.recenter (now() / 1000.0);
  1154. }
  1155. const int raises = inFifo.raises();
  1156. inFifo.pull (blockIn.data(), b, now() / 1000.0);
  1157. if (inFifo.raises() != raises && hostKnowsLatencyChanges) // the input latency grew: hosts that can re-read it
  1158. callbacks->asioMessage (kAsioLatenciesChanged, 0, nullptr, nullptr);
  1159. const int stride = inFifo.numChannels();
  1160. for (auto& c : channels)
  1161. if (c.isInput)
  1162. {
  1163. float* dst = c.buffers[bufferIndex];
  1164. for (int i = 0; i < b; ++i)
  1165. dst[i] = blockIn[(size_t) (i * stride + c.index)];
  1166. }
  1167. }
  1168. else
  1169. for (auto& c : channels)
  1170. if (c.isInput)
  1171. std::fill (c.buffers[bufferIndex], c.buffers[bufferIndex] + b, 0.0f);
  1172. lastPosition = position;
  1173. lastSystemNs = (long long) (nowMs() * 1.0e6);
  1174. if (useTimeInfo)
  1175. {
  1176. ASIOTime t {};
  1177. t.timeInfo.speed = 1.0;
  1178. t.timeInfo.systemTime.hi = (unsigned long) ((unsigned long long) lastSystemNs.load() >> 32);
  1179. t.timeInfo.systemTime.lo = (unsigned long) ((unsigned long long) lastSystemNs.load() & 0xffffffffu);
  1180. t.timeInfo.samplePosition.hi = (unsigned long) ((unsigned long long) position >> 32);
  1181. t.timeInfo.samplePosition.lo = (unsigned long) ((unsigned long long) position & 0xffffffffu);
  1182. t.timeInfo.sampleRate = sampleRate;
  1183. t.timeInfo.flags = kSystemTimeValid | kSamplePositionValid | kSampleRateValid | kSpeedValid;
  1184. callbacks->bufferSwitchTimeInfo (&t, bufferIndex, ASIOTrue);
  1185. }
  1186. else
  1187. callbacks->bufferSwitch (bufferIndex, ASIOTrue);
  1188. const int stride = renderFormat.channels;
  1189. std::fill (blockOut.begin(), blockOut.end(), 0.0f);
  1190. for (auto& c : channels)
  1191. if (! c.isInput)
  1192. {
  1193. const float* src = c.buffers[bufferIndex];
  1194. for (int i = 0; i < b; ++i)
  1195. blockOut[(size_t) (i * stride + c.index)] = src[i];
  1196. }
  1197. outFifo.push (blockOut.data(), b);
  1198. position += b;
  1199. bufferIndex ^= 1;
  1200. ++hostBlocks;
  1201. }
  1202. // Writes `frames` frames from the output FIFO (host blocks run until it holds enough) into the device.
  1203. void feedDevice (int frames)
  1204. {
  1205. if (frames <= 0)
  1206. return;
  1207. const double t0 = nowMs();
  1208. while (outFifo.count < frames)
  1209. {
  1210. runHostBlock();
  1211. drainCapture(); // a long burst must not let the recording buffer overflow
  1212. }
  1213. const double used = nowMs() - t0;
  1214. maxBurstMs = std::max (maxBurstMs, used);
  1215. if (used > 1000.0 * devicePeriod / sampleRate)
  1216. ++slowBursts;
  1217. BYTE* data = nullptr;
  1218. if (FAILED (renderService->GetBuffer ((UINT32) frames, &data)))
  1219. return;
  1220. scratch.resize ((size_t) (frames * renderFormat.channels));
  1221. outFifo.pop (scratch.data(), frames);
  1222. writeSamples (scratch.data(), data, frames * renderFormat.channels, renderFormat.kind);
  1223. renderService->ReleaseBuffer ((UINT32) frames, 0);
  1224. }
  1225. void prime()
  1226. {
  1227. const int ch = renderFormat.channels;
  1228. outFifo.reset (ch, (int) renderFrames + 2 * blockSize + 64);
  1229. if (captureClient != nullptr) // starts at its target level (silence), then follows the capture clock
  1230. inFifo.reset (captureFormat.channels, inputTarget, sampleRate);
  1231. blockIn.assign ((size_t) (blockSize * std::max (1, captureFormat.channels)), 0.0f);
  1232. blockOut.assign ((size_t) (blockSize * ch), 0.0f);
  1233. // the first buffer: silence, so the stream starts without a gap
  1234. BYTE* data = nullptr;
  1235. const int first = streamExclusive ? (int) renderFrames : deviceQueue;
  1236. if (SUCCEEDED (renderService->GetBuffer ((UINT32) first, &data)))
  1237. renderService->ReleaseBuffer ((UINT32) first, AUDCLNT_BUFFERFLAGS_SILENT);
  1238. bufferIndex = 0;
  1239. events = hostBlocks = lateEvents = inputShortBefore = slowBursts = captureEvents = captureGaps = 0;
  1240. traced = 0;
  1241. settledSteps = 0;
  1242. lastDrainMs = maxCaptureGapMs = 0.0;
  1243. nextCapturePosition = -1;
  1244. lostFrames = 0;
  1245. lastEventMs = maxGapMs = maxBurstMs = 0.0;
  1246. startMs = nowMs();
  1247. }
  1248. void onDeviceEvent()
  1249. {
  1250. const double t = nowMs();
  1251. if (lastEventMs > 0.0 && t - startMs > 200.0) // the device's first periods are irregular: not counted
  1252. {
  1253. const double gap = t - lastEventMs;
  1254. maxGapMs = std::max (maxGapMs, gap);
  1255. if (gap > 1.5 * 1000.0 * devicePeriod / sampleRate + 1.0)
  1256. ++lateEvents;
  1257. }
  1258. lastEventMs = t;
  1259. ++events;
  1260. if (t - startMs < 200.0)
  1261. inputShortBefore = inFifo.underflows;
  1262. drainCapture();
  1263. if (streamExclusive)
  1264. feedDevice ((int) renderFrames);
  1265. else
  1266. {
  1267. UINT32 padding = 0;
  1268. if (FAILED (renderClient->GetCurrentPadding (&padding)))
  1269. {
  1270. deviceLost = true;
  1271. return;
  1272. }
  1273. feedDevice (deviceQueue - (int) padding);
  1274. }
  1275. }
  1276. void logStats()
  1277. {
  1278. logLine ("stats: %lld device events, %lld host blocks, late events %lld (max gap %.2f ms), slow bursts %lld (max %.2f ms)",
  1279. events, hostBlocks, lateEvents, maxGapMs, slowBursts, maxBurstMs);
  1280. if (captureClient != nullptr)
  1281. logLine ("input: %lld capture events, FIFO level %.0f (target %d, now %d), clock ratio %+.1f ppm (range %+.1f..%+.1f), "
  1282. "underflows %lld (+%lld while starting), overflows %lld, device gaps %lld (%lld frames replaced), longest wait for a packet %.2f ms",
  1283. captureEvents, inFifo.averageFill(), inputTarget, inFifo.target(), (inFifo.ratio() - 1.0) * 1.0e6, (inFifo.minRatio - 1.0) * 1.0e6,
  1284. (inFifo.maxRatio - 1.0) * 1.0e6, (long long) inFifo.underflows - inputShortBefore, inputShortBefore,
  1285. (long long) inFifo.overflows, captureGaps, lostFrames, maxCaptureGapMs);
  1286. if (captureClient != nullptr && traced > 0)
  1287. {
  1288. std::string line = "input per second (level/ppm/underflows/gaps):";
  1289. for (int i = 0; i < traced; ++i)
  1290. {
  1291. char t[64];
  1292. std::snprintf (t, sizeof (t), " %.0f/%+.0f/%d/%d", trace[i].level, trace[i].ppm, trace[i].underflows, trace[i].gaps);
  1293. line += t;
  1294. }
  1295. logLine ("%s", line.substr (0, 1000).c_str());
  1296. }
  1297. for (int i = 0; i < (int) std::min<long long> (8, captureGaps); ++i)
  1298. logLine ("gap %d at %.1f ms: %.2f ms since the last packet, %d frames, packet %d of its drain", i, gapNotes[i].atMs,
  1299. gapNotes[i].sinceDrainMs, gapNotes[i].frames, gapNotes[i].packetIndex);
  1300. }
  1301. static DWORD WINAPI audioThreadMain (LPVOID self)
  1302. {
  1303. ((LynxAsio*) self)->audioThread();
  1304. return 0;
  1305. }
  1306. void audioThread()
  1307. {
  1308. const auto com = CoInitializeEx (nullptr, COINIT_MULTITHREADED);
  1309. DWORD taskIndex = 0;
  1310. HANDLE task = nullptr;
  1311. openOk = false;
  1312. if (IMMDevice* d = openEndpoint (eRender, settings.output))
  1313. {
  1314. openOk = openRender (d);
  1315. d->Release();
  1316. }
  1317. else
  1318. setError ("The playback device is not available.");
  1319. if (openOk)
  1320. openCapture();
  1321. SetEvent (doneEvent);
  1322. bool streaming = false;
  1323. for (;;)
  1324. {
  1325. // the capture event comes first: when both are signalled, the recorded packet is taken before the block
  1326. HANDLE waits[3] = { wakeEvent, captureEvent != nullptr ? captureEvent : renderEvent, renderEvent };
  1327. const DWORD n = ! streaming ? 1 : captureEvent != nullptr ? 3 : 2;
  1328. const DWORD r = WaitForMultipleObjects (n, waits, FALSE, streaming ? 2000 : INFINITE);
  1329. if (r == WAIT_OBJECT_0)
  1330. {
  1331. const auto c = pending.exchange (Command::none);
  1332. if (c == Command::start && openOk && ! streaming)
  1333. {
  1334. task = AvSetMmThreadCharacteristicsW (L"Pro Audio", &taskIndex);
  1335. if (task != nullptr)
  1336. AvSetMmThreadPriority (task, AVRT_PRIORITY_CRITICAL);
  1337. prime();
  1338. if (captureClient != nullptr)
  1339. captureClient->Start();
  1340. streaming = SUCCEEDED (renderClient->Start());
  1341. commandOk = streaming;
  1342. }
  1343. else if (c == Command::stop || c == Command::quit)
  1344. {
  1345. if (streaming)
  1346. {
  1347. renderClient->Stop();
  1348. renderClient->Reset(); // a later start begins with an empty queue
  1349. if (captureClient != nullptr)
  1350. {
  1351. captureClient->Stop();
  1352. captureClient->Reset();
  1353. }
  1354. logStats();
  1355. if (task != nullptr)
  1356. AvRevertMmThreadCharacteristics (task);
  1357. task = nullptr;
  1358. }
  1359. streaming = false;
  1360. commandOk = true;
  1361. if (c == Command::quit)
  1362. {
  1363. closeDevices();
  1364. SetEvent (doneEvent);
  1365. break;
  1366. }
  1367. }
  1368. else
  1369. commandOk = c != Command::start || streaming;
  1370. SetEvent (doneEvent);
  1371. }
  1372. else if (r == WAIT_OBJECT_0 + 1 && n == 3)
  1373. {
  1374. ++captureEvents;
  1375. drainCapture();
  1376. }
  1377. else if (r == WAIT_OBJECT_0 + 1 || r == WAIT_OBJECT_0 + 2)
  1378. onDeviceEvent();
  1379. else if (r == WAIT_TIMEOUT && streaming)
  1380. {
  1381. ++lateEvents; // the device stopped calling (unplugged, sleep): ask the host to reopen
  1382. if (callbacks != nullptr)
  1383. callbacks->asioMessage (kAsioResetRequest, 0, nullptr, nullptr);
  1384. }
  1385. if (deviceLost)
  1386. {
  1387. deviceLost = false;
  1388. if (callbacks != nullptr)
  1389. callbacks->asioMessage (kAsioResetRequest, 0, nullptr, nullptr);
  1390. }
  1391. }
  1392. if (SUCCEEDED (com))
  1393. CoUninitialize();
  1394. }
  1395. std::atomic<long> refs { 1 };
  1396. HWND owner = nullptr;
  1397. char error[128] = "";
  1398. bool initialised = false;
  1399. double sampleRate = 48000.0;
  1400. ASIOCallbacks* callbacks = nullptr;
  1401. bool useTimeInfo = false, hostKnowsLatencyChanges = false;
  1402. std::vector<Channel> channels;
  1403. std::vector<float> memory;
  1404. int blockSize = 0;
  1405. int deviceQueue = 0;
  1406. int capturePeriod = 0, inputTarget = 0, renderLatency = 0, captureLatency = 0;
  1407. bool captureExclusive = false;
  1408. HANDLE thread = nullptr, wakeEvent = nullptr, doneEvent = nullptr;
  1409. std::atomic<Command> pending { Command::none };
  1410. std::atomic<bool> commandOk { false };
  1411. bool openOk = false, running = false, deviceLost = false, streamExclusive = false;
  1412. std::atomic<long long> lastPosition { 0 }, lastSystemNs { 0 };
  1413. };
  1414. //==============================================================================================================
  1415. // Control panel: a small window built in code (mode, devices, buffer, safety margin)
  1416. enum
  1417. {
  1418. idMode = 101,
  1419. idOutput,
  1420. idInput,
  1421. idBuffer,
  1422. idSafety,
  1423. idInfo,
  1424. idLatency,
  1425. idOk,
  1426. idCancel
  1427. };
  1428. struct Panel
  1429. {
  1430. LynxAsio& driver;
  1431. Settings edit;
  1432. std::vector<Endpoint> outputs, inputs;
  1433. HWND window = nullptr;
  1434. bool done = false, accepted = false;
  1435. HFONT font = nullptr;
  1436. HWND item (int id) const { return GetDlgItem (window, id); }
  1437. static void addString (HWND combo, const std::wstring& s) { SendMessageW (combo, CB_ADDSTRING, 0, (LPARAM) s.c_str()); }
  1438. void fillBuffers()
  1439. {
  1440. HWND b = item (idBuffer);
  1441. SendMessageW (b, CB_RESETCONTENT, 0, 0);
  1442. addString (b, tr (L"Automatic", L"Automático"));
  1443. const double rate = driver.render.mixRate > 0 ? driver.render.mixRate : 48000.0;
  1444. const bool exclusive = edit.mode == Mode::exclusive && driver.render.exclusiveMinPeriod > 0;
  1445. std::vector<int> sizes;
  1446. if (exclusive)
  1447. sizes.push_back (driver.render.exclusiveMinPeriod);
  1448. for (int s : { 32, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 2048 })
  1449. if (! exclusive || s > driver.render.exclusiveMinPeriod)
  1450. sizes.push_back (s);
  1451. int selected = 0;
  1452. for (size_t i = 0; i < sizes.size(); ++i)
  1453. {
  1454. wchar_t text[64];
  1455. swprintf (text, 64, tr (L"%d samples (%.1f ms)", L"%d amostras (%.1f ms)"), sizes[i], 1000.0 * sizes[i] / rate);
  1456. addString (b, text);
  1457. SendMessageW (b, CB_SETITEMDATA, i + 1, (LPARAM) sizes[i]);
  1458. if (sizes[i] == edit.bufferSize)
  1459. selected = (int) i + 1;
  1460. }
  1461. SendMessageW (b, CB_SETCURSEL, (WPARAM) selected, 0);
  1462. }
  1463. void updateInfo()
  1464. {
  1465. const auto& r = driver.render;
  1466. const double rate = r.mixRate > 0 ? r.mixRate : 48000.0;
  1467. wchar_t text[600];
  1468. if (! r.ok)
  1469. swprintf (text, 600, L"%ls", tr (L"No playback device is available.", L"Nenhum dispositivo de reprodução disponível."));
  1470. else if (edit.mode == Mode::exclusive)
  1471. {
  1472. if (r.exclusiveMinPeriod > 0)
  1473. swprintf (text, 600, tr (L"Exclusive: LYNX ASIO uses \"%ls\" alone (other programs go silent; the input device too, when it accepts exclusive mode). Shortest period on this device: %d samples (%.1f ms).",
  1474. L"Exclusivo: o LYNX ASIO usa \"%ls\" sozinho (os outros programas ficam mudos; o dispositivo de entrada também, quando aceita o modo exclusivo). Menor período neste dispositivo: %d amostras (%.1f ms)."),
  1475. r.name.c_str(), r.exclusiveMinPeriod, 1000.0 * r.exclusiveMinPeriod / rate);
  1476. else
  1477. swprintf (text, 600, L"%ls", tr (L"This device does not accept exclusive mode; the shared mode will be used.",
  1478. L"Este dispositivo não aceita o modo exclusivo; o modo compartilhado será usado."));
  1479. }
  1480. else
  1481. swprintf (text, 600, tr (L"Shared: other programs keep their sound. Windows mixes \"%ls\" every %d samples (%.1f ms)%ls; the latency cannot go below that.",
  1482. L"Compartilhado: os outros programas continuam com som. O Windows mistura \"%ls\" a cada %d amostras (%.1f ms)%ls; a latência não fica menor que isso."),
  1483. r.name.c_str(), r.sharedPeriod, 1000.0 * r.sharedPeriod / rate,
  1484. r.sharedPeriod < r.classicPeriod ? tr (L" (low-latency period)", L" (período de baixa latência)") : L"");
  1485. SetWindowTextW (item (idInfo), text);
  1486. updateLatency();
  1487. }
  1488. // "Latency" readout: what these settings give, and what the open stream really uses.
  1489. void updateLatency()
  1490. {
  1491. const auto& r = driver.render;
  1492. const double rate = r.mixRate > 0 ? r.mixRate : 48000.0;
  1493. auto ms = [rate] (int frames) { return 1000.0 * frames / rate; };
  1494. std::wstring text;
  1495. wchar_t line[400];
  1496. if (r.ok)
  1497. {
  1498. const auto l = driver.latencies (driver.preferredBlock(), false);
  1499. swprintf (line, 400, tr (L"Latency at %d samples (%.1f ms): output %.1f ms", L"Latência com %d amostras (%.1f ms): saída %.1f ms"),
  1500. l.block, ms (l.block), ms (l.output));
  1501. text = line;
  1502. if (l.hasInput)
  1503. {
  1504. swprintf (line, 400, tr (L", input %.1f ms (%ls)", L", entrada %.1f ms (%ls)"), ms (l.input),
  1505. l.captureExclusive ? tr (L"exclusive", L"exclusiva") : tr (L"shared", L"compartilhada"));
  1506. text += line;
  1507. }
  1508. else
  1509. text += tr (L", no input", L", sem entrada");
  1510. text += L".";
  1511. const auto now = driver.latencies (0, true);
  1512. if (now.open)
  1513. {
  1514. swprintf (line, 400, tr (L"\nRunning now: %ls, buffer %d, output %.1f ms", L"\nEm uso agora: %ls, buffer %d, saída %.1f ms"),
  1515. now.exclusive ? tr (L"exclusive", L"exclusivo") : tr (L"shared", L"compartilhado"), now.block, ms (now.output));
  1516. text += line;
  1517. if (now.hasInput)
  1518. {
  1519. swprintf (line, 400, tr (L", input %.1f ms (%ls)", L", entrada %.1f ms (%ls)"), ms (now.input),
  1520. now.captureExclusive ? tr (L"exclusive", L"exclusiva") : tr (L"shared", L"compartilhada"));
  1521. text += line;
  1522. }
  1523. text += tr (L". Changes apply when the program restarts the driver.", L". As mudanças valem quando o programa reiniciar o driver.");
  1524. }
  1525. }
  1526. SetWindowTextW (item (idLatency), text.c_str());
  1527. }
  1528. void readControls()
  1529. {
  1530. edit.mode = SendMessageW (item (idMode), CB_GETCURSEL, 0, 0) == 1 ? Mode::exclusive : Mode::shared;
  1531. const auto o = (int) SendMessageW (item (idOutput), CB_GETCURSEL, 0, 0);
  1532. edit.output = o <= 0 || o > (int) outputs.size() ? std::wstring() : outputs[(size_t) o - 1].id;
  1533. const auto in = (int) SendMessageW (item (idInput), CB_GETCURSEL, 0, 0);
  1534. edit.input = in <= 0 ? std::wstring() : in == 1 ? std::wstring (L"-") : in - 2 < (int) inputs.size() ? inputs[(size_t) in - 2].id : std::wstring();
  1535. const auto b = (int) SendMessageW (item (idBuffer), CB_GETCURSEL, 0, 0);
  1536. edit.bufferSize = b <= 0 ? 0 : (int) SendMessageW (item (idBuffer), CB_GETITEMDATA, (WPARAM) b, 0);
  1537. edit.safety = std::clamp ((int) SendMessageW (item (idSafety), CB_GETCURSEL, 0, 0), 0, 2);
  1538. }
  1539. void create (HWND owner)
  1540. {
  1541. NONCLIENTMETRICSW m {};
  1542. m.cbSize = sizeof (m);
  1543. SystemParametersInfoW (SPI_GETNONCLIENTMETRICS, sizeof (m), &m, 0);
  1544. font = CreateFontIndirectW (&m.lfMessageFont);
  1545. HDC screen = GetDC (nullptr);
  1546. const int dpi = GetDeviceCaps (screen, LOGPIXELSY);
  1547. ReleaseDC (nullptr, screen);
  1548. auto px = [dpi] (int v) { return MulDiv (v, dpi > 0 ? dpi : 96, 96); };
  1549. RECT rc { 0, 0, px (460), px (368) };
  1550. AdjustWindowRectEx (&rc, WS_CAPTION | WS_SYSMENU, FALSE, WS_EX_DLGMODALFRAME);
  1551. window = CreateWindowExW (WS_EX_DLGMODALFRAME, L"LynxAsioPanel", L"LYNX ASIO", WS_CAPTION | WS_SYSMENU | WS_POPUP,
  1552. CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, owner, nullptr, moduleHandle, this);
  1553. auto make = [&] (const wchar_t* cls, const wchar_t* text, DWORD style, int x, int y, int w, int h, int id)
  1554. {
  1555. HWND c = CreateWindowExW (0, cls, text, WS_CHILD | WS_VISIBLE | style, px (x), px (y), px (w), px (h), window, (HMENU) (INT_PTR) id, moduleHandle, nullptr);
  1556. SendMessageW (c, WM_SETFONT, (WPARAM) font, TRUE);
  1557. return c;
  1558. };
  1559. const DWORD combo = CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL;
  1560. int y = 14;
  1561. auto row = [&] (const wchar_t* label, int id)
  1562. {
  1563. make (L"STATIC", label, SS_LEFT, 14, y + 3, 130, 20, 0);
  1564. make (L"COMBOBOX", L"", combo, 150, y, 296, 300, id);
  1565. y += 34;
  1566. };
  1567. row (tr (L"Mode", L"Modo"), idMode);
  1568. row (tr (L"Output", L"Saída"), idOutput);
  1569. row (tr (L"Input", L"Entrada"), idInput);
  1570. row (tr (L"Buffer size", L"Tamanho do buffer"), idBuffer);
  1571. row (tr (L"Safety margin", L"Margem de segurança"), idSafety);
  1572. make (L"STATIC", L"", SS_LEFT, 14, y + 4, 432, 66, idInfo);
  1573. make (L"STATIC", L"", SS_LEFT, 14, y + 72, 432, 56, idLatency);
  1574. make (L"BUTTON", L"OK", BS_DEFPUSHBUTTON | WS_TABSTOP, 270, 328, 84, 28, idOk);
  1575. make (L"BUTTON", tr (L"Cancel", L"Cancelar"), BS_PUSHBUTTON | WS_TABSTOP, 362, 328, 84, 28, idCancel);
  1576. addString (item (idMode), tr (L"Shared (other programs keep their sound)", L"Compartilhado (os outros programas continuam com som)"));
  1577. addString (item (idMode), tr (L"Exclusive (lowest latency, device used alone)", L"Exclusivo (menor latência, dispositivo só do LYNX ASIO)"));
  1578. SendMessageW (item (idMode), CB_SETCURSEL, edit.mode == Mode::exclusive ? 1 : 0, 0);
  1579. auto lists = [this]
  1580. {
  1581. outputs = listEndpoints (eRender);
  1582. inputs = listEndpoints (eCapture);
  1583. };
  1584. onMtaThread (lists);
  1585. addString (item (idOutput), tr (L"Windows default device", L"Dispositivo padrão do Windows"));
  1586. int sel = 0;
  1587. for (size_t i = 0; i < outputs.size(); ++i)
  1588. {
  1589. addString (item (idOutput), outputs[i].name);
  1590. if (outputs[i].id == edit.output)
  1591. sel = (int) i + 1;
  1592. }
  1593. SendMessageW (item (idOutput), CB_SETCURSEL, (WPARAM) sel, 0);
  1594. addString (item (idInput), tr (L"Windows default device", L"Dispositivo padrão do Windows"));
  1595. addString (item (idInput), tr (L"None", L"Nenhuma"));
  1596. sel = edit.input == L"-" ? 1 : 0;
  1597. for (size_t i = 0; i < inputs.size(); ++i)
  1598. {
  1599. addString (item (idInput), inputs[i].name);
  1600. if (inputs[i].id == edit.input)
  1601. sel = (int) i + 2;
  1602. }
  1603. SendMessageW (item (idInput), CB_SETCURSEL, (WPARAM) sel, 0);
  1604. addString (item (idSafety), tr (L"None (lowest latency, may click)", L"Nenhuma (menor latência, pode estalar)"));
  1605. addString (item (idSafety), tr (L"Small", L"Pequena"));
  1606. addString (item (idSafety), tr (L"Normal", L"Normal"));
  1607. SendMessageW (item (idSafety), CB_SETCURSEL, (WPARAM) edit.safety, 0);
  1608. fillBuffers();
  1609. updateInfo();
  1610. RECT wr {}, or_ {};
  1611. GetWindowRect (window, &wr);
  1612. if (owner != nullptr && GetWindowRect (owner, &or_))
  1613. SetWindowPos (window, nullptr, (or_.left + or_.right - (wr.right - wr.left)) / 2, (or_.top + or_.bottom - (wr.bottom - wr.top)) / 2, 0, 0,
  1614. SWP_NOSIZE | SWP_NOZORDER);
  1615. ShowWindow (window, SW_SHOW);
  1616. }
  1617. static LRESULT CALLBACK proc (HWND h, UINT msg, WPARAM wp, LPARAM lp)
  1618. {
  1619. if (msg == WM_NCCREATE)
  1620. SetWindowLongPtrW (h, GWLP_USERDATA, (LONG_PTR) ((CREATESTRUCTW*) lp)->lpCreateParams);
  1621. auto* p = (Panel*) GetWindowLongPtrW (h, GWLP_USERDATA);
  1622. if (p != nullptr)
  1623. {
  1624. switch (msg)
  1625. {
  1626. case WM_COMMAND:
  1627. {
  1628. const int id = LOWORD (wp);
  1629. if (id == idOk || id == IDOK)
  1630. {
  1631. p->readControls();
  1632. p->accepted = true;
  1633. p->done = true;
  1634. return 0;
  1635. }
  1636. if (id == idCancel || id == IDCANCEL)
  1637. {
  1638. p->done = true;
  1639. return 0;
  1640. }
  1641. if (HIWORD (wp) == CBN_SELCHANGE && (id == idMode || id == idOutput || id == idInput))
  1642. {
  1643. p->readControls();
  1644. // re-probe the chosen device so the sizes, the explanation and the latency match it
  1645. p->driver.settings = p->edit;
  1646. p->driver.probe();
  1647. p->fillBuffers();
  1648. p->readControls();
  1649. p->driver.settings = p->edit;
  1650. p->updateInfo();
  1651. }
  1652. else if (HIWORD (wp) == CBN_SELCHANGE && (id == idBuffer || id == idSafety))
  1653. {
  1654. p->readControls();
  1655. p->driver.settings = p->edit; // restored by showPanel on Cancel
  1656. p->updateLatency();
  1657. }
  1658. break;
  1659. }
  1660. case WM_CLOSE:
  1661. p->done = true;
  1662. return 0;
  1663. default:
  1664. break;
  1665. }
  1666. }
  1667. return DefWindowProcW (h, msg, wp, lp);
  1668. }
  1669. };
  1670. INT_PTR showPanel (LynxAsio& driver, HWND owner)
  1671. {
  1672. static bool registered = false;
  1673. if (! registered)
  1674. {
  1675. WNDCLASSW wc {};
  1676. wc.lpfnWndProc = Panel::proc;
  1677. wc.hInstance = moduleHandle;
  1678. wc.hCursor = LoadCursor (nullptr, IDC_ARROW);
  1679. wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
  1680. wc.lpszClassName = L"LynxAsioPanel";
  1681. registered = RegisterClassW (&wc) != 0;
  1682. }
  1683. const auto original = driver.settings;
  1684. Panel panel { driver, driver.settings, {}, {} };
  1685. panel.create (owner);
  1686. if (owner != nullptr)
  1687. EnableWindow (owner, FALSE);
  1688. MSG msg;
  1689. while (! panel.done && GetMessageW (&msg, nullptr, 0, 0) > 0)
  1690. {
  1691. if (! IsDialogMessageW (panel.window, &msg))
  1692. {
  1693. TranslateMessage (&msg);
  1694. DispatchMessageW (&msg);
  1695. }
  1696. }
  1697. if (owner != nullptr)
  1698. {
  1699. EnableWindow (owner, TRUE);
  1700. SetForegroundWindow (owner);
  1701. }
  1702. DestroyWindow (panel.window);
  1703. if (panel.font != nullptr)
  1704. DeleteObject (panel.font);
  1705. driver.settings = panel.accepted ? panel.edit : original;
  1706. if (! panel.accepted)
  1707. driver.probe();
  1708. return panel.accepted ? IDOK : IDCANCEL;
  1709. }
  1710. //==============================================================================================================
  1711. // COM class factory and registration
  1712. class Factory final : public IClassFactory
  1713. {
  1714. public:
  1715. HRESULT STDMETHODCALLTYPE QueryInterface (REFIID iid, void** out) override
  1716. {
  1717. if (IsEqualIID (iid, IID_IUnknown) || IsEqualIID (iid, IID_IClassFactory))
  1718. {
  1719. *out = static_cast<IClassFactory*> (this);
  1720. AddRef();
  1721. return S_OK;
  1722. }
  1723. *out = nullptr;
  1724. return E_NOINTERFACE;
  1725. }
  1726. ULONG STDMETHODCALLTYPE AddRef() override { return 2; }
  1727. ULONG STDMETHODCALLTYPE Release() override { return 1; }
  1728. HRESULT STDMETHODCALLTYPE CreateInstance (IUnknown* outer, REFIID iid, void** out) override
  1729. {
  1730. if (outer != nullptr)
  1731. return CLASS_E_NOAGGREGATION;
  1732. auto* d = new LynxAsio();
  1733. const auto hr = d->QueryInterface (iid, out);
  1734. d->Release();
  1735. return hr;
  1736. }
  1737. HRESULT STDMETHODCALLTYPE LockServer (BOOL lock) override
  1738. {
  1739. lock ? ++serverLocks : --serverLocks;
  1740. return S_OK;
  1741. }
  1742. };
  1743. Factory factory;
  1744. std::wstring clsidString()
  1745. {
  1746. LPOLESTR s = nullptr;
  1747. StringFromCLSID (CLSID_LynxAsio, &s);
  1748. std::wstring r = s != nullptr ? s : L"";
  1749. CoTaskMemFree (s);
  1750. return r;
  1751. }
  1752. LONG setValue (HKEY root, const std::wstring& key, const wchar_t* name, const std::wstring& value)
  1753. {
  1754. HKEY k = nullptr;
  1755. auto r = RegCreateKeyExW (root, key.c_str(), 0, nullptr, 0, KEY_WRITE, nullptr, &k, nullptr);
  1756. if (r == ERROR_SUCCESS)
  1757. {
  1758. r = RegSetValueExW (k, name, 0, REG_SZ, (const BYTE*) value.c_str(), (DWORD) ((value.size() + 1) * sizeof (wchar_t)));
  1759. RegCloseKey (k);
  1760. }
  1761. return r;
  1762. }
  1763. } // namespace
  1764. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  1765. {
  1766. if (reason == DLL_PROCESS_ATTACH)
  1767. {
  1768. moduleHandle = instance;
  1769. DisableThreadLibraryCalls (instance);
  1770. }
  1771. return TRUE;
  1772. }
  1773. extern "C" HRESULT STDAPICALLTYPE DllGetClassObject (REFCLSID clsid, REFIID iid, void** out)
  1774. {
  1775. if (! IsEqualCLSID (clsid, CLSID_LynxAsio))
  1776. return CLASS_E_CLASSNOTAVAILABLE;
  1777. return factory.QueryInterface (iid, out);
  1778. }
  1779. extern "C" HRESULT STDAPICALLTYPE DllCanUnloadNow()
  1780. {
  1781. return serverLocks == 0 && liveObjects == 0 ? S_OK : S_FALSE;
  1782. }
  1783. // regsvr32 lynx-asio.dll (as administrator): the COM class and the entry in the ASIO driver list.
  1784. extern "C" HRESULT STDAPICALLTYPE DllRegisterServer()
  1785. {
  1786. wchar_t path[MAX_PATH * 2] {};
  1787. GetModuleFileNameW (moduleHandle, path, MAX_PATH * 2);
  1788. const auto clsid = clsidString();
  1789. const auto classKey = L"SOFTWARE\\Classes\\CLSID\\" + clsid;
  1790. LONG r = setValue (HKEY_LOCAL_MACHINE, classKey, nullptr, driverNameW);
  1791. if (r == ERROR_SUCCESS)
  1792. r = setValue (HKEY_LOCAL_MACHINE, classKey + L"\\InprocServer32", nullptr, path);
  1793. if (r == ERROR_SUCCESS)
  1794. r = setValue (HKEY_LOCAL_MACHINE, classKey + L"\\InprocServer32", L"ThreadingModel", L"Apartment");
  1795. const std::wstring asioKey = std::wstring (L"SOFTWARE\\ASIO\\") + driverNameW;
  1796. if (r == ERROR_SUCCESS)
  1797. r = setValue (HKEY_LOCAL_MACHINE, asioKey, L"CLSID", clsid);
  1798. if (r == ERROR_SUCCESS)
  1799. r = setValue (HKEY_LOCAL_MACHINE, asioKey, L"Description", driverNameW);
  1800. return r == ERROR_SUCCESS ? S_OK : (r == ERROR_ACCESS_DENIED ? E_ACCESSDENIED : E_FAIL);
  1801. }
  1802. extern "C" HRESULT STDAPICALLTYPE DllUnregisterServer()
  1803. {
  1804. const auto clsid = clsidString();
  1805. RegDeleteTreeW (HKEY_LOCAL_MACHINE, (L"SOFTWARE\\Classes\\CLSID\\" + clsid).c_str());
  1806. const auto r = RegDeleteTreeW (HKEY_LOCAL_MACHINE, (std::wstring (L"SOFTWARE\\ASIO\\") + driverNameW).c_str());
  1807. return r == ERROR_SUCCESS || r == ERROR_FILE_NOT_FOUND ? S_OK : E_ACCESSDENIED;
  1808. }