midiDmon.c 13.5 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
#include <sys/types.h>
#include <sys/prctl.h>
#include <sys/syssgi.h>
#include <sys/ipc.h>
#include <sys/dir.h>
#include <sys/procfs.h>
#include <sys/select.h>
#include <limits.h>
#include <paths.h>
#include <libaudio.h> 
#include <audiotools.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <poll.h> 
#include <unistd.h>
#include <fcntl.h>
#include <u64gio.h>
#include "midiApp.h"
#include "midiDmon.h"


#define SGImidiDmonName  "Ultra64 Daemon"

char        gAppName[]="midiDmon";
int         gGIOfd,gObjCt,gObjMax;
int         verbose=FALSE,hardware=TRUE;
MDport      gMidiOutPort[MAX_PORTS];

int         gNumPorts;
char        *gMirror,*gSamples;
u32         gMirrorCur;
u32         gSamplesCur;
ALSymObj    *gSymObj;
u32         gCurChanInst[MAX_SEQ_CHANNELS];
s16         gCurBank;

MDevent     gMidiEvents[MAX_MSGS];


/********************************************************************
 *
 *  Receive Midi.  Primary midi receiving routine.  Upon receiving
 *  midi, seperate out system exclusive, from regular status mesgs.
 *  Send regular messages in one block, for each system exclusive,
 *  Handle one at a time, by calling ProcessSysEx
 *
 *********************************************************************/

void ReceiveMidi(MDport inPort)
{
    int         sysExCt = 0;
    int         sysMsg[MAX_MSGS];
    int         validMsgs = 0;
    int         numMsgs,ct,msgType;
    char        chan;

    
    unsigned char   status;
    midiBlock       midiBlk;
    u64_write_arg_t writeHdr;

    unsigned long long deltaTime,gioTime;
    float              deltaFlt;
    
    numMsgs=mdReceive(inPort,gMidiEvents,MAX_MSGS);
    if(numMsgs<0)
    {
        fprintf(stderr,"%s: ERROR receiving midi data!\n",gAppName);
        return;
    }
    else if(numMsgs>0)
    {
        for(ct=0;ct<numMsgs;ct++)
        {
            if(verbose)
            {
                syssgi(SGI_GET_UST,&deltaTime,0);
                deltaTime -= gMidiEvents[ct].stamp;
                deltaFlt = deltaTime;
                deltaFlt /= 1000; /* nanoseconds to microseconds */
            }
            status = gMidiEvents[ct].msg[0] & 0xF0;

            if(status) /* status has a value */
            {
                switch(status)
                {
                    case 0x80: /* note off         */
                    case 0x90: /* note on          */
                    case 0xA0: /* poly pressure    */
                    case 0xB0: /* controller       */
                    case 0xD0: /* channel pressure */
                    case 0xE0: /* pitch bend       */
                        midiBlk.mess[validMsgs].midiByte[0]=gMidiEvents[ct].msg[0];
                        midiBlk.mess[validMsgs].midiByte[1]=gMidiEvents[ct].msg[1];
                        midiBlk.mess[validMsgs].midiByte[2]=gMidiEvents[ct].msg[2];
                        if(verbose)
                            fprintf(stderr,"%s: midi data: 0x%X 0x%X 0x%X  deltaTime = %f\n",
                                    gAppName, gMidiEvents[ct].msg[0],gMidiEvents[ct].msg[1],
                                    gMidiEvents[ct].msg[2],deltaFlt);
                        validMsgs++;
                        break;
                    case 0xC0: /* program change */
                        chan = gMidiEvents[ct].msg[0] & 0x0F;
                        gCurChanInst[chan] = gMidiEvents[ct].msg[1];
                        midiBlk.mess[validMsgs].midiByte[0]=gMidiEvents[ct].msg[0];
                        midiBlk.mess[validMsgs].midiByte[1]=gMidiEvents[ct].msg[1];
                        midiBlk.mess[validMsgs].midiByte[2]=gMidiEvents[ct].msg[2];
                        if(verbose)
                            fprintf(stderr,"%s: midi data: 0x%X 0x%X 0x%X  deltaTime = %f\n",
                                    gAppName, gMidiEvents[ct].msg[0],gMidiEvents[ct].msg[1],
                                    gMidiEvents[ct].msg[2],deltaFlt);
                        validMsgs++;
                        break;
                    case 0xF0:
                        if(gMidiEvents[ct].msg[0]==0xF0)
                        {
                            sysMsg[sysExCt]=ct;
                            sysExCt++;
                        }
			else if(gMidiEvents[ct].msg[0] == 0xFF) 
			{
			    midiBlk.mess[validMsgs].midiByte[0]=gMidiEvents[ct].msg[0];
			    midiBlk.mess[validMsgs].midiByte[1]=gMidiEvents[ct].msg[1];
			    midiBlk.mess[validMsgs].midiByte[2]=gMidiEvents[ct].msg[2];
			    if(verbose)
				fprintf(stderr,"%s: midi data: 0x%X 0x%X 0x%X  deltaTime = %f\n",
					gAppName, gMidiEvents[ct].msg[0],gMidiEvents[ct].msg[1],
					gMidiEvents[ct].msg[2],deltaFlt);
			    validMsgs++;
			}
                        break;
                }
            }
            else if(verbose)
                fprintf(stderr, "%s: Status has no value %X\n",gAppName,gMidiEvents[ct].msg[0]);

        }
        
        if(validMsgs)
        {
            midiBlk.pcktType = STATUS_TYPE;
            midiBlk.numEvts = validMsgs;
            writeHdr.buffer = &midiBlk;
            writeHdr.ramrom_addr = RAMROM_APP_READ_ADDR;
            writeHdr.nbytes =  sizeof(midiBlock);
            writeHdr.value = HOST_APP_CMD_READY;

            if(hardware)
            {
                if(verbose)
                    syssgi(SGI_GET_UST,&gioTime,0);

                ioctl(gGIOfd, U64_SAFE_WRITE, &writeHdr); 
                if(verbose)
                {
                    syssgi(SGI_GET_UST,&deltaTime,0);
                    deltaTime -= gioTime;
                    deltaFlt = deltaTime;
                    deltaFlt /= 1000; /* nanoseconds to microseconds */
                    fprintf(stderr,"%s: IOCTL delta time %f\n",gAppName,deltaFlt);
                }
            }
        }
#ifdef SYSEX_IMPL
        if(sysExCt)
        {
            for(ct=0;ct<sysExCt;ct++)
                ProcessSysEx(&gMidiEvents[sysMsg[ct]]); 
        }
#endif
   
    }
}

