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

1631 lines
54KB

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