File: midimgr.c

package info (click to toggle)
audacity 2.0.6-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 80,076 kB
  • sloc: cpp: 192,859; ansic: 158,072; sh: 34,021; python: 24,248; lisp: 7,495; makefile: 3,667; xml: 573; perl: 31; sed: 16
file content (784 lines) | stat: -rw-r--r-- 28,796 bytes parent folder | download | duplicates (21)
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
/* midimgr.c -- this file contains interface code to support use of Apple Midi Manager */
/*
 * This code is based on code supplied with the Apple Midi Manager.
 * Copyright 1991, Carnegie Mellon University
 */
 
/* BUGS: 
 *     If exclusive() is called to turn exclusive messages on or off DURING the
 * receipt of an exclusive message, incoming data will be garbled.  The correct
 * handling would be to record when receipt of an exclusive message is in
 * progress, then properly remove any partial message when exclusive is turned
 * off, and ignore any remaining message part when exclusive is turned on.
 * The present code does neither.
 */
 
#include "cext.h"
#undef round
#ifdef THINK_C
#include <pascal.h> /* for ThinkC 7 */
#endif

#include "stdio.h"
#include "userio.h"
#include "MIDI.h"
#include "midifns.h"
#include "midibuff.h"
#include "midierr.h"
#include "midimgr.h"
#include "midicode.h"
#include "cmdline.h"

/* Needed for KillEverybody */
#include <toolutils.h>
#include <AppleEvents.h>
#include <EPPC.h>
#include <Gestalt.h>
#include <PPCToolbox.h> 
#include <Processes.h>
#include <Sound.h>


#define CMTclientID             'CMT '
/* note the following are in alphabetical order for Patcher display */
#define timePortID              'Atim'
#define inputPortID             'Bin '
#define outputPortID    'Cout'
#define noClient                '    '

#define noTimeBaseRefNum        0
#define noReadHook                      0L
#define zeroTime                        0L
#define timePortBuffSize        0L
#define inputPortBuffSize       2048
#define outputPortBuffSize      0L
#define refCon0 0L

pascal short CMTreader(MIDIPacket *ThePacketPtr, long TheRefCon);

/* "patch" switch from command line.  This switch is cached in patch_flag and tells
   whether to look in the resource fork for a patch, or just hook up to midi in and
   out.  If the resource fork is used, the patch will be saved upon exit. */
private boolean patch_flag; 
extern boolean ctrlFilter;
extern boolean exclFilter;
extern boolean realFilter;

private midi_read_lock = false;	/* used to stop input during data structure manipulation */

private void set_error(int bit);
#ifndef NYQUIST
void PatchPorts(void);
void SavePatch(OSType PortID, short PortInfoResID, char *PortInfoResName);
#endif

/* exported:  */
public short InputRefNum;                       /* Input port reference number. */
public short OutputRefNum;                      /* Output port reference number. */
public short TimeRefNum;                        /* Time base port reference number. */

Boolean         GManualPatch;   /* True if not launched by a PatchBay Config. File. */

/****************************************************************************
*
*       variables shared with other modules
*
****************************************************************************/

/* midi input buffer */
long buff[BUFF_SIZE/4]; /* data buffer, declared long to get 32-bit alignment */
int buffhead = 0;               /* buffer head and tail pointers */
int bufftail = 0;

/* user supplied system exclusive buffer */
byte *xbuff = NULL;     /* address of the user-supplied buffer */
public long xbufmask;    /* mask for circular buffer address calculation */
long xbufhead = 0;       /* buffer head and tail pointers */
long xbuftail = 0;
boolean xbuf_flush = true;	/* says to flush remainder of sysex message */

#ifdef SYSEXDEBUG
int sysexcount = 0;	/* for debugging */
int sysexdone = 0;
int sysexheadcount = 0;
byte sysexfirst = 0;
int sysexsysex = 0;
#endif

/* midi_flush -- empty out buffers */
/**/
void midi_flush()
{
    midi_read_lock = true;
    buffhead = 0;
    bufftail = 0;
    xbufhead = 0;
    xbuftail = 0;
    xbuf_flush = true;	/* in case sysex continuation messages are still coming */
    midi_read_lock = false;
}


