playseq.c 33.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 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 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
/*
 *  NINTENDO64 SAMPLE PROGRAM
 *
 *  FILE : playseq.c (for 64DD)
 *
 *  Copyright (C) 1998, NINTENDO Co,Ltd.
 */


#include <ultra64.h>
#include <assert.h>
#include <PR/os.h>
#include <PR/ramrom.h>
#include <PR/gu.h>
#include <PR/leo.h>

#include "dd_audio.h"
#include "playseq.h"


/*
 * Threads
 */
u64	        bootStack[STACKSIZE/8];

static void	mainproc(u8 *);
static OSThread	mainThread;
static u64	mainThreadStack[STACKSIZE/8];

static void	gameproc(u8 *);
static OSThread	gameThread;
static u64	gameThreadStack[STACKSIZE/8];

/*
 * For PI manager
 */
static OSMesgQueue PiMessageQ;
static OSMesg      PiMessages[DMA_QUEUE_SIZE];

/*
 * For 64DD
 */
static OSMesgQueue diskQ;
static OSMesg      diskQBuf;

static OSMesg      LeoMessages[NUM_LEO_MESGS];

static LEODiskID   diskID;
static LEOCmd      cmdBlock;

void DiskInitialize(void);
void CheckDiskInsert(void);
s32  CheckDiskEject(void);
void DiskRead(u32, void *, u32);

/*
 * For synchronization
 */
static OSMesgQueue retraceMessageQ;
static OSMesg      retraceMessageBuf;

static OSMesgQueue taskMessageQ;
static OSMesg      taskMessageBuf;

static OSMesgQueue dmaMessageQ;
static OSMesg      dmaMessageBuf[DMA_QUEUE_SIZE];

static OSMesgQueue resetMessageQ;
static OSMesg      resetMessageBuf;

/*
 * For audio
 */
static ALGlobals g;
static u8        audioHeap[AUDIO_HEAP_SIZE];
static ALHeap    hp;

static ALSynConfig  c;
static ALSeqpConfig seqc;

static s32 curBuf = 0;
static s32 curAudioBuf = 1;

/*
 * Double-buffer
 */
static OSTask *tlist[2];
static Acmd   *cmdList[2];

/*
 * Triple-buffer
 */
static s16 audioSamples[3] = {0, 0, 0};
static s16 *audioBuffer[3];

/*
 * For vibrato and tremelo
 */
static ALMicroTime initOsc(void **oscState, f32 *initVal, u8 oscType,
                           u8 oscRate, u8 oscDepth, u8 oscDelay);
static ALMicroTime updateOsc(void *oscState, f32 *updateVal);
static void        stopOsc(void *oscState);

/*
 * For dma callback routine
 */
#define NBUFFERS 64

typedef struct 
{
    ALLink node;
    int    startAddr;
    u32    lastFrame;
    char   *ptr;
} DMABuffer;

typedef struct 
{
    u8        initialized;
    DMABuffer *firstUsed;
    DMABuffer *firstFree;

} DMAState;

static OSPiHandle *cartromHandle;
static OSPiHandle *driveromHandle;

static OSIoMesg dmaIOMesgBuf[DMA_QUEUE_SIZE];
static s32      nextDMA = 0;

DMAState  dmaState;
DMABuffer dmaBuffs[NBUFFERS];
u32       gFrameCt;


