File: alsamidiinput.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 (395 lines) | stat: -rw-r--r-- 14,051 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
388
389
390
391
392
393
394
395
/*
    Drumstick RT Backend using the ALSA Sequencer
    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 "alsamidiinput.h"
#include <QMap>
#include <QStringList>
#include <drumstick/alsaclient.h>
#include <drumstick/alsaevent.h>
#include <drumstick/alsaport.h>
#include <drumstick/rtmidioutput.h>

namespace drumstick { namespace rt {

    using namespace ALSA;

    const QString ALSAMIDIInput::DEFAULT_PUBLIC_NAME = QStringLiteral("MIDI In");

    class ALSAMIDIInput::ALSAMIDIInputPrivate : public SequencerEventHandler
    {
    public:

        ALSAMIDIInput *m_inp;
        MIDIOutput *m_out;
        MidiClient *m_client;
        MidiPort *m_port;
        int m_portId;
        int m_clientId;
        bool m_thruEnabled;
        bool m_clientFilter;
        int m_runtimeAlsaNum;
        QString m_publicName;
        MIDIConnection m_currentInput;
        QList<MIDIConnection> m_inputDevices;
        QStringList m_excludedNames;
        bool m_initialized;
        bool m_status;
        QStringList m_diagnostics;

        explicit ALSAMIDIInputPrivate(ALSAMIDIInput *inp) :
            m_inp(inp),
            m_out(nullptr),
            m_client(nullptr),
            m_port(nullptr),
            m_portId(-1),
            m_clientId(-1),
            m_thruEnabled(false),
            m_clientFilter(false),
            m_publicName(ALSAMIDIInput::DEFAULT_PUBLIC_NAME),
            m_initialized(false),
            m_status(false)
        {
            m_runtimeAlsaNum = getRuntimeALSALibraryNumber();
        }

        virtual ~ALSAMIDIInputPrivate()
        {
            if (m_initialized) {
                clearSubscription();
                uninitialize();
            }
        }

        void initialize() {
            if (!m_initialized) {
                m_client = new MidiClient(m_inp);
                m_client->open();
                m_client->setClientName(m_publicName);
                m_port = m_client->createPort();
                m_port->setPortName("in");
                m_port->setCapability( SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE );
                m_port->setPortType( SND_SEQ_PORT_TYPE_APPLICATION | SND_SEQ_PORT_TYPE_MIDI_GENERIC );
                m_clientId = m_client->getClientId();
                m_portId = m_port->getPortId();
                m_port->setTimestamping(false);
                m_port->setTimestampReal(false);
                m_client->setHandler(this);
                m_initialized = true;
                m_status = true;
                m_diagnostics.clear();
                m_client->startSequencerInput();
                reloadDeviceList(false);
            }
            //qDebug() << Q_FUNC_INFO << m_initialized;
        }

        void uninitialize() {
            if (m_initialized) {
                if (m_port != nullptr) {
                    m_port->detach();
                    delete m_port;
                    m_port = nullptr;
                }
                if (m_client != nullptr) {
                    m_client->close();
                    delete m_client;
                    m_client = nullptr;
                }
                m_initialized = false;
                m_status = false;
                m_diagnostics.clear();
            }
            //qDebug() << Q_FUNC_INFO << m_initialized;
        }

        bool clientIsAdvanced(int clientId)
        {
            // asking for runtime version instead of SND_LIB_VERSION
            if (m_runtimeAlsaNum < 0x01000B)
                // ALSA <= 1.0.10
                return (clientId < 64);
            else
                // ALSA >= 1.0.11
                return (clientId < 16);
        }

        void reloadDeviceList(bool advanced)
        {
            QStringList clientNames;
            QMap<QString,int> namesMap;
            if (!m_initialized) {
                initialize();
            }
            auto inputs = m_client->getAvailableInputs();
            m_clientFilter = !advanced;
            m_inputDevices.clear();
            m_inputDevices << MIDIConnection();
            for (const PortInfo &p : std::as_const(inputs)) {
                QString name = p.getClientName();
                clientNames << name;
                if (namesMap.contains(name)) {
                    namesMap[name]++;
                } else {
                    namesMap.insert(name, 1);
                }
            }
            for (PortInfo& p : inputs) {
                bool excluded = false;
                QString name = p.getClientName();
                if (m_clientFilter && clientIsAdvanced(p.getClient()))
                    continue;
                if ( m_clientFilter && name.startsWith(QStringLiteral("Virtual Raw MIDI")) )
                    continue;
                if ( name.startsWith(m_publicName) )
                    continue;
                for (const QString &n : std::as_const(m_excludedNames)) {
                    if (name.startsWith(n)) {
                        excluded = true;
                        break;
                    }
                }
                if (!excluded) {
                    int k = clientNames.count(name) + 1;
                    QString addr = QString("%1:%2").arg(p.getClient()).arg(p.getPort());
                    if (k > 2) {
                        m_inputDevices << MIDIConnection(QString("%1 (%2)").arg(name).arg(k - namesMap[name]--), addr);
                    } else {
                        m_inputDevices << MIDIConnection(name, addr);
                    }
                }
            }
            if (!m_currentInput.first.isEmpty() &&
                !m_inputDevices.contains(m_currentInput)) {
                m_currentInput = MIDIConnection();
            }
        }

        bool setSubscription(const MIDIConnection &newDevice)
        {
            //qDebug() << Q_FUNC_INFO << newDevice;
            if (!m_initialized) {
                initialize();
            }
            if (m_inputDevices.contains(newDevice)) {
                m_currentInput = newDevice;
                m_port->unsubscribeAll();
                m_port->subscribeFrom(newDevice.second.toString());
                return true;
            }
            return false;
        }

        void clearSubscription()
        {
            //qDebug() << Q_FUNC_INFO;
            if (!m_currentInput.first.isEmpty() && m_initialized) {
                m_client->stopSequencerInput();
                m_port->unsubscribeAll();
                m_currentInput = MIDIConnection();
            }
        }

        void setPublicName(QString newName)
        {
            if (newName != m_publicName) {
                m_publicName = newName;
                if(m_initialized) {
                    m_client->setClientName(newName);
                }
            }
        }

        void handleSequencerEvent(SequencerEvent* ev) override
        {
            //qDebug() << Q_FUNC_INFO;
            if ( !SequencerEvent::isConnectionChange(ev) && m_initialized)
                switch(ev->getSequencerType()) {
                case SND_SEQ_EVENT_NOTEOFF: {
                        const NoteOffEvent* n = static_cast<const NoteOffEvent*>(ev);
                        if(m_out != nullptr && m_thruEnabled) {
                            m_out->sendNoteOff(n->getChannel(), n->getKey(), n->getVelocity());
                        }
                        Q_EMIT m_inp->midiNoteOff(n->getChannel(), n->getKey(), n->getVelocity());
                    }
                    break;
                case SND_SEQ_EVENT_NOTEON: {
                        const NoteOnEvent* n = static_cast<const NoteOnEvent*>(ev);
                        if(m_out != nullptr && m_thruEnabled) {
                            m_out->sendNoteOn(n->getChannel(), n->getKey(), n->getVelocity());
                        }
                        Q_EMIT m_inp->midiNoteOn(n->getChannel(), n->getKey(), n->getVelocity());
                    }
                    break;
                case SND_SEQ_EVENT_KEYPRESS: {
                        const KeyPressEvent* n = static_cast<const KeyPressEvent*>(ev);
                        if(m_out != nullptr && m_thruEnabled) {
                            m_out->sendKeyPressure(n->getChannel(), n->getKey(), n->getVelocity());
                        }
                        Q_EMIT m_inp->midiKeyPressure(n->getChannel(), n->getKey(), n->getVelocity());
                    }
                    break;
                case SND_SEQ_EVENT_CONTROLLER:
                case SND_SEQ_EVENT_CONTROL14: {
                        const ControllerEvent* n = static_cast<const ControllerEvent*>(ev);
                        if(m_out != nullptr && m_thruEnabled) {
                            m_out->sendController(n->getChannel(), n->getParam(), n->getValue());
                        }
                        Q_EMIT m_inp->midiController(n->getChannel(), n->getParam(), n->getValue());
                    }
                    break;
                case SND_SEQ_EVENT_PGMCHANGE: {
                        const ProgramChangeEvent* p = static_cast<const ProgramChangeEvent*>(ev);
                        if(m_out != nullptr && m_thruEnabled) {
                            m_out->sendProgram(p->getChannel(), p->getValue());
                        }
                        Q_EMIT m_inp->midiProgram(p->getChannel(), p->getValue());
                    }
                    break;
                case SND_SEQ_EVENT_CHANPRESS: {
                        const ChanPressEvent* n = static_cast<const ChanPressEvent*>(ev);
                        if(m_out != nullptr && m_thruEnabled) {
                            m_out->sendChannelPressure(n->getChannel(), n->getValue());
                        }
                        Q_EMIT m_inp->midiChannelPressure(n->getChannel(), n->getValue());
                    }
                    break;
                case SND_SEQ_EVENT_PITCHBEND: {
                        const PitchBendEvent* n = static_cast<const PitchBendEvent*>(ev);
                        if(m_out != nullptr && m_thruEnabled) {
                            m_out->sendPitchBend(n->getChannel(), n->getValue());
                        }
                        Q_EMIT m_inp->midiPitchBend(n->getChannel(), n->getValue());
                    }
                    break;
                case SND_SEQ_EVENT_SYSEX: {
                        const SysExEvent* n = static_cast<const SysExEvent*>(ev);
                        QByteArray data(n->getData(), n->getLength());
                        if(m_out != nullptr && m_thruEnabled) {
                            m_out->sendSysex(data);
                        }
                        Q_EMIT m_inp->midiSysex(data);
                    }
                    break;
                case SND_SEQ_EVENT_SYSTEM: {
                        const SystemEvent* n = static_cast<const SystemEvent*>(ev);
                        int status = (int) n->getRaw8(0);
                        if(m_out != nullptr && m_thruEnabled) {
                            m_out->sendSystemMsg(status);
                        }
                        if (status < 0xF7)
                            Q_EMIT m_inp->midiSystemCommon(status);
                        else if (status > 0xF7)
                            Q_EMIT m_inp->midiSystemRealtime(status);
                    }
                    break;
                default:
                    break;
                }
            delete ev;
        }
    };

    ALSAMIDIInput::ALSAMIDIInput(QObject *parent) : MIDIInput(parent),
        d(new ALSAMIDIInputPrivate(this))
    { }

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

    void ALSAMIDIInput::initialize(QSettings* settings)
    {
        Q_UNUSED(settings)
        d->initialize();
    }

    QString ALSAMIDIInput::backendName()
    {
        return QStringLiteral("ALSA");
    }

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

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

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

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

    void ALSAMIDIInput::open(const MIDIConnection& name)
    {
        //qDebug() << Q_FUNC_INFO;
        auto b = d->setSubscription(name);
        if (!b) {
            d->m_diagnostics << "failed subscription to " + name.first;
        }
    }

    void ALSAMIDIInput::close()
    {
        //qDebug() << Q_FUNC_INFO;
        d->clearSubscription();
        d->uninitialize();
    }

    MIDIConnection ALSAMIDIInput::currentConnection()
    {
        return d->m_currentInput;
    }

    void ALSAMIDIInput::setMIDIThruDevice(MIDIOutput *device)
    {
        d->m_out = device;
    }

    void ALSAMIDIInput::enableMIDIThru(bool enable)
    {
        d->m_thruEnabled = enable;
    }

    bool ALSAMIDIInput::isEnabledMIDIThru()
    {
        return d->m_thruEnabled && (d->m_out != nullptr);
    }

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

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

} // namespace rt
} // namespace drumstick