midiApp.c 16.2 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
#include <ultra64.h>
#include <os.h>
#include <ultralog.h>
#include "midiApp.h"


/* Stacks for the threads and message queues  */
u64     bootStack[STACKSIZE/8];

static void mainproc(char *);
static void gameproc(char *);
static void midiproc(char *);
static void SendBackStuff(u32 *stuff);
static void initAudio(s32 sampleRate);
static void loadAudio(void);
static void CleanDMABuffs(void);

static OSThread	rmonThread;
static OSThread	mainThread;
static OSThread	gameThread;
static OSThread	midiThread;

static u64	rmonThreadStack[RMON_STACKSIZE/8];
static u64	mainThreadStack[STACKSIZE/8];
static u64	gameThreadStack[STACKSIZE/8];
static u64	midiThreadStack[STACKSIZE/8];

/* For PI manager */
#define PI_QUEUE_SIZE  DMA_QUEUE_SIZE + 1  /* enough buffers for all the samples and one midi */
static OSMesg PiMessages[PI_QUEUE_SIZE];
static OSMesgQueue PiMessageQ;

OSMesgQueue taskMessageQ;
OSMesg      taskMessageBuf;

OSMesgQueue audioIntQ;
OSMesg      audioIntBuf;

OSMesgQueue	smplDMAMesgQ;      /* many sample dma's allowed at one time */
OSMesg		smplDMAMesgBuf[DMA_QUEUE_SIZE];
OSIoMesg    smplDMAIOMesgBuf[DMA_QUEUE_SIZE];

OSMesgQueue	midiDMAMesgQ;      /* only one midi dma at a time */
OSMesg		midiDMAMesgBuf;
OSIoMesg    midiDMAIOMesgBuf;


/*  public - shared by rmon and users */
extern OSMesgQueue rmonCalloutMQ;   
extern void rmonMain(void *);
extern void __osGIOInterrupt(s32 value);

/*extern char _seqSegmentRomStart[], _seqSegmentRomEnd[]; */


/* Globals for audio  */
ALHeap          aHeap;
ALGlobals       audioGlbls;
ALSynConfig     synConfig;
ALSeqpConfig    seqConfig;
ALSeqPlayer     seqPlayer;
/* ALSeq           sequence; */
/* ALSeqMarker     startMark,endMark; */
Acmd            *cmdList[2];
OSTask          *tlist[2];               /* globaltask list      */
u32             nextDMA = 0;
/* u32             seqLen; */
/* u8              *seqPtr; */


/* Buffers for storing audio output data, must be 8 byte aligned */
s16    *audioBuffer[2];

char            audioHeap[AUDIO_HEAP_SIZE];

#define         NBUFFERS       80

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

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

} DMAState;

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


boot(void)
{
    
    osInitialize();

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

    osStartThread(&mainThread);
}


s32 dmaCallBack(s32 addr, s32 len, void *state)
{
    void        *freeBuffer;
    int         delta;
    DMABuffer   *dmaPtr,*lastDmaPtr;
    s32         addrEnd,buffEnd;


    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;
    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 */
    osPiStartDma(&smplDMAIOMesgBuf[nextDMA++], OS_MESG_PRI_NORMAL, OS_READ,
                 (u32)addr, freeBuffer, MAX_BUFFER_LENGTH, &smplDMAMesgQ);

    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(&aHeap, 1, MAX_BUFFER_LENGTH);
        }

        dmaState.initialized = 1;
    }

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

    return dmaCallBack;
}

void CleanDMABuffs()
{
    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;
    }
}

static void mainproc(char *argv) 
{    

    osCreateThread(&gameThread, 3, (void(*)(void *))gameproc, argv,
                       (u8*)gameThreadStack+STACKSIZE, 10); 

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

    /* Start PI Mgr for access to cartridge & GIO    */
    osCreatePiManager(OS_PRIORITY_PIMGR, &PiMessageQ, PiMessages,
                  PI_QUEUE_SIZE); 
    osCreateThread(&rmonThread, 0, rmonMain, (void *)0,
                  (u8*)rmonThreadStack+ RMON_STACKSIZE, OS_PRIORITY_RMON );
    osStartThread(&rmonThread);
    osStartThread(&gameThread);  
    
    /* Become the idle thread   */
    osSetIntMask( OS_IM_ALL );
    osSetThreadPri( 0, 0 );
    for (;;);
}

