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.

500 lines
13KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. class MidiInCollector
  24. {
  25. public:
  26. MidiInCollector (MidiInput* const input_,
  27. MidiInputCallback& callback_)
  28. : deviceHandle (0),
  29. input (input_),
  30. callback (callback_),
  31. concatenator (4096),
  32. isStarted (false),
  33. startTime (0)
  34. {
  35. }
  36. ~MidiInCollector()
  37. {
  38. stop();
  39. if (deviceHandle != 0)
  40. {
  41. for (int count = 5; --count >= 0;)
  42. {
  43. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  44. break;
  45. Sleep (20);
  46. }
  47. }
  48. }
  49. //==============================================================================
  50. void handleMessage (const uint8* bytes, const uint32 timeStamp)
  51. {
  52. if (bytes[0] >= 0x80 && isStarted)
  53. {
  54. concatenator.pushMidiData (bytes, MidiMessage::getMessageLengthFromFirstByte (bytes[0]),
  55. convertTimeStamp (timeStamp), input, callback);
  56. writeFinishedBlocks();
  57. }
  58. }
  59. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  60. {
  61. if (isStarted && hdr->dwBytesRecorded > 0)
  62. {
  63. concatenator.pushMidiData (hdr->lpData, (int) hdr->dwBytesRecorded,
  64. convertTimeStamp (timeStamp), input, callback);
  65. writeFinishedBlocks();
  66. }
  67. }
  68. void start()
  69. {
  70. if (deviceHandle != 0 && ! isStarted)
  71. {
  72. activeMidiCollectors.addIfNotAlreadyThere (this);
  73. for (int i = 0; i < (int) numHeaders; ++i)
  74. {
  75. headers[i].prepare (deviceHandle);
  76. headers[i].write (deviceHandle);
  77. }
  78. startTime = Time::getMillisecondCounterHiRes();
  79. MMRESULT res = midiInStart (deviceHandle);
  80. if (res == MMSYSERR_NOERROR)
  81. {
  82. concatenator.reset();
  83. isStarted = true;
  84. }
  85. else
  86. {
  87. unprepareAllHeaders();
  88. }
  89. }
  90. }
  91. void stop()
  92. {
  93. if (isStarted)
  94. {
  95. isStarted = false;
  96. midiInReset (deviceHandle);
  97. midiInStop (deviceHandle);
  98. activeMidiCollectors.removeFirstMatchingValue (this);
  99. unprepareAllHeaders();
  100. concatenator.reset();
  101. }
  102. }
  103. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance,
  104. DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  105. {
  106. MidiInCollector* const collector = reinterpret_cast<MidiInCollector*> (dwInstance);
  107. if (activeMidiCollectors.contains (collector))
  108. {
  109. if (uMsg == MIM_DATA)
  110. collector->handleMessage ((const uint8*) &midiMessage, (uint32) timeStamp);
  111. else if (uMsg == MIM_LONGDATA)
  112. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  113. }
  114. }
  115. HMIDIIN deviceHandle;
  116. private:
  117. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  118. MidiInput* input;
  119. MidiInputCallback& callback;
  120. MidiDataConcatenator concatenator;
  121. bool volatile isStarted;
  122. double startTime;
  123. class MidiHeader
  124. {
  125. public:
  126. MidiHeader() {}
  127. void prepare (HMIDIIN device)
  128. {
  129. zerostruct (hdr);
  130. hdr.lpData = data;
  131. hdr.dwBufferLength = (DWORD) numElementsInArray (data);
  132. midiInPrepareHeader (device, &hdr, sizeof (hdr));
  133. }
  134. void unprepare (HMIDIIN device)
  135. {
  136. if ((hdr.dwFlags & WHDR_DONE) != 0)
  137. {
  138. int c = 10;
  139. while (--c >= 0 && midiInUnprepareHeader (device, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  140. Thread::sleep (20);
  141. jassert (c >= 0);
  142. }
  143. }
  144. void write (HMIDIIN device)
  145. {
  146. hdr.dwBytesRecorded = 0;
  147. midiInAddBuffer (device, &hdr, sizeof (hdr));
  148. }
  149. void writeIfFinished (HMIDIIN device)
  150. {
  151. if ((hdr.dwFlags & WHDR_DONE) != 0)
  152. write (device);
  153. }
  154. private:
  155. MIDIHDR hdr;
  156. char data [256];
  157. JUCE_DECLARE_NON_COPYABLE (MidiHeader)
  158. };
  159. enum { numHeaders = 32 };
  160. MidiHeader headers [numHeaders];
  161. void writeFinishedBlocks()
  162. {
  163. for (int i = 0; i < (int) numHeaders; ++i)
  164. headers[i].writeIfFinished (deviceHandle);
  165. }
  166. void unprepareAllHeaders()
  167. {
  168. for (int i = 0; i < (int) numHeaders; ++i)
  169. headers[i].unprepare (deviceHandle);
  170. }
  171. double convertTimeStamp (uint32 timeStamp)
  172. {
  173. double t = startTime + timeStamp;
  174. const double now = Time::getMillisecondCounterHiRes();
  175. if (t > now)
  176. {
  177. if (t > now + 2.0)
  178. startTime -= 1.0;
  179. t = now;
  180. }
  181. return t * 0.001;
  182. }
  183. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector)
  184. };
  185. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  186. //==============================================================================
  187. StringArray MidiInput::getDevices()
  188. {
  189. StringArray s;
  190. const UINT num = midiInGetNumDevs();
  191. for (UINT i = 0; i < num; ++i)
  192. {
  193. MIDIINCAPS mc = { 0 };
  194. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  195. s.add (String (mc.szPname, sizeof (mc.szPname)));
  196. }
  197. return s;
  198. }
  199. int MidiInput::getDefaultDeviceIndex()
  200. {
  201. return 0;
  202. }
  203. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  204. {
  205. if (callback == nullptr)
  206. return nullptr;
  207. UINT deviceId = MIDI_MAPPER;
  208. int n = 0;
  209. String name;
  210. const UINT num = midiInGetNumDevs();
  211. for (UINT i = 0; i < num; ++i)
  212. {
  213. MIDIINCAPS mc = { 0 };
  214. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  215. {
  216. if (index == n)
  217. {
  218. deviceId = i;
  219. name = String (mc.szPname, (size_t) numElementsInArray (mc.szPname));
  220. break;
  221. }
  222. ++n;
  223. }
  224. }
  225. ScopedPointer<MidiInput> in (new MidiInput (name));
  226. ScopedPointer<MidiInCollector> collector (new MidiInCollector (in, *callback));
  227. HMIDIIN h;
  228. MMRESULT err = midiInOpen (&h, deviceId,
  229. (DWORD_PTR) &MidiInCollector::midiInCallback,
  230. (DWORD_PTR) (MidiInCollector*) collector,
  231. CALLBACK_FUNCTION);
  232. if (err == MMSYSERR_NOERROR)
  233. {
  234. collector->deviceHandle = h;
  235. in->internal = collector.release();
  236. return in.release();
  237. }
  238. return nullptr;
  239. }
  240. MidiInput::MidiInput (const String& name_)
  241. : name (name_),
  242. internal (0)
  243. {
  244. }
  245. MidiInput::~MidiInput()
  246. {
  247. delete static_cast<MidiInCollector*> (internal);
  248. }
  249. void MidiInput::start() { static_cast<MidiInCollector*> (internal)->start(); }
  250. void MidiInput::stop() { static_cast<MidiInCollector*> (internal)->stop(); }
  251. //==============================================================================
  252. struct MidiOutHandle
  253. {
  254. int refCount;
  255. UINT deviceId;
  256. HMIDIOUT handle;
  257. static Array<MidiOutHandle*> activeHandles;
  258. private:
  259. JUCE_LEAK_DETECTOR (MidiOutHandle)
  260. };
  261. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  262. //==============================================================================
  263. StringArray MidiOutput::getDevices()
  264. {
  265. StringArray s;
  266. const UINT num = midiOutGetNumDevs();
  267. for (UINT i = 0; i < num; ++i)
  268. {
  269. MIDIOUTCAPS mc = { 0 };
  270. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  271. s.add (String (mc.szPname, sizeof (mc.szPname)));
  272. }
  273. return s;
  274. }
  275. int MidiOutput::getDefaultDeviceIndex()
  276. {
  277. const UINT num = midiOutGetNumDevs();
  278. int n = 0;
  279. for (UINT i = 0; i < num; ++i)
  280. {
  281. MIDIOUTCAPS mc = { 0 };
  282. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  283. {
  284. if ((mc.wTechnology & MOD_MAPPER) != 0)
  285. return n;
  286. ++n;
  287. }
  288. }
  289. return 0;
  290. }
  291. MidiOutput* MidiOutput::openDevice (int index)
  292. {
  293. UINT deviceId = MIDI_MAPPER;
  294. const UINT num = midiOutGetNumDevs();
  295. int n = 0;
  296. String deviceName;
  297. for (UINT i = 0; i < num; ++i)
  298. {
  299. MIDIOUTCAPS mc = { 0 };
  300. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  301. {
  302. String name = String (mc.szPname, sizeof (mc.szPname));
  303. // use the microsoft sw synth as a default - best not to allow deviceId
  304. // to be MIDI_MAPPER, or else device sharing breaks
  305. if (name.containsIgnoreCase ("microsoft"))
  306. deviceId = i;
  307. if (index == n)
  308. {
  309. deviceName = name;
  310. deviceId = i;
  311. break;
  312. }
  313. ++n;
  314. }
  315. }
  316. for (int i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  317. {
  318. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  319. if (han->deviceId == deviceId)
  320. {
  321. han->refCount++;
  322. MidiOutput* const out = new MidiOutput (deviceName);
  323. out->internal = han;
  324. return out;
  325. }
  326. }
  327. for (int i = 4; --i >= 0;)
  328. {
  329. HMIDIOUT h = 0;
  330. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  331. if (res == MMSYSERR_NOERROR)
  332. {
  333. MidiOutHandle* const han = new MidiOutHandle();
  334. han->deviceId = deviceId;
  335. han->refCount = 1;
  336. han->handle = h;
  337. MidiOutHandle::activeHandles.add (han);
  338. MidiOutput* const out = new MidiOutput (deviceName);
  339. out->internal = han;
  340. return out;
  341. }
  342. else if (res == MMSYSERR_ALLOCATED)
  343. {
  344. Sleep (100);
  345. }
  346. else
  347. {
  348. break;
  349. }
  350. }
  351. return nullptr;
  352. }
  353. MidiOutput::~MidiOutput()
  354. {
  355. stopBackgroundThread();
  356. MidiOutHandle* const h = static_cast<MidiOutHandle*> (internal);
  357. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  358. {
  359. midiOutClose (h->handle);
  360. MidiOutHandle::activeHandles.removeFirstMatchingValue (h);
  361. delete h;
  362. }
  363. }
  364. void MidiOutput::sendMessageNow (const MidiMessage& message)
  365. {
  366. const MidiOutHandle* const handle = static_cast<const MidiOutHandle*> (internal);
  367. if (message.getRawDataSize() > 3 || message.isSysEx())
  368. {
  369. MIDIHDR h = { 0 };
  370. h.lpData = (char*) message.getRawData();
  371. h.dwBytesRecorded = h.dwBufferLength = (DWORD) message.getRawDataSize();
  372. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  373. {
  374. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  375. if (res == MMSYSERR_NOERROR)
  376. {
  377. while ((h.dwFlags & MHDR_DONE) == 0)
  378. Sleep (1);
  379. int count = 500; // 1 sec timeout
  380. while (--count >= 0)
  381. {
  382. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  383. if (res == MIDIERR_STILLPLAYING)
  384. Sleep (2);
  385. else
  386. break;
  387. }
  388. }
  389. }
  390. }
  391. else
  392. {
  393. for (int i = 0; i < 50; ++i)
  394. {
  395. if (midiOutShortMsg (handle->handle, *(unsigned int*) message.getRawData()) != MIDIERR_NOTREADY)
  396. break;
  397. Sleep (1);
  398. }
  399. }
  400. }