audio.c 19.9 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
#include <ultra64.h>
#include <os.h>
#include <ultralog.h>
#include "n64.h"
#include "sched.h"
#include "stats.h"
#include "synthInternals.h"

#define MAX_SEQ_CHANNELS        16
#define	CLOCK_RATE              45637500
#define AUDIO_KILL_THREAD_MSG	1234


static void 		audioInit (TN64Config *audConfig);
static void 		audioFini (void);
static void		audioProc (void);

static ALDMAproc	dmaNew (DMAState **state);
static void		cleanDMABufs (void);
static void		calcPeak (s16 *data, u32 cnt);

#ifdef DEBUG
static void		PrintBank (ALBank *);
static void		PrintInst (ALInstrument *, int id);
static void		PrintSound (ALSound *, int id);
#endif

/* Stacks for the threads and message queues  */
extern char 	_bootSegmentEnd[];
extern char 	_bootSegmentRomEnd[];

OSThread  	audioThread;
u64       	audioThreadStack[STACKSIZE/8];

OSMesgQueue     audioTaskMsgQ;
OSMesg          audioTaskMsgBuf[4];

OSMesgQueue     audioIntQ;
OSMesg          audioIntBuf[4];

OSMesgQueue	audioDMAMsgQ;      /* many sample dma's allowed at one time */
OSMesg		*audioDMAMsgBuf;
OSIoMesg        *audioDMAIOMsgBuf;

OSMesgQueue     audioQuitMsgQ;
OSMesg          audioQuitMsgBuf[1];


/* Globals for audio  */
ALHeap          aHeap;
u8              transferSpace[TRANSFER_SPACE_SIZE]; /* memory for stuff32 and the
                                          CommPckt data. not in the heap */
ALGlobals       audioGlbls;
ALFxRef         fxRef;
ALSeqPlayer     seqPlayer;
u8		audioInited = FALSE;
u8		audioKillThread = FALSE;

u32             nextDMA = 0;
DMAState        dmaState;
DMABuffer       *dmaBuffs;
u32             dmaBufSize;
u32		dmaFreeFrameLag;

int             gFrameCt;
s32             frameSize;
u32             frameClockFactor = 13243; /* anything other than zero */
                                          /* this is 44100hz at 640 frameSize */
s16             *audioBuffer[2];
Acmd            *cmdList[2];
OSScTask        *tasks[2];               /* globaltask list      */
OSScClient      audioClient;

/* profiler statistics */
s16             peaksL[NUM_PEAKS],peaksR[NUM_PEAKS];
OSTime          rspTimes[NUM_TIMES];
OSTime          cpuTimes[NUM_TIMES];
s32             usedVoices[NUM_TIMES];
s16             rspTimeCt,cpuTimeCt,usedVsCt;
s32		maxUsedVcs, maxRSPCmds;

/* Scheduler globals */
extern OSSched         sc;
extern OSMesgQueue     *sched_cmdQ;


int         curBuf = 0;

void resetValues(void);

u32 totalSeqpEvts;
u32 curProfCt = 0;
u32 numAudCmds[MAX_PROF_CT];
u32 numDMAs[MAX_PROF_CT];
u32 numDMABufs[MAX_PROF_CT];
u32 numSynUpds[MAX_PROF_CT];
u32 numSeqEvts[MAX_PROF_CT];

u32      maxAudCmds;
u32      maxDMAs;
u32      maxDMABufs;
u32      maxSynUpds;
u32      maxSeqEvts;

