Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/Util/Clooper/aclient.cpp
blob: a01dcc30214c8712c0387eec0cf8eb7cfaacff33 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
#include <Python.h>

#include <pthread.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <sys/time.h>
#include <sched.h>

#include <vector>
#include <map>
#include <cmath>

#include <csound/csound.h>
#include <alsa/asoundlib.h>

static double pytime(const struct timeval * tv)
{
    struct timeval t;
    if (!tv)
    {
        tv = &t;
        gettimeofday(&t, NULL);
    }
    return (double) tv->tv_sec + (double) tv->tv_usec / 1000000.0;
}
#include "log.cpp"
#include "audio.cpp"

#define ERROR_HERE if (_debug && (VERBOSE > 0)) fprintf(_debug, "ERROR: %s:%i\n", __FILE__, __LINE__)

#define IF_DEBUG(N) if (_debug && (VERBOSE > N))

int VERBOSE = 3;
FILE * _debug = NULL;
struct TamTamSound;
TamTamSound * sc_tt = NULL;
log_t * g_log = NULL;

/**
 * ev_t is the type of event that Clooper puts in the loop buffer.
 * It corresponds to a line of csound that starts with an 'i'
 */
struct ev_t
{
    char type;  ///< if this event were listed in a csound file, the line would begin with this letter
    int onset;  ///< the onset time of this event (its temporal position)
    bool time_in_ticks; ///< if true, then some parameters will be updated according to the tempo
    bool active; ///< if true, then event() will actually do something
    MYFLT prev_secs_per_tick; ///< normally used for ____, sometimes set to -1 to force recalculation of param[] entries
    MYFLT duration, attack, decay;///< canonical values of some tempo-dependent parameters
    std::vector<MYFLT> param;     ///< parameter buffer for csound

    ev_t(char type, MYFLT * p, int param_count, bool in_ticks, bool active)
        : type(type), onset(0), time_in_ticks(in_ticks), active(active), param(param_count)
    {
        assert(param_count >= 4);
        onset = (int) p[1];
        duration = p[2];
        attack = param_count > 8 ? p[8]: 0.0; //attack
        decay = param_count > 9 ? p[9]: 0.0; //decay
        prev_secs_per_tick = -1.0;
        for (int i = 0; i < param_count; ++i) param[i] = p[i];

        param[1] = 0.0; //onset
    }
    /*
    bool operator<(const ev_t &e) const
    {
        return onset < e.onset;
    }
    */
    void ev_print(FILE *f)
    {
        fprintf(f, "INFO: scoreEvent %c ", type);
        for (size_t i = 0; i < param.size(); ++i) fprintf(f, "%lf ", param[i]);
        fprintf(f, "[%s]\n", active ? "active": "inactive");
    }
    /**
     *  Update the idx'th param value to have a certain value.
     *
     * Certain of the parameters are linked in strange hack-y ways, as defined by
     * the constructor, and update()  (which should be consistent with one another!)
     *
     * These events are for use with the file: TamTam/Resources/univorc.csd.
     * So that file defines how the parameters will be interpreted by csound.
     */
    void update(int idx, MYFLT val)
    {
        if ( (unsigned)idx >= param.size())
        {
            if (_debug && (VERBOSE > 0)) fprintf(_debug, "ERROR: updateEvent request for too-high parameter %i\n", idx);
            return;
        }
        if (time_in_ticks)
        {
            switch(idx)
            {
                case 1: onset = (int) val; break;
                case 2: duration =    val; break;
                case 8: attack =      val; break;
                case 9: decay  =      val; break;
                default: param[idx] = val; break;
            }
            prev_secs_per_tick = -1.0; //force recalculation
        }
        else
        {
            param[idx] = val;
        }
    }
    /**
     * An ev_t instance can be in an active or inactive state.  If an ev_t instance
     * is active, then event() will call a corresponding csoundScoreEvent().  If an
     * ev_t instance is inactive, then event() is a noop.
     */
    void activate_cmd(int cmd)
    {
        switch(cmd)
        {
            case 0: active = false; break;
            case 1: active = true; break;
            case 2: active = !active; break;
        }
    }