/* Nyquist only uses CMT for Midi and Adagio file IO */
#ifndef NYQUIST
/* Get String representation of MIDI Mgr Version Num.*/
/* See Mac Tech Note #189 for details. */
char *StdMacVerNumToStr(long VerNum, char *VerStr)
{
        char    *RetVal;
        char    MajVer, MinVer, VerStage, VerRev, BugFixVer = 0;
        
        if (VerNum == 0)
        {
                RetVal = NULL;
        }
        else
        {
                MajVer          = (VerNum & 0xFF000000) >> 24;
                MinVer          = (VerNum & 0x00FF0000) >> 16;
                VerStage        = (VerNum & 0x0000FF00) >> 8;
                VerRev          = (VerNum & 0x000000FF) >> 0;
                BugFixVer       =  MinVer & 0x0F;
                
                switch (VerStage)
                {
                        case 0x20:
                                    VerStage = 'd';
                                    break;
                        case 0x40:
                                    VerStage = 'a';
                                    break;
                        case 0x60:
                                    VerStage = 'b';
                                    break;
                        case 0x80:
                                    VerStage = ' ';
                                    break;
                        default:
                                    VerStage = '?';
                                    break;
                }
                
                if (BugFixVer == 0)
                {
                        sprintf(VerStr,"%X.%X%c%X", 
                                    MajVer, MinVer>>4, VerStage, VerRev);
                }
                else
                {
                        sprintf(VerStr,"%X.%X.%X%c%X", 
                                    MajVer, MinVer >> 4, MinVer & 0x0F, VerStage, VerRev);
                }
                
                RetVal = VerStr;
        }
                
        return(RetVal);
}


/* C2PStrCpy -- Convert a C String (from Cstr) into a Pascal string */
/*
 * NOTE: this is not the same code as shipped with midi manager example
 */
char *C2PStrCpy(char *Cstr, Str255 Pstr)
{
        char *c = Cstr;
        char *p = ((char *) Pstr) + 1;
        
        while (*c) *p++ = *c++;
        *Pstr = c - Cstr;
        return( (char *) Pstr );
}

/* This checks to see if THINK C is running under System 7,
   and ONLY WORKS UNDER SYSTEM 7!  Don't use unless you check! */
boolean ThinkCRunning(void)
{
     ProcessSerialNumber processSN;
    OSErr myErr;
    ProcessInfoRec infoRec;
    
    processSN.lowLongOfPSN = kNoProcess;
    processSN.highLongOfPSN = kNoProcess;
    do {
        myErr = GetNextProcess(&processSN);
        
        infoRec.processInfoLength = sizeof(ProcessInfoRec);
        infoRec.processName = 0L;
        infoRec.processAppSpec = 0L;
        myErr = GetProcessInformation(&processSN, &infoRec);
        if (!myErr) {
                if (infoRec.processSignature == 'KAHL') {
                    return(true);
                }
        }
    } while (myErr == noErr);
    return(false);
}

/* This kills off all the other running processes... 
   ONLY WORKS UNDER SYSTEM 7!  Don't use unless you check! */