static void midiproc(char *argv)
{
    int         cnt;
    u32         totalSize,blkSize,breakFrame;
    OSMesg      midiMesg;
    u32         *stuff32;
    char        *blkPtr;
    midiBlock   *midiBlkPtr;
    SysExReq    *SEXRptr;
    ALBank      *midiBank;
    
    midiBlkPtr = alHeapAlloc(&aHeap, 1, sizeof(midiBlock));
    SEXRptr = (SysExReq *)midiBlkPtr;
    stuff32 = alHeapAlloc(&aHeap, 1, 4);

    __osGIOInterrupt(GAME_APP_DATA_READY);     
    
    while(1)
    {
        osRecvMesg(&rmonCalloutMQ, NULL, OS_MESG_BLOCK);
        osInvalDCache(midiBlkPtr,sizeof(midiBlock));
        osPiStartDma(&midiDMAIOMesgBuf, OS_MESG_PRI_NORMAL, OS_READ, 
                     RAMROM_APP_READ_ADDR, midiBlkPtr,
                     sizeof(midiBlock), &midiDMAMesgQ);  
        osRecvMesg(&midiDMAMesgQ, NULL, OS_MESG_BLOCK); 
        __osGIOInterrupt(HOST_APP_CMD_READY);


        if(midiBlkPtr->pcktType == STATUS_TYPE)
        {        
            for(cnt=0; cnt < midiBlkPtr->numEvts; cnt++)
            {
		if(midiBlkPtr->mess[cnt].midiByte[0] == 0xFF)  /* system reset */
		{
		    alSeqpStop(&seqPlayer);
		    alSeqpPlay(&seqPlayer);
		}
		else
		    alSeqpSendMidi(&seqPlayer,(long) 0,
                       midiBlkPtr->mess[cnt].midiByte[0],
                       midiBlkPtr->mess[cnt].midiByte[1],
                       midiBlkPtr->mess[cnt].midiByte[2]);   
            }
        }
        else if(midiBlkPtr->pcktType == SYSEX_TYPE)
        {
            switch(SEXRptr->reqType)
            {
                case GET_8:
                    *stuff32 = (u32)*(u8 *)SEXRptr->offset;
                    SendBackStuff(stuff32);
                    break;
                case GET_16:
                    *stuff32 = (u32)*(u16 *)SEXRptr->offset;
                    SendBackStuff(stuff32);
                    break;
                case GET_32:
                    if(SEXRptr->offset == 0)
                        *stuff32 = (u32)&rmonThreadStack[0];  /* gChipDebug; */
                    else
                        *stuff32 = *(u32*)SEXRptr->offset;
                    SendBackStuff(stuff32);
                    break;
                case SET_8:
                    *(u8*)SEXRptr->offset = (u8)SEXRptr->value;
                    break;
                case SET_16:
                    *(u16*)SEXRptr->offset = (u16)SEXRptr->value;
                    break;
                case SET_32:
                    *(u32*)SEXRptr->offset = (u32)SEXRptr->value;
                    break;
                case WRITE_BLOCK:
                    totalSize = SEXRptr->value;
                    blkPtr = (char *)SEXRptr->offset;
                    while(totalSize)
                    {
                        blkSize = MIN(totalSize,RAMROM_BUF_SIZE);
                        osRecvMesg(&rmonCalloutMQ, NULL, OS_MESG_BLOCK);
                        osInvalDCache(blkPtr,blkSize);
                        osPiStartDma(&midiDMAIOMesgBuf, OS_MESG_PRI_NORMAL, OS_READ, 
                                  RAMROM_APP_READ_ADDR, blkPtr, blkSize, &midiDMAMesgQ);  
                        osRecvMesg(&midiDMAMesgQ, NULL, OS_MESG_BLOCK); 
                        __osGIOInterrupt(HOST_APP_CMD_READY);
                        blkPtr+=blkSize;
                        totalSize-=blkSize;
                    }
                    break;
                case START_SEQUENCE:
                    alSeqpPlay(&seqPlayer);
		    alSeqpSendMidi(&seqPlayer,(s32) 0, 0x90, 60, 100);
		    alSeqpSendMidi(&seqPlayer,(s32) 2048, 0x80, 60, 0);
                    break;
                case WRITE_RAMROM:
                    osRecvMesg(&rmonCalloutMQ, NULL, OS_MESG_BLOCK);
                    __osGIOInterrupt(HOST_APP_CMD_READY);
                    break;
                case SET_BANK: /* must be first midi related action */
		    midiBank = (ALBank*)SEXRptr->offset;
		    initAudio(midiBank->sampleRate);
		    osSendMesg(&taskMessageQ, NULL, OS_MESG_BLOCK); 
                    alSeqpSetBank(&seqPlayer,midiBank);
                    break;
                case RESET_BANK:
                    alSeqpStop(&seqPlayer);
                    breakFrame = gFrameCt+10;
                    while(gFrameCt<breakFrame)
                        cnt++;
                    alSeqpSetBank(&seqPlayer,(ALBank*)SEXRptr->offset);
     
/*                    alSeqNew(&sequence, seqPtr, seqLen);      
                    alSeqpSetSeq(&seqPlayer, &sequence); 
                    alSeqNewMarker(&sequence,&startMark,MIDI_LOOP_START);
                    alSeqNewMarker(&sequence,&endMark,MIDI_LOOP_END);
                    alSeqpLoop(&seqPlayer,&startMark,&endMark,LOOP_COUNT);  */
                    alSeqpPlay(&seqPlayer);
                    break;

            }
        }
    }
}

