native_midi.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /* -*- mode: c; tab-width: 4; c-basic-offset: 4; c-file-style: "linux" -*- */
  2. //
  3. // Copyright (c) 2009-2011, Wei Mingzhi <whistler_wmz@users.sf.net>.
  4. // Copyright (c) 2011-2017, SDLPAL development team.
  5. // All rights reserved.
  6. //
  7. // This file is part of SDLPAL.
  8. //
  9. // SDLPAL is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU General Public License as published by
  11. // the Free Software Foundation, either version 3 of the License, or
  12. // (at your option) any later version.
  13. //
  14. // This program is distributed in the hope that it will be useful,
  15. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. // GNU General Public License for more details.
  18. //
  19. // You should have received a copy of the GNU General Public License
  20. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. //
  22. // native_midi.cpp: Native Windows Runtime MIDI player for SDLPal.
  23. // @Author: Lou Yihua, 2017
  24. //
  25. #include "pch.h"
  26. #include "AsyncHelper.h"
  27. #include "NativeBuffer.h"
  28. #include <SDL.h>
  29. #include <memory>
  30. #include <future>
  31. #include <thread>
  32. #include <condition_variable>
  33. #include <mutex>
  34. #include <atomic>
  35. #include "native_midi/native_midi.h"
  36. #include "native_midi/native_midi_common.h"
  37. using namespace Windows::Devices::Midi;
  38. struct MidiEvent
  39. {
  40. IMidiMessage^ message;
  41. uint32_t deltaTime; // time in ticks
  42. uint32_t tempo; // microseconds per quarter note
  43. std::chrono::system_clock::duration DeltaTimeAsTick(uint16_t ppq)
  44. {
  45. return std::chrono::system_clock::duration((int64_t)deltaTime * tempo * 10 / ppq);
  46. }
  47. void Send(MidiSynthesizer^ synthesizer) { synthesizer->SendMessage(message); }
  48. };
  49. struct _NativeMidiSong {
  50. std::vector<MidiEvent> Events;
  51. std::thread Thread;
  52. std::mutex Mutex;
  53. std::condition_variable Stop;
  54. MidiSynthesizer^ Synthesizer;
  55. int Size;
  56. int Position;
  57. Uint16 ppq; // parts (ticks) per quarter note
  58. volatile bool Playing;
  59. bool Loaded;
  60. bool Looping;
  61. _NativeMidiSong()
  62. : Synthesizer(nullptr), Size(0), Position(0)
  63. , ppq(0), Playing(false), Loaded(false), Looping(false)
  64. { }
  65. };
  66. static MidiSystemResetMessage^ ResetMessage = ref new MidiSystemResetMessage();
  67. enum class MidiSystemMessage {
  68. Exclusive = 0,
  69. TimeCode = 1,
  70. SongPositionPointer = 2,
  71. SongSelect = 3,
  72. TuneRequest = 6,
  73. TimingClock = 8,
  74. Start = 10,
  75. Continue = 11,
  76. Stop = 12,
  77. ActiveSensing = 14,
  78. SystemReset = 15
  79. };
  80. static void MIDItoStream(NativeMidiSong *song, MIDIEvent *eventlist)
  81. {
  82. int eventcount = 0, prevtime = 0, tempo = 500000;
  83. for (MIDIEvent* event = eventlist; event; event = event->next)
  84. {
  85. if (event->status != 0xFF)
  86. eventcount++;
  87. }
  88. song->Events.resize(song->Size = eventcount);
  89. song->Position = 0;
  90. song->Loaded = true;
  91. eventcount = 0;
  92. for (MIDIEvent* event = eventlist; event; event = event->next)
  93. {
  94. IMidiMessage^ message = nullptr;
  95. int status = (event->status & 0xF0) >> 4;
  96. switch (status)
  97. {
  98. case MIDI_STATUS_NOTE_OFF:
  99. message = ref new MidiNoteOffMessage(event->status - (status << 4), event->data[0], event->data[1]);
  100. break;
  101. case MIDI_STATUS_NOTE_ON:
  102. message = ref new MidiNoteOnMessage(event->status - (status << 4), event->data[0], event->data[1]);
  103. break;
  104. case MIDI_STATUS_AFTERTOUCH:
  105. message = ref new MidiPolyphonicKeyPressureMessage(event->status - (status << 4), event->data[0], event->data[1]);
  106. break;
  107. case MIDI_STATUS_CONTROLLER:
  108. message = ref new MidiControlChangeMessage(event->status - (status << 4), event->data[0], event->data[1]);
  109. break;
  110. case MIDI_STATUS_PROG_CHANGE:
  111. message = ref new MidiProgramChangeMessage(event->status - (status << 4), event->data[0]);
  112. break;
  113. case MIDI_STATUS_PRESSURE:
  114. message = ref new MidiChannelPressureMessage(event->status - (status << 4), event->data[0]);
  115. break;
  116. case MIDI_STATUS_PITCH_WHEEL:
  117. message = ref new MidiPitchBendChangeMessage(event->status - (status << 4), event->data[0] | (event->data[1] << 7));
  118. break;
  119. case MIDI_STATUS_SYSEX:
  120. switch ((MidiSystemMessage)(event->status & 0xF))
  121. {
  122. case MidiSystemMessage::Exclusive:
  123. {
  124. auto buffer = NativeBuffer::GetIBuffer(event->extraData, event->extraLen);
  125. if (buffer)
  126. {
  127. message = ref new MidiSystemExclusiveMessage(buffer);
  128. delete buffer;
  129. }
  130. }
  131. break;
  132. case MidiSystemMessage::TimeCode:
  133. message = ref new MidiTimeCodeMessage(event->extraData[0] >> 4, event->extraData[0] & 0xF);
  134. break;
  135. case MidiSystemMessage::SongPositionPointer:
  136. message = ref new MidiSongPositionPointerMessage(event->extraData[0] | (event->extraData[1] << 7));
  137. break;
  138. case MidiSystemMessage::SongSelect:
  139. message = ref new MidiSongSelectMessage(event->extraData[0]);
  140. break;
  141. case MidiSystemMessage::TuneRequest:
  142. message = ref new MidiTuneRequestMessage();
  143. break;
  144. case MidiSystemMessage::TimingClock:
  145. message = ref new MidiTimingClockMessage();
  146. break;
  147. case MidiSystemMessage::Start:
  148. message = ref new MidiStartMessage();
  149. break;
  150. case MidiSystemMessage::Continue:
  151. message = ref new MidiContinueMessage();
  152. break;
  153. case MidiSystemMessage::Stop:
  154. message = ref new MidiStopMessage();
  155. break;
  156. case MidiSystemMessage::ActiveSensing:
  157. message = ref new MidiActiveSensingMessage();
  158. break;
  159. case MidiSystemMessage::SystemReset:
  160. // This message is only used as meta-event in MIDI files
  161. if (event->data[0] == 0x51)
  162. tempo = (event->extraData[0] << 16) | (event->extraData[1] << 8) | event->extraData[2];
  163. break;
  164. }
  165. break;
  166. }
  167. if (message)
  168. {
  169. song->Events[eventcount].message = message;
  170. song->Events[eventcount].deltaTime = event->time - prevtime;
  171. song->Events[eventcount].tempo = tempo;
  172. prevtime = event->time; eventcount++;
  173. }
  174. }
  175. }
  176. int native_midi_detect()
  177. {
  178. auto synthesizer = AWait(MidiSynthesizer::CreateAsync());
  179. if (synthesizer)
  180. {
  181. delete synthesizer;
  182. return 1;
  183. }
  184. return 0;
  185. }
  186. NativeMidiSong *native_midi_loadsong(const char *midifile)
  187. {
  188. /* Attempt to load the midi file */
  189. auto rw = SDL_RWFromFile(midifile, "rb");
  190. if (rw)
  191. {
  192. auto song = native_midi_loadsong_RW(rw);
  193. SDL_RWclose(rw);
  194. return song;
  195. }
  196. return nullptr;
  197. }
  198. NativeMidiSong *native_midi_loadsong_RW(SDL_RWops *rw)
  199. {
  200. std::unique_ptr<NativeMidiSong> newsong(new NativeMidiSong);
  201. if (newsong)
  202. {
  203. auto evntlist = CreateMIDIEventList(rw, &newsong->ppq);
  204. if (evntlist)
  205. {
  206. MIDItoStream(newsong.get(), evntlist);
  207. FreeMIDIEventList(evntlist);
  208. if (newsong->Synthesizer = AWait(MidiSynthesizer::CreateAsync()))
  209. return newsong.release();
  210. }
  211. }
  212. return nullptr;
  213. }
  214. void native_midi_freesong(NativeMidiSong *song)
  215. {
  216. if (song)
  217. {
  218. native_midi_stop(song);
  219. if (song->Synthesizer)
  220. delete song->Synthesizer;
  221. delete song;
  222. }
  223. }
  224. void native_midi_start(NativeMidiSong *song, int looping)
  225. {
  226. if (!song) return;
  227. native_midi_stop(song);
  228. song->Playing = true;
  229. song->Looping = looping ? true : false;
  230. song->Thread = std::move(std::thread([](NativeMidiSong *song)->void {
  231. auto time = std::chrono::system_clock::now();
  232. while (song->Playing)
  233. {
  234. do
  235. {
  236. song->Events[song->Position++].Send(song->Synthesizer);
  237. } while (song->Position < song->Size && song->Events[song->Position].deltaTime == 0);
  238. if (song->Position < song->Size)
  239. {
  240. auto mutex = std::unique_lock<std::mutex>(song->Mutex);
  241. time += std::chrono::system_clock::duration(song->Events[song->Position].DeltaTimeAsTick(song->ppq));
  242. while (song->Playing)
  243. {
  244. if (song->Stop.wait_until(mutex, time) == std::cv_status::timeout)
  245. break;
  246. }
  247. }
  248. else if (song->Playing = song->Looping)
  249. {
  250. song->Position = 0;
  251. song->Synthesizer->SendMessage(ResetMessage);
  252. }
  253. }
  254. }, song));
  255. }
  256. void native_midi_stop(NativeMidiSong *song)
  257. {
  258. if (song)
  259. {
  260. song->Playing = false;
  261. song->Stop.notify_all();
  262. if (song->Thread.joinable())
  263. song->Thread.join();
  264. song->Thread = std::move(std::thread());
  265. if (song->Synthesizer)
  266. {
  267. song->Synthesizer->SendMessage(ResetMessage);
  268. }
  269. }
  270. }
  271. int native_midi_active(NativeMidiSong *song)
  272. {
  273. return (song && song->Playing) ? 1 : 0;
  274. }
  275. void native_midi_setvolume(NativeMidiSong *song, int volume)
  276. {
  277. if (song && song->Synthesizer)
  278. {
  279. if (volume > 127)
  280. volume = 127;
  281. else if (volume < 0)
  282. volume = 0;
  283. song->Synthesizer->Volume = (double)volume / 127.0;
  284. }
  285. }
  286. const char *native_midi_error(NativeMidiSong *song)
  287. {
  288. return "";
  289. }