void KillEverybody(void)
{
    ProcessSerialNumber myProc, processSN;
    ProcessSerialNumber finderPSN;
    ProcessInfoRec infoRec;
    Str31 processName;
    FSSpec procSpec;
    
    OSErr myErr = noErr;
    OSErr otherError;
    AppleEvent theEvent;
    AEDesc theAddress;
    Boolean ourFlag, notFinder;
    Boolean finderFound = false;
    
    GetCurrentProcess(&myProc);
    /* Preset the PSN to no PSN, see IM VI, the Process Manager */
    processSN.lowLongOfPSN = kNoProcess;
    processSN.highLongOfPSN = kNoProcess;
    finderPSN.lowLongOfPSN = 0UL; /* brk: was nil */
    finderPSN.highLongOfPSN = 0UL; /* brk: was nil */
    
    do {
        myErr = GetNextProcess(&processSN);
        /* See if it's us first */
        notFinder = true;
        SameProcess(&myProc, &processSN, &ourFlag);

            infoRec.processInfoLength = sizeof(ProcessInfoRec);
            infoRec.processName = (StringPtr) &processName;
            infoRec.processAppSpec = &procSpec;
            GetProcessInformation(&processSN, &infoRec);
        if (!ourFlag && !finderFound) {
            /* see if it's the Finder, we have to kill the finder LAST */
            /* or else non-sys 7 apps won't get killed */
            /* since the Finder must be there to convert the AppleEvent to Puppet Strings */
            /* if the app is not APpleEvent aware */
            /* Also, FileShare HAS to be killed before the Finder */
            /* or your life will be unpleasant */

            if (infoRec.processSignature == 'MACS' && infoRec.processType == 'FNDR') {
                /* save this number for later  */
                finderPSN = processSN;
                notFinder = false;
                finderFound = true;
            
            } else {
                notFinder = true;
            }
        }
        if (!myErr && !ourFlag && notFinder) {
            otherError = AECreateDesc(typeProcessSerialNumber, (Ptr)&processSN, sizeof(processSN), &theAddress);
            if (!otherError)
                otherError = AECreateAppleEvent(kCoreEventClass, kAEQuitApplication, &theAddress, kAutoGenerateReturnID,
                                                                    kAnyTransactionID, &theEvent);
            if (!otherError)
                AEDisposeDesc(&theAddress);
            /* Again, the Finder will convert the AppleEvent to puppetstrings if */
            /* the application is a System 6 or non-AE aware app.  This ONLY  */
            /* happens for the 4 required (oapp,odoc,pdoc, and quit) AppleEvents  */
            /* and ONLY if you use the PSN for the address */
            if (!otherError)
                AESend(&theEvent, 0L, kAENoReply + kAEAlwaysInteract + kAECanSwitchLayer, kAENormalPriority, kAEDefaultTimeout,
                       0L, 0L);
            AEDisposeDesc(&theEvent);
        }
    } while (!myErr);
    
    /* Now, if the finder was running, it's safe to kill it */
    if (finderPSN.lowLongOfPSN || finderPSN.highLongOfPSN) {
        otherError = AECreateDesc(typeProcessSerialNumber, (Ptr)&finderPSN, sizeof(processSN), &theAddress);
        if (!otherError)
            otherError = AECreateAppleEvent(kCoreEventClass, kAEQuitApplication, &theAddress, kAutoGenerateReturnID,
                                                            kAnyTransactionID, &theEvent);
        if (!otherError)
            AEDisposeDesc(&theAddress);
        if (!otherError)
            AESend(&theEvent, 0L, kAENoReply + kAEAlwaysInteract + kAECanSwitchLayer, kAENormalPriority, kAEDefaultTimeout, 0L,
                   0L);
        AEDisposeDesc(&theEvent);
    }
}

