/
default_libpd_render.cpp
1788 lines (1696 loc) · 50.4 KB
/
default_libpd_render.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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Default render file for Bela projects running Pd patches
* using libpd.
*/
#include <Bela.h>
// Enable features here. These may be undef'ed below if the corresponding
// BELA_LIBPD_DISABLE_* flag is passed
#define BELA_LIBPD_SCOPE
#define BELA_LIBPD_MIDI
#define BELA_LIBPD_TRILL
#define BELA_LIBPD_GUI
#define BELA_LIBPD_SERIAL
#define BELA_LIBPD_SYSTEM_THREADED
#ifdef BELA_LIBPD_DISABLE_SCOPE
#undef BELA_LIBPD_SCOPE
#endif // BELA_LIBPD_DISABLE_SCOPE
#ifdef BELA_LIBPD_DISABLE_MIDI
#undef BELA_LIBPD_MIDI
#endif // BELA_LIBPD_DISABLE_MIDI
#ifdef BELA_LIBPD_DISABLE_TRILL
#undef BELA_LIBPD_TRILL
#endif // BELA_LIBPD_DISABLE_TRILL
#ifdef BELA_LIBPD_DISABLE_GUI
#undef BELA_LIBPD_GUI
#endif // BELA_LIBPD_DISABLE_GUI
#ifdef BELA_LIBPD_DISABLE_SERIAL
#undef BELA_LIBPD_SERIAL
#endif // BELA_LIBPD_DISABLE_SERIAL
#ifdef BELA_LIBPD_DISABLE_SYSTEM_THREADD
#undef BELA_LIBPD_SYSTEM_THREADED
#endif // BELA_LIBPD_DISABLE_SYSTEM_THREADD
#define PD_THREADED_IO
#include <libraries/libpd/libpd.h>
#include <DigitalChannelManager.h>
#include <stdio.h>
#ifdef BELA_LIBPD_MIDI
#include <algorithm>
#include <libraries/Midi/Midi.h>
#include <libraries/Pipe/Pipe.h>
#endif // BELA_LIBPD_MIDI
#ifdef BELA_LIBPD_SCOPE
#include <libraries/Scope/Scope.h>
#endif // BELA_LIBPD_SCOPE
#include <string>
#include <sstream>
#include <string.h>
#include <vector>
#if (defined(BELA_LIBPD_GUI) || defined(BELA_LIBPD_TRILL))
#include <libraries/Pipe/Pipe.h>
template <typename T>
int getIdxFromId(const char* id, std::vector<std::pair<std::string,T>>& db)
{
for(unsigned int n = 0; n < db.size(); ++n)
{
if(0 == strcmp(id, db[n].first.c_str()))
return n;
}
return -1;
}
#endif // BELA_LIBPD_GUI || BELA_LIBPD_TRILL
#ifdef BELA_LIBPD_TRILL
#include <tuple>
#include <libraries/Trill/Trill.h>
AuxiliaryTask gTrillTask;
Pipe gTrillPipe;
static std::vector<std::string> gTrillAcks;
static std::vector<std::pair<std::string,Trill*>> gTouchSensors;
// how often to read the cap sensors inputs.
float touchSensorSleepInterval = 0.007;
void readTouchSensors(void*)
{
for(unsigned int n = 0; n < gTouchSensors.size(); ++n)
{
Trill& touchSensor = *gTouchSensors[n].second;
int ret;
const Trill::Device type = touchSensor.deviceType();
if(Trill::NONE == type)
ret = 1;
else
ret = touchSensor.readI2C();
if(!ret)
{
gTrillPipe.writeNonRt(n);
}
}
}
#endif // BELA_LIBPD_TRILL
#ifdef BELA_LIBPD_GUI
#include <libraries/Gui/Gui.h>
Pipe gGuiPipe;
Gui gui;
struct bufferDescription
{
std::string name;
int id;
int size;
};
static std::vector<struct bufferDescription> gGuiDataBuffers;
static std::vector<std::string> gGuiControlBuffers;
struct guiControlMessageHeader
{
uint32_t size;
uint32_t type;
uint32_t id;
};
bool guiControlDataCallback(JSONObject& root, void* arg)
{
int ret = true;
for(unsigned int n = 0; n < gGuiControlBuffers.size(); ++n)
{
const auto& b = gGuiControlBuffers[n];
std::wstring key = JSON::s2ws(b);
if (root.end() != root.find(key))
{
JSONValue* found = root[key];
struct guiControlMessageHeader header;
header.id = n;
char* array;
if(found->IsString())
{
std::string value = JSON::ws2s(found->AsString());
header.type = 's';
header.size = value.size();
array = (char*)alloca(header.size);
memcpy(array, value.c_str(), header.size);
} else if(found->IsNumber())
{
float value = found->AsNumber();
header.type = 'f';
header.size = sizeof(value);
array = (char*)alloca(header.size);
memcpy(array, &value, header.size);
} else {
continue;
}
// do two separate reads: the pipe is datagram-based
// so it would be impossible to receive partial messages
// at the other end
gGuiPipe.writeNonRt(header);
gGuiPipe.writeNonRt(&array[0], header.size);
// we have successully parsed this message, so the
// default parser shouldn't when we return
// note: in practice there may be times when we'd want
// to have the default parser handle this message
// (e.g.: when an "event" field is also present), but
// for now we ignore them
ret = false;
continue;
}
}
return ret;
}
#endif // BELA_LIBPD_GUI
#ifdef BELA_LIBPD_SERIAL
#include <libraries/Serial/Serial.h>
#include <libraries/Pipe/Pipe.h>
#include <string>
Pipe gSerialPipe;
Serial gSerial;
std::string gSerialId;
int gSerialEom;
enum SerialType {
kSerialFloats,
kSerialBytes,
kSerialSymbol,
kSerialSymbols,
} gSerialType = kSerialFloats;
AuxiliaryTask gSerialInputTask;
AuxiliaryTask gSerialOutputTask;
struct serialMessageHeader
{
uint32_t idSize = 0;
uint32_t dataSize = 0;
};
enum WaitingFor {
kHeader,
kId,
kData,
};
struct SerialPipeState {
struct serialMessageHeader h;
enum WaitingFor waitingFor = kHeader;
char id[100];
};
static void processSerialPipe(bool rt, SerialPipeState& s)
{
// Not sure we actually need while() below. We were using it earlier
// when this was coded inside render() in order to be able to perform early returns
while(1)
{
auto& h = s.h;
auto& waitingFor = s.waitingFor;
auto& id = s.id;
if(kHeader == waitingFor)
{
int ret = rt ? gSerialPipe.readRt(h) : gSerialPipe.readNonRt(h);
if(ret <= 0)
break;
waitingFor = kId;
}
if(kId == waitingFor)
{
if(h.idSize > sizeof(id) - 1)
rt_fprintf(stderr, "Serial: ID too large\n");
else
{
int ret = rt ? gSerialPipe.readRt(id, h.idSize) : gSerialPipe.readNonRt(id, h.idSize);
if(ret <= 0)
break;
if(int(h.idSize) != ret)
{
rt_fprintf(stderr, "Invalid number of bytes read from gSerialPipe. Expected: %u, got %u\n", h.idSize, ret);
break;
}
id[ret] = '\0'; // ensure it's null-terminated
waitingFor = kData;
}
}
if(kData == waitingFor)
{
char data[h.dataSize + 1];
int ret = rt ? gSerialPipe.readRt(data, h.dataSize) : gSerialPipe.readNonRt(data, h.dataSize);
if(ret <= 0)
break;
if(int(h.dataSize) != ret)
{
rt_fprintf(stderr, "Invalid number of bytes read from gSerialPipe. Expected: %u, got %u\n", h.dataSize, ret);
break;
}
if(rt)
{
// rt: forward data from pipe to Pd
data[h.dataSize] = '\0'; // ensure it's null-terminated
if(h.dataSize)
{
const char* rec = "bela_serialIn";
if(kSerialSymbol == gSerialType)
{
libpd_symbol(rec, data);
} else if(kSerialBytes == gSerialType) {
if(gSerialEom >= 0) {
// messages are separated: send as a list
libpd_start_message(h.dataSize);
for(size_t n = 0; n < h.dataSize; ++n)
libpd_add_float(data[n]);
libpd_finish_message(rec, id);
} else {
// messages are not separated: send one byte at a time
for(size_t n = 0; n < h.dataSize; ++n)
{
libpd_start_message(h.dataSize);
libpd_add_float(data[n]);
libpd_finish_message(rec, id);
}
}
} else {
unsigned int nTokens = 1;
const uint8_t separators[] = { ' ', '\0'};
// find number of delimiters
size_t start = 0;
for(size_t n = 0; n < sizeof(data); ++n)
{
for(size_t c = 0; c < sizeof(separators); ++c)
{
if(separators[c] == data[n] && n != start) // exclude empty tokens
{
start = n + 1;
nTokens++;
}
}
}
libpd_start_message(nTokens);
start = 0;
for(size_t n = 0; n < sizeof(data); ++n)
{
bool end = false;
for(size_t c = 0; c < sizeof(separators); ++c)
{
if(separators[c] == data[n])
{
if(start == n)
start++; // remove empty tokens
else
end = true;
break; // no need to check for more separators
}
}
if(end)
{
data[n] = '\0'; // ensure the string is null-terminated so the next line works
if(kSerialSymbols == gSerialType)
libpd_add_symbol(data + start);
else if (kSerialFloats == gSerialType)
libpd_add_float(atof(data + start));
start = n + 1;
}
}
libpd_finish_message(rec, id);
}
}
} else {
// non-rt: forward data from pipe to serial
if(h.dataSize)
gSerial.write(data, h.dataSize);
}
waitingFor = kHeader;
}
}
}
static void serialOutputLoop(void* arg) {
// blocking read with timeout
gSerialPipe.setBlockingNonRt(true);
gSerialPipe.setTimeoutMsNonRt(100);
std::vector<uint8_t> rec(1024);
std::vector<uint8_t> id(100);
SerialPipeState serialStateNonRt {};
while(!Bela_stopRequested())
{
processSerialPipe(false, serialStateNonRt);
}
}
static void serialInputLoop(void* arg) {
char serialBuffer[10000];
unsigned int i = 0;
serialMessageHeader h;
h.idSize = strlen(gSerialId.c_str()) + 1;
while(!Bela_stopRequested())
{
// read from the serial port with a timeout of 100ms
int ret = gSerial.read(serialBuffer + i, sizeof(serialBuffer) - i, 100);
if (ret > 0) {
if(gSerialEom < 0)
{
h.dataSize = ret;
// send everything immediately
gSerialPipe.writeNonRt(h);
gSerialPipe.writeNonRt(gSerialId.c_str(), h.idSize);
gSerialPipe.writeNonRt(serialBuffer, h.dataSize);
} else {
// find EOM in new data
unsigned int searchStart = i;
unsigned int searchStop = searchStart + ret;
unsigned int n;
unsigned int lastSent = 0;
bool found;
do
{
found = false;
for(n = searchStart; n < searchStop; ++n)
{
if(serialBuffer[n] == gSerialEom)
{
found = true;
break;
}
}
// if found, send all data till that point
if(found)
{
h.dataSize = n - lastSent;
if(h.dataSize)
{
gSerialPipe.writeNonRt(h);
gSerialPipe.writeNonRt(gSerialId.c_str(), h.idSize);
gSerialPipe.writeNonRt(serialBuffer + lastSent, h.dataSize);
}
searchStart = n + 1;
lastSent += 1 + h.dataSize;
}
}
while(found);
// if we are left with any data, move it to the beginning of the buffer.
// TODO: avoid this and use it as a circular buffer
if(searchStart != i)
{
memmove(serialBuffer, serialBuffer + searchStart, searchStop - searchStart);
i = searchStop - searchStart;
} else
i = i + searchStop - searchStart;
}
}
}
}
#endif // BELA_LIBPD_SERIAL
enum { minFirstDigitalChannel = 10 };
static unsigned int gAnalogChannelsInUse;
static unsigned int gDigitalChannelsInUse;
#ifdef BELA_LIBPD_SCOPE
static unsigned int gScopeChannelsInUse = 4;
#else // BELA_LIBPD_SCOPE
static unsigned int gScopeChannelsInUse = 0;
#endif // BELA_LIBPD_SCOPE
static unsigned int gLibpdBlockSize;
static unsigned int gChannelsInUse;
//static const unsigned int gFirstAudioChannel = 0;
static unsigned int gFirstAnalogInChannel;
static unsigned int gFirstAnalogOutChannel;
static unsigned int gFirstDigitalChannel;
static unsigned int gLibpdDigitalChannelOffset;
static unsigned int gFirstScopeChannel;
void Bela_userSettings(BelaInitSettings *settings)
{
settings->uniformSampleRate = 1;
settings->interleave = 0;
settings->analogOutputsPersist = 0;
}
float* gInBuf;
float* gOutBuf;
#ifdef BELA_LIBPD_MIDI
#define PARSE_MIDI
int gMidiVerbose = 1;
const int kMidiVerbosePrintLevel = 1;
#include <thread>
static Midi* openMidiDevice(const std::string& name, bool verboseSuccess = false, bool verboseError = false);
static const std::string& midiName(const Midi* m)
{
// assumes input and output are the same subdevice
if(m) {
if(m->isInputEnabled())
return m->getInputPort().name;
else if(m->isOutputEnabled())
return m->getOutputPort().name;
}
static const std::string none("NONE");
return none;
}
static std::thread gMidiDiscoveryThread;
static volatile bool gMidiDiscoveryThreadShouldStop;
static volatile bool gMidiDiscoveryThreadAuto;
static bool gMidiAny;
Pipe gMidiDiscoveryPipe("midiDiscoveryPipe");
enum MidiDiscoveryCmd {
kMidiAdd,
kMidiAck,
};
struct MidiDiscoveryMsgFromNonRt {
MidiDiscoveryCmd cmd;
Midi* ptr;
};
struct MidiDiscoveryMsgFromRt {
MidiDiscoveryCmd cmd;
Midi* ptr;
char name[32];
};
static volatile unsigned int gNumMidiDevicesInitialised = 0;
static void midiDiscovery()
{
gMidiDiscoveryPipe.setBlockingNonRt(true);
gMidiDiscoveryPipe.setTimeoutMsNonRt(100);
// it's hard to use inotify meaningfully, so we poll instead
auto shouldStop = []() {
return Bela_stopRequested() || gMidiDiscoveryThreadShouldStop;
};
std::vector<std::string> toOpen;
std::vector<Midi*> localMidi;
std::vector<MidiDiscoveryMsgFromNonRt> msgs;
int count = 1;
bool doDiscovery = false;
while(!shouldStop())
{
msgs.resize(0);
if(gNumMidiDevicesInitialised == localMidi.size())
{
//printf("We are equal: %d\n", gNumMidiDevicesInitialised);
// when we are fully synced up:
if(doDiscovery && !toOpen.size() && gMidiDiscoveryThreadAuto)
{
doDiscovery = false;
// do discovery
auto list = Midi::listAllPorts();
for(auto& l : list)
{
// Check if there are new devices that are not open yet.
toOpen.push_back(l.name);
// NOTE: devices that are unplugged and plugged back in
// that were previously initialised will be automatically reopened,
// so we are only concerned with new devices here.
}
count = 0;
}
while(toOpen.size())
{
std::string name = toOpen[0];
toOpen.erase(toOpen.begin());
bool found = false;
for(const auto m : localMidi)
{
if(midiName(m) == name)
{
found = true;
break;
}
}
if(!found)
{
printf("New device %s, opening it\n", name.c_str());
Midi* midi = openMidiDevice(name);
if(midi) {
MidiDiscoveryMsgFromNonRt msg = {
.cmd = kMidiAdd,
.ptr = midi,
};
msgs.push_back(msg);
gNumMidiDevicesInitialised++;
break;
}
}
}
}
if(count++ > 20)
doDiscovery = true;
for(auto& msg : msgs)
gMidiDiscoveryPipe.writeNonRt(msg);
MidiDiscoveryMsgFromRt msg;
// potentially blocking read
int ret = gMidiDiscoveryPipe.readNonRt(msg);
if(1 == ret)
{
if(kMidiAck == msg.cmd)
{
localMidi.push_back(msg.ptr);
void dumpMidi();
dumpMidi();
}
if(kMidiAdd == msg.cmd)
toOpen.push_back(msg.name);
}
}
}
static std::vector<Midi*> midi;
void dumpMidi()
{
if(midi.size() == 0)
{
printf("No MIDI device enabled\n");
return;
}
printf("The following MIDI devices are enabled:\n");
printf("%4s%20s %3s %3s %s\n",
"Num",
"Name",
"In",
"Out",
"Pd channels"
);
for(unsigned int n = 0; n < midi.size(); ++n)
{
printf("[%2d]%20s %3s %3s (%d-%d) %s\n",
n,
midiName(midi[n]).c_str(),
midi[n]->isInputEnabled() ? "x" : "_",
midi[n]->isOutputEnabled() ? "x" : "_",
n * 16 + 1,
n * 16 + 16,
gMidiAny ? "(ANY)" : ""
);
}
}
static Midi* openMidiDevice(const std::string& name, bool verboseSuccess, bool verboseError)
{
Midi* newMidi;
newMidi = new Midi();
newMidi->readFrom(name.c_str());
newMidi->writeTo(name.c_str());
#ifdef PARSE_MIDI
newMidi->enableParser(true);
#else
newMidi->enableParser(false);
#endif /* PARSE_MIDI */
if(newMidi->isOutputEnabled())
{
if(verboseSuccess)
printf("Opened MIDI device %s as output\n", name.c_str());
}
if(newMidi->isInputEnabled())
{
if(verboseSuccess)
printf("Opened MIDI device %s as input\n", name.c_str());
}
if(!newMidi->isInputEnabled() && !newMidi->isOutputEnabled())
{
if(verboseError)
fprintf(stderr, "Failed to open MIDI device %s\n", name.c_str());
return nullptr;
} else {
return newMidi;
}
}
static unsigned int getPortChannel(int* channel){
// improper way of using ANY, maybe it should be sending out to all of them instead
if(gMidiAny)
return 0;
unsigned int port = 0;
while(*channel >= 16){
*channel -= 16;
port += 1;
}
return port;
}
void Bela_MidiOutNoteOn(int channel, int pitch, int velocity) {
unsigned int port = getPortChannel(&channel);
if(gMidiVerbose >= kMidiVerbosePrintLevel)
rt_printf("noteout _ port: %d, channel: %d, pitch: %d, velocity %d\n", port, channel, pitch, velocity);
port < midi.size() && midi[port]->writeNoteOn(channel, pitch, velocity);
}
void Bela_MidiOutControlChange(int channel, int controller, int value) {
unsigned int port = getPortChannel(&channel);
if(gMidiVerbose >= kMidiVerbosePrintLevel)
rt_printf("ctlout _ port: %d, channel: %d, controller: %d, value: %d\n", port, channel, controller, value);
port < midi.size() && midi[port]->writeControlChange(channel, controller, value);
}
void Bela_MidiOutProgramChange(int channel, int program) {
unsigned int port = getPortChannel(&channel);
if(gMidiVerbose >= kMidiVerbosePrintLevel)
rt_printf("pgmout _ port: %d, channel: %d, program: %d\n", port, channel, program);
port < midi.size() && midi[port]->writeProgramChange(channel, program);
}
void Bela_MidiOutPitchBend(int channel, int value) {
unsigned int port = getPortChannel(&channel);
if(gMidiVerbose >= kMidiVerbosePrintLevel)
rt_printf("bendout _ port: %d, channel: %d, value: %d\n", port, channel, value);
value += 8192; // correct for Pd's oddity
port < midi.size() && midi[port]->writePitchBend(channel, value);
}
void Bela_MidiOutAftertouch(int channel, int pressure){
unsigned int port = getPortChannel(&channel);
if(gMidiVerbose >= kMidiVerbosePrintLevel)
rt_printf("touchout _ port: %d, channel: %d, pressure: %d\n", port, channel, pressure);
port < midi.size() && midi[port]->writeChannelPressure(channel, pressure);
}
void Bela_MidiOutPolyAftertouch(int channel, int pitch, int pressure){
unsigned int port = getPortChannel(&channel);
if(gMidiVerbose >= kMidiVerbosePrintLevel)
rt_printf("polytouchout _ port: %d, channel: %d, pitch: %d, pressure: %d\n", port, channel, pitch, pressure);
port < midi.size() && midi[port]->writePolyphonicKeyPressure(channel, pitch, pressure);
}
void Bela_MidiOutByte(int port, int byte){
if(gMidiVerbose >= kMidiVerbosePrintLevel)
rt_printf("port: %d, byte: %d\n", port, byte);
if(port > (int)midi.size()){
// if the port is out of range, redirect to the first port.
rt_fprintf(stderr, "Port out of range, using port 0 instead\n");
port = 0;
}
port < (int)midi.size() && midi[port]->writeOutput(byte);
}
#endif // BELA_LIBPD_MIDI
void Bela_printHook(const char *received){
rt_printf("%s", received);
}
static DigitalChannelManager dcm;
void sendDigitalMessage(bool state, unsigned int delay, void* receiverName){
libpd_float((const char*)receiverName, (float)state);
// rt_printf("%s: %d\n", (char*)receiverName, state);
}
#ifdef BELA_LIBPD_TRILL
void setTrillPrintError()
{
rt_fprintf(stderr, "bela_setTrill format is wrong. Should be:\n"
"[mode <sensor_id> <prescaler_value>(\n"
" or\n"
"[threshold <sensor_id> <threshold_value>(\n"
" or\n"
"[prescaler <sensor_id> <prescaler_value>(\n");
}
#endif // BELA_LIBPD_TRILL
static void systemDoSystem(const char* cmd)
{
rt_printf("system(\"%s\");\n", cmd);
system(cmd);
}
#ifdef BELA_LIBPD_SYSTEM_THREADED
#include <AuxTaskNonRT.h>
static AuxTaskNonRT systemTask("systemTask", [](void* buf, int size) {
systemDoSystem((const char*)buf);
});
#endif // BELA_LIBPD_SYSTEM_THREADED
static void belaSystem(const char* first, int argc, t_atom* argv)
{
static std::string cmd; // make it static to try and avoid repeated allocations
cmd = first ? first : "";
for(size_t n = 0; n < argc; ++n)
{
if(0 != n || first)
cmd += " ";
if(libpd_is_float(argv + n)) {
float arg = libpd_get_float(argv + n);
if(arg == (int)arg)
cmd += std::to_string((int)arg);
else
cmd += std::to_string(arg);
} else if(libpd_is_symbol(argv + n)) {
cmd += libpd_get_symbol(argv + n);
} else {
rt_fprintf(stderr, "Error: argument %d of bela_system is not a float or symbol. Command so far: '%s', this will be discarded\n", n, cmd.c_str());
return;
}
}
#ifdef BELA_LIBPD_SYSTEM_THREADED
systemTask.schedule(cmd.c_str(), cmd.size());
#else // BELA_LIBPD_SYSTEM_THREADED
systemDoSystem(cmd.c_str());
#endif // // BELA_LIBPD_SYSTEM_THREADED
}
void Bela_listHook(const char *source, int argc, t_atom *argv)
{
#ifdef BELA_LIBPD_GUI
if(0 == strcmp(source, "bela_guiOut"))
{
if(!libpd_is_float(&argv[0]))
{
rt_fprintf(stderr, "Wrong format for bela_gui, the first element should be a float\n");
return;
}
unsigned int bufNum = libpd_get_float(&argv[0]);
if(libpd_is_float(&argv[1])) // if the first element is a float, we send an array of floats
{
float buf[argc - 1];
for(int n = 1; n < argc; ++n)
{
t_atom *a = &argv[n];
if(!libpd_is_float(a))
{
rt_fprintf(stderr, "Wrong format for bela_gui\n"); // this should never happen, because then the selector would've not been "float"
return;
}
buf[n - 1] = libpd_get_float(a);
}
gui.sendBuffer(bufNum, buf, argc - 1);
return;
} else { // otherwise we send each element of the list separately
for(int n = 1; n < argc; ++n)
{
t_atom *a = &argv[n];
if (libpd_is_float(a)) {
float x = libpd_get_float(a);
gui.sendBuffer(bufNum, x);
} else if (libpd_is_symbol(a)) {
const char *s = libpd_get_symbol(a);
gui.sendBuffer(bufNum, s, strlen(s)); // TODO: should it be strlen(s)+1?
}
}
}
return;
}
#endif // BELA_LIBPD_GUI
if(0 == strcmp(source, "bela_system"))
{
belaSystem(nullptr, argc, argv);
return;
}
}
void Bela_messageHook(const char *source, const char *symbol, int argc, t_atom *argv){
#ifdef BELA_LIBPD_MIDI
if(strcmp(source, "bela_setMidi") == 0)
{
if(0 == strcmp("verbose", symbol))
{
if(1 != argc || !libpd_is_float(argv))
{
rt_fprintf(stderr, "Wrong format for bela_setMidi, expected: [verbose <n>(\n");
} else {
gMidiVerbose = libpd_get_float(argv);
rt_printf("MIDI verbose: %d\n", gMidiVerbose);
}
return;
}
if(0 == strcmp("auto", symbol))
{
if(!gMidiDiscoveryThread.joinable())
gMidiDiscoveryThread = std::thread(midiDiscovery);
bool value = true;
if(argc && libpd_is_float(argv))
value = libpd_get_float(argv);
rt_printf("%s automatic discover of new MIDI devices\n", value ? "Enabling" : "Disabling");
gMidiDiscoveryThreadAuto = value;
return;
}
if(0 == strcmp("any", symbol))
{
bool value = true;
if(argc && libpd_is_float(argv))
value = libpd_get_float(argv);
rt_printf("%s MIDI any\n", value ? "Enabling" : "Disabling");
gMidiAny = value;
return;
}
int num[3] = {0, 0, 0};
for(int n = 0; n < argc && n < 3; ++n)
{
if(!libpd_is_float(&argv[n]))
{
fprintf(stderr, "Wrong format for bela_setMidi, expected:[hw 1 0 0(");
return;
}
num[n] = libpd_get_float(&argv[n]);
}
// TODO: this string/stream business is not actually realtime-safe.
std::ostringstream deviceName;
deviceName << symbol << ":" << num[0] << "," << num[1] << "," << num[2];
MidiDiscoveryMsgFromRt msg = {
.cmd = kMidiAdd,
};
std::string name = deviceName.str();
if(name.size() + 1 > sizeof(msg.name)) {
fprintf(stderr, "MIDI name too long: %s\n", name.c_str());
return;
}
strncpy(msg.name, deviceName.str().c_str(), sizeof(msg.name));
gMidiDiscoveryPipe.writeRt(msg);
return;
}
#endif // BELA_LIBPD_MIDI
if(strcmp(source, "bela_setDigital") == 0){
// symbol is the direction, argv[0] is the channel, argv[1] (optional)
// is signal("sig" or "~") or message("message", default) rate
bool isMessageRate = true; // defaults to message rate
bool direction = 0; // initialize it just to avoid the compiler's warning
bool disable = false;
if(strcmp(symbol, "in") == 0){
direction = INPUT;
} else if(strcmp(symbol, "out") == 0){
direction = OUTPUT;
} else if(strcmp(symbol, "disable") == 0){
disable = true;
} else {
return;
}
if(argc == 0){
return;
} else if (libpd_is_float(&argv[0]) == false){
return;
}
int channel = libpd_get_float(&argv[0]) - gLibpdDigitalChannelOffset;
if(disable == true){
dcm.unmanage(channel);
return;
}
if(argc >= 2){
t_atom* a = &argv[1];
if(libpd_is_symbol(a)){
const char *s = libpd_get_symbol(a);
if(strcmp(s, "~") == 0 || strncmp(s, "sig", 3) == 0){
isMessageRate = false;
}
}
}
dcm.manage(channel, direction, isMessageRate);
return;
}
if(strcmp(source, "bela_system") == 0){
belaSystem(symbol, argc, argv);
return;
}
if(strcmp(source, "bela_control") == 0){
if(strcmp("stop", symbol) == 0){
rt_printf("bela_control: stop\n");
Bela_requestStop();
}
return;
}
#ifdef BELA_LIBPD_GUI
if(0 == strcmp(source, "bela_setGui"))
{
if(0 == strcmp(symbol, "new"))
{
if(
argc < 2
|| !libpd_is_symbol(argv)
|| !libpd_is_symbol(argv + 1)
)
{
return;
}
const char* mode = libpd_get_symbol(argv);
const char* name = libpd_get_symbol(argv + 1);
if(0 == strcmp(mode, "control"))
{
gGuiControlBuffers.emplace_back(name);
return;
}
if(0 == strcmp(mode, "array"))
{
// because of
// https://github.com/libpd/libpd/issues/274
// (again), we cannot access the arrays right
// here (as it would deadlock on loadbang), so
// we have to defer creation of the Gui
// buffers until render() runs
gGuiDataBuffers.emplace_back(bufferDescription{.name = name, .id = -1, .size = 0});
return;
}
return;
}
}
#endif // BELA_LIBPD_GUI
#ifdef BELA_LIBPD_SERIAL
if(0 == strcmp(source, "bela_setSerial"))
{
if(0 == strcmp(symbol, "new"))
{
if(
argc < 5
|| !libpd_is_symbol(argv + 0) // serial_id
|| !libpd_is_symbol(argv + 1) // device
|| !libpd_is_float(argv + 2) // baudrate
|| !(libpd_is_symbol(argv + 3) || libpd_is_float(argv + 3)) // EOM
|| !libpd_is_symbol(argv + 4) // type
)
{
fprintf(stderr, "Invalid bela_setSerial arguments. Should be:\n"
"`new serial_id device baudrate EOM type`,\n"
"where `EOM` is one of `newline` or `none` or a character (expressed as an integer"
" between 0 and 255)\n"
"and `type` is one of `bytes`, `floats`, `symbol`, `symbols`\n");
return;
}
gSerialId = libpd_get_symbol(argv + 0);
const char* device = libpd_get_symbol(argv + 1);
unsigned int baudrate = libpd_get_float(argv + 2);
gSerialEom = -1;
if(libpd_is_symbol(argv + 3)) {
const char* eom = libpd_get_symbol(argv + 3);
if(0 == strcmp(eom, "newline"))
gSerialEom = '\n';
} else if(libpd_is_float(argv + 3)) {
gSerialEom = libpd_get_float(argv + 3);
}
const char* type = libpd_get_symbol(argv + 4);
if(0 == strcmp("floats", type))
gSerialType = kSerialFloats;
else if(0 == strcmp("bytes", type))
gSerialType = kSerialBytes;
else if(0 == strcmp("symbol", type))
gSerialType = kSerialSymbol;
else if(0 == strcmp("symbols", type))
gSerialType = kSerialSymbols;
if(gSerial.setup(device, baudrate))
return;
gSerialInputTask = Bela_runAuxiliaryTask(serialInputLoop, 0);
gSerialOutputTask = Bela_runAuxiliaryTask(serialOutputLoop, 0);
}
}
if(0 == strcmp(source, "bela_serialOut"))
{
if(!argc) {
fprintf(stderr, "Invalid bela_serialOut arguments. Should be:\n"
"`serial_id firstByte <other bytes>`\n");
return;
}
const char* id = symbol;
// convert floats to bytes
char data[argc];