    /**
     * Iff this instance is active, this call generates a csound event.
     * Parameters are passed directly as a buffer of floats.  If secs_per_tick
     * != prev_secs_per_tick (possibly because prev_secs_per_tick was set to -1
     * by update() ) then this call will do some floating point ops to
     * recalculate the parameter buffer.
     */
    void event(CSOUND * csound, MYFLT secs_per_tick)
    {
        if (!active) return;

        if (time_in_ticks && (secs_per_tick != prev_secs_per_tick))
        {
            param[2] = duration * secs_per_tick;
            if (param.size() > 8) param[8] = std::max(0.002f, attack * param[2]);
            if (param.size() > 9) param[9] = std::max(0.002f, decay * param[2]);
            prev_secs_per_tick = secs_per_tick;
            if (_debug && (VERBOSE > 2)) fprintf(_debug, "setting duration to %f\n", param[5]);
        }
        csoundScoreEvent(csound, type, &param[0], param.size());
    }
};

/** 
 *
 * EvLoop is a repeat-able loop of ev_t instances.
 * */
struct EvLoop
{
    int tick_prev;
    int tickMax;
    MYFLT rtick;
    MYFLT secs_per_tick;
    typedef std::pair<int, ev_t *> pair_t;
    typedef std::multimap<int, ev_t *>::iterator iter_t;
    typedef std::map<int, iter_t>::iterator idmap_t;

    std::multimap<int, ev_t *> ev;
    std::multimap<int, ev_t *>::iterator ev_pos;
    std::map<int, iter_t> idmap;
    CSOUND * csound;
    void * mutex;
    int steps;
    TamTamSound * tt;

