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.

373 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)HandleMessageEvent,
  48. (DWORD)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. stop_execution:
  200. return false;
  201. }
  202. void
  203. JackWinMMEOutputPort::HandleMessage(UINT message, DWORD_PTR param1,
  204. DWORD_PTR param2)
  205. {
  206. set_threaded_log_function();
  207. switch (message) {
  208. case MOM_CLOSE:
  209. jack_info("JackWinMMEOutputPort::HandleMessage - MIDI device closed.");
  210. break;
  211. case MOM_DONE:
  212. Signal(sysex_semaphore);
  213. break;
  214. case MOM_OPEN:
  215. jack_info("JackWinMMEOutputPort::HandleMessage - MIDI device opened.");
  216. break;
  217. case MOM_POSITIONCB:
  218. LPMIDIHDR header = (LPMIDIHDR) param2;
  219. jack_info("JackWinMMEOutputPort::HandleMessage - %d bytes out of %d "
  220. "bytes of the current sysex message have been sent.",
  221. header->dwOffset, header->dwBytesRecorded);
  222. }
  223. }
  224. bool
  225. JackWinMMEOutputPort::Init()
  226. {
  227. set_threaded_log_function();
  228. // XX: Can more be done? Ideally, this thread should have the JACK server
  229. // thread priority + 1.
  230. if (thread->AcquireSelfRealTime()) {
  231. jack_error("JackWinMMEOutputPort::Init - could not acquire realtime "
  232. "scheduling. Continuing anyway.");
  233. }
  234. return true;
  235. }
  236. void
  237. JackWinMMEOutputPort::ProcessJack(JackMidiBuffer *port_buffer,
  238. jack_nframes_t frames)
  239. {
  240. read_queue->ResetMidiBuffer(port_buffer);
  241. for (jack_midi_event_t *event = read_queue->DequeueEvent(); event;
  242. event = read_queue->DequeueEvent()) {
  243. switch (thread_queue->EnqueueEvent(event, frames)) {
  244. case JackMidiWriteQueue::BUFFER_FULL:
  245. jack_error("JackWinMMEOutputPort::ProcessJack - The thread queue "
  246. "buffer is full. Dropping event.");
  247. break;
  248. case JackMidiWriteQueue::BUFFER_TOO_SMALL:
  249. jack_error("JackWinMMEOutputPort::ProcessJack - The thread queue "
  250. "couldn't enqueue a %d-byte event. Dropping event.",
  251. event->size);
  252. break;
  253. default:
  254. Signal(thread_queue_semaphore);
  255. }
  256. }
  257. }
  258. bool
  259. JackWinMMEOutputPort::Signal(HANDLE semaphore)
  260. {
  261. bool result = (bool) ReleaseSemaphore(semaphore, 1, NULL);
  262. if (! result) {
  263. WriteOSError("JackWinMMEOutputPort::Signal", "ReleaseSemaphore");
  264. }
  265. return result;
  266. }
  267. bool
  268. JackWinMMEOutputPort::Start()
  269. {
  270. bool result = thread->GetStatus() != JackThread::kIdle;
  271. if (! result) {
  272. result = ! thread->StartSync();
  273. if (! result) {
  274. jack_error("JackWinMMEOutputPort::Start - failed to start MIDI "
  275. "processing thread.");
  276. }
  277. }
  278. return result;
  279. }
  280. bool
  281. JackWinMMEOutputPort::Stop()
  282. {
  283. jack_info("JackWinMMEOutputPort::Stop - stopping MIDI output port "
  284. "processing thread.");
  285. int result;
  286. const char *verb;
  287. switch (thread->GetStatus()) {
  288. case JackThread::kIniting:
  289. case JackThread::kStarting:
  290. result = thread->Kill();
  291. verb = "kill";
  292. break;
  293. case JackThread::kRunning:
  294. Signal(thread_queue_semaphore);
  295. result = thread->Stop();
  296. verb = "stop";
  297. break;
  298. default:
  299. return true;
  300. }
  301. if (result) {
  302. jack_error("JackWinMMEOutputPort::Stop - could not %s MIDI processing "
  303. "thread.", verb);
  304. }
  305. return ! result;
  306. }
  307. bool
  308. JackWinMMEOutputPort::Wait(HANDLE semaphore)
  309. {
  310. DWORD result = WaitForSingleObject(semaphore, INFINITE);
  311. switch (result) {
  312. case WAIT_FAILED:
  313. WriteOSError("JackWinMMEOutputPort::Wait", "WaitForSingleObject");
  314. break;
  315. case WAIT_OBJECT_0:
  316. return true;
  317. default:
  318. jack_error("JackWinMMEOutputPort::Wait - unexpected result from "
  319. "'WaitForSingleObject'.");
  320. }
  321. return false;
  322. }
  323. void
  324. JackWinMMEOutputPort::GetOutErrorString(MMRESULT error, LPTSTR text)
  325. {
  326. MMRESULT result = midiOutGetErrorText(error, text, MAXERRORLENGTH);
  327. if (result != MMSYSERR_NOERROR) {
  328. snprintf(text, MAXERRORLENGTH, "Unknown MM error code '%d'", error);
  329. }
  330. }
  331. void
  332. JackWinMMEOutputPort::WriteOutError(const char *jack_func, const char *mm_func,
  333. MMRESULT result)
  334. {
  335. char error_message[MAXERRORLENGTH];
  336. GetOutErrorString(result, error_message);
  337. jack_error("%s - %s: %s", jack_func, mm_func, error_message);
  338. }