/********************************************************************
 *
 *  LoadBank. Called after communication is established with Ultra
 *  Transfers samples to rom, bank to RDRAM, set the sampleOffset,
 *  and the bank offset, updates the bank, and starts the sequence.
 *  If there are communciation problems with GIO, this is the most
 *  likely place for failures to show up.
 *
 *********************************************************************/
void LoadBank(void)
{
    u64_write_arg_t  writeHdr;
    SysExReq         SEXReq;
    ALBankFile       *bnkfPtr;
    u32              rv,bnkOffset;
    
    WriteRamRom(SAMPLES_RAMROM_ADDR,gSamples,gSamplesCur);

    rv = WriteMirror();
    if(rv != MEMORY_OK)
    {
        fprintf(stderr,"%s: Failure writing mirror to ultra dev board\n",gAppName);
        exit(1);
    }

    bnkfPtr = (ALBankFile*)gMirror;   /* BankFile object should always be start of mirror */
    bnkOffset = (u32)bnkfPtr->bankArray[0];
    bnkOffset += BANK_RDRAM_ADDR;
    SEXReq.pcktType = SYSEX_TYPE;
    SEXReq.reqType = SET_BANK; 
    SEXReq.offset = bnkOffset;
    writeHdr.buffer = &SEXReq;
    writeHdr.ramrom_addr = RAMROM_APP_READ_ADDR;
    writeHdr.nbytes = sizeof(SysExReq);
    writeHdr.value = HOST_APP_CMD_READY;

    ioctl(gGIOfd, U64_SAFE_WRITE, &writeHdr);
    SEXReq.reqType = START_SEQUENCE;
    ioctl(gGIOfd, U64_SAFE_WRITE, &writeHdr);
}

int MIDIDevicePresent(char *name)
{
    int i, count;
    if (!name)
        return (FALSE);
    count = mdInit();
    for (i = 0; i < count; i++)
    {
        if (!strcmp(name, mdGetName(i)))
            return (TRUE);
    }
    return (FALSE);
}

/*****************************************************************
 *
 *  Midi Daemon.  Initialize midi connections, poll each one in turn
 *  if you receive any midi data, call handling routine.
 *
 *******************************************************************/