s32 dmaCallBack(s32 addr, s32 len, void *state)
{
    s32         
      delta,
      addrEnd,
      buffEnd;
    u32
      tmp;
    DMABuffer  
      *dmaPtr,
      *lastDmaPtr;
    void 
      *freeBuffer;
    OSPiHandle
      *piHandle;
    OSIoMesg
      *ioMesg;


    /* check address (device flag) */
    tmp = addr & DDROM_FLAG;

    /* When in DDROM */
    if(tmp == DDROM_FLAG) {

      piHandle = driveromHandle;
      addr &= 0x0fffffff;
    } 

    /* When in other media */
    else {

      /* When in RAM */
      if(tmp)
	return (osVirtualToPhysical((void *)addr));

      /* When in CARTRIDGE ROM */
#ifdef FINAL
      piHandle = cartromHandle;
#else
      osSyncPrintf("Error : Data in CARTRIDGE ROM\n");
#endif
    }


    lastDmaPtr = 0;
    dmaPtr = dmaState.firstUsed;
    addrEnd = addr+len;
 
    while(dmaPtr)  /* see if buffer is already set up */
    {

        buffEnd = dmaPtr->startAddr + MAX_BUFFER_LENGTH;
        if(dmaPtr->startAddr > addr) /* since buffers are ordered */
            break;                   /* abort if past possible */

        else if(addrEnd <= buffEnd) /* yes, found one */
        {
            dmaPtr->lastFrame = gFrameCt; /* mark it used */
            freeBuffer = dmaPtr->ptr + addr - dmaPtr->startAddr;
            return (int) osVirtualToPhysical(freeBuffer);
        }
        lastDmaPtr = dmaPtr;
        dmaPtr = (DMABuffer*)dmaPtr->node.next;
    }

    /* get here, and you didn't find a buffer, so dma a new one */

    /* get a buffer from the free list */
    dmaPtr = dmaState.firstFree;

    assert(dmaPtr);  /* be sure you have a buffer */

    dmaState.firstFree = (DMABuffer*)dmaPtr->node.next;
    alUnlink((ALLink*)dmaPtr);

    /* add it to the used list */
    if(lastDmaPtr) /* normal procedure */
    {
        alLink((ALLink*)dmaPtr,(ALLink*)lastDmaPtr);
    }
    else if(dmaState.firstUsed) /* jam at begining of list */
    {
        lastDmaPtr = dmaState.firstUsed;
        dmaState.firstUsed = dmaPtr;
        dmaPtr->node.next = (ALLink*)lastDmaPtr;
        dmaPtr->node.prev = 0;
        lastDmaPtr->node.prev = (ALLink*)dmaPtr;
    }
    else /* no buffers in list, this is the first one */
    {
        dmaState.firstUsed = dmaPtr;
        dmaPtr->node.next = 0;
        dmaPtr->node.prev = 0;
    }
    
    freeBuffer = dmaPtr->ptr;
    delta = addr & 0x1;
    addr -= delta;
    dmaPtr->startAddr = addr;
    dmaPtr->lastFrame = gFrameCt;  /* mark it */

    ioMesg = &dmaIOMesgBuf[nextDMA ++];

    ioMesg->hdr.pri      = OS_MESG_PRI_NORMAL;
    ioMesg->hdr.retQueue = &dmaMessageQ;
    ioMesg->dramAddr     = freeBuffer;
    ioMesg->devAddr      = addr;
    ioMesg->size         = MAX_BUFFER_LENGTH;
    
    if(tmp)
      piHandle->transferInfo.cmdType = OS_OTHERS;

    osEPiStartDma(piHandle, ioMesg, OS_READ);


    return (int) osVirtualToPhysical(freeBuffer) + delta;
}


ALDMAproc dmaNew(DMAState **state)
{
    int i;


    if(!dmaState.initialized)  /* only do this once */
    {
        dmaState.firstFree = &dmaBuffs[0];
        for (i=0; i<NBUFFERS-1; i++)
        {
            alLink((ALLink*)&dmaBuffs[i+1],(ALLink*)&dmaBuffs[i]);
            dmaBuffs[i].ptr = alHeapAlloc(&hp, 1, MAX_BUFFER_LENGTH);
        }

        dmaState.initialized = 1;
    }

    *state = &dmaState;  /* state is never used in this case */


    /* Initialize device handle */
    cartromHandle  = osCartRomInit();
    driveromHandle = osDriveRomInit();


    return dmaCallBack;
}


void CleanDMABuffs(void)
{
    DMABuffer
      *dmaPtr,
      *nextPtr;


    dmaPtr = dmaState.firstUsed;
    while(dmaPtr)
    {
        nextPtr = (DMABuffer*)dmaPtr->node.next;

        /* Can change this value.  Should be at least one.  */
        /* Larger values mean more buffers needed, but fewer DMA's */

        if(dmaPtr->lastFrame + 2  < gFrameCt) /* remove from used list */
        {
            if(dmaState.firstUsed == dmaPtr)
                dmaState.firstUsed = (DMABuffer*)dmaPtr->node.next;
            alUnlink((ALLink*)dmaPtr);
            if(dmaState.firstFree)
                alLink((ALLink*)dmaPtr,(ALLink*)dmaState.firstFree);
            else
            {
                dmaState.firstFree = dmaPtr;
                dmaPtr->node.next = 0;
                dmaPtr->node.prev = 0;
            }
        }
        dmaPtr = nextPtr;
    }
}


/***********************************************************************
 *    initOsc, updateOsc and stopOsc are callbacks used to implement
 *    LFO's for vibrato and tremelo. Type values are set in the bank.inst
 *    file, and should always be different between vibrato and tremelo.
 *    Your initOsc routine should then be able to distinguish based on this
 *    value whether the LFO is for tremelo or vibrato. The audio library
 *    does not use the type value to know, but uses a different method, so
 *    applications are free to use any values 1-255 for types. (A type of
 *    zero means no vibrato or no tremelo.) In the initOsc routine, the
 *    application initializes the oscillator, allocates memory for the
 *    oscState and stores a pointer to that memory in the oscState handle.
 *    This pointer will be handed back to the application at each updateOsc
 *    call. The initVal is a pointer to either a u8, when the osc is a tremelo
 *    oscillator, or a f32 when the oscillator is a vibrato oscillator.
 *    This value should always be set. In the case of tremelo oscillators,
 *    the u8 should be a volume value from 0-127.  In the case of the vibrato
 *    oscillator, the f32 is a ratio that the original pitch of the note should
 *    be multiplied by.  A ratio of 1.0 will produce unity pitch, while a value
 *    of 0.5 will produce one octave lower, and 2.0 will produce one octave higher.
 *    initOsc returns a deltaTime in microseconds until the first call to
 *    updateOsc. If a deltaTime of zero is returned the initVal will be used
 *    but no further calls to the oscillator will be made. When an updateOsc
 *    call occurs the application should do any necessary calculations to update
 *    the oscillator, set the value pointed to by updateVal, and return the
 *    time, in microseconds, until the next updateOsc call.  When a stopOsc
 *    call occurs, the application should do any necessary cleaning up, and
 *    freeing of memory. Given below are several examples of how to implement
 *    an LFO to control tremelo and vibrato.
 *****************************************************************************/

