jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

370 lines
12KB

  1. /*
  2. Copyright (C) 2011 Devin Anderson
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  14. */
  15. #include <memory>
  16. #include <stdexcept>
  17. #include "JackMidiUtil.h"
  18. #include "JackTime.h"
  19. #include "JackWinMMEOutputPort.h"
  20. using Jack::JackWinMMEOutputPort;
  21. ///////////////////////////////////////////////////////////////////////////////
  22. // Static callbacks
  23. ///////////////////////////////////////////////////////////////////////////////
  24. void CALLBACK
  25. JackWinMMEOutputPort::HandleMessageEvent(HMIDIOUT handle, UINT message,
  26. DWORD_PTR port, DWORD_PTR param1,
  27. DWORD_PTR param2)
  28. {
  29. ((JackWinMMEOutputPort *) port)->HandleMessage(message, param1, param2);
  30. }
  31. ///////////////////////////////////////////////////////////////////////////////
  32. // Class
  33. ///////////////////////////////////////////////////////////////////////////////
  34. JackWinMMEOutputPort::JackWinMMEOutputPort(const char *alias_name,
  35. const char *client_name,
  36. const char *driver_name, UINT index,
  37. size_t max_bytes,
  38. size_t max_messages)
  39. {
  40. read_queue = new JackMidiBufferReadQueue();
  41. std::auto_ptr<JackMidiBufferReadQueue> read_queue_ptr(read_queue);
  42. thread_queue = new JackMidiAsyncQueue(max_bytes, max_messages);
  43. std::auto_ptr<JackMidiAsyncQueue> thread_queue_ptr(thread_queue);
  44. thread = new JackThread(this);
  45. std::auto_ptr<JackThread> thread_ptr(thread);
  46. char error_message[MAXERRORLENGTH];
  47. MMRESULT result = midiOutOpen(&handle, index, (DWORD_PTR)HandleMessageEvent,
  48. (DWORD_PTR)this, CALLBACK_FUNCTION);
  49. if (result != MMSYSERR_NOERROR) {
  50. GetOutErrorString(result, error_message);
  51. goto raise_exception;
  52. }
  53. thread_queue_semaphore = CreateSemaphore(NULL, 0, max_messages, NULL);
  54. if (thread_queue_semaphore == NULL) {
  55. GetOSErrorString(error_message);
  56. goto close_handle;
  57. }
  58. sysex_semaphore = CreateSemaphore(NULL, 0, 1, NULL);
  59. if (sysex_semaphore == NULL) {
  60. GetOSErrorString(error_message);
  61. goto destroy_thread_queue_semaphore;
  62. }
  63. MIDIOUTCAPS capabilities;
  64. char *name_tmp;
  65. result = midiOutGetDevCaps(index, &capabilities, sizeof(capabilities));
  66. if (result != MMSYSERR_NOERROR) {
  67. WriteOutError("JackWinMMEOutputPort [constructor]", "midiOutGetDevCaps",
  68. result);
  69. name_tmp = (char*)driver_name;
  70. } else {
  71. name_tmp = capabilities.szPname;
  72. }
  73. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%d", alias_name, name_tmp,
  74. index + 1);
  75. snprintf(name, sizeof(name) - 1, "%s:playback_%d", client_name, index + 1);
  76. read_queue_ptr.release();
  77. thread_queue_ptr.release();
  78. thread_ptr.release();
  79. return;
  80. destroy_thread_queue_semaphore:
  81. if (! CloseHandle(thread_queue_semaphore)) {
  82. WriteOSError("JackWinMMEOutputPort [constructor]", "CloseHandle");
  83. }
  84. close_handle:
  85. result = midiOutClose(handle);
  86. if (result != MMSYSERR_NOERROR) {
  87. WriteOutError("JackWinMMEOutputPort [constructor]", "midiOutClose",
  88. result);
  89. }
  90. raise_exception:
  91. throw std::runtime_error(error_message);
  92. }
  93. JackWinMMEOutputPort::~JackWinMMEOutputPort()
  94. {
  95. MMRESULT result = midiOutReset(handle);
  96. if (result != MMSYSERR_NOERROR) {
  97. WriteOutError("JackWinMMEOutputPort [destructor]", "midiOutReset",
  98. result);
  99. }
  100. result = midiOutClose(handle);
  101. if (result != MMSYSERR_NOERROR) {
  102. WriteOutError("JackWinMMEOutputPort [destructor]", "midiOutClose",
  103. result);
  104. }
  105. if (! CloseHandle(sysex_semaphore)) {
  106. WriteOSError("JackWinMMEOutputPort [destructor]", "CloseHandle");
  107. }
  108. if (! CloseHandle(thread_queue_semaphore)) {
  109. WriteOSError("JackWinMMEOutputPort [destructor]", "CloseHandle");
  110. }
  111. delete read_queue;
  112. delete thread_queue;
  113. delete thread;
  114. }
  115. bool
  116. JackWinMMEOutputPort::Execute()
  117. {
  118. for (;;) {
  119. if (! Wait(thread_queue_semaphore)) {
  120. jack_log("JackWinMMEOutputPort::Execute BREAK");
  121. break;
  122. }
  123. jack_midi_event_t *event = thread_queue->DequeueEvent();
  124. if (! event) {
  125. break;
  126. }
  127. jack_time_t frame_time = GetTimeFromFrames(event->time);
  128. for (jack_time_t current_time = GetMicroSeconds();
  129. frame_time > current_time; current_time = GetMicroSeconds()) {
  130. jack_time_t sleep_time = frame_time - current_time;
  131. // Windows has a millisecond sleep resolution for its Sleep calls.
  132. // This is unfortunate, as MIDI timing often requires a higher
  133. // resolution. For now, we attempt to compensate by letting an
  134. // event be sent if we're less than 500 microseconds from sending
  135. // the event. We assume that it's better to let an event go out
  136. // 499 microseconds early than let an event go out 501 microseconds
  137. // late. Of course, that's assuming optimal sleep times, which is
  138. // a whole different Windows issue ...
  139. if (sleep_time < 500) {
  140. break;
  141. }
  142. if (sleep_time < 1000) {
  143. sleep_time = 1000;
  144. }
  145. JackSleep(sleep_time);
  146. }
  147. jack_midi_data_t *data = event->buffer;
  148. DWORD message = 0;
  149. MMRESULT result;
  150. size_t size = event->size;
  151. switch (size) {
  152. case 3:
  153. message |= (((DWORD) data[2]) << 16);
  154. // Fallthrough on purpose.
  155. case 2:
  156. message |= (((DWORD) data[1]) << 8);
  157. // Fallthrough on purpose.
  158. case 1:
  159. message |= (DWORD) data[0];
  160. result = midiOutShortMsg(handle, message);
  161. if (result != MMSYSERR_NOERROR) {
  162. WriteOutError("JackWinMMEOutputPort::Execute",
  163. "midiOutShortMsg", result);
  164. }
  165. continue;
  166. }
  167. MIDIHDR header;
  168. header.dwBufferLength = size;
  169. header.dwBytesRecorded = size;
  170. header.dwFlags = 0;
  171. header.dwOffset = 0;
  172. header.dwUser = 0;
  173. header.lpData = (LPSTR)data;
  174. result = midiOutPrepareHeader(handle, &header, sizeof(MIDIHDR));
  175. if (result != MMSYSERR_NOERROR) {
  176. WriteOutError("JackWinMMEOutputPort::Execute",
  177. "midiOutPrepareHeader", result);
  178. continue;
  179. }
  180. result = midiOutLongMsg(handle, &header, sizeof(MIDIHDR));
  181. if (result != MMSYSERR_NOERROR) {
  182. WriteOutError("JackWinMMEOutputPort::Execute", "midiOutLongMsg",
  183. result);
  184. continue;
  185. }
  186. // System exclusive messages may be sent synchronously or
  187. // asynchronously. The choice is up to the WinMME driver. So, we wait
  188. // until the message is sent, regardless of the driver's choice.
  189. if (! Wait(sysex_semaphore)) {
  190. break;
  191. }
  192. result = midiOutUnprepareHeader(handle, &header, sizeof(MIDIHDR));
  193. if (result != MMSYSERR_NOERROR) {
  194. WriteOutError("JackWinMMEOutputPort::Execute",
  195. "midiOutUnprepareHeader", result);
  196. break;
  197. }
  198. }
  199. return false;
  200. }
  201. void
  202. JackWinMMEOutputPort::HandleMessage(UINT message, DWORD_PTR param1,
  203. DWORD_PTR param2)
  204. {
  205. set_threaded_log_function();
  206. switch (message) {
  207. case MOM_CLOSE:
  208. jack_info("JackWinMMEOutputPort::HandleMessage - MIDI device closed.");
  209. break;
  210. case MOM_DONE:
  211. Signal(sysex_semaphore);
  212. break;
  213. case MOM_OPEN:
  214. jack_info("JackWinMMEOutputPort::HandleMessage - MIDI device opened.");
  215. break;
  216. case MOM_POSITIONCB:
  217. LPMIDIHDR header = (LPMIDIHDR) param2;
  218. jack_info("JackWinMMEOutputPort::HandleMessage - %d bytes out of %d "
  219. "bytes of the current sysex message have been sent.",
  220. header->dwOffset, header->dwBytesRecorded);
  221. }
  222. }
  223. bool
  224. JackWinMMEOutputPort::Init()
  225. {
  226. set_threaded_log_function();
  227. // XX: Can more be done? Ideally, this thread should have the JACK server
  228. // thread priority + 1.
  229. if (thread->AcquireSelfRealTime()) {
  230. jack_error("JackWinMMEOutputPort::Init - could not acquire realtime "
  231. "scheduling. Continuing anyway.");
  232. }
  233. return true;
  234. }
  235. void
  236. JackWinMMEOutputPort::ProcessJack(JackMidiBuffer *port_buffer,
  237. jack_nframes_t frames)
  238. {
  239. read_queue->ResetMidiBuffer(port_buffer);
  240. for (jack_midi_event_t *event = read_queue->DequeueEvent(); event;
  241. event = read_queue->DequeueEvent()) {
  242. switch (thread_queue->EnqueueEvent(event, frames)) {
  243. case JackMidiWriteQueue::BUFFER_FULL:
  244. jack_error("JackWinMMEOutputPort::ProcessJack - The thread queue "
  245. "buffer is full. Dropping event.");
  246. break;
  247. case JackMidiWriteQueue::BUFFER_TOO_SMALL:
  248. jack_error("JackWinMMEOutputPort::ProcessJack - The thread queue "
  249. "couldn't enqueue a %d-byte event. Dropping event.",
  250. event->size);
  251. break;
  252. default:
  253. Signal(thread_queue_semaphore);
  254. }
  255. }
  256. }
  257. bool
  258. JackWinMMEOutputPort::Signal(HANDLE semaphore)
  259. {
  260. bool result = (bool) ReleaseSemaphore(semaphore, 1, NULL);
  261. if (! result) {
  262. WriteOSError("JackWinMMEOutputPort::Signal", "ReleaseSemaphore");
  263. }
  264. return result;
  265. }
  266. bool
  267. JackWinMMEOutputPort::Start()
  268. {
  269. bool result = thread->GetStatus() != JackThread::kIdle;
  270. if (! result) {
  271. result = ! thread->StartSync();
  272. if (! result) {
  273. jack_error("JackWinMMEOutputPort::Start - failed to start MIDI "
  274. "processing thread.");
  275. }
  276. }
  277. return result;
  278. }
  279. bool
  280. JackWinMMEOutputPort::Stop()
  281. {
  282. jack_info("JackWinMMEOutputPort::Stop - stopping MIDI output port "
  283. "processing thread.");
  284. int result;
  285. const char *verb;
  286. switch (thread->GetStatus()) {
  287. case JackThread::kIniting:
  288. case JackThread::kStarting:
  289. result = thread->Kill();
  290. verb = "kill";
  291. break;
  292. case JackThread::kRunning:
  293. Signal(thread_queue_semaphore);
  294. result = thread->Stop();
  295. verb = "stop";
  296. break;
  297. default:
  298. return true;
  299. }
  300. if (result) {
  301. jack_error("JackWinMMEOutputPort::Stop - could not %s MIDI processing "
  302. "thread.", verb);
  303. }
  304. return ! result;
  305. }
  306. bool
  307. JackWinMMEOutputPort::Wait(HANDLE semaphore)
  308. {
  309. DWORD result = WaitForSingleObject(semaphore, INFINITE);
  310. switch (result) {
  311. case WAIT_FAILED:
  312. WriteOSError("JackWinMMEOutputPort::Wait", "WaitForSingleObject");
  313. break;
  314. case WAIT_OBJECT_0:
  315. return true;
  316. default:
  317. jack_error("JackWinMMEOutputPort::Wait - unexpected result from "
  318. "'WaitForSingleObject'.");
  319. }
  320. return false;
  321. }
  322. void
  323. JackWinMMEOutputPort::GetOutErrorString(MMRESULT error, LPTSTR text)
  324. {
  325. MMRESULT result = midiOutGetErrorText(error, text, MAXERRORLENGTH);
  326. if (result != MMSYSERR_NOERROR) {
  327. snprintf(text, MAXERRORLENGTH, "Unknown MM error code '%d'", error);
  328. }
  329. }
  330. void
  331. JackWinMMEOutputPort::WriteOutError(const char *jack_func, const char *mm_func,
  332. MMRESULT result)
  333. {
  334. char error_message[MAXERRORLENGTH];
  335. GetOutErrorString(result, error_message);
  336. jack_error("%s - %s: %s", jack_func, mm_func, error_message);
  337. }