void MidiDaemon(void *arg)
{
    int             c;
    char            *portname,*newName;
    MDport          midiInPort[MAX_PORTS];
    int             midiFds[MAX_PORTS];
    int             numBytes,dummyBuf;
    fd_set              inports, outports;
    int                 nfds, highfd;
   
    gNumPorts=mdInit();  /* start midi lib stuff, and open in port */

    if(verbose)
        fprintf(stderr,"%s: %d ports for midi\n",gAppName,gNumPorts);

    if (gNumPorts<1)
    {
        fprintf(stderr,"%s: No ports configured for midi. Exiting\n",gAppName); 
        exit(-1);
    }
    if(gNumPorts>MAX_PORTS)
    {
        fprintf(stderr,"%s: More than %d ports configured for midi.\n",gAppName,MAX_PORTS);
        fprintf(stderr,"%s: Will use only the first %d ports.\n",gAppName,MAX_PORTS);
        gNumPorts=MAX_PORTS;
    }

    for(c=0;c<gNumPorts;c++)
    {
        portname=mdGetName(c);

        if(portname==NULL)
            fprintf(stderr,"%s: Port %d is not correctly set for midi.\n",gAppName,c+1);
        if(verbose)
            fprintf(stderr,"%s: %s signed in for midi input\n",gAppName, portname);
        
        midiInPort[c]=mdOpenInPort(portname);
        if(midiInPort[c]==NULL)
            fprintf(stderr,"%s: Failure opening midi in port for %s\n",gAppName,portname);

        mdSetStampMode(midiInPort[c],MD_NOSTAMP);
        
        midiFds[c]=mdGetFd(midiInPort[c]);

        FD_SET(midiFds[c],&inports);
        /*
        FD_SET(mdGetFd(midiOutPort[c]),&outports);
        */
        highfd = midiFds[c] + 1; 

        gMidiOutPort[c]=mdOpenOutPort(portname);
        if(gMidiOutPort[c]==NULL)
            fprintf(stderr,"%s: Failure opening midi in port for %s\n",gAppName,portname);
        if(verbose)
            fprintf(stderr,"%s: %s signed in for midi output\n",gAppName,portname);

        mdSetStampMode(gMidiOutPort[c],MD_NOSTAMP);
    }
    if(hardware)
    {
        loadrom();
        if(verbose)
            fprintf(stderr,"%s: Finished loadrom\n",gAppName);

        gGIOfd = open(DEV_U64, O_RDWR);
        if (gGIOfd == -1)
        {
            fprintf(stderr, "%s: Unable to open %s, Exiting\n",gAppName, DEV_U64);
            exit(-1);
        }
        if(verbose)
            fprintf(stderr,"%s: Waiting for game to send message\n",gAppName);
        ioctl(gGIOfd, U64_LISTEN, GAME_APP_DATA_READY);
        numBytes=read(gGIOfd,&dummyBuf,1);

        if(verbose)
            fprintf(stderr,"%s: Got message from game\n",gAppName);

        LoadBank();
        if(verbose)
            fprintf(stderr,"%s and Ultra64 in synch\n",gAppName);
    }  

/*  Continually poll midi ports, and if you get some data, handle it. */

#if 0
    while(1)
    {
        for(c=0;c<gNumPorts;c++)
        {
            if(poll(&midiFdSet[c],1,0))  /* see if there is midi data waiting to be read */
                ReceiveMidi(midiInPort[c]);

        }        
    }
#endif

    while(1)
    {
        nfds = select(highfd,&inports,0,0,0);
        for (c = 0; c < gNumPorts; c++)
        {
	    if (FD_ISSET(midiFds[c],&inports))
                ReceiveMidi(midiInPort[c]);
            else
		FD_SET(midiFds[c],&inports);
        }
    }
}


static int IsAppRunning(char *appname)
{
    DIR             *dirp;      /* Directory pointer */
    struct direct   *dp;        /* Directory entry */
    char            pbuf[PATH_MAX]; /* Buffer for procfs file name */
    int             pfd;        /* Process file descriptor */
    prpsinfo_t      psinfo;     /* Process information */
    int             found = 0;  /* Flag indicating that we found a match */
    pid_t           mypid;      /* My Process ID */

    /* Open the process info directory */
    if ((dirp = opendir(_PATH_PROCFSPI)) == NULL)
        return -1;

    mypid = getpid();

    /* Iterate through all of the files in the directory */
    while ((dp = readdir(dirp)) != NULL && !found)
    {
        /* We don't care about ourselves */
        if (mypid == atoi(dp->d_name))
            continue;

        /* Open the actual process file */
        strcpy(pbuf, _PATH_PROCFSPI);
        strcat(pbuf, dp->d_name);
        if ((pfd = open(pbuf, O_RDONLY)) < 0)
            continue;

        /* Try and retrieve the process info */
        if (ioctl(pfd, PIOCPSINFO, &psinfo) == -1)
        {
            close(pfd);
            continue;
        }

        close(pfd);

        if (strcmp(appname, psinfo.pr_fname) == 0)
            found = psinfo.pr_pid;
    }

    closedir(dirp);
    return found;
}

/*******************************************************************************
 *
 *  main()  Parse the arguments and lauch the midi processing daemon
 *
 *******************************************************************************/

int main(int argc, char **argv)
{
    int     c,newPID;
    int     symbolFile = FALSE;
    extern char *optarg;

    while ((c = getopt(argc, argv, "vhb:")) != EOF)
    {
        switch (c) 
        {
            case 'v':
                verbose = TRUE;
                break;
            case 'h':
                hardware = FALSE;
                break;
            case 'b':
                ReadFiles(optarg);
                symbolFile = TRUE;
                break;
            case '?':
                fprintf(stderr,"%s: Usage -v(erbose) -b(ankFile) file\n",gAppName);
                exit(0);
                break;
        }
    }

    if(!symbolFile)
    {
        fprintf(stderr,"%s: You must specify a set of bank files\n",gAppName);
        exit(-1);
    }

    if(IsAppRunning(gAppName))
    {
        fprintf(stderr,"%s: A copy of %s is already running. Will exit\n",gAppName,gAppName);
        exit(-1);
    }
    
    newPID = sproc(MidiDaemon, PR_SALL, NULL);
    if (newPID < 0)
    {
        fprintf(stderr, "%s: AACK! Unable to start midi processing daemon!\n", argv[0]);
        exit(-1);
    }
}