The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

1632 lines
55KB

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