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.

490 lines
13KB

  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. 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 deviceHandle)
  122. {
  123. zerostruct (hdr);
  124. hdr.lpData = data;
  125. hdr.dwBufferLength = (DWORD) numElementsInArray (data);
  126. midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  127. }
  128. void unprepare (HMIDIIN deviceHandle)
  129. {
  130. if ((hdr.dwFlags & WHDR_DONE) != 0)
  131. {
  132. int c = 10;
  133. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  134. Thread::sleep (20);
  135. jassert (c >= 0);
  136. }
  137. }
  138. void write (HMIDIIN deviceHandle)
  139. {
  140. hdr.dwBytesRecorded = 0;
  141. midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  142. }
  143. void writeIfFinished (HMIDIIN deviceHandle)
  144. {
  145. if ((hdr.dwFlags & WHDR_DONE) != 0)
  146. write (deviceHandle);
  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. for (UINT i = 0; i < num; ++i)
  291. {
  292. MIDIOUTCAPS mc = { 0 };
  293. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  294. {
  295. // use the microsoft sw synth as a default - best not to allow deviceId
  296. // to be MIDI_MAPPER, or else device sharing breaks
  297. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  298. deviceId = i;
  299. if (index == n)
  300. {
  301. deviceId = i;
  302. break;
  303. }
  304. ++n;
  305. }
  306. }
  307. for (int i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  308. {
  309. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  310. if (han->deviceId == deviceId)
  311. {
  312. han->refCount++;
  313. MidiOutput* const out = new MidiOutput();
  314. out->internal = han;
  315. return out;
  316. }
  317. }
  318. for (int i = 4; --i >= 0;)
  319. {
  320. HMIDIOUT h = 0;
  321. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  322. if (res == MMSYSERR_NOERROR)
  323. {
  324. MidiOutHandle* const han = new MidiOutHandle();
  325. han->deviceId = deviceId;
  326. han->refCount = 1;
  327. han->handle = h;
  328. MidiOutHandle::activeHandles.add (han);
  329. MidiOutput* const out = new MidiOutput();
  330. out->internal = han;
  331. return out;
  332. }
  333. else if (res == MMSYSERR_ALLOCATED)
  334. {
  335. Sleep (100);
  336. }
  337. else
  338. {
  339. break;
  340. }
  341. }
  342. return nullptr;
  343. }
  344. MidiOutput::~MidiOutput()
  345. {
  346. stopBackgroundThread();
  347. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  348. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  349. {
  350. midiOutClose (h->handle);
  351. MidiOutHandle::activeHandles.removeFirstMatchingValue (h);
  352. delete h;
  353. }
  354. }
  355. void MidiOutput::sendMessageNow (const MidiMessage& message)
  356. {
  357. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  358. if (message.getRawDataSize() > 3 || message.isSysEx())
  359. {
  360. MIDIHDR h = { 0 };
  361. h.lpData = (char*) message.getRawData();
  362. h.dwBytesRecorded = h.dwBufferLength = (DWORD) message.getRawDataSize();
  363. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  364. {
  365. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  366. if (res == MMSYSERR_NOERROR)
  367. {
  368. while ((h.dwFlags & MHDR_DONE) == 0)
  369. Sleep (1);
  370. int count = 500; // 1 sec timeout
  371. while (--count >= 0)
  372. {
  373. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  374. if (res == MIDIERR_STILLPLAYING)
  375. Sleep (2);
  376. else
  377. break;
  378. }
  379. }
  380. }
  381. }
  382. else
  383. {
  384. for (int i = 0; i < 50; ++i)
  385. {
  386. if (midiOutShortMsg (handle->handle, *(unsigned int*) message.getRawData()) != MIDIERR_NOTREADY)
  387. break;
  388. Sleep (1);
  389. }
  390. }
  391. }