midifile.c++ 10.8 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
//====================================================================
// midifile.c++
//
// Copyright 1993, Silicon Graphics, Inc.
// All Rights Reserved.
//
// This is UNPUBLISHED PROPRIETARY SOURCE CODE of Silicon Graphics, Inc.;
// the contents of this file may not be disclosed to third parties, copied or
// duplicated in any form, in whole or in part, without the prior written
// permission of Silicon Graphics, Inc.
//
// RESTRICTED RIGHTS LEGEND:
// Use, duplication or disclosure by the Government is subject to restrictions
// as set forth in subdivision (c)(1)(ii) of the Rights in Technical Data
// and Computer Software clause at DFARS 252.227-7013, and/or in similar or
// successor clauses in the FAR, DOD or NASA FAR Supplement. Unpublished -
// rights reserved under the Copyright Laws of the United States.
//====================================================================

#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#include "midifile.h"

MIDIFile::MIDIFile()
{
}

int MIDIFile::Open(const char *fileName, const char *rw)
{
    file = fopen(fileName, rw);
    if (!file) {
        printf("couldn't open file %s\n", name);
        exit(1);
    }

       
    fseek(file, 0, SEEK_END);
    fileSize = ftell(file);
    rewind(file);

    name = (char *) malloc(strlen(fileName)+1);
    strcpy(name, fileName);
    
    return 0;
}

int MIDIFile::Close()
{
    return fclose(file);
}

void MIDIFile::Parse() 
{
    parseHeader();

    int i;
    for (i = 0; i < hdr.ntrks; i++) {
        parseTrack();
    }   
}

void MIDIFile::Write(short format, short ntracks, short division)
{
    writeHeader(format, ntracks, division);
    
    if (format == 1)
        midiWriteTempoTrack();

    int i;
    for (i = 0; i < ntracks; i++)
        writeTrack(i);
    
}

void MIDIFile::parseHeader()
{
    ChunkHdr chdr;
    int rv;
    
    rv = fread (&chdr, sizeof(ChunkHdr), 1, file);

    if (rv != 1)
        midiError("could not read file");
    
    if (chdr.ckID != IFF_ID_MTHD)
        midiError("this is not a Standard MIDI file");

    rv = fread(&hdr, sizeof(TrackHdr), 1, file);
    if (rv != 1)
        midiError("could not read file");
    
    midiHeader(&hdr);
}

void MIDIFile::writeHeader(short format, short tracks, short division)
{
    write32bit(IFF_ID_MTHD);
    write32bit(6);
    write16bit(format);
    write16bit(tracks);
    write16bit(division);    
}

static int msgBytes[] = {
    0, 0, 0, 0, 0, 0, 0, 0,		// 0x00 - 0x70
    2, 2, 2, 2, 1, 1, 2, 0		// 0x80 - 0xf0
};

