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.

1616 lines
54KB

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