void midiproc(char *argv)
{
    int           cnt,c;
    u32           blkSize,breakFrame;
    u32           *stuff32;
    char          *blkPtr;
    CommPckt      *commPckt;
    ALBank        *midiBank;
    ALBankFile    *ctl;
    u8            *tbl;
    ALInstrument  *instPtr;



    stuff32 = (u32*)CACHE_ALIGN_UP((int)&transferSpace[0]);
    commPckt = (CommPckt*)CACHE_ALIGN_UP((int)&transferSpace[16]);
     
    *stuff32 = (u32)_bootSegmentEnd;
    osWriteHost(stuff32,4);
    *stuff32 = (u32)_bootSegmentRomEnd;
    osWriteHost(stuff32,4);
    *stuff32 = (u32)osMemSize;
    osWriteHost(stuff32,4);

    while(1)
    {
	osReadHost(commPckt, sizeof(CommPckt));

        if(commPckt->pcktType == STATUS_TYPE)
        {        
            for(cnt=0; cnt < commPckt->d.mb.numEvts; cnt++)
            {
		if(commPckt->d.mb.mess[cnt].midiByte[0] == 0xFF)  /* system reset */
		{
		    alSeqpStop(&seqPlayer);
		    alSeqpPlay(&seqPlayer);
		    resetValues();
		}
		else
		{
		    alSeqpSendMidi(&seqPlayer,(long) 0,
                       commPckt->d.mb.mess[cnt].midiByte[0],
                       commPckt->d.mb.mess[cnt].midiByte[1],
                       commPckt->d.mb.mess[cnt].midiByte[2]);   
		}
            }
        }
        else if(commPckt->pcktType == SYSEX_TYPE)
        {
            switch(commPckt->d.sysr.reqType)
            {
                case WRITE_BLOCK:
		    blkSize = commPckt->d.sysr.value;
                    blkPtr = (char *)commPckt->d.sysr.offset;
		    osReadHost(blkPtr,blkSize);
                    break;
                case WRITE_RAMROM:
		    osAckRamromWrite(); 
                    break;
		case INIT_AUDIO:
		    audioFini ();
		    audioInit ((TN64Config*)commPckt->d.sysr.offset);
		    *stuff32 = (u32)aHeap.cur;   
		    osWriteHost(stuff32,4);
		    break;
		case LOAD_BANKFILE:
		    ctl = (ALBankFile*)commPckt->d.sysr.offset;
		    tbl = (u8*)commPckt->d.sysr.value;
		    /*alBnkfNew(ctl,tbl); */
		    break;
                case START_SEQUENCE:
                    alSeqpPlay(&seqPlayer);
		    alSeqpSendMidi(&seqPlayer,(s32) 0, 0x90, 60, 100);
		    alSeqpSendMidi(&seqPlayer,(s32) 0, 0xb0, AL_MIDI_FX1_CTRL, 100);
		    alSeqpSendMidi(&seqPlayer,(s32) 2048, 0x80, 60, 0);
                    break;
		case STOP_SEQUENCE:
		    alSeqpStop(&seqPlayer);
		    break;
                case SET_BANK:
		    midiBank = (ALBank*)commPckt->d.sysr.offset;
		    if (alSeqpGetState(&seqPlayer) == AL_STOPPED)
			alSeqpSetBank(&seqPlayer, midiBank);
		    else
			osSyncPrintf ("error: n64: sequence not stopped. cannot set bank.\n");
                    break;
                case RESET_BANK:
                    alSeqpStop(&seqPlayer);
                    alSeqpSetBank(&seqPlayer,(ALBank*)commPckt->d.sysr.offset);
		    alSeqpPlay(&seqPlayer);
                    break;
		case SET_FX_PARAM:
		    alSynSetFXParam(&audioGlbls.drvr,fxRef,commPckt->d.sysr.offset,
				    &commPckt->d.sysr.value); 
		    break;
		case SET_FX_SXN_PARAMS:
		    {
			int	i;
			u32 params[PARAMS_PER_SECTION];
			int id = commPckt->d.sysr.offset;
			osReadHost (&params, PARAMS_PER_SECTION*sizeof(u32));

			for (i=0; i<PARAMS_PER_SECTION; i++)
			    alSynSetFXParam (&audioGlbls.drvr, fxRef, id+i, &params[i]);
		    }
		    break;
            }
        }
    }
}

