Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_win32_ASIO.cpp 55KB

7 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
7 years ago
9 years ago
7 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
7 years ago
9 years ago
9 years ago
7 years ago
7 years ago
7 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. #undef WINDOWS
  20. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  21. to be pretty random about whether or not they do this. If you hit an error using these functions
  22. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  23. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  24. */
  25. #define JUCE_ASIOCALLBACK __cdecl
  26. //==============================================================================
  27. namespace ASIODebugging
  28. {
  29. #if JUCE_ASIO_DEBUGGING
  30. #define JUCE_ASIO_LOG(msg) ASIODebugging::logMessage (msg)
  31. #define JUCE_ASIO_LOG_ERROR(msg, errNum) ASIODebugging::logError ((msg), (errNum))
  32. static void logMessage (String message)
  33. {
  34. message = "ASIO: " + message;
  35. DBG (message);
  36. Logger::writeToLog (message);
  37. }
  38. static void logError (const String& context, long error)
  39. {
  40. const char* err = "Unknown error";
  41. switch (error)
  42. {
  43. case ASE_OK: return;
  44. case ASE_NotPresent: err = "Not Present"; break;
  45. case ASE_HWMalfunction: err = "Hardware Malfunction"; break;
  46. case ASE_InvalidParameter: err = "Invalid Parameter"; break;
  47. case ASE_InvalidMode: err = "Invalid Mode"; break;
  48. case ASE_SPNotAdvancing: err = "Sample position not advancing"; break;
  49. case ASE_NoClock: err = "No Clock"; break;
  50. case ASE_NoMemory: err = "Out of memory"; break;
  51. default: break;
  52. }
  53. logMessage ("error: " + context + " - " + err);
  54. }
  55. #else
  56. static void dummyLog() {}
  57. #define JUCE_ASIO_LOG(msg) ASIODebugging::dummyLog()
  58. #define JUCE_ASIO_LOG_ERROR(msg, errNum) ignoreUnused (errNum); ASIODebugging::dummyLog()
  59. #endif
  60. }
  61. //==============================================================================
  62. struct ASIOSampleFormat
  63. {
  64. ASIOSampleFormat() noexcept {}
  65. ASIOSampleFormat (const long type) noexcept
  66. : bitDepth (24),
  67. littleEndian (true),
  68. formatIsFloat (false),
  69. byteStride (4)
  70. {
  71. switch (type)
  72. {
  73. case ASIOSTInt16MSB: byteStride = 2; littleEndian = false; bitDepth = 16; break;
  74. case ASIOSTInt24MSB: byteStride = 3; littleEndian = false; break;
  75. case ASIOSTInt32MSB: bitDepth = 32; littleEndian = false; break;
  76. case ASIOSTFloat32MSB: bitDepth = 32; littleEndian = false; formatIsFloat = true; break;
  77. case ASIOSTFloat64MSB: bitDepth = 64; byteStride = 8; littleEndian = false; break;
  78. case ASIOSTInt32MSB16: bitDepth = 16; littleEndian = false; break;
  79. case ASIOSTInt32MSB18: littleEndian = false; break;
  80. case ASIOSTInt32MSB20: littleEndian = false; break;
  81. case ASIOSTInt32MSB24: littleEndian = false; break;
  82. case ASIOSTInt16LSB: byteStride = 2; bitDepth = 16; break;
  83. case ASIOSTInt24LSB: byteStride = 3; break;
  84. case ASIOSTInt32LSB: bitDepth = 32; break;
  85. case ASIOSTFloat32LSB: bitDepth = 32; formatIsFloat = true; break;
  86. case ASIOSTFloat64LSB: bitDepth = 64; byteStride = 8; break;
  87. case ASIOSTInt32LSB16: bitDepth = 16; break;
  88. case ASIOSTInt32LSB18: break; // (unhandled)
  89. case ASIOSTInt32LSB20: break; // (unhandled)
  90. case ASIOSTInt32LSB24: break;
  91. case ASIOSTDSDInt8LSB1: break; // (unhandled)
  92. case ASIOSTDSDInt8MSB1: break; // (unhandled)
  93. case ASIOSTDSDInt8NER8: break; // (unhandled)
  94. default:
  95. jassertfalse; // (not a valid format code..)
  96. break;
  97. }
  98. }
  99. void convertToFloat (const void* const src, float* const dst, const int samps) const noexcept
  100. {
  101. if (formatIsFloat)
  102. {
  103. memcpy (dst, src, samps * sizeof (float));
  104. }
  105. else
  106. {
  107. switch (bitDepth)
  108. {
  109. case 16: convertInt16ToFloat (static_cast<const char*> (src), dst, byteStride, samps, littleEndian); break;
  110. case 24: convertInt24ToFloat (static_cast<const char*> (src), dst, byteStride, samps, littleEndian); break;
  111. case 32: convertInt32ToFloat (static_cast<const char*> (src), dst, byteStride, samps, littleEndian); break;
  112. default: jassertfalse; break;
  113. }
  114. }
  115. }
  116. void convertFromFloat (const float* const src, void* const dst, const int samps) const noexcept
  117. {
  118. if (formatIsFloat)
  119. {
  120. memcpy (dst, src, samps * sizeof (float));
  121. }
  122. else
  123. {
  124. switch (bitDepth)
  125. {
  126. case 16: convertFloatToInt16 (src, static_cast<char*> (dst), byteStride, samps, littleEndian); break;
  127. case 24: convertFloatToInt24 (src, static_cast<char*> (dst), byteStride, samps, littleEndian); break;
  128. case 32: convertFloatToInt32 (src, static_cast<char*> (dst), byteStride, samps, littleEndian); break;
  129. default: jassertfalse; break;
  130. }
  131. }
  132. }
  133. void clear (void* dst, const int numSamps) noexcept
  134. {
  135. if (dst != nullptr)
  136. zeromem (dst, numSamps * byteStride);
  137. }
  138. int bitDepth, byteStride;
  139. bool formatIsFloat, littleEndian;
  140. private:
  141. static void convertInt16ToFloat (const char* src, float* dest, const int srcStrideBytes,
  142. int numSamples, const bool littleEndian) noexcept
  143. {
  144. const double g = 1.0 / 32768.0;
  145. if (littleEndian)
  146. {
  147. while (--numSamples >= 0)
  148. {
  149. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  150. src += srcStrideBytes;
  151. }
  152. }
  153. else
  154. {
  155. while (--numSamples >= 0)
  156. {
  157. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  158. src += srcStrideBytes;
  159. }
  160. }
  161. }
  162. static void convertFloatToInt16 (const float* src, char* dest, const int dstStrideBytes,
  163. int numSamples, const bool littleEndian) noexcept
  164. {
  165. const double maxVal = (double) 0x7fff;
  166. if (littleEndian)
  167. {
  168. while (--numSamples >= 0)
  169. {
  170. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  171. dest += dstStrideBytes;
  172. }
  173. }
  174. else
  175. {
  176. while (--numSamples >= 0)
  177. {
  178. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  179. dest += dstStrideBytes;
  180. }
  181. }
  182. }
  183. static void convertInt24ToFloat (const char* src, float* dest, const int srcStrideBytes,
  184. int numSamples, const bool littleEndian) noexcept
  185. {
  186. const double g = 1.0 / 0x7fffff;
  187. if (littleEndian)
  188. {
  189. while (--numSamples >= 0)
  190. {
  191. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  192. src += srcStrideBytes;
  193. }
  194. }
  195. else
  196. {
  197. while (--numSamples >= 0)
  198. {
  199. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  200. src += srcStrideBytes;
  201. }
  202. }
  203. }
  204. static void convertFloatToInt24 (const float* src, char* dest, const int dstStrideBytes,
  205. int numSamples, const bool littleEndian) noexcept
  206. {
  207. const double maxVal = (double) 0x7fffff;
  208. if (littleEndian)
  209. {
  210. while (--numSamples >= 0)
  211. {
  212. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213. dest += dstStrideBytes;
  214. }
  215. }
  216. else
  217. {
  218. while (--numSamples >= 0)
  219. {
  220. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  221. dest += dstStrideBytes;
  222. }
  223. }
  224. }
  225. static void convertInt32ToFloat (const char* src, float* dest, const int srcStrideBytes,
  226. int numSamples, const bool littleEndian) noexcept
  227. {
  228. const double g = 1.0 / 0x7fffffff;
  229. if (littleEndian)
  230. {
  231. while (--numSamples >= 0)
  232. {
  233. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  234. src += srcStrideBytes;
  235. }
  236. }
  237. else
  238. {
  239. while (--numSamples >= 0)
  240. {
  241. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  242. src += srcStrideBytes;
  243. }
  244. }
  245. }
  246. static void convertFloatToInt32 (const float* src, char* dest, const int dstStrideBytes,
  247. int numSamples, const bool littleEndian) noexcept
  248. {
  249. const double maxVal = (double) 0x7fffffff;
  250. if (littleEndian)
  251. {
  252. while (--numSamples >= 0)
  253. {
  254. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  255. dest += dstStrideBytes;
  256. }
  257. }
  258. else
  259. {
  260. while (--numSamples >= 0)
  261. {
  262. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  263. dest += dstStrideBytes;
  264. }
  265. }
  266. }
  267. };
  268. //==============================================================================
  269. class ASIOAudioIODevice;
  270. static ASIOAudioIODevice* volatile currentASIODev[16] = { 0 };
  271. extern HWND juce_messageWindowHandle;
  272. class ASIOAudioIODeviceType;
  273. static void sendASIODeviceChangeToListeners (ASIOAudioIODeviceType*);
  274. //==============================================================================
  275. class ASIOAudioIODevice : public AudioIODevice,
  276. private Timer
  277. {
  278. public:
  279. ASIOAudioIODevice (ASIOAudioIODeviceType* ownerType, const String& devName,
  280. const CLSID clsID, const int slotNumber)
  281. : AudioIODevice (devName, "ASIO"),
  282. owner (ownerType),
  283. asioObject (nullptr),
  284. classId (clsID),
  285. inputLatency (0),
  286. outputLatency (0),
  287. minBufferSize (0), maxBufferSize (0),
  288. preferredBufferSize (0),
  289. bufferGranularity (0),
  290. numClockSources (0),
  291. currentBlockSizeSamples (0),
  292. currentBitDepth (16),
  293. currentSampleRate (0),
  294. currentCallback (nullptr),
  295. bufferIndex (0),
  296. numActiveInputChans (0),
  297. numActiveOutputChans (0),
  298. deviceIsOpen (false),
  299. isStarted (false),
  300. buffersCreated (false),
  301. calledback (false),
  302. littleEndian (false),
  303. postOutput (true),
  304. needToReset (false),
  305. insideControlPanelModalLoop (false),
  306. shouldUsePreferredSize (false)
  307. {
  308. ::CoInitialize (nullptr);
  309. name = devName;
  310. inBuffers.calloc (4);
  311. outBuffers.calloc (4);
  312. jassert (currentASIODev [slotNumber] == nullptr);
  313. currentASIODev [slotNumber] = this;
  314. openDevice();
  315. }
  316. ~ASIOAudioIODevice()
  317. {
  318. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  319. if (currentASIODev[i] == this)
  320. currentASIODev[i] = nullptr;
  321. close();
  322. JUCE_ASIO_LOG ("closed");
  323. removeCurrentDriver();
  324. }
  325. void updateSampleRates()
  326. {
  327. // find a list of sample rates..
  328. Array<double> newRates;
  329. if (asioObject != nullptr)
  330. {
  331. const int possibleSampleRates[] = { 32000, 44100, 48000, 88200, 96000, 176400, 192000, 352800, 384000 };
  332. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  333. if (asioObject->canSampleRate ((double) possibleSampleRates[index]) == 0)
  334. newRates.add ((double) possibleSampleRates[index]);
  335. }
  336. if (newRates.isEmpty())
  337. {
  338. double cr = getSampleRate();
  339. JUCE_ASIO_LOG ("No sample rates supported - current rate: " + String ((int) cr));
  340. if (cr > 0)
  341. newRates.add ((int) cr);
  342. }
  343. if (sampleRates != newRates)
  344. {
  345. sampleRates.swapWith (newRates);
  346. #if JUCE_ASIO_DEBUGGING
  347. StringArray s;
  348. for (int i = 0; i < sampleRates.size(); ++i)
  349. s.add (String (sampleRates.getUnchecked(i)));
  350. JUCE_ASIO_LOG ("Rates: " + s.joinIntoString (" "));
  351. #endif
  352. }
  353. }
  354. StringArray getOutputChannelNames() override { return outputChannelNames; }
  355. StringArray getInputChannelNames() override { return inputChannelNames; }
  356. Array<double> getAvailableSampleRates() override { return sampleRates; }
  357. Array<int> getAvailableBufferSizes() override { return bufferSizes; }
  358. int getDefaultBufferSize() override { return preferredBufferSize; }
  359. int getXRunCount() const noexcept override { return xruns; }
  360. String open (const BigInteger& inputChannels,
  361. const BigInteger& outputChannels,
  362. double sr, int bufferSizeSamples) override
  363. {
  364. if (isOpen())
  365. close();
  366. jassert (currentCallback == nullptr);
  367. if (bufferSizeSamples < 8 || bufferSizeSamples > 16384)
  368. shouldUsePreferredSize = true;
  369. if (asioObject == nullptr)
  370. {
  371. const String openingError (openDevice());
  372. if (asioObject == nullptr)
  373. return openingError;
  374. }
  375. isStarted = false;
  376. bufferIndex = -1;
  377. long err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans);
  378. jassert (err == ASE_OK);
  379. bufferSizeSamples = readBufferSizes (bufferSizeSamples);
  380. double sampleRate = sr;
  381. currentSampleRate = sampleRate;
  382. currentBlockSizeSamples = bufferSizeSamples;
  383. currentChansOut.clear();
  384. currentChansIn.clear();
  385. updateSampleRates();
  386. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  387. sampleRate = sampleRates[0];
  388. jassert (sampleRate != 0);
  389. if (sampleRate == 0)
  390. sampleRate = 44100.0;
  391. updateClockSources();
  392. currentSampleRate = getSampleRate();
  393. error.clear();
  394. buffersCreated = false;
  395. setSampleRate (sampleRate);
  396. // (need to get this again in case a sample rate change affected the channel count)
  397. err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans);
  398. jassert (err == ASE_OK);
  399. if (asioObject->future (kAsioCanReportOverload, nullptr) != ASE_OK)
  400. xruns = -1;
  401. inBuffers.calloc (totalNumInputChans + 8);
  402. outBuffers.calloc (totalNumOutputChans + 8);
  403. if (needToReset)
  404. {
  405. JUCE_ASIO_LOG (" Resetting");
  406. removeCurrentDriver();
  407. loadDriver();
  408. String initError = initDriver();
  409. if (initError.isNotEmpty())
  410. JUCE_ASIO_LOG ("ASIOInit: " + initError);
  411. needToReset = false;
  412. }
  413. const int totalBuffers = resetBuffers (inputChannels, outputChannels);
  414. setCallbackFunctions();
  415. JUCE_ASIO_LOG ("disposing buffers");
  416. err = asioObject->disposeBuffers();
  417. JUCE_ASIO_LOG ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  418. err = asioObject->createBuffers (bufferInfos, totalBuffers, currentBlockSizeSamples, &callbacks);
  419. if (err != ASE_OK)
  420. {
  421. currentBlockSizeSamples = preferredBufferSize;
  422. JUCE_ASIO_LOG_ERROR ("create buffers 2", err);
  423. asioObject->disposeBuffers();
  424. err = asioObject->createBuffers (bufferInfos, totalBuffers, currentBlockSizeSamples, &callbacks);
  425. }
  426. if (err == ASE_OK)
  427. {
  428. buffersCreated = true;
  429. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  430. int n = 0;
  431. Array <int> types;
  432. currentBitDepth = 16;
  433. for (int i = 0; i < (int) totalNumInputChans; ++i)
  434. {
  435. if (inputChannels[i])
  436. {
  437. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  438. ASIOChannelInfo channelInfo = { 0 };
  439. channelInfo.channel = i;
  440. channelInfo.isInput = 1;
  441. asioObject->getChannelInfo (&channelInfo);
  442. types.addIfNotAlreadyThere (channelInfo.type);
  443. inputFormat[n] = ASIOSampleFormat (channelInfo.type);
  444. currentBitDepth = jmax (currentBitDepth, inputFormat[n].bitDepth);
  445. ++n;
  446. }
  447. }
  448. jassert (numActiveInputChans == n);
  449. n = 0;
  450. for (int i = 0; i < (int) totalNumOutputChans; ++i)
  451. {
  452. if (outputChannels[i])
  453. {
  454. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  455. ASIOChannelInfo channelInfo = { 0 };
  456. channelInfo.channel = i;
  457. channelInfo.isInput = 0;
  458. asioObject->getChannelInfo (&channelInfo);
  459. types.addIfNotAlreadyThere (channelInfo.type);
  460. outputFormat[n] = ASIOSampleFormat (channelInfo.type);
  461. currentBitDepth = jmax (currentBitDepth, outputFormat[n].bitDepth);
  462. ++n;
  463. }
  464. }
  465. jassert (numActiveOutputChans == n);
  466. for (int i = types.size(); --i >= 0;)
  467. JUCE_ASIO_LOG ("channel format: " + String (types[i]));
  468. jassert (n <= totalBuffers);
  469. for (int i = 0; i < numActiveOutputChans; ++i)
  470. {
  471. outputFormat[i].clear (bufferInfos [numActiveInputChans + i].buffers[0], currentBlockSizeSamples);
  472. outputFormat[i].clear (bufferInfos [numActiveInputChans + i].buffers[1], currentBlockSizeSamples);
  473. }
  474. readLatencies();
  475. refreshBufferSizes();
  476. deviceIsOpen = true;
  477. JUCE_ASIO_LOG ("starting");
  478. calledback = false;
  479. err = asioObject->start();
  480. if (err != 0)
  481. {
  482. deviceIsOpen = false;
  483. JUCE_ASIO_LOG ("stop on failure");
  484. Thread::sleep (10);
  485. asioObject->stop();
  486. error = "Can't start device";
  487. Thread::sleep (10);
  488. }
  489. else
  490. {
  491. int count = 300;
  492. while (--count > 0 && ! calledback)
  493. Thread::sleep (10);
  494. isStarted = true;
  495. if (! calledback)
  496. {
  497. error = "Device didn't start correctly";
  498. JUCE_ASIO_LOG ("no callbacks - stopping..");
  499. asioObject->stop();
  500. }
  501. }
  502. }
  503. else
  504. {
  505. error = "Can't create i/o buffers";
  506. }
  507. if (error.isNotEmpty())
  508. {
  509. JUCE_ASIO_LOG_ERROR (error, err);
  510. disposeBuffers();
  511. Thread::sleep (20);
  512. isStarted = false;
  513. deviceIsOpen = false;
  514. const String errorCopy (error);
  515. close(); // (this resets the error string)
  516. error = errorCopy;
  517. }
  518. needToReset = false;
  519. return error;
  520. }
  521. void close() override
  522. {
  523. error.clear();
  524. stopTimer();
  525. stop();
  526. if (asioObject != nullptr && deviceIsOpen)
  527. {
  528. const ScopedLock sl (callbackLock);
  529. deviceIsOpen = false;
  530. isStarted = false;
  531. needToReset = false;
  532. JUCE_ASIO_LOG ("stopping");
  533. if (asioObject != nullptr)
  534. {
  535. Thread::sleep (20);
  536. asioObject->stop();
  537. Thread::sleep (10);
  538. disposeBuffers();
  539. }
  540. Thread::sleep (10);
  541. }
  542. }
  543. bool isOpen() override { return deviceIsOpen || insideControlPanelModalLoop; }
  544. bool isPlaying() override { return asioObject != nullptr && currentCallback != nullptr; }
  545. int getCurrentBufferSizeSamples() override { return currentBlockSizeSamples; }
  546. double getCurrentSampleRate() override { return currentSampleRate; }
  547. int getCurrentBitDepth() override { return currentBitDepth; }
  548. BigInteger getActiveOutputChannels() const override { return currentChansOut; }
  549. BigInteger getActiveInputChannels() const override { return currentChansIn; }
  550. int getOutputLatencyInSamples() override { return outputLatency + currentBlockSizeSamples / 4; }
  551. int getInputLatencyInSamples() override { return inputLatency + currentBlockSizeSamples / 4; }
  552. void start (AudioIODeviceCallback* callback) override
  553. {
  554. if (callback != nullptr)
  555. {
  556. callback->audioDeviceAboutToStart (this);
  557. const ScopedLock sl (callbackLock);
  558. currentCallback = callback;
  559. }
  560. }
  561. void stop() override
  562. {
  563. AudioIODeviceCallback* const lastCallback = currentCallback;
  564. {
  565. const ScopedLock sl (callbackLock);
  566. currentCallback = nullptr;
  567. }
  568. if (lastCallback != nullptr)
  569. lastCallback->audioDeviceStopped();
  570. }
  571. String getLastError() { return error; }
  572. bool hasControlPanel() const { return true; }
  573. bool showControlPanel()
  574. {
  575. JUCE_ASIO_LOG ("showing control panel");
  576. bool done = false;
  577. insideControlPanelModalLoop = true;
  578. const uint32 started = Time::getMillisecondCounter();
  579. if (asioObject != nullptr)
  580. {
  581. asioObject->controlPanel();
  582. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  583. JUCE_ASIO_LOG ("spent: " + String (spent));
  584. if (spent > 300)
  585. {
  586. shouldUsePreferredSize = true;
  587. done = true;
  588. }
  589. }
  590. insideControlPanelModalLoop = false;
  591. return done;
  592. }
  593. void resetRequest() noexcept
  594. {
  595. startTimer (500);
  596. }
  597. void timerCallback() override
  598. {
  599. if (! insideControlPanelModalLoop)
  600. {
  601. stopTimer();
  602. JUCE_ASIO_LOG ("restart request!");
  603. AudioIODeviceCallback* const oldCallback = currentCallback;
  604. close();
  605. needToReset = true;
  606. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  607. currentSampleRate, currentBlockSizeSamples);
  608. reloadChannelNames();
  609. if (oldCallback != nullptr)
  610. start (oldCallback);
  611. sendASIODeviceChangeToListeners (owner);
  612. }
  613. else
  614. {
  615. startTimer (100);
  616. }
  617. }
  618. private:
  619. //==============================================================================
  620. WeakReference<ASIOAudioIODeviceType> owner;
  621. IASIO* volatile asioObject;
  622. ASIOCallbacks callbacks;
  623. CLSID classId;
  624. String error;
  625. long totalNumInputChans, totalNumOutputChans;
  626. StringArray inputChannelNames, outputChannelNames;
  627. Array<double> sampleRates;
  628. Array<int> bufferSizes;
  629. long inputLatency, outputLatency;
  630. long minBufferSize, maxBufferSize, preferredBufferSize, bufferGranularity;
  631. ASIOClockSource clocks[32];
  632. int numClockSources;
  633. int volatile currentBlockSizeSamples;
  634. int volatile currentBitDepth;
  635. double volatile currentSampleRate;
  636. BigInteger currentChansOut, currentChansIn;
  637. AudioIODeviceCallback* volatile currentCallback;
  638. CriticalSection callbackLock;
  639. HeapBlock<ASIOBufferInfo> bufferInfos;
  640. HeapBlock<float*> inBuffers, outBuffers;
  641. HeapBlock<ASIOSampleFormat> inputFormat, outputFormat;
  642. WaitableEvent event1;
  643. HeapBlock<float> tempBuffer;
  644. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  645. bool deviceIsOpen, isStarted, buffersCreated;
  646. bool volatile calledback;
  647. bool volatile littleEndian, postOutput, needToReset;
  648. bool volatile insideControlPanelModalLoop;
  649. bool volatile shouldUsePreferredSize;
  650. int xruns = 0;
  651. //==============================================================================
  652. static String convertASIOString (char* const text, int length)
  653. {
  654. if (CharPointer_UTF8::isValidString (text, length))
  655. return String::fromUTF8 (text, length);
  656. WCHAR wideVersion [64] = { 0 };
  657. MultiByteToWideChar (CP_ACP, 0, text, length, wideVersion, numElementsInArray (wideVersion));
  658. return wideVersion;
  659. }
  660. String getChannelName (int index, bool isInput) const
  661. {
  662. ASIOChannelInfo channelInfo = { 0 };
  663. channelInfo.channel = index;
  664. channelInfo.isInput = isInput ? 1 : 0;
  665. asioObject->getChannelInfo (&channelInfo);
  666. return convertASIOString (channelInfo.name, sizeof (channelInfo.name));
  667. }
  668. void reloadChannelNames()
  669. {
  670. if (asioObject != nullptr
  671. && asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans) == ASE_OK)
  672. {
  673. inputChannelNames.clear();
  674. outputChannelNames.clear();
  675. for (int i = 0; i < totalNumInputChans; ++i)
  676. inputChannelNames.add (getChannelName (i, true));
  677. for (int i = 0; i < totalNumOutputChans; ++i)
  678. outputChannelNames.add (getChannelName (i, false));
  679. outputChannelNames.trim();
  680. inputChannelNames.trim();
  681. outputChannelNames.appendNumbersToDuplicates (false, true);
  682. inputChannelNames.appendNumbersToDuplicates (false, true);
  683. }
  684. }
  685. long refreshBufferSizes()
  686. {
  687. return asioObject->getBufferSize (&minBufferSize, &maxBufferSize, &preferredBufferSize, &bufferGranularity);
  688. }
  689. int readBufferSizes (int bufferSizeSamples)
  690. {
  691. minBufferSize = 0;
  692. maxBufferSize = 0;
  693. bufferGranularity = 0;
  694. long newPreferredSize = 0;
  695. if (asioObject->getBufferSize (&minBufferSize, &maxBufferSize, &newPreferredSize, &bufferGranularity) == ASE_OK)
  696. {
  697. if (preferredBufferSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredBufferSize)
  698. shouldUsePreferredSize = true;
  699. if (bufferSizeSamples < minBufferSize || bufferSizeSamples > maxBufferSize)
  700. shouldUsePreferredSize = true;
  701. preferredBufferSize = newPreferredSize;
  702. }
  703. // unfortunate workaround for certain drivers which crash if you make
  704. // dynamic changes to the buffer size...
  705. shouldUsePreferredSize = shouldUsePreferredSize || getName().containsIgnoreCase ("Digidesign");
  706. if (shouldUsePreferredSize)
  707. {
  708. JUCE_ASIO_LOG ("Using preferred size for buffer..");
  709. long err = refreshBufferSizes();
  710. if (err == ASE_OK)
  711. {
  712. bufferSizeSamples = (int) preferredBufferSize;
  713. }
  714. else
  715. {
  716. bufferSizeSamples = 1024;
  717. JUCE_ASIO_LOG_ERROR ("getBufferSize1", err);
  718. }
  719. shouldUsePreferredSize = false;
  720. }
  721. return bufferSizeSamples;
  722. }
  723. int resetBuffers (const BigInteger& inputChannels,
  724. const BigInteger& outputChannels)
  725. {
  726. numActiveInputChans = 0;
  727. numActiveOutputChans = 0;
  728. ASIOBufferInfo* info = bufferInfos;
  729. for (int i = 0; i < totalNumInputChans; ++i)
  730. {
  731. if (inputChannels[i])
  732. {
  733. currentChansIn.setBit (i);
  734. info->isInput = 1;
  735. info->channelNum = i;
  736. info->buffers[0] = info->buffers[1] = nullptr;
  737. ++info;
  738. ++numActiveInputChans;
  739. }
  740. }
  741. for (int i = 0; i < totalNumOutputChans; ++i)
  742. {
  743. if (outputChannels[i])
  744. {
  745. currentChansOut.setBit (i);
  746. info->isInput = 0;
  747. info->channelNum = i;
  748. info->buffers[0] = info->buffers[1] = nullptr;
  749. ++info;
  750. ++numActiveOutputChans;
  751. }
  752. }
  753. return numActiveInputChans + numActiveOutputChans;
  754. }
  755. void addBufferSizes (long minSize, long maxSize, long preferredSize, long granularity)
  756. {
  757. // find a list of buffer sizes..
  758. JUCE_ASIO_LOG (String ((int) minSize) + "->" + String ((int) maxSize) + ", "
  759. + String ((int) preferredSize) + ", " + String ((int) granularity));
  760. if (granularity >= 0)
  761. {
  762. granularity = jmax (16, (int) granularity);
  763. for (int i = jmax ((int) (minSize + 15) & ~15, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  764. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  765. }
  766. else if (granularity < 0)
  767. {
  768. for (int i = 0; i < 18; ++i)
  769. {
  770. const int s = (1 << i);
  771. if (s >= minSize && s <= maxSize)
  772. bufferSizes.add (s);
  773. }
  774. }
  775. bufferSizes.addIfNotAlreadyThere (preferredSize);
  776. bufferSizes.sort();
  777. }
  778. double getSampleRate() const
  779. {
  780. double cr = 0;
  781. long err = asioObject->getSampleRate (&cr);
  782. JUCE_ASIO_LOG_ERROR ("getSampleRate", err);
  783. return cr;
  784. }
  785. void setSampleRate (double newRate)
  786. {
  787. if (currentSampleRate != newRate)
  788. {
  789. JUCE_ASIO_LOG ("rate change: " + String (currentSampleRate) + " to " + String (newRate));
  790. long err = asioObject->setSampleRate (newRate);
  791. if (err == ASE_NoClock && numClockSources > 0)
  792. {
  793. JUCE_ASIO_LOG ("trying to set a clock source..");
  794. Thread::sleep (10);
  795. err = asioObject->setClockSource (clocks[0].index);
  796. JUCE_ASIO_LOG_ERROR ("setClockSource2", err);
  797. Thread::sleep (10);
  798. err = asioObject->setSampleRate (newRate);
  799. }
  800. if (err == 0)
  801. currentSampleRate = newRate;
  802. // on fail, ignore the attempt to change rate, and run with the current one..
  803. }
  804. }
  805. void updateClockSources()
  806. {
  807. zeromem (clocks, sizeof (clocks));
  808. long numSources = numElementsInArray (clocks);
  809. asioObject->getClockSources (clocks, &numSources);
  810. numClockSources = (int) numSources;
  811. bool isSourceSet = false;
  812. // careful not to remove this loop because it does more than just logging!
  813. for (int i = 0; i < numClockSources; ++i)
  814. {
  815. String s ("clock: ");
  816. s += clocks[i].name;
  817. if (clocks[i].isCurrentSource)
  818. {
  819. isSourceSet = true;
  820. s << " (cur)";
  821. }
  822. JUCE_ASIO_LOG (s);
  823. }
  824. if (numClockSources > 1 && ! isSourceSet)
  825. {
  826. JUCE_ASIO_LOG ("setting clock source");
  827. long err = asioObject->setClockSource (clocks[0].index);
  828. JUCE_ASIO_LOG_ERROR ("setClockSource1", err);
  829. Thread::sleep (20);
  830. }
  831. else
  832. {
  833. if (numClockSources == 0)
  834. JUCE_ASIO_LOG ("no clock sources!");
  835. }
  836. }
  837. void readLatencies()
  838. {
  839. inputLatency = outputLatency = 0;
  840. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  841. JUCE_ASIO_LOG ("getLatencies() failed");
  842. else
  843. JUCE_ASIO_LOG ("Latencies: in = " + String ((int) inputLatency) + ", out = " + String ((int) outputLatency));
  844. }
  845. void createDummyBuffers (long preferredSize)
  846. {
  847. numActiveInputChans = 0;
  848. numActiveOutputChans = 0;
  849. ASIOBufferInfo* info = bufferInfos;
  850. int numChans = 0;
  851. for (int i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  852. {
  853. info->isInput = 1;
  854. info->channelNum = i;
  855. info->buffers[0] = info->buffers[1] = nullptr;
  856. ++info;
  857. ++numChans;
  858. }
  859. const int outputBufferIndex = numChans;
  860. for (int i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  861. {
  862. info->isInput = 0;
  863. info->channelNum = i;
  864. info->buffers[0] = info->buffers[1] = nullptr;
  865. ++info;
  866. ++numChans;
  867. }
  868. setCallbackFunctions();
  869. JUCE_ASIO_LOG ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  870. if (preferredSize > 0)
  871. {
  872. long err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  873. JUCE_ASIO_LOG_ERROR ("dummy buffers", err);
  874. }
  875. long newInps = 0, newOuts = 0;
  876. asioObject->getChannels (&newInps, &newOuts);
  877. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  878. {
  879. totalNumInputChans = newInps;
  880. totalNumOutputChans = newOuts;
  881. JUCE_ASIO_LOG (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  882. }
  883. updateSampleRates();
  884. reloadChannelNames();
  885. for (int i = 0; i < totalNumOutputChans; ++i)
  886. {
  887. ASIOChannelInfo channelInfo = { 0 };
  888. channelInfo.channel = i;
  889. channelInfo.isInput = 0;
  890. asioObject->getChannelInfo (&channelInfo);
  891. outputFormat[i] = ASIOSampleFormat (channelInfo.type);
  892. if (i < 2)
  893. {
  894. // clear the channels that are used with the dummy stuff
  895. outputFormat[i].clear (bufferInfos [outputBufferIndex + i].buffers[0], preferredBufferSize);
  896. outputFormat[i].clear (bufferInfos [outputBufferIndex + i].buffers[1], preferredBufferSize);
  897. }
  898. }
  899. }
  900. void removeCurrentDriver()
  901. {
  902. if (asioObject != nullptr)
  903. {
  904. asioObject->Release();
  905. asioObject = nullptr;
  906. }
  907. }
  908. bool loadDriver()
  909. {
  910. removeCurrentDriver();
  911. bool crashed = false;
  912. bool ok = tryCreatingDriver (crashed);
  913. if (crashed)
  914. JUCE_ASIO_LOG ("** Driver crashed while being opened");
  915. return ok;
  916. }
  917. bool tryCreatingDriver (bool& crashed)
  918. {
  919. #if ! JUCE_MINGW
  920. __try
  921. #endif
  922. {
  923. return CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  924. classId, (void**) &asioObject) == S_OK;
  925. }
  926. #if ! JUCE_MINGW
  927. __except (EXCEPTION_EXECUTE_HANDLER) { crashed = true; }
  928. return false;
  929. #endif
  930. }
  931. String getLastDriverError() const
  932. {
  933. jassert (asioObject != nullptr);
  934. char buffer [512] = { 0 };
  935. asioObject->getErrorMessage (buffer);
  936. return String (buffer, sizeof (buffer) - 1);
  937. }
  938. String initDriver()
  939. {
  940. if (asioObject == nullptr)
  941. return "No Driver";
  942. const bool initOk = !! asioObject->init (juce_messageWindowHandle);
  943. String driverError;
  944. // Get error message if init() failed, or if it's a buggy Denon driver,
  945. // which returns true from init() even when it fails.
  946. if ((! initOk) || getName().containsIgnoreCase ("denon dj"))
  947. driverError = getLastDriverError();
  948. if ((! initOk) && driverError.isEmpty())
  949. driverError = "Driver failed to initialise";
  950. if (driverError.isEmpty())
  951. {
  952. char buffer [512];
  953. asioObject->getDriverName (buffer); // just in case any flimsy drivers expect this to be called..
  954. }
  955. return driverError;
  956. }
  957. String openDevice()
  958. {
  959. // open the device and get its info..
  960. JUCE_ASIO_LOG ("opening device: " + getName());
  961. needToReset = false;
  962. outputChannelNames.clear();
  963. inputChannelNames.clear();
  964. bufferSizes.clear();
  965. sampleRates.clear();
  966. deviceIsOpen = false;
  967. totalNumInputChans = 0;
  968. totalNumOutputChans = 0;
  969. numActiveInputChans = 0;
  970. numActiveOutputChans = 0;
  971. xruns = 0;
  972. currentCallback = nullptr;
  973. error.clear();
  974. if (getName().isEmpty())
  975. return error;
  976. long err = 0;
  977. if (loadDriver())
  978. {
  979. if ((error = initDriver()).isEmpty())
  980. {
  981. numActiveInputChans = 0;
  982. numActiveOutputChans = 0;
  983. totalNumInputChans = 0;
  984. totalNumOutputChans = 0;
  985. if (asioObject != nullptr
  986. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  987. {
  988. JUCE_ASIO_LOG (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  989. const int chansToAllocate = totalNumInputChans + totalNumOutputChans + 4;
  990. bufferInfos.calloc (chansToAllocate);
  991. inBuffers.calloc (chansToAllocate);
  992. outBuffers.calloc (chansToAllocate);
  993. inputFormat.calloc (chansToAllocate);
  994. outputFormat.calloc (chansToAllocate);
  995. if ((err = refreshBufferSizes()) == 0)
  996. {
  997. addBufferSizes (minBufferSize, maxBufferSize, preferredBufferSize, bufferGranularity);
  998. double currentRate = getSampleRate();
  999. if (currentRate < 1.0 || currentRate > 192001.0)
  1000. {
  1001. JUCE_ASIO_LOG ("setting default sample rate");
  1002. err = asioObject->setSampleRate (44100.0);
  1003. JUCE_ASIO_LOG_ERROR ("setting sample rate", err);
  1004. currentRate = getSampleRate();
  1005. }
  1006. currentSampleRate = currentRate;
  1007. postOutput = (asioObject->outputReady() == 0);
  1008. if (postOutput)
  1009. JUCE_ASIO_LOG ("outputReady true");
  1010. updateSampleRates();
  1011. readLatencies(); // ..doing these steps because cubase does so at this stage
  1012. createDummyBuffers (preferredBufferSize); // in initialisation, and some devices fail if we don't.
  1013. readLatencies();
  1014. // start and stop because cubase does it..
  1015. err = asioObject->start();
  1016. // ignore an error here, as it might start later after setting other stuff up
  1017. JUCE_ASIO_LOG_ERROR ("start", err);
  1018. Thread::sleep (80);
  1019. asioObject->stop();
  1020. }
  1021. else
  1022. {
  1023. error = "Can't detect buffer sizes";
  1024. }
  1025. }
  1026. else
  1027. {
  1028. error = "Can't detect asio channels";
  1029. }
  1030. }
  1031. }
  1032. else
  1033. {
  1034. error = "No such device";
  1035. }
  1036. if (error.isNotEmpty())
  1037. {
  1038. JUCE_ASIO_LOG_ERROR (error, err);
  1039. disposeBuffers();
  1040. removeCurrentDriver();
  1041. }
  1042. else
  1043. {
  1044. JUCE_ASIO_LOG ("device open");
  1045. }
  1046. deviceIsOpen = false;
  1047. needToReset = false;
  1048. stopTimer();
  1049. return error;
  1050. }
  1051. void disposeBuffers()
  1052. {
  1053. if (asioObject != nullptr && buffersCreated)
  1054. {
  1055. buffersCreated = false;
  1056. asioObject->disposeBuffers();
  1057. }
  1058. }
  1059. //==============================================================================
  1060. void JUCE_ASIOCALLBACK callback (const long index)
  1061. {
  1062. if (isStarted)
  1063. {
  1064. bufferIndex = index;
  1065. processBuffer();
  1066. }
  1067. else
  1068. {
  1069. if (postOutput && (asioObject != nullptr))
  1070. asioObject->outputReady();
  1071. }
  1072. calledback = true;
  1073. }
  1074. void processBuffer()
  1075. {
  1076. const ASIOBufferInfo* const infos = bufferInfos;
  1077. const int bi = bufferIndex;
  1078. const ScopedLock sl (callbackLock);
  1079. if (bi >= 0)
  1080. {
  1081. const int samps = currentBlockSizeSamples;
  1082. if (currentCallback != nullptr)
  1083. {
  1084. for (int i = 0; i < numActiveInputChans; ++i)
  1085. {
  1086. jassert (inBuffers[i] != nullptr);
  1087. inputFormat[i].convertToFloat (infos[i].buffers[bi], inBuffers[i], samps);
  1088. }
  1089. currentCallback->audioDeviceIOCallback (const_cast<const float**> (inBuffers.getData()), numActiveInputChans,
  1090. outBuffers, numActiveOutputChans, samps);
  1091. for (int i = 0; i < numActiveOutputChans; ++i)
  1092. {
  1093. jassert (outBuffers[i] != nullptr);
  1094. outputFormat[i].convertFromFloat (outBuffers[i], infos [numActiveInputChans + i].buffers[bi], samps);
  1095. }
  1096. }
  1097. else
  1098. {
  1099. for (int i = 0; i < numActiveOutputChans; ++i)
  1100. outputFormat[i].clear (infos[numActiveInputChans + i].buffers[bi], samps);
  1101. }
  1102. }
  1103. if (postOutput)
  1104. asioObject->outputReady();
  1105. }
  1106. long asioMessagesCallback (long selector, long value)
  1107. {
  1108. switch (selector)
  1109. {
  1110. case kAsioSelectorSupported:
  1111. if (value == kAsioResetRequest || value == kAsioEngineVersion || value == kAsioResyncRequest
  1112. || value == kAsioLatenciesChanged || value == kAsioSupportsInputMonitor || value == kAsioOverload)
  1113. return 1;
  1114. break;
  1115. case kAsioBufferSizeChange: JUCE_ASIO_LOG ("kAsioBufferSizeChange"); resetRequest(); return 1;
  1116. case kAsioResetRequest: JUCE_ASIO_LOG ("kAsioResetRequest"); resetRequest(); return 1;
  1117. case kAsioResyncRequest: JUCE_ASIO_LOG ("kAsioResyncRequest"); resetRequest(); return 1;
  1118. case kAsioLatenciesChanged: JUCE_ASIO_LOG ("kAsioLatenciesChanged"); return 1;
  1119. case kAsioEngineVersion: return 2;
  1120. case kAsioSupportsTimeInfo:
  1121. case kAsioSupportsTimeCode: return 0;
  1122. case kAsioOverload: xruns++; return 1;
  1123. }
  1124. return 0;
  1125. }
  1126. //==============================================================================
  1127. template <int deviceIndex>
  1128. struct ASIOCallbackFunctions
  1129. {
  1130. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback (ASIOTime*, long index, long)
  1131. {
  1132. if (currentASIODev[deviceIndex] != nullptr)
  1133. currentASIODev[deviceIndex]->callback (index);
  1134. return nullptr;
  1135. }
  1136. static void JUCE_ASIOCALLBACK bufferSwitchCallback (long index, long)
  1137. {
  1138. if (currentASIODev[deviceIndex] != nullptr)
  1139. currentASIODev[deviceIndex]->callback (index);
  1140. }
  1141. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, void*, double*)
  1142. {
  1143. return currentASIODev[deviceIndex] != nullptr
  1144. ? currentASIODev[deviceIndex]->asioMessagesCallback (selector, value)
  1145. : 0;
  1146. }
  1147. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  1148. {
  1149. if (currentASIODev[deviceIndex] != nullptr)
  1150. currentASIODev[deviceIndex]->resetRequest();
  1151. }
  1152. static void setCallbacks (ASIOCallbacks& callbacks) noexcept
  1153. {
  1154. callbacks.bufferSwitch = &bufferSwitchCallback;
  1155. callbacks.asioMessage = &asioMessagesCallback;
  1156. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback;
  1157. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  1158. }
  1159. static void setCallbacksForDevice (ASIOCallbacks& callbacks, ASIOAudioIODevice* device) noexcept
  1160. {
  1161. if (currentASIODev[deviceIndex] == device)
  1162. setCallbacks (callbacks);
  1163. else
  1164. ASIOCallbackFunctions<deviceIndex + 1>::setCallbacksForDevice (callbacks, device);
  1165. }
  1166. };
  1167. void setCallbackFunctions() noexcept
  1168. {
  1169. /**/ if (currentASIODev[0] == this) ASIOCallbackFunctions<0>::setCallbacks (callbacks);
  1170. else if (currentASIODev[1] == this) ASIOCallbackFunctions<1>::setCallbacks (callbacks);
  1171. else if (currentASIODev[2] == this) ASIOCallbackFunctions<2>::setCallbacks (callbacks);
  1172. else if (currentASIODev[3] == this) ASIOCallbackFunctions<3>::setCallbacks (callbacks);
  1173. else jassertfalse;
  1174. }
  1175. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice)
  1176. };
  1177. template <>
  1178. struct ASIOAudioIODevice::ASIOCallbackFunctions <sizeof(currentASIODev) / sizeof(currentASIODev[0])>
  1179. {
  1180. static void setCallbacksForDevice (ASIOCallbacks&, ASIOAudioIODevice*) noexcept {}
  1181. };
  1182. //==============================================================================
  1183. class ASIOAudioIODeviceType : public AudioIODeviceType
  1184. {
  1185. public:
  1186. ASIOAudioIODeviceType() : AudioIODeviceType ("ASIO") {}
  1187. //==============================================================================
  1188. void scanForDevices()
  1189. {
  1190. hasScanned = true;
  1191. deviceNames.clear();
  1192. classIds.clear();
  1193. HKEY hk = 0;
  1194. int index = 0;
  1195. if (RegOpenKey (HKEY_LOCAL_MACHINE, _T("software\\asio"), &hk) == ERROR_SUCCESS)
  1196. {
  1197. TCHAR name [256];
  1198. while (RegEnumKey (hk, index++, name, numElementsInArray (name)) == ERROR_SUCCESS)
  1199. addDriverInfo (name, hk);
  1200. RegCloseKey (hk);
  1201. }
  1202. }
  1203. StringArray getDeviceNames (bool /*wantInputNames*/) const
  1204. {
  1205. jassert (hasScanned); // need to call scanForDevices() before doing this
  1206. return deviceNames;
  1207. }
  1208. int getDefaultDeviceIndex (bool) const
  1209. {
  1210. jassert (hasScanned); // need to call scanForDevices() before doing this
  1211. for (int i = deviceNames.size(); --i >= 0;)
  1212. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  1213. return i; // asio4all is a safe choice for a default..
  1214. #if JUCE_DEBUG
  1215. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  1216. return 1; // (the digi m-box driver crashes the app when you run
  1217. // it in the debugger, which can be a bit annoying)
  1218. #endif
  1219. return 0;
  1220. }
  1221. static int findFreeSlot()
  1222. {
  1223. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  1224. if (currentASIODev[i] == 0)
  1225. return i;
  1226. jassertfalse; // unfortunately you can only have a finite number
  1227. // of ASIO devices open at the same time..
  1228. return -1;
  1229. }
  1230. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  1231. {
  1232. jassert (hasScanned); // need to call scanForDevices() before doing this
  1233. return d == nullptr ? -1 : deviceNames.indexOf (d->getName());
  1234. }
  1235. bool hasSeparateInputsAndOutputs() const { return false; }
  1236. AudioIODevice* createDevice (const String& outputDeviceName,
  1237. const String& inputDeviceName)
  1238. {
  1239. // ASIO can't open two different devices for input and output - they must be the same one.
  1240. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  1241. jassert (hasScanned); // need to call scanForDevices() before doing this
  1242. const String deviceName (outputDeviceName.isNotEmpty() ? outputDeviceName
  1243. : inputDeviceName);
  1244. const int index = deviceNames.indexOf (deviceName);
  1245. if (index >= 0)
  1246. {
  1247. const int freeSlot = findFreeSlot();
  1248. if (freeSlot >= 0)
  1249. return new ASIOAudioIODevice (this, deviceName,
  1250. classIds.getReference (index), freeSlot);
  1251. }
  1252. return nullptr;
  1253. }
  1254. void sendDeviceChangeToListeners()
  1255. {
  1256. callDeviceChangeListeners();
  1257. }
  1258. JUCE_DECLARE_WEAK_REFERENCEABLE (ASIOAudioIODeviceType)
  1259. private:
  1260. StringArray deviceNames;
  1261. Array<CLSID> classIds;
  1262. bool hasScanned = false;
  1263. //==============================================================================
  1264. static bool checkClassIsOk (const String& classId)
  1265. {
  1266. HKEY hk = 0;
  1267. bool ok = false;
  1268. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  1269. {
  1270. int index = 0;
  1271. TCHAR name [512];
  1272. while (RegEnumKey (hk, index++, name, numElementsInArray (name)) == ERROR_SUCCESS)
  1273. {
  1274. if (classId.equalsIgnoreCase (name))
  1275. {
  1276. HKEY subKey, pathKey;
  1277. if (RegOpenKeyEx (hk, name, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  1278. {
  1279. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  1280. {
  1281. TCHAR pathName [1024] = { 0 };
  1282. DWORD dtype = REG_SZ;
  1283. DWORD dsize = sizeof (pathName);
  1284. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  1285. // In older code, this used to check for the existence of the file, but there are situations
  1286. // where our process doesn't have access to it, but where the driver still loads ok..
  1287. ok = (pathName[0] != 0);
  1288. RegCloseKey (pathKey);
  1289. }
  1290. RegCloseKey (subKey);
  1291. }
  1292. break;
  1293. }
  1294. }
  1295. RegCloseKey (hk);
  1296. }
  1297. return ok;
  1298. }
  1299. //==============================================================================
  1300. void addDriverInfo (const String& keyName, HKEY hk)
  1301. {
  1302. HKEY subKey;
  1303. if (RegOpenKeyEx (hk, keyName.toWideCharPointer(), 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  1304. {
  1305. TCHAR buf [256] = { 0 };
  1306. DWORD dtype = REG_SZ;
  1307. DWORD dsize = sizeof (buf);
  1308. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  1309. {
  1310. if (dsize > 0 && checkClassIsOk (buf))
  1311. {
  1312. CLSID classId;
  1313. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  1314. {
  1315. dtype = REG_SZ;
  1316. dsize = sizeof (buf);
  1317. String deviceName;
  1318. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  1319. deviceName = buf;
  1320. else
  1321. deviceName = keyName;
  1322. JUCE_ASIO_LOG ("found " + deviceName);
  1323. deviceNames.add (deviceName);
  1324. classIds.add (classId);
  1325. }
  1326. }
  1327. RegCloseKey (subKey);
  1328. }
  1329. }
  1330. }
  1331. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType)
  1332. };
  1333. void sendASIODeviceChangeToListeners (ASIOAudioIODeviceType* type)
  1334. {
  1335. if (type != nullptr)
  1336. type->sendDeviceChangeToListeners();
  1337. }
  1338. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO()
  1339. {
  1340. return new ASIOAudioIODeviceType();
  1341. }
  1342. } // namespace juce