    EvLoop(CSOUND * cs, TamTamSound * tt) : tick_prev(0), tickMax(1), rtick(0.0), ev(), ev_pos(ev.end()), csound(cs), mutex(NULL), steps(0), tt(tt)
    {
        setTickDuration(0.05);
        mutex = csoundCreateMutex(0);
    }
    ~EvLoop()
    {
        csoundLockMutex(mutex);
        for (iter_t i = ev.begin(); i != ev.end(); ++i)
        {
            delete i->second;
        }
        csoundUnlockMutex(mutex);
        csoundDestroyMutex(mutex);
    }
    void clear()
    {
        csoundLockMutex(mutex);
        for (iter_t i = ev.begin(); i != ev.end(); ++i)
        {
            delete i->second;
        }
        ev.erase(ev.begin(), ev.end());
        ev_pos = ev.end();
        idmap.erase(idmap.begin(), idmap.end());
        csoundUnlockMutex(mutex);
    }
    void deactivateAll()
    {
        csoundLockMutex(mutex);
        for (iter_t i = ev.begin(); i != ev.end(); ++i)
        {
            i->second->activate_cmd(0);
        }
        csoundUnlockMutex(mutex);
    }
    int getTick()
    {
        return (int)rtick % tickMax;
    }
    void setNumTicks(int nticks)
    {
        tickMax = nticks;
        if ((int)rtick > nticks)
        {
            int t = (int)rtick % nticks;
            rtick = t;
        }
    }
    void setTick(int t)
    {
        t = t % tickMax;
        rtick = (MYFLT)(t % tickMax);
        //TODO: binary search would be faster
        csoundLockMutex(mutex);
        ev_pos = ev.lower_bound( t );
        csoundUnlockMutex(mutex);
    }
    void setTickDuration(MYFLT d)
    {
        if (!csound) {
            if (_debug && (VERBOSE > 1)) fprintf(_debug, "skipping setTickDuration, csound==NULL\n");
            return;
        }
        secs_per_tick = d;
    }
    /**  advance in play loop by rtick_inc ticks, possibly generate some
     * csoundScoreEvent calls.
     */
    void step(MYFLT rtick_inc )
    {
        rtick += rtick_inc;
        int tick = (int)rtick % tickMax;
        if (tick == tick_prev) return;

        csoundLockMutex(mutex);
        int events = 0;
        int loop0 = 0;
        int loop1 = 0;
        const int eventMax = 8;  //NOTE: events beyond this number will be ignored!!!
        if (!ev.empty()) 
        {
            if (steps && (tick < tick_prev)) // should be true only after the loop wraps (not after insert)
            {
                while (ev_pos != ev.end())
                {
                    if (_debug && (VERBOSE > 3)) ev_pos->second->ev_print(_debug);
                    if (events < eventMax) ev_pos->second->event(csound, secs_per_tick);
                    ++ev_pos;
                    ++events;
                    ++loop0;
                }
                ev_pos = ev.begin();
            }
            while ((ev_pos != ev.end()) && (tick >= ev_pos->first))
            {
                if (_debug && (VERBOSE > 3)) ev_pos->second->ev_print(_debug);
                if (events < eventMax) ev_pos->second->event(csound, secs_per_tick);
                ++ev_pos;
                ++events;
                ++loop1;
            }
        }
        csoundUnlockMutex(mutex);
        tick_prev = tick;
        if (_debug && (VERBOSE>1) && (events >= eventMax)) fprintf(_debug, "WARNING: %i/%i events at once (%i, %i)\n", events,ev.size(),loop0,loop1);
        ++steps;
    }
    void addEvent(int id, char type, MYFLT * p, int np, bool in_ticks, bool active)
    {
        ev_t * e = new ev_t(type, p, np, in_ticks, active);

        idmap_t id_iter = idmap.find(id);
        if (id_iter == idmap.end())
        {
            //this is a new id
            csoundLockMutex(mutex);

            iter_t e_iter = ev.insert(pair_t(e->onset, e));

            //TODO: optimize by thinking about whether to do ev_pos = e_iter
            ev_pos = ev.upper_bound( tick_prev );
            idmap[id] = e_iter;

            csoundUnlockMutex(mutex);
        }
        else
        {
            if (_debug && (VERBOSE > 0)) fprintf(_debug, "ERROR: skipping request to add duplicate note %i\n", id);
        }
    }
    void delEvent(int id)
    {
        idmap_t id_iter = idmap.find(id);
        if (id_iter == idmap.end())
        {
            if (_debug && (VERBOSE > 0)) fprintf(_debug, "ERROR: delEvent request for unknown note %i\n", id);
        }
        else
        {
            csoundLockMutex(mutex);
            iter_t e_iter = id_iter->second;//idmap[id];
            if (e_iter == ev_pos) ++ev_pos;

            delete e_iter->second;
            ev.erase(e_iter);
            idmap.erase(id_iter);

            csoundUnlockMutex(mutex);
        }
    }
    void updateEvent(int id, int idx, float val, int activate_cmd)
    {
        idmap_t id_iter = idmap.find(id);
        if (id_iter == idmap.end())
        {
            if (_debug && (VERBOSE > 0)) fprintf(_debug, "ERROR: updateEvent request for unknown note %i\n", id);
            return;
        }

        //this is a new id
        csoundLockMutex(mutex);
        iter_t e_iter = id_iter->second;
        ev_t * e = e_iter->second;
        int onset = e->onset;
        e->update(idx, val);
        e->activate_cmd(activate_cmd);
        if (onset != e->onset)
        {
            ev.erase(e_iter);

            e_iter = ev.insert(pair_t(e->onset, e));

            //TODO: optimize by thinking about whether to do ev_pos = e_iter
            ev_pos = ev.upper_bound( tick_prev );
            idmap[id] = e_iter;
        }
        csoundUnlockMutex(mutex);
    }
    void reset()
    {
        steps = 0;
    }
};

/**
 * The main object of control in the Clooper plugin.
 *
 * This guy controls the sound rendering thread, loads and unloads ALSA, 
 * maintains a csound instance, and maintains a subset of notes from the
 * currently-loaded TamTam.
 */
struct TamTamSound
{
    /** the id of an running sound-rendering thread, or NULL */
    void * ThreadID;
    /** a flag to tell the thread to continue, or break */
    enum {CONTINUE, STOP} PERF_STATUS;
    /** our csound object, NULL iff there was a problem creating it */
    CSOUND * csound;

    EvLoop * loop;
    /** a flag, true iff the thread should play&advance the loop */
    int thread_playloop;

    /** the upsampling ratio from csound */
    unsigned int csound_ksmps;
    snd_pcm_uframes_t csound_frame_rate;
    snd_pcm_uframes_t csound_period_size;
    snd_pcm_uframes_t period0;
    unsigned int period_per_buffer; //should be 2
    int up_ratio;  //if the hardware only supports a small integer multiple of our effective samplerate, do a real-time conversion