/**********************************************************************
 *    OscType may be assigned in any way suited to the application. In
 *    this example, oscType's are assigned as follows:
 *    oscType = 1     A tremelo that uses a sin function
 *    oscType = 2     A tremelo that uses a square wave
 *    oscType = 3     A tremelo that uses a descending sawtooth
 *    oscType = 4     A tremelo that uses an ascending sawtooth
 *    oscType = 128   A vibrato that uses a sin function
 *    oscType = 129   A vibrato that uses a square wave
 *    oscType = 130   A vibrato that uses a descending sawtooth
 *    oscType = 131   A vibrato that uses an ascending sawtooth
 **********************************************************************/

#define  TREMELO_SIN        1
#define  TREMELO_SQR        2
#define  TREMELO_DSC_SAW    3
#define  TREMELO_ASC_SAW    4
#define  VIBRATO_SIN        128
#define  VIBRATO_SQR        129
#define  VIBRATO_DSC_SAW    130
#define  VIBRATO_ASC_SAW    131

#define  OSC_HIGH   0
#define  OSC_LOW    1
#define  TWO_PI     6.2831853

/*****************************************************************************
 *   oscDepth, oscRate and oscDelay may be used in anyway deemed appropriate
 *   by the programmer. These values are not used by the sequence player, but
 *   merely passed to the init routine. In this example, oscDelay is converted
 *   to microseconds by multiplying by 0x4000. But many other methods could have
 *   been chosen. In the vibrato examples, oscDepth is converted by the routine
 *   _depth2Cents.  Cents can then easily be converted to ratio. For the tremelo
 *   examples, oscDepth is the max depth on the volume scale of 0-127. Sin
 *   oscillators are implemented using the sinf() library call.
 *****************************************************************************/

typedef struct {  
    u8      rate;
    u8      depth;
    u8      oscCount;
} defData;

typedef struct {
    u8      halfdepth;
    u8      baseVol;
} tremSinData;
    
typedef struct {
    u8      curVal;
    u8      hiVal;
    u8      loVal;
} tremSqrData;

typedef struct {
    u8      baseVol;
    u8      depth;
} tremSawData;
    
typedef struct {
    f32     depthcents;
} vibSinData;

typedef struct {
    f32     loRatio;
    f32     hiRatio;
} vibSqrData;

typedef struct {
    s32     hicents;
    s32     centsrange;
} vibDSawData;

typedef struct {
    s32     locents;
    s32     centsrange;
} vibASawData;

typedef struct oscData_s {
    struct oscData_s  *next;
    u8      type;
    u8      stateFlags;
    u16     maxCount;
    u16     curCount;
    union {
        defData         def;
        tremSinData     tsin;
        tremSqrData     tsqr;
        tremSawData     tsaw;
        vibSinData      vsin;
        vibSqrData      vsqr;
        vibDSawData     vdsaw;
        vibASawData     vasaw;
    } data;        
} oscData;

/*
 * Number of osc states needed. In worst case will need two for each
 * voice. But if tremelo and vibrato not used on all instruments will
 * need less.
 */
#define  OSC_STATE_COUNT    2*MAX_VOICES 
oscData  *freeOscStateList;
oscData  oscStates[OSC_STATE_COUNT];


/************************************************************************
 *   _depth2Cents()  convert a u8 (0-255) to a cents value. Convert using
 *   1.03099303^(depth). This gives an exponential range of values from
 *   1 to 2400.  (2400 cents is 2 octaves). Lots of small values for
 *   good control of depth in musical applications, and a couple of
 *   really broad ranges for special effects.
 ************************************************************************/
f32 _depth2Cents(u8 depth)
{
    f32     x = 1.03099303;
    f32     cents = 1.0;

    while(depth)
    {
        if(depth & 1)
            cents *= x;
        x *= x;
        depth >>= 1;
    }

    return(cents);
}


