midiApp.c 15.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 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561

#include <ultra64.h>
#include <ramrom.h>
#include <os.h>
#include <ultralog.h>
#include "midiApp.h"
#define static

/* 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 SendBlock(u32 *offset,u32 numBytes);
static void initAudio(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 */
static OSMesg PiMessages[DMA_QUEUE_SIZE+10];
static OSMesgQueue PiMessageQ;

OSMesgQueue	dmaMessageQ, taskMessageQ, dmaMidiQ;
OSMesg		dmaMessageBuf[DMA_QUEUE_SIZE], taskMessageBuf,  dmaMidiBuf;
OSMesg		dummyMessage ;
OSIoMesg    dmaIOMessageBuf;

OSMesgQueue audioIntQ;
OSMesg      audioIntBuf;

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

extern char _codeSegmentRomStart[], _codeSegmentRomEnd[];


void CleanDMABuffs(void);

/* #define LOGGING_ON */

#ifdef LOGGING_ON
#define LOG_LEN 0x10000
extern u32 osGetCount();
u32     startTime,endTime,deltaTime;
OSLog logger;
OSLog *myLog = &logger;
u32 logData[LOG_LEN];
#define LOOP_COUNT  6
#else
#define LOOP_COUNT -1
#endif


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

/* Buffers for storing audio dma data, must be 8 byte aligned */
u64             garbage1[2];
static short    audioBuffer[2][MAX_AUDIO_LENGTH];
u64             garbage2[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;

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(&dmaIOMesgBuf[nextDMA++], OS_MESG_PRI_NORMAL, OS_READ,
                 (u32)addr, freeBuffer, MAX_BUFFER_LENGTH, &dmaMessageQ);

    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;
    }
}



boot(void *arg)
{
    int i;
    
    osInitialize();

#ifdef LOGGING_ON
    for(i=0;i<STACKSIZE/4;i++)
       ((u32*) mainThreadStack)[i] = 0xABABABAB;
    for(i=0;i<STACKSIZE/4;i++)
       ((u32*) midiThreadStack)[i] = 0xABABABAB;
    for(i=0;i<STACKSIZE/4;i++)
       ((u32*) gameThreadStack)[i] = 0xABABABAB;
#endif

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

    osStartThread(&mainThread);
}

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,
                  DMA_QUEUE_SIZE+10); 
    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 );
    osPause();
}


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

#ifdef LOGGING_ON
    osLogEvent(myLog,106,1,aHeap.base);
#endif
    __osGIOInterrupt(GAME_APP_DATA_READY);     
    
    while(1)
    {
        osRecvMesg(&rmonCalloutMQ, &midiMesg, OS_MESG_BLOCK);
        osPiStartDma(&dmaIOMessageBuf, OS_MESG_PRI_NORMAL, OS_READ, 
                     RAMROM_APP_READ_ADDR, midiBlkPtr,
                     sizeof(midiBlock), &dmaMidiQ);  
        osRecvMesg(&dmaMidiQ, &midiMesg, OS_MESG_BLOCK); 
        __osGIOInterrupt(HOST_APP_CMD_READY);
        osInvalDCache(midiBlkPtr,sizeof(midiBlock));

        if(midiBlkPtr->pcktType == STATUS_TYPE)
        {        
            for(cnt=0; cnt < midiBlkPtr->numEvts; cnt++)
            {
                alSeqpSendMidi(&seqPlayer,(long) 0,
                       midiBlkPtr->mess[cnt].midiByte[0],
                       midiBlkPtr->mess[cnt].midiByte[1],
                       midiBlkPtr->mess[cnt].midiByte[2]);   
            }
        }
    }
}


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

#ifdef LOGGING_ON
    int         maxCmds=0;
    osCreateLog(myLog, logData, LOG_LEN);
