native_midi.cpp 8.3 KB

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