The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1646 lines
54KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  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) ignoreUnused (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[16] = { 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. minBufferSize (0), maxBufferSize (0),
  286. preferredBufferSize (0),
  287. bufferGranularity (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. ::CoInitialize (nullptr);
  307. name = devName;
  308. inBuffers.calloc (4);
  309. outBuffers.calloc (4);
  310. jassert (currentASIODev [slotNumber] == nullptr);
  311. currentASIODev [slotNumber] = this;
  312. openDevice();
  313. }
  314. ~ASIOAudioIODevice()
  315. {
  316. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  317. if (currentASIODev[i] == this)
  318. currentASIODev[i] = nullptr;
  319. close();
  320. JUCE_ASIO_LOG ("closed");
  321. removeCurrentDriver();
  322. }
  323. void updateSampleRates()
  324. {
  325. // find a list of sample rates..
  326. Array<double> newRates;
  327. if (asioObject != nullptr)
  328. {
  329. const int possibleSampleRates[] = { 32000, 44100, 48000, 88200, 96000, 176400, 192000, 352800, 384000 };
  330. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  331. if (asioObject->canSampleRate ((double) possibleSampleRates[index]) == 0)
  332. newRates.add ((double) possibleSampleRates[index]);
  333. }
  334. if (newRates.isEmpty())
  335. {
  336. double cr = getSampleRate();
  337. JUCE_ASIO_LOG ("No sample rates supported - current rate: " + String ((int) cr));
  338. if (cr > 0)
  339. newRates.add ((int) cr);
  340. }
  341. if (sampleRates != newRates)
  342. {
  343. sampleRates.swapWith (newRates);
  344. #if JUCE_ASIO_DEBUGGING
  345. StringArray s;
  346. for (int i = 0; i < sampleRates.size(); ++i)
  347. s.add (String (sampleRates.getUnchecked(i)));
  348. JUCE_ASIO_LOG ("Rates: " + s.joinIntoString (" "));
  349. #endif
  350. }
  351. }
  352. StringArray getOutputChannelNames() override { return outputChannelNames; }
  353. StringArray getInputChannelNames() override { return inputChannelNames; }
  354. Array<double> getAvailableSampleRates() override { return sampleRates; }
  355. Array<int> getAvailableBufferSizes() override { return bufferSizes; }
  356. int getDefaultBufferSize() override { return preferredBufferSize; }
  357. String open (const BigInteger& inputChannels,
  358. const BigInteger& outputChannels,
  359. double sr, int bufferSizeSamples) override
  360. {
  361. if (isOpen())
  362. close();
  363. jassert (currentCallback == nullptr);
  364. if (bufferSizeSamples < 8 || bufferSizeSamples > 16384)
  365. shouldUsePreferredSize = true;
  366. if (asioObject == nullptr)
  367. {
  368. const String openingError (openDevice());
  369. if (asioObject == nullptr)
  370. return openingError;
  371. }
  372. isStarted = false;
  373. bufferIndex = -1;
  374. long err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans);
  375. jassert (err == ASE_OK);
  376. bufferSizeSamples = readBufferSizes (bufferSizeSamples);
  377. double sampleRate = sr;
  378. currentSampleRate = sampleRate;
  379. currentBlockSizeSamples = bufferSizeSamples;
  380. currentChansOut.clear();
  381. currentChansIn.clear();
  382. updateSampleRates();
  383. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  384. sampleRate = sampleRates[0];
  385. jassert (sampleRate != 0);
  386. if (sampleRate == 0)
  387. sampleRate = 44100.0;
  388. updateClockSources();
  389. currentSampleRate = getSampleRate();
  390. error.clear();
  391. buffersCreated = false;
  392. setSampleRate (sampleRate);
  393. // (need to get this again in case a sample rate change affected the channel count)
  394. err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans);
  395. jassert (err == ASE_OK);
  396. inBuffers.calloc (totalNumInputChans + 8);
  397. outBuffers.calloc (totalNumOutputChans + 8);
  398. if (needToReset)
  399. {
  400. JUCE_ASIO_LOG (" Resetting");
  401. removeCurrentDriver();
  402. loadDriver();
  403. String initError = initDriver();
  404. if (initError.isNotEmpty())
  405. JUCE_ASIO_LOG ("ASIOInit: " + initError);
  406. needToReset = false;
  407. }
  408. const int totalBuffers = resetBuffers (inputChannels, outputChannels);
  409. setCallbackFunctions();
  410. JUCE_ASIO_LOG ("disposing buffers");
  411. err = asioObject->disposeBuffers();
  412. JUCE_ASIO_LOG ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  413. err = asioObject->createBuffers (bufferInfos, totalBuffers, currentBlockSizeSamples, &callbacks);
  414. if (err != ASE_OK)
  415. {
  416. currentBlockSizeSamples = preferredBufferSize;
  417. JUCE_ASIO_LOG_ERROR ("create buffers 2", err);
  418. asioObject->disposeBuffers();
  419. err = asioObject->createBuffers (bufferInfos, totalBuffers, currentBlockSizeSamples, &callbacks);
  420. }
  421. if (err == ASE_OK)
  422. {
  423. buffersCreated = true;
  424. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  425. int n = 0;
  426. Array <int> types;
  427. currentBitDepth = 16;
  428. for (int i = 0; i < (int) totalNumInputChans; ++i)
  429. {
  430. if (inputChannels[i])
  431. {
  432. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  433. ASIOChannelInfo channelInfo = { 0 };
  434. channelInfo.channel = i;
  435. channelInfo.isInput = 1;
  436. asioObject->getChannelInfo (&channelInfo);
  437. types.addIfNotAlreadyThere (channelInfo.type);
  438. inputFormat[n] = ASIOSampleFormat (channelInfo.type);
  439. currentBitDepth = jmax (currentBitDepth, inputFormat[n].bitDepth);
  440. ++n;
  441. }
  442. }
  443. jassert (numActiveInputChans == n);
  444. n = 0;
  445. for (int i = 0; i < (int) totalNumOutputChans; ++i)
  446. {
  447. if (outputChannels[i])
  448. {
  449. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  450. ASIOChannelInfo channelInfo = { 0 };
  451. channelInfo.channel = i;
  452. channelInfo.isInput = 0;
  453. asioObject->getChannelInfo (&channelInfo);
  454. types.addIfNotAlreadyThere (channelInfo.type);
  455. outputFormat[n] = ASIOSampleFormat (channelInfo.type);
  456. currentBitDepth = jmax (currentBitDepth, outputFormat[n].bitDepth);
  457. ++n;
  458. }
  459. }
  460. jassert (numActiveOutputChans == n);
  461. for (int i = types.size(); --i >= 0;)
  462. JUCE_ASIO_LOG ("channel format: " + String (types[i]));
  463. jassert (n <= totalBuffers);
  464. for (int i = 0; i < numActiveOutputChans; ++i)
  465. {
  466. outputFormat[i].clear (bufferInfos [numActiveInputChans + i].buffers[0], currentBlockSizeSamples);
  467. outputFormat[i].clear (bufferInfos [numActiveInputChans + i].buffers[1], currentBlockSizeSamples);
  468. }
  469. readLatencies();
  470. refreshBufferSizes();
  471. deviceIsOpen = true;
  472. JUCE_ASIO_LOG ("starting");
  473. calledback = false;
  474. err = asioObject->start();
  475. if (err != 0)
  476. {
  477. deviceIsOpen = false;
  478. JUCE_ASIO_LOG ("stop on failure");
  479. Thread::sleep (10);
  480. asioObject->stop();
  481. error = "Can't start device";
  482. Thread::sleep (10);
  483. }
  484. else
  485. {
  486. int count = 300;
  487. while (--count > 0 && ! calledback)
  488. Thread::sleep (10);
  489. isStarted = true;
  490. if (! calledback)
  491. {
  492. error = "Device didn't start correctly";
  493. JUCE_ASIO_LOG ("no callbacks - stopping..");
  494. asioObject->stop();
  495. }
  496. }
  497. }
  498. else
  499. {
  500. error = "Can't create i/o buffers";
  501. }
  502. if (error.isNotEmpty())
  503. {
  504. JUCE_ASIO_LOG_ERROR (error, err);
  505. disposeBuffers();
  506. Thread::sleep (20);
  507. isStarted = false;
  508. deviceIsOpen = false;
  509. const String errorCopy (error);
  510. close(); // (this resets the error string)
  511. error = errorCopy;
  512. }
  513. needToReset = false;
  514. return error;
  515. }
  516. void close() override
  517. {
  518. error.clear();
  519. stopTimer();
  520. stop();
  521. if (asioObject != nullptr && deviceIsOpen)
  522. {
  523. const ScopedLock sl (callbackLock);
  524. deviceIsOpen = false;
  525. isStarted = false;
  526. needToReset = false;
  527. JUCE_ASIO_LOG ("stopping");
  528. if (asioObject != nullptr)
  529. {
  530. Thread::sleep (20);
  531. asioObject->stop();
  532. Thread::sleep (10);
  533. disposeBuffers();
  534. }
  535. Thread::sleep (10);
  536. }
  537. }
  538. bool isOpen() override { return deviceIsOpen || insideControlPanelModalLoop; }
  539. bool isPlaying() override { return asioObject != nullptr && currentCallback != nullptr; }
  540. int getCurrentBufferSizeSamples() override { return currentBlockSizeSamples; }
  541. double getCurrentSampleRate() override { return currentSampleRate; }
  542. int getCurrentBitDepth() override { return currentBitDepth; }
  543. BigInteger getActiveOutputChannels() const override { return currentChansOut; }
  544. BigInteger getActiveInputChannels() const override { return currentChansIn; }
  545. int getOutputLatencyInSamples() override { return outputLatency + currentBlockSizeSamples / 4; }
  546. int getInputLatencyInSamples() override { return inputLatency + currentBlockSizeSamples / 4; }
  547. void start (AudioIODeviceCallback* callback) override
  548. {
  549. if (callback != nullptr)
  550. {
  551. callback->audioDeviceAboutToStart (this);
  552. const ScopedLock sl (callbackLock);
  553. currentCallback = callback;
  554. }
  555. }
  556. void stop() override
  557. {
  558. AudioIODeviceCallback* const lastCallback = currentCallback;
  559. {
  560. const ScopedLock sl (callbackLock);
  561. currentCallback = nullptr;
  562. }
  563. if (lastCallback != nullptr)
  564. lastCallback->audioDeviceStopped();
  565. }
  566. String getLastError() { return error; }
  567. bool hasControlPanel() const { return true; }
  568. bool showControlPanel()
  569. {
  570. JUCE_ASIO_LOG ("showing control panel");
  571. bool done = false;
  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. insideControlPanelModalLoop = false;
  586. return done;
  587. }
  588. void resetRequest() noexcept
  589. {
  590. startTimer (500);
  591. }
  592. void timerCallback() override
  593. {
  594. if (! insideControlPanelModalLoop)
  595. {
  596. stopTimer();
  597. JUCE_ASIO_LOG ("restart request!");
  598. AudioIODeviceCallback* const oldCallback = currentCallback;
  599. close();
  600. needToReset = true;
  601. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  602. currentSampleRate, currentBlockSizeSamples);
  603. reloadChannelNames();
  604. if (oldCallback != nullptr)
  605. start (oldCallback);
  606. sendASIODeviceChangeToListeners (owner);
  607. }
  608. else
  609. {
  610. startTimer (100);
  611. }
  612. }
  613. private:
  614. //==============================================================================
  615. WeakReference<ASIOAudioIODeviceType> owner;
  616. IASIO* volatile asioObject;
  617. ASIOCallbacks callbacks;
  618. CLSID classId;
  619. String error;
  620. long totalNumInputChans, totalNumOutputChans;
  621. StringArray inputChannelNames, outputChannelNames;
  622. Array<double> sampleRates;
  623. Array<int> bufferSizes;
  624. long inputLatency, outputLatency;
  625. long minBufferSize, maxBufferSize, preferredBufferSize, bufferGranularity;
  626. ASIOClockSource clocks[32];
  627. int numClockSources;
  628. int volatile currentBlockSizeSamples;
  629. int volatile currentBitDepth;
  630. double volatile currentSampleRate;
  631. BigInteger currentChansOut, currentChansIn;
  632. AudioIODeviceCallback* volatile currentCallback;
  633. CriticalSection callbackLock;
  634. HeapBlock<ASIOBufferInfo> bufferInfos;
  635. HeapBlock<float*> inBuffers, outBuffers;
  636. HeapBlock<ASIOSampleFormat> inputFormat, outputFormat;
  637. WaitableEvent event1;
  638. HeapBlock<float> tempBuffer;
  639. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  640. bool deviceIsOpen, isStarted, buffersCreated;
  641. bool volatile calledback;
  642. bool volatile littleEndian, postOutput, needToReset;
  643. bool volatile insideControlPanelModalLoop;
  644. bool volatile shouldUsePreferredSize;
  645. //==============================================================================
  646. static String convertASIOString (char* const text, int length)
  647. {
  648. if (CharPointer_UTF8::isValidString (text, length))
  649. return String::fromUTF8 (text, length);
  650. WCHAR wideVersion [64] = { 0 };
  651. MultiByteToWideChar (CP_ACP, 0, text, length, wideVersion, numElementsInArray (wideVersion));
  652. return wideVersion;
  653. }
  654. String getChannelName (int index, bool isInput) const
  655. {
  656. ASIOChannelInfo channelInfo = { 0 };
  657. channelInfo.channel = index;
  658. channelInfo.isInput = isInput ? 1 : 0;
  659. asioObject->getChannelInfo (&channelInfo);
  660. return convertASIOString (channelInfo.name, sizeof (channelInfo.name));
  661. }
  662. void reloadChannelNames()
  663. {
  664. if (asioObject != nullptr
  665. && asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans) == ASE_OK)
  666. {
  667. inputChannelNames.clear();
  668. outputChannelNames.clear();
  669. for (int i = 0; i < totalNumInputChans; ++i)
  670. inputChannelNames.add (getChannelName (i, true));
  671. for (int i = 0; i < totalNumOutputChans; ++i)
  672. outputChannelNames.add (getChannelName (i, false));
  673. outputChannelNames.trim();
  674. inputChannelNames.trim();
  675. outputChannelNames.appendNumbersToDuplicates (false, true);
  676. inputChannelNames.appendNumbersToDuplicates (false, true);
  677. }
  678. }
  679. long refreshBufferSizes()
  680. {
  681. return asioObject->getBufferSize (&minBufferSize, &maxBufferSize, &preferredBufferSize, &bufferGranularity);
  682. }
  683. int readBufferSizes (int bufferSizeSamples)
  684. {
  685. minBufferSize = 0;
  686. maxBufferSize = 0;
  687. bufferGranularity = 0;
  688. long newPreferredSize = 0;
  689. if (asioObject->getBufferSize (&minBufferSize, &maxBufferSize, &newPreferredSize, &bufferGranularity) == ASE_OK)
  690. {
  691. if (preferredBufferSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredBufferSize)
  692. shouldUsePreferredSize = true;
  693. if (bufferSizeSamples < minBufferSize || bufferSizeSamples > maxBufferSize)
  694. shouldUsePreferredSize = true;
  695. preferredBufferSize = newPreferredSize;
  696. }
  697. // unfortunate workaround for certain drivers which crash if you make
  698. // dynamic changes to the buffer size...
  699. shouldUsePreferredSize = shouldUsePreferredSize || getName().containsIgnoreCase ("Digidesign");
  700. if (shouldUsePreferredSize)
  701. {
  702. JUCE_ASIO_LOG ("Using preferred size for buffer..");
  703. long err = refreshBufferSizes();
  704. if (err == ASE_OK)
  705. {
  706. bufferSizeSamples = (int) preferredBufferSize;
  707. }
  708. else
  709. {
  710. bufferSizeSamples = 1024;
  711. JUCE_ASIO_LOG_ERROR ("getBufferSize1", err);
  712. }
  713. shouldUsePreferredSize = false;
  714. }
  715. return bufferSizeSamples;
  716. }
  717. int resetBuffers (const BigInteger& inputChannels,
  718. const BigInteger& outputChannels)
  719. {
  720. numActiveInputChans = 0;
  721. numActiveOutputChans = 0;
  722. ASIOBufferInfo* info = bufferInfos;
  723. for (int i = 0; i < totalNumInputChans; ++i)
  724. {
  725. if (inputChannels[i])
  726. {
  727. currentChansIn.setBit (i);
  728. info->isInput = 1;
  729. info->channelNum = i;
  730. info->buffers[0] = info->buffers[1] = nullptr;
  731. ++info;
  732. ++numActiveInputChans;
  733. }
  734. }
  735. for (int i = 0; i < totalNumOutputChans; ++i)
  736. {
  737. if (outputChannels[i])
  738. {
  739. currentChansOut.setBit (i);
  740. info->isInput = 0;
  741. info->channelNum = i;
  742. info->buffers[0] = info->buffers[1] = nullptr;
  743. ++info;
  744. ++numActiveOutputChans;
  745. }
  746. }
  747. return numActiveInputChans + numActiveOutputChans;
  748. }
  749. void addBufferSizes (long minSize, long maxSize, long preferredSize, long granularity)
  750. {
  751. // find a list of buffer sizes..
  752. JUCE_ASIO_LOG (String ((int) minSize) + "->" + String ((int) maxSize) + ", "
  753. + String ((int) preferredSize) + ", " + String ((int) granularity));
  754. if (granularity >= 0)
  755. {
  756. granularity = jmax (16, (int) granularity);
  757. for (int i = jmax ((int) (minSize + 15) & ~15, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  758. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  759. }
  760. else if (granularity < 0)
  761. {
  762. for (int i = 0; i < 18; ++i)
  763. {
  764. const int s = (1 << i);
  765. if (s >= minSize && s <= maxSize)
  766. bufferSizes.add (s);
  767. }
  768. }
  769. bufferSizes.addIfNotAlreadyThere (preferredSize);
  770. bufferSizes.sort();
  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 (double 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], preferredBufferSize);
  890. outputFormat[i].clear (bufferInfos [outputBufferIndex + i].buffers[1], preferredBufferSize);
  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.clear();
  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 = refreshBufferSizes()) == 0)
  989. {
  990. addBufferSizes (minBufferSize, maxBufferSize, preferredBufferSize, bufferGranularity);
  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 (preferredBufferSize); // 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. long asioMessagesCallback (long selector, long value)
  1100. {
  1101. switch (selector)
  1102. {
  1103. case kAsioSelectorSupported:
  1104. if (value == kAsioResetRequest || value == kAsioEngineVersion || value == kAsioResyncRequest
  1105. || value == kAsioLatenciesChanged || value == kAsioSupportsInputMonitor)
  1106. return 1;
  1107. break;
  1108. case kAsioBufferSizeChange: JUCE_ASIO_LOG ("kAsioBufferSizeChange"); resetRequest(); return 1;
  1109. case kAsioResetRequest: JUCE_ASIO_LOG ("kAsioResetRequest"); resetRequest(); return 1;
  1110. case kAsioResyncRequest: JUCE_ASIO_LOG ("kAsioResyncRequest"); resetRequest(); return 1;
  1111. case kAsioLatenciesChanged: JUCE_ASIO_LOG ("kAsioLatenciesChanged"); return 1;
  1112. case kAsioEngineVersion: return 2;
  1113. case kAsioSupportsTimeInfo:
  1114. case kAsioSupportsTimeCode: return 0;
  1115. }
  1116. return 0;
  1117. }
  1118. //==============================================================================
  1119. template <int deviceIndex>
  1120. struct ASIOCallbackFunctions
  1121. {
  1122. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback (ASIOTime*, long index, long)
  1123. {
  1124. if (currentASIODev[deviceIndex] != nullptr)
  1125. currentASIODev[deviceIndex]->callback (index);
  1126. return nullptr;
  1127. }
  1128. static void JUCE_ASIOCALLBACK bufferSwitchCallback (long index, long)
  1129. {
  1130. if (currentASIODev[deviceIndex] != nullptr)
  1131. currentASIODev[deviceIndex]->callback (index);
  1132. }
  1133. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, void*, double*)
  1134. {
  1135. return currentASIODev[deviceIndex] != nullptr
  1136. ? currentASIODev[deviceIndex]->asioMessagesCallback (selector, value)
  1137. : 0;
  1138. }
  1139. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  1140. {
  1141. if (currentASIODev[deviceIndex] != nullptr)
  1142. currentASIODev[deviceIndex]->resetRequest();
  1143. }
  1144. static void setCallbacks (ASIOCallbacks& callbacks) noexcept
  1145. {
  1146. callbacks.bufferSwitch = &bufferSwitchCallback;
  1147. callbacks.asioMessage = &asioMessagesCallback;
  1148. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback;
  1149. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  1150. }
  1151. static void setCallbacksForDevice (ASIOCallbacks& callbacks, ASIOAudioIODevice* device) noexcept
  1152. {
  1153. if (currentASIODev[deviceIndex] == device)
  1154. setCallbacks (callbacks);
  1155. else
  1156. ASIOCallbackFunctions<deviceIndex + 1>::setCallbacksForDevice (callbacks, device);
  1157. }
  1158. };
  1159. void setCallbackFunctions() noexcept
  1160. {
  1161. /**/ if (currentASIODev[0] == this) ASIOCallbackFunctions<0>::setCallbacks (callbacks);
  1162. else if (currentASIODev[1] == this) ASIOCallbackFunctions<1>::setCallbacks (callbacks);
  1163. else if (currentASIODev[2] == this) ASIOCallbackFunctions<2>::setCallbacks (callbacks);
  1164. else if (currentASIODev[3] == this) ASIOCallbackFunctions<3>::setCallbacks (callbacks);
  1165. else jassertfalse;
  1166. }
  1167. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice)
  1168. };
  1169. template <>
  1170. struct ASIOAudioIODevice::ASIOCallbackFunctions <sizeof(currentASIODev) / sizeof(currentASIODev[0])>
  1171. {
  1172. static void setCallbacksForDevice (ASIOCallbacks&, ASIOAudioIODevice*) noexcept {}
  1173. };
  1174. //==============================================================================
  1175. class ASIOAudioIODeviceType : public AudioIODeviceType
  1176. {
  1177. public:
  1178. ASIOAudioIODeviceType()
  1179. : AudioIODeviceType ("ASIO"),
  1180. hasScanned (false)
  1181. {
  1182. }
  1183. ~ASIOAudioIODeviceType()
  1184. {
  1185. masterReference.clear();
  1186. }
  1187. //==============================================================================
  1188. void scanForDevices()
  1189. {
  1190. hasScanned = true;
  1191. deviceNames.clear();
  1192. classIds.clear();
  1193. HKEY hk = 0;
  1194. int index = 0;
  1195. if (RegOpenKey (HKEY_LOCAL_MACHINE, _T("software\\asio"), &hk) == ERROR_SUCCESS)
  1196. {
  1197. TCHAR name [256];
  1198. while (RegEnumKey (hk, index++, name, numElementsInArray (name)) == ERROR_SUCCESS)
  1199. addDriverInfo (name, hk);
  1200. RegCloseKey (hk);
  1201. }
  1202. }
  1203. StringArray getDeviceNames (bool /*wantInputNames*/) const
  1204. {
  1205. jassert (hasScanned); // need to call scanForDevices() before doing this
  1206. return deviceNames;
  1207. }
  1208. int getDefaultDeviceIndex (bool) const
  1209. {
  1210. jassert (hasScanned); // need to call scanForDevices() before doing this
  1211. for (int i = deviceNames.size(); --i >= 0;)
  1212. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  1213. return i; // asio4all is a safe choice for a default..
  1214. #if JUCE_DEBUG
  1215. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  1216. return 1; // (the digi m-box driver crashes the app when you run
  1217. // it in the debugger, which can be a bit annoying)
  1218. #endif
  1219. return 0;
  1220. }
  1221. static int findFreeSlot()
  1222. {
  1223. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  1224. if (currentASIODev[i] == 0)
  1225. return i;
  1226. jassertfalse; // unfortunately you can only have a finite number
  1227. // of ASIO devices open at the same time..
  1228. return -1;
  1229. }
  1230. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  1231. {
  1232. jassert (hasScanned); // need to call scanForDevices() before doing this
  1233. return d == nullptr ? -1 : deviceNames.indexOf (d->getName());
  1234. }
  1235. bool hasSeparateInputsAndOutputs() const { return false; }
  1236. AudioIODevice* createDevice (const String& outputDeviceName,
  1237. const String& inputDeviceName)
  1238. {
  1239. // ASIO can't open two different devices for input and output - they must be the same one.
  1240. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  1241. jassert (hasScanned); // need to call scanForDevices() before doing this
  1242. const String deviceName (outputDeviceName.isNotEmpty() ? outputDeviceName
  1243. : inputDeviceName);
  1244. const int index = deviceNames.indexOf (deviceName);
  1245. if (index >= 0)
  1246. {
  1247. const int freeSlot = findFreeSlot();
  1248. if (freeSlot >= 0)
  1249. return new ASIOAudioIODevice (this, deviceName,
  1250. classIds.getReference (index), freeSlot);
  1251. }
  1252. return nullptr;
  1253. }
  1254. void sendDeviceChangeToListeners()
  1255. {
  1256. callDeviceChangeListeners();
  1257. }
  1258. WeakReference<ASIOAudioIODeviceType>::Master masterReference;
  1259. private:
  1260. StringArray deviceNames;
  1261. Array<CLSID> classIds;
  1262. bool hasScanned;
  1263. //==============================================================================
  1264. static bool checkClassIsOk (const String& classId)
  1265. {
  1266. HKEY hk = 0;
  1267. bool ok = false;
  1268. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  1269. {
  1270. int index = 0;
  1271. TCHAR name [512];
  1272. while (RegEnumKey (hk, index++, name, numElementsInArray (name)) == ERROR_SUCCESS)
  1273. {
  1274. if (classId.equalsIgnoreCase (name))
  1275. {
  1276. HKEY subKey, pathKey;
  1277. if (RegOpenKeyEx (hk, name, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  1278. {
  1279. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  1280. {
  1281. TCHAR pathName [1024] = { 0 };
  1282. DWORD dtype = REG_SZ;
  1283. DWORD dsize = sizeof (pathName);
  1284. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  1285. // In older code, this used to check for the existence of the file, but there are situations
  1286. // where our process doesn't have access to it, but where the driver still loads ok..
  1287. ok = (pathName[0] != 0);
  1288. RegCloseKey (pathKey);
  1289. }
  1290. RegCloseKey (subKey);
  1291. }
  1292. break;
  1293. }
  1294. }
  1295. RegCloseKey (hk);
  1296. }
  1297. return ok;
  1298. }
  1299. //==============================================================================
  1300. void addDriverInfo (const String& keyName, HKEY hk)
  1301. {
  1302. HKEY subKey;
  1303. if (RegOpenKeyEx (hk, keyName.toWideCharPointer(), 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  1304. {
  1305. TCHAR buf [256] = { 0 };
  1306. DWORD dtype = REG_SZ;
  1307. DWORD dsize = sizeof (buf);
  1308. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  1309. {
  1310. if (dsize > 0 && checkClassIsOk (buf))
  1311. {
  1312. CLSID classId;
  1313. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  1314. {
  1315. dtype = REG_SZ;
  1316. dsize = sizeof (buf);
  1317. String deviceName;
  1318. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  1319. deviceName = buf;
  1320. else
  1321. deviceName = keyName;
  1322. JUCE_ASIO_LOG ("found " + deviceName);
  1323. deviceNames.add (deviceName);
  1324. classIds.add (classId);
  1325. }
  1326. }
  1327. RegCloseKey (subKey);
  1328. }
  1329. }
  1330. }
  1331. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType)
  1332. };
  1333. void sendASIODeviceChangeToListeners (ASIOAudioIODeviceType* type)
  1334. {
  1335. if (type != nullptr)
  1336. type->sendDeviceChangeToListeners();
  1337. }
  1338. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO()
  1339. {
  1340. return new ASIOAudioIODeviceType();
  1341. }