/* Sign into the MIDI Manager. */
/* Set up time, input, and output ports. */
/* Start our time base clock. */
void setup_midimgr(void)
{
    MIDIPortParams  Init;   /* MIDI Mgr Init data structure */ 
    Handle                  TheIconHndl;
    OSErr                   TheErr;
    long                    MIDIMgrVerNum;  /* MIDI Manager Ver (Std Mac Ver #) */
    Str255 name = "\pCMU MIDI Toolkit";
    char MIDIMgrVerStr[256]; /* MIDI Manager Ver (Std Mac Ver # String) */
    long vers;
    EventRecord theEvent;
    
    Gestalt(gestaltSystemVersion, &vers);
    vers = (vers >> 8) & 0xf;                               /* shift result over and mask out major version number */
    if ((vers >= 7) && (!cl_switch("keep"))  && (!ThinkCRunning()))  {
        gprintf(TRANS,"Killing other processes...\n");
        KillEverybody();
        for (vers=0; vers<100; ++vers) {
            while (WaitNextEvent(everyEvent, &theEvent, 0L, 0L)) ;
        }
    }
        
    /* Make sure MIDIMgr is installed and save version num. */
    MIDIMgrVerNum = SndDispVersion(midiToolNum);
    if (MIDIMgrVerNum == 0) {
        gprintf(ERROR, "The MIDI Manager is not installed! Exiting...\n");
        EXIT(1);
    } else {        
        StdMacVerNumToStr(MIDIMgrVerNum, MIDIMgrVerStr);
        gprintf(TRANS,"MIDI Manager Version %s\n", MIDIMgrVerStr);
    }

        
    /* Sign in to the MIDI Manager. */
    TheIconHndl = GetResource('ICN#', 1);
    TheErr = MIDISignIn(CMTclientID,
                        0L, 
                        TheIconHndl,
                        name);
    if (TheErr) {
            gprintf(ERROR, "Trouble signing into MIDI Manager!  Aborting...");
            EXIT(1);
    }

    /* Assume not a Patchbay configuration. */
    GManualPatch = true;    

    /* Add time port. */
    Init.portID = timePortID;
    Init.portType = midiPortTypeTime;
    Init.timeBase = noTimeBaseRefNum;
    Init.readHook = noReadHook;
    Init.initClock.syncType = midiInternalSync;
    Init.initClock.curTime = zeroTime;
    Init.initClock.format = midiFormatMSec;
    Init.refCon = SetCurrentA5();
    C2PStrCpy("TimeBase", Init.name);
    TheErr = MIDIAddPort(CMTclientID, timePortBuffSize, &TimeRefNum, &Init);
    /* Has a PatchBay connection been resolved? */
    if (TheErr == midiVConnectMade) {
        GManualPatch = false;
    } else if (TheErr == memFullErr) {
        gprintf(ERROR, "Not enough room in heap zone to add time port!  Aborting...");
        MIDISignOut(CMTclientID);       
        EXIT(1);
    }
        
    /* Add an input port. */
    Init.portID = inputPortID;
    Init.portType = midiPortTypeInput;
    Init.timeBase = TimeRefNum;
    Init.offsetTime = midiGetCurrent;
    Init.readHook = NewMIDIReadHookProc(CMTreader);
    Init.refCon = SetCurrentA5();
    C2PStrCpy("InputPort", Init.name);
    TheErr = MIDIAddPort(CMTclientID, inputPortBuffSize, &InputRefNum, &Init);
    /* Has a PatchBay connection been resolved? */
    if (TheErr == midiVConnectMade) {
        GManualPatch = false;
    } else if (TheErr == memFullErr) {
        gprintf(ERROR, "Not enough room in heap zone to add input port!  Aborting...");
        MIDISignOut(CMTclientID);       
        EXIT(1);
    }
        
    /* Add an output port. */
    Init.portID = outputPortID;
    Init.portType = midiPortTypeOutput;
    Init.timeBase = TimeRefNum;
    Init.offsetTime = midiGetCurrent;
    Init.readHook = NULL;
    Init.refCon = refCon0;
    C2PStrCpy("OutputPort", Init.name);
    TheErr = MIDIAddPort(CMTclientID, outputPortBuffSize, &OutputRefNum, &Init);
    /* Has a PatchBay connection been resolved? */
    if (TheErr == midiVConnectMade) {
        GManualPatch = false;
    } else if (TheErr == memFullErr) {
        printf("Not enough room in heap zone to add output port!  Aborting...");
        MIDISignOut(CMTclientID);       
        EXIT(1);
    }
        
    if (GManualPatch) {
        PatchPorts(); /* connect ports as they were */
    }
    /* to clean this up (later) call finish_midimgr() */
    cu_register((cu_fn_type) finish_midimgr, (cu_parm_type) finish_midimgr);
        
    /* Start our Clock. */
    MIDIStartTime(TimeRefNum);              
}


/* The Read Hook Function. */

/* 1st 4 bytes of sysex message get saved here and enqueued later */
char save_sysex_head[4];
int save_sysex_head_x = 0;

void sysex_insert(unsigned char data) {
    if (save_sysex_head_x < 4) {
        save_sysex_head[save_sysex_head_x++] = data;
    }
    xbuff[xbuftail++] = data;
    xbuftail &= xbufmask;
    if (xbuftail == xbufhead) {
        set_error(SYSEXOVFL);
    }
    if (data == MIDI_EOX) { /* we're done with the message */
        *((long *) (((byte *) buff) + bufftail)) = *((long *)save_sysex_head);
        bufftail = (bufftail + 4) & BUFF_MASK;
        if (bufftail == buffhead) {
            set_error(BUFFOVFL);
        }
    }
}

/* Read all incomming MIDI data. */