ALMicroTime initOsc(void **oscState, f32 *initVal,u8 oscType,
                    u8 oscRate,u8 oscDepth,u8 oscDelay)
{
    oscData         *statePtr;
    ALMicroTime     deltaTime = 0;


    if(freeOscStateList)  /* yes there are oscStates available */
    {
        statePtr = freeOscStateList;
        freeOscStateList = freeOscStateList->next;
        statePtr->type = oscType;
        *oscState = statePtr;

        /*
         * Convert delay into usec's, In this example, multiply by
         * 0x4000, but could easily use another conversion method.
         */
        deltaTime = oscDelay * 0x4000;

        switch(oscType) /* set the initVal */
        {
            case TREMELO_SIN:
                statePtr->curCount = 0;
                statePtr->maxCount = 259-oscRate; /* gives values 4-259 */
                statePtr->data.tsin.halfdepth = oscDepth >> 1;
                statePtr->data.tsin.baseVol = AL_VOL_FULL - statePtr->data.tsin.halfdepth;
                *initVal = (f32)statePtr->data.tsin.baseVol;
                break;

            case TREMELO_SQR:
                statePtr->maxCount = 256-oscRate; /* values from 1-256 */
                statePtr->curCount = statePtr->maxCount;
                statePtr->stateFlags = OSC_HIGH;
                statePtr->data.tsqr.loVal = AL_VOL_FULL-oscDepth;
                statePtr->data.tsqr.hiVal = AL_VOL_FULL;
                statePtr->data.tsqr.curVal = AL_VOL_FULL;
                *initVal = (f32)AL_VOL_FULL;
                break;

            case TREMELO_DSC_SAW:
                statePtr->maxCount = 256-oscRate;
                statePtr->curCount = 0;
                statePtr->data.tsaw.depth = oscDepth;
                statePtr->data.tsaw.baseVol = AL_VOL_FULL;
                *initVal = (f32)statePtr->data.tsaw.baseVol;
                break;

            case TREMELO_ASC_SAW: 
                statePtr->maxCount = 256-oscRate;
                statePtr->curCount = 0;
                statePtr->data.tsaw.depth = oscDepth;
                statePtr->data.tsaw.baseVol = AL_VOL_FULL - oscDepth;
                *initVal = (f32)statePtr->data.tsaw.baseVol;
                break;           

            case VIBRATO_SIN:
                statePtr->data.vsin.depthcents = _depth2Cents(oscDepth);
                statePtr->curCount = 0;
                statePtr->maxCount = 259-oscRate; /* gives values 4-259 */
                *initVal = 1.0f; /* start at unity pitch */
                break;

            case VIBRATO_SQR:
                {
                    s32     cents;
                    statePtr->maxCount = 256-oscRate; /* values from 1-256 */
                    statePtr->curCount = statePtr->maxCount;
                    statePtr->stateFlags = OSC_HIGH;
                    cents = _depth2Cents(oscDepth);
                    statePtr->data.vsqr.loRatio = alCents2Ratio(-cents);
                    statePtr->data.vsqr.hiRatio = alCents2Ratio(cents);
                    *initVal = statePtr->data.vsqr.hiRatio;
                }
                break;
                    
            case VIBRATO_DSC_SAW:
                {
                    s32     cents;
                    statePtr->maxCount = 256-oscRate; /* values from 1-256 */
                    statePtr->curCount = statePtr->maxCount;
                    cents = _depth2Cents(oscDepth);
                    statePtr->data.vdsaw.hicents = cents;
                    statePtr->data.vdsaw.centsrange = 2 * cents;
                    *initVal = alCents2Ratio(statePtr->data.vdsaw.hicents);
                }
                break;
                
            case VIBRATO_ASC_SAW:
                {
                    s32     cents;
                    statePtr->maxCount = 256-oscRate; /* values from 1-256 */
                    statePtr->curCount = statePtr->maxCount;
                    cents = _depth2Cents(oscDepth);
                    statePtr->data.vasaw.locents = -cents;
                    statePtr->data.vasaw.centsrange = 2 * cents;
                    *initVal = alCents2Ratio(statePtr->data.vasaw.locents);
                }
                break;

        }
    }
    return(deltaTime);  /* if there are no oscStates, return zero, but if
                           oscState was available, return delay in usecs */
}


