native_midi.cpp 9.4 KB

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