pascal short CMTreader(MIDIPacket *ThePacketPtr, long TheRefCon)
{
    /* Set up our A5 world. */
    long    SysA5 = SetA5(TheRefCon);
    short   RetVal = midiMorePacket, i, j;
    unsigned char *mm_data = ThePacketPtr->data;
    register byte data1 = mm_data[1];
        
    if (midi_read_lock) {
        /* Don't want to read packet now, get it later */
        /* DOES THIS REALLY WORK?  WHAT WILL CAUSE AN INTERRUPT
         * TO OCCUR LATER?  THIS IS ONLY USED BY midi_flush, IS
         * BASED ON THE MidiArp CODE FROM APPLE, AND IS UNTESTED - RBD
         */
        RetVal = midiKeepPacket;
        goto alldone;	
    }

    /* see if Packet is an error message */
    if (((ThePacketPtr->flags & midiTypeMask) == midiMgrType) && 
        *((short *) (&(ThePacketPtr->data))) < midiMaxErr) {
        set_error(MIDIMGRERR);
        goto alldone;
    }
        
    /* filter out control changes */
    if (ctrlFilter) {
        register int hibits = *mm_data & 0xF0;
        if (hibits == 0xD0 ||   /* Chan Pressure */
            hibits == 0xE0 ||       /* Pitch Bend */
            hibits == 0xA0 ||       /* Poly Pressure */
            ((hibits == 0xB0) &&    /* Control change (don't count switches) */
             ((data1 < 64) || (data1 > 121)))) {
            /* CONTROL MESSAGE HAS BEEN FILTERED */
            goto alldone;
        }
    } else if (realFilter) {
        register int hibits = *mm_data & 0xF0;
        if (hibits >= 0xF8) goto alldone;
    }

        
    /* if not a continuation, copy the data into cmt_data */
    /* The logic to detect a non-continued
     * packet or a first packet is: "flags bit 1 is clear".
     */
    if ((((ThePacketPtr->flags & midiContMask) == midiNoCont)) && 
        (*mm_data != MIDI_SYSEX)) {
        register byte *cmt_data = ((byte *) buff) + bufftail;
        *((long *) cmt_data) = *((long *) mm_data);

        bufftail = (bufftail + 4) & BUFF_MASK;
        if (bufftail == buffhead) {
            /* filled buffer faster than client emptied it */
            set_error(BUFFOVFL);
        }
    }
        
    /* see if we have a sysex message to copy to buffer */
    if (xbuff && !exclFilter &&
        ((ThePacketPtr->flags & midiContMask) || *mm_data == MIDI_SYSEX)) {
        int i;
        register byte *x_data = xbuff + xbuftail;

        /* iterate over data in message */
        /* NOTE: in the previous implementation, I thought Sysex messages were
         * always starting at the beginning of the buffer, but that didn't work.
         * This implementation assumes nothing -- it is slower because of additional
         * testing and parsing inside the loop, but seems to work.
         */
        for (i = ThePacketPtr->len - 6; i > 0; i--) {
            if (xbuf_flush) {	/* we're searching for beginning of message */
                if (*mm_data == MIDI_SYSEX) {
                    xbuf_flush = false;
                    sysex_insert(MIDI_SYSEX);
                }
            } else {	/* we're scanning to the end of the message */
                if (*mm_data == MIDI_SYSEX) {	/* found it, insert proper EOX */
                    sysex_insert(MIDI_EOX);
                    sysex_insert(MIDI_SYSEX);
                } else if (*mm_data == MIDI_EOX) {	/* found it */
                    sysex_insert(MIDI_EOX);
                    xbuf_flush = true;
                } else sysex_insert(*mm_data);

            }
            mm_data++;
        }
    }
alldone:

    /* Restore the systems A5 world. */
    SetA5(SysA5);
    
    return(RetVal);
}


/* Sign out from the MIDI Manager. */
void finish_midimgr(void)
{
        if (GManualPatch && patch_flag) {
                SavePatch(timePortID, timePortResInfoID, "timePortInfo");
                SavePatch(inputPortID, inputPortResInfoID, "inputPortInfo");
                SavePatch(outputPortID, outputPortResInfoID, "outputPortInfo");
        }
        MIDISignOut(CMTclientID);
}



