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.

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