static void SendBackStuff(u32 *stuff)
{
    OSMesg      midiMesg;
    
    /* clear the cache before sending values back */
    osWritebackDCache(stuff,4);
    osPiStartDma(&midiDMAIOMesgBuf, OS_MESG_PRI_NORMAL, OS_WRITE, 
              RAMROM_APP_WRITE_ADDR, stuff, 4, &midiDMAMesgQ);  
    osRecvMesg(&midiDMAMesgQ, NULL, OS_MESG_BLOCK); 
    __osGIOInterrupt(GAME_APP_DATA_READY);
}

static void gameproc(char *argv)
{
    Acmd        *cmdlp;
    OSTask      *tlistp;
    s32         clcount;
    short       *audioOp,i;
    int         curBuf = 0;

/* setup Message queue for PI manager, task, and video */
    osCreateMesgQueue(&smplDMAMesgQ, smplDMAMesgBuf, DMA_QUEUE_SIZE);
    osCreateMesgQueue(&midiDMAMesgQ, &midiDMAMesgBuf, 1);
    osCreateMesgQueue(&taskMessageQ, &taskMessageBuf, 1);
    osSetEventMesg(OS_EVENT_SP, &taskMessageQ, NULL);
    osCreateMesgQueue(&audioIntQ, &audioIntBuf, 1);
    osSetEventMesg(OS_EVENT_AI, &audioIntQ, NULL);
    
    loadAudio();   /* must load the sequence before WriteRam is executed */
    osCreateThread(&midiThread, 4, (void(*)(void *))midiproc, argv,
                  (u8*) midiThreadStack+STACKSIZE, 8);

    osStartThread(&midiThread);


    /* Wait here until init audio has completed. */
    (void)osRecvMesg(&taskMessageQ, NULL, OS_MESG_BLOCK); 

    /* Prime the task queue   */
    osSendMesg(&taskMessageQ, NULL, OS_MESG_BLOCK);

    while(1)
    {
        /* Where the task list goes in DRAM */
        tlistp = tlist[curBuf];
        cmdlp = cmdList[curBuf];
        
        /* Where the audio goes in DRAM    */
        audioOp = (s16 *) osVirtualToPhysical(audioBuffer[curBuf]);

        /* Call the frame handler ask for samples  */
        cmdlp = alAudioFrame(cmdlp, &clcount, audioOp, FRAME_SIZE);
        
        /* Build the audio task */       
        tlistp->t.type = M_AUDTASK;
        tlistp->t.flags = 0x0;
        tlistp->t.ucode_boot = (unsigned long long *) rspbootTextStart;
        tlistp->t.ucode_boot_size = ((int)rspbootTextEnd -
                                     (int)rspbootTextStart);
        tlistp->t.ucode = (unsigned long long *) aspMainTextStart;
        tlistp->t.ucode_data = (unsigned long long *) aspMainDataStart;
        tlistp->t.ucode_size = 4096;
        tlistp->t.ucode_data_size = 1024;
        tlistp->t.data_ptr = (unsigned long long *) cmdList[curBuf];
        tlistp->t.data_size = (cmdlp - cmdList[curBuf]) * sizeof(Acmd);
        
        /* Make sure the last task has completed. */
        (void)osRecvMesg(&taskMessageQ, NULL, OS_MESG_BLOCK);

        /* Point the DAC at the next buffer */
        osAiSetNextBuffer(audioBuffer[curBuf^1], FRAME_SIZE<<2);

        /* sync up to the audio interrupt. */
        (void)osRecvMesg(&audioIntQ, NULL, OS_MESG_BLOCK);

        /* Empty the dma queue to make sure all DMAs have completed */
        for (i=0; i<nextDMA; i++)
            osRecvMesg(&smplDMAMesgQ, NULL, OS_MESG_BLOCK);
        
        /* Send new command list to RSP or emulator */
        osWritebackDCacheAll();
        osSpTaskStart(tlistp);

        /* clean out the dmaBuffers */
        CleanDMABuffs();

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

static void loadAudio(void) 
{

    alHeapInit(&aHeap, audioHeap, AUDIO_HEAP_SIZE);

    cmdList[0] = alHeapAlloc(&aHeap, 1, MAX_CLIST_SIZE*sizeof(Acmd));
    cmdList[1] = alHeapAlloc(&aHeap, 1, MAX_CLIST_SIZE*sizeof(Acmd));
    
    tlist[0] = alHeapAlloc(&aHeap, 1, sizeof(OSTask));
    tlist[1] = alHeapAlloc(&aHeap, 1, sizeof(OSTask));
    
    audioBuffer[0] = alHeapAlloc(&aHeap, 1, sizeof(s32)*MAX_AUDIO_LENGTH);
    audioBuffer[1] = alHeapAlloc(&aHeap, 1, sizeof(s32)*MAX_AUDIO_LENGTH);
    
/*    seqLen = _seqSegmentRomEnd - _seqSegmentRomStart;
    seqPtr = alHeapAlloc(&aHeap, 1, seqLen);
    osPiStartDma(&midiDMAIOMesgBuf, OS_MESG_PRI_NORMAL, OS_READ,
             (u32)_seqSegmentRomStart, seqPtr, seqLen, &midiDMAMesgQ);
    (void) osRecvMesg(&midiDMAMesgQ, NULL, OS_MESG_BLOCK);
    */
}

static void initAudio(s32 sampleRate)     
{
    /* Initialize the DACs */
    synConfig.outputRate = osAiSetFrequency(sampleRate); 
    synConfig.maxVVoices = MAX_VOICES;
    synConfig.maxPVoices = MAX_VOICES;
    synConfig.maxUpdates = MAX_UPDATES;
    synConfig.dmaproc    = &dmaNew;
    synConfig.heap       = &aHeap;
    synConfig.fxType	 = AL_FX_SMALLROOM;
    
    alInit(&audioGlbls, &synConfig);
    
    seqConfig.maxVoices      = MAX_VOICES;
    seqConfig.maxEvents      = MAX_SEQP_EVENTS;
    seqConfig.maxChannels    = MAX_SEQ_CHANNELS;
    seqConfig.heap           = &aHeap;
    seqConfig.initOsc        = 0;
    seqConfig.updateOsc      = 0;
    seqConfig.stopOsc        = 0;
    
        
    alSeqpNew(&seqPlayer, &seqConfig);
/*    alSeqNew(&sequence, seqPtr, seqLen);    
    alSeqpSetSeq(&seqPlayer, &sequence);

    alSeqNewMarker(&sequence,&startMark,MIDI_LOOP_START);
    alSeqNewMarker(&sequence,&endMark,MIDI_LOOP_END);
    alSeqpLoop(&seqPlayer,&startMark,&endMark,LOOP_COUNT);  
    */



}