void MIDIFile::parseTrack()
{
    ChunkHdr    chdr;
    int         rv;
    char        c;
    char        c1;
    int         running = 0;
    int         status = 0;
    
    rv = fread(&chdr, sizeof(ChunkHdr), 1, file);

    if (chdr.ckID != IFF_ID_MTRK)
        midiError("bad track header");

    long offset = ftell(file);
    
    midiTrackStart();

    long bytesToRead = chdr.ckSize;

    curTime = 0;
    
    endOfTrack = 0;
    
    while ( !endOfTrack > 0 ) {

        curTime += readVarLen();	/* delta time */

        c = getc(file);

        switch ( c ) {

            case 0xff:			/* meta event */
                {
                    int type = getc(file);
                    long len = readVarLen();
                    char *buf;
                    if (len) {
                        buf = (char *)malloc((int)len);
                        fread(buf, sizeof(char), (int)len, file);
                    }                    
                    metaEvent(type, buf, len);
                    running = 0;
                    status = 0;
                }
                break;

            case 0xf0: /* start of multi packet system exclusive */
                {
                    long len = readVarLen();
                    char *buf = (char *)malloc((int)len);
                    fread(buf, sizeof(char), (int)len, file);
                    midiSysExStart(buf, (int)len);
                    running = 0;
                    status = 0;
                }
                break;

            case 0xf7:	/* system exclusive  */
                {
                    long len = readVarLen();
                    char *buf = (char *)malloc((int)len);
                    fread(buf, sizeof(char), (int)len, file);
                    midiSysEx(buf, (int)len);
                    running = 0;
                    status = 0;
                }                
                break;

            default:
                {                    
                    if ( (c & 0x80) == 0 ) {	 /* running status? */
                        if ( status == 0 ) {
                            midiError("unexpected running status");
                        }
                        running = 1;
                    } else {
                        status = c;
                        running = 0;
                    }

                    int bytes = msgBytes[ (status>>4) & 0xf ];

                    if ( bytes ) {

                        if ( running ) {
                            c1 = c;
                        } else {
                            c1 = getc(file);
                        }

                        channelEvent( status, c1, (bytes>1) ? getc(file) : 0 );

                    }
                }                
                break;
        }
    }
    
    midiTrackEnd();
    fseek(file, offset + chdr.ckSize, SEEK_SET); // forget any garbage    
}

void MIDIFile::writeTrack(int track) 
{
    long offset = ftell(file);

    write32bit(IFF_ID_MTRK);
    write32bit(0);              // don't know how long the track is yet

    midiWriteTrack(track);

    write8bit(1);              // write the end of track marker
    write8bit(0xff);           // one tick after last midi event
    write8bit(0x2f);           // this extra tick is needed so 
    write8bit(0);              // looping works correctly.
    
    long eot = ftell(file);

    fseek(file, offset, SEEK_SET);
    
    write32bit(IFF_ID_MTRK);
    write32bit(eot - offset - sizeof(ChunkHdr));

    fseek(file, eot, SEEK_SET);
    
}

void MIDIFile::writeMidiEvent(long deltaTime, char status, char b1, char b2) 
{
    writeVarLen(deltaTime);

    if (status != lastStatus)   // running status
        write8bit(status);

    write8bit(b1);

    int bytes = msgBytes[ (status>>4) & 0xf ];

    if (bytes == 2)
        write8bit(b2);
    
    lastStatus = status;
}

void MIDIFile::writeMetaEvent(long deltaTime, char type, char *msg, int len)
{
    lastStatus = 0;

    writeVarLen(deltaTime);

    write8bit(0xff);
    write8bit(type);

    writeVarLen(len); 

    int i;
    for(i = 0; i < len; i++) {
        write8bit(msg[i]);
        
    }
}

void MIDIFile::channelEvent(int status, char byte1, char byte2)
{
    int chan = status & 0xf;

    switch ( status & 0xf0 ) {
	case 0x80:
            midiNoteOff(chan, byte1, byte2);
            break;
            
	case 0x90:
            midiNoteOn(chan, byte1, byte2);
            break;
            
	case 0xa0:
            midiKeyPressure(chan, byte1, byte2);
            break;
            
	case 0xb0:
            midiControlChange(chan, byte1, byte2);
            break;
            
	case 0xe0:
            midiPitchBend(chan, byte1, byte2);
            break;
            
	case 0xc0:
            midiProgramChange(chan, byte1);
            break;
    
	case 0xd0:
            midiChannelPressure(chan, byte1);
            break;
    }
}