ALMicroTime updateOsc(void *oscState, f32 *updateVal)
{
    f32             tmpFlt;
    oscData         *statePtr = (oscData*)oscState;
    ALMicroTime     deltaTime = AL_USEC_PER_FRAME; /* in this example callback every */
                                              /* frame, but could be at any interval */

    switch(statePtr->type)   /* perform update calculations */
    {
        case TREMELO_SIN:
            statePtr->curCount++;
            if(statePtr->curCount >= statePtr->maxCount)
                statePtr->curCount = 0;
            tmpFlt = (f32)statePtr->curCount / (f32)statePtr->maxCount;
            tmpFlt = sinf(tmpFlt*TWO_PI);
            tmpFlt = tmpFlt * (f32)statePtr->data.tsin.halfdepth;
            *updateVal = (f32)statePtr->data.tsin.baseVol + tmpFlt;
            break;

        case TREMELO_SQR:
            if(statePtr->stateFlags == OSC_HIGH)
            {
                *updateVal = (f32)statePtr->data.tsqr.loVal;
                statePtr->stateFlags = OSC_LOW;
            }
            else
            {
                *updateVal = (f32)statePtr->data.tsqr.hiVal;
                statePtr->stateFlags = OSC_HIGH;
            }
            deltaTime *= statePtr->maxCount;
            break;
            
        case TREMELO_DSC_SAW:
            statePtr->curCount++;
            if(statePtr->curCount > statePtr->maxCount)
                statePtr->curCount = 0;
            
            tmpFlt = (f32)statePtr->curCount / (f32)statePtr->maxCount;
            tmpFlt *= (f32)statePtr->data.tsaw.depth;
            *updateVal = (f32)statePtr->data.tsaw.baseVol - tmpFlt;
            break;
            
        case TREMELO_ASC_SAW: 
            statePtr->curCount++;
            if(statePtr->curCount > statePtr->maxCount)
                statePtr->curCount = 0;
            tmpFlt = (f32)statePtr->curCount / (f32)statePtr->maxCount;
            tmpFlt *= (f32)statePtr->data.tsaw.depth;
            *updateVal = (f32)statePtr->data.tsaw.baseVol + tmpFlt;
            break;

        case VIBRATO_SIN:
            /* calculate a sin value (from -1 to 1) and multiply it by depthcents.
               Then convert cents to ratio. */

            statePtr->curCount++;
            if(statePtr->curCount >= statePtr->maxCount)
                statePtr->curCount = 0;
            tmpFlt = (f32)statePtr->curCount / (f32)statePtr->maxCount;
            tmpFlt = sinf(tmpFlt*TWO_PI) * statePtr->data.vsin.depthcents;
            *updateVal = alCents2Ratio((s32)tmpFlt);
            break;
            
        case VIBRATO_SQR:
            if(statePtr->stateFlags == OSC_HIGH)
            {
                statePtr->stateFlags = OSC_LOW;
                *updateVal = statePtr->data.vsqr.loRatio;
            }
            else
            {
                statePtr->stateFlags = OSC_HIGH;
                *updateVal = statePtr->data.vsqr.hiRatio;
            }
            deltaTime *= statePtr->maxCount;
            break;

        case VIBRATO_DSC_SAW:
            statePtr->curCount++;
            if(statePtr->curCount > statePtr->maxCount)
                statePtr->curCount = 0;
            tmpFlt = (f32)statePtr->curCount / (f32)statePtr->maxCount;
            tmpFlt *= (f32)statePtr->data.vdsaw.centsrange;
            tmpFlt = (f32)statePtr->data.vdsaw.hicents - tmpFlt;
            *updateVal = alCents2Ratio((s32)tmpFlt);
            break;
            
        case VIBRATO_ASC_SAW:
            statePtr->curCount++;
            if(statePtr->curCount > statePtr->maxCount)
                statePtr->curCount = 0;
            tmpFlt = (f32)statePtr->curCount / (f32)statePtr->maxCount;
            tmpFlt *= (f32)statePtr->data.vasaw.centsrange;
            tmpFlt += (f32)statePtr->data.vasaw.locents;
            *updateVal = alCents2Ratio((s32)tmpFlt);
            break;
    }
    
    return(deltaTime);
}


void stopOsc(void *oscState)
{
    ((oscData*)oscState)->next = freeOscStateList;
    freeOscStateList = (oscData*)oscState;
}


/*
 * BOOT
 */
boot(void *arg)
{
    osInitialize();

    osCreateThread(&mainThread, 1, (void(*)(void *))mainproc, arg,
		  ((u8 *) mainThreadStack) + STACKSIZE, 10);
    osStartThread(&mainThread);
}


/*
 * Idle thread
 */
static void mainproc(u8 *argv) 
{

    /*
     * Initialize video
     */
    osCreateViManager(OS_PRIORITY_VIMGR);
    osViSetMode(&osViModeTable[OS_VI_NTSC_LAN1]);

    /*
     * Start PI Manager
     */
    osCreatePiManager((OSPri) 150, &PiMessageQ, PiMessages, DMA_QUEUE_SIZE);

    /*
     * Create and start game(main) thread
     */
    osCreateThread(&gameThread, 3, (void(*)(void *))gameproc, argv,
                                 ((u8 *) gameThreadStack) + STACKSIZE, 10);
    osStartThread(&gameThread);

    /*
     * Become the idle thread
     */
    osSetIntMask( OS_IM_ALL );
    osSetThreadPri( 0, 0 );
    for (;;);
}


/*
 * Main(game) thread
 */