    MYFLT ticks_per_period, tick_adjustment; //the default time increment in thread_fn

    log_t * ll;
    SystemStuff * sys_stuff;

    TamTamSound(log_t * ll, char * orc, snd_pcm_uframes_t period0, unsigned int ppb, int ksmps, int framerate )
        : ThreadID(NULL), PERF_STATUS(STOP), csound(NULL),
        loop(NULL), thread_playloop(0),
        csound_ksmps(ksmps),                    //must agree with the orchestra file
        csound_frame_rate(framerate),           //must agree with the orchestra file
        period0(period0),
        period_per_buffer(ppb),
        up_ratio(1),
        ticks_per_period(1.0),
        tick_adjustment(0.0),
        ll( ll ),
        sys_stuff(NULL)
    {
        sys_stuff = new SystemStuff(ll);
        if (0 > sys_stuff->open(csound_frame_rate, 4, period0, period_per_buffer))
        {
            return;
        }
        sys_stuff->close(0);
        up_ratio = sys_stuff->rate / csound_frame_rate;
        csound_period_size = (sys_stuff->period_size % up_ratio == 0)
                  ? sys_stuff->period_size / up_ratio
                  : csound_ksmps * 4;

        csound = csoundCreate(NULL);
        int argc=3;
        char  **argv = (char**)malloc(argc*sizeof(char*));
        argv[0] = "csound";
        argv[1] = "-m0";
        argv[2] = orc;

        ll->printf(1,  "loading csound orchestra file %s\n", orc);
        //csoundInitialize(&argc, &argv, 0);
        csoundPreCompile(csound);
        csoundSetHostImplementedAudioIO(csound, 1, csound_period_size);
        int result = csoundCompile(csound, argc, &(argv[0]));
        if (result)
        {
            csound = NULL;
            ll->printf( "ERROR: csoundCompile of orchestra %s failed with code %i\n", orc, result);
        }
        free(argv);
        loop = new EvLoop(csound, this);
    }
    ~TamTamSound()
    {
        if (csound)
        {
            stop();
            delete loop;
            ll->printf(2, "Going for csoundDestroy\n");
            csoundDestroy(csound);
        }
        ll->printf(2, "TamTamSound destroyed\n");
        if (sys_stuff) delete sys_stuff;
        delete ll;
    }
    uintptr_t thread_fn()
    {
        assert(csound);

        const int nchannels = 2;
        int nloops = 0;
        long int csound_nsamples = csoundGetOutputBufferSize(csound);
        long int csound_nframes = csound_nsamples / nchannels;

        ll->printf(2, "INFO: nsamples = %li nframes = %li\n", csound_nsamples, csound_nframes);

        if (0 > sys_stuff->open(csound_frame_rate, 4, period0, period_per_buffer))
        {
            ll->printf( "ERROR: failed to open alsa device, thread abort\n");
            return 1;
        }
                 
        assert(up_ratio = sys_stuff->rate / csound_frame_rate);

        bool do_upsample = (signed)sys_stuff->period_size != csound_nframes;
        float *upbuf = do_upsample ? new float[ sys_stuff->period_size * nchannels ]: NULL; //2 channels
        int cbuf_pos = csound_nframes;
        float *cbuf = NULL;
        int up_pos = 0;
        int ratio_pos = 0;

        while (PERF_STATUS == CONTINUE)
        {
            if ( do_upsample ) //fill one period of audio buffer data by 0 or more calls to csound
            {
                up_pos = 0;
                int messed = 0;
                while(!messed)
                {
                    if (cbuf_pos == csound_nframes)
                    {
                        cbuf_pos = 0;
                        if (csoundPerformBuffer(csound)) { messed = 1;break;}
                        cbuf = csoundGetOutputBuffer(csound);
                    }
                    upbuf[2*up_pos+0] = cbuf[cbuf_pos*2+0];
                    upbuf[2*up_pos+1] = cbuf[cbuf_pos*2+1];

                    if (++ratio_pos == up_ratio)
                    {
                        ratio_pos = 0;
                        ++cbuf_pos;
                    }

                    if (++up_pos == (signed)sys_stuff->period_size) break;
                }
                if (messed || (up_pos != (signed)sys_stuff->period_size)) break;

                if (0 > sys_stuff->writebuf(sys_stuff->period_size, upbuf)) break;
            }
            else               //fill one period of audio directly from csound
            {
                //if (0 > sys_stuff->readbuf((char*)csoundGetInputBuffer(csound))) break;
                if (csoundPerformBuffer(csound)) break;
                if (0 > sys_stuff->writebuf(csound_nframes,csoundGetOutputBuffer(csound))) break;
            }

            if (thread_playloop)
            {
                if (tick_adjustment > - ticks_per_period)
                {
                    loop->step(ticks_per_period + tick_adjustment);
                    tick_adjustment = 0.0;
                }
                else
                {
                    tick_adjustment += ticks_per_period;
                }
            }
            ++nloops;
        }

        sys_stuff->close(1);
        if (do_upsample) delete [] upbuf;
        ll->printf(2, "INFO: performance thread returning 0\n");
        return 0;
    }
    static uintptr_t csThread(void *clientData)
    {
        return ((TamTamSound*)clientData)->thread_fn();
    }
    int start(int )
    {
        if (!csound) {
            ll->printf(1, "skipping %s, csound==NULL\n", __FUNCTION__);
            return 1;
        }
        if (!ThreadID)
        {
            PERF_STATUS = CONTINUE;
            ThreadID = csoundCreateThread(csThread, (void*)this);
            ll->printf( "INFO(%s:%i) aclient launching performance thread (%p)\n", __FILE__, __LINE__, ThreadID );
            return 0;
        }
        ll->printf( "INFO(%s:%i) skipping duplicate request to launch a thread\n", __FILE__, __LINE__ );
        return 1;
    }
    int stop()
    {
        if (!csound) {
            ll->printf(1, "skipping %s, csound==NULL\n", __FUNCTION__);
            return 1;
        }
        if (ThreadID)
        {
            PERF_STATUS = STOP;
            ll->printf( "INFO(%s:%i) aclient joining performance thread\n", __FILE__, __LINE__ );
            uintptr_t rval = csoundJoinThread(ThreadID);
            ll->printf( "INFO(%s:%i) ... joined\n", __FILE__, __LINE__ );
            if (rval)  ll->printf( "WARNING: thread returned %zu\n", rval);
            ThreadID = NULL;
            return 0;
        }
        return 1;
    }

