Audio plugin host https://kx.studio/carla
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.

juce_win32_ASIO.cpp 54KB

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