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.

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