native_midi.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. native_midi: Hardware Midi support for the SDL_mixer library
  3. Copyright (C) 2000,2001 Florian 'Proff' Schulze
  4. This library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Library General Public
  6. License as published by the Free Software Foundation; either
  7. version 2 of the License, or (at your option) any later version.
  8. This library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Library General Public License for more details.
  12. You should have received a copy of the GNU Library General Public
  13. License along with this library; if not, write to the Free
  14. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  15. Florian 'Proff' Schulze
  16. florian.proff.schulze@gmx.net
  17. */
  18. #include "SDL.h"
  19. /* everything below is currently one very big bad hack ;) Proff */
  20. #define WIN32_LEAN_AND_MEAN
  21. #include <windows.h>
  22. #include <mmsystem.h>
  23. #include <stdlib.h>
  24. #include <memory>
  25. #include <future>
  26. #include <thread>
  27. #include <condition_variable>
  28. #include <mutex>
  29. #include <atomic>
  30. #include <vector>
  31. #include "native_midi/native_midi.h"
  32. #include "native_midi/native_midi_common.h"
  33. enum class MidiSystemMessage {
  34. Exclusive = 0,
  35. TimeCode = 1,
  36. SongPositionPointer = 2,
  37. SongSelect = 3,
  38. TuneRequest = 6,
  39. EndOfExclusive = 7,
  40. TimingClock = 8,
  41. Start = 10,
  42. Continue = 11,
  43. Stop = 12,
  44. ActiveSensing = 14,
  45. SystemReset = 15
  46. };
  47. struct MidiMessage
  48. {
  49. virtual MMRESULT Send(HMIDIOUT hmo) = 0;
  50. };
  51. struct MidiShortMessage
  52. : public MidiMessage
  53. {
  54. uint32_t data;
  55. MidiShortMessage(uint32_t data) : data(data) {}
  56. virtual MMRESULT Send(HMIDIOUT hmo) { return midiOutShortMsg(hmo, data); }
  57. };
  58. struct MidiLongMessage
  59. : public MidiMessage
  60. {
  61. MIDIHDR hdr;
  62. MidiLongMessage(uint8_t* data, int length)
  63. {
  64. memset(&hdr, 0, sizeof(MIDIHDR));
  65. hdr.lpData = (LPSTR)malloc(length);
  66. hdr.dwBufferLength = hdr.dwBytesRecorded = length;
  67. memcpy(hdr.lpData, data, length);
  68. }
  69. virtual MMRESULT Send(HMIDIOUT hmo)
  70. {
  71. MMRESULT retval;
  72. if (MMSYSERR_NOERROR == (retval = midiOutPrepareHeader(hmo, &hdr, sizeof(MIDIHDR))))
  73. {
  74. retval = midiOutLongMsg(hmo, &hdr, sizeof(MIDIHDR));
  75. midiOutUnprepareHeader(hmo, &hdr, sizeof(MIDIHDR));
  76. }
  77. return retval;
  78. }
  79. };
  80. struct MidiResetMessage
  81. : public MidiMessage
  82. {
  83. virtual MMRESULT Send(HMIDIOUT hmo) { return midiOutReset(hmo); }
  84. };
  85. struct MidiCustomMessage
  86. : public MidiMessage
  87. {
  88. uint32_t message;
  89. uint32_t data1;
  90. uint32_t data2;
  91. MidiCustomMessage(uint8_t status, uint8_t data1, uint8_t data2)
  92. : message(status), data1(data1), data2(data2)
  93. {}
  94. virtual MMRESULT SendEvent(HMIDIOUT hmo) { return midiOutMessage(hmo, message, data1, data2); }
  95. };
  96. struct MidiEvent
  97. {
  98. std::unique_ptr<MidiMessage> message;
  99. uint32_t deltaTime; // time in ticks
  100. uint32_t tempo; // microseconds per quarter note
  101. std::chrono::system_clock::duration DeltaTimeAsTick(uint16_t ppq)
  102. {
  103. return std::chrono::system_clock::duration((int64_t)deltaTime * tempo * 10 / ppq);
  104. }
  105. MMRESULT Send(HMIDIOUT hmo) { return message->Send(hmo); }
  106. };
  107. struct _NativeMidiSong {
  108. std::vector<MidiEvent> Events;
  109. std::thread Thread;
  110. std::mutex Mutex;
  111. std::condition_variable Stop;
  112. HMIDIOUT Synthesizer;
  113. int Size;
  114. int Position;
  115. Uint16 ppq; // parts (ticks) per quarter note
  116. volatile bool Playing;
  117. bool Loaded;
  118. bool Looping;
  119. _NativeMidiSong()
  120. : Synthesizer(nullptr), Size(0), Position(0)
  121. , ppq(0), Playing(false), Loaded(false), Looping(false)
  122. { }
  123. };
  124. static void MIDItoStream(NativeMidiSong *song, MIDIEvent *eventlist)
  125. {
  126. int eventcount = 0, prevtime = 0, tempo = 500000;
  127. for (MIDIEvent* event = eventlist; event; event = event->next)
  128. {
  129. if (event->status != 0xFF)
  130. eventcount++;
  131. }
  132. song->Events.resize(song->Size = eventcount);
  133. song->Position = 0;
  134. song->Loaded = true;
  135. eventcount = 0;
  136. for (MIDIEvent* event = eventlist; event; event = event->next)
  137. {
  138. MidiMessage* message = nullptr;
  139. int status = (event->status & 0xF0) >> 4;
  140. switch (status)
  141. {
  142. case MIDI_STATUS_NOTE_OFF:
  143. case MIDI_STATUS_NOTE_ON:
  144. case MIDI_STATUS_AFTERTOUCH:
  145. case MIDI_STATUS_CONTROLLER:
  146. case MIDI_STATUS_PROG_CHANGE:
  147. case MIDI_STATUS_PRESSURE:
  148. case MIDI_STATUS_PITCH_WHEEL:
  149. message = new MidiShortMessage(event->status | (event->data[0] << 8) | (event->data[1] << 16));
  150. break;
  151. case MIDI_STATUS_SYSEX:
  152. switch ((MidiSystemMessage)(event->status & 0xF))
  153. {
  154. case MidiSystemMessage::Exclusive:
  155. message = new MidiLongMessage(event->extraData, event->extraLen);
  156. break;
  157. case MidiSystemMessage::TimeCode:
  158. case MidiSystemMessage::SongSelect:
  159. message = new MidiShortMessage(event->status | (event->extraData[0] << 8));
  160. break;
  161. case MidiSystemMessage::SongPositionPointer:
  162. message = new MidiShortMessage(event->status | (event->extraData[0] << 8) | (event->extraData[1] << 16));
  163. break;
  164. case MidiSystemMessage::TuneRequest:
  165. case MidiSystemMessage::TimingClock:
  166. case MidiSystemMessage::Start:
  167. case MidiSystemMessage::Continue:
  168. case MidiSystemMessage::Stop:
  169. case MidiSystemMessage::ActiveSensing:
  170. message = new MidiShortMessage(event->status);
  171. break;
  172. case MidiSystemMessage::SystemReset:
  173. // This message is only used as meta-event in MIDI files
  174. if (event->data[0] == 0x51)
  175. tempo = (event->extraData[0] << 16) | (event->extraData[1] << 8) | event->extraData[2];
  176. break;
  177. }
  178. break;
  179. }
  180. if (message)
  181. {
  182. auto evt = &song->Events[eventcount++];
  183. evt->message.reset(message);
  184. evt->deltaTime = event->time - prevtime;
  185. evt->tempo = tempo;
  186. prevtime = event->time;
  187. }
  188. }
  189. }
  190. int native_midi_detect()
  191. {
  192. HMIDIOUT out;
  193. if (MMSYSERR_NOERROR == midiOutOpen(&out, MIDI_MAPPER, 0, 0, CALLBACK_NULL))
  194. {
  195. midiOutClose(out);
  196. return 1;
  197. }
  198. return 0;
  199. }
  200. NativeMidiSong *native_midi_loadsong(const char *midifile)
  201. {
  202. /* Attempt to load the midi file */
  203. auto rw = SDL_RWFromFile(midifile, "rb");
  204. return native_midi_loadsong_RW(rw);
  205. }
  206. NativeMidiSong *native_midi_loadsong_RW(SDL_RWops *rw)
  207. {
  208. std::unique_ptr<NativeMidiSong> newsong(new NativeMidiSong);
  209. if (newsong)
  210. {
  211. auto eventlist = CreateMIDIEventList(rw, &newsong->ppq);
  212. if (eventlist)
  213. {
  214. MIDItoStream(newsong.get(), eventlist);
  215. FreeMIDIEventList(eventlist);
  216. if (midiOutOpen(&newsong->Synthesizer, MIDI_MAPPER, NULL, 0, CALLBACK_NULL) == MMSYSERR_NOERROR)
  217. return newsong.release();
  218. }
  219. }
  220. return nullptr;
  221. }
  222. void native_midi_freesong(NativeMidiSong *song)
  223. {
  224. if (song)
  225. {
  226. native_midi_stop(song);
  227. if (song->Synthesizer)
  228. midiOutClose(song->Synthesizer);
  229. delete song;
  230. }
  231. }
  232. void native_midi_start(NativeMidiSong *song, int looping)
  233. {
  234. if (!song) return;
  235. native_midi_stop(song);
  236. song->Playing = true;
  237. song->Looping = looping ? true : false;
  238. song->Thread = std::move(std::thread([](NativeMidiSong *song)->void {
  239. auto time = std::chrono::system_clock::now();
  240. while (song->Playing)
  241. {
  242. do
  243. {
  244. song->Events[song->Position++].Send(song->Synthesizer);
  245. } while (song->Position < song->Size && song->Events[song->Position].deltaTime == 0);
  246. if (song->Position < song->Size)
  247. {
  248. time += std::chrono::system_clock::duration(song->Events[song->Position].DeltaTimeAsTick(song->ppq));
  249. while (song->Playing)
  250. {
  251. if (song->Stop.wait_until(std::unique_lock<std::mutex>(song->Mutex), time) == std::cv_status::timeout)
  252. break;
  253. }
  254. }
  255. else if (song->Playing = song->Looping)
  256. {
  257. song->Position = 0;
  258. midiOutReset(song->Synthesizer);
  259. }
  260. }
  261. }, song));
  262. }
  263. void native_midi_stop(NativeMidiSong *song)
  264. {
  265. if (song)
  266. {
  267. song->Playing = false;
  268. song->Stop.notify_all();
  269. if (song->Thread.joinable())
  270. song->Thread.join();
  271. song->Thread = std::move(std::thread());
  272. if (song->Synthesizer)
  273. midiOutReset(song->Synthesizer);
  274. }
  275. }
  276. int native_midi_active(NativeMidiSong *song)
  277. {
  278. return (song && song->Playing) ? 1 : 0;
  279. }
  280. void native_midi_setvolume(NativeMidiSong *song, int volume)
  281. {
  282. if (song && song->Synthesizer)
  283. {
  284. uint16_t calcVolume;
  285. if (volume > 127)
  286. volume = 127;
  287. if (volume < 0)
  288. volume = 0;
  289. calcVolume = volume << 9;
  290. midiOutSetVolume(song->Synthesizer, MAKELONG(calcVolume, calcVolume));
  291. }
  292. }
  293. const char *native_midi_error(NativeMidiSong *song)
  294. {
  295. return "";
  296. }