#endif
    /* setup Message queue for PI manager, task, and video */
    osCreateMesgQueue(&dmaMessageQ, dmaMessageBuf, DMA_QUEUE_SIZE);
    osCreateMesgQueue(&dmaMidiQ, &dmaMidiBuf, 1);
    osCreateMesgQueue(&taskMessageQ, &taskMessageBuf, 1);
    osSetEventMesg(OS_EVENT_SP, &taskMessageQ, dummyMessage);
    /* Prime the task queue   */
    osSendMesg(&taskMessageQ, dummyMessage, OS_MESG_BLOCK);
    osCreateMesgQueue(&audioIntQ, &audioIntBuf, 1);
    osSetEventMesg(OS_EVENT_AI, &audioIntQ, dummyMessage);

    initAudio();  /* starts sequence also */

    
    osCreateThread(&midiThread, 4, (void(*)(void *))midiproc, argv,
                  (u8*) midiThreadStack+STACKSIZE, 8);

    osStartThread(&midiThread);

    while (seqPlayer.state == AL_PLAYING)  
    {

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

        /* Call the frame handler ask for samples  */
#ifdef LOGGING_ON
        startTime = osGetCount();
#endif
        cmdlp = alAudioFrame(cmdlp, &clcount, audioOp, FRAME_SIZE);
#ifdef LOGGING_ON
        endTime = osGetCount();
        deltaTime = endTime - startTime;
#endif 

        
#ifdef LOGGING_ON
        if(clcount>maxCmds)
            maxCmds=clcount;
#endif
        
        /* 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, &dummyMessage, 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, &dummyMessage, OS_MESG_BLOCK);

        /* Empty the dma queue to make sure all DMAs have completed */
        for (i=0; i<nextDMA; i++)
            osRecvMesg(&dmaMessageQ, &dummyMessage, 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++;
    }

#ifdef LOGGING_ON
    osLogEvent(myLog,200,1,maxCmds);
    osLogEvent(myLog,201,1,(int)mainThreadStack);

    for(i=0;i<STACKSIZE/4;i++)
    {
        if(((u32*) mainThreadStack)[i] != 0xABABABAB)
        {
             osLogEvent(myLog,202,2,(int)mainThreadStack+(4*i),
                       STACKSIZE-(4*i));
             break;
        }
    }
    osLogEvent(myLog,203,1,(int)gameThreadStack);
    for(i=0;i<STACKSIZE/4;i++)
    {
        if(((u32*) gameThreadStack)[i] != 0xABABABAB)
        {
            osLogEvent(myLog,204,2,(int)gameThreadStack+(4*i),
                       STACKSIZE-(4*i));
            break;
        }
    }
    osLogEvent(myLog,205,1,(int)midiThreadStack);
    for(i=0;i<STACKSIZE/4;i++)
    {
        if( ((u32*) midiThreadStack)[i] != 0xABABABAB)
        {
            osLogEvent(myLog,206,2,(int)midiThreadStack+(4*i),
                       STACKSIZE-(4*i));
            break;
        }
    }

    osLogEvent(myLog,207,1,(int)bootStack);
    osLogEvent(myLog,208,1,(int)mainproc);
    osLogEvent(myLog,209,1,(int)gameproc);
    osLogEvent(myLog,210,1,(int)midiproc);
    osLogEvent(myLog,211,1,(int)&rmonThread);
    osLogEvent(myLog,212,1,(int)&mainThread);
    osLogEvent(myLog,213,1,(int)&rmonCalloutMQ);
    osFlushLog(myLog);
#endif

    alSeqpStop(&seqPlayer);
    alClose(&audioGlbls);
    osExit();
}


static void initAudio(void) 
{
    ALBank          *midiBank;
    int             bankLen;
    u8              *seqPtr;

    DMABuffer   *dmaPtr;

    alHeapInit(&aHeap, audioHeap, AUDIO_HEAP_SIZE);

#ifdef LOGGING_ON
    osLogEvent(myLog,100,1,aHeap.cur);
#endif
    
    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));

    
    bankLen = _midibankSegmentRomEnd - _midibankSegmentRomStart;
    midiBankPtr = alHeapAlloc(&aHeap, 1, bankLen);
    osPiStartDma(&dmaIOMessageBuf, OS_MESG_PRI_NORMAL, OS_READ,
             (u32)_midibankSegmentRomStart, midiBankPtr,
             bankLen, &dmaMessageQ);
    (void) osRecvMesg(&dmaMessageQ, &dummyMessage, OS_MESG_BLOCK);
    
    bankLen = _seqSegmentRomEnd - _seqSegmentRomStart;
    seqPtr = alHeapAlloc(&aHeap, 1, bankLen);
    osPiStartDma(&dmaIOMessageBuf, OS_MESG_PRI_NORMAL, OS_READ,
             (u32)_seqSegmentRomStart, seqPtr, bankLen, &dmaMessageQ);
    (void) osRecvMesg(&dmaMessageQ, &dummyMessage, OS_MESG_BLOCK);

    
    /* Initialize the DACs */
    synConfig.outputRate = osAiSetFrequency(OUTPUT_RATE);

    synConfig.maxVVoices = MAX_VOICES;
    synConfig.maxPVoices = MAX_VOICES;
    synConfig.maxUpdates = MAX_UPDATES;
    synConfig.dmaproc    = &dmaNew;
    synConfig.fxSize	 = FX_BUFFER_SIZE;
    synConfig.heap       = &aHeap;
    
    alInit(&audioGlbls, &synConfig);

    seqConfig.maxVoices      = MAX_VOICES;
    seqConfig.maxEvents      = MAX_SEQP_EVENTS;
    seqConfig.maxChannels    = MAX_SEQ_CHANNELS;
    seqConfig.heap           = &aHeap;
    
    alSeqpNew(&seqPlayer, &seqConfig);
    alSeqNew(&sequence, seqPtr, bankLen);    
    alSeqpSetSeq(&seqPlayer, &sequence);

    alBnkfNew((ALBankFile *)midiBankPtr, _miditableSegmentRomStart);
    midiBank = ((ALBankFile *)midiBankPtr)->bankArray[0];
    alSeqpSetBank(&seqPlayer, midiBank);

    alSeqNewMarker(&sequence,&startMark,239);
    alSeqNewMarker(&sequence,&endMark,1200);
    alSeqpLoop(&seqPlayer,&startMark,&endMark,LOOP_COUNT);  

    alSeqpPlay(&seqPlayer);

#ifdef LOGGING_ON
    osLogEvent(myLog,101,1,aHeap.cur);
    osLogEvent(myLog,102,1,_codeSegmentRomStart);
    osLogEvent(myLog,103,1,_codeSegmentRomEnd);
    osLogEvent(myLog,104,1,_midibankSegmentRomStart);
    osLogEvent(myLog,105,1,_midibankSegmentRomEnd);
    osLogEvent(myLog,106,1,_miditableSegmentRomStart);
    osLogEvent(myLog,107,1,_miditableSegmentRomEnd);
    osLogEvent(myLog,108,1,_seqSegmentRomStart);
    osLogEvent(myLog,109,1,_seqSegmentRomEnd);

    osFlushLog(myLog);

#endif

}