native_midi.cpp 8.5 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. extern "C" {
  36. #include "native_midi/native_midi.h"
  37. #include "native_midi/native_midi_common.h"
  38. }
  39. struct MidiEvent
  40. {
  41. Windows::Devices::Midi::IMidiMessage^ message;
  42. uint32_t deltaTime; // time in ticks
  43. uint32_t tempo; // microseconds per quarter note
  44. std::chrono::system_clock::duration DeltaTimeAsTick(uint16_t ppq)
  45. {
  46. return std::chrono::system_clock::duration((int64_t)deltaTime * tempo * 10 / ppq);
  47. }
  48. };
  49. struct _NativeMidiSong {
  50. Windows::Devices::Midi::MidiSynthesizer^ Synthesizer;
  51. MidiEvent* Events;
  52. int Size;
  53. int Position;
  54. Uint16 ppq; // parts (ticks) per quarter note
  55. volatile bool Playing;
  56. bool Loaded;
  57. std::thread Thread;
  58. std::mutex Mutex;
  59. std::condition_variable Stop;
  60. _NativeMidiSong()
  61. : Events(nullptr), Size(0), Position(0)
  62. , ppq(0), Playing(false), Loaded(false)
  63. , Synthesizer(nullptr)
  64. { }
  65. };
  66. static std::atomic<NativeMidiSong*> CurrentSong = nullptr;
  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. MIDIEvent *event = eventlist;
  84. while (event)
  85. {
  86. eventcount++;
  87. event = event->next;
  88. }
  89. if (!(song->Events = new MidiEvent[eventcount]))
  90. return;
  91. for (event = eventlist, eventcount = 0; event; event = event->next)
  92. {
  93. Windows::Devices::Midi::IMidiMessage^ message = nullptr;
  94. int status = (event->status & 0xF0) >> 4;
  95. switch (status)
  96. {
  97. case MIDI_STATUS_NOTE_OFF:
  98. message = ref new Windows::Devices::Midi::MidiNoteOffMessage(event->status - (status << 4), event->data[0], event->data[1]);
  99. break;
  100. case MIDI_STATUS_NOTE_ON:
  101. message = ref new Windows::Devices::Midi::MidiNoteOnMessage(event->status - (status << 4), event->data[0], event->data[1]);
  102. break;
  103. case MIDI_STATUS_AFTERTOUCH:
  104. message = ref new Windows::Devices::Midi::MidiPolyphonicKeyPressureMessage(event->status - (status << 4), event->data[0], event->data[1]);
  105. break;
  106. case MIDI_STATUS_CONTROLLER:
  107. message = ref new Windows::Devices::Midi::MidiControlChangeMessage(event->status - (status << 4), event->data[0], event->data[1]);
  108. break;
  109. case MIDI_STATUS_PROG_CHANGE:
  110. message = ref new Windows::Devices::Midi::MidiProgramChangeMessage(event->status - (status << 4), event->data[0]);
  111. break;
  112. case MIDI_STATUS_PRESSURE:
  113. message = ref new Windows::Devices::Midi::MidiChannelPressureMessage(event->status - (status << 4), event->data[0]);
  114. break;
  115. case MIDI_STATUS_PITCH_WHEEL:
  116. message = ref new Windows::Devices::Midi::MidiPitchBendChangeMessage(event->status - (status << 4), event->data[0] | (event->data[1] << 7));
  117. break;
  118. case MIDI_STATUS_SYSEX:
  119. switch ((MidiSystemMessage)(event->status & 0xF))
  120. {
  121. case MidiSystemMessage::Exclusive:
  122. {
  123. auto buffer = NativeBuffer::GetIBuffer(event->extraData, event->extraLen);
  124. if (buffer)
  125. {
  126. message = ref new Windows::Devices::Midi::MidiSystemExclusiveMessage(buffer);
  127. delete buffer;
  128. }
  129. }
  130. break;
  131. case MidiSystemMessage::TimeCode:
  132. message = ref new Windows::Devices::Midi::MidiTimeCodeMessage(event->extraData[0] >> 4, event->extraData[0] & 0xF);
  133. break;
  134. case MidiSystemMessage::SongPositionPointer:
  135. message = ref new Windows::Devices::Midi::MidiSongPositionPointerMessage(event->extraData[0] | (event->extraData[1] << 7));
  136. break;
  137. case MidiSystemMessage::SongSelect:
  138. message = ref new Windows::Devices::Midi::MidiSongSelectMessage(event->extraData[0]);
  139. break;
  140. case MidiSystemMessage::TuneRequest:
  141. message = ref new Windows::Devices::Midi::MidiTuneRequestMessage();
  142. break;
  143. case MidiSystemMessage::TimingClock:
  144. message = ref new Windows::Devices::Midi::MidiTimingClockMessage();
  145. break;
  146. case MidiSystemMessage::Start:
  147. message = ref new Windows::Devices::Midi::MidiStartMessage();
  148. break;
  149. case MidiSystemMessage::Continue:
  150. message = ref new Windows::Devices::Midi::MidiContinueMessage();
  151. break;
  152. case MidiSystemMessage::Stop:
  153. message = ref new Windows::Devices::Midi::MidiStopMessage();
  154. break;
  155. case MidiSystemMessage::ActiveSensing:
  156. message = ref new Windows::Devices::Midi::MidiActiveSensingMessage();
  157. break;
  158. case MidiSystemMessage::SystemReset:
  159. message = ref new Windows::Devices::Midi::MidiSystemResetMessage();
  160. if (event->data[0] == 0x51)
  161. tempo = (event->extraData[0] << 16) | (event->extraData[1] << 8) | event->extraData[2];
  162. break;
  163. }
  164. break;
  165. }
  166. if (message)
  167. {
  168. song->Events[eventcount].message = message;
  169. song->Events[eventcount].deltaTime = event->time - prevtime;
  170. song->Events[eventcount].tempo = tempo;
  171. prevtime = event->time; eventcount++;
  172. }
  173. }
  174. song->Size = eventcount;
  175. song->Position = 0;
  176. song->Loaded = 1;
  177. }
  178. int native_midi_detect()
  179. {
  180. auto synthesizer = AWait(Windows::Devices::Midi::MidiSynthesizer::CreateAsync());
  181. if (synthesizer)
  182. {
  183. delete synthesizer;
  184. return 1;
  185. }
  186. return 0;
  187. }
  188. NativeMidiSong *native_midi_loadsong(const char *midifile)
  189. {
  190. /* Attempt to load the midi file */
  191. std::unique_ptr<SDL_RWops> rw(SDL_RWFromFile(midifile, "rb"));
  192. return rw ? native_midi_loadsong_RW(rw.get()) : nullptr;
  193. }
  194. NativeMidiSong *native_midi_loadsong_RW(SDL_RWops *rw)
  195. {
  196. std::unique_ptr<NativeMidiSong> newsong(new NativeMidiSong);
  197. if (newsong)
  198. {
  199. auto evntlist = CreateMIDIEventList(rw, &newsong->ppq);
  200. if (evntlist)
  201. {
  202. MIDItoStream(newsong.get(), evntlist);
  203. FreeMIDIEventList(evntlist);
  204. return newsong.release();
  205. }
  206. }
  207. return nullptr;
  208. }
  209. void native_midi_freesong(NativeMidiSong *song)
  210. {
  211. if (song)
  212. {
  213. native_midi_stop();
  214. if (song->Events)
  215. delete[] song->Events;
  216. delete song;
  217. }
  218. }
  219. void native_midi_start(NativeMidiSong *song)
  220. {
  221. if (!song) return;
  222. native_midi_stop();
  223. if (!song->Synthesizer)
  224. {
  225. song->Synthesizer = AWait(Windows::Devices::Midi::MidiSynthesizer::CreateAsync());
  226. if (!song->Synthesizer) return;
  227. }
  228. song->Thread = std::move(std::thread([](NativeMidiSong *song)->void {
  229. auto time = std::chrono::system_clock::now();
  230. while (song->Position < song->Size)
  231. {
  232. do
  233. {
  234. song->Synthesizer->SendMessage(song->Events[song->Position++].message);
  235. } while (song->Position < song->Size && song->Events[song->Position].deltaTime == 0);
  236. time += std::chrono::system_clock::duration(song->Events[song->Position].DeltaTimeAsTick(song->ppq));
  237. if (song->Stop.wait_until(std::unique_lock<std::mutex>(song->Mutex), time) == std::cv_status::no_timeout) break;
  238. }
  239. song->Playing = false;
  240. }, song));
  241. song->Playing = true;
  242. CurrentSong.exchange(song);
  243. }
  244. void native_midi_stop()
  245. {
  246. NativeMidiSong* song;
  247. if (song = CurrentSong.exchange(nullptr))
  248. {
  249. song->Stop.notify_all();
  250. if (song->Thread.joinable())
  251. song->Thread.join();
  252. song->Thread = std::move(std::thread());
  253. song->Playing = false;
  254. if (song->Synthesizer)
  255. {
  256. delete song->Synthesizer;
  257. song->Synthesizer = nullptr;
  258. }
  259. }
  260. }
  261. int native_midi_active()
  262. {
  263. auto song = CurrentSong.load();
  264. return (song && song->Playing) ? 1 : 0;
  265. }
  266. void native_midi_setvolume(int volume)
  267. {
  268. auto song = CurrentSong.load();
  269. if (song && song->Synthesizer)
  270. {
  271. if (volume > 128)
  272. volume = 128;
  273. else if (volume < 0)
  274. volume = 0;
  275. song->Synthesizer->Volume = (double)volume / 128.0;
  276. }
  277. }
  278. const char *native_midi_error(void)
  279. {
  280. return "";
  281. }