    void scoreEvent(char type, MYFLT * p, int np)
    {
        if (!csound) {
            ll->printf(1, "skipping %s, csound==NULL\n", __FUNCTION__);
            return;
        }
        if (!ThreadID)
        {
            if (_debug && (VERBOSE > 1)) fprintf(_debug, "skipping %s, ThreadID==NULL\n", __FUNCTION__);
            return ;
        }
        if (_debug && (VERBOSE > 2))
        {
            fprintf(_debug, "INFO: scoreEvent %c ", type);
            for (int i = 0; i < np; ++i) fprintf(_debug, "%lf ", p[i]);
            fprintf(_debug, "\n");
        }
        csoundScoreEvent(csound, type, p, np);
    }
    void inputMessage(const char * msg)
    {
        if (!csound) {
            ll->printf(1, "skipping %s, csound==NULL\n", __FUNCTION__);
            return;
        }
        if (!ThreadID)
        {
            if (_debug && (VERBOSE > 1)) fprintf(_debug, "skipping %s, ThreadID==NULL\n", __FUNCTION__);
            return ;
        }
        if (_debug &&(VERBOSE > 3)) fprintf(_debug, "%s\n", msg);
        csoundInputMessage(csound, msg);
    }
    bool good()
    {
        return csound != NULL;
    }

    void setMasterVolume(MYFLT vol)
    {
        if (!csound) {
            ll->printf(1, "skipping %s, csound==NULL\n", __FUNCTION__);
            return;
        }
        if (!ThreadID)
        {
            if (_debug && (VERBOSE > 1)) fprintf(_debug, "skipping %s, ThreadID==NULL\n", __FUNCTION__);
            return ;
        }
        MYFLT *p;
        if (!(csoundGetChannelPtr(csound, &p, "masterVolume", CSOUND_CONTROL_CHANNEL | CSOUND_INPUT_CHANNEL)))
            *p = (MYFLT) vol;
        else
        {
            if (_debug && (VERBOSE >0)) fprintf(_debug, "ERROR: failed to set master volume\n");
        }
    }

