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

9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
10 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI 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) ignoreUnused (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[16] = { 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. minBufferSize (0), maxBufferSize (0),
  286. preferredBufferSize (0),
  287. bufferGranularity (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, 352800, 384000 };
  326. Array<double> 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 ((double) 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() override { return outputChannelNames; }
  352. StringArray getInputChannelNames() override { return inputChannelNames; }
  353. Array<double> getAvailableSampleRates() override { return sampleRates; }
  354. Array<int> getAvailableBufferSizes() override { return bufferSizes; }
  355. int getDefaultBufferSize() override { return preferredBufferSize; }
  356. String open (const BigInteger& inputChannels,
  357. const BigInteger& outputChannels,
  358. double sr, int bufferSizeSamples) override
  359. {
  360. if (isOpen())
  361. close();
  362. jassert (currentCallback == nullptr);
  363. if (bufferSizeSamples < 8 || bufferSizeSamples > 16384)
  364. shouldUsePreferredSize = true;
  365. if (asioObject == nullptr)
  366. {
  367. const String openingError (openDevice());
  368. if (asioObject == nullptr)
  369. return openingError;
  370. }
  371. isStarted = false;
  372. bufferIndex = -1;
  373. long err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans);
  374. jassert (err == ASE_OK);
  375. bufferSizeSamples = readBufferSizes (bufferSizeSamples);
  376. double sampleRate = sr;
  377. currentSampleRate = sampleRate;
  378. currentBlockSizeSamples = bufferSizeSamples;
  379. currentChansOut.clear();
  380. currentChansIn.clear();
  381. updateSampleRates();
  382. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  383. sampleRate = sampleRates[0];
  384. jassert (sampleRate != 0);
  385. if (sampleRate == 0)
  386. sampleRate = 44100.0;
  387. updateClockSources();
  388. currentSampleRate = getSampleRate();
  389. error.clear();
  390. buffersCreated = false;
  391. setSampleRate (sampleRate);
  392. // (need to get this again in case a sample rate change affected the channel count)
  393. err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans);
  394. jassert (err == ASE_OK);
  395. inBuffers.calloc (totalNumInputChans + 8);
  396. outBuffers.calloc (totalNumOutputChans + 8);
  397. if (needToReset)
  398. {
  399. JUCE_ASIO_LOG (" Resetting");
  400. removeCurrentDriver();
  401. loadDriver();
  402. String initError = initDriver();
  403. if (initError.isNotEmpty())
  404. JUCE_ASIO_LOG ("ASIOInit: " + initError);
  405. needToReset = false;
  406. }
  407. const int totalBuffers = resetBuffers (inputChannels, outputChannels);
  408. setCallbackFunctions();
  409. JUCE_ASIO_LOG ("disposing buffers");
  410. err = asioObject->disposeBuffers();
  411. JUCE_ASIO_LOG ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  412. err = asioObject->createBuffers (bufferInfos, totalBuffers, currentBlockSizeSamples, &callbacks);
  413. if (err != ASE_OK)
  414. {
  415. currentBlockSizeSamples = preferredBufferSize;
  416. JUCE_ASIO_LOG_ERROR ("create buffers 2", err);
  417. asioObject->disposeBuffers();
  418. err = asioObject->createBuffers (bufferInfos, totalBuffers, currentBlockSizeSamples, &callbacks);
  419. }
  420. if (err == ASE_OK)
  421. {
  422. buffersCreated = true;
  423. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  424. int n = 0;
  425. Array <int> types;
  426. currentBitDepth = 16;
  427. for (int i = 0; i < (int) totalNumInputChans; ++i)
  428. {
  429. if (inputChannels[i])
  430. {
  431. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  432. ASIOChannelInfo channelInfo = { 0 };
  433. channelInfo.channel = i;
  434. channelInfo.isInput = 1;
  435. asioObject->getChannelInfo (&channelInfo);
  436. types.addIfNotAlreadyThere (channelInfo.type);
  437. inputFormat[n] = ASIOSampleFormat (channelInfo.type);
  438. currentBitDepth = jmax (currentBitDepth, inputFormat[n].bitDepth);
  439. ++n;
  440. }
  441. }
  442. jassert (numActiveInputChans == n);
  443. n = 0;
  444. for (int i = 0; i < (int) totalNumOutputChans; ++i)
  445. {
  446. if (outputChannels[i])
  447. {
  448. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  449. ASIOChannelInfo channelInfo = { 0 };
  450. channelInfo.channel = i;
  451. channelInfo.isInput = 0;
  452. asioObject->getChannelInfo (&channelInfo);
  453. types.addIfNotAlreadyThere (channelInfo.type);
  454. outputFormat[n] = ASIOSampleFormat (channelInfo.type);
  455. currentBitDepth = jmax (currentBitDepth, outputFormat[n].bitDepth);
  456. ++n;
  457. }
  458. }
  459. jassert (numActiveOutputChans == n);
  460. for (int i = types.size(); --i >= 0;)
  461. JUCE_ASIO_LOG ("channel format: " + String (types[i]));
  462. jassert (n <= totalBuffers);
  463. for (int i = 0; i < numActiveOutputChans; ++i)
  464. {
  465. outputFormat[i].clear (bufferInfos [numActiveInputChans + i].buffers[0], currentBlockSizeSamples);
  466. outputFormat[i].clear (bufferInfos [numActiveInputChans + i].buffers[1], currentBlockSizeSamples);
  467. }
  468. readLatencies();
  469. refreshBufferSizes();
  470. deviceIsOpen = true;
  471. JUCE_ASIO_LOG ("starting");
  472. calledback = false;
  473. err = asioObject->start();
  474. if (err != 0)
  475. {
  476. deviceIsOpen = false;
  477. JUCE_ASIO_LOG ("stop on failure");
  478. Thread::sleep (10);
  479. asioObject->stop();
  480. error = "Can't start device";
  481. Thread::sleep (10);
  482. }
  483. else
  484. {
  485. int count = 300;
  486. while (--count > 0 && ! calledback)
  487. Thread::sleep (10);
  488. isStarted = true;
  489. if (! calledback)
  490. {
  491. error = "Device didn't start correctly";
  492. JUCE_ASIO_LOG ("no callbacks - stopping..");
  493. asioObject->stop();
  494. }
  495. }
  496. }
  497. else
  498. {
  499. error = "Can't create i/o buffers";
  500. }
  501. if (error.isNotEmpty())
  502. {
  503. JUCE_ASIO_LOG_ERROR (error, err);
  504. disposeBuffers();
  505. Thread::sleep (20);
  506. isStarted = false;
  507. deviceIsOpen = false;
  508. const String errorCopy (error);
  509. close(); // (this resets the error string)
  510. error = errorCopy;
  511. }
  512. needToReset = false;
  513. return error;
  514. }
  515. void close() override
  516. {
  517. error.clear();
  518. stopTimer();
  519. stop();
  520. if (asioObject != nullptr && deviceIsOpen)
  521. {
  522. const ScopedLock sl (callbackLock);
  523. deviceIsOpen = false;
  524. isStarted = false;
  525. needToReset = false;
  526. JUCE_ASIO_LOG ("stopping");
  527. if (asioObject != nullptr)
  528. {
  529. Thread::sleep (20);
  530. asioObject->stop();
  531. Thread::sleep (10);
  532. disposeBuffers();
  533. }
  534. Thread::sleep (10);
  535. }
  536. }
  537. bool isOpen() override { return deviceIsOpen || insideControlPanelModalLoop; }
  538. bool isPlaying() override { return asioObject != nullptr && currentCallback != nullptr; }
  539. int getCurrentBufferSizeSamples() override { return currentBlockSizeSamples; }
  540. double getCurrentSampleRate() override { return currentSampleRate; }
  541. int getCurrentBitDepth() override { return currentBitDepth; }
  542. BigInteger getActiveOutputChannels() const override { return currentChansOut; }
  543. BigInteger getActiveInputChannels() const override { return currentChansIn; }
  544. int getOutputLatencyInSamples() override { return outputLatency + currentBlockSizeSamples / 4; }
  545. int getInputLatencyInSamples() override { return inputLatency + currentBlockSizeSamples / 4; }
  546. void start (AudioIODeviceCallback* callback) override
  547. {
  548. if (callback != nullptr)
  549. {
  550. callback->audioDeviceAboutToStart (this);
  551. const ScopedLock sl (callbackLock);
  552. currentCallback = callback;
  553. }
  554. }
  555. void stop() override
  556. {
  557. AudioIODeviceCallback* const lastCallback = currentCallback;
  558. {
  559. const ScopedLock sl (callbackLock);
  560. currentCallback = nullptr;
  561. }
  562. if (lastCallback != nullptr)
  563. lastCallback->audioDeviceStopped();
  564. }
  565. String getLastError() { return error; }
  566. bool hasControlPanel() const { return true; }
  567. bool showControlPanel()
  568. {
  569. JUCE_ASIO_LOG ("showing control panel");
  570. bool done = false;
  571. insideControlPanelModalLoop = true;
  572. const uint32 started = Time::getMillisecondCounter();
  573. if (asioObject != nullptr)
  574. {
  575. asioObject->controlPanel();
  576. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  577. JUCE_ASIO_LOG ("spent: " + String (spent));
  578. if (spent > 300)
  579. {
  580. shouldUsePreferredSize = true;
  581. done = true;
  582. }
  583. }
  584. insideControlPanelModalLoop = false;
  585. return done;
  586. }
  587. void resetRequest() noexcept
  588. {
  589. startTimer (500);
  590. }
  591. void timerCallback() override
  592. {
  593. if (! insideControlPanelModalLoop)
  594. {
  595. stopTimer();
  596. JUCE_ASIO_LOG ("restart request!");
  597. AudioIODeviceCallback* const oldCallback = currentCallback;
  598. close();
  599. needToReset = true;
  600. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  601. currentSampleRate, currentBlockSizeSamples);
  602. reloadChannelNames();
  603. if (oldCallback != nullptr)
  604. start (oldCallback);
  605. sendASIODeviceChangeToListeners (owner);
  606. }
  607. else
  608. {
  609. startTimer (100);
  610. }
  611. }
  612. private:
  613. //==============================================================================
  614. WeakReference<ASIOAudioIODeviceType> owner;
  615. IASIO* volatile asioObject;
  616. ASIOCallbacks callbacks;
  617. CLSID classId;
  618. String error;
  619. long totalNumInputChans, totalNumOutputChans;
  620. StringArray inputChannelNames, outputChannelNames;
  621. Array<double> sampleRates;
  622. Array<int> bufferSizes;
  623. long inputLatency, outputLatency;
  624. long minBufferSize, maxBufferSize, preferredBufferSize, bufferGranularity;
  625. ASIOClockSource clocks[32];
  626. int numClockSources;
  627. int volatile currentBlockSizeSamples;
  628. int volatile currentBitDepth;
  629. double volatile currentSampleRate;
  630. BigInteger currentChansOut, currentChansIn;
  631. AudioIODeviceCallback* volatile currentCallback;
  632. CriticalSection callbackLock;
  633. HeapBlock<ASIOBufferInfo> bufferInfos;
  634. HeapBlock<float*> inBuffers, outBuffers;
  635. HeapBlock<ASIOSampleFormat> inputFormat, outputFormat;
  636. WaitableEvent event1;
  637. HeapBlock<float> tempBuffer;
  638. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  639. bool deviceIsOpen, isStarted, buffersCreated;
  640. bool volatile calledback;
  641. bool volatile littleEndian, postOutput, needToReset;
  642. bool volatile insideControlPanelModalLoop;
  643. bool volatile shouldUsePreferredSize;
  644. //==============================================================================
  645. static String convertASIOString (char* const text, int length)
  646. {
  647. if (CharPointer_UTF8::isValidString (text, length))
  648. return String::fromUTF8 (text, length);
  649. WCHAR wideVersion [64] = { 0 };
  650. MultiByteToWideChar (CP_ACP, 0, text, length, wideVersion, numElementsInArray (wideVersion));
  651. return wideVersion;
  652. }
  653. String getChannelName (int index, bool isInput) const
  654. {
  655. ASIOChannelInfo channelInfo = { 0 };
  656. channelInfo.channel = index;
  657. channelInfo.isInput = isInput ? 1 : 0;
  658. asioObject->getChannelInfo (&channelInfo);
  659. return convertASIOString (channelInfo.name, sizeof (channelInfo.name));
  660. }
  661. void reloadChannelNames()
  662. {
  663. if (asioObject != nullptr
  664. && asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans) == ASE_OK)
  665. {
  666. inputChannelNames.clear();
  667. outputChannelNames.clear();
  668. for (int i = 0; i < totalNumInputChans; ++i)
  669. inputChannelNames.add (getChannelName (i, true));
  670. for (int i = 0; i < totalNumOutputChans; ++i)
  671. outputChannelNames.add (getChannelName (i, false));
  672. outputChannelNames.trim();
  673. inputChannelNames.trim();
  674. outputChannelNames.appendNumbersToDuplicates (false, true);
  675. inputChannelNames.appendNumbersToDuplicates (false, true);
  676. }
  677. }
  678. long refreshBufferSizes()
  679. {
  680. return asioObject->getBufferSize (&minBufferSize, &maxBufferSize, &preferredBufferSize, &bufferGranularity);
  681. }
  682. int readBufferSizes (int bufferSizeSamples)
  683. {
  684. minBufferSize = 0;
  685. maxBufferSize = 0;
  686. bufferGranularity = 0;
  687. long newPreferredSize = 0;
  688. if (asioObject->getBufferSize (&minBufferSize, &maxBufferSize, &newPreferredSize, &bufferGranularity) == ASE_OK)
  689. {
  690. if (preferredBufferSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredBufferSize)
  691. shouldUsePreferredSize = true;
  692. if (bufferSizeSamples < minBufferSize || bufferSizeSamples > maxBufferSize)
  693. shouldUsePreferredSize = true;
  694. preferredBufferSize = 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 = refreshBufferSizes();
  703. if (err == ASE_OK)
  704. {
  705. bufferSizeSamples = (int) preferredBufferSize;
  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. bufferSizes.sort();
  770. }
  771. double getSampleRate() const
  772. {
  773. double cr = 0;
  774. long err = asioObject->getSampleRate (&cr);
  775. JUCE_ASIO_LOG_ERROR ("getSampleRate", err);
  776. return cr;
  777. }
  778. void setSampleRate (double newRate)
  779. {
  780. if (currentSampleRate != newRate)
  781. {
  782. JUCE_ASIO_LOG ("rate change: " + String (currentSampleRate) + " to " + String (newRate));
  783. long err = asioObject->setSampleRate (newRate);
  784. if (err == ASE_NoClock && numClockSources > 0)
  785. {
  786. JUCE_ASIO_LOG ("trying to set a clock source..");
  787. Thread::sleep (10);
  788. err = asioObject->setClockSource (clocks[0].index);
  789. JUCE_ASIO_LOG_ERROR ("setClockSource2", err);
  790. Thread::sleep (10);
  791. err = asioObject->setSampleRate (newRate);
  792. }
  793. if (err == 0)
  794. currentSampleRate = newRate;
  795. // on fail, ignore the attempt to change rate, and run with the current one..
  796. }
  797. }
  798. void updateClockSources()
  799. {
  800. zeromem (clocks, sizeof (clocks));
  801. long numSources = numElementsInArray (clocks);
  802. asioObject->getClockSources (clocks, &numSources);
  803. numClockSources = (int) numSources;
  804. bool isSourceSet = false;
  805. // careful not to remove this loop because it does more than just logging!
  806. for (int i = 0; i < numClockSources; ++i)
  807. {
  808. String s ("clock: ");
  809. s += clocks[i].name;
  810. if (clocks[i].isCurrentSource)
  811. {
  812. isSourceSet = true;
  813. s << " (cur)";
  814. }
  815. JUCE_ASIO_LOG (s);
  816. }
  817. if (numClockSources > 1 && ! isSourceSet)
  818. {
  819. JUCE_ASIO_LOG ("setting clock source");
  820. long err = asioObject->setClockSource (clocks[0].index);
  821. JUCE_ASIO_LOG_ERROR ("setClockSource1", err);
  822. Thread::sleep (20);
  823. }
  824. else
  825. {
  826. if (numClockSources == 0)
  827. JUCE_ASIO_LOG ("no clock sources!");
  828. }
  829. }
  830. void readLatencies()
  831. {
  832. inputLatency = outputLatency = 0;
  833. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  834. JUCE_ASIO_LOG ("getLatencies() failed");
  835. else
  836. JUCE_ASIO_LOG ("Latencies: in = " + String ((int) inputLatency) + ", out = " + String ((int) outputLatency));
  837. }
  838. void createDummyBuffers (long preferredSize)
  839. {
  840. numActiveInputChans = 0;
  841. numActiveOutputChans = 0;
  842. ASIOBufferInfo* info = bufferInfos;
  843. int numChans = 0;
  844. for (int i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  845. {
  846. info->isInput = 1;
  847. info->channelNum = i;
  848. info->buffers[0] = info->buffers[1] = nullptr;
  849. ++info;
  850. ++numChans;
  851. }
  852. const int outputBufferIndex = numChans;
  853. for (int i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  854. {
  855. info->isInput = 0;
  856. info->channelNum = i;
  857. info->buffers[0] = info->buffers[1] = nullptr;
  858. ++info;
  859. ++numChans;
  860. }
  861. setCallbackFunctions();
  862. JUCE_ASIO_LOG ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  863. if (preferredSize > 0)
  864. {
  865. long err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  866. JUCE_ASIO_LOG_ERROR ("dummy buffers", err);
  867. }
  868. long newInps = 0, newOuts = 0;
  869. asioObject->getChannels (&newInps, &newOuts);
  870. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  871. {
  872. totalNumInputChans = newInps;
  873. totalNumOutputChans = newOuts;
  874. JUCE_ASIO_LOG (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  875. }
  876. updateSampleRates();
  877. reloadChannelNames();
  878. for (int i = 0; i < totalNumOutputChans; ++i)
  879. {
  880. ASIOChannelInfo channelInfo = { 0 };
  881. channelInfo.channel = i;
  882. channelInfo.isInput = 0;
  883. asioObject->getChannelInfo (&channelInfo);
  884. outputFormat[i] = ASIOSampleFormat (channelInfo.type);
  885. if (i < 2)
  886. {
  887. // clear the channels that are used with the dummy stuff
  888. outputFormat[i].clear (bufferInfos [outputBufferIndex + i].buffers[0], preferredBufferSize);
  889. outputFormat[i].clear (bufferInfos [outputBufferIndex + i].buffers[1], preferredBufferSize);
  890. }
  891. }
  892. }
  893. void removeCurrentDriver()
  894. {
  895. if (asioObject != nullptr)
  896. {
  897. asioObject->Release();
  898. asioObject = nullptr;
  899. }
  900. }
  901. bool loadDriver()
  902. {
  903. removeCurrentDriver();
  904. bool crashed = false;
  905. bool ok = tryCreatingDriver (crashed);
  906. if (crashed)
  907. JUCE_ASIO_LOG ("** Driver crashed while being opened");
  908. return ok;
  909. }
  910. bool tryCreatingDriver (bool& crashed)
  911. {
  912. #if ! JUCE_MINGW
  913. __try
  914. #endif
  915. {
  916. return CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  917. classId, (void**) &asioObject) == S_OK;
  918. }
  919. #if ! JUCE_MINGW
  920. __except (EXCEPTION_EXECUTE_HANDLER) { crashed = true; }
  921. return false;
  922. #endif
  923. }
  924. String getLastDriverError() const
  925. {
  926. jassert (asioObject != nullptr);
  927. char buffer [512] = { 0 };
  928. asioObject->getErrorMessage (buffer);
  929. return String (buffer, sizeof (buffer) - 1);
  930. }
  931. String initDriver()
  932. {
  933. if (asioObject == nullptr)
  934. return "No Driver";
  935. const bool initOk = !! asioObject->init (juce_messageWindowHandle);
  936. String driverError;
  937. // Get error message if init() failed, or if it's a buggy Denon driver,
  938. // which returns true from init() even when it fails.
  939. if ((! initOk) || getName().containsIgnoreCase ("denon dj"))
  940. driverError = getLastDriverError();
  941. if ((! initOk) && driverError.isEmpty())
  942. driverError = "Driver failed to initialise";
  943. if (driverError.isEmpty())
  944. {
  945. char buffer [512];
  946. asioObject->getDriverName (buffer); // just in case any flimsy drivers expect this to be called..
  947. }
  948. return driverError;
  949. }
  950. String openDevice()
  951. {
  952. // open the device and get its info..
  953. JUCE_ASIO_LOG ("opening device: " + getName());
  954. needToReset = false;
  955. outputChannelNames.clear();
  956. inputChannelNames.clear();
  957. bufferSizes.clear();
  958. sampleRates.clear();
  959. deviceIsOpen = false;
  960. totalNumInputChans = 0;
  961. totalNumOutputChans = 0;
  962. numActiveInputChans = 0;
  963. numActiveOutputChans = 0;
  964. currentCallback = nullptr;
  965. error.clear();
  966. if (getName().isEmpty())
  967. return error;
  968. long err = 0;
  969. if (loadDriver())
  970. {
  971. if ((error = initDriver()).isEmpty())
  972. {
  973. numActiveInputChans = 0;
  974. numActiveOutputChans = 0;
  975. totalNumInputChans = 0;
  976. totalNumOutputChans = 0;
  977. if (asioObject != nullptr
  978. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  979. {
  980. JUCE_ASIO_LOG (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  981. const int chansToAllocate = totalNumInputChans + totalNumOutputChans + 4;
  982. bufferInfos.calloc (chansToAllocate);
  983. inBuffers.calloc (chansToAllocate);
  984. outBuffers.calloc (chansToAllocate);
  985. inputFormat.calloc (chansToAllocate);
  986. outputFormat.calloc (chansToAllocate);
  987. if ((err = refreshBufferSizes()) == 0)
  988. {
  989. addBufferSizes (minBufferSize, maxBufferSize, preferredBufferSize, bufferGranularity);
  990. double currentRate = getSampleRate();
  991. if (currentRate < 1.0 || currentRate > 192001.0)
  992. {
  993. JUCE_ASIO_LOG ("setting default sample rate");
  994. err = asioObject->setSampleRate (44100.0);
  995. JUCE_ASIO_LOG_ERROR ("setting sample rate", err);
  996. currentRate = getSampleRate();
  997. }
  998. currentSampleRate = currentRate;
  999. postOutput = (asioObject->outputReady() == 0);
  1000. if (postOutput)
  1001. JUCE_ASIO_LOG ("outputReady true");
  1002. updateSampleRates();
  1003. readLatencies(); // ..doing these steps because cubase does so at this stage
  1004. createDummyBuffers (preferredBufferSize); // in initialisation, and some devices fail if we don't.
  1005. readLatencies();
  1006. // start and stop because cubase does it..
  1007. err = asioObject->start();
  1008. // ignore an error here, as it might start later after setting other stuff up
  1009. JUCE_ASIO_LOG_ERROR ("start", err);
  1010. Thread::sleep (80);
  1011. asioObject->stop();
  1012. }
  1013. else
  1014. {
  1015. error = "Can't detect buffer sizes";
  1016. }
  1017. }
  1018. else
  1019. {
  1020. error = "Can't detect asio channels";
  1021. }
  1022. }
  1023. }
  1024. else
  1025. {
  1026. error = "No such device";
  1027. }
  1028. if (error.isNotEmpty())
  1029. {
  1030. JUCE_ASIO_LOG_ERROR (error, err);
  1031. disposeBuffers();
  1032. removeCurrentDriver();
  1033. }
  1034. else
  1035. {
  1036. JUCE_ASIO_LOG ("device open");
  1037. }
  1038. deviceIsOpen = false;
  1039. needToReset = false;
  1040. stopTimer();
  1041. return error;
  1042. }
  1043. void disposeBuffers()
  1044. {
  1045. if (asioObject != nullptr && buffersCreated)
  1046. {
  1047. buffersCreated = false;
  1048. asioObject->disposeBuffers();
  1049. }
  1050. }
  1051. //==============================================================================
  1052. void JUCE_ASIOCALLBACK callback (const long index)
  1053. {
  1054. if (isStarted)
  1055. {
  1056. bufferIndex = index;
  1057. processBuffer();
  1058. }
  1059. else
  1060. {
  1061. if (postOutput && (asioObject != nullptr))
  1062. asioObject->outputReady();
  1063. }
  1064. calledback = true;
  1065. }
  1066. void processBuffer()
  1067. {
  1068. const ASIOBufferInfo* const infos = bufferInfos;
  1069. const int bi = bufferIndex;
  1070. const ScopedLock sl (callbackLock);
  1071. if (bi >= 0)
  1072. {
  1073. const int samps = currentBlockSizeSamples;
  1074. if (currentCallback != nullptr)
  1075. {
  1076. for (int i = 0; i < numActiveInputChans; ++i)
  1077. {
  1078. jassert (inBuffers[i] != nullptr);
  1079. inputFormat[i].convertToFloat (infos[i].buffers[bi], inBuffers[i], samps);
  1080. }
  1081. currentCallback->audioDeviceIOCallback (const_cast<const float**> (inBuffers.getData()), numActiveInputChans,
  1082. outBuffers, numActiveOutputChans, samps);
  1083. for (int i = 0; i < numActiveOutputChans; ++i)
  1084. {
  1085. jassert (outBuffers[i] != nullptr);
  1086. outputFormat[i].convertFromFloat (outBuffers[i], infos [numActiveInputChans + i].buffers[bi], samps);
  1087. }
  1088. }
  1089. else
  1090. {
  1091. for (int i = 0; i < numActiveOutputChans; ++i)
  1092. outputFormat[i].clear (infos[numActiveInputChans + i].buffers[bi], samps);
  1093. }
  1094. }
  1095. if (postOutput)
  1096. asioObject->outputReady();
  1097. }
  1098. long asioMessagesCallback (long selector, long value)
  1099. {
  1100. switch (selector)
  1101. {
  1102. case kAsioSelectorSupported:
  1103. if (value == kAsioResetRequest || value == kAsioEngineVersion || value == kAsioResyncRequest
  1104. || value == kAsioLatenciesChanged || value == kAsioSupportsInputMonitor)
  1105. return 1;
  1106. break;
  1107. case kAsioBufferSizeChange: JUCE_ASIO_LOG ("kAsioBufferSizeChange"); resetRequest(); return 1;
  1108. case kAsioResetRequest: JUCE_ASIO_LOG ("kAsioResetRequest"); resetRequest(); return 1;
  1109. case kAsioResyncRequest: JUCE_ASIO_LOG ("kAsioResyncRequest"); resetRequest(); return 1;
  1110. case kAsioLatenciesChanged: JUCE_ASIO_LOG ("kAsioLatenciesChanged"); return 1;
  1111. case kAsioEngineVersion: return 2;
  1112. case kAsioSupportsTimeInfo:
  1113. case kAsioSupportsTimeCode: return 0;
  1114. }
  1115. return 0;
  1116. }
  1117. //==============================================================================
  1118. template <int deviceIndex>
  1119. struct ASIOCallbackFunctions
  1120. {
  1121. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback (ASIOTime*, long index, long)
  1122. {
  1123. if (currentASIODev[deviceIndex] != nullptr)
  1124. currentASIODev[deviceIndex]->callback (index);
  1125. return nullptr;
  1126. }
  1127. static void JUCE_ASIOCALLBACK bufferSwitchCallback (long index, long)
  1128. {
  1129. if (currentASIODev[deviceIndex] != nullptr)
  1130. currentASIODev[deviceIndex]->callback (index);
  1131. }
  1132. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, void*, double*)
  1133. {
  1134. return currentASIODev[deviceIndex] != nullptr
  1135. ? currentASIODev[deviceIndex]->asioMessagesCallback (selector, value)
  1136. : 0;
  1137. }
  1138. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  1139. {
  1140. if (currentASIODev[deviceIndex] != nullptr)
  1141. currentASIODev[deviceIndex]->resetRequest();
  1142. }
  1143. static void setCallbacks (ASIOCallbacks& callbacks) noexcept
  1144. {
  1145. callbacks.bufferSwitch = &bufferSwitchCallback;
  1146. callbacks.asioMessage = &asioMessagesCallback;
  1147. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback;
  1148. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  1149. }
  1150. static void setCallbacksForDevice (ASIOCallbacks& callbacks, ASIOAudioIODevice* device) noexcept
  1151. {
  1152. if (currentASIODev[deviceIndex] == device)
  1153. setCallbacks (callbacks);
  1154. else
  1155. ASIOCallbackFunctions<deviceIndex + 1>::setCallbacksForDevice (callbacks, device);
  1156. }
  1157. };
  1158. void setCallbackFunctions() noexcept
  1159. {
  1160. /**/ if (currentASIODev[0] == this) ASIOCallbackFunctions<0>::setCallbacks (callbacks);
  1161. else if (currentASIODev[1] == this) ASIOCallbackFunctions<1>::setCallbacks (callbacks);
  1162. else if (currentASIODev[2] == this) ASIOCallbackFunctions<2>::setCallbacks (callbacks);
  1163. else if (currentASIODev[3] == this) ASIOCallbackFunctions<3>::setCallbacks (callbacks);
  1164. else jassertfalse;
  1165. }
  1166. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice)
  1167. };
  1168. template <>
  1169. struct ASIOAudioIODevice::ASIOCallbackFunctions <sizeof(currentASIODev) / sizeof(currentASIODev[0])>
  1170. {
  1171. static void setCallbacksForDevice (ASIOCallbacks&, ASIOAudioIODevice*) noexcept {}
  1172. };
  1173. //==============================================================================
  1174. class ASIOAudioIODeviceType : public AudioIODeviceType
  1175. {
  1176. public:
  1177. ASIOAudioIODeviceType()
  1178. : AudioIODeviceType ("ASIO"),
  1179. hasScanned (false)
  1180. {
  1181. }
  1182. ~ASIOAudioIODeviceType()
  1183. {
  1184. masterReference.clear();
  1185. }
  1186. //==============================================================================
  1187. void scanForDevices()
  1188. {
  1189. hasScanned = true;
  1190. deviceNames.clear();
  1191. classIds.clear();
  1192. HKEY hk = 0;
  1193. int index = 0;
  1194. if (RegOpenKey (HKEY_LOCAL_MACHINE, _T("software\\asio"), &hk) == ERROR_SUCCESS)
  1195. {
  1196. TCHAR name [256];
  1197. while (RegEnumKey (hk, index++, name, numElementsInArray (name)) == ERROR_SUCCESS)
  1198. addDriverInfo (name, hk);
  1199. RegCloseKey (hk);
  1200. }
  1201. }
  1202. StringArray getDeviceNames (bool /*wantInputNames*/) const
  1203. {
  1204. jassert (hasScanned); // need to call scanForDevices() before doing this
  1205. return deviceNames;
  1206. }
  1207. int getDefaultDeviceIndex (bool) const
  1208. {
  1209. jassert (hasScanned); // need to call scanForDevices() before doing this
  1210. for (int i = deviceNames.size(); --i >= 0;)
  1211. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  1212. return i; // asio4all is a safe choice for a default..
  1213. #if JUCE_DEBUG
  1214. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  1215. return 1; // (the digi m-box driver crashes the app when you run
  1216. // it in the debugger, which can be a bit annoying)
  1217. #endif
  1218. return 0;
  1219. }
  1220. static int findFreeSlot()
  1221. {
  1222. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  1223. if (currentASIODev[i] == 0)
  1224. return i;
  1225. jassertfalse; // unfortunately you can only have a finite number
  1226. // of ASIO devices open at the same time..
  1227. return -1;
  1228. }
  1229. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  1230. {
  1231. jassert (hasScanned); // need to call scanForDevices() before doing this
  1232. return d == nullptr ? -1 : deviceNames.indexOf (d->getName());
  1233. }
  1234. bool hasSeparateInputsAndOutputs() const { return false; }
  1235. AudioIODevice* createDevice (const String& outputDeviceName,
  1236. const String& inputDeviceName)
  1237. {
  1238. // ASIO can't open two different devices for input and output - they must be the same one.
  1239. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  1240. jassert (hasScanned); // need to call scanForDevices() before doing this
  1241. const String deviceName (outputDeviceName.isNotEmpty() ? outputDeviceName
  1242. : inputDeviceName);
  1243. const int index = deviceNames.indexOf (deviceName);
  1244. if (index >= 0)
  1245. {
  1246. const int freeSlot = findFreeSlot();
  1247. if (freeSlot >= 0)
  1248. return new ASIOAudioIODevice (this, deviceName,
  1249. classIds.getReference (index), freeSlot);
  1250. }
  1251. return nullptr;
  1252. }
  1253. void sendDeviceChangeToListeners()
  1254. {
  1255. callDeviceChangeListeners();
  1256. }
  1257. WeakReference<ASIOAudioIODeviceType>::Master masterReference;
  1258. private:
  1259. StringArray deviceNames;
  1260. Array<CLSID> classIds;
  1261. bool hasScanned;
  1262. //==============================================================================
  1263. static bool checkClassIsOk (const String& classId)
  1264. {
  1265. HKEY hk = 0;
  1266. bool ok = false;
  1267. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  1268. {
  1269. int index = 0;
  1270. TCHAR name [512];
  1271. while (RegEnumKey (hk, index++, name, numElementsInArray (name)) == ERROR_SUCCESS)
  1272. {
  1273. if (classId.equalsIgnoreCase (name))
  1274. {
  1275. HKEY subKey, pathKey;
  1276. if (RegOpenKeyEx (hk, name, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  1277. {
  1278. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  1279. {
  1280. TCHAR pathName [1024] = { 0 };
  1281. DWORD dtype = REG_SZ;
  1282. DWORD dsize = sizeof (pathName);
  1283. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  1284. // In older code, this used to check for the existance of the file, but there are situations
  1285. // where our process doesn't have access to it, but where the driver still loads ok..
  1286. ok = (pathName[0] != 0);
  1287. RegCloseKey (pathKey);
  1288. }
  1289. RegCloseKey (subKey);
  1290. }
  1291. break;
  1292. }
  1293. }
  1294. RegCloseKey (hk);
  1295. }
  1296. return ok;
  1297. }
  1298. //==============================================================================
  1299. void addDriverInfo (const String& keyName, HKEY hk)
  1300. {
  1301. HKEY subKey;
  1302. if (RegOpenKeyEx (hk, keyName.toWideCharPointer(), 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  1303. {
  1304. TCHAR buf [256] = { 0 };
  1305. DWORD dtype = REG_SZ;
  1306. DWORD dsize = sizeof (buf);
  1307. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  1308. {
  1309. if (dsize > 0 && checkClassIsOk (buf))
  1310. {
  1311. CLSID classId;
  1312. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  1313. {
  1314. dtype = REG_SZ;
  1315. dsize = sizeof (buf);
  1316. String deviceName;
  1317. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  1318. deviceName = buf;
  1319. else
  1320. deviceName = keyName;
  1321. JUCE_ASIO_LOG ("found " + deviceName);
  1322. deviceNames.add (deviceName);
  1323. classIds.add (classId);
  1324. }
  1325. }
  1326. RegCloseKey (subKey);
  1327. }
  1328. }
  1329. }
  1330. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType)
  1331. };
  1332. void sendASIODeviceChangeToListeners (ASIOAudioIODeviceType* type)
  1333. {
  1334. if (type != nullptr)
  1335. type->sendDeviceChangeToListeners();
  1336. }
  1337. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO()
  1338. {
  1339. return new ASIOAudioIODeviceType();
  1340. }