/* Alert user to Resource Manager Error. */
void
ReportResError(char *Msg)
{
        OSErr   TheErr;
        char    Buf[256];
        
        if ( (TheErr = ResError()) != noErr) {
                gprintf(ERROR, "ResError %d: %s...Aborting.", TheErr, Msg);
                EXIT(1);
        } else {
                /* gprintf(ERROR, "%s OK\n", Msg); */
        }
}


/****************************************************************************
*                                       error handling
* Effect:
*       various error conditions are flagged by setting bits in
*       the global midi_error_flags.  it is up to the client to clear this 
*       word when necessary.
****************************************************************************/

private void set_error(int bit)
{
        midi_error_flags |= (1 << bit);
}


void midi_show_errors()
{
    if (midi_error_flags & (1<<BUFFOVFL)) 
        gprintf(ERROR, "Midi Buffer Overflow Error\n");
    if (midi_error_flags & (1<<MIDIMGRERR)) 
        gprintf(ERROR, "Midi Manager Error\n");
    if (midi_error_flags & (1<<SYSEXOVFL)) 
        gprintf(ERROR, "Midi Sysex Overflow Error\n");
}


/**************** PATCHING CODE ***************/

/*
        MIDIArp Time, Input, and Output Port 
        Info Record Resource ID's.
*/

/* Get previously saved port connections (port info records) */
/* from application's 'port' resource. */
void
PatchPorts(void)
{
        MIDIPortInfoHdl PortInfoH;      /* Handle to port info record. */
        MIDIPortInfoPtr PortInfoP;      /* Pointer to port info record. */
        short                   i, TheErr;
        
        patch_flag = cl_switch("patch");
                
                /* SET UP TIME PORT CONNECTIONS. */
        if (patch_flag)
                PortInfoH = (MIDIPortInfoHdl) GetResource(portResType, timePortResInfoID);
        if (!patch_flag || PortInfoH == NULL) {
                MIDIIDListHdl clients, ports;
                OSErr err;
                
                gprintf(TRANS, "Connecting to MIDI IN and OUT\n");
#ifdef MIDIMGR_VERBOSE
                clients = MIDIGetClients();
                gprintf(TRANS, "clients = %lx\n", clients);
                HLock((Handle) clients);
                
                for (i = 0; i < (*clients)->numIDs; i++) {
                        OSType id = (*clients)->list[i];
                        gprintf(TRANS, "%d: %c%c%c%c\n", i, (char) (id>>24),
                                    (char) ((id >> 16) & 0xFF), (char) ((id >> 8) & 0xFF),
                                    (char) (id & 0xFF));
                }
                ports = MIDIGetPorts('amdr');
                HLock((Handle) ports);
                for (i = 0; i < (*ports)->numIDs; i++) {
                        OSType id = (*ports)->list[i];
                        gprintf(TRANS, "%d: %c%c%c%c\n", i, (char) (id>>24),
                                    (char) ((id >> 16) & 0xFF), (char) ((id >> 8) & 0xFF),
                                    (char) (id & 0xFF));
                }
                HUnlock((Handle) ports);
                HUnlock((Handle) clients);
#endif
                /* the work starts here */
                err = MIDIConnectData('CMT ', 'Cout', 'amdr', 'Aout');
                /* gprintf(TRANS, "Connected CMT.Cout to amdr.Aout: %d\n", err); */
                err = MIDIConnectData('amdr', 'Ain ', 'CMT ', 'Bin ');
                /* gprintf(TRANS, "Connected amdr.Ain to CMT.Bin: %d\n", err); */

                return;
        }
        HLock((Handle) PortInfoH);
        PortInfoP = *PortInfoH;
        if (GetHandleSize((Handle) PortInfoH) != 0)
        {
                        /* Were we supposed to be sync'd to another client? */
                if (PortInfoP->timeBase.clientID != noClient)
                {               
                                    /* Yes, so make that client our time base. */
                        TheErr = MIDIConnectTime(
                                                                    PortInfoP->timeBase.clientID, 
                                                                    PortInfoP->timeBase.portID,
                                                                    CMTclientID, 
                                                                    timePortID 
                                                                    );
#ifdef IGNORE
                                    /* Is the client still signed in? */
                        if (TheErr != midiVConnectErr) 
                        {       
                                                    /* Yes, so set our sync mode to external. */
                                    MIDISetSync(ArpGlobals.TimeRefNum, midiExternalSync);
                        }
#endif
                        
                }
                        /* Were we somebody else's time base? */
                for (i=0; i<PortInfoP->numConnects; i++)
                {
                        MIDIConnectTime(CMTclientID, 
                                                                    timePortID, 
                                                                    PortInfoP->cList[i].clientID, 
                                                                    PortInfoP->cList[i].portID);
                }
        }
        HUnlock((Handle) PortInfoH);
        ReleaseResource((Handle) PortInfoH);
        ReportResError("PatchPorts/ReleaseResource()");
        
                /* SET UP INPUT PORT CONNECTIONS. */
        PortInfoH = (MIDIPortInfoHdl) GetResource(portResType, inputPortResInfoID);
        if (PortInfoH == NULL)
        {
                ReportResError("PatchPorts/GetResource()");
        }
        HLock((Handle) PortInfoH);
        PortInfoP = *PortInfoH;
        if (GetHandleSize((Handle) PortInfoH) != 0)
        {
                        /* Were we connected to anyone? */
                for (i=0; i<PortInfoP->numConnects; i++)
                {
                        MIDIConnectData(CMTclientID, 
                                                                    inputPortID, 
                                                                    PortInfoP->cList[i].clientID, 
                                                                    PortInfoP->cList[i].portID);
                }
        }
        HUnlock((Handle) PortInfoH);
        ReleaseResource((Handle) PortInfoH);
        ReportResError("PatchPorts/GetResource()");
        
                /* SET UP OUTPUT PORT CONNECTIONS. */
        PortInfoH = (MIDIPortInfoHdl) GetResource(portResType, outputPortResInfoID);
        if (PortInfoH == NULL)
        {       
                ReportResError("PatchPorts/GetResource()");
        }
        HLock((Handle) PortInfoH);
        PortInfoP = *PortInfoH;
        if (GetHandleSize((Handle) PortInfoH) != 0) {
                        /* Were we connected to anyone? */
                for (i=0; i<PortInfoP->numConnects; i++)
                {
                        MIDIConnectData(CMTclientID, 
                                                                    outputPortID, 
                                                                    PortInfoP->cList[i].clientID, 
                                                                    PortInfoP->cList[i].portID);
                }
        }
        HUnlock((Handle) PortInfoH);
        ReleaseResource((Handle) PortInfoH);
        ReportResError("PatchPorts/ReleaseResource()");
        
}

