native_midi.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. std::unique_ptr<SDL_RWops> rw(SDL_RWFromFile(midifile, "rb"));
  190. return rw ? native_midi_loadsong_RW(rw.get()) : nullptr;
  191. }
  192. NativeMidiSong *native_midi_loadsong_RW(SDL_RWops *rw)
  193. {
  194. std::unique_ptr<NativeMidiSong> newsong(new NativeMidiSong);
  195. if (newsong)
  196. {
  197. auto evntlist = CreateMIDIEventList(rw, &newsong->ppq);
  198. if (evntlist)
  199. {
  200. MIDItoStream(newsong.get(), evntlist);
  201. FreeMIDIEventList(evntlist);
  202. if (newsong->Synthesizer = AWait(MidiSynthesizer::CreateAsync()))
  203. return newsong.release();
  204. }
  205. }
  206. return nullptr;
  207. }
  208. void native_midi_freesong(NativeMidiSong *song)
  209. {
  210. if (song)
  211. {
  212. native_midi_stop(song);
  213. if (song->Synthesizer)
  214. delete song->Synthesizer;
  215. delete song;
  216. }
  217. }
  218. void native_midi_start(NativeMidiSong *song, int looping)
  219. {
  220. if (!song) return;
  221. native_midi_stop(song);
  222. song->Playing = true;
  223. song->Looping = looping ? true : false;
  224. song->Thread = std::move(std::thread([](NativeMidiSong *song)->void {
  225. auto time = std::chrono::system_clock::now();
  226. while (song->Playing)
  227. {
  228. do
  229. {
  230. song->Events[song->Position++].Send(song->Synthesizer);
  231. } while (song->Position < song->Size && song->Events[song->Position].deltaTime == 0);
  232. if (song->Position < song->Size)
  233. {
  234. time += std::chrono::system_clock::duration(song->Events[song->Position].DeltaTimeAsTick(song->ppq));
  235. while (song->Playing)
  236. {
  237. if (song->Stop.wait_until(std::unique_lock<std::mutex>(song->Mutex), time) == std::cv_status::timeout)
  238. break;
  239. }
  240. }
  241. else if (song->Playing = song->Looping)
  242. {
  243. song->Position = 0;
  244. song->Synthesizer->SendMessage(ResetMessage);
  245. }
  246. }
  247. }, song));
  248. }
  249. void native_midi_stop(NativeMidiSong *song)
  250. {
  251. if (song)
  252. {
  253. song->Playing = false;
  254. song->Stop.notify_all();
  255. if (song->Thread.joinable())
  256. song->Thread.join();
  257. song->Thread = std::move(std::thread());
  258. if (song->Synthesizer)
  259. {
  260. song->Synthesizer->SendMessage(ResetMessage);
  261. }
  262. }
  263. }
  264. int native_midi_active(NativeMidiSong *song)
  265. {
  266. return (song && song->Playing) ? 1 : 0;
  267. }
  268. void native_midi_setvolume(NativeMidiSong *song, int volume)
  269. {
  270. if (song && song->Synthesizer)
  271. {
  272. if (volume > 127)
  273. volume = 127;
  274. else if (volume < 0)
  275. volume = 0;
  276. song->Synthesizer->Volume = (double)volume / 127.0;
  277. }
  278. }
  279. const char *native_midi_error(NativeMidiSong *song)
  280. {
  281. return "";
  282. }