Debian Codegraph @

src/core/util_opsc.cpp

raw symbols SCIP
1 /*----------------------------------------------------------------------------
2 ChucK Strongly-timed Audio Programming Language
3 Compiler, Virtual Machine, and Synthesis Engine
4
5 Copyright (c) 2003 Ge Wang and Perry R. Cook. All rights reserved.
6 http://chuck.stanford.edu/
7 http://chuck.cs.princeton.edu/
8
9 This program is free software; you can redistribute it and/or modify
10 it under the dual-license terms of EITHER the MIT License OR the GNU
11 General Public License (the latter as published by the Free Software
12 Foundation; either version 2 of the License or, at your option, any
13 later version).
14
15 This program is distributed in the hope that it will be useful and/or
16 interesting, but WITHOUT ANY WARRANTY; without even the implied warranty
17 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 MIT Licence and/or the GNU General Public License for details.
19
20 You should have received a copy of the MIT License and the GNU General
21 Public License (GPL) along with this program; a copy of the GPL can also
22 be obtained by writing to the Free Software Foundation, Inc., 59 Temple
23 Place, Suite 330, Boston, MA 02111-1307 U.S.A.
24 -----------------------------------------------------------------------------*/
25
26 //-----------------------------------------------------------------------------
27 // file: util_opsc.cpp
28 // desc: utility for open sound control
29 //
30 // author: Philip L. Davidson ([email protected])
31 // Ge Wang ([email protected])
32 // date: Spring 2005
33 //-----------------------------------------------------------------------------
34 #include "util_opsc.h"
35
36 //chuck networking code
37 #include "util_network.h"
38 #include "util_thread.h"
39 #include "util_platforms.h"
40
41 #include "chuck_errmsg.h"
42 #include "chuck_vm.h"
43
44 #include <algorithm>
45 #include <cstdio>
46 using namespace std;
47
48
49 // FROM PLATFORM.H -UDP TRANSMITTER / RECEIVER
50
51 #if defined(__PLATFORM_WINDOWS__)
52 // 2022 QTSIN added winsock2.h and wsw2tcpip.h
53 #include <winsock2.h>
54 #include <ws2tcpip.h>
55 #include <windows.h>
56 #else
57 #include <sys/types.h>
58 #include <sys/socket.h>
59 #include <sys/time.h>
60 #include <unistd.h>
61 #include <netinet/in.h>
62 #include <netinet/tcp.h>
63 #include <arpa/inet.h>
64 #include <netdb.h>
65 #endif
66
67 // 1.4.1.0 (ge) added
68 #if _MSC_VER
69 #define snprintf _snprintf
70 #endif
71
72 #if defined(__PLATFORM_APPLE__)
73 #define SOCKET int
74 #define SOCKADDR_IN struct sockaddr_in
75 #elif !defined(SOCKADDR_IN)
76 #define SOCKET int
77 #define SOCKADDR_IN struct sockaddr_in
78 #endif
79
80
81 // squeeze the whole wad of OSC-Kit code in here.
82
83 // OSC-pattern-match.cpp
84
85 /*
86 Copyright � 1998. The Regents of the University of California (Regents).
87 All Rights Reserved.
88
89 Written by Matt Wright, The Center for New Music and Audio Technologies,
90 University of California, Berkeley.
91
92 Permission to use, copy, modify, distribute, and distribute modified versions
93 of this software and its documentation without fee and without a signed
94 licensing agreement, is hereby granted, provided that the above copyright
95 notice, this paragraph and the following two paragraphs appear in all copies,
96 modifications, and distributions.
97
98 IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
99 SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
100 OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
101 BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
102
103 REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
104 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
105 PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
106 HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
107 MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
108
109 The OpenSound Control WWW page is
110 http://www.cnmat.berkeley.edu/OpenSoundControl
111 */
112
113
114
115 /*
116 OSC-pattern-match.c
117 Matt Wright, 3/16/98
118 Adapted from oscpattern.c, by Matt Wright and Amar Chaudhury
119 */
120
121 // #include "OSC-pattern-match.h"
122
123 static const char *theWholePattern; /* Just for warning messages */
124
125 static bool MatchBrackets( const char * pattern, const char * test );
126 static bool MatchList( const char * pattern, const char * test );
127
128 bool PatternMatch( const char * pattern, const char * test )
129 {
130 theWholePattern = pattern;
131
132 if( pattern == 0 || pattern[0] == 0 ) {
133 return test[0] == 0;
134 }
135
136 if( test[0] == 0 ) {
137 if(pattern[0] == '*')
138 return PatternMatch (pattern+1,test);
139 else
140 return FALSE;
141 }
142
143 switch( pattern[0] )
144 {
145 case 0 : return test[0] == 0;
146 case '?' : return PatternMatch (pattern + 1, test + 1);
147 case '*' :
148 if( PatternMatch (pattern+1, test) ) {
149 return TRUE;
150 } else {
151 return PatternMatch (pattern, test+1);
152 }
153 case ']' :
154 case '}' :
155 CK_FPRINTF_STDERR( "[chuck](via OSC): spurious %c in pattern \".../%s/...\"\n", pattern[0], theWholePattern );
156 return FALSE;
157 case '[' :
158 return MatchBrackets (pattern,test);
159 case '{' :
160 return MatchList (pattern,test);
161 case '\\' :
162 if(pattern[1] == 0) {
163 return test[0] == 0;
164 } else if(pattern[1] == test[0]) {
165 return PatternMatch (pattern+2,test+1);
166 } else {
167 return FALSE;
168 }
169 default :
170 if(pattern[0] == test[0]) {
171 return PatternMatch (pattern+1,test+1);
172 } else {
173 return FALSE;
174 }
175 }
176 }
177
178
179 /* we know that pattern[0] == '[' and test[0] != 0 */
180
181 static bool MatchBrackets( const char * pattern, const char * test )
182 {
183 bool result;
184 bool negated = FALSE;
185 const char *p = pattern;
186
187 if(pattern[1] == 0) {
188 CK_FPRINTF_STDERR( "[chuck](via OSC): unterminated [ in pattern \".../%s/...\"\n", theWholePattern );
189 return FALSE;
190 }
191
192 if(pattern[1] == '!') {
193 negated = TRUE;
194 p++;
195 }
196
197 while (*p != ']') {
198 if(*p == 0) {
199 CK_FPRINTF_STDERR( "[chuck](via OSC): unterminated [ in pattern \".../%s/...\"\n", theWholePattern );
200 return FALSE;
201 }
202
203 if(p[1] == '-' && p[2] != 0) {
204 if(test[0] >= p[0] && test[0] <= p[2]) {
205 result = !negated;
206 goto advance;
207 }
208 }
209
210 if(p[0] == test[0]) {
211 result = !negated;
212 goto advance;
213 }
214 p++;
215 }
216
217 result = negated;
218
219 advance:
220
221 if(!result)
222 return FALSE;
223
224 while (*p != ']') {
225 if(*p == 0) {
226 CK_FPRINTF_STDERR( "[chuck](via OSC): unterminated [ in pattern \".../%s/...\"\n", theWholePattern );
227 return FALSE;
228 }
229 p++;
230 }
231
232 return PatternMatch (p+1,test+1);
233 }
234
235
236 static bool MatchList( const char * pattern, const char * test )
237 {
238 const char *restOfPattern, *tp = test;
239
240 for(restOfPattern = pattern; *restOfPattern != '}'; restOfPattern++) {
241 if(*restOfPattern == 0) {
242 CK_FPRINTF_STDERR( "[chuck](via OSC): unterminated { in pattern \".../%s/...\"\n", theWholePattern );
243 return FALSE;
244 }
245 }
246
247 restOfPattern++; /* skip close curly brace */
248
249 pattern++; /* skip open curly brace */
250
251 while( 1 )
252 {
253 if(*pattern == ',') {
254 if(PatternMatch (restOfPattern, tp)) {
255 return TRUE;
256 } else {
257 tp = test;
258 ++pattern;
259 }
260 } else if(*pattern == '}') {
261 return PatternMatch (restOfPattern, tp);
262 } else if(*pattern == *tp) {
263 ++pattern;
264 ++tp;
265 } else {
266 tp = test;
267 while (*pattern != ',' && *pattern != '}') {
268 pattern++;
269 }
270 if(*pattern == ',') {
271 pattern++;
272 }
273 }
274 }
275 }
276
277 // end OSC-pattern-match.h
278
279
280 // OSC-timetag.cpp
281
282 /*
283 Copyright (c) 1998. The Regents of the University of California (Regents).
284 All Rights Reserved.
285
286 Permission to use, copy, modify, and distribute this software and its
287 documentation for educational, research, and not-for-profit purposes, without
288 fee and without a signed licensing agreement, is hereby granted, provided that
289 the above copyright notice, this paragraph and the following two paragraphs
290 appear in all copies, modifications, and distributions. Contact The Office of
291 Technology Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley,
292 CA 94720-1620, (510) 643-7201, for commercial licensing opportunities.
293
294 Written by Matt Wright, The Center for New Music and Audio Technologies,
295 University of California, Berkeley.
296
297 IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
298 SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
299 ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
300 REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
301
302 REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
303 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
304 FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
305 DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS".
306 REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
307 ENHANCEMENTS, OR MODIFICATIONS.
308
309 The OpenSound Control WWW page is
310 http://www.cnmat.berkeley.edu/OpenSoundControl
311 */
312
313 /*
314 OSC_timeTag.c: library for manipulating OSC time tags
315 Matt Wright, 5/29/97
316
317 Version 0.2 (9/11/98): cleaned up so no explicit type names in the .c file.
318 */
319
320 //#include "OSC-timetag.h"
321
322
323 #ifdef HAS8BYTEINT
324 #define TWO_TO_THE_32_FLOAT 4294967296.0f
325
326 OSCTimeTag OSCTT_Immediately(void) {
327 return (OSCTimeTag) 1;
328 }
329
330 OSCTimeTag OSCTT_BiggestPossibleTimeTag(void) {
331 return (OSCTimeTag) 0xffffffffffffffff;
332 }
333
334 OSCTimeTag OSCTT_PlusSeconds(OSCTimeTag original, float secondsOffset) {
335 int64 offset = (int64) (secondsOffset * TWO_TO_THE_32_FLOAT);
336
337 /* printf("* OSCTT_PlusSeconds %llx plus %f seconds (i.e., %lld offset) is %llx\n", original,
338 secondsOffset, offset, original + offset); */
339
340 return original + offset;
341 }
342
343 int OSCTT_Compare(OSCTimeTag left, OSCTimeTag right)
344 {
345 #if 0
346 printf("***** OSCTT_Compare(%llx, %llx): %d\n", left, right,
347 (left<right) ? -1 : ((left == right) ? 0 : 1));
348 #endif
349 if(left < right) {
350 return -1;
351 } else if(left == right) {
352 return 0;
353 } else {
354 return 1;
355 }
356 }
357
358 #ifdef __sgi
359 #include <sys/time.h>
360
361 #define SECONDS_FROM_1900_to_1970 2208988800 /* 17 leap years */
362 #define TWO_TO_THE_32_OVER_ONE_MILLION 4295
363
364
365 OSCTimeTag OSCTT_CurrentTime(void) {
366 uint64 result;
367 uint32 usecOffset;
368 struct timeval tv;
369 struct timezone tz;
370
371 BSDgettimeofday(&tv, &tz);
372
373 /* First get the seconds right */
374 result = (unsigned) SECONDS_FROM_1900_to_1970 +
375 (unsigned) tv.tv_sec -
376 (unsigned) 60 * tz.tz_minuteswest +
377 (unsigned) (tz.tz_dsttime ? 3600 : 0);
378
379 #if 0
380 /* No timezone, no DST version ... */
381 result = (unsigned) SECONDS_FROM_1900_to_1970 +
382 (unsigned) tv.tv_sec;
383 #endif
384
385
386 /* make seconds the high-order 32 bits */
387 result = result << 32;
388
389 /* Now get the fractional part. */
390 usecOffset = (unsigned) tv.tv_usec * (unsigned) TWO_TO_THE_32_OVER_ONE_MILLION;
391 /* printf("** %ld microsec is offset %x\n", tv.tv_usec, usecOffset); */
392
393 result += usecOffset;
394
395 /* printf("* OSCTT_CurrentTime is %llx\n", result); */
396 return result;
397 }
398
399 #else /* __sgi */
400
401 /* Instead of asking your operating system what time it is, it might be
402 clever to find out the current time at the instant your application
403 starts audio processing, and then keep track of the number of samples
404 output to know how much time has passed. */
405
406 /* Loser version for systems that have no ability to tell the current time: */
407 OSCTimeTag OSCTT_CurrentTime(void) {
408 return (OSCTimeTag) 1;
409 }
410
411 #endif /* __sgi */
412
413
414 #else /* Not HAS8BYTEINT */
415
416 OSCTimeTag OSCTT_CurrentTime(void) {
417 OSCTimeTag result;
418 result.seconds = 0;
419 result.fraction = 1;
420 return result;
421 }
422
423 OSCTimeTag OSCTT_BiggestPossibleTimeTag(void) {
424 OSCTimeTag result;
425 result.seconds = 0xffffffff;
426 result.fraction = 0xffffffff;
427 return result;
428 }
429
430 OSCTimeTag OSCTT_Immediately(void) {
431 OSCTimeTag result;
432 result.seconds = 0;
433 result.fraction = 1;
434 return result;
435 }
436
437 OSCTimeTag OSCTT_PlusSeconds(OSCTimeTag original, float secondsOffset) {
438 OSCTimeTag result;
439 result.seconds = 0;
440 result.fraction = 1;
441 return result;
442 }
443
444 int OSCTT_Compare(OSCTimeTag left, OSCTimeTag right) {
445 /* Untested! */
446 int highResult = left.seconds - right.seconds;
447
448 if(highResult != 0) return highResult;
449
450 return left.fraction - right.fraction;
451 }
452
453
454 #endif /* HAS8BYTEINT */
455
456 // end OSC-timetag.cpp
457
458 // OSC-client.cpp
459
460 /*
461 Copyright (c) 1996. The Regents of the University of California (Regents).
462 All Rights Reserved.
463
464 Permission to use, copy, modify, and distribute this software and its
465 documentation for educational, research, and not-for-profit purposes, without
466 fee and without a signed licensing agreement, is hereby granted, provided that
467 the above copyright notice, this paragraph and the following two paragraphs
468 appear in all copies, modifications, and distributions. Contact The Office of
469 Technology Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley,
470 CA 94720-1620, (510) 643-7201, for commercial licensing opportunities.
471
472 Written by Matt Wright, The Center for New Music and Audio Technologies,
473 University of California, Berkeley.
474
475 IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
476 SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
477 ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
478 REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
479
480 REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
481 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
482 FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
483 DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS".
484 REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
485 ENHANCEMENTS, OR MODIFICATIONS.
486 */
487
488
489 /*
490 Author: Matt Wright
491 Version 2.2: Calls htonl in the right places 20000620
492 Version 2.3: Gets typed messages right.
493 */
494
495
496 /* Here are the possible values of the state field: */
497
498 #define EMPTY 0 /* Nothing written to packet yet */
499 #define ONE_MSG_ARGS 1 /* Packet has a single message; gathering arguments */
500 #define NEED_COUNT 2 /* Just opened a bundle; must write message name or
501 open another bundle */
502 #define GET_ARGS 3 /* Getting arguments to a message. If we see a message
503 name or a bundle open/close then the current message
504 will end. */
505 #define DONE 4 /* All open bundles have been closed, so can't write
506 anything else */
507
508
509 //#include "OSC-client.h"
510
511 const char * OSC_errorMessage;
512
513
514 //static int strlen(char *s);
515 static int OSC_padString(char *dest, const char *str);
516 static int OSC_padStringWithAnExtraStupidComma(char *dest, const char *str);
517 static int OSC_WritePadding(char *dest, int i);
518 static int CheckTypeTag(OSCbuf *buf, char expectedType);
519
520 void OSC_initBuffer(OSCbuf *buf, int size, char *byteArray) {
521 buf->buffer = byteArray;
522 buf->size = size;
523 OSC_resetBuffer(buf);
524 }
525
526 void OSC_resetBuffer(OSCbuf *buf) {
527 buf->bufptr = buf->buffer;
528 buf->state = EMPTY;
529 buf->bundleDepth = 0;
530 buf->prevCounts[0] = 0;
531 buf->gettingFirstUntypedArg = 0;
532 buf->typeStringPtr = 0;
533 }
534
535 int OSC_isBufferEmpty(OSCbuf *buf) {
536 return buf->bufptr == buf->buffer;
537 }
538
539 int OSC_freeSpaceInBuffer(OSCbuf *buf) {
540 return buf->size - (buf->bufptr - buf->buffer);
541 }
542
543 int OSC_isBufferDone(OSCbuf *buf) {
544 return (buf->state == DONE || buf->state == ONE_MSG_ARGS);
545 }
546
547 char *OSC_getPacket(OSCbuf *buf)
548 {
549 #ifdef ERROR_CHECK_GETPACKET
550 if(buf->state == DONE || buf->state == ONE_MSG_ARGS) {
551 return buf->buffer;
552 } else {
553 OSC_errorMessage = "Packet has unterminated bundles";
554 return 0;
555 }
556 #else
557 return buf->buffer;
558 #endif
559 }
560
561 int OSC_packetSize(OSCbuf *buf)
562 {
563 #ifdef ERROR_CHECK_PACKETSIZE
564 if(buf->state == DONE || buf->state == ONE_MSG_ARGS) {
565 return (buf->bufptr - buf->buffer);
566 } else {
567 OSC_errorMessage = "Packet has unterminated bundles";
568 return 0;
569 }
570 #else
571 return (buf->bufptr - buf->buffer);
572 #endif
573 }
574
575 #define CheckOverflow(buf, bytesNeeded) { \
576 if((bytesNeeded) > OSC_freeSpaceInBuffer(buf)) { \
577 OSC_errorMessage = "buffer overflow"; \
578 return 1; \
579 } \
580 }
581
582 static void PatchMessageSize(OSCbuf *buf)
583 {
584 int4byte size;
585 size = buf->bufptr - ((char *) buf->thisMsgSize) - 4;
586 *(buf->thisMsgSize) = htonl(size);
587 }
588
589 int OSC_openBundle(OSCbuf *buf, OSCTimeTag tt)
590 {
591 if(buf->state == ONE_MSG_ARGS) {
592 OSC_errorMessage = "Can't open a bundle in a one-message packet";
593 return 3;
594 }
595
596 if(buf->state == DONE) {
597 OSC_errorMessage = "This packet is finished; can't open a new bundle";
598 return 4;
599 }
600
601 if(++(buf->bundleDepth) >= MAX_BUNDLE_NESTING) {
602 OSC_errorMessage = "Bundles nested too deeply; change MAX_BUNDLE_NESTING in OpenSoundControl.h";
603 return 2;
604 }
605
606 if(CheckTypeTag(buf, '\0')) return 9;
607
608 if(buf->state == GET_ARGS) {
609 PatchMessageSize(buf);
610 }
611
612 if(buf->state == EMPTY) {
613 /* Need 16 bytes for "#bundle" and time tag */
614 CheckOverflow(buf, 16);
615 } else {
616 /* This bundle is inside another bundle, so we need to leave
617 a blank size count for the size of this current bundle. */
618 CheckOverflow(buf, 20);
619 *((int4byte *)buf->bufptr) = 0xaaaaaaaa;
620 buf->prevCounts[buf->bundleDepth] = (int4byte *)buf->bufptr;
621
622 buf->bufptr += 4;
623 }
624
625 buf->bufptr += OSC_padString(buf->bufptr, "#bundle");
626
627 *((OSCTimeTag *) buf->bufptr) = tt;
628
629 if(htonl(1) != 1)
630 {
631 /* Byte swap the 8-byte integer time tag */
632 int4byte *intp = (int4byte *)buf->bufptr;
633 intp[0] = htonl(intp[0]);
634 intp[1] = htonl(intp[1]);
635
636 #ifdef HAS8BYTEINT
637 { /* tt is a 64-bit int so we have to swap the two 32-bit words.
638 (Otherwise tt is a struct of two 32-bit words, and even though
639 each word was wrong-endian, they were in the right order
640 in the struct.) */
641 int4byte temp = intp[0];
642 intp[0] = intp[1];
643 intp[1] = temp;
644 }
645 #endif
646 }
647
648 buf->bufptr += sizeof(OSCTimeTag);
649
650 buf->state = NEED_COUNT;
651
652 buf->gettingFirstUntypedArg = 0;
653 buf->typeStringPtr = 0;
654 return 0;
655 }
656
657 int OSC_closeBundle(OSCbuf *buf)
658 {
659 if(buf->bundleDepth == 0) {
660 /* This handles EMPTY, ONE_MSG, ARGS, and DONE */
661 OSC_errorMessage = "Can't close bundle; no bundle is open!";
662 return 5;
663 }
664
665 if(CheckTypeTag(buf, '\0')) return 9;
666
667 if(buf->state == GET_ARGS) {
668 PatchMessageSize(buf);
669 }
670
671 if(buf->bundleDepth == 1) {
672 /* Closing the last bundle: No bundle size to patch */
673 buf->state = DONE;
674 } else {
675 /* Closing a sub-bundle: patch bundle size */
676 int size = buf->bufptr - ((char *) buf->prevCounts[buf->bundleDepth]) - 4;
677 *(buf->prevCounts[buf->bundleDepth]) = htonl(size);
678 buf->state = NEED_COUNT;
679 }
680
681 --buf->bundleDepth;
682 buf->gettingFirstUntypedArg = 0;
683 buf->typeStringPtr = 0;
684 return 0;
685 }
686
687
688 int OSC_closeAllBundles(OSCbuf *buf)
689 {
690 if(buf->bundleDepth == 0) {
691 /* This handles EMPTY, ONE_MSG, ARGS, and DONE */
692 OSC_errorMessage = "Can't close all bundles; no bundle is open!";
693 return 6;
694 }
695
696 if(CheckTypeTag(buf, '\0')) return 9;
697
698 while (buf->bundleDepth > 0) {
699 OSC_closeBundle(buf);
700 }
701
702 buf->typeStringPtr = 0;
703 return 0;
704 }
705
706 int OSC_writeAddress(OSCbuf *buf, char *name)
707 {
708 int4byte paddedLength;
709
710 if(buf->state == ONE_MSG_ARGS) {
711 OSC_errorMessage = "This packet is not a bundle, so you can't write another address";
712 return 7;
713 }
714
715 if(buf->state == DONE) {
716 OSC_errorMessage = "This packet is finished; can't write another address";
717 return 8;
718 }
719
720 if(CheckTypeTag(buf, '\0')) return 9;
721
722 paddedLength = OSC_effectiveStringLength(name);
723
724 if(buf->state == EMPTY) {
725 /* This will be a one-message packet, so no sizes to worry about */
726 CheckOverflow(buf, paddedLength);
727 buf->state = ONE_MSG_ARGS;
728 } else {
729 /* GET_ARGS or NEED_COUNT */
730 CheckOverflow(buf, 4+paddedLength);
731 if(buf->state == GET_ARGS) {
732 /* Close the old message */
733 PatchMessageSize(buf);
734 }
735 buf->thisMsgSize = (int4byte *)buf->bufptr;
736 *(buf->thisMsgSize) = 0xbbbbbbbb;
737 buf->bufptr += 4;
738 buf->state = GET_ARGS;
739 }
740
741 /* Now write the name */
742 buf->bufptr += OSC_padString(buf->bufptr, name);
743 buf->typeStringPtr = 0;
744 buf->gettingFirstUntypedArg = 1;
745
746 return 0;
747 }
748
749 int OSC_writeAddressAndTypes(OSCbuf *buf, char *name, char *types)
750 {
751 int result;
752 int4byte paddedLength;
753
754 if(CheckTypeTag(buf, '\0')) return 9;
755
756 result = OSC_writeAddress(buf, name);
757
758 if(result) return result;
759
760 paddedLength = OSC_effectiveStringLength(types);
761
762 CheckOverflow(buf, paddedLength);
763
764 buf->typeStringPtr = buf->bufptr + 1; /* skip comma */
765 buf->bufptr += OSC_padString(buf->bufptr, types);
766
767 buf->gettingFirstUntypedArg = 0;
768
769 return 0;
770 }
771
772 static int CheckTypeTag(OSCbuf *buf, char expectedType)
773 {
774 if(buf->typeStringPtr) {
775 if(*(buf->typeStringPtr) != expectedType) {
776 if(expectedType == '\0') {
777 OSC_errorMessage =
778 "According to the type tag I expected more arguments.";
779 } else if(*(buf->typeStringPtr) == '\0') {
780 OSC_errorMessage =
781 "According to the type tag I didn't expect any more arguments.";
782 } else {
783 OSC_errorMessage =
784 "According to the type tag I expected an argument of a different type.";
785 printf("* Expected %c, string now %s\n", expectedType, buf->typeStringPtr);
786 }
787
788 return 9;
789 }
790
791 ++(buf->typeStringPtr);
792 }
793
794 return 0;
795 }
796
797
798 int OSC_writeFloatArg(OSCbuf *buf, float arg)
799 {
800 int4byte *intp;
801
802 CheckOverflow(buf, 4);
803
804 if(CheckTypeTag(buf, 'f')) return 9;
805
806 /* Pretend arg is a long int so we can use htonl() */
807 intp = ((int4byte *) &arg);
808 *((int4byte *) buf->bufptr) = htonl(*intp);
809
810 buf->bufptr += 4;
811
812 buf->gettingFirstUntypedArg = 0;
813
814 return 0;
815 }
816
817
818 int OSC_writeFloatArgs(OSCbuf *buf, int numFloats, float *args)
819 {
820 int i;
821 int4byte *intp;
822
823 CheckOverflow(buf, 4 * numFloats);
824
825 /* Pretend args are long ints so we can use htonl() */
826 intp = ((int4byte *) args);
827
828 for(i = 0; i < numFloats; i++) {
829 if(CheckTypeTag(buf, 'f')) return 9;
830 *((int4byte *) buf->bufptr) = htonl(intp[i]);
831 buf->bufptr += 4;
832 }
833
834 buf->gettingFirstUntypedArg = 0;
835
836 return 0;
837 }
838
839
840 int OSC_writeIntArg(OSCbuf *buf, int4byte arg)
841 {
842 CheckOverflow(buf, 4);
843 if(CheckTypeTag(buf, 'i')) return 9;
844
845 *((int4byte *) buf->bufptr) = htonl(arg);
846 buf->bufptr += 4;
847
848 buf->gettingFirstUntypedArg = 0;
849 return 0;
850 }
851
852
853 int OSC_writeStringArg(OSCbuf *buf, char *arg)
854 {
855 int len;
856
857 if(CheckTypeTag(buf, 's')) return 9;
858
859 len = OSC_effectiveStringLength(arg);
860
861 if(buf->gettingFirstUntypedArg && arg[0] == ',') {
862 /* This un-type-tagged message starts with a string
863 that starts with a comma, so we have to escape it
864 (with a double comma) so it won't look like a type
865 tag string. */
866
867 CheckOverflow(buf, len+4); /* Too conservative */
868 buf->bufptr +=
869 OSC_padStringWithAnExtraStupidComma(buf->bufptr, arg);
870 } else {
871 CheckOverflow(buf, len);
872 buf->bufptr += OSC_padString(buf->bufptr, arg);
873 }
874
875 buf->gettingFirstUntypedArg = 0;
876
877 return 0;
878 }
879
880
881 /* String utilities */
882 /*
883 static int strlen(char *s) {
884 int i;
885 for(i=0; s[i] != '\0'; i++);
886 return i;
887 }
888 */
889
890 #define STRING_ALIGN_PAD 4
891 int OSC_effectiveStringLength(char *string)
892 {
893 t_CKINT len = strlen(string) + 1; /* We need space for the null char. */
894
895 /* Round up len to next multiple of STRING_ALIGN_PAD to account for alignment padding */
896 if((len % STRING_ALIGN_PAD) != 0) {
897 len += STRING_ALIGN_PAD - (len % STRING_ALIGN_PAD);
898 }
899
900 return len;
901 }
902
903
904 static int OSC_padString(char *dest, const char *str)
905 {
906 int i;
907
908 for(i = 0; str[i] != '\0'; i++) {
909 dest[i] = str[i];
910 }
911
912 return OSC_WritePadding(dest, i);
913 }
914
915
916 static int OSC_padStringWithAnExtraStupidComma(char *dest, const char *str)
917 {
918 int i;
919
920 dest[0] = ',';
921 for(i = 0; str[i] != '\0'; i++) {
922 dest[i+1] = str[i];
923 }
924
925 return OSC_WritePadding(dest, i+1);
926 }
927
928
929 static int OSC_WritePadding(char *dest, int i)
930 {
931 dest[i] = '\0';
932 i++;
933
934 for(; (i % STRING_ALIGN_PAD) != 0; i++) {
935 dest[i] = '\0';
936 }
937
938 return i;
939 }
940
941
942 // end OSC-client.cpp
943
944
945
946 // ACTUAL CODE
947
948 /*
949 //chuck networking code
950 #include "util_network.h"
951 #include "util_thread.h"
952
953 // FROM PLATFORM.H -UDP TRANSMITTER / RECEIVER
954
955 #if defined(__PLATFORM_WINDOWS__)
956 #include <winsock2.h> // changed to winsock2.h | 1.5.5.2 (ge)
957 #else
958 #include <sys/types.h>
959 #include <sys/socket.h>
960 #include <sys/time.h>
961 #include <unistd.h>
962 #include <netinet/in.h>
963 #include <netinet/tcp.h>
964 #include <arpa/inet.h>
965 #include <netdb.h>
966 #endif
967
968 #ifdef __PLATFORM_APPLE__
969 #define SOCKET int
970 #define SOCKADDR_IN struct sockaddr_in
971 #endif
972 */
973 #include "stdarg.h"
974
975 enum udp_stat { UDP_NOINIT, UDP_UNBOUND, UDP_BOUND, UDP_READY, UDP_ERROR, UDP_NUM };
976
977
978 /* in the .h so that OSC can subclass it
979
980 class UDP_Subscriber {
981 virtual void onRecieve( char * mesg, int mesgLen ) = 0;
982 virtual bool subscribe( int port );
983 virtual bool unsubscribe();
984 virtual int& port(); //get/set the value of the subscriber's current port.
985 }
986
987 */
988
989 class DefUDP_Subscriber : public UDP_Subscriber {
990 public:
991 int _port;
992 void onReceive ( char * mesg, int mesgLen ) {} // ignore
993 int& port() { return _port; }
994 };
995
996 class UDP_Port_Listener {
997 private:
998 UDP_Receiver* m_in;
999 bool m_port;
1000
1001 XThread* m_thread;
1002 XMutex* m_mutex;
1003
1004 char m_inbuf[OSCINBUFSIZE];
1005 int m_inbufsize;
1006
1007 vector < UDP_Subscriber * > m_subscribers;
1008 queue < UDP_Subscriber * > m_free;
1009
1010 public:
1011 UDP_Port_Listener( int port );
1012 ~UDP_Port_Listener();
1013 void init();
1014 bool bind_to_port(int port);
1015 void close();
1016 bool listen();
1017 int recv_mesg();
1018 bool add ( UDP_Subscriber * );
1019 bool drop ( UDP_Subscriber * );
1020 int nsubs();
1021
1022 bool listening;
1023 };
1024
1025
1026
1027
1028 class UDP_Port_Manager
1029 {
1030 private:
1031 static UDP_Port_Manager * _inst;
1032 map<int, UDP_Port_Listener *> _listeners;
1033
1034 public:
1035 static UDP_Port_Manager * instance();
1036 UDP_Port_Manager();
1037 void init();
1038 bool subscribe ( UDP_Subscriber * sub, int port );
1039 bool unsubscribe ( UDP_Subscriber * sub );
1040 };
1041
1042
1043
1044
1045 class UDP_Receiver
1046 {
1047 protected:
1048 ck_socket _sock;
1049 udp_stat _status;
1050
1051 SOCKADDR_IN _remote_addr;
1052 int _remote_addr_len;
1053 int _mesgLen;
1054
1055 public:
1056 UDP_Receiver();
1057 ~UDP_Receiver() { }
1058 void init();
1059 bool bind_to_port(int port);
1060 int recv_next(char *buffer, int size);
1061 void close_sock();
1062 udp_stat status();
1063 };
1064
1065
1066
1067
1068 class UDP_Transmitter
1069 {
1070 protected:
1071 ck_socket _sock;
1072 SOCKADDR_IN _host_addr;
1073 udp_stat _status;
1074
1075 public:
1076 UDP_Transmitter() {
1077 _status = UDP_NOINIT;
1078 }
1079 virtual ~UDP_Transmitter() {}
1080 void init();
1081
1082 void set_host(char * hostaddress, int port);
1083 int send(char *buffer, int size);
1084 udp_stat status(void) { return _status; }
1085 void close_sock();
1086 };
1087
1088
1089 UDP_Port_Manager * UDP_Port_Manager::_inst = NULL;
1090 UDP_Port_Manager * UDP_Port_Manager::instance()
1091 {
1092 if( _inst == NULL )
1093 {
1094 _inst = new UDP_Port_Manager();
1095 assert( _inst );
1096 }
1097
1098 return _inst;
1099 }
1100
1101 UDP_Port_Manager::UDP_Port_Manager() {
1102 init();
1103 }
1104
1105 void
1106 UDP_Port_Manager::init() {
1107 _listeners.clear();
1108 }
1109
1110 bool UDP_Port_Manager::subscribe ( UDP_Subscriber * sub, int port )
1111 {
1112 if( _listeners.count( port ) == 0 )
1113 {
1114 EM_log(CK_LOG_INFO, "PortManager: starting Listener on %d", port );
1115 _listeners[port] = new UDP_Port_Listener( port ); //make a new listener on this port
1116 }
1117
1118 return _listeners[port]->add( sub );
1119 }
1120
1121 bool UDP_Port_Manager::unsubscribe( UDP_Subscriber * sub )
1122 {
1123 if( sub->port() < 0 )
1124 {
1125 EM_log( CK_LOG_INFO, "error, subscriber's port < 0, return false" );
1126 return false;
1127 }
1128
1129 if( _listeners.count( sub->port() ) == 0 )
1130 {
1131 EM_log( CK_LOG_INFO, "error, cannot unsubscribe: port %d not in use", sub->port() );
1132 return false;
1133 }
1134 else
1135 {
1136 int pp = sub->port();
1137 UDP_Port_Listener * listener = _listeners[pp];
1138 bool ret = listener->drop( sub );
1139 //check empty
1140 if( listener->nsubs() == 0 ) {
1141 EM_log( CK_LOG_INFO, "PortManager: Listener on port %d is empty - removing", sub->port() );
1142 delete listener;
1143 _listeners.erase( pp );
1144 }
1145 return ret;
1146 }
1147 }
1148
1149 UDP_Port_Listener::UDP_Port_Listener( int port )
1150 : m_inbufsize( OSCINBUFSIZE ), listening( false )
1151 {
1152 init();
1153 m_in->bind_to_port( port );
1154 listen();
1155 }
1156
1157 UDP_Port_Listener::~UDP_Port_Listener()
1158 {
1159 //CK_FPRINTF_STDERR( "port listener destructor\n" );
1160 close();
1161 // ck_usleep( 10 ); // do we need this ?
1162 delete m_in;
1163 delete m_mutex;
1164 delete m_thread;
1165 }
1166
1167 void UDP_Port_Listener::init()
1168 {
1169 memset( (void*)m_inbuf, '\0', m_inbufsize * sizeof(char) );
1170 m_thread = new XThread();
1171 m_mutex = new XMutex();
1172 m_in = new UDP_Receiver();
1173 m_in->init();
1174 }
1175
1176 int UDP_Port_Listener::nsubs() { return (int)m_subscribers.size(); }
1177
1178 bool UDP_Port_Listener::add( UDP_Subscriber * sub )
1179 {
1180 m_mutex->acquire();
1181 if( find( m_subscribers.begin(), m_subscribers.end(), sub ) == m_subscribers.end() )
1182 {
1183 EM_log(CK_LOG_INFO, "UDP_Port_Listener: adding subscriber" );
1184 m_subscribers.push_back( sub );
1185 sub->port() = m_port;
1186 m_mutex->release();
1187 return true;
1188 }
1189 else
1190 {
1191 EM_log(CK_LOG_INFO, "UDP_Port_Listener: add - error subscriber already exists" );
1192 m_mutex->release();
1193 return false;
1194 }
1195 }
1196
1197
1198 bool UDP_Port_Listener::drop( UDP_Subscriber * sub )
1199 {
1200 // lock
1201 m_mutex->acquire();
1202 // find
1203 vector < UDP_Subscriber * >::iterator m_iter = find( m_subscribers.begin(), m_subscribers.end(), sub );
1204 // check
1205 if( m_iter != m_subscribers.end() )
1206 {
1207 EM_log(CK_LOG_INFO, "UDP_Port_Listener: dropping subscriber" );
1208 m_subscribers.erase( m_iter );
1209 sub->port() = -1;
1210 // unlock
1211 m_mutex->release();
1212 return true;
1213 }
1214 else
1215 {
1216 EM_log(CK_LOG_INFO, "UDP_Port_Listener: add - error subscriber already exists" );
1217 // unlock
1218 m_mutex->release();
1219 return false;
1220 }
1221 }
1222
1223
1224 THREAD_RETURN (THREAD_TYPE udp_port_listener_thread)( void * data )
1225 {
1226 UDP_Port_Listener * upl = (UDP_Port_Listener *) data;
1227
1228 // priority boost
1229 if( XThreadUtil::our_priority != 0x7fffffff )
1230 XThreadUtil::set_priority( XThreadUtil::our_priority );
1231
1232 EM_log( CK_LOG_INFO, "UDP_Port_Listener:: starting receive loop...\n" );
1233 int mLen;
1234 do {
1235 mLen = upl->recv_mesg();
1236 ck_usleep( 10 );
1237 } while( mLen != 0 );
1238
1239 EM_log( CK_LOG_INFO, "UDP_Port_Listener:: receive loop terminated...\n" );
1240
1241 return (THREAD_RETURN)0;
1242 }
1243
1244
1245
1246 // returns whether an attempt to start the listening thread was made
1247 bool UDP_Port_Listener::listen()
1248 {
1249 if( !listening && m_in->status() != UDP_ERROR )
1250 {
1251 listening = true;
1252 m_thread->start( udp_port_listener_thread, (void*) this );
1253 return true;
1254 }
1255
1256 return false;
1257 }
1258
1259 bool UDP_Port_Listener::bind_to_port( int port )
1260 {
1261 return m_in->bind_to_port( port );
1262 }
1263
1264 void UDP_Port_Listener::close()
1265 {
1266 if( m_in->status() == UDP_BOUND )
1267 {
1268 listening = false;
1269 m_in->close_sock();
1270 }
1271 }
1272
1273 int UDP_Port_Listener::recv_mesg()
1274 {
1275 int mLen = m_in->recv_next( m_inbuf, m_inbufsize );
1276
1277 if( mLen == 0 )
1278 {
1279 EM_log( CK_LOG_INFO, "recvLen 0 on socket, returning 0" );
1280 return 0;
1281 }
1282
1283 m_mutex->acquire();
1284 vector<UDP_Subscriber *>::size_type i;
1285 for( i = 0 ; i < m_subscribers.size(); i++ )
1286 {
1287 m_subscribers[i]->onReceive( m_inbuf, mLen );
1288 }
1289 m_mutex->release();
1290
1291 return mLen;
1292 }
1293
1294
1295 // UDP_Subscriber
1296 bool UDP_Subscriber::subscribe( int p )
1297 {
1298 if( port() >= 0 )
1299 {
1300 return false; // already subscribed
1301 }
1302 else if( UDP_Port_Manager::instance()->subscribe( this, p ) )
1303 {
1304 port() = p;
1305 return true;
1306 }
1307 else
1308 {
1309 port() = -1;
1310 return false;
1311 }
1312 }
1313
1314 bool UDP_Subscriber::unsubscribe()
1315 {
1316 if( port() < 0 )
1317 {
1318 return false; // currently unsubscribed
1319 }
1320 else if( UDP_Port_Manager::instance()->unsubscribe( this ) )
1321 {
1322 port() = -1;
1323 return true;
1324 }
1325 else
1326 {
1327 return false; // could not unsubscribe?
1328 }
1329 }
1330
1331
1332
1333 UDP_Receiver::UDP_Receiver()
1334 {
1335 _status = UDP_NOINIT;
1336 }
1337
1338
1339 void UDP_Receiver::init()
1340 {
1341 //open port
1342 _sock = ck_udp_create();
1343 _status = ( _sock != NULL ) ? UDP_UNBOUND : UDP_ERROR;
1344 }
1345
1346 bool UDP_Receiver::bind_to_port(int port)
1347 {
1348 // fill in the interface information
1349 _status = ( ck_bind ( _sock, port ) ) ? UDP_BOUND : UDP_ERROR;
1350 // check status
1351 if( _status == UDP_ERROR )
1352 {
1353 EM_log( CK_LOG_SYSTEM, "(via OSC): cannot bind to port %d!", port);
1354 return false;
1355 }
1356
1357 return true;
1358 }
1359
1360 udp_stat UDP_Receiver::status() { return _status; }
1361
1362 int UDP_Receiver::recv_next(char * buffer, int bsize)
1363 {
1364 if( _status != UDP_BOUND )
1365 {
1366 EM_log( CK_LOG_SYSTEM, "(via OSC): recv -> socket not bound!"); return 0;
1367 }
1368
1369 _remote_addr_len = sizeof(_remote_addr);
1370 int ret = ck_recvfrom(_sock, buffer, bsize, (struct sockaddr *) &_remote_addr, &_remote_addr_len );
1371
1372 return ( ret <= 0 ) ? 0 : ret;
1373 }
1374
1375
1376 void UDP_Receiver::close_sock()
1377 {
1378 ck_close ( _sock );
1379 _status = UDP_NOINIT;
1380 }
1381
1382
1383 void UDP_Transmitter::init()
1384 {
1385 //open socket
1386 _sock = ck_udp_create();
1387 _status = ( _sock != NULL ) ? UDP_READY : UDP_ERROR;
1388 }
1389
1390
1391 void UDP_Transmitter::set_host( char * hostaddress, int port )
1392 {
1393 // fill in the interface information
1394 struct hostent * host;
1395 // printf( "gathering host information..." );
1396 _host_addr.sin_family = AF_INET;
1397 _host_addr.sin_port = htons(port);
1398 _host_addr.sin_addr.s_addr = inet_addr(hostaddress);
1399
1400 if( _host_addr.sin_addr.s_addr == INADDR_NONE ) // the address wasn't in numeric
1401 {
1402 host = NULL;
1403 host = gethostbyname(hostaddress); // get the IP address of the server
1404 if(host == NULL)
1405 {
1406 CK_FPRINTF_STDERR( "[chuck](via OSC): UDP_Transmitter: unknown host: %s\n", hostaddress);
1407 _status = UDP_ERROR;
1408 return;
1409 }
1410 memcpy(&_host_addr.sin_addr, host->h_addr_list[0], host->h_length);
1411 // printf(" ...set\n");
1412 }
1413 // else printf(" ...set\n");
1414 _status = UDP_READY;
1415 }
1416
1417
1418 int UDP_Transmitter::send( char * buffer, int bsize )
1419 {
1420 if( _status != UDP_READY )
1421 {
1422 EM_log( CK_LOG_SYSTEM, "(via OSC): send -> socket not bound!");
1423 return 0;
1424 }
1425 int ret = ck_sendto(_sock, buffer, bsize, (struct sockaddr *) &_host_addr, sizeof(_host_addr) );
1426 return ( ret <= 0 ) ? 0 : ret ;
1427 }
1428
1429
1430 void UDP_Transmitter::close_sock()
1431 {
1432 ck_close( _sock );
1433 }
1434
1435
1436 // OSC_TRANSMITTER
1437
1438 OSC_Transmitter::OSC_Transmitter() {
1439 _out = new UDP_Transmitter();
1440 _holdMessage = false;
1441 init();
1442 }
1443
1444 OSC_Transmitter::OSC_Transmitter( UDP_Transmitter * out ) {
1445 _out = out;
1446 _holdMessage = false;
1447 }
1448
1449 OSC_Transmitter::~OSC_Transmitter() { delete _out; }
1450
1451 void
1452 OSC_Transmitter::init() {
1453 if( _out->status() == UDP_NOINIT ) _out->init();
1454 OSC_initBuffer(&_osc, sizeof(_buffer), _buffer );
1455 }
1456
1457 void
1458 OSC_Transmitter::setHost( char * hadd, int p ) {
1459 _out->set_host(hadd, p);
1460 }
1461
1462 void
1463 OSC_Transmitter::presend( char * buf, int sz ) {
1464 _out->send(buf,sz);
1465 }
1466
1467 void
1468 OSC_Transmitter::openBundle( OSCTimeTag t) {
1469 OSC_openBundle( &_osc, t);
1470 }
1471
1472
1473 void
1474 OSC_Transmitter::closeBundle() {
1475 OSC_closeBundle( &_osc );
1476 tryMessage();
1477 }
1478
1479
1480 void
1481 OSC_Transmitter::addMessage( char *address, char * args, ...)
1482 {
1483 if( args == NULL || args[0] == '\0' ) { // if there's no text
1484 OSC_writeAddress( &_osc, address ); // nothing
1485 return;
1486 }
1487
1488 va_list tags; // pointer to list of arguments
1489 va_start(tags, args); // parses the string for variables
1490
1491 OSC_writeAddressAndTypes( &_osc, address, args );
1492
1493 t_CKINT argnum = strlen(args);
1494 t_CKINT osc_err = 0;
1495 for(t_CKINT j = 1; !osc_err && j < argnum; j++ ) {
1496 switch ( args[j] ) {
1497 case 'i':
1498 osc_err = OSC_writeIntArg ( &_osc, va_arg(tags, int) );
1499 break;
1500 case 'f':
1501 osc_err = OSC_writeFloatArg ( &_osc, va_arg(tags, double) );
1502 break;
1503 case 's':
1504 osc_err = OSC_writeStringArg ( &_osc, va_arg(tags, char *) );
1505 break;
1506 }
1507 }
1508
1509 if( osc_err ) {
1510 EM_log( CK_LOG_SYSTEM, "(via OSC): error writing packet: %d %s...", osc_err, OSC_errorMessage );
1511 // failure action???
1512 }
1513
1514 va_end(tags); // Results Are Stored In Text
1515 tryMessage();
1516 }
1517
1518 void
1519 OSC_Transmitter::startMessage( char * spec ) {
1520
1521 t_CKINT len = strlen( spec );
1522
1523 char * comma = strchr( spec, ',');
1524 char * space = strchr ( spec, ' ');
1525 int coff = ( comma == NULL ) ? len : comma - spec;
1526 int spoff = ( space == NULL ) ? len : space - spec;
1527 int off = min ( coff, spoff );
1528
1529 if( off < len )
1530 spec[off] = '\0';
1531
1532 startMessage( spec, spec + off + 1 );
1533 }
1534
1535 void
1536 OSC_Transmitter::startMessage( char * address, char * args )
1537 {
1538 // OSC_writeAddressAndTypes( &_osc, address, args );
1539 char addrfix[512];
1540 t_CKINT addrlen = strlen( address );
1541 // int mx = strlen(address) + strlen(args) + 1; // either we need to add a comma to args,
1542 // or it's got junk in it.
1543 // char addrfix[] = new char[mx]; // (char*) malloc( mx * sizeof( char ) );
1544 strcpy ( addrfix, address );
1545 addrfix[addrlen] = '\0';
1546 addrfix[addrlen+1] = ',';
1547 char * argptr = addrfix + (addrlen + 2);
1548 char * p_args = args;
1549 while ( *p_args != '\0' ) {
1550 if( *p_args != ',' && *p_args != ' ' ) {
1551 *argptr = *p_args;
1552 argptr++;
1553 }
1554 p_args++;
1555 }
1556 *argptr = '\0';
1557
1558 OSC_writeAddressAndTypes( &_osc, addrfix, addrfix + addrlen + 1); //expects the ',' before spec tag.
1559 // delete[] addrfix;
1560 //free ( (void*)addrfix );
1561 tryMessage();
1562 }
1563
1564 void
1565 OSC_Transmitter::addInt ( int4byte i ) {
1566 int osc_err = OSC_writeIntArg ( &_osc, i );
1567 if( osc_err ) {
1568 CK_FPRINTF_STDERR( "[chuck](via OSC): error writing packet: %d %s\n", osc_err, OSC_errorMessage );
1569 //failure action???
1570 }
1571 tryMessage();
1572 }
1573
1574 void
1575 OSC_Transmitter::addFloat ( float f ) {
1576 int osc_err = OSC_writeFloatArg ( &_osc, f );
1577 if( osc_err ) {
1578 CK_FPRINTF_STDERR( "[chuck](via OSC): error writing packet: %d %s\n", osc_err, OSC_errorMessage );
1579 //failure action???
1580 }
1581 tryMessage();
1582 }
1583
1584 void
1585 OSC_Transmitter::addString ( char * s ) {
1586 int osc_err = OSC_writeStringArg ( &_osc, s );
1587 if( osc_err ) {
1588 CK_FPRINTF_STDERR( "[chuck](via OSC): error writing packet: %d %s\n", osc_err, OSC_errorMessage );
1589 //failure action???
1590 }
1591 tryMessage();
1592 }
1593
1594 bool
1595 OSC_Transmitter::packetReady() {
1596 if( _holdMessage ) return false; //message hold is on
1597 if( _osc.typeStringPtr ) { //if it's been typed, check that type is complete
1598 if( CheckTypeTag(&_osc, '\0' ) ) return false;
1599 }
1600 return ( OSC_isBufferDone(&_osc) != 0 );
1601 }
1602
1603 void
1604 OSC_Transmitter::tryMessage() {
1605 if( !packetReady() ) return;
1606
1607 _out->send( OSC_getPacket(&_osc), OSC_packetSize(&_osc) );
1608 OSC_resetBuffer(&_osc);
1609 }
1610
1611 void
1612 OSC_Transmitter::holdMessage(bool b) {
1613 _holdMessage = b;
1614 }
1615
1616 void
1617 OSC_Transmitter::kickMessage() {
1618 if( !OSC_isBufferDone(&_osc) ) {
1619 CK_FPRINTF_STDERR( "[chuck](via OSC): error -> sending incomplete packet!\n" );
1620 }
1621 _out->send( OSC_getPacket(&_osc), OSC_packetSize(&_osc) );
1622 OSC_resetBuffer(&_osc);
1623 }
1624
1625
1626 // OSC_RECEIVER
1627
1628 OSC_Receiver::OSC_Receiver( Chuck_VM * vm ):
1629 // _listening(false),
1630 // _inbufsize(OSCINBUFSIZE),
1631 _port(-1),
1632 _tmp_port(-1),
1633 _io_mutex(NULL),
1634 _address_mutex(NULL),
1635 _inbox(NULL),
1636 _inbox_size(2),
1637 _started(false),
1638 _in_read(0),
1639 _in_write(1),
1640 _address_space(NULL),
1641 _address_size(2),
1642 _address_num(0),
1643 m_event_buffer(NULL)
1644 {
1645 // store vm ref
1646 m_vmRef = vm;
1647 // allocate inbox
1648 _inbox = (OSCMesg *)malloc( sizeof(OSCMesg) * _inbox_size );
1649 // initialize payload
1650 for( int i = 0; i < _inbox_size; i++ )
1651 _inbox[i].payload = NULL;
1652
1653 // allocate address space
1654 _address_space = (OSC_Address_Space **)realloc( _address_space, _address_size * sizeof(OSC_Address_Space *) );
1655
1656 _io_mutex = new XMutex();
1657 _address_mutex = new XMutex();
1658 // _io_thread = new XThread();
1659
1660 //_in = new UDP_Receiver();
1661
1662 init();
1663 }
1664
1665 OSC_Receiver::OSC_Receiver( Chuck_VM * vm, UDP_Receiver * in )
1666 {
1667 // _in = in;
1668 _port = -1;
1669 // store vm ref
1670 m_vmRef = vm;
1671 }
1672
1673 void OSC_Receiver::init()
1674 {
1675 _port = -1;
1676 // _in->init();
1677 }
1678
1679 OSC_Receiver::~OSC_Receiver()
1680 {
1681 // stop
1682 stopListening();
1683 // clean up
1684 for( int i = 0; i < _inbox_size; i++ )
1685 {
1686 // check
1687 if( _inbox[i].payload )
1688 {
1689 free( _inbox[i].payload );
1690 _inbox[i].payload = NULL;
1691 }
1692 }
1693
1694 // 1.3.1.1: moving this outside the loop, oops
1695 free( _inbox );
1696
1697 // clean up
1698 CK_SAFE_DELETE( _io_mutex );
1699 CK_SAFE_DELETE( _address_mutex );
1700
1701 // TODO: do this thread-safely
1702 // if( m_event_buffer )
1703 // {
1704 // m_vmRef->destroy_event_buffer( m_event_buffer );
1705 // m_event_buffer = NULL;
1706 // }
1707
1708 // delete _in;
1709 }
1710
1711 THREAD_RETURN (THREAD_TYPE osc_recv_thread)( void * data )
1712 {
1713 OSC_Receiver * oscar = (OSC_Receiver * )data;
1714
1715 // priority boost
1716 if( XThreadUtil::our_priority != 0x7fffffff )
1717 XThreadUtil::set_priority( XThreadUtil::our_priority );
1718
1719 do {
1720 oscar->recv_mesg();
1721 ck_usleep( 10 );
1722 }while( true );
1723
1724 return (THREAD_RETURN)0;
1725 }
1726
1727
1728 int&
1729 OSC_Receiver::port() { return _port; }
1730
1731 void
1732 OSC_Receiver::onReceive( char * mesg, int mesgLen ) {
1733 handle_mesg( mesg, mesgLen );
1734 }
1735
1736 void
1737 OSC_Receiver::bind_to_port(int port ) {
1738 _tmp_port = port;
1739 // _in->bind_to_port(port);
1740 }
1741
1742 bool
1743 OSC_Receiver::listen( int port ) {
1744 bind_to_port ( port );
1745 return listen();
1746 }
1747
1748 void
1749 OSC_Receiver::stopListening()
1750 {
1751 unsubscribe();
1752 }
1753
1754 bool
1755 OSC_Receiver::listen()
1756 {
1757 if( m_event_buffer == NULL )
1758 m_event_buffer = m_vmRef->create_event_buffer();
1759
1760 unsubscribe(); // in case we're connected.
1761
1762 return subscribe( _tmp_port );
1763
1764 /*
1765 if( !_listening ) {
1766 _listening = true;
1767 _io_thread->start( osc_recv_thread, (void*)this );
1768 }
1769 return _listening;
1770 */
1771 }
1772
1773
1774
1775 void
1776 OSC_Receiver::close_sock() {
1777 unsubscribe();
1778 // _in->close_sock();
1779 }
1780
1781 void
1782 OSC_Receiver::recv_mesg() {
1783 // this is when OSC_Receiver was
1784 // used as the port-manager. now this code ( and callback ) are in UDP_Port_Listener interface,
1785 // which OSC_Receiver subclasses
1786
1787 /*
1788 _mesglen = _in->recv_next( _inbuf, _inbufsize );
1789 if( _mesglen > 0 ) {
1790 //parse();
1791 handle_mesg(_inbuf, _mesglen);
1792 }
1793 */
1794 }
1795
1796
1797 bool OSC_Receiver::has_mesg()
1798 {
1799 // EM_log( CK_LOG_FINER, "OSC has message?" );
1800 return ( _started && ( _in_read+1 ) % _inbox_size != _in_write );
1801 }
1802
1803 bool OSC_Receiver::get_mesg( OSCMesg * bucket )
1804 {
1805 _io_mutex->acquire();
1806
1807 if( has_mesg() )
1808 {
1809 // next write _may_ fuck with _in_read
1810 // where when resizing the buffer...
1811 *bucket = *next_read();
1812 // CK_FPRINTF_STDERR( "r" ); //read: %d of %d \n", _in_read, _inbox_size);
1813 _io_mutex->release();
1814 return true;
1815 }
1816
1817 _io_mutex->release();
1818
1819 return false;
1820 }
1821
1822 void OSC_Receiver::parse( char * mesg, int mesgLen )
1823 {
1824 // unpack bundles, dump all messages
1825 // any local prep we need here?
1826
1827 long i = 0;
1828
1829 // log
1830 EM_log( CK_LOG_FINER, "OSC_Receiver: print message length %d", mesgLen );
1831
1832 for( i = 0 ; i < mesgLen; i++ )
1833 {
1834 CK_FPRINTF_STDERR( "\t%c(%0x):", mesg[i], mesg[i] );
1835 }
1836
1837 CK_FPRINTF_STDERR( "\n" );
1838 }
1839
1840 void
1841 OSC_Receiver::next_write()
1842 {
1843 // called by the UDP client ( blocks )
1844
1845 if( !_started ) {
1846 _started = true;
1847 }
1848
1849 int next = (_in_write+1) % _inbox_size;
1850
1851 if( next == _in_read ) {
1852
1853 // CK_FPRINTF_STDERR( "OSC::need to resize..." );
1854
1855 _io_mutex->acquire(); //don't let next read return a bogus pointer
1856
1857 if( _inbox_size < OSCINBOXMAX) {
1858
1859 // LOCK MUTEX (on next_read)
1860 // prevents
1861
1862 // mesgs might move around, but their data doesn't..(this is good)..
1863 // if we return an OSCmesg* to an out-of-thread function, it can expire.
1864 // so we pass in pointer to our own mesg from outside (get_mesg) and copy
1865 // from the current 'read' in the buffer...buffer may then be resized...
1866 // since data buffers do not move, we remain okay.
1867
1868 // perhaps a monolithic chunk of memory is a better option...
1869 // but what if we want to handle multiple messages at once?
1870
1871 // orrr..if we follow timetags and need semirandom access to
1872 // mesg contents for scheduling bundles..hmm.
1873
1874 // make a separate case for scheduled messages...
1875 // throw them into a heap...
1876
1877 // fuck...back to the todo...
1878
1879 int new_size = ( _inbox_size * 2 > OSCINBOXMAX ) ? OSCINBOXMAX : _inbox_size * 2 ;
1880
1881 bool err = false;
1882
1883 // okay. read and write may be anywhere.
1884 if( _in_write > _in_read ) {
1885 // easy case
1886 _inbox = (OSCMesg* ) realloc ((void*)_inbox, new_size * sizeof(*_inbox) );
1887 err = (!_inbox);
1888 // indices are still valid
1889 }
1890 else {
1891 // write is behind read in the buffer
1892 // copy into buffer so that contents remain contiguous
1893 // note:: copy the buffers between write and read...
1894 // they may have valid packet pointers.......
1895
1896 OSCMesg * new_inbox =(OSCMesg*)malloc ( new_size * sizeof(*new_inbox) );
1897 err = (!new_inbox);
1898
1899 if( !err ) {
1900 int _read_tail = _inbox_size - _in_read;
1901 memcpy( (void*)new_inbox, (void*)(_inbox+_in_read), (_read_tail) * sizeof(*_inbox) );
1902 memcpy( (void*)(new_inbox+_read_tail), (void*)_inbox, (_in_read ) * sizeof(*_inbox) );
1903
1904 // update indices
1905 _in_read = 0;
1906 _in_write = (_in_write + _read_tail);
1907
1908 free ( _inbox );
1909 _inbox = new_inbox;
1910 }
1911
1912 else err = true;
1913 }
1914
1915
1916 if( !err ) {
1917 // new inbox elements need their payload pointers init to NULL
1918 for( int i = _inbox_size; i < new_size; i++ ) _inbox[i].payload = NULL;
1919 }
1920 else {
1921 // CK_FPRINTF_STDERR( "oh no!! buffer reallocation error!\n" );
1922 exit(0);
1923 }
1924
1925 next = (_in_write+1)%new_size; //where we're headed..
1926 _inbox_size = new_size;
1927
1928 // CK_FPRINTF_STDERR( "(%d)", _inbox_size );
1929 // UNLOCK MUTEX
1930 }
1931 else {
1932 // CK_FPRINTF_STDERR( "max buffer...dropping old mesg %d\n", next );
1933 _in_read = (next+1)%_inbox_size;
1934 }
1935
1936 _io_mutex->release();
1937 }
1938
1939 _in_write = next;
1940 }
1941
1942
1943 OSCMesg*
1944 OSC_Receiver::next_read() {
1945 int next = ( _in_read + 1 ) % _inbox_size;
1946 if( next == _in_write ) return NULL; // can't intrude on write
1947
1948 _in_read = next; //advance
1949 OSCMesg* ret= _inbox + _in_read; // return this pointer
1950 return ret;
1951 }
1952
1953 void
1954 OSC_Receiver::set_mesg(OSCMesg* mrp, char * buf, int len ) {
1955
1956 // put pointers in the appropriate places
1957 // this means that mrp has no idea whether
1958 // its pointers refer to its own payload
1959 // or to an external buffer
1960
1961 mrp->len = len; //total size of message
1962 mrp->address = buf;
1963 mrp->types = mrp->address + strlen(mrp->address) + 4 - strlen(mrp->address)%4;
1964 if( mrp->types[0] == ',') {
1965 // typed message
1966 mrp->data= mrp->types + strlen(mrp->types) + 4 - strlen(mrp->types)%4;
1967 }
1968 else {
1969 // untyped message.
1970 // should there be a warning?
1971 // classes that handle mesgs
1972 // should take care of that.
1973 mrp->data = mrp->types;
1974 mrp->types = NULL;
1975 }
1976
1977 }
1978
1979 void
1980 OSC_Receiver::handle_mesg( char * buf, int len )
1981 {
1982 // this is called sequentially by the receiving thread.
1983 if( buf[0] == '#' ) { handle_bundle( buf, len ); return; }
1984
1985 OSCMesg * mrp = write();
1986
1987 if( mrp->payload == NULL ) {
1988 mrp->payload = (char *)malloc( OSCINBUFSIZE * sizeof(char) );
1989 // CK_FPRINTF_STDERR( "oscrecv:mallocing %d bytes\n", OSCINBUFSIZE );
1990 }
1991
1992 memcpy( (void*)mrp->payload, (const void*)buf, len ); // copy data from buffer to message payload
1993 set_mesg( mrp, mrp->payload, len ); // set pointers for the message to its own payload
1994 mrp->recvtime = 0.000; // GetTime(); // set message time
1995
1996 distribute_message( mrp ); // copy message to any & all matching address spaces
1997
1998 // the distribute message will copy any necessary data into the addr object's private queue.
1999 // so we don't need to buffer here.. ( totally wasting the kick-ass expanding buffer i have in this class...drat )
2000
2001 // next_write();
2002 }
2003
2004 void OSC_Receiver::handle_bundle( char * b, int len )
2005 {
2006 // no scheduling for now
2007 // just immediately unpack everything
2008
2009 // CK_FPRINTF_STDERR( "bundle (length %d)\n", len );
2010
2011 int off = 16; //skip "#bundle\0timetags"
2012
2013 while ( off < len )
2014 {
2015 char * z = b+off;
2016 unsigned long size = ntohl(*((unsigned long*)z));
2017
2018 char * m = z+4;
2019
2020 if( m[0] == '#' ) handle_bundle(m,size);
2021 else handle_mesg(m,size);
2022
2023 off += size+4; //beginning of next message
2024 }
2025 }
2026
2027 OSC_Address_Space * OSC_Receiver::new_event( char * spec)
2028 {
2029 OSC_Address_Space * event = new OSC_Address_Space( spec );
2030 add_address( event );
2031 return event;
2032 }
2033
2034 OSC_Address_Space * OSC_Receiver::new_event( char * addr, char * type)
2035 {
2036 OSC_Address_Space * event = new OSC_Address_Space( addr, type );
2037 add_address( event );
2038 return event;
2039 }
2040
2041
2042 void OSC_Receiver::add_address( OSC_Address_Space * src )
2043 {
2044 // lock (added 1.3.1.1)
2045 _address_mutex->acquire();
2046
2047 // grow array, in place if possible
2048 if( _address_num == _address_size )
2049 {
2050 _address_size *= 2;
2051 _address_space = (OSC_Address_Space **)realloc( _address_space, _address_size * sizeof( OSC_Address_Space **) );
2052 }
2053 // add the source
2054 _address_space[_address_num++] = src;
2055
2056 // set the receiver
2057 src->setReceiver( this );
2058
2059 // release (added 1.3.1.1)
2060 _address_mutex->release();
2061 }
2062
2063 void OSC_Receiver::remove_address( OSC_Address_Space *odd )
2064 {
2065 // lock (added 1.3.1.1)
2066 _address_mutex->acquire();
2067
2068 for( int i = 0 ; i < _address_num ; i++ )
2069 {
2070 while( _address_space[i] == odd )
2071 {
2072 _address_space[i] = _address_space[--_address_num];
2073 }
2074 }
2075
2076 // release (added 1.3.1.1)
2077 _address_mutex->release();
2078 }
2079
2080 /*
2081 this function distributes each message to a matching address inside
2082 the chuck shred. There are some issues with this. bundle simultaneity
2083 might be solved via mutex?
2084 */
2085 void OSC_Receiver::distribute_message( OSCMesg * msg )
2086 {
2087 // lock (added 1.3.1.1)
2088 _address_mutex->acquire();
2089
2090 // iterate
2091 for( int i = 0 ; i < _address_num ; i++ )
2092 {
2093 if( _address_space[i]->try_queue_mesg( msg ) )
2094 {
2095 // CK_FPRINTF_STDERR( "broadcasting %x from %x\n", (uint)_address_space[i]->SELF, (uint)_address_space[i] );
2096 // if the event has any shreds queued, fire them off..
2097 ((Chuck_Event *)_address_space[i]->SELF)->queue_broadcast( m_event_buffer );
2098 }
2099 }
2100
2101 // release (added 1.3.1.1)
2102 _address_mutex->release();
2103 }
2104
2105
2106 // OSC SOURCE ( Parser )
2107 // rename to OSC_address ?
2108
2109 // this is an OSC_Address_Space - we register it to a particular receiver
2110 // the receiver matches an incoming message against registered
2111 // address and sends the message to all that match.
2112
2113 // OSCMesg may still have pointers to a mysterious void.
2114 // we should copy values locally for string and blob.
2115
2116 // public for of inherited chuck_event mfunc.
2117
2118 const char * osc_typename_strings[] = {
2119 "untyped",
2120 "no arguments",
2121 "integer",
2122 "float",
2123 "string",
2124 "blob",
2125 "ERROR: num types exceeded"
2126 };
2127
2128
2129
2130 OSC_Address_Space::OSC_Address_Space() {
2131 init();
2132 setSpec( "/undefined/default,i" );
2133 }
2134
2135
2136 OSC_Address_Space::OSC_Address_Space( const char * spec ) {
2137 init();
2138 setSpec( spec );
2139 }
2140
2141 OSC_Address_Space::OSC_Address_Space( const char * addr, const char * types) {
2142 init();
2143 setSpec( addr, types );
2144 }
2145
2146 void
2147 OSC_Address_Space::init() {
2148 _receiver = NULL;
2149 SELF = NULL;
2150 _queueSize = 512; // start queue size at 512 // 64.
2151 _dataSize = 0;
2152 _cur_mesg = NULL;
2153 _queue = NULL;
2154 _cur_value = 0;
2155 _current_data = NULL;
2156 _buffer_mutex = new XMutex();
2157 }
2158
2159 OSC_Address_Space::~OSC_Address_Space()
2160 {
2161 // clean up
2162 if( _queue ) free( _queue );
2163 // added 1.3.1.1
2164 CK_SAFE_DELETE( _buffer_mutex );
2165 }
2166
2167 void
2168 OSC_Address_Space::setReceiver(OSC_Receiver * recv) {
2169 _receiver = recv;
2170 }
2171
2172 void
2173 OSC_Address_Space::setSpec( const char *addr, const char * types ) {
2174 if( snprintf( _spec, sizeof _spec, "%s,%s", addr, types ) >= sizeof _spec) {
2175 // TODO: handle the overflow more gracefully.
2176 EM_log(CK_LOG_HERALD, "OSC_Address_Space::setSpec: Not enough space in _spec buffer, data was truncated.");
2177 }
2178 scanSpec();
2179 _needparse = true;
2180 parseSpec();
2181 }
2182
2183 void
2184 OSC_Address_Space::setSpec( const char *c ) {
2185 strncpy ( _spec, c, 512);
2186 scanSpec();
2187 _needparse = true;
2188 parseSpec();
2189 }
2190
2191 void
2192 OSC_Address_Space::scanSpec() { //this allows for sloppy-ish definitions in type string
2193 //assumes that a potential spec is already in _spec;
2194 char * pread;
2195 char * pwrite;
2196 pread = pwrite = (char*)_spec;
2197 bool in_type = false;
2198 while ( *pread != '\0' ) {
2199 if( *pread == ',' || *pread == ' ' ) {
2200 if( !in_type ) {
2201 in_type = true;
2202 *pwrite = ',';
2203 pwrite++;
2204 } // otherwise, we ignore
2205 else if( *pread == ' ' ) {
2206 EM_log(CK_LOG_INFO, "OSC-Address-Space: spaces in OSC type tag string! ignoring");
2207 }
2208 }
2209 else {
2210 if( pwrite != pread ) { *pwrite = *pread; }
2211 pwrite++;
2212 }
2213 pread++;
2214 }
2215 if( !in_type ) {
2216 //no type args found, add a comma to indicate a zero-arg string.
2217 *(pwrite++) = ',';
2218 }
2219 *pwrite = '\0'; //if pread terminates, so does pwrite.
2220 }
2221
2222 void
2223 OSC_Address_Space::parseSpec() {
2224
2225 if( !_needparse ) return;
2226
2227 char * type = strrchr(_spec, ',');
2228 if( !type ) return;
2229
2230 *type = '\0'; //null the address
2231 type++; //point to type string
2232
2233 strcpy ( _address, _spec );
2234 strcpy ( _type , type );
2235
2236 // CK_FPRINTF_STDERR( " parsing spec- address %s :: type %s\n", _address, _type );
2237
2238 t_CKINT n = strlen ( type );
2239 _noArgs = ( n == 0 );
2240 resizeData( ( n < 1 ) ? 1 : n );
2241 _qread = 0;
2242 _qwrite = 1;
2243
2244 _needparse = false;
2245 }
2246
2247 void
2248 OSC_Address_Space::resizeQueue( int n )
2249 {
2250 if( n <= _queueSize )
2251 return; // only grows
2252
2253 // lock
2254 _buffer_mutex->acquire();
2255
2256 // it's possible that between the test above and now,
2257 // qread has moved on and we actually DO have space..
2258
2259 EM_log( CK_LOG_INFO, "OSC_Address (%s) -- buffer full ( r:%d , w:%d, of %d(x%d) ), resizing...",
2260 _address, _qread, _qwrite, _queueSize, _dataSize );
2261 // CK_FPRINTF_STDERR( "--- hasMesg ( %d ) nextMesg ( %d )\n", (int) has_mesg(), (int)next_mesg() );
2262
2263 // we're the server... all we know is that the contents of qread are in the current_buffer,
2264 // so we can move the data, but we don't want to move ahead and lose it just yet.
2265
2266 // compute chunk size
2267 size_t chunkSize = _dataSize * sizeof( opsc_data );
2268
2269 // allocate
2270 int _newQSize = n;
2271 opsc_data * _new_queue = (opsc_data *)malloc( _newQSize * chunkSize );
2272
2273 // clear
2274 memset( _new_queue, 0, _newQSize * chunkSize ); // out with the old...
2275 // copy
2276 if( _qread < _qwrite )
2277 {
2278 // we're doing this because qwrite is out of room.
2279 // so if qwrite is already greater than qread,
2280 // just copy the whole thing to the start of the new buffer ( adding more space to the end )
2281 memcpy( (void*)_new_queue, (const void*)_queue, _queueSize * chunkSize);
2282 // _qwrite and _qread can stay right where they are.
2283 // CK_FPRINTF_STDERR( "resize - case 1\n" );
2284 }
2285 else
2286 {
2287 // _qread is in front of _qwrite, so we must unwrap, and place _qread at the
2288 // front of the queue, and qwrite at the end, preserving all elements that qread
2289 // is waiting to consume.
2290 int nread = _queueSize - _qread;
2291 memcpy( (void*)_new_queue,
2292 (const void*)(_queue + _qread * _dataSize),
2293 (nread) * chunkSize);
2294 memcpy( (void*)(_new_queue + nread * _dataSize),
2295 (const void*)_queue,
2296 (_qread) * _dataSize * sizeof( opsc_data ));
2297 _qread = 0;
2298 _qwrite += nread;
2299 // EM_log(CK_LOG_INFO, "resize - case 2\n");
2300 }
2301
2302 _queueSize = _newQSize;
2303 opsc_data * trash = _queue;
2304 _queue = _new_queue;
2305 free ( (void*)trash );
2306
2307 // don't move qread or qwrite until we're done.
2308 _buffer_mutex->release();
2309 }
2310
2311
2312 void
2313 OSC_Address_Space::resizeData( int n ) {
2314 if( _dataSize == n ) return;
2315 _dataSize = n;
2316 int queueLen = _queueSize * _dataSize * sizeof( opsc_data );
2317 _queue = ( opsc_data * ) realloc ( _queue, queueLen );
2318 memset ( _queue, 0, queueLen );
2319 _current_data = (opsc_data* ) realloc ( _current_data, _dataSize * sizeof( opsc_data) );
2320 }
2321
2322
2323 bool
2324 OSC_Address_Space::message_matches( OSCMesg * m ) {
2325
2326 //this should test for type as well.
2327
2328 bool addr_match;
2329 if( strcmp ( m->address, _address ) == 0 ) addr_match = true;
2330 else addr_match = PatternMatch( m->address, _address);
2331 if( !addr_match ) return false;
2332
2333 //address AND type must match
2334 //but there should be an option for the blank 'information about this' pattern
2335
2336 char * type = m->types+1;
2337 if( m->types == NULL || strcmp( _type , type ) != 0 ) {
2338 // if( type )
2339 // CK_FPRINTF_STDERR( "error, mismatched type string( %s ) vs ( %s ) \n", _type, type );
2340 // else
2341 // CK_FPRINTF_STDERR( "error, missing type string (expecting %s) \n", _type );
2342 return false;
2343 }
2344 return true;
2345 }
2346
2347
2348 bool OSC_Address_Space::try_queue_mesg( OSCMesg * m )
2349 {
2350 if( !message_matches( m ) ) return false;
2351 queue_mesg( m );
2352 return true;
2353 }
2354
2355
2356 bool OSC_Address_Space::has_mesg()
2357 {
2358 // EM_log( CK_LOG_FINER, "OSC has mesg" );
2359 return ( ( _qread + 1 ) % _queueSize != _qwrite );
2360 }
2361
2362
2363 bool OSC_Address_Space::next_mesg()
2364 {
2365 // 1.3.1.1 update
2366 if( !has_mesg() )
2367 return false;
2368
2369 // lock
2370 _buffer_mutex->acquire();
2371
2372 if( has_mesg() )
2373 {
2374 // move qread forward
2375 _qread = ( _qread + 1 ) % _queueSize;
2376 memcpy( _current_data, _queue + _qread * _dataSize, _dataSize * sizeof( opsc_data ) );
2377 _cur_mesg = _current_data;
2378 _cur_value = 0;
2379
2380 // release
2381 _buffer_mutex->release();
2382 return true;
2383 }
2384
2385 // release
2386 _buffer_mutex->release();
2387 return false;
2388 }
2389
2390 bool OSC_Address_Space::vcheck( osc_datatype tt )
2391 {
2392 if( !_cur_mesg )
2393 {
2394 EM_log( CK_LOG_HERALD, "OscEvent: getVal(): nextMsg() must be called before reading data..." );
2395 return false;
2396 }
2397 else if( _cur_value < 0 || _cur_value >= _dataSize )
2398 {
2399 EM_log( CK_LOG_HERALD, "OscEvent: read position %d outside message ...", _cur_value );
2400 return false;
2401 }
2402 else if( _cur_mesg[_cur_value].t != tt )
2403 {
2404 EM_log( CK_LOG_HERALD, "OscEvent: error -> message type %s != request type %s", osc_typename_strings[_cur_mesg[_cur_value].t], osc_typename_strings[tt] );
2405 return false;
2406 }
2407
2408 return true;
2409 }
2410
2411 int4byte OSC_Address_Space::next_int()
2412 {
2413 return (vcheck(OSC_INT)) ? _cur_mesg[_cur_value++].i : 0;
2414 }
2415
2416 float OSC_Address_Space::next_float()
2417 {
2418 return (vcheck(OSC_FLOAT)) ? _cur_mesg[_cur_value++].f : 0.0;
2419 }
2420
2421 char * OSC_Address_Space::next_string()
2422 {
2423 return (vcheck(OSC_STRING)) ? _cur_mesg[_cur_value++].s : NULL ;
2424 }
2425
2426 char *
2427 OSC_Address_Space::next_string_dup()
2428 {
2429 if( !vcheck(OSC_STRING) ) return NULL;
2430 char * alt_c = _cur_mesg[_cur_value++].s;
2431 char * dup_c = (char * ) malloc ( (strlen ( alt_c )+1 ) * sizeof(char) );
2432 strcpy ( dup_c, alt_c );
2433 return dup_c;
2434 }
2435
2436 char *
2437 OSC_Address_Space::next_blob() {
2438 return ( vcheck(OSC_BLOB) ) ? _cur_mesg[_cur_value++].s : NULL ;
2439 }
2440
2441 void
2442 OSC_Address_Space::queue_mesg( OSCMesg * m )
2443 {
2444 // in the server thread.
2445 int nqw = ( _qwrite + 1 ) % _queueSize;
2446 EM_log( CK_LOG_FINE, "OSC address(%s): read: %d write: %d size: %d", _address, _qread, _qwrite, _queueSize );
2447
2448 if( nqw == _qread ) {
2449 if( _queueSize < OSC_ADDRESS_QUEUE_MAX ) {
2450 resizeQueue( _queueSize * 2 );
2451 nqw = ( _qwrite + 1 ) % _queueSize; // _qwrite, _qread may have changed.
2452 }
2453 else {
2454 EM_log( CK_LOG_INFO, "OSC_Address_Space(%s): message queue reached max size %d...", _address, _queueSize );
2455 EM_log( CK_LOG_INFO, "...(dropping oldest message %d)", _qread );
2456
2457 // bump!
2458 _buffer_mutex->acquire();
2459 _qread = ( _qread + 1 ) % _queueSize;
2460 _buffer_mutex->release();
2461 }
2462 }
2463
2464 _vals = _queue + _qwrite * _dataSize;
2465
2466 if( _noArgs ) { // if address takes no arguments,
2467 _vals[0].t = OSC_NOARGS;
2468 }
2469 else {
2470 char * type = m->types+1;
2471 char * data = m->data;
2472
2473 unsigned int endy;
2474 int i=0;
2475
2476 float *fp;
2477 int *ip;
2478 t_CKINT clen;
2479 while ( *type != '\0' ) {
2480 switch ( *type ) {
2481 case 'f':
2482 endy = ntohl(*((unsigned long*)data));
2483 fp = (float*)(&endy);
2484 _vals[i].t = OSC_FLOAT;
2485 _vals[i].f = *fp;
2486 data += 4;
2487 break;
2488 case 'i':
2489 endy = ntohl(*((unsigned long*)data));
2490 ip = (int4byte*)(&endy);
2491 _vals[i].t = OSC_INT;
2492 _vals[i].i = *ip;
2493 data += 4;
2494 break;
2495 case 's':
2496 // string
2497 clen = strlen(data) + 1; // terminating!
2498 _vals[i].t = OSC_STRING;
2499 _vals[i].s = (char *) realloc ( _vals[i].s, clen * sizeof(char) );
2500 memcpy ( _vals[i].s, data, clen ); // make a copy of the data...
2501 // CK_FPRINTF_STDERR( "add string |%s| ( %d ) \n", _vals[i].s, clen );
2502 data += (((clen-1) >> 2) + 1) << 2;
2503 // data += clen + 4 - clen % 4;
2504 break;
2505 case 'b':
2506 // blobs
2507 endy = ntohl(*((unsigned long*)data));
2508 clen = *((int*)(&endy));
2509 _vals[i].t = OSC_BLOB;
2510 _vals[i].s = (char* ) realloc ( _vals[i].s, clen * sizeof(char) );
2511 memcpy ( _vals[i].s, data, clen );
2512 data += clen + 4 - clen % 4;
2513 break;
2514 }
2515 i++;
2516 type++;
2517 }
2518 }
2519
2520 _qwrite = nqw;
2521
2522 //review
2523 /*
2524 for( i=0; i < _nvals; i++ ) {
2525 CK_FPRINTF_STDERR( "%d %f : ", i, _val[i] );
2526 }
2527 CK_FPRINTF_STDERR( "\n" );
2528 */
2529 }