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.

397 lines
13KB

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