-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathmidicontroller.cpp
529 lines (459 loc) · 19.7 KB
/
midicontroller.cpp
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
#include "controllers/midi/midicontroller.h"
#include "control/controlobject.h"
#include "controllers/defs_controllers.h"
#include "controllers/midi/midiutils.h"
#include "defs_urls.h"
#include "errordialoghandler.h"
#include "mixer/playermanager.h"
#include "moc_midicontroller.cpp"
#include "util/math.h"
#include "util/screensaver.h"
MidiController::MidiController(const QString& deviceName)
: Controller(deviceName) {
setDeviceCategory(tr("MIDI Controller"));
}
MidiController::~MidiController() {
destroyOutputHandlers();
// Don't close the device here. Sub-classes should close the device in their
// destructors.
}
ControllerJSProxy* MidiController::jsProxy() {
return new MidiControllerJSProxy(this);
}
QString MidiController::mappingExtension() {
return MIDI_MAPPING_EXTENSION;
}
void MidiController::setMapping(std::shared_ptr<LegacyControllerMapping> pMapping) {
m_pMapping = downcastAndTakeOwnership<LegacyMidiControllerMapping>(std::move(pMapping));
}
std::shared_ptr<LegacyControllerMapping> MidiController::cloneMapping() {
if (!m_pMapping) {
return nullptr;
}
return m_pMapping->clone();
}
int MidiController::close() {
destroyOutputHandlers();
return 0;
}
bool MidiController::matchMapping(const MappingInfo& mapping) {
// Product info mapping not implemented for MIDI devices yet
Q_UNUSED(mapping);
return false;
}
bool MidiController::applyMapping() {
// Handles the engine
bool result = Controller::applyMapping();
// Only execute this code if this is an output device
if (isOutputDevice()) {
if (m_outputs.count() > 0) {
destroyOutputHandlers();
}
createOutputHandlers();
updateAllOutputs();
}
return result;
}
void MidiController::createOutputHandlers() {
if (!m_pMapping) {
return;
}
if (m_pMapping->getOutputMappings().isEmpty()) {
return;
}
QStringList failures;
for (const auto& mapping : m_pMapping->getOutputMappings()) {
QString group = mapping.controlKey.group;
QString key = mapping.controlKey.item;
unsigned char status = mapping.output.status;
unsigned char control = mapping.output.control;
unsigned char on = mapping.output.on;
unsigned char off = mapping.output.off;
double min = mapping.output.min;
double max = mapping.output.max;
qCDebug(m_logBase)
<< QString("Creating output handler for %1,%2 between %3 and "
"%4 to MIDI out: 0x%5 0x%6, on: 0x%7 off: 0x%8")
.arg(group,
key,
QString::number(min),
QString::number(max),
QString::number(status, 16).toUpper(),
QString::number(control, 16)
.toUpper()
.rightJustified(2, '0'),
QString::number(on, 16)
.toUpper()
.rightJustified(2, '0'),
QString::number(off, 16)
.toUpper()
.rightJustified(2, '0'));
MidiOutputHandler* moh = new MidiOutputHandler(this, mapping, m_logOutput);
if (!moh->validate()) {
QString errorLog =
QString("MIDI output message 0x%1 0x%2 has invalid MixxxControl %3, %4")
.arg(QString::number(status, 16).toUpper(),
QString::number(control, 16).toUpper().rightJustified(2, '0'),
group,
key)
.toUtf8();
qCWarning(m_logBase) << errorLog;
int deckNum = 0;
if (m_logBase().isDebugEnabled()) {
failures.append(errorLog);
} else if (PlayerManager::isDeckGroup(group, &deckNum)) {
int numDecks = PlayerManager::numDecks();
if (deckNum <= numDecks) {
failures.append(errorLog);
}
}
delete moh;
continue;
}
m_outputs.append(moh);
}
if (!failures.isEmpty()) {
ErrorDialogProperties* props = ErrorDialogHandler::instance()->newDialogProperties();
props->setType(DLG_WARNING);
props->setTitle(tr("MixxxControl(s) not found"));
props->setText(tr(
"One or more MixxxControls specified in the "
"outputs section of the loaded mapping were invalid."));
props->setInfoText(tr("Some LEDs or other feedback may not work correctly."));
QString detailsText = tr("* Check to see that the MixxxControl "
"names are spelled correctly in the mapping "
"file (.xml)\n");
detailsText += tr(
"* Make sure the MixxxControls in question actually exist."
" Visit the manual for a complete list: ");
detailsText += MIXXX_MANUAL_CONTROLS_URL + QStringLiteral("\n\n");
detailsText += failures.join("\n");
props->setDetails(detailsText);
ErrorDialogHandler::instance()->requestErrorDialog(props);
}
}
void MidiController::updateAllOutputs() {
foreach (MidiOutputHandler* pOutput, m_outputs) {
pOutput->update();
}
}
void MidiController::destroyOutputHandlers() {
while (m_outputs.size() > 0) {
delete m_outputs.takeLast();
}
}
void MidiController::learnTemporaryInputMappings(const MidiInputMappings& mappings) {
foreach (const MidiInputMapping& mapping, mappings) {
m_temporaryInputMappings.insert(mapping.key.key, mapping);
MidiOpCode opCode = MidiUtils::opCodeFromStatus(mapping.key.status);
bool twoBytes = MidiUtils::isMessageTwoBytes(opCode);
QString message = twoBytes ? QString("0x%1 0x%2")
.arg(QString::number(mapping.key.status, 16).toUpper(),
QString::number(mapping.key.control, 16).toUpper()
.rightJustified(2,'0')) :
QString("0x%1")
.arg(QString::number(mapping.key.status, 16).toUpper());
qDebug() << "Set mapping for" << message << "to"
<< mapping.control.group << mapping.control.item;
}
}
void MidiController::clearTemporaryInputMappings() {
m_temporaryInputMappings.clear();
}
void MidiController::commitTemporaryInputMappings() {
if (!m_pMapping) {
return;
}
// We want to replace duplicates that exist in m_mapping but allow duplicates
// in m_temporaryInputMappings. To do this, we first remove every key in
// m_temporaryInputMappings from m_mapping's input mappings.
for (auto it = m_temporaryInputMappings.constBegin();
it != m_temporaryInputMappings.constEnd(); ++it) {
m_pMapping->removeInputMapping(it.key());
}
// Now, we can just use add all mappings from m_temporaryInputMappings
// since we removed the duplicates in the original set.
for (auto it = m_temporaryInputMappings.constBegin();
it != m_temporaryInputMappings.constEnd();
++it) {
m_pMapping->addInputMapping(it.key(), it.value());
}
m_temporaryInputMappings.clear();
}
void MidiController::receivedShortMessage(unsigned char status,
unsigned char control,
unsigned char value,
mixxx::Duration timestamp) {
// The rest of this function is for legacy mappings
unsigned char channel = MidiUtils::channelFromStatus(status);
MidiOpCode opCode = MidiUtils::opCodeFromStatus(status);
// Ignore MIDI beat clock messages (0xF8) until we have proper MIDI sync in
// Mixxx. These messages are not suitable to use in JS anyway, as they are
// sent at 24 ppqn (i.e. one message every 20.83 ms for a 120 BPM track)
// and require real-time code. Currently, they are only spam on the
// console, inhibit the screen saver unintentionally, could potentially
// slow down Mixxx or interfere with the learning wizard.
if (status == 0xF8) {
return;
}
qCDebug(m_logInput) << MidiUtils::formatMidiOpCode(
getName(), status, control, value, channel, opCode, timestamp);
MidiKey mappingKey(status, control);
triggerActivity();
if (isLearning()) {
emit messageReceived(status, control, value);
auto it = m_temporaryInputMappings.constFind(mappingKey.key);
if (it != m_temporaryInputMappings.constEnd()) {
for (; it != m_temporaryInputMappings.constEnd() && it.key() == mappingKey.key; ++it) {
processInputMapping(it.value(), status, control, value, timestamp);
}
return;
}
}
auto it = m_pMapping->getInputMappings().constFind(mappingKey.key);
for (; it != m_pMapping->getInputMappings().constEnd() && it.key() == mappingKey.key; ++it) {
processInputMapping(it.value(), status, control, value, timestamp);
}
}
void MidiController::processInputMapping(const MidiInputMapping& mapping,
unsigned char status,
unsigned char control,
unsigned char value,
mixxx::Duration timestamp) {
Q_UNUSED(timestamp);
unsigned char channel = MidiUtils::channelFromStatus(status);
MidiOpCode opCode = MidiUtils::opCodeFromStatus(status);
if (mapping.options.testFlag(MidiOption::Script)) {
ControllerScriptEngineLegacy* pEngine = getScriptEngine();
if (pEngine == nullptr) {
return;
}
QJSValue function = pEngine->wrapFunctionCode(mapping.control.item, 5);
const auto args = QJSValueList{
channel,
control,
value,
status,
mapping.control.group,
};
if (!pEngine->executeFunction(function, args)) {
qCWarning(m_logBase) << "MidiController: Invalid script function"
<< mapping.control.item;
}
return;
}
// Only pass values on to valid ControlObjects.
ControlObject* pCO = ControlObject::getControl(mapping.control);
if (pCO == nullptr) {
return;
}
double newValue = value;
const bool mapping_is_14bit = mapping.options &
(MidiOption::FourteenBitMSB | MidiOption::FourteenBitLSB);
if (!mapping_is_14bit && !m_fourteen_bit_queued_mappings.isEmpty()) {
qCWarning(m_logBase) << "MidiController was waiting for the MSB/LSB of a 14-bit"
<< "message but the next message received was not mapped as 14-bit."
<< "Ignoring the original message.";
m_fourteen_bit_queued_mappings.clear();
}
//qDebug() << "MIDI Options" << QString::number(mapping.options, 2).rightJustified(16,'0');
if (mapping_is_14bit) {
bool found = false;
for (auto it = m_fourteen_bit_queued_mappings.begin();
it != m_fourteen_bit_queued_mappings.end(); ++it) {
if (it->first.control == mapping.control) {
if ((it->first.options & mapping.options) &
(MidiOption::FourteenBitLSB | MidiOption::FourteenBitMSB)) {
qCWarning(m_logBase)
<< "MidiController: 14-bit MIDI mapping has "
"mis-matched LSB/MSB options."
<< "Ignoring both messages.";
m_fourteen_bit_queued_mappings.erase(it);
return;
}
int iValue = 0;
if (mapping.options.testFlag(MidiOption::FourteenBitMSB)) {
iValue = (value << 7) | it->second;
// qDebug() << "MSB" << value
// << "LSB" << it->second
// << "Joint:" << iValue;
} else if (mapping.options.testFlag(MidiOption::FourteenBitLSB)) {
iValue = (it->second << 7) | value;
// qDebug() << "MSB" << it->second
// << "LSB" << value
// << "Joint:" << iValue;
}
// NOTE(rryan): The 14-bit message ranges from 0x0000 to
// 0x3FFF. Dividing by 0x81 maps this onto the range of 0 to
// 127. However, some controllers map the center to MSB 64
// (0x40) and LSB 0. Dividing by 128 (0x80) maps 0x2000
// directly to 0x40. See ControlLinPotmeterBehavior and
// ControlPotmeterBehavior for more fun of this variety :).
newValue = static_cast<double>(iValue) / 128.0;
newValue = math_min(newValue, 127.0);
// Erase the queued message since we processed it.
m_fourteen_bit_queued_mappings.erase(it);
found = true;
break;
}
}
if (!found) {
// Queue this mapping and value for processing once we receive the next
// message.
m_fourteen_bit_queued_mappings.append(qMakePair(mapping, value));
return;
}
} else if (opCode == MidiOpCode::PitchBendChange) {
// compute 14-bit value for pitch bend messages
int iValue;
iValue = (value << 7) | control;
// NOTE(rryan): The 14-bit message ranges from 0x0000 to
// 0x3FFF. Dividing by 0x81 maps this onto the range of 0 to
// 127. However, some controllers map the center to MSB 64
// (0x40) and LSB 0. Dividing by 128 (0x80) maps 0x2000
// directly to 0x40. See ControlLinPotmeterBehavior and
// ControlPotmeterBehavior for more fun of this variety :).
newValue = static_cast<double>(iValue) / 128.0;
newValue = math_min(newValue, 127.0);
} else {
double currControlValue = pCO->getMidiParameter();
newValue = computeValue(mapping.options, currControlValue, value);
}
// ControlPushButton ControlObjects only accept NOTE_ON, so if the midi
// mapping is <button> we override the Midi 'status' appropriately.
if (mapping.options & (MidiOption::Button | MidiOption::Switch)) {
opCode = MidiOpCode::NoteOn;
}
if (mapping.options.testFlag(MidiOption::SoftTakeover)) {
// This is the only place to enable it if it isn't already.
m_st.enable(pCO);
if (m_st.ignore(pCO, pCO->getParameterForMidi(newValue))) {
return;
}
}
pCO->setValueFromMidi(static_cast<MidiOpCode>(opCode), newValue);
}
double MidiController::computeValue(
MidiOptions options, double prevmidivalue, double newmidivalue) {
double tempval = 0.;
double diff = 0.;
if (!options) {
return newmidivalue;
}
if (options.testFlag(MidiOption::Invert)) {
return 127. - newmidivalue;
}
if (options & (MidiOption::Rot64 | MidiOption::Rot64Invert)) {
tempval = prevmidivalue;
diff = newmidivalue - 64.;
if (diff == -1 || diff == 1) {
diff /= 16;
} else {
diff += (diff > 0 ? -1 : +1);
}
if (options.testFlag(MidiOption::Rot64)) {
tempval += diff;
} else {
tempval -= diff;
}
return (tempval < 0. ? 0. : (tempval > 127. ? 127.0 : tempval));
}
if (options.testFlag(MidiOption::Rot64Fast)) {
tempval = prevmidivalue;
diff = newmidivalue - 64.;
diff *= 1.5;
tempval += diff;
return (tempval < 0. ? 0. : (tempval > 127. ? 127.0 : tempval));
}
if (options.testFlag(MidiOption::Diff)) {
//Interpret 7-bit signed value using two's compliment.
if (newmidivalue >= 64.) {
newmidivalue = newmidivalue - 128.;
}
//Apply sensitivity to signed value. FIXME
// if(sensitivity > 0)
// _newmidivalue = _newmidivalue * ((double)sensitivity / 50.);
//Apply new value to current value.
newmidivalue = prevmidivalue + newmidivalue;
}
if (options.testFlag(MidiOption::SelectKnob)) {
//Interpret 7-bit signed value using two's compliment.
if (newmidivalue >= 64.) {
newmidivalue = newmidivalue - 128.;
}
//Apply sensitivity to signed value. FIXME
//if(sensitivity > 0)
// _newmidivalue = _newmidivalue * ((double)sensitivity / 50.);
//Since this is a selection knob, we do not want to inherit previous values.
}
if (options.testFlag(MidiOption::Button)) {
newmidivalue = newmidivalue != 0;
}
if (options.testFlag(MidiOption::Switch)) {
newmidivalue = 1;
}
if (options.testFlag(MidiOption::Spread64)) {
//qDebug() << "MIDI_OPT_SPREAD64";
// BJW: Spread64: Distance away from centre point (aka "relative CC")
// Uses a similar non-linear scaling formula as ControlTTRotary::getValueFromWidget()
// but with added sensitivity adjustment. This formula is still experimental.
newmidivalue = newmidivalue - 64.;
//FIXME
//double distance = _newmidivalue - 64.;
// _newmidivalue = distance * distance * sensitivity / 50000.;
//if (distance < 0.)
// _newmidivalue = -newmidivalue;
//qDebug() << "Spread64: in " << distance << " out " << newmidivalue;
}
if (options.testFlag(MidiOption::HercJog)) {
if (newmidivalue > 64.) {
newmidivalue -= 128.;
}
newmidivalue += prevmidivalue;
//if (_prevmidivalue != 0.0) { qDebug() << "AAAAAAAAAAAA" << prevmidivalue; }
}
if (options.testFlag(MidiOption::HercJogFast)) {
if (newmidivalue > 64.) {
newmidivalue -= 128.;
}
newmidivalue = prevmidivalue + (newmidivalue * 3);
}
return newmidivalue;
}
void MidiController::receive(const QByteArray& data, mixxx::Duration timestamp) {
qCDebug(m_logInput) << MidiUtils::formatSysexMessage(getName(), data, timestamp);
MidiKey mappingKey(data.at(0), 0xFF);
triggerActivity();
// TODO(rryan): Need to review how MIDI learn works with sysex messages. I
// don't think this actually does anything useful.
if (isLearning()) {
// TODO(rryan): Fake a one value?
emit messageReceived(mappingKey.status, mappingKey.control, 0x7F);
auto it = m_temporaryInputMappings.constFind(mappingKey.key);
if (it != m_temporaryInputMappings.constEnd()) {
for (; it != m_temporaryInputMappings.constEnd() && it.key() == mappingKey.key; ++it) {
processInputMapping(it.value(), data, timestamp);
}
return;
}
}
auto it = m_pMapping->getInputMappings().constFind(mappingKey.key);
for (; it != m_pMapping->getInputMappings().constEnd() && it.key() == mappingKey.key; ++it) {
processInputMapping(it.value(), data, timestamp);
}
}
void MidiController::processInputMapping(const MidiInputMapping& mapping,
const QByteArray& data,
mixxx::Duration timestamp) {
// Custom script handler
if (mapping.options.testFlag(MidiOption::Script)) {
ControllerScriptEngineLegacy* pEngine = getScriptEngine();
if (pEngine == nullptr) {
return;
}
pEngine->handleIncomingData(data);
return;
}
qCWarning(m_logBase) << "MidiController: No script function specified for"
<< MidiUtils::formatSysexMessage(getName(), data, timestamp);
}