2 * Copyright (C) 2015 Tim Mayberry <mojofunk@gmail.com>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 #include "winmmemidi_output_device.h"
23 #include "pbd/debug.h"
24 #include "pbd/compose.h"
25 #include "pbd/pthread_utils.h"
26 #include "pbd/windows_timer_utils.h"
27 #include "pbd/windows_mmcss.h"
29 #include "midi_util.h"
33 // remove dup with input_device
34 static const uint32_t MIDI_BUFFER_SIZE = 32768;
35 static const uint32_t MAX_QUEUE_SIZE = 4096;
39 WinMMEMidiOutputDevice::WinMMEMidiOutputDevice (int index)
41 , m_queue_semaphore(0)
42 , m_sysex_semaphore(0)
46 , m_thread_running(false)
47 , m_thread_quit(false)
48 , m_midi_buffer(new RingBuffer<uint8_t>(MIDI_BUFFER_SIZE))
50 DEBUG_MIDI (string_compose ("Creating midi output device index: %1\n", index));
52 std::string error_msg;
54 if (!open (index, error_msg)) {
55 DEBUG_MIDI (error_msg);
56 throw std::runtime_error (error_msg);
59 set_device_name (index);
62 WinMMEMidiOutputDevice::~WinMMEMidiOutputDevice ()
64 std::string error_msg;
65 if (!close (error_msg)) {
66 DEBUG_MIDI (error_msg);
71 WinMMEMidiOutputDevice::enqueue_midi_event (uint64_t timestamp,
75 const uint32_t total_bytes = sizeof(MidiEventHeader) + size;
76 if (m_midi_buffer->write_space () < total_bytes) {
77 DEBUG_MIDI ("WinMMEMidiOutput: ring buffer overflow\n");
81 MidiEventHeader h (timestamp, size);
82 m_midi_buffer->write ((uint8_t*)&h, sizeof(MidiEventHeader));
83 m_midi_buffer->write (data, size);
85 signal (m_queue_semaphore);
90 WinMMEMidiOutputDevice::open (UINT index, std::string& error_msg)
92 MMRESULT result = midiOutOpen (&m_handle,
94 (DWORD_PTR)winmm_output_callback,
97 if (result != MMSYSERR_NOERROR) {
98 error_msg = get_error_string (result);
102 m_queue_semaphore = CreateSemaphore (NULL, 0, MAX_QUEUE_SIZE, NULL);
103 if (m_queue_semaphore == NULL) {
104 DEBUG_MIDI ("WinMMEMidiOutput: Unable to create queue semaphore\n");
107 m_sysex_semaphore = CreateSemaphore (NULL, 0, 1, NULL);
108 if (m_sysex_semaphore == NULL) {
109 DEBUG_MIDI ("WinMMEMidiOutput: Unable to create sysex semaphore\n");
116 WinMMEMidiOutputDevice::close (std::string& error_msg)
118 // return error message for first error encountered?
120 MMRESULT result = midiOutClose (m_handle);
121 if (result != MMSYSERR_NOERROR) {
122 error_msg = get_error_string (result);
123 DEBUG_MIDI (error_msg);
127 if (m_sysex_semaphore) {
128 if (!CloseHandle (m_sysex_semaphore)) {
129 DEBUG_MIDI ("WinMMEMidiOut Unable to close sysex semaphore\n");
132 m_sysex_semaphore = 0;
135 if (m_queue_semaphore) {
136 if (!CloseHandle (m_queue_semaphore)) {
137 DEBUG_MIDI ("WinMMEMidiOut Unable to close queue semaphore\n");
140 m_queue_semaphore = 0;
149 WinMMEMidiOutputDevice::set_device_name (UINT index)
151 MIDIOUTCAPS capabilities;
153 midiOutGetDevCaps (index, &capabilities, sizeof(capabilities));
155 if (result != MMSYSERR_NOERROR) {
156 DEBUG_MIDI (get_error_string (result));
157 m_name = "Unknown Midi Output Device";
160 m_name = capabilities.szPname;
166 WinMMEMidiOutputDevice::get_error_string (MMRESULT error_code)
168 char error_msg[MAXERRORLENGTH];
169 MMRESULT result = midiOutGetErrorText (error_code, error_msg, MAXERRORLENGTH);
170 if (result != MMSYSERR_NOERROR) {
173 return "WinMMEMidiOutput: Unknown Error code";
177 WinMMEMidiOutputDevice::start ()
179 if (m_thread_running) {
181 string_compose ("WinMMEMidiOutput: device %1 already started\n", m_name));
185 m_timer = CreateWaitableTimer (NULL, FALSE, NULL);
188 DEBUG_MIDI ("WinMMEMidiOutput: unable to create waitable timer\n");
192 if (!start_midi_output_thread ()) {
193 DEBUG_MIDI ("WinMMEMidiOutput: Failed to start MIDI output thread\n");
195 if (!CloseHandle (m_timer)) {
196 DEBUG_MIDI ("WinMMEMidiOutput: unable to close waitable timer\n");
204 WinMMEMidiOutputDevice::stop ()
206 if (!m_thread_running) {
207 DEBUG_MIDI ("WinMMEMidiOutputDevice: device already stopped\n");
211 if (!stop_midi_output_thread ()) {
212 DEBUG_MIDI ("WinMMEMidiOutput: Failed to stop MIDI output thread\n");
216 if (!CloseHandle (m_timer)) {
217 DEBUG_MIDI ("WinMMEMidiOutput: unable to close waitable timer\n");
225 WinMMEMidiOutputDevice::start_midi_output_thread ()
227 m_thread_quit = false;
229 //pthread_attr_t attr;
230 size_t stacksize = 100000;
232 // TODO Use native threads
233 if (pbd_realtime_pthread_create (PBD_SCHED_FIFO, -21, stacksize,
234 &m_output_thread_handle, midi_output_thread, this)) {
239 while (!m_thread_running && --timeout > 0) { Glib::usleep (1000); }
240 if (timeout == 0 || !m_thread_running) {
241 DEBUG_MIDI (string_compose ("Unable to start midi output device thread: %1\n",
249 WinMMEMidiOutputDevice::stop_midi_output_thread ()
252 m_thread_quit = true;
253 signal (m_queue_semaphore);
255 while (m_thread_running && --timeout > 0) { Glib::usleep (1000); }
256 if (timeout == 0 || m_thread_running) {
257 DEBUG_MIDI (string_compose ("Unable to stop midi output device thread: %1\n",
263 if (pthread_join (m_output_thread_handle, &status)) {
264 DEBUG_MIDI (string_compose ("Unable to join midi output device thread: %1\n",
272 WinMMEMidiOutputDevice::signal (HANDLE semaphore)
274 bool result = (bool)ReleaseSemaphore (semaphore, 1, NULL);
276 DEBUG_MIDI ("WinMMEMidiOutDevice: Cannot release semaphore\n");
282 WinMMEMidiOutputDevice::wait (HANDLE semaphore)
284 DWORD result = WaitForSingleObject (semaphore, INFINITE);
287 DEBUG_MIDI ("WinMMEMidiOutDevice: WaitForSingleObject Failed\n");
292 DEBUG_MIDI ("WinMMEMidiOutDevice: Unexpected result from WaitForSingleObject\n");
298 WinMMEMidiOutputDevice::winmm_output_callback (HMIDIOUT handle,
304 ((WinMMEMidiOutputDevice*)instance)
305 ->midi_output_callback (msg, midi_data, timestamp);
309 WinMMEMidiOutputDevice::midi_output_callback (UINT message,
315 DEBUG_MIDI ("WinMMEMidiOutput - MIDI device closed\n");
318 signal (m_sysex_semaphore);
321 DEBUG_MIDI ("WinMMEMidiOutput - MIDI device opened\n");
324 LPMIDIHDR header = (LPMIDIHDR)midi_data;
325 DEBUG_MIDI (string_compose ("WinMMEMidiOut - %1 bytes out of %2 bytes of "
326 "the current sysex message have been sent.\n",
328 header->dwBytesRecorded));
333 WinMMEMidiOutputDevice::midi_output_thread (void *arg)
335 WinMMEMidiOutputDevice* output_device = reinterpret_cast<WinMMEMidiOutputDevice*> (arg);
336 output_device->midi_output_thread ();
341 WinMMEMidiOutputDevice::midi_output_thread ()
343 m_thread_running = true;
345 DEBUG_MIDI ("WinMMEMidiOut: MIDI output thread started\n");
347 #ifdef USE_MMCSS_THREAD_PRIORITIES
350 PBD::MMCSS::set_thread_characteristics ("Pro Audio", &task_handle);
351 PBD::MMCSS::set_thread_priority (task_handle, PBD::MMCSS::AVRT_PRIORITY_HIGH);
354 while (!m_thread_quit) {
355 if (!wait (m_queue_semaphore)) {
356 DEBUG_MIDI ("WinMMEMidiOut: output thread waiting for semaphore failed\n");
360 DEBUG_MIDI ("WinMMEMidiOut: output thread woken by semaphore\n");
362 MidiEventHeader h (0, 0);
363 uint8_t data[MaxWinMidiEventSize];
365 const uint32_t read_space = m_midi_buffer->read_space ();
367 DEBUG_MIDI (string_compose ("WinMMEMidiOut: total readable MIDI data %1\n", read_space));
369 if (read_space > sizeof(MidiEventHeader)) {
370 if (m_midi_buffer->read ((uint8_t*)&h, sizeof(MidiEventHeader)) !=
371 sizeof(MidiEventHeader)) {
372 DEBUG_MIDI ("WinMMEMidiOut: Garbled MIDI EVENT HEADER!!\n");
375 assert (read_space >= h.size);
377 if (h.size > MaxWinMidiEventSize) {
378 m_midi_buffer->increment_read_idx (h.size);
379 DEBUG_MIDI ("WinMMEMidiOut: MIDI event too large!\n");
382 if (m_midi_buffer->read (&data[0], h.size) != h.size) {
383 DEBUG_MIDI ("WinMMEMidiOut: Garbled MIDI EVENT DATA!!\n");
388 DEBUG_MIDI ("WinMMEMidiOut: MIDI buffer underrun, shouldn't occur\n");
391 uint64_t current_time = PBD::get_microseconds ();
393 DEBUG_TIMING (string_compose (
394 "WinMMEMidiOut: h.time = %1, current_time = %2\n", h.time, current_time));
396 if (h.time > current_time) {
398 DEBUG_TIMING (string_compose ("WinMMEMidiOut: waiting at %1 for %2 "
399 "milliseconds before sending message\n",
400 ((double)current_time) / 1000.0,
401 ((double)(h.time - current_time)) / 1000.0));
403 if (!wait_for_microseconds (h.time - current_time))
405 DEBUG_MIDI ("WinMMEMidiOut: Error waiting for timer\n");
409 uint64_t wakeup_time = PBD::get_microseconds ();
410 DEBUG_TIMING (string_compose ("WinMMEMidiOut: woke up at %1(ms)\n",
411 ((double)wakeup_time) / 1000.0));
412 if (wakeup_time > h.time) {
413 DEBUG_TIMING (string_compose ("WinMMEMidiOut: overslept by %1(ms)\n",
414 ((double)(wakeup_time - h.time)) / 1000.0));
415 } else if (wakeup_time < h.time) {
416 DEBUG_TIMING (string_compose ("WinMMEMidiOut: woke up %1(ms) too early\n",
417 ((double)(h.time - wakeup_time)) / 1000.0));
420 } else if (h.time < current_time) {
421 DEBUG_TIMING (string_compose (
422 "WinMMEMidiOut: MIDI event at sent to driver %1(ms) late\n",
423 ((double)(current_time - h.time)) / 1000.0));
426 DEBUG_MIDI (string_compose ("WinMMEMidiOut: MIDI event size: %1 time %2 now %3\n", h.size, h.time, current_time));
432 message |= (((DWORD)data[2]) << 16);
433 // Fallthrough on purpose.
435 message |= (((DWORD)data[1]) << 8);
436 // Fallthrough on purpose.
438 message |= (DWORD)data[0];
439 result = midiOutShortMsg (m_handle, message);
440 if (result != MMSYSERR_NOERROR) {
442 string_compose ("WinMMEMidiOutput: %1\n", get_error_string (result)));
448 header.dwBufferLength = h.size;
450 header.lpData = (LPSTR)data;
452 result = midiOutPrepareHeader (m_handle, &header, sizeof(MIDIHDR));
453 if (result != MMSYSERR_NOERROR) {
454 DEBUG_MIDI (string_compose ("WinMMEMidiOutput: midiOutPrepareHeader %1\n",
455 get_error_string (result)));
459 result = midiOutLongMsg (m_handle, &header, sizeof(MIDIHDR));
460 if (result != MMSYSERR_NOERROR) {
461 DEBUG_MIDI (string_compose ("WinMMEMidiOutput: midiOutLongMsg %1\n",
462 get_error_string (result)));
466 // Sysex messages may be sent synchronously or asynchronously. The
467 // choice is up to the WinMME driver. So, we wait until the message is
468 // sent, regardless of the driver's choice.
470 DEBUG_MIDI ("WinMMEMidiOut: wait for sysex semaphore\n");
472 if (!wait (m_sysex_semaphore)) {
473 DEBUG_MIDI ("WinMMEMidiOut: wait for sysex semaphore - failed!\n");
477 result = midiOutUnprepareHeader (m_handle, &header, sizeof(MIDIHDR));
478 if (result != MMSYSERR_NOERROR) {
479 DEBUG_MIDI (string_compose ("WinMMEMidiOutput: midiOutUnprepareHeader %1\n",
480 get_error_string (result)));
485 #ifdef USE_MMCSS_THREAD_PRIORITIES
486 PBD::MMCSS::revert_thread_characteristics (task_handle);
489 m_thread_running = false;
493 WinMMEMidiOutputDevice::wait_for_microseconds (int64_t wait_us)
495 LARGE_INTEGER due_time;
498 due_time.QuadPart = -((LONGLONG)(wait_us * 10));
499 if (!SetWaitableTimer (m_timer, &due_time, 0, NULL, NULL, 0)) {
500 DEBUG_MIDI ("WinMMEMidiOut: Error waiting for timer\n");
504 if (!wait (m_timer)) {
511 } // namespace ARDOUR