    void setTrackVolume(MYFLT vol, int Id)
    {
        if (!csound) {
            ll->printf(1, "skipping %s, csound==NULL\n", __FUNCTION__);
            return;
        }
        if (!ThreadID)
        {
            if (_debug && (VERBOSE > 1)) fprintf(_debug, "skipping %s, ThreadID==NULL\n", __FUNCTION__);
            return ;
        }
        MYFLT *p;
        char buf[128];
        sprintf( buf, "trackVolume%i", Id);
        if (_debug && (VERBOSE > 10)) fprintf(_debug, "DEBUG: setTrackvolume string [%s]\n", buf);
        if (!(csoundGetChannelPtr(csound, &p, buf, CSOUND_CONTROL_CHANNEL | CSOUND_INPUT_CHANNEL)))
            *p = (MYFLT) vol;
        else
        {
            if (_debug) fprintf(_debug, "ERROR: failed to set track volume\n");
        }
    }

    void setTrackpadX(MYFLT value)
    {
        if (!csound) {
            ll->printf(1, "skipping %s, csound==NULL\n", __FUNCTION__);
            return;
        }
        if (!ThreadID)
        {
            if (_debug && (VERBOSE > 1)) fprintf(_debug, "skipping %s, ThreadID==NULL\n", __FUNCTION__);
            return ;
        }
        MYFLT *p;
        if (!(csoundGetChannelPtr(csound, &p, "trackpadX", CSOUND_CONTROL_CHANNEL | CSOUND_INPUT_CHANNEL)))
            *p = (MYFLT) value;
        else
        {
            if (_debug && (VERBOSE > 0)) fprintf(_debug, "ERROR: failed to set trackpad X value\n");
        }
    }

    void setTrackpadY(MYFLT value)
    {
        if (!csound) {
            ll->printf(1, "skipping %s, csound==NULL\n", __FUNCTION__);
            return;
        }
        if (!ThreadID)
        {
            if (_debug && (VERBOSE > 1)) fprintf(_debug, "skipping %s, ThreadID==NULL\n", __FUNCTION__);
            return ;
        }
        MYFLT *p;
        if (!(csoundGetChannelPtr(csound, &p, "trackpadY", CSOUND_CONTROL_CHANNEL | CSOUND_INPUT_CHANNEL)))
            *p = (MYFLT) value;
        else
        {
             if (_debug && (VERBOSE >0)) fprintf(_debug, "ERROR: failed to set trackpad Y value\n");
        }
    }
    void loopPlaying(int tf)
    {
        thread_playloop= tf;
        if (tf) loop->reset();
    }

    void setTickDuration(MYFLT secs_per_tick )
    {
        if (loop) loop->setTickDuration( secs_per_tick);
        ticks_per_period = csound_period_size / ( secs_per_tick  * csound_frame_rate);
        ll->printf( 3, "INFO: duration %lf := ticks_per_period %lf\n", secs_per_tick , ticks_per_period);
    }
    void adjustTick(MYFLT dtick)
    {
        tick_adjustment += dtick;
    }
};


static void cleanup(void)
{
    if (sc_tt)
    {
        delete sc_tt;
        sc_tt = NULL;
    }
}

#define DECL(s) static PyObject * s(PyObject * self, PyObject *args)
#define RetNone Py_INCREF(Py_None); return Py_None;