static void gameproc(u8 *argv)
{
    ALCSPlayer
        sequencePlayer,
        *seqp = &sequencePlayer;

    ALCSeq
        sequence,
        *seq = &sequence;

    ALBank
        *waveBank;

    Acmd
        *cmdlp;

    OSTask
        *tlistp;

    s16
        *audioOp;

    s32
        frameSize,
        minFrameSize,
        buf,
        clcount,
        samplesLeft = 0;

    u32
        i,
        tmp_u32;

    f32
        fsize;

    oscData
        *oscStatePtr;
    

    /*
     * Message queue for PI manager return messages
     */
    osCreateMesgQueue(&dmaMessageQ, dmaMessageBuf, DMA_QUEUE_SIZE);

    /*
     * Set up message queue for TASK interrupts
     */
    osCreateMesgQueue(&taskMessageQ, &taskMessageBuf, 1);
    osSetEventMesg(OS_EVENT_SP, &taskMessageQ, NULL);

    osSendMesg(&taskMessageQ, NULL, OS_MESG_BLOCK);

    /*
     * Set up message queue for video interrupts
     */
    osCreateMesgQueue(&retraceMessageQ, &retraceMessageBuf, 1);
    osViSetEvent(&retraceMessageQ, NULL, NUM_FIELDS);
    
    /*
     * Set up message queue for preNMI interrupts
     */
    osCreateMesgQueue(&resetMessageQ, &resetMessageBuf, 1);
    osSetEventMesg(OS_EVENT_PRENMI, &resetMessageQ, NULL);

    /*
     * Audio heap
     */
    alHeapInit(&hp, (u8 *) audioHeap, AUDIO_HEAP_SIZE);

    /*
     * Allocate storage for command list and task headers
     */
    cmdList[0] = alHeapAlloc(&hp, 1, MAX_CLIST_SIZE*sizeof(Acmd));
    cmdList[1] = alHeapAlloc(&hp, 1, MAX_CLIST_SIZE*sizeof(Acmd));

    tlist[0] = alHeapAlloc(&hp, 1, sizeof(OSTask));
    tlist[1] = alHeapAlloc(&hp, 1, sizeof(OSTask));

    audioBuffer[0] = alHeapAlloc(&hp, 1, sizeof(s32)*MAX_AUDIO_LENGTH);
    audioBuffer[1] = alHeapAlloc(&hp, 1, sizeof(s32)*MAX_AUDIO_LENGTH);
    audioBuffer[2] = alHeapAlloc(&hp, 1, sizeof(s32)*MAX_AUDIO_LENGTH);

    /*
     * Initialize 64DD
     */
    DiskInitialize();

    /*
     * Read .ctl file
     */
    tmp_u32 = (u32)_wavebankSegmentDiskEnd - (u32)_wavebankSegmentDiskStart;
    DiskRead((u32)_wavebankSegmentDiskStart, waveBankFile, tmp_u32);

    /*
     * Read .tbl file
     */
    tmp_u32 = (u32)_wavetableSegmentDiskEnd - (u32)_wavetableSegmentDiskStart;
    DiskRead((u32)_wavetableSegmentDiskStart, waveTableFile, tmp_u32);

    dd_alBnkfNew((ALBankFile *)waveBankFile, (u8 *)waveTableFile);
    waveBank = ((ALBankFile *)waveBankFile)->bankArray[0];

    /*
     * Read sequence data
     */
    tmp_u32 = (u32)_seqSegmentDiskEnd - (u32)_seqSegmentDiskStart;
    DiskRead((u32)_seqSegmentDiskStart, seqData, tmp_u32);

    /*
     * Initialize DAC output rate
     */
    c.outputRate = osAiSetFrequency(OUTPUT_RATE);

    fsize = (f32) NUM_FIELDS * c.outputRate / (f32) 60;
    frameSize = (s32) fsize;
    if (frameSize < fsize)
        frameSize++;
    if (frameSize & 0xf)
        frameSize = (frameSize & ~0xf) + 0x10;
    minFrameSize = frameSize - 16;

    /*
     * Audio synthesizer initialization
     */
    c.maxVVoices = MAX_VOICES;
    c.maxPVoices = MAX_VOICES;
    c.maxUpdates = MAX_UPDATES;
    c.dmaproc    = &dmaNew;
    c.heap       = &hp;
    c.fxType	 = AL_FX_SMALLROOM;

    alInit(&g, &c);

    /*
     * For vibrato and tremelo
     */
    freeOscStateList = &oscStates[0];
    oscStatePtr = &oscStates[0];
    for(i=0;i<(OSC_STATE_COUNT-1);i++)
    {
        oscStatePtr->next = &oscStates[i+1];
        oscStatePtr = oscStatePtr->next;
    }
    oscStatePtr->next = 0;  /* set last pointer to zero */
    
    /*
     * Sequence player initialization 
     */
    seqc.maxVoices      = MAX_VOICES;
    seqc.maxEvents      = EVT_COUNT;
    seqc.maxChannels    = 16;
    seqc.heap           = &hp;
    seqc.initOsc        = &initOsc;
    seqc.updateOsc      = &updateOsc;
    seqc.stopOsc        = &stopOsc;
#ifdef _DEBUG
    seqc.debugFlags     = NO_VOICE_ERR_MASK |NOTE_OFF_ERR_MASK | NO_SOUND_ERR_MASK;
#endif

    alCSPNew(seqp, &seqc);

    /*
     * Allocate wavebank and sequence data
     */
    alCSPSetBank(seqp, waveBank);
    alCSeqNew(seq, seqData);
    alCSPSetSeq(seqp, seq);

    /*
     * Main loop 
     */
    while (1){

        alCSPPlay(seqp);

        /*
         * Sync up on vertical retrace - read more than 1 to be sure!
         */
        (void)osRecvMesg(&retraceMessageQ, NULL, OS_MESG_BLOCK);
        (void)osRecvMesg(&retraceMessageQ, NULL, OS_MESG_BLOCK);

	/*
	 * Note that this must be a do-while in order for seqp's state to
	 * get updated during the alAudioFrame processing.
	 */
       do {

            /*
             * Where the task list goes in DRAM
             */
            tlistp = tlist[curBuf];
            cmdlp = cmdList[curBuf];       

            /*
             * Where the audio goes in DRAM
             */
            buf = curAudioBuf % 3;
            audioOp = (s16 *) osVirtualToPhysical(audioBuffer[buf]);
            audioSamples[buf] = 16 + (frameSize - samplesLeft + EXTRA_SAMPLES) & ~0xf;
            if (audioSamples[buf] < minFrameSize)
                audioSamples[buf] = minFrameSize;

            /*
             * Call the frame handler
             */
            cmdlp = alAudioFrame(cmdlp, &clcount, audioOp, audioSamples[buf]);
            
            /*
             * Build the audio task
             */       
            tlistp->t.type            = M_AUDTASK;
            tlistp->t.flags           = 0x0;
            tlistp->t.ucode_boot      = (u64 *)rspbootTextStart;
            tlistp->t.ucode_boot_size = ((s32)rspbootTextEnd -
                                         (s32)rspbootTextStart);
            tlistp->t.ucode           = (u64 *) aspMainTextStart;
            tlistp->t.ucode_size      = SP_UCODE_SIZE;
            tlistp->t.ucode_data      = (u64 *) aspMainDataStart;
            tlistp->t.ucode_data_size = SP_UCODE_DATA_SIZE;
            tlistp->t.data_ptr        = (u64 *) cmdList[curBuf];
            tlistp->t.data_size       = (cmdlp - cmdList[curBuf]) * sizeof(Acmd);
            
            /*
             * Video does nothing - just syncs up on the frame boundary.
             */
            (void)osRecvMesg(&retraceMessageQ, NULL, OS_MESG_BLOCK);

            /*
             * Find out how many samples left in the currently running
             * audio buffer
             */
            samplesLeft = IO_READ(AI_LEN_REG)>>2;

            /*
             * The last task should have finished before the frame message
             * so this just clears the message queue
             */
            (void)osRecvMesg(&taskMessageQ, NULL, OS_MESG_BLOCK);

            /*
             * Point the DAC at the next buffer
             */
            buf = (curAudioBuf-1) % 3;

            osAiSetNextBuffer(audioBuffer[buf], audioSamples[buf]<<2);

            /*
             * Empty the dma queue to make sure all DMAs have completed.
             * If the app blocks here it is a bug since resources must
             * be managed so that all DMAs complete.
             */
            for (i=0; i<nextDMA; i++)
                if (osRecvMesg(&dmaMessageQ, NULL, OS_MESG_NOBLOCK) == -1)
                    osSyncPrintf("Dma not done\n");

            /*
             * Flush the cache and start task on RSP
             */
            osWritebackDCacheAll();
            osSpTaskStart(tlistp);

            CleanDMABuffs();

	    /*
	     * Check preNMI
	     */
	    if(!osRecvMesg(&resetMessageQ, NULL, OS_MESG_NOBLOCK))
	      LeoReset();

            /*
             * Swap buffers for wavetable storage and output
             */
            gFrameCt++;
            curBuf ^= 1; 
            curAudioBuf++; 
            nextDMA = 0;

        } while (seqp->state != AL_STOPPED);

	alCSeqNew(seq, seqData);
    }

    alCSPStop(seqp);
    alClose(&g);
}


