-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathOSCBundle.cpp
More file actions
408 lines (360 loc) · 13.3 KB
/
Copy pathOSCBundle.cpp
File metadata and controls
408 lines (360 loc) · 13.3 KB
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
/*
Written by Yotam Mann, The Center for New Music and Audio Technologies,
University of California, Berkeley. Copyright (c) 2012, The Regents of
the University of California (Regents).
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, this paragraph and the following two paragraphs appear in all copies,
modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
For bug reports and feature requests please email me at yotam@cnmat.berkeley.edu
*/
#include "OSCBundle.h"
#include <stdlib.h>
#define OSCBUNDLE_PREALLOCATE 16
/*=============================================================================
CONSTRUCTORS / DESTRUCTOR
=============================================================================*/
OSCBundle::OSCBundle(osctime_t _timetag){
setTimetag(_timetag);
numMessages = 0;
error = OSC_OK;
messages = NULL;
incomingBuffer = NULL;
incomingBufferSize = 0;
incomingBufferFree = 0;
decodeState = STANDBY;
}
OSCBundle::~OSCBundle(){
for (int i = 0; i < numMessages; i++){
OSCMessage * msg = getOSCMessage(i);
delete msg;
}
free(messages);
free(incomingBuffer);
}
//clears all of the OSCMessages inside
OSCBundle& OSCBundle::empty(){
error = OSC_OK;
for (int i = 0; i < numMessages; i++){
OSCMessage * msg = getOSCMessage(i);
delete msg;
}
free(messages);
messages = NULL;
shrinkIncomingBuffer();
numMessages = 0;
//Reset the decoder too. Without this a bundle left in any state other
//than STANDBY stayed there forever, so the usual pattern of one long-lived
//OSCBundle refilled in loop() accepted the first packet and then rejected
//every packet after it, permanently.
decodeState = STANDBY;
return *this;
}
/*=============================================================================
SETTERS
=============================================================================*/
OSCMessage & OSCBundle::add(const char * _address){
OSCMessage * msg = new OSCMessage(_address);
if (!msg->hasError()){
//realloc the array to fit the message
OSCMessage ** messageMem = (OSCMessage **) realloc(messages, sizeof(OSCMessage *) * (numMessages + 1));
if (messageMem != NULL){
messages = messageMem;
messages[numMessages] = msg;
numMessages++;
} else {
error = ALLOCFAILED;
}
}
return *msg;
}
OSCMessage & OSCBundle::add(){
OSCMessage * msg = new OSCMessage();
//realloc the array to fit the message
OSCMessage ** messageMem = (OSCMessage **) realloc(messages, sizeof(OSCMessage *) * (numMessages + 1));
if (messageMem != NULL){
messages = messageMem;
messages[numMessages] = msg;
numMessages++;
} else {
error = ALLOCFAILED;
}
return *msg;
}
OSCMessage & OSCBundle::add(OSCMessage & _msg){
OSCMessage * msg = new OSCMessage(&_msg);
if (!msg->hasError()){
//realloc the array to fit the message
OSCMessage ** messageMem = (OSCMessage **) realloc(messages, sizeof(OSCMessage *) * (numMessages + 1));
if (messageMem != NULL){
messages = messageMem;
messages[numMessages] = msg;
numMessages++;
} else {
error = ALLOCFAILED;
}
}
return *msg;
}
/*=============================================================================
GETTERS
=============================================================================*/
//returns the first fullMatch.
OSCMessage * OSCBundle::getOSCMessage( char * addr){
for (int i = 0; i < numMessages; i++){
OSCMessage * msg = getOSCMessage(i);
if (msg->fullMatch(addr)){
return msg;
}
}
return NULL;
}
//the position is the same as the order they were declared in
OSCMessage * OSCBundle::getOSCMessage(int pos){
if (pos < numMessages){
return messages[pos];
}
return NULL;
}
/*=============================================================================
PATTERN MATCHING
=============================================================================*/
bool OSCBundle::dispatch(const char * pattern, void (*callback)(OSCMessage&), int initial_offset){
bool called = false;
for (int i = 0; i < numMessages; i++){
//Use the message in place. This used to be `OSCMessage msg = getOSCMessage(i)`,
//which - because getOSCMessage returns a pointer and OSCMessage(OSCMessage*)
//is a converting constructor - deep-copied every message in the bundle on
//every dispatch, allocating a fresh address string and a fresh OSCData per
//argument and then freeing the lot. A sketch calling route() four times per
//packet paid that four times over. It also meant callbacks were handed a
//temporary, so anything they wrote to the message was discarded.
OSCMessage * msg = getOSCMessage(i);
if (msg == NULL) continue;
called = msg->dispatch(pattern, callback, initial_offset) || called ;
}
return called;
}
bool OSCBundle::route(const char * pattern, void (*callback)(OSCMessage&, int), int initial_offset){
bool called = false;
for (int i = 0; i < numMessages; i++){
OSCMessage * msg = getOSCMessage(i); //in place; see dispatch() above
if (msg == NULL) continue;
called = msg->route(pattern, callback, initial_offset) || called;
}
return called;
}
/*=============================================================================
SIZE
=============================================================================*/
int OSCBundle::size(){
return numMessages;
}
/*=============================================================================
ERROR HANDLING
=============================================================================*/
bool OSCBundle::hasError(){
bool retError = error != OSC_OK;
//test each of the data
for (int i = 0; i < numMessages; i++){
OSCMessage * msg = getOSCMessage(i);
retError |= msg->hasError();
}
return retError;
}
OSCErrorCode OSCBundle::getError(){
return error;
}
/*=============================================================================
SENDING
=============================================================================*/
OSCBundle& OSCBundle::send(Print &p){
//don't send a bundle with errors
if (hasError()){
return *this;
}
//write the bundle header
static const uint8_t header[] = {'#', 'b', 'u', 'n', 'd', 'l', 'e', 0};
p.write(header, 8);
//write the timetag
{
osctime_t time = timetag;
uint32_t d = BigEndian(time.seconds);
uint8_t * ptr = (uint8_t *) &d;
p.write(ptr, 4);
d = BigEndian(time.fractionofseconds);
ptr = (uint8_t *) &d;
p.write(ptr, 4);
}
//send the messages
for (int i = 0; i < numMessages; i++){
const auto msg = getOSCMessage(i);
int msgSize = msg->bytes();
//turn the message size into a pointer
const uint32_t s32 = BigEndian((uint32_t) msgSize);
const uint8_t * sptr = (uint8_t *) &s32;
//write the message size
p.write(sptr, 4);
msg->send(p);
}
return *this;
}
/*=============================================================================
FILLING
=============================================================================*/
OSCBundle& OSCBundle::fill(uint8_t incomingByte){
decode(incomingByte);
return *this;
}
OSCBundle& OSCBundle::fill(const uint8_t * incomingBytes, int length){
while (length--){
decode(*incomingBytes++);
}
return *this;
}
/*=============================================================================
DECODING
=============================================================================*/
void OSCBundle::decodeTimetag(){
//parse the incoming buffer as a uint64; setTimetag handles the endianness
setTimetag(incomingBuffer);
decodeState = MESSAGE_SIZE;
clearIncomingBuffer();
}
void OSCBundle::decodeHeader(){
const char * header = "#bundle";
if (strcmp(header, (char *) incomingBuffer)!=0){
//otherwise go back to the top and wait for a new bundle header
decodeState = STANDBY;
error = INVALID_OSC;
} else {
decodeState = TIMETAG;
}
clearIncomingBuffer();
}
void OSCBundle::decodeMessage(uint8_t incomingByte){
//get the current message
if (numMessages > 0){
OSCMessage * lastMessage = messages[numMessages - 1];
//put the bytes in there
lastMessage->fill(incomingByte);
//if it's all done
if (incomingBufferSize == incomingMessageSize){
//move onto the next message
decodeState = MESSAGE_SIZE;
clearIncomingBuffer();
} else if (incomingMessageSize > 0 && incomingBufferSize > incomingMessageSize){
error = INVALID_OSC;
}
}
}
//does not validate the incoming OSC for correctness
void OSCBundle::decode(uint8_t incomingByte){
addToIncomingBuffer(incomingByte);
switch (decodeState){
case STANDBY:
if (incomingByte == '#'){
decodeState = HEADER;
} else if (incomingByte == '/'){
add();//add a simple message to the bundle
decodeMessage(incomingByte);
decodeState = MESSAGE;
//in this special case we initialize the message size
//to zero to skip the later error check
incomingMessageSize = 0;
}
break;
case HEADER:
if (incomingBufferSize == 8){
decodeHeader();
decodeState = TIMETAG;
}
break;
case TIMETAG:
if (incomingBufferSize == 8){
decodeTimetag();
decodeState = MESSAGE_SIZE;
}
break;
case MESSAGE_SIZE:
if (incomingBufferSize == 4){
//make sure the message size is valid
int32_t msgSize;
memcpy(&msgSize, incomingBuffer, 4);
msgSize = BigEndian(msgSize);
//msgSize <= 0, not just == 0: the element size is a signed
//value taken straight off the wire, so a negative one passed
//both of the old tests and was then used as a byte count.
if (msgSize <= 0 || msgSize % 4 != 0){
error = INVALID_OSC;
} else {
//add a message to the buffer
decodeState = MESSAGE;
incomingMessageSize = msgSize;
clearIncomingBuffer();
//add a new empty message
add();
}
}
break;
case MESSAGE:
decodeMessage(incomingByte);
break;
}
}
/*=============================================================================
INCOMING BUFFER MANAGEMENT
=============================================================================*/
void OSCBundle::addToIncomingBuffer(uint8_t incomingByte){
//refuse to grow without bound on a length taken from the wire
if (incomingBufferSize >= OSC_MAX_INCOMING){
error = BUFFER_FULL;
return;
}
//Grow in blocks. This used to realloc for every single byte, which on a
//part with no heap compaction is both slow and fragmenting.
if (incomingBufferFree == 0){
//double, clamped to the cap
int capacity = incomingBufferSize + incomingBufferFree;
int want = capacity ? capacity * 2 : OSCBUNDLE_PREALLOCATE;
if (want > OSC_MAX_INCOMING){
want = OSC_MAX_INCOMING;
}
if (want <= incomingBufferSize){
want = incomingBufferSize + 1;
}
uint8_t * mem = (uint8_t *) realloc(incomingBuffer, want);
if (mem == NULL){
error = ALLOCFAILED;
return;
}
incomingBuffer = mem;
incomingBufferFree = want - incomingBufferSize;
}
incomingBuffer[incomingBufferSize++] = incomingByte;
incomingBufferFree--;
}
//Called at every message boundary inside a bundle, so like OSCMessage's this
//is a hot path. It used to free the buffer outright and force the next message
//to build it again from nothing. Keep the capacity; empty() gives it back.
void OSCBundle::clearIncomingBuffer(){
incomingBufferFree += incomingBufferSize;
incomingBufferSize = 0;
}
//Release capacity acquired by an unusually large bundle. Only from empty().
void OSCBundle::shrinkIncomingBuffer(){
incomingBufferSize = 0;
incomingBufferFree = 0;
free(incomingBuffer);
incomingBuffer = NULL;
}