/* Save current port connections (port info records) */
/* to application's 'port' resource. */
void
SavePatch(OSType PortID, short PortInfoResID, char *PortInfoResName)
{
        Handle                  PortResH;       /* Handle to ptch resource. */
        CursHandle              WatchCurs;      
        
        WatchCurs = GetCursor(watchCursor);
        HLock((Handle) WatchCurs);
        SetCursor(*WatchCurs);
        HUnlock((Handle) WatchCurs);

        
                /* Remove existing port info resource. */
        PortResH = GetResource(portResType, PortInfoResID);
        /* gprintf(TRANS, "PortResH: %lx, *PortResH: %lx\n", PortResH, *PortResH); */
        if (PortResH) {
                ReportResError("SavePatch/GetResource()");
                RmveResource(PortResH);
                ReportResError("SavePatch/RmveResource()");
                DisposHandle(PortResH);
                UpdateResFile(CurResFile());
                ReportResError("SavePatch/UpdateResFile()");
        }
        
                /*      Get new configurateion. */
        PortResH = (Handle) MIDIGetPortInfo(CMTclientID, PortID);
        
                /*      Save new configurateion. */
        CtoPstr(PortInfoResName);
        AddResource(PortResH, portResType, PortInfoResID,
            (ConstStr255Param) PortInfoResName);
        PtoCstr((unsigned char *) PortInfoResName);
        
        ReportResError("SavePatch/AddResource()");
        WriteResource(PortResH);
        ReportResError("SavePatch/WriteResource()");
        UpdateResFile(CurResFile());
        ReportResError("SavePatch/UpdateResFile()");
        ReleaseResource(PortResH);
        ReportResError("SavePatch/ReleaseResource()");
        
        InitCursor();
}
#endif /* NYQUIST */