/*
 * Initialize 64DD
 */
void DiskInitialize(void)
{
  s32
    error;


  osCreateMesgQueue(&diskQ, &diskQBuf, 1);
  error = LeoCreateLeoManager((OSPri)OS_PRIORITY_LEOMGR - 1,
			      (OSPri)OS_PRIORITY_LEOMGR,
			      LeoMessages, NUM_LEO_MESGS);

  if(error == LEO_ERROR_DEVICE_COMMUNICATION_FAILURE){
    osSyncPrintf("Error %d\n", error);
    osSyncPrintf("Please read 64DD manual.\n");
    for(;;);
  }
    
  CheckDiskInsert();

  if(bcmp((void *)&leoBootID, (void *)&diskID, sizeof(LEODiskID))){
    osSyncPrintf("You insert a bad disk. Please reboot 64DD.\n");
    for(;;);
  }

}


/*
 * Disk insert check
 */
void CheckDiskInsert(void)
{
  s32
    loop_flag = 1,
    error,
    old_error = -100;
    

  do {

    LeoReadDiskID(&cmdBlock, &diskID, &diskQ);
    osRecvMesg(&diskQ, (OSMesg *)&error, OS_MESG_BLOCK);
      
    switch(error) {
      
    case LEO_ERROR_GOOD:
      loop_flag = 0;
      break;
	
    case LEO_ERROR_QUEUE_FULL:
      break;
	
    case LEO_ERROR_EJECTED_ILLEGALLY_RESUME:
      if(error != old_error){
	osSyncPrintf("Error %d\n", error);
	osSyncPrintf("Please don't eject the disk when the accsess-lamp is blinking.\n");
      }
      break;

    case LEO_ERROR_MEDIUM_NOT_PRESENT:
      if(error != old_error){
	osSyncPrintf("Error %d\n", error);
	osSyncPrintf("Please insert a disk.\n");
      }
      break;

    case LEO_ERROR_INCOMPATIBLE_MEDIUM_INSTALLED:
      osSyncPrintf("Error %d\n", error);
      osSyncPrintf("Please read 64DD manual.\n");
      while(!CheckDiskEject());
      break;

    case LEO_ERROR_DIAGNOSTIC_FAILURE:
      osSyncPrintf("Error %d\n", error);
      osSyncPrintf("Please eject the disk and then insert it again.\n");
      while(!CheckDiskEject());
      break;

    case LEO_ERROR_COMMAND_TERMINATED:
    default:
      osSyncPrintf("Error %d\n", error);
      osSyncPrintf("Please read 64DD manual.\n");
      for(;;);
    }

    old_error = error;
    
  } while(loop_flag);

}


