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.

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