void MIDIFile::metaEvent(int type, char *m, long len)
{
    switch  ( type ) {
	case 0x00:
            midiSeqNum(to16bit(m[0],m[1]));
            break;

	case 0x01:	/* Text event */
	case 0x02:	/* Copyright notice */
	case 0x03:	/* Sequence/Track name */
	case 0x04:	/* Instrument name */
	case 0x05:	/* Lyric */
	case 0x06:	/* Marker */
	case 0x07:	/* Cue point */
	case 0x08:
	case 0x09:
	case 0x0a:
	case 0x0b:
	case 0x0c:
	case 0x0d:
	case 0x0e:
	case 0x0f:
            midiText(type, m , (int)len);
            break;
            
	case 0x2f:	/* End of Track */
            midiEndOfTrack();
            endOfTrack = 1;
            break;
            
	case 0x51:	/* Set tempo */
            midiTempo(to32bit(0,m[0],m[1],m[2]));
            break;
            
	case 0x54:      /* SMPTE time */
            midiSMPTE(m[0],m[1],m[2],m[3],m[4]);
            break;

	case 0x58:
            midiTimeSig(m[0],m[1],m[2],m[3]);
            break;
    
	case 0x59:
            midiKeySig(m[0],m[1]);
            break;
    
	case 0x7f:
            midiSeqSpecific(m, len);
            break;
    
	default:
            midiMetaMisc(type, m, len);
            break;
    }
}

long MIDIFile::to32bit(char c1, char c2, char c3, char c4)
{
	long value = 0L;

	value = (c1 & 0xff);
	value = (value<<8) + (c2 & 0xff);
	value = (value<<8) + (c3 & 0xff);
	value = (value<<8) + (c4 & 0xff);
	return (value);
}

short MIDIFile::to16bit(int c1, int c2)
{
	return ((c1 & 0xff ) << 8) + (c2 & 0xff);
}

long MIDIFile::readVarLen()
{
    long value;
    int c;

    c = getc(file);
    value = c;
    if ( c & 0x80 ) {
        value &= 0x7f;
        do {
            c = getc(file);
            value = (value << 7) + (c & 0x7f);
        } while (c & 0x80);
    }
    return (value);
}

void MIDIFile::writeVarLen(long value)
{
    unsigned long buffer;

    buffer = value & 0x7f;
    while((value >>= 7) > 0)
    {
	buffer <<= 8;
	buffer |= 0x80;
	buffer += (value & 0x7f);
    }

    while(1){
        write8bit((int)buffer & 0xff);
       
	if(buffer & 0x80)
            buffer >>= 8;
	else
            break;
    }
}

/*
 * MIDI File event handlers do nothing in the base class
 */
void MIDIFile::midiHeader(TrackHdr *)
{
}

void MIDIFile::midiTrackStart()
{}

void MIDIFile::midiTrackEnd()
{}

void MIDIFile::midiSeqNum(short )
{}

void MIDIFile::midiMetaMisc(int, char *, long)
{}

void MIDIFile::midiText(int , char * , int )
{}

void MIDIFile::midiEndOfTrack()
{}

void MIDIFile::midiTempo(long /* tempo */)
{}

void MIDIFile::midiSMPTE(char , char , char , char , char )
{}

void MIDIFile::midiTimeSig(char, char, char, char)
{}

void MIDIFile::midiKeySig(char, char)
{}

void MIDIFile::midiNoteOn(char, char, char)
{}

void MIDIFile::midiNoteOff(char, char, char)
{}

void MIDIFile::midiKeyPressure(char, char, char)
{}

void MIDIFile::midiControlChange(char, char, char)
{}

void MIDIFile::midiPitchBend(char, char, char)
{}

void MIDIFile::midiProgramChange(char, char)
{}

void MIDIFile::midiChannelPressure(char , char )
{}

void MIDIFile::midiSeqSpecific(char *, long)
{}

void MIDIFile::midiSysExStart(char *, int)
{}

void MIDIFile::midiSysEx(char *, int)
{}

void MIDIFile::midiError(char *msg) 
{
    printf("error: %s\n", msg);
    exit(1);
}

void MIDIFile::midiWriteTempoTrack() 
{}

void MIDIFile::midiWriteTrack(int )
{}

void MIDIFile::write8bit(int val)
{
    putc(val &0xff, file);
}

void MIDIFile::write16bit(int val)
{
    short tmp = val & 0xffff;

    fwrite(&tmp, sizeof(short), 1, file);
}

void MIDIFile::write32bit(long val)
{
    fwrite(&val, sizeof(long), 1, file);
}