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.

374 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. //thread_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. Stop();
  96. MMRESULT result = midiOutReset(handle);
  97. if (result != MMSYSERR_NOERROR) {
  98. WriteOutError("JackWinMMEOutputPort [destructor]", "midiOutReset",
  99. result);
  100. }
  101. result = midiOutClose(handle);
  102. if (result != MMSYSERR_NOERROR) {
  103. WriteOutError("JackWinMMEOutputPort [destructor]", "midiOutClose",
  104. result);
  105. }
  106. if (! CloseHandle(sysex_semaphore)) {
  107. WriteOSError("JackWinMMEOutputPort [destructor]", "CloseHandle");
  108. }
  109. if (! CloseHandle(thread_queue_semaphore)) {
  110. WriteOSError("JackWinMMEOutputPort [destructor]", "CloseHandle");
  111. }
  112. delete read_queue;
  113. delete thread_queue;
  114. delete thread;
  115. }
  116. bool
  117. JackWinMMEOutputPort::Execute()
  118. {
  119. for (;;) {
  120. if (! Wait(thread_queue_semaphore)) {
  121. jack_log("JackWinMMEOutputPort::Execute BREAK");
  122. break;
  123. }
  124. jack_midi_event_t *event = thread_queue->DequeueEvent();
  125. if (! event) {
  126. break;
  127. }
  128. jack_time_t frame_time = GetTimeFromFrames(event->time);
  129. for (jack_time_t current_time = GetMicroSeconds();
  130. frame_time > current_time; current_time = GetMicroSeconds()) {
  131. jack_time_t sleep_time = frame_time - current_time;
  132. // Windows has a millisecond sleep resolution for its Sleep calls.
  133. // This is unfortunate, as MIDI timing often requires a higher
  134. // resolution. For now, we attempt to compensate by letting an
  135. // event be sent if we're less than 500 microseconds from sending
  136. // the event. We assume that it's better to let an event go out
  137. // 499 microseconds early than let an event go out 501 microseconds
  138. // late. Of course, that's assuming optimal sleep times, which is
  139. // a whole different Windows issue ...
  140. if (sleep_time < 500) {
  141. break;
  142. }
  143. if (sleep_time < 1000) {
  144. sleep_time = 1000;
  145. }
  146. JackSleep(sleep_time);
  147. }
  148. jack_midi_data_t *data = event->buffer;
  149. DWORD message = 0;
  150. MMRESULT result;
  151. size_t size = event->size;
  152. switch (size) {
  153. case 3:
  154. message |= (((DWORD) data[2]) << 16);
  155. // Fallthrough on purpose.
  156. case 2:
  157. message |= (((DWORD) data[1]) << 8);
  158. // Fallthrough on purpose.
  159. case 1:
  160. message |= (DWORD) data[0];
  161. result = midiOutShortMsg(handle, message);
  162. if (result != MMSYSERR_NOERROR) {
  163. WriteOutError("JackWinMMEOutputPort::Execute",
  164. "midiOutShortMsg", result);
  165. }
  166. continue;
  167. }
  168. MIDIHDR header;
  169. header.dwBufferLength = size;
  170. header.dwBytesRecorded = size;
  171. header.dwFlags = 0;
  172. header.dwOffset = 0;
  173. header.dwUser = 0;
  174. header.lpData = (LPSTR)data;
  175. result = midiOutPrepareHeader(handle, &header, sizeof(MIDIHDR));
  176. if (result != MMSYSERR_NOERROR) {
  177. WriteOutError("JackWinMMEOutputPort::Execute",
  178. "midiOutPrepareHeader", result);
  179. continue;
  180. }
  181. result = midiOutLongMsg(handle, &header, sizeof(MIDIHDR));
  182. if (result != MMSYSERR_NOERROR) {
  183. WriteOutError("JackWinMMEOutputPort::Execute", "midiOutLongMsg",
  184. result);
  185. continue;
  186. }
  187. // System exclusive messages may be sent synchronously or
  188. // asynchronously. The choice is up to the WinMME driver. So, we wait
  189. // until the message is sent, regardless of the driver's choice.
  190. if (! Wait(sysex_semaphore)) {
  191. break;
  192. }
  193. result = midiOutUnprepareHeader(handle, &header, sizeof(MIDIHDR));
  194. if (result != MMSYSERR_NOERROR) {
  195. WriteOutError("JackWinMMEOutputPort::Execute",
  196. "midiOutUnprepareHeader", result);
  197. break;
  198. }
  199. }
  200. stop_execution:
  201. return false;
  202. }
  203. void
  204. JackWinMMEOutputPort::HandleMessage(UINT message, DWORD_PTR param1,
  205. DWORD_PTR param2)
  206. {
  207. set_threaded_log_function();
  208. switch (message) {
  209. case MOM_CLOSE:
  210. jack_info("JackWinMMEOutputPort::HandleMessage - MIDI device closed.");
  211. break;
  212. case MOM_DONE:
  213. Signal(sysex_semaphore);
  214. break;
  215. case MOM_OPEN:
  216. jack_info("JackWinMMEOutputPort::HandleMessage - MIDI device opened.");
  217. break;
  218. case MOM_POSITIONCB:
  219. LPMIDIHDR header = (LPMIDIHDR) param2;
  220. jack_info("JackWinMMEOutputPort::HandleMessage - %d bytes out of %d "
  221. "bytes of the current sysex message have been sent.",
  222. header->dwOffset, header->dwBytesRecorded);
  223. }
  224. }
  225. bool
  226. JackWinMMEOutputPort::Init()
  227. {
  228. set_threaded_log_function();
  229. // XX: Can more be done? Ideally, this thread should have the JACK server
  230. // thread priority + 1.
  231. if (thread->AcquireSelfRealTime()) {
  232. jack_error("JackWinMMEOutputPort::Init - could not acquire realtime "
  233. "scheduling. Continuing anyway.");
  234. }
  235. return true;
  236. }
  237. void
  238. JackWinMMEOutputPort::ProcessJack(JackMidiBuffer *port_buffer,
  239. jack_nframes_t frames)
  240. {
  241. read_queue->ResetMidiBuffer(port_buffer);
  242. for (jack_midi_event_t *event = read_queue->DequeueEvent(); event;
  243. event = read_queue->DequeueEvent()) {
  244. switch (thread_queue->EnqueueEvent(event, frames)) {
  245. case JackMidiWriteQueue::BUFFER_FULL:
  246. jack_error("JackWinMMEOutputPort::ProcessJack - The thread queue "
  247. "buffer is full. Dropping event.");
  248. break;
  249. case JackMidiWriteQueue::BUFFER_TOO_SMALL:
  250. jack_error("JackWinMMEOutputPort::ProcessJack - The thread queue "
  251. "couldn't enqueue a %d-byte event. Dropping event.",
  252. event->size);
  253. break;
  254. default:
  255. Signal(thread_queue_semaphore);
  256. }
  257. }
  258. }
  259. bool
  260. JackWinMMEOutputPort::Signal(HANDLE semaphore)
  261. {
  262. bool result = (bool) ReleaseSemaphore(semaphore, 1, NULL);
  263. if (! result) {
  264. WriteOSError("JackWinMMEOutputPort::Signal", "ReleaseSemaphore");
  265. }
  266. return result;
  267. }
  268. bool
  269. JackWinMMEOutputPort::Start()
  270. {
  271. bool result = thread->GetStatus() != JackThread::kIdle;
  272. if (! result) {
  273. result = ! thread->StartSync();
  274. if (! result) {
  275. jack_error("JackWinMMEOutputPort::Start - failed to start MIDI "
  276. "processing thread.");
  277. }
  278. }
  279. return result;
  280. }
  281. bool
  282. JackWinMMEOutputPort::Stop()
  283. {
  284. jack_info("JackWinMMEOutputPort::Stop - stopping MIDI output port "
  285. "processing thread.");
  286. int result;
  287. const char *verb;
  288. switch (thread->GetStatus()) {
  289. case JackThread::kIniting:
  290. case JackThread::kStarting:
  291. result = thread->Kill();
  292. verb = "kill";
  293. break;
  294. case JackThread::kRunning:
  295. Signal(thread_queue_semaphore);
  296. result = thread->Stop();
  297. verb = "stop";
  298. break;
  299. default:
  300. return true;
  301. }
  302. if (result) {
  303. jack_error("JackWinMMEOutputPort::Stop - could not %s MIDI processing "
  304. "thread.", verb);
  305. }
  306. return ! result;
  307. }
  308. bool
  309. JackWinMMEOutputPort::Wait(HANDLE semaphore)
  310. {
  311. DWORD result = WaitForSingleObject(semaphore, INFINITE);
  312. switch (result) {
  313. case WAIT_FAILED:
  314. WriteOSError("JackWinMMEOutputPort::Wait", "WaitForSingleObject");
  315. break;
  316. case WAIT_OBJECT_0:
  317. return true;
  318. default:
  319. jack_error("JackWinMMEOutputPort::Wait - unexpected result from "
  320. "'WaitForSingleObject'.");
  321. }
  322. return false;
  323. }
  324. void
  325. JackWinMMEOutputPort::GetOutErrorString(MMRESULT error, LPTSTR text)
  326. {
  327. MMRESULT result = midiOutGetErrorText(error, text, MAXERRORLENGTH);
  328. if (result != MMSYSERR_NOERROR) {
  329. snprintf(text, MAXERRORLENGTH, "Unknown MM error code '%d'", error);
  330. }
  331. }
  332. void
  333. JackWinMMEOutputPort::WriteOutError(const char *jack_func, const char *mm_func,
  334. MMRESULT result)
  335. {
  336. char error_message[MAXERRORLENGTH];
  337. GetOutErrorString(result, error_message);
  338. jack_error("%s - %s: %s", jack_func, mm_func, error_message);
  339. }