//call once at end
DECL(sc_destroy)
{
    if (!PyArg_ParseTuple(args, ""))
    {
        return NULL;
    }
    if (sc_tt)
    {
        delete sc_tt;
        sc_tt = NULL;
        if (_debug) fclose(_debug);
    }
    RetNone;
}
//call once at startup, should return 0
DECL(sc_initialize) //(char * csd)
{
    char * str;
    char * log_file;
    int period, ppb, ksmps, framerate;
    if (!PyArg_ParseTuple(args, "ssiiiii", &str, &log_file, &period, &ppb, &VERBOSE, &ksmps, &framerate ))
    {
        return NULL;
    }
    if ( log_file[0] )
    {
        _debug = fopen(log_file,"w"); 
        if (_debug==NULL) 
        {
            fprintf(stderr, "WARNING: fopen(%s) failed, logging to stderr\n", log_file);
            _debug = stderr;
        }
    }
    else
    {
        _debug = NULL;
        fprintf(stderr, "Logging disabled on purpose\n");
    }
    g_log = new log_t(_debug, VERBOSE);
    sc_tt = new TamTamSound(g_log, str, period, ppb, ksmps, framerate);
    atexit(&cleanup);
    if (sc_tt->good()) 
        return Py_BuildValue("i", 0);
    else
        return Py_BuildValue("i", -1);
}
//compile the score, connect to device, start a sound rendering thread
DECL(sc_start)
{
    int ppb;
    if (!PyArg_ParseTuple(args, "i", &ppb ))
    {
        return NULL;
    }
    return Py_BuildValue("i", sc_tt->start(ppb));
}
//stop csound rendering thread, disconnect from sound device, clear tables.
DECL(sc_stop) 
{
    if (!PyArg_ParseTuple(args, "" ))
    {
        return NULL;
    }
    return Py_BuildValue("i", sc_tt->stop());
}
DECL(sc_scoreEvent) //(char type, farray param)
{
    char ev_type;
    PyObject *o;
    if (!PyArg_ParseTuple(args, "cO", &ev_type, &o ))
    {
        return NULL;
    }
    if (o->ob_type
            &&  o->ob_type->tp_as_buffer
            &&  (1 == o->ob_type->tp_as_buffer->bf_getsegcount(o, NULL)))
    {
        if (o->ob_type->tp_as_buffer->bf_getreadbuffer)
        {
            void * ptr;
            size_t len;
            len = o->ob_type->tp_as_buffer->bf_getreadbuffer(o, 0, &ptr);
            float * fptr = (float*)ptr;
            size_t flen = len / sizeof(float);
            sc_tt->scoreEvent(ev_type, fptr, flen);

            Py_INCREF(Py_None);
            return Py_None;
        }
        else
        {
            assert(!"asdf");
        }
    }
    assert(!"not reached");
    return NULL;
}
DECL(sc_setMasterVolume) //(float v)
{
    float v;
    if (!PyArg_ParseTuple(args, "f", &v))
    {
        return NULL;
    }
    sc_tt->setMasterVolume(v);
    Py_INCREF(Py_None);
    return Py_None;
}
DECL(sc_setTrackVolume) //(float v)
{
    float v;
    int i;
    if (!PyArg_ParseTuple(args, "fi", &v, &i))
    {
        return NULL;
    }
    sc_tt->setTrackVolume(v,i);
    Py_INCREF(Py_None);
    return Py_None;
}
DECL(sc_setTrackpadX) //(float v)
{
    float v;
    if (!PyArg_ParseTuple(args, "f", &v))
    {
        return NULL;
    }
    sc_tt->setTrackpadX(v);
    Py_INCREF(Py_None);
    return Py_None;
}
DECL(sc_setTrackpadY) //(float v)
{
    float v;
    if (!PyArg_ParseTuple(args, "f", &v))
    {
        return NULL;
    }
    sc_tt->setTrackpadY(v);
    Py_INCREF(Py_None);
    return Py_None;
}
DECL(sc_loop_getTick) // -> int
{
    if (!PyArg_ParseTuple(args, "" ))
    {
        return NULL;
    }
    return Py_BuildValue("i", sc_tt->loop ? sc_tt->loop->getTick():-1);
}
DECL(sc_loop_setNumTicks) //(int nticks)
{
    int nticks;
    if (!PyArg_ParseTuple(args, "i", &nticks ))
    {
        return NULL;
    }
    if (sc_tt->loop) sc_tt->loop->setNumTicks(nticks);
    RetNone;
}
DECL(sc_loop_setTick) // (int ctick)
{
    int ctick;
    if (!PyArg_ParseTuple(args, "i", &ctick ))
    {
        return NULL;
    }
    if (sc_tt->loop) sc_tt->loop->setTick(ctick);
    RetNone;
}
DECL(sc_loop_setTickDuration) // (MYFLT secs_per_tick)
{
    float spt;
    if (!PyArg_ParseTuple(args, "f", &spt ))
    {
        return NULL;
    }
    sc_tt->setTickDuration(spt);
    RetNone;
}
DECL(sc_loop_adjustTick) // (MYFLT ntick)
{
    float spt;
    if (!PyArg_ParseTuple(args, "f", &spt ))
    {
        return NULL;
    }
    sc_tt->adjustTick(spt);
    RetNone;
}
DECL(sc_loop_addScoreEvent) // (int id, int duration_in_ticks, char type, farray param)
{
    int qid, inticks, active;
    char ev_type;
    PyObject *o;
    if (!PyArg_ParseTuple(args, "iiicO", &qid, &inticks, &active, &ev_type, &o ))
    {
        return NULL;
    }
    if (o->ob_type
            &&  o->ob_type->tp_as_buffer
            &&  (1 == o->ob_type->tp_as_buffer->bf_getsegcount(o, NULL)))
    {
        if (o->ob_type->tp_as_buffer->bf_getreadbuffer)
        {
            void * ptr;
            size_t len;
            len = o->ob_type->tp_as_buffer->bf_getreadbuffer(o, 0, &ptr);
            float * fptr = (float*)ptr;
            size_t flen = len / sizeof(float);
            if (sc_tt->loop) sc_tt->loop->addEvent(qid, ev_type, fptr, flen, inticks, active);

            Py_INCREF(Py_None);
            return Py_None;
        }
        else
        {
            assert(!"asdf");
        }
    }
    assert(!"not reached");
    return NULL;
}
DECL(sc_loop_delScoreEvent) // (int id)
{
    int id;
    if (!PyArg_ParseTuple(args, "i", &id ))
    {
        return NULL;
    }
    if (sc_tt->loop) sc_tt->loop->delEvent(id);
    RetNone;
}
DECL(sc_loop_updateEvent) // (int id)
{
    int id;
    int idx;
    float val;
    int cmd;
    if (!PyArg_ParseTuple(args, "iifi", &id, &idx, &val, &cmd))
    {
        return NULL;
    }
    if (sc_tt->loop) sc_tt->loop->updateEvent(id, idx, val, cmd);
    RetNone;
}
DECL(sc_loop_deactivate_all) // (int id)
{
    if (!PyArg_ParseTuple(args, ""))
    {
        return NULL;
    }
    if (sc_tt->loop) sc_tt->loop->deactivateAll();
    RetNone;
}
DECL(sc_loop_clear)
{
    if (!PyArg_ParseTuple(args, "" ))
    {
        return NULL;
    }
    if (sc_tt->loop) sc_tt->loop->clear();
    RetNone;
}
DECL(sc_loop_playing) // (int tf)
{
    int i;
    if (!PyArg_ParseTuple(args, "i", &i ))
    {
        return NULL;
    }
    if (sc_tt->loop) sc_tt->loopPlaying(i);
    RetNone;
}
DECL (sc_inputMessage) //(const char *msg)
{
    char * msg;
    if (!PyArg_ParseTuple(args, "s", &msg ))
    {
        return NULL;
    }
    sc_tt->inputMessage(msg);
    RetNone;
}

#define MDECL(s) {""#s, s, METH_VARARGS, "documentation of "#s"... nothing!"}
static PyMethodDef SpamMethods[] = {
    MDECL(sc_destroy),
    MDECL(sc_initialize),
    MDECL(sc_start),
    MDECL(sc_stop),
    MDECL(sc_scoreEvent),
    MDECL(sc_setMasterVolume),
    MDECL(sc_setTrackVolume),
    MDECL(sc_setTrackpadX),
    MDECL(sc_setTrackpadY),
    MDECL(sc_loop_getTick),
    MDECL(sc_loop_setNumTicks),
    MDECL(sc_loop_setTick),
    MDECL(sc_loop_setTickDuration),
    MDECL(sc_loop_adjustTick),
    MDECL(sc_loop_delScoreEvent),
    MDECL(sc_loop_addScoreEvent),
    MDECL(sc_loop_updateEvent),
    MDECL(sc_loop_clear),
    MDECL(sc_loop_deactivate_all),
    MDECL(sc_loop_playing),
    MDECL(sc_inputMessage),
    {NULL, NULL, 0, NULL} /*end of list */
};

PyMODINIT_FUNC
initaclient(void)
{
    (void) Py_InitModule("aclient", SpamMethods);
}