/*
 * Disk eject check
 */
s32 CheckDiskEject(void) 
{
  s32
    loop_flag = 1,
    error;


  do {

    LeoSpdlMotor(&cmdBlock, LEO_MOTOR_SLEEP, &diskQ);
    osRecvMesg(&diskQ, (OSMesg *)&error, OS_MESG_BLOCK);

    switch(error){

    case LEO_ERROR_GOOD:
    case LEO_ERROR_DIAGNOSTIC_FAILURE:
      error = 0;

    case LEO_ERROR_MEDIUM_NOT_PRESENT:
    case LEO_ERROR_MEDIUM_MAY_HAVE_CHANGED:
    case LEO_ERROR_EJECTED_ILLEGALLY_RESUME:
      loop_flag = 0;
      break;

    case LEO_ERROR_QUEUE_FULL:
      break;

    case LEO_ERROR_COMMAND_TERMINATED:
    default:
      osSyncPrintf("Error %d\n", error);
      osSyncPrintf("Please read 64DD manual.\n");
      for(;;);
    }

  } while(loop_flag);

  return error;
}


/*
 * Read disk (only)
 */
void DiskRead(u32 srcLBA, void *destDRAM, u32 nLBAs)
{
  s32
    loop_flag = 1,
    error;


  do {

    osWritebackDCacheAll();
    LeoReadWrite(&cmdBlock, 
		 OS_READ,
		 srcLBA,
		 destDRAM,
		 nLBAs, 
		 &diskQ);
    osRecvMesg(&diskQ, (OSMesg *)&error, OS_MESG_BLOCK);

    switch(error){

    case LEO_ERROR_GOOD:
      loop_flag = 0;
      break;
	
    case LEO_ERROR_QUEUE_FULL:
      break;
	
    case LEO_ERROR_DIAGNOSTIC_FAILURE:
      osSyncPrintf("Error %d\n", error);
      osSyncPrintf("Please eject the disk and then insert it again.\n");

      do {
	while(!CheckDiskEject());

	CheckDiskInsert();

	if(bcmp((void *)&leoBootID, (void *)&diskID, sizeof(LEODiskID)))
	  osSyncPrintf("You insert a bad disk. Please check the disk.\n");
	else
	  break;

      } while(1);
      break;

    case LEO_ERROR_EJECTED_ILLEGALLY_RESUME:
    case LEO_ERROR_MEDIUM_NOT_PRESENT:
      osSyncPrintf("Error %d\n", error);
      if(error == LEO_ERROR_EJECTED_ILLEGALLY_RESUME)
	osSyncPrintf("Please don't eject the disk when the accsess-lamp is blinking.\n");
      else
	osSyncPrintf("Please insert a disk.\n");

    case LEO_ERROR_MEDIUM_MAY_HAVE_CHANGED:
      do {
	CheckDiskInsert();
	
	if(!bcmp((void *)&leoBootID, (void *)&diskID, sizeof(LEODiskID)))
	  break;

	osSyncPrintf("You insert a bad disk. Please check the disk.\n");

	while(!CheckDiskEject());

      } while(1);
      break;

    case LEO_ERROR_COMMAND_TERMINATED:
    default:
      osSyncPrintf("Error %d\n", error);
      osSyncPrintf("Please read 64DD manual.\n");
      for(;;);
    }

  } while(loop_flag);

}