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.

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