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.

1949 lines
61KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. #include "win32_headers.h"
  24. #if JUCE_ASIO
  25. //==============================================================================
  26. /*
  27. This is very frustrating - we only need to use a handful of definitions from
  28. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  29. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  30. implementation...
  31. ..unfortunately that would break Steinberg's license agreement for use of
  32. their SDK, so I'm not allowed to do this.
  33. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  34. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  35. (see www.steinberg.net/Steinberg/Developers.asp).
  36. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  37. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  38. if you prefer). Make sure that your header search path will find the
  39. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  40. files are actually needed - so to simplify things, you could just copy
  41. these into your JUCE directory).
  42. */
  43. #include "iasiodrv.h" // if you're compiling and this line causes an error because
  44. // you don't have the ASIO SDK installed, you can disable ASIO
  45. // support by commenting-out the "#define JUCE_ASIO" line in
  46. // juce_Config.h
  47. #include "../../../src/juce_core/basics/juce_StandardHeader.h"
  48. BEGIN_JUCE_NAMESPACE
  49. #include "../../../src/juce_appframework/audio/devices/juce_AudioIODeviceType.h"
  50. #include "../../../src/juce_core/threads/juce_ScopedLock.h"
  51. #include "../../../src/juce_appframework/gui/components/juce_Component.h"
  52. #include "../../../src/juce_core/basics/juce_Time.h"
  53. #include "../../../src/juce_core/threads/juce_Thread.h"
  54. #include "../../../src/juce_appframework/events/juce_Timer.h"
  55. #include "../../../src/juce_appframework/events/juce_MessageManager.h"
  56. //==============================================================================
  57. // #define ASIO_DEBUGGING
  58. #ifdef ASIO_DEBUGGING
  59. #define log(a) { Logger::writeToLog (a); DBG (a) }
  60. #else
  61. #define log(a) {}
  62. #endif
  63. //==============================================================================
  64. #ifdef ASIO_DEBUGGING
  65. static void logError (const String& context, long error)
  66. {
  67. String err ("unknown error");
  68. if (error == ASE_NotPresent)
  69. err = "Not Present";
  70. else if (error == ASE_HWMalfunction)
  71. err = "Hardware Malfunction";
  72. else if (error == ASE_InvalidParameter)
  73. err = "Invalid Parameter";
  74. else if (error == ASE_InvalidMode)
  75. err = "Invalid Mode";
  76. else if (error == ASE_SPNotAdvancing)
  77. err = "Sample position not advancing";
  78. else if (error == ASE_NoClock)
  79. err = "No Clock";
  80. else if (error == ASE_NoMemory)
  81. err = "Out of memory";
  82. log (T("!!error: ") + context + T(" - ") + err);
  83. }
  84. #else
  85. #define logError(a, b) {}
  86. #endif
  87. //==============================================================================
  88. class ASIOAudioIODevice;
  89. static ASIOAudioIODevice* volatile currentASIODev = 0;
  90. static IASIO* volatile asioObject = 0;
  91. static const int maxASIOChannels = 160;
  92. static ASIOCallbacks callbacks;
  93. static ASIOBufferInfo bufferInfos[64];
  94. static bool volatile insideControlPanelModalLoop = false;
  95. static bool volatile shouldUsePreferredSize = false;
  96. //==============================================================================
  97. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  98. private Thread,
  99. private Timer
  100. {
  101. public:
  102. Component ourWindow;
  103. ASIOAudioIODevice (const String& name_, CLSID classId_)
  104. : AudioIODevice (name_, T("ASIO")),
  105. Thread ("Juce ASIO"),
  106. classId (classId_),
  107. currentBitDepth (16),
  108. currentSampleRate (0),
  109. tempBuffer (0),
  110. isOpen_ (false),
  111. isStarted (false),
  112. postOutput (true)
  113. {
  114. name = name_;
  115. ourWindow.addToDesktop (0);
  116. windowHandle = ourWindow.getWindowHandle();
  117. jassert (currentASIODev == 0);
  118. currentASIODev = this;
  119. shouldUseThread = false;
  120. openDevice();
  121. }
  122. ~ASIOAudioIODevice()
  123. {
  124. jassert (currentASIODev == this);
  125. if (currentASIODev == this)
  126. currentASIODev = 0;
  127. close();
  128. log ("ASIO - exiting");
  129. removeCurrentDriver();
  130. juce_free (tempBuffer);
  131. if (isUsingThread)
  132. {
  133. signalThreadShouldExit();
  134. event1.signal();
  135. stopThread (3000);
  136. }
  137. }
  138. void updateSampleRates()
  139. {
  140. // find a list of sample rates..
  141. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  142. sampleRates.clear();
  143. if (asioObject != 0)
  144. {
  145. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  146. {
  147. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  148. if (err == 0)
  149. {
  150. sampleRates.add ((int) possibleSampleRates[index]);
  151. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  152. }
  153. else if (err != ASE_NoClock)
  154. {
  155. logError (T("CanSampleRate"), err);
  156. }
  157. }
  158. if (sampleRates.size() == 0)
  159. {
  160. double cr = 0;
  161. const long err = asioObject->getSampleRate (&cr);
  162. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  163. if (err == 0)
  164. sampleRates.add ((int) cr);
  165. }
  166. }
  167. }
  168. const StringArray getOutputChannelNames()
  169. {
  170. return outputChannelNames;
  171. }
  172. const StringArray getInputChannelNames()
  173. {
  174. return inputChannelNames;
  175. }
  176. int getNumSampleRates()
  177. {
  178. return sampleRates.size();
  179. }
  180. double getSampleRate (int index)
  181. {
  182. return sampleRates [index];
  183. }
  184. int getNumBufferSizesAvailable()
  185. {
  186. return bufferSizes.size();
  187. }
  188. int getBufferSizeSamples (int index)
  189. {
  190. return bufferSizes [index];
  191. }
  192. int getDefaultBufferSize()
  193. {
  194. return preferredSize;
  195. }
  196. const String open (const BitArray& inputChannels,
  197. const BitArray& outputChannels,
  198. double sr,
  199. int bufferSizeSamples)
  200. {
  201. close();
  202. currentCallback = 0;
  203. if (bufferSizeSamples <= 0)
  204. shouldUsePreferredSize = true;
  205. if (asioObject == 0 || ! isASIOOpen)
  206. {
  207. log ("Warning: device not open");
  208. const String err (openDevice());
  209. if (asioObject == 0 || ! isASIOOpen)
  210. return err;
  211. }
  212. isStarted = false;
  213. bufferIndex = -1;
  214. long err = 0;
  215. long newPreferredSize = 0;
  216. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  217. minSize = 0;
  218. maxSize = 0;
  219. newPreferredSize = 0;
  220. granularity = 0;
  221. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  222. {
  223. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  224. shouldUsePreferredSize = true;
  225. preferredSize = newPreferredSize;
  226. }
  227. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  228. // dynamic changes to the buffer size...
  229. shouldUsePreferredSize = shouldUsePreferredSize
  230. || getName().containsIgnoreCase (T("Digidesign"));
  231. if (shouldUsePreferredSize)
  232. {
  233. log ("Using preferred size for buffer..");
  234. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  235. {
  236. bufferSizeSamples = preferredSize;
  237. }
  238. else
  239. {
  240. bufferSizeSamples = 1024;
  241. logError ("GetBufferSize1", err);
  242. }
  243. shouldUsePreferredSize = false;
  244. }
  245. int sampleRate = roundDoubleToInt (sr);
  246. currentSampleRate = sampleRate;
  247. currentBlockSizeSamples = bufferSizeSamples;
  248. currentChansOut = outputChannels;
  249. currentChansIn = inputChannels;
  250. updateSampleRates();
  251. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  252. sampleRate = sampleRates[0];
  253. jassert (sampleRate != 0);
  254. if (sampleRate == 0)
  255. sampleRate = 44100;
  256. long numSources = 32;
  257. ASIOClockSource clocks[32];
  258. zeromem (clocks, sizeof (clocks));
  259. asioObject->getClockSources (clocks, &numSources);
  260. bool isSourceSet = false;
  261. // careful not to remove this loop because it does more than just logging!
  262. int i;
  263. for (i = 0; i < numSources; ++i)
  264. {
  265. String s ("clock: ");
  266. s += clocks[i].name;
  267. if (clocks[i].isCurrentSource)
  268. {
  269. isSourceSet = true;
  270. s << " (cur)";
  271. }
  272. log (s);
  273. }
  274. if (numSources > 1 && ! isSourceSet)
  275. {
  276. log ("setting clock source");
  277. asioObject->setClockSource (clocks[0].index);
  278. Thread::sleep (20);
  279. }
  280. else
  281. {
  282. if (numSources == 0)
  283. {
  284. log ("ASIO - no clock sources!");
  285. }
  286. }
  287. double cr = 0;
  288. err = asioObject->getSampleRate (&cr);
  289. if (err == 0)
  290. {
  291. currentSampleRate = cr;
  292. }
  293. else
  294. {
  295. logError ("GetSampleRate", err);
  296. currentSampleRate = 0;
  297. }
  298. error = String::empty;
  299. needToReset = false;
  300. isReSync = false;
  301. err = 0;
  302. bool buffersCreated = false;
  303. if (currentSampleRate != sampleRate)
  304. {
  305. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  306. err = asioObject->setSampleRate (sampleRate);
  307. if (err == ASE_NoClock && numSources > 0)
  308. {
  309. log ("trying to set a clock source..");
  310. Thread::sleep (10);
  311. err = asioObject->setClockSource (clocks[0].index);
  312. if (err != 0)
  313. {
  314. logError ("SetClock", err);
  315. }
  316. Thread::sleep (10);
  317. err = asioObject->setSampleRate (sampleRate);
  318. }
  319. }
  320. if (err == 0)
  321. {
  322. currentSampleRate = sampleRate;
  323. if (needToReset)
  324. {
  325. if (isReSync)
  326. {
  327. log ("Resync request");
  328. }
  329. log ("! Resetting ASIO after sample rate change");
  330. removeCurrentDriver();
  331. loadDriver();
  332. const String error (initDriver());
  333. if (error.isNotEmpty())
  334. {
  335. log (T("ASIOInit: ") + error);
  336. }
  337. needToReset = false;
  338. isReSync = false;
  339. }
  340. numActiveInputChans = 0;
  341. numActiveOutputChans = 0;
  342. ASIOBufferInfo* info = bufferInfos;
  343. int i;
  344. for (i = 0; i < numInputs; ++i)
  345. {
  346. if (inputChannels[i])
  347. {
  348. info->isInput = 1;
  349. info->channelNum = i;
  350. info->buffers[0] = info->buffers[1] = 0;
  351. ++info;
  352. ++numActiveInputChans;
  353. }
  354. }
  355. for (i = 0; i < numOutputs; ++i)
  356. {
  357. if (outputChannels[i])
  358. {
  359. info->isInput = 0;
  360. info->channelNum = i;
  361. info->buffers[0] = info->buffers[1] = 0;
  362. ++info;
  363. ++numActiveOutputChans;
  364. }
  365. }
  366. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  367. callbacks.bufferSwitch = &bufferSwitchCallback;
  368. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  369. callbacks.asioMessage = &asioMessagesCallback;
  370. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback;
  371. log ("disposing buffers");
  372. err = asioObject->disposeBuffers();
  373. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  374. err = asioObject->createBuffers (bufferInfos,
  375. totalBuffers,
  376. currentBlockSizeSamples,
  377. &callbacks);
  378. if (err != 0)
  379. {
  380. currentBlockSizeSamples = preferredSize;
  381. logError ("create buffers 2", err);
  382. asioObject->disposeBuffers();
  383. err = asioObject->createBuffers (bufferInfos,
  384. totalBuffers,
  385. currentBlockSizeSamples,
  386. &callbacks);
  387. }
  388. if (err == 0)
  389. {
  390. buffersCreated = true;
  391. jassert (! isThreadRunning());
  392. juce_free (tempBuffer);
  393. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  394. int n = 0;
  395. Array <int> types;
  396. currentBitDepth = 16;
  397. for (i = 0; i < jmin (numInputs, maxASIOChannels); ++i)
  398. {
  399. if (inputChannels[i])
  400. {
  401. inBuffers[i] = tempBuffer + (currentBlockSizeSamples * n++);
  402. ASIOChannelInfo channelInfo;
  403. zerostruct (channelInfo);
  404. channelInfo.channel = i;
  405. channelInfo.isInput = 1;
  406. asioObject->getChannelInfo (&channelInfo);
  407. types.addIfNotAlreadyThere (channelInfo.type);
  408. typeToFormatParameters (channelInfo.type,
  409. inputChannelBitDepths[i],
  410. inputChannelBytesPerSample[i],
  411. inputChannelIsFloat[i],
  412. inputChannelLittleEndian[i]);
  413. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[i]);
  414. }
  415. else
  416. {
  417. inBuffers[i] = 0;
  418. }
  419. }
  420. for (i = 0; i < jmin (numOutputs, maxASIOChannels); ++i)
  421. {
  422. if (outputChannels[i])
  423. {
  424. outBuffers[i] = tempBuffer + (currentBlockSizeSamples * n++);
  425. ASIOChannelInfo channelInfo;
  426. zerostruct (channelInfo);
  427. channelInfo.channel = i;
  428. channelInfo.isInput = 0;
  429. asioObject->getChannelInfo (&channelInfo);
  430. types.addIfNotAlreadyThere (channelInfo.type);
  431. typeToFormatParameters (channelInfo.type,
  432. outputChannelBitDepths[i],
  433. outputChannelBytesPerSample[i],
  434. outputChannelIsFloat[i],
  435. outputChannelLittleEndian[i]);
  436. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[i]);
  437. }
  438. else
  439. {
  440. outBuffers[i] = 0;
  441. }
  442. }
  443. for (i = types.size(); --i >= 0;)
  444. {
  445. log (T("channel format: ") + String (types[i]));
  446. }
  447. jassert (n <= totalBuffers);
  448. n = numActiveInputChans;
  449. for (i = 0; i < numOutputs; ++i)
  450. {
  451. if (outputChannels[i])
  452. {
  453. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  454. if (bufferInfos[n].buffers[0] == 0
  455. || bufferInfos[n].buffers[1] == 0)
  456. {
  457. log ("!! Null buffers");
  458. }
  459. else
  460. {
  461. zeromem (bufferInfos[n].buffers[0], size);
  462. zeromem (bufferInfos[n].buffers[1], size);
  463. }
  464. ++n;
  465. }
  466. }
  467. jassert (n <= totalBuffers);
  468. inputLatency = outputLatency = 0;
  469. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  470. {
  471. log ("ASIO - no latencies");
  472. }
  473. else
  474. {
  475. log (T("ASIO latencies: ")
  476. + String ((int) outputLatency)
  477. + T(", ")
  478. + String ((int) inputLatency));
  479. }
  480. isOpen_ = true;
  481. isThreadReady = false;
  482. if (isUsingThread)
  483. {
  484. event1.wait (1); // reset the event in case it was flipped by a callback from the ASIO->start call in openDevice()
  485. startThread (8);
  486. int count = 5000;
  487. while (--count > 0 && ! isThreadReady)
  488. sleep (1);
  489. }
  490. if (isUsingThread && ! isThreadRunning())
  491. {
  492. error = "Can't start thread!";
  493. }
  494. else
  495. {
  496. log ("starting ASIO");
  497. calledback = false;
  498. err = asioObject->start();
  499. if (err != 0)
  500. {
  501. if (isUsingThread)
  502. {
  503. signalThreadShouldExit();
  504. event1.signal();
  505. stopThread (3000);
  506. }
  507. isOpen_ = false;
  508. log ("ASIO - stop on failure");
  509. Thread::sleep (10);
  510. asioObject->stop();
  511. error = "Can't start device";
  512. Thread::sleep (10);
  513. }
  514. else
  515. {
  516. int count = 300;
  517. while (--count > 0 && ! calledback)
  518. Thread::sleep (10);
  519. isStarted = true;
  520. if (! calledback)
  521. {
  522. error = "Device didn't start correctly";
  523. log ("ASIO didn't callback - stopping..");
  524. asioObject->stop();
  525. }
  526. }
  527. }
  528. }
  529. else
  530. {
  531. error = "Can't create i/o buffers";
  532. }
  533. }
  534. else
  535. {
  536. error = "Can't set sample rate: ";
  537. error << sampleRate;
  538. }
  539. if (error.isNotEmpty())
  540. {
  541. logError (error, err);
  542. if (asioObject != 0 && buffersCreated)
  543. asioObject->disposeBuffers();
  544. Thread::sleep (20);
  545. isStarted = false;
  546. isOpen_ = false;
  547. close();
  548. }
  549. needToReset = false;
  550. isReSync = false;
  551. return error;
  552. }
  553. void close()
  554. {
  555. error = String::empty;
  556. stopTimer();
  557. stop();
  558. if (isASIOOpen && isOpen_)
  559. {
  560. const ScopedLock sl (callbackLock);
  561. if (isUsingThread)
  562. {
  563. signalThreadShouldExit();
  564. event1.signal();
  565. stopThread (3000);
  566. }
  567. isOpen_ = false;
  568. isStarted = false;
  569. needToReset = false;
  570. isReSync = false;
  571. log ("ASIO - stopping");
  572. if (asioObject != 0)
  573. {
  574. Thread::sleep (20);
  575. asioObject->stop();
  576. Thread::sleep (10);
  577. asioObject->disposeBuffers();
  578. }
  579. Thread::sleep (10);
  580. }
  581. }
  582. bool isOpen()
  583. {
  584. return isOpen_ || insideControlPanelModalLoop;
  585. }
  586. int getCurrentBufferSizeSamples()
  587. {
  588. return currentBlockSizeSamples;
  589. }
  590. double getCurrentSampleRate()
  591. {
  592. return currentSampleRate;
  593. }
  594. int getCurrentBitDepth()
  595. {
  596. return currentBitDepth;
  597. }
  598. int getOutputLatencyInSamples()
  599. {
  600. return outputLatency;
  601. }
  602. int getInputLatencyInSamples()
  603. {
  604. return inputLatency;
  605. }
  606. void start (AudioIODeviceCallback* callback)
  607. {
  608. if (callback != 0)
  609. {
  610. callback->audioDeviceAboutToStart (currentSampleRate, currentBlockSizeSamples);
  611. const ScopedLock sl (callbackLock);
  612. currentCallback = callback;
  613. }
  614. }
  615. void stop()
  616. {
  617. AudioIODeviceCallback* const lastCallback = currentCallback;
  618. {
  619. const ScopedLock sl (callbackLock);
  620. currentCallback = 0;
  621. }
  622. if (lastCallback != 0)
  623. lastCallback->audioDeviceStopped();
  624. }
  625. bool isPlaying()
  626. {
  627. return isASIOOpen
  628. && (isThreadRunning() || ! isUsingThread)
  629. && (currentCallback != 0);
  630. }
  631. const String getLastError()
  632. {
  633. return error;
  634. }
  635. void setUsingThread (bool b)
  636. {
  637. shouldUseThread = b;
  638. }
  639. bool hasControlPanel() const
  640. {
  641. return true;
  642. }
  643. bool showControlPanel()
  644. {
  645. log ("ASIO - showing control panel");
  646. Component modalWindow (String::empty);
  647. modalWindow.setOpaque (true);
  648. modalWindow.addToDesktop (0);
  649. modalWindow.enterModalState();
  650. bool done = false;
  651. JUCE_TRY
  652. {
  653. close();
  654. insideControlPanelModalLoop = true;
  655. const uint32 started = Time::getMillisecondCounter();
  656. if (asioObject != 0)
  657. {
  658. asioObject->controlPanel();
  659. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  660. log (T("spent: ") + String (spent));
  661. if (spent > 300)
  662. {
  663. shouldUsePreferredSize = true;
  664. done = true;
  665. }
  666. }
  667. }
  668. JUCE_CATCH_ALL
  669. insideControlPanelModalLoop = false;
  670. return done;
  671. }
  672. void run()
  673. {
  674. isThreadReady = true;
  675. for (;;)
  676. {
  677. event1.wait();
  678. if (threadShouldExit())
  679. break;
  680. processBuffer();
  681. }
  682. if (bufferIndex < 0)
  683. {
  684. log ("! ASIO callback never called");
  685. }
  686. }
  687. void resetRequest() throw()
  688. {
  689. needToReset = true;
  690. }
  691. void resyncRequest() throw()
  692. {
  693. needToReset = true;
  694. isReSync = true;
  695. }
  696. void timerCallback()
  697. {
  698. if (! insideControlPanelModalLoop)
  699. {
  700. stopTimer();
  701. // used to cause a reset
  702. log ("! ASIO restart request!");
  703. if (isOpen_)
  704. {
  705. AudioIODeviceCallback* const oldCallback = currentCallback;
  706. close();
  707. open (currentChansIn, currentChansOut,
  708. currentSampleRate, currentBlockSizeSamples);
  709. if (oldCallback != 0)
  710. start (oldCallback);
  711. }
  712. }
  713. else
  714. {
  715. startTimer (100);
  716. }
  717. }
  718. //==============================================================================
  719. juce_UseDebuggingNewOperator
  720. private:
  721. //==============================================================================
  722. void* windowHandle;
  723. CLSID classId;
  724. String error;
  725. long numInputs, numOutputs;
  726. StringArray outputChannelNames, inputChannelNames;
  727. Array<int> sampleRates, bufferSizes;
  728. long inputLatency, outputLatency;
  729. long minSize, maxSize, preferredSize, granularity;
  730. int volatile currentBlockSizeSamples;
  731. int volatile currentBitDepth;
  732. double volatile currentSampleRate;
  733. BitArray currentChansOut, currentChansIn;
  734. AudioIODeviceCallback* volatile currentCallback;
  735. CriticalSection callbackLock;
  736. float* inBuffers[maxASIOChannels];
  737. float* outBuffers[maxASIOChannels];
  738. int inputChannelBitDepths[maxASIOChannels];
  739. int outputChannelBitDepths[maxASIOChannels];
  740. int inputChannelBytesPerSample[maxASIOChannels];
  741. int outputChannelBytesPerSample[maxASIOChannels];
  742. bool inputChannelIsFloat[maxASIOChannels];
  743. bool outputChannelIsFloat[maxASIOChannels];
  744. bool inputChannelLittleEndian[maxASIOChannels];
  745. bool outputChannelLittleEndian[maxASIOChannels];
  746. WaitableEvent event1;
  747. float* tempBuffer;
  748. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  749. bool isOpen_, isStarted;
  750. bool isUsingThread, shouldUseThread;
  751. bool volatile isASIOOpen;
  752. bool volatile calledback;
  753. bool volatile littleEndian, postOutput, needToReset, isReSync, isThreadReady;
  754. //==============================================================================
  755. static void removeCurrentDriver()
  756. {
  757. if (asioObject != 0)
  758. {
  759. asioObject->Release();
  760. asioObject = 0;
  761. }
  762. }
  763. bool loadDriver()
  764. {
  765. removeCurrentDriver();
  766. JUCE_TRY
  767. {
  768. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  769. classId, (void**) &asioObject) == S_OK)
  770. {
  771. return true;
  772. }
  773. }
  774. JUCE_CATCH_ALL
  775. asioObject = 0;
  776. return false;
  777. }
  778. const String initDriver()
  779. {
  780. if (asioObject != 0)
  781. {
  782. char buffer [256];
  783. zeromem (buffer, sizeof (buffer));
  784. if (! asioObject->init (windowHandle))
  785. {
  786. asioObject->getErrorMessage (buffer);
  787. return String (buffer, sizeof (buffer) - 1);
  788. }
  789. // just in case any daft drivers expect this to be called..
  790. asioObject->getDriverName (buffer);
  791. return String::empty;
  792. }
  793. return "No Driver";
  794. }
  795. const String openDevice()
  796. {
  797. // use this in case the driver starts opening dialog boxes..
  798. Component modalWindow (String::empty);
  799. modalWindow.setOpaque (true);
  800. modalWindow.addToDesktop (0);
  801. modalWindow.enterModalState();
  802. isUsingThread = shouldUseThread;
  803. // open the device and get its info..
  804. log (T("opening ASIO device: ") + getName());
  805. needToReset = false;
  806. isReSync = false;
  807. outputChannelNames.clear();
  808. inputChannelNames.clear();
  809. bufferSizes.clear();
  810. sampleRates.clear();
  811. isASIOOpen = false;
  812. isOpen_ = false;
  813. numInputs = 0;
  814. numOutputs = 0;
  815. currentCallback = 0;
  816. error = String::empty;
  817. if (getName().isEmpty())
  818. return error;
  819. long err = 0;
  820. if (loadDriver())
  821. {
  822. String driverName;
  823. if ((error = initDriver()).isEmpty())
  824. {
  825. numInputs = 0;
  826. numOutputs = 0;
  827. if (asioObject != 0
  828. && (err = asioObject->getChannels (&numInputs, &numOutputs)) == 0)
  829. {
  830. log (String ((int) numInputs) + T(" in, ") + String ((int) numOutputs) + T(" out"));
  831. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  832. {
  833. // find a list of buffer sizes..
  834. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  835. if (granularity >= 0)
  836. {
  837. granularity = jmax (1, (int) granularity);
  838. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  839. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  840. }
  841. else if (granularity < 0)
  842. {
  843. for (int i = 0; i < 18; ++i)
  844. {
  845. const int s = (1 << i);
  846. if (s >= minSize && s <= maxSize)
  847. bufferSizes.add (s);
  848. }
  849. }
  850. if (! bufferSizes.contains (preferredSize))
  851. bufferSizes.insert (0, preferredSize);
  852. double currentRate = 0;
  853. asioObject->getSampleRate (&currentRate);
  854. if (currentRate <= 0.0 || currentRate > 192001.0)
  855. {
  856. log ("setting sample rate");
  857. err = asioObject->setSampleRate (44100.0);
  858. if (err != 0)
  859. {
  860. logError ("setting sample rate", err);
  861. }
  862. asioObject->getSampleRate (&currentRate);
  863. }
  864. currentSampleRate = currentRate;
  865. postOutput = (asioObject->outputReady() == 0);
  866. if (postOutput)
  867. {
  868. log ("ASIO outputReady = ok");
  869. }
  870. updateSampleRates();
  871. // ..because cubase does it at this point
  872. inputLatency = outputLatency = 0;
  873. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  874. {
  875. log ("ASIO - no latencies");
  876. }
  877. log (String ("latencies: ")
  878. + String ((int) inputLatency)
  879. + T(", ") + String ((int) outputLatency));
  880. // create some dummy buffers now.. because cubase does..
  881. numActiveInputChans = 0;
  882. numActiveOutputChans = 0;
  883. ASIOBufferInfo* info = bufferInfos;
  884. int i, numChans = 0;
  885. for (i = 0; i < jmin (2, numInputs); ++i)
  886. {
  887. info->isInput = 1;
  888. info->channelNum = i;
  889. info->buffers[0] = info->buffers[1] = 0;
  890. ++info;
  891. ++numChans;
  892. }
  893. const int outputBufferIndex = numChans;
  894. for (i = 0; i < jmin (2, numOutputs); ++i)
  895. {
  896. info->isInput = 0;
  897. info->channelNum = i;
  898. info->buffers[0] = info->buffers[1] = 0;
  899. ++info;
  900. ++numChans;
  901. }
  902. callbacks.bufferSwitch = &bufferSwitchCallback;
  903. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  904. callbacks.asioMessage = &asioMessagesCallback;
  905. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback;
  906. log (T("creating buffers (dummy): ") + String (numChans)
  907. + T(", ") + String ((int) preferredSize));
  908. if (preferredSize > 0)
  909. {
  910. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  911. if (err != 0)
  912. {
  913. logError ("dummy buffers", err);
  914. }
  915. }
  916. long newInps = 0, newOuts = 0;
  917. asioObject->getChannels (&newInps, &newOuts);
  918. if (numInputs != newInps || numOutputs != newOuts)
  919. {
  920. numInputs = newInps;
  921. numOutputs = newOuts;
  922. log (String ((int) numInputs) + T(" in; ")
  923. + String ((int) numOutputs) + T(" out"));
  924. }
  925. updateSampleRates();
  926. ASIOChannelInfo channelInfo;
  927. channelInfo.type = 0;
  928. for (i = 0; i < numInputs; ++i)
  929. {
  930. zerostruct (channelInfo);
  931. channelInfo.channel = i;
  932. channelInfo.isInput = 1;
  933. asioObject->getChannelInfo (&channelInfo);
  934. inputChannelNames.add (String (channelInfo.name));
  935. }
  936. for (i = 0; i < numOutputs; ++i)
  937. {
  938. zerostruct (channelInfo);
  939. channelInfo.channel = i;
  940. channelInfo.isInput = 0;
  941. asioObject->getChannelInfo (&channelInfo);
  942. outputChannelNames.add (String (channelInfo.name));
  943. typeToFormatParameters (channelInfo.type,
  944. outputChannelBitDepths[i],
  945. outputChannelBytesPerSample[i],
  946. outputChannelIsFloat[i],
  947. outputChannelLittleEndian[i]);
  948. if (i < 2)
  949. {
  950. // clear the channels that are used with the dummy stuff
  951. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  952. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  953. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  954. }
  955. }
  956. outputChannelNames.trim();
  957. inputChannelNames.trim();
  958. outputChannelNames.appendNumbersToDuplicates (false, true);
  959. inputChannelNames.appendNumbersToDuplicates (false, true);
  960. // start and stop because cubase does it..
  961. asioObject->getLatencies (&inputLatency, &outputLatency);
  962. if ((err = asioObject->start()) != 0)
  963. {
  964. // ignore an error here, as it might start later after setting other stuff up
  965. logError ("ASIO start", err);
  966. }
  967. Thread::sleep (100);
  968. asioObject->stop();
  969. }
  970. else
  971. {
  972. error = "Can't detect buffer sizes";
  973. }
  974. }
  975. else
  976. {
  977. error = "Can't detect asio channels";
  978. }
  979. }
  980. }
  981. else
  982. {
  983. error = "No such device";
  984. }
  985. if (error.isNotEmpty())
  986. {
  987. logError (error, err);
  988. if (asioObject != 0)
  989. asioObject->disposeBuffers();
  990. removeCurrentDriver();
  991. isASIOOpen = false;
  992. }
  993. else
  994. {
  995. isASIOOpen = true;
  996. log ("ASIO device open");
  997. }
  998. isOpen_ = false;
  999. needToReset = false;
  1000. isReSync = false;
  1001. return error;
  1002. }
  1003. //==============================================================================
  1004. void callback (const long index) throw()
  1005. {
  1006. if (isStarted)
  1007. {
  1008. bufferIndex = index;
  1009. if (isUsingThread) // if not started, just use processBuffer() to clear the buffers directly
  1010. {
  1011. event1.signal();
  1012. if (postOutput && (! isThreadRunning()) && asioObject != 0)
  1013. asioObject->outputReady();
  1014. }
  1015. else
  1016. {
  1017. processBuffer();
  1018. }
  1019. }
  1020. else
  1021. {
  1022. if (postOutput && (asioObject != 0))
  1023. asioObject->outputReady();
  1024. }
  1025. calledback = true;
  1026. }
  1027. void processBuffer() throw()
  1028. {
  1029. const ASIOBufferInfo* const infos = bufferInfos;
  1030. const int bi = bufferIndex;
  1031. const ScopedLock sl (callbackLock);
  1032. if (needToReset)
  1033. {
  1034. needToReset = false;
  1035. if (isReSync)
  1036. {
  1037. log ("! ASIO resync");
  1038. isReSync = false;
  1039. }
  1040. else
  1041. {
  1042. startTimer (20);
  1043. }
  1044. }
  1045. if (bi >= 0)
  1046. {
  1047. const int samps = currentBlockSizeSamples;
  1048. if (currentCallback != 0)
  1049. {
  1050. int n = 0;
  1051. int i;
  1052. for (i = 0; i < numInputs; ++i)
  1053. {
  1054. float* const dst = inBuffers[i];
  1055. if (dst != 0)
  1056. {
  1057. const char* const src = (const char*) (infos[n].buffers[bi]);
  1058. if (inputChannelIsFloat[i])
  1059. {
  1060. memcpy (dst, src, samps * sizeof (float));
  1061. }
  1062. else
  1063. {
  1064. jassert (dst == tempBuffer + (samps * n));
  1065. switch (inputChannelBitDepths[i])
  1066. {
  1067. case 16:
  1068. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  1069. samps, inputChannelLittleEndian[i]);
  1070. break;
  1071. case 24:
  1072. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  1073. samps, inputChannelLittleEndian[i]);
  1074. break;
  1075. case 32:
  1076. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  1077. samps, inputChannelLittleEndian[i]);
  1078. break;
  1079. case 64:
  1080. jassertfalse
  1081. break;
  1082. }
  1083. }
  1084. ++n;
  1085. }
  1086. }
  1087. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  1088. numInputs,
  1089. outBuffers,
  1090. numOutputs,
  1091. samps);
  1092. for (i = 0; i < numOutputs; ++i)
  1093. {
  1094. float* const src = outBuffers[i];
  1095. if (src != 0)
  1096. {
  1097. char* const dst = (char*) (infos[n].buffers[bi]);
  1098. if (outputChannelIsFloat[i])
  1099. {
  1100. memcpy (dst, src, samps * sizeof (float));
  1101. }
  1102. else
  1103. {
  1104. jassert (src == tempBuffer + (samps * n));
  1105. switch (outputChannelBitDepths[i])
  1106. {
  1107. case 16:
  1108. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  1109. samps, outputChannelLittleEndian[i]);
  1110. break;
  1111. case 24:
  1112. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  1113. samps, outputChannelLittleEndian[i]);
  1114. break;
  1115. case 32:
  1116. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  1117. samps, outputChannelLittleEndian[i]);
  1118. break;
  1119. case 64:
  1120. jassertfalse
  1121. break;
  1122. }
  1123. }
  1124. ++n;
  1125. }
  1126. }
  1127. }
  1128. else
  1129. {
  1130. int n = 0;
  1131. int i;
  1132. for (i = 0; i < numInputs; ++i)
  1133. if (inBuffers[i] != 0)
  1134. ++n;
  1135. for (i = 0; i < numOutputs; ++i)
  1136. {
  1137. if (outBuffers[i] != 0)
  1138. {
  1139. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  1140. zeromem (infos[n].buffers[bi], bytesPerBuffer);
  1141. ++n;
  1142. }
  1143. }
  1144. }
  1145. }
  1146. if (postOutput)
  1147. asioObject->outputReady();
  1148. }
  1149. //==============================================================================
  1150. static ASIOTime* bufferSwitchTimeInfoCallback (ASIOTime*, long index, long) throw()
  1151. {
  1152. if (currentASIODev != 0)
  1153. currentASIODev->callback (index);
  1154. return 0;
  1155. }
  1156. static void bufferSwitchCallback (long index, long) throw()
  1157. {
  1158. if (currentASIODev != 0)
  1159. currentASIODev->callback (index);
  1160. }
  1161. static long asioMessagesCallback (long selector, long value, void*, double*) throw()
  1162. {
  1163. switch (selector)
  1164. {
  1165. case kAsioSelectorSupported:
  1166. if (value == kAsioResetRequest
  1167. || value == kAsioEngineVersion
  1168. || value == kAsioResyncRequest
  1169. || value == kAsioLatenciesChanged
  1170. || value == kAsioSupportsInputMonitor)
  1171. return 1;
  1172. break;
  1173. case kAsioBufferSizeChange:
  1174. break;
  1175. case kAsioResetRequest:
  1176. if (currentASIODev != 0)
  1177. currentASIODev->resetRequest();
  1178. return 1;
  1179. case kAsioResyncRequest:
  1180. if (currentASIODev != 0)
  1181. currentASIODev->resyncRequest();
  1182. return 1;
  1183. case kAsioLatenciesChanged:
  1184. return 1;
  1185. case kAsioEngineVersion:
  1186. return 2;
  1187. case kAsioSupportsTimeInfo:
  1188. case kAsioSupportsTimeCode:
  1189. return 0;
  1190. }
  1191. return 0;
  1192. }
  1193. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  1194. {
  1195. }
  1196. //==============================================================================
  1197. static void convertInt16ToFloat (const char* src,
  1198. float* dest,
  1199. const int srcStrideBytes,
  1200. int numSamples,
  1201. const bool littleEndian) throw()
  1202. {
  1203. const double g = 1.0 / 32768.0;
  1204. if (littleEndian)
  1205. {
  1206. while (--numSamples >= 0)
  1207. {
  1208. *dest++ = (float) (g * (short) littleEndianShort (src));
  1209. src += srcStrideBytes;
  1210. }
  1211. }
  1212. else
  1213. {
  1214. while (--numSamples >= 0)
  1215. {
  1216. *dest++ = (float) (g * (short) bigEndianShort (src));
  1217. src += srcStrideBytes;
  1218. }
  1219. }
  1220. }
  1221. static void convertFloatToInt16 (const float* src,
  1222. char* dest,
  1223. const int dstStrideBytes,
  1224. int numSamples,
  1225. const bool littleEndian) throw()
  1226. {
  1227. const double maxVal = (double) 0x7fff;
  1228. if (littleEndian)
  1229. {
  1230. while (--numSamples >= 0)
  1231. {
  1232. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  1233. dest += dstStrideBytes;
  1234. }
  1235. }
  1236. else
  1237. {
  1238. while (--numSamples >= 0)
  1239. {
  1240. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  1241. dest += dstStrideBytes;
  1242. }
  1243. }
  1244. }
  1245. static void convertInt24ToFloat (const char* src,
  1246. float* dest,
  1247. const int srcStrideBytes,
  1248. int numSamples,
  1249. const bool littleEndian) throw()
  1250. {
  1251. const double g = 1.0 / 0x7fffff;
  1252. if (littleEndian)
  1253. {
  1254. while (--numSamples >= 0)
  1255. {
  1256. *dest++ = (float) (g * littleEndian24Bit (src));
  1257. src += srcStrideBytes;
  1258. }
  1259. }
  1260. else
  1261. {
  1262. while (--numSamples >= 0)
  1263. {
  1264. *dest++ = (float) (g * bigEndian24Bit (src));
  1265. src += srcStrideBytes;
  1266. }
  1267. }
  1268. }
  1269. static void convertFloatToInt24 (const float* src,
  1270. char* dest,
  1271. const int dstStrideBytes,
  1272. int numSamples,
  1273. const bool littleEndian) throw()
  1274. {
  1275. const double maxVal = (double) 0x7fffff;
  1276. if (littleEndian)
  1277. {
  1278. while (--numSamples >= 0)
  1279. {
  1280. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  1281. dest += dstStrideBytes;
  1282. }
  1283. }
  1284. else
  1285. {
  1286. while (--numSamples >= 0)
  1287. {
  1288. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  1289. dest += dstStrideBytes;
  1290. }
  1291. }
  1292. }
  1293. static void convertInt32ToFloat (const char* src,
  1294. float* dest,
  1295. const int srcStrideBytes,
  1296. int numSamples,
  1297. const bool littleEndian) throw()
  1298. {
  1299. const double g = 1.0 / 0x7fffffff;
  1300. if (littleEndian)
  1301. {
  1302. while (--numSamples >= 0)
  1303. {
  1304. *dest++ = (float) (g * (int) littleEndianInt (src));
  1305. src += srcStrideBytes;
  1306. }
  1307. }
  1308. else
  1309. {
  1310. while (--numSamples >= 0)
  1311. {
  1312. *dest++ = (float) (g * (int) bigEndianInt (src));
  1313. src += srcStrideBytes;
  1314. }
  1315. }
  1316. }
  1317. static void convertFloatToInt32 (const float* src,
  1318. char* dest,
  1319. const int dstStrideBytes,
  1320. int numSamples,
  1321. const bool littleEndian) throw()
  1322. {
  1323. const double maxVal = (double) 0x7fffffff;
  1324. if (littleEndian)
  1325. {
  1326. while (--numSamples >= 0)
  1327. {
  1328. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  1329. dest += dstStrideBytes;
  1330. }
  1331. }
  1332. else
  1333. {
  1334. while (--numSamples >= 0)
  1335. {
  1336. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  1337. dest += dstStrideBytes;
  1338. }
  1339. }
  1340. }
  1341. //==============================================================================
  1342. static void typeToFormatParameters (const long type,
  1343. int& bitDepth,
  1344. int& byteStride,
  1345. bool& formatIsFloat,
  1346. bool& littleEndian) throw()
  1347. {
  1348. bitDepth = 0;
  1349. littleEndian = false;
  1350. formatIsFloat = false;
  1351. switch (type)
  1352. {
  1353. case ASIOSTInt16MSB:
  1354. case ASIOSTInt16LSB:
  1355. case ASIOSTInt32MSB16:
  1356. case ASIOSTInt32LSB16:
  1357. bitDepth = 16; break;
  1358. case ASIOSTFloat32MSB:
  1359. case ASIOSTFloat32LSB:
  1360. formatIsFloat = true;
  1361. bitDepth = 32; break;
  1362. case ASIOSTInt32MSB:
  1363. case ASIOSTInt32LSB:
  1364. bitDepth = 32; break;
  1365. case ASIOSTInt24MSB:
  1366. case ASIOSTInt24LSB:
  1367. case ASIOSTInt32MSB24:
  1368. case ASIOSTInt32LSB24:
  1369. case ASIOSTInt32MSB18:
  1370. case ASIOSTInt32MSB20:
  1371. case ASIOSTInt32LSB18:
  1372. case ASIOSTInt32LSB20:
  1373. bitDepth = 24; break;
  1374. case ASIOSTFloat64MSB:
  1375. case ASIOSTFloat64LSB:
  1376. default:
  1377. bitDepth = 64;
  1378. break;
  1379. }
  1380. switch (type)
  1381. {
  1382. case ASIOSTInt16MSB:
  1383. case ASIOSTInt32MSB16:
  1384. case ASIOSTFloat32MSB:
  1385. case ASIOSTFloat64MSB:
  1386. case ASIOSTInt32MSB:
  1387. case ASIOSTInt32MSB18:
  1388. case ASIOSTInt32MSB20:
  1389. case ASIOSTInt32MSB24:
  1390. case ASIOSTInt24MSB:
  1391. littleEndian = false; break;
  1392. case ASIOSTInt16LSB:
  1393. case ASIOSTInt32LSB16:
  1394. case ASIOSTFloat32LSB:
  1395. case ASIOSTFloat64LSB:
  1396. case ASIOSTInt32LSB:
  1397. case ASIOSTInt32LSB18:
  1398. case ASIOSTInt32LSB20:
  1399. case ASIOSTInt32LSB24:
  1400. case ASIOSTInt24LSB:
  1401. littleEndian = true; break;
  1402. default:
  1403. break;
  1404. }
  1405. switch (type)
  1406. {
  1407. case ASIOSTInt16LSB:
  1408. case ASIOSTInt16MSB:
  1409. byteStride = 2; break;
  1410. case ASIOSTInt24LSB:
  1411. case ASIOSTInt24MSB:
  1412. byteStride = 3; break;
  1413. case ASIOSTInt32MSB16:
  1414. case ASIOSTInt32LSB16:
  1415. case ASIOSTInt32MSB:
  1416. case ASIOSTInt32MSB18:
  1417. case ASIOSTInt32MSB20:
  1418. case ASIOSTInt32MSB24:
  1419. case ASIOSTInt32LSB:
  1420. case ASIOSTInt32LSB18:
  1421. case ASIOSTInt32LSB20:
  1422. case ASIOSTInt32LSB24:
  1423. case ASIOSTFloat32LSB:
  1424. case ASIOSTFloat32MSB:
  1425. byteStride = 4; break;
  1426. case ASIOSTFloat64MSB:
  1427. case ASIOSTFloat64LSB:
  1428. byteStride = 8; break;
  1429. default:
  1430. break;
  1431. }
  1432. }
  1433. };
  1434. //==============================================================================
  1435. class ASIOAudioIODeviceType : public AudioIODeviceType
  1436. {
  1437. public:
  1438. ASIOAudioIODeviceType()
  1439. : AudioIODeviceType (T("ASIO")),
  1440. classIds (2),
  1441. hasScanned (false)
  1442. {
  1443. CoInitialize (0);
  1444. }
  1445. ~ASIOAudioIODeviceType()
  1446. {
  1447. }
  1448. //==============================================================================
  1449. void scanForDevices()
  1450. {
  1451. hasScanned = true;
  1452. deviceNames.clear();
  1453. classIds.clear();
  1454. HKEY hk = 0;
  1455. int index = 0;
  1456. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  1457. {
  1458. for (;;)
  1459. {
  1460. char name [256];
  1461. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  1462. {
  1463. addDriverInfo (name, hk);
  1464. }
  1465. else
  1466. {
  1467. break;
  1468. }
  1469. }
  1470. RegCloseKey (hk);
  1471. }
  1472. }
  1473. const StringArray getDeviceNames (const bool /*preferInputNames*/) const
  1474. {
  1475. jassert (hasScanned); // need to call scanForDevices() before doing this
  1476. return deviceNames;
  1477. }
  1478. const String getDefaultDeviceName (const bool /*preferInputNames*/) const
  1479. {
  1480. jassert (hasScanned); // need to call scanForDevices() before doing this
  1481. return deviceNames [0];
  1482. }
  1483. AudioIODevice* createDevice (const String& deviceName)
  1484. {
  1485. jassert (hasScanned); // need to call scanForDevices() before doing this
  1486. const int index = deviceNames.indexOf (deviceName);
  1487. if (index >= 0)
  1488. {
  1489. jassert (currentASIODev == 0); // unfortunately you can't have more than one ASIO device
  1490. // open at the same time..
  1491. if (currentASIODev == 0)
  1492. return new ASIOAudioIODevice (deviceName, *(classIds [index]));
  1493. }
  1494. return 0;
  1495. }
  1496. //==============================================================================
  1497. juce_UseDebuggingNewOperator
  1498. private:
  1499. StringArray deviceNames;
  1500. OwnedArray <CLSID> classIds;
  1501. bool hasScanned;
  1502. //==============================================================================
  1503. static bool checkClassIsOk (const String& classId)
  1504. {
  1505. HKEY hk = 0;
  1506. bool ok = false;
  1507. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  1508. {
  1509. int index = 0;
  1510. for (;;)
  1511. {
  1512. char buf [512];
  1513. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  1514. {
  1515. if (classId.equalsIgnoreCase (buf))
  1516. {
  1517. HKEY subKey, pathKey;
  1518. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  1519. {
  1520. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  1521. {
  1522. char pathName [600];
  1523. DWORD dtype = REG_SZ;
  1524. DWORD dsize = sizeof (pathName);
  1525. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  1526. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  1527. {
  1528. OFSTRUCT of;
  1529. zerostruct (of);
  1530. of.cBytes = sizeof (of);
  1531. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  1532. }
  1533. RegCloseKey (pathKey);
  1534. }
  1535. RegCloseKey (subKey);
  1536. }
  1537. break;
  1538. }
  1539. }
  1540. else
  1541. {
  1542. break;
  1543. }
  1544. }
  1545. RegCloseKey (hk);
  1546. }
  1547. return ok;
  1548. }
  1549. void addDriverInfo (const String& keyName, HKEY hk)
  1550. {
  1551. HKEY subKey;
  1552. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  1553. {
  1554. char buf [256];
  1555. DWORD dtype = REG_SZ;
  1556. DWORD dsize = sizeof (buf);
  1557. zeromem (buf, dsize);
  1558. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  1559. {
  1560. if (dsize > 0 && checkClassIsOk (buf))
  1561. {
  1562. wchar_t classIdStr [130];
  1563. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  1564. String deviceName;
  1565. CLSID classId;
  1566. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  1567. {
  1568. dtype = REG_SZ;
  1569. dsize = sizeof (buf);
  1570. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  1571. deviceName = buf;
  1572. else
  1573. deviceName = keyName;
  1574. log (T("found ") + deviceName);
  1575. deviceNames.add (deviceName);
  1576. classIds.add (new CLSID (classId));
  1577. }
  1578. }
  1579. RegCloseKey (subKey);
  1580. }
  1581. }
  1582. }
  1583. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  1584. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  1585. };
  1586. AudioIODeviceType* juce_createASIOAudioIODeviceType()
  1587. {
  1588. return new ASIOAudioIODeviceType();
  1589. }
  1590. END_JUCE_NAMESPACE
  1591. #endif