static void audioInit(TN64Config *audConfig)     
{
    int      i;
    s32      *sPtr;
    ALSynth  *drvr;
    ALParam  *updatePtr;
    ALEventListItem *itemPtr;

    audioKillThread = FALSE;

    /* create the audio heap */
    alHeapInit(&aHeap, audConfig->audioHeap,audConfig->heapSize);

    maxRSPCmds = audConfig->maxCmdListSize;
    cmdList[0] = alHeapAlloc(&aHeap, 1, maxRSPCmds * sizeof(Acmd));
    cmdList[1] = alHeapAlloc(&aHeap, 1, maxRSPCmds * sizeof(Acmd));

    tasks[0] = alHeapAlloc(&aHeap, 1, sizeof(OSScTask));
    tasks[1] = alHeapAlloc(&aHeap, 1, sizeof(OSScTask));

    frameSize = audConfig->frameSize;
    audioBuffer[0] = alHeapAlloc(&aHeap, 1, frameSize * sizeof(s32));
    audioBuffer[1] = alHeapAlloc(&aHeap, 1, frameSize * sizeof(s32));

    audioDMAMsgBuf = alHeapAlloc(&aHeap, audConfig->dmaQSize, sizeof(OSMesg));
    audioDMAIOMsgBuf = alHeapAlloc(&aHeap, audConfig->dmaQSize, sizeof(OSIoMesg));
    
    dmaBufSize = audConfig->dmaBufSize;
    dmaFreeFrameLag = audConfig->frameLag;
    dmaBuffs = (DMABuffer *)alHeapAlloc(&aHeap, audConfig->numDMABuffs, sizeof(DMABuffer));
    dmaBuffs[0].node.prev = 0;
    dmaBuffs[0].node.next = 0;
    for (i=0; i<audConfig->numDMABuffs-1; i++)
    {
	dmaBuffs[i].ptr = alHeapAlloc(&aHeap, 1, dmaBufSize);
	alLink((ALLink*)&dmaBuffs[i+1],(ALLink*)&dmaBuffs[i]);
    }    
    /* last buffer already linked, but still needs buffer */
    dmaBuffs[i].ptr = alHeapAlloc(&aHeap, 1, dmaBufSize);
    dmaState.initialized = FALSE;

    audConfig->synConfig.outputRate = osAiSetFrequency(audConfig->synConfig.outputRate); 
    audConfig->synConfig.dmaproc    = &dmaNew;
    audConfig->synConfig.heap       = &aHeap;

    /* create the synthesis driver */
    alInit(&audioGlbls, &audConfig->synConfig); 
    drvr = &audioGlbls.drvr;

    /* initialize the synthesis driver update list */
    updatePtr = drvr->paramList;
    while(updatePtr)
    {
	updatePtr->type = 0xff;
	updatePtr = updatePtr->next;
    }

    frameClockFactor = ((CLOCK_RATE / audConfig->synConfig.outputRate ) * frameSize) / 50;

    fxRef = alSynGetFXRef(&audioGlbls.drvr, 0, 0);
    audConfig->seqpConfig.heap      = &aHeap;

    /* create the sequence player */
    alSeqpNew(&seqPlayer, &audConfig->seqpConfig);

    /* initialize the sequence player event list */
    totalSeqpEvts = audConfig->seqpConfig.maxEvents;
    itemPtr = (ALEventListItem*)&seqPlayer.evtq.freeList.next;
    while(itemPtr)
    {
	itemPtr->evt.type = 0xff;
	itemPtr = (ALEventListItem*)itemPtr->node.next;
    }

    /* create the audio message queues */
    osCreateMesgQueue (&audioDMAMsgQ, audioDMAMsgBuf, audConfig->dmaQSize);
    osCreateMesgQueue (&audioIntQ, &audioIntBuf[0], 4);
    osCreateMesgQueue (&audioTaskMsgQ, &audioTaskMsgBuf[0], 4);
    osCreateMesgQueue (&audioQuitMsgQ, audioQuitMsgBuf, 1); 

    /* create and start the audio thread */
    osCreateThread (&audioThread, 5, (void*)audioProc, NULL,
		   (u8*)audioThreadStack + STACKSIZE, 9);
    osStartThread (&audioThread); 

    osSendMesg (&audioTaskMsgQ, NULL, OS_MESG_BLOCK);
    osSendMesg (&audioIntQ, NULL, OS_MESG_BLOCK);

    audioInited = TRUE;
}

