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.

1983 lines
63KB

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