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.

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