void audioFini (void)
{
    if (audioInited)
    {
	/* stop the sequence player */
	alSeqpStop (&seqPlayer);

	/* tell the audio thread to kill itself */
	audioKillThread = TRUE;
	osRecvMesg (&audioQuitMsgQ, NULL, OS_MESG_BLOCK);

	/* remove the audio thread from the scheduler */
	osScRemoveAudioClient (&sc, &audioClient);

	/* close the audio library */
	alClose (&audioGlbls);

	nextDMA = 0;
	audioInited = FALSE;
    }
}

void audioProc (void)
{
    Acmd            *cmdlp;
    OSTask          *taskp;
    s32             clcount;
    short           *audioOp;
    OSScTask        *t,*cmplT;
    OSMesgQueue     *sched_intQ;
    u32             length;
    OSTime          alAFTime;
    OSTime          rspAver = 0, cpuAver = 0;
    s16             rspAverCt = 0, cpuAverCt = 0;
    ALVoiceState    *vs;
    s32             vAverCt = 0, vAver = 0, vCount;

    osScAddAudioClient(&sc, &audioClient, &audioIntQ); 
    sched_intQ = osScGetIntQ(&sc);

    while(1)
    {
	/* Where the task list goes in DRAM */
	cmdlp = cmdList[curBuf];
	
	/* Where the audio goes in DRAM    */
	audioOp = (s16 *) osVirtualToPhysical(audioBuffer[curBuf]);
    
	/* Call the frame handler ask for samples  */
	clcount = 0;
	alAFTime = osGetTime();

	cmdlp = alAudioFrame(cmdlp, &clcount, audioOp, frameSize);
	
	if(clcount > maxRSPCmds)
	{
	    osSyncPrintf("error: n64: Overflow of command list buffer! %d too many commands\n",
			 clcount - maxRSPCmds);
	    osSyncPrintf("Increase the size of commands in the configuration.\n");
	}

	cpuAver += osGetTime() - alAFTime;
	cpuAverCt++;
	if(cpuAverCt == 4)
	{
	    cpuTimes[cpuTimeCt++] = cpuAver >> 2;
	    cpuAver = 0;
	    cpuAverCt = 0;
	    if(cpuTimeCt >= NUM_TIMES)
		cpuTimeCt = 0;
	}

	numAudCmds[curProfCt] = clcount;

	for (vs = seqPlayer.vAllocHead, vCount = 0; vs != 0; vs = vs->next)
	    vCount++;
	if(vCount > maxUsedVcs)
	    maxUsedVcs = vCount;

	vAver += vCount;
	vAverCt++;
	if(vAverCt == 4)
	{
	    usedVoices[usedVsCt++] = vAver >> 2;
	    vAver = 0;
	    vAverCt = 0;
	    if(usedVsCt >= NUM_TIMES)
		usedVsCt = 0;
	}

	if(clcount)
	{
	    /* Make sure the last task has completed. */
	    (void)osRecvMesg(&audioTaskMsgQ, (OSMesg*)&cmplT, OS_MESG_BLOCK); 
    
	    if (audioKillThread)
		break;

	    /* Point the DAC at the next buffer */
	    if(cmplT)
	    {
		osAiSetNextBuffer(cmplT->d.ad.output, frameSize<<2); 
		
		calcPeak(cmplT->d.ad.output, frameSize);
		
		rspAver += cmplT->d.ad.endTicks;
		rspAverCt++;
		if(rspAverCt == 4)
		{
		    rspTimes[rspTimeCt++] = rspAver >> 2;
		    rspAver = 0;
		    rspAverCt = 0;
		    if(rspTimeCt >= NUM_TIMES)
			rspTimeCt = 0;
		}
	    }

	    t = tasks[curBuf];
	    t->next = 0;
	    t->msgQ = &audioTaskMsgQ;
	    t->msg = (OSMesg *) t;
	    t->flags = OS_SC_NEEDS_RSP;
	    t->d.ad.output = audioBuffer[curBuf]; 
	    t->d.ad.endTicks = 0;
	    /* Build the audio task */       
	    taskp = &t->list;
	    taskp->t.type = M_AUDTASK;
	    taskp->t.flags = 0x0;
	    taskp->t.data_ptr = (unsigned long long *) cmdList[curBuf];
	    taskp->t.data_size = (cmdlp - cmdList[curBuf]) * sizeof(Acmd);
	    taskp->t.ucode_boot = (unsigned long long *) rspbootTextStart;
	    taskp->t.ucode_boot_size = ((int)rspbootTextEnd -
					(int)rspbootTextStart);
	    taskp->t.ucode = (unsigned long long *) aspMainTextStart;
	    taskp->t.ucode_data = (unsigned long long *) aspMainDataStart;
	    taskp->t.ucode_size = SP_UCODE_SIZE;
	    taskp->t.ucode_data_size = SP_UCODE_DATA_SIZE;
	    taskp->t.dram_stack = (u64 *) NULL;
	    taskp->t.dram_stack_size = 0;
	    taskp->t.output_buff = (u64 *) NULL;
	    taskp->t.output_buff_size = 0;
	    taskp->t.yield_data_ptr = NULL;
	    taskp->t.yield_data_size = 0;


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

	    /* Send new command list to scheduler */
	    osSendMesg(sched_cmdQ, (OSMesg) t, OS_MESG_BLOCK); 
	    osSendMesg(sched_intQ, NULL, OS_MESG_BLOCK); 

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

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

    osSendMesg (&audioQuitMsgQ, NULL, OS_MESG_BLOCK);
}

static void calcPeak(s16 *data, u32 cnt)
{
    s16  maxL = 0, maxR = 0, absol;
    u32  c,d;
    static s16 peakct = 0;

    for(c = 0, d = 0; c < cnt; c++)
    {
	absol = ABSOL(data[d]);
	d++;
	if(absol > maxL)
	    maxL = absol;

	absol = ABSOL(data[d]);
	d++;
	if(absol > maxR)
	    maxR = absol;
    }

    if(peakct >= NUM_PEAKS)
	peakct = 0;
    peaksL[peakct] = maxL;
    peaksR[peakct] = maxR;
    peakct++;
}

static 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 + dmaBufSize;
        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 */
    if(dmaState.firstFree)
	dmaPtr = dmaState.firstFree;
    else
    {
	osSyncPrintf("error: n64: Out of DMA buffers!\n");
	osSyncPrintf("Increase the number of DMA buffers in the configuration.\n");
	dmaPtr = dmaState.firstUsed; /* attempt to avoid disaster */
	return((int) osVirtualToPhysical(dmaPtr->ptr));
    }

    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(&audioDMAIOMsgBuf[nextDMA++], OS_MESG_PRI_NORMAL, OS_READ,
                 (u32)addr, freeBuffer, dmaBufSize, &audioDMAMsgQ);

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

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

    if(!dmaState.initialized)  /* only do this once */
    {
        dmaState.firstFree = &dmaBuffs[0];
	dmaState.firstUsed = 0;
        dmaState.initialized = 1;
    }

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

    return dmaCallBack;
}

static void cleanDMABufs (void)
{
    DMABuffer  *dmaPtr,*nextPtr;
    u32        i, usedDMAs = 0;
    ALParam    *updatePtr;
    u32        updateCt;
    ALSynth    *drvr;
    u32        unusedEvent;
    ALEventListItem *itemPtr;

    /* Empty the dma queue to make sure all DMAs have completed */
    for (i=0; i<nextDMA; i++)
	osRecvMesg(&audioDMAMsgQ, NULL, OS_MESG_NOBLOCK);

    numDMAs[curProfCt] = nextDMA;

    dmaPtr = dmaState.firstUsed;
    while(dmaPtr)
    {
	usedDMAs++;
        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 + dmaFreeFrameLag  < 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;
    }

    drvr = &audioGlbls.drvr;
    updateCt = 0;
    updatePtr = drvr->paramList;
    while(updatePtr)
    {
	if(updatePtr->type != 0xff)
	{
	    updateCt++;
	    updatePtr->type = 0xff;
	}
	updatePtr = updatePtr->next;
    }

    unusedEvent = 0;
    itemPtr = (ALEventListItem*)seqPlayer.evtq.freeList.next;
    while(itemPtr)
    {
	if(itemPtr->evt.type == 0xff)
	    unusedEvent++;
	else
	    itemPtr->evt.type = 0xff;

	itemPtr = (ALEventListItem*)itemPtr->node.next;
    }

    numSeqEvts[curProfCt] = totalSeqpEvts - unusedEvent;
    numSynUpds[curProfCt] = updateCt;
    numDMABufs[curProfCt] = usedDMAs;

    nextDMA = 0;

    curProfCt++;
    if(curProfCt >= MAX_PROF_CT)
	curProfCt = 0;

}

void resetValues(void)
{
    int  c;

    curProfCt = 0;
    maxAudCmds = 0;
    maxDMAs = 0;
    maxDMABufs = 0;
    maxSynUpds = 0;
    maxSeqEvts = 0;    

    for(c = 0; c < MAX_PROF_CT; c++)
    {
	numAudCmds[c] = 0;
	numDMAs[c] = 0;
	numDMABufs[c] = 0;
	numSynUpds[c] = 0;
	numSeqEvts[c] = 0;
    }

    for(c = 0; c < NUM_PEAKS; c++)
    {
	peaksL[c] = 0;
	peaksR[c] = 0;
    }

    for(c = 0; c < NUM_TIMES; c++)
    {
	rspTimes[c] = 0;
	cpuTimes[c] = 0;
	usedVoices[c] = 0;
    }

    rspTimeCt = 0;
    cpuTimeCt = 0;
    usedVsCt = 0;
    maxUsedVcs = 0;
}


/* debugging only */
#ifdef DEBUG
static void
PrintBank (ALBank * bank)
{
    int i;

    osSyncPrintf ("#inst = %d, rate = %d\n",
		  bank->instCount, bank->sampleRate);

    for (i=0; i<bank->instCount; i++)
	PrintInst (bank->instArray[i], i);
}

static void
PrintInst (ALInstrument *inst, int id)
{
    int i;

    osSyncPrintf ("  inst[%02d] = %x: #snd = %d, vol = %d, pan = %d\n",
		  id, inst, inst->soundCount, inst->volume, inst->pan);

    for (i=0; i<inst->soundCount; i++)
	PrintSound (inst->soundArray[i], i);
}

static void
PrintSound (ALSound * snd, int id)
{
    osSyncPrintf ("    snd [%02d] = %x: vol = %d, pan = %d, keymap = %x, env = %x, wave = %x\n",
		  id, snd, snd->sampleVolume, snd->samplePan,
		  snd->keyMap, snd->envelope, snd->wavetable);

#if 0
    ALEnvelope *	env;
    ALKeyMap *		keymap;
    ALWaveTable *	wave;
    env = snd->envelope;

    osSyncPrintf ("attTime = %d, decTime = %d, relTime = %d, attVol = %d, decVol = %d\n",
		  env->attackTime, env->decayTime, env->releaseTime,
		  env->attackVolume, env->decayVolume);

    keymap = snd->keyMap;

    osSyncPrintf ("velMin = %d, velMax = %d, keyMin = %d, keyMax = %d, keyBase = %d, detune = %d\n",
		  keymap->velocityMin, keymap->velocityMax,
		  keymap->keyMin, keymap->keyMax, keymap->keyBase, keymap->detune);

    wave = snd->wavetable;

    osSyncPrintf ("base = %x, len = %d, type = %s\n",
		  wave->base, wave->len,
		  wave->type == AL_ADPCM_WAVE ? "adpcm" : "raw");
#endif
}
#endif