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_Midi.cpp 13KB

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