File: winmidioutput.cpp

package info (click to toggle)
libdrumstick 2.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,876 kB
  • sloc: cpp: 25,685; xml: 122; sh: 14; makefile: 5
file content (387 lines) | stat: -rw-r--r-- 11,809 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/*
    Drumstick RT Windows Backend
    Copyright (C) 2009-2024 Pedro Lopez-Cabanillas <plcl@users.sf.net>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include <QStringList>
#include <QByteArray>
#include <QVarLengthArray>
#include <qmath.h>
#include <windows.h>
#include <mmsystem.h>
#include "winmidioutput.h"

#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
#define hex Qt::hex
#endif

namespace drumstick {
namespace rt {

    union WinMIDIPacket {
        WinMIDIPacket() : dwPacket(0) {}
        DWORD dwPacket;
        quint8 data[sizeof(DWORD)];
    };

    static QLatin1String DEFAULT_PUBLIC_NAME = QLatin1String("MIDI Out");

    void CALLBACK midiCallback( HMIDIOUT hmo,
                                UINT wMsg,
                                DWORD_PTR dwInstance,
                                DWORD_PTR dwParam1,
                                DWORD_PTR dwParam2);

    class WinMIDIOutput::WinMIDIOutputPrivate {
    public:
        HMIDIOUT m_handle;
        bool m_clientFilter;
        QString m_publicName;
        MIDIConnection m_currentOutput;
        QList<MIDIConnection> m_outputDevices;
        MIDIHDR m_midiSysexHdr;
        QByteArray m_sysexBuffer;
        QStringList m_excludedNames;
        bool m_status;
        QStringList m_diagnostics;

        WinMIDIOutputPrivate():
            m_handle(nullptr),
            m_clientFilter(true),
            m_publicName(DEFAULT_PUBLIC_NAME)
        {
            reloadDeviceList(true);
        }

        ~WinMIDIOutputPrivate()
        {
            close();
        }

        void reloadDeviceList(bool advanced)
        {
            MMRESULT res;
            MIDIOUTCAPS deviceCaps;
            QString devName;
            unsigned int dev, max = midiOutGetNumDevs();
            m_outputDevices.clear();
            m_clientFilter = !advanced;

            for ( dev = 0; dev < max; ++dev) {
                bool excluded = false;
                res = midiOutGetDevCaps( dev, &deviceCaps, sizeof(MIDIOUTCAPS));
                if (res != MMSYSERR_NOERROR)
                    break;
                if (m_clientFilter && (deviceCaps.wTechnology == MOD_MAPPER || dev == MIDI_MAPPER))
                    continue;
    #if defined(UNICODE)
                devName = QString::fromWCharArray(deviceCaps.szPname);
    #else
                devName = QString::fromLocal8Bit(deviceCaps.szPname);
    #endif
                foreach (const QString& n, m_excludedNames) {
                    if (devName.startsWith(n)) {
                        excluded = true;
                        break;
                    }
                }

                if (!excluded) {
                    m_outputDevices << MIDIConnection(devName, dev);
                }
            }
            if (!m_clientFilter) {
                dev = MIDI_MAPPER;
                res = midiOutGetDevCaps( dev, &deviceCaps, sizeof(MIDIOUTCAPS));
                if (res == MMSYSERR_NOERROR) {
    #if defined(UNICODE)
                    devName = QString::fromWCharArray(deviceCaps.szPname);
    #else
                    devName = QString::fromLocal8Bit(deviceCaps.szPname);
    #endif
                    m_outputDevices << MIDIConnection(devName, dev);
                }
            }
        }

        void setPublicName(QString name)
        {
            if (m_publicName != name) {
                m_publicName = name;
            }
        }

        void open(const MIDIConnection& conn)
        {
            MMRESULT res;
            m_status = false;
            m_diagnostics.clear();
            if (m_handle != nullptr)
                close();
            reloadDeviceList(!m_clientFilter);
            if (!conn.first.isEmpty()) {
                res = midiOutOpen( &m_handle, conn.second.toInt(), (DWORD_PTR) midiCallback, (DWORD_PTR) this, CALLBACK_FUNCTION);
                if (res == MMSYSERR_NOERROR) {
                    m_currentOutput = conn;
                    m_status = true;
                } else {
                    logError("midiStreamOpen()", res);
                }
            }
        }

        void close()
        {
            MMRESULT res;
            m_status = false;
            m_diagnostics.clear();
            if (m_handle != nullptr) {
                res = midiOutReset( m_handle );
                if (res != MMSYSERR_NOERROR)
                    logError("midiOutReset()", res);
                res = midiOutClose( m_handle );
                if (res == MMSYSERR_NOERROR)
                    m_currentOutput = MIDIConnection();
                else
                    logError("midiStreamClose()", res);
                m_handle = nullptr;
            }
        }

        void doneHeader( LPMIDIHDR lpMidiHdr )
        {
            MMRESULT res;
            res = midiOutUnprepareHeader( m_handle, lpMidiHdr, sizeof(MIDIHDR) );
            if (res != MMSYSERR_NOERROR)
                logError("midiOutUnprepareHeader()", res);
            if ((lpMidiHdr->dwFlags & MHDR_ISSTRM) == 0)
                return; // sysex header?
        }

        void sendShortMessage(WinMIDIPacket &packet)
        {
            MMRESULT res;
            res = midiOutShortMsg( m_handle, packet.dwPacket );
            if ( res != MMSYSERR_NOERROR )
                logError("midiOutShortMsg()", res);
        }

        void sendSysexEvent(const QByteArray& data)
        {
            MMRESULT res;
            m_sysexBuffer = data;
            m_midiSysexHdr.lpData = (LPSTR) m_sysexBuffer.data();
            m_midiSysexHdr.dwBufferLength = m_sysexBuffer.size();
            m_midiSysexHdr.dwBytesRecorded = m_sysexBuffer.size();
            m_midiSysexHdr.dwFlags = 0;
            m_midiSysexHdr.dwUser = 0;
            res = midiOutPrepareHeader( m_handle, &m_midiSysexHdr, sizeof(MIDIHDR) );
            if (res != MMSYSERR_NOERROR)
                logError("midiOutPrepareHeader()", res);
            else {
                res = midiOutLongMsg( m_handle, &m_midiSysexHdr, sizeof(MIDIHDR) );
                if (res != MMSYSERR_NOERROR)
                    logError("midiOutLongMsg()", res);
            }
        }

        QString mmErrorString(MMRESULT err)
        {
            QString errstr;
    #ifdef UNICODE
            WCHAR buffer[1024];
            midiOutGetErrorText(err, &buffer[0], sizeof(buffer));
            errstr = QString::fromWCharArray(buffer);
    #else
            char buffer[1024];
            midiOutGetErrorText(err, &buffer[0], sizeof(buffer));
            errstr = QString::fromLocal8Bit(buffer);
    #endif
            return errstr;
        }

        void logError(const QString context, const MMRESULT code)
        {
            m_diagnostics << QString("%1 error: %2 (%3)").arg(context).arg(code).arg(mmErrorString(code));
        }
    };


    void CALLBACK midiCallback( HMIDIOUT hmo,
                                UINT wMsg,
                                DWORD_PTR dwInstance,
                                DWORD_PTR dwParam1,
                                DWORD_PTR dwParam2)
    {
        Q_UNUSED(hmo)
        Q_UNUSED(dwParam2)
        WinMIDIOutput::WinMIDIOutputPrivate* obj = (WinMIDIOutput::WinMIDIOutputPrivate*) dwInstance;
        switch( wMsg ) {
        case MOM_DONE:
            obj->doneHeader( (LPMIDIHDR) dwParam1 );
            break;
        case MOM_OPEN:
            obj->m_diagnostics << "Open output";
            break;
        case MOM_CLOSE:
            obj->m_diagnostics << "Close output";
            break;
        default:
            obj->m_diagnostics << QString("unknown output message: %1").arg(wMsg);
            break;
        }
    }

    WinMIDIOutput::WinMIDIOutput(QObject *parent) :
        MIDIOutput(parent), d(new WinMIDIOutputPrivate)
    { }

    WinMIDIOutput::~WinMIDIOutput()
    {
        delete d;
    }

    void WinMIDIOutput::initialize(QSettings *settings)
    {
        Q_UNUSED(settings)
    }

    QString WinMIDIOutput::backendName()
    {
        return "Windows MM";
    }

    QString WinMIDIOutput::publicName()
    {
        return d->m_publicName;
    }

    void WinMIDIOutput::setPublicName(QString name)
    {
        d->setPublicName(name);
    }

    QList<MIDIConnection> WinMIDIOutput::connections(bool advanced)
    {
        d->reloadDeviceList(advanced);
        return d->m_outputDevices;
    }

    void WinMIDIOutput::setExcludedConnections(QStringList conns)
    {
        d->m_excludedNames = conns;
    }

    void WinMIDIOutput::open(const MIDIConnection& name)
    {
        d->open(name);
    }

    void WinMIDIOutput::close()
    {
        d->close();
    }

    MIDIConnection WinMIDIOutput::currentConnection()
    {
        return d->m_currentOutput;
    }

    void WinMIDIOutput::sendNoteOn(int chan, int note, int vel)
    {
        WinMIDIPacket packet;
        packet.data[0] = MIDI_STATUS_NOTEON | (chan & MIDI_CHANNEL_MASK);
        packet.data[1] = note;
        packet.data[2] = vel;
        d->sendShortMessage(packet);
    }

    void WinMIDIOutput::sendNoteOff(int chan, int note, int vel)
    {
        WinMIDIPacket packet;
        packet.data[0] = MIDI_STATUS_NOTEOFF | (chan & MIDI_CHANNEL_MASK);
        packet.data[1] = note;
        packet.data[2] = vel;
        d->sendShortMessage(packet);
    }

    void WinMIDIOutput::sendController(int chan, int control, int value)
    {
        WinMIDIPacket packet;
        packet.data[0] = MIDI_STATUS_CONTROLCHANGE | (chan & MIDI_CHANNEL_MASK);
        packet.data[1] = control;
        packet.data[2] = value;
        d->sendShortMessage(packet);
    }

    void WinMIDIOutput::sendKeyPressure(int chan, int note, int value)
    {
        WinMIDIPacket packet;
        packet.data[0] = MIDI_STATUS_KEYPRESURE | (chan & MIDI_CHANNEL_MASK);
        packet.data[1] = note;
        packet.data[2] = value;
        d->sendShortMessage(packet);
    }

    void WinMIDIOutput::sendProgram(int chan, int program)
    {
        WinMIDIPacket packet;
        packet.data[0] = MIDI_STATUS_PROGRAMCHANGE | (chan & MIDI_CHANNEL_MASK);
        packet.data[1] = program;
        d->sendShortMessage(packet);
    }

    void WinMIDIOutput::sendChannelPressure(int chan, int value)
    {
        WinMIDIPacket packet;
        packet.data[0] = MIDI_STATUS_CHANNELPRESSURE | (chan & MIDI_CHANNEL_MASK);
        packet.data[1] = value;
        d->sendShortMessage(packet);
    }

    void WinMIDIOutput::sendPitchBend(int chan, int v)
    {
        WinMIDIPacket packet;
        // -8192 <= v <= 8191; 0 <= value <= 16384
        int value = 8192 + v;
        packet.data[0] = MIDI_STATUS_PITCHBEND | (chan & MIDI_CHANNEL_MASK);
        packet.data[1] = MIDI_LSB(value);
        packet.data[2] = MIDI_MSB(value);
        d->sendShortMessage(packet);
    }

    void WinMIDIOutput::sendSystemMsg(const int status)
    {
        WinMIDIPacket packet;
        packet.data[0] = status;
        d->sendShortMessage(packet);
    }

    void WinMIDIOutput::sendSysex(const QByteArray &data)
    {
        d->sendSysexEvent(data);
    }

    QStringList WinMIDIOutput::getDiagnostics()
    {
        return d->m_diagnostics;
    }

    bool WinMIDIOutput::getStatus()
    {
        return d->m_status;
    }
}}