AeWaveFile.c++ 20.3 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 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <iostream.h>
#include <PR/libaudio.h>

#include "GList.h"
#include "AeWaveFile.h"
#include "AeAsset.h"
#include "AeErr.h"


double	_AFConvertFromIeeeExtended (char *bytes);


AeWaveFile::AeWaveFile (char * name)
    : AeAssetFile (name)
{
    fWave = NULL;
    fKeymap = NULL;
}

AeWaveFile::~AeWaveFile (void)
{
}


// try to use the Audio File library to read the file
// otherwise use our own parser to read the file.
AeErr
AeWaveFile::ReadList (GList<AeAsset *> *& list)
{
    AeErr err;

#ifdef NOT_IN_USE
    if ((err = afRead ()) == kAeFileCantOpen)
	err = aeRead ();
#endif

    err = aeRead ();

    if (!err)
    {
	if (list = new GList<AeAsset *>)
	{
	    list->Append (fWave);
	    list->Append (fKeymap);
	}
	else
	    err = kAeLowMemErr;
    }

    if (err)
	ReportError (err);

    return err;
}


// try to use the Audio File library to read the file
// otherwise use our own parser to read the file.
AeErr
AeWaveFile::Read (AeAsset *& asset)
{
    AeErr err;

#ifdef NOT_IN_USE
    if ((err = afRead ()) == kAeFileCantOpen)
	err = aeRead ();
#endif

    err = aeRead ();

    if (!err)
	asset = fWave;
    else
	ReportError (err);

    return err;
}


AeErr
AeWaveFile::ReadSampleData (char *& buffer, long & nbytes)
{
    AeErr err;

#ifdef NOT_IN_USE
    if ((err = afReadSampleData (buffer, nbytes)) == kAeFileCantOpen)
	err = aeReadSampleData (buffer, nbytes);
#endif

    if (err = aeReadSampleData (buffer, nbytes))
	ReportError (err);

    return err;
}



AeErr
AeWaveFile::afRead (void)
{
    AFfilehandle	fileRef;
    AeErr		err = kAeNoErr;

    if ((fileRef = AFopenfile (fFullName, "r", NULL)) == AF_NULL_FILEHANDLE)
    {
	err = kAeFileCantOpen;
	goto Abort;
    }

    // create the wave asset based on the file type
    if (err = newWaveAsset (fileRef))
	goto Abort;

    // read the generic wave parameters
    afReadWaveParams (fileRef, fWave);
    afReadInstParams (fileRef);

    // read the specific wave parameters
    if (fWave->GetWaveType () == kRaw16WaveType)
	afReadRaw16Params (fileRef, (AeRaw16WaveAsset *)fWave);
    else
	afReadADPCMParams (fileRef, (AeADPCMWaveAsset *)fWave);

Abort:
    if (fileRef != AF_NULL_FILEHANDLE)
	AFclosefile (fileRef);

    return err;
}


AeErr
AeWaveFile::newWaveAsset (AFfilehandle fileRef)
{
    AeWaveAsset *	asset;
    long  	     	fileFmt;
    long       		compFmt;
    long       		version;
    AeErr		err = kAeNoErr;

    fileFmt = AFgetfilefmt (fileRef, &version);

    switch (fileFmt)
    {
	case AF_FILE_AIFF:
	    fWave = (AeWaveAsset *)new AeRaw16WaveAsset (this);
	    break;

	case AF_FILE_AIFFC:
	    compFmt = AFgetcompression (fileRef, AF_DEFAULT_TRACK);
	    switch (compFmt)
	    {
		case AF_COMPRESSION_NONE:
		    fWave = (AeWaveAsset *)new AeRaw16WaveAsset (this);
		    break;

		default:
		    fWave = (AeWaveAsset *)new AeADPCMWaveAsset (this);
		    break;
	    }

	default:
	    fWave = NULL;
	    err = kAeFileNoSupport;
	    break;
    }

    if (!err && fWave == NULL)
	err = kAeLowMemErr;

    return err;
}


AeErr
AeWaveFile::newKeymapAsset (void)
{
    AeErr err = kAeNoErr;
    char name[64];
    char * prefix = MakeFilePrefix ();
    char * p;

    // hack to replace periods with underscores
    // periods are illegal in the ic tool
    p = prefix;
    while (*p)
    {
	if (*p == '.')
	    *p = '_';
	p++;
    }

    sprintf (name, "%s_key", prefix);

    if ((fKeymap = new AeKeymapAsset (name)) == NULL)
	err = kAeLowMemErr;

    free (prefix);

    return err;
}


void
AeWaveFile::afReadWaveParams (AFfilehandle fileRef, AeWaveAsset * asset)
{
    long	sampleFmt;
    long       	sampleSize;
    long	sampleFrames;

    assert (fileRef != AF_NULL_FILEHANDLE);
    assert (asset);

    // must be uncompressed data so that sample frames = data bytes * 2
    assert (asset->GetWaveType () == kRaw16WaveType);

    AFgetsampfmt (fileRef, AF_DEFAULT_TRACK, &sampleFmt, &sampleSize);
    sampleFrames = AFgetframecnt (fileRef, AF_DEFAULT_TRACK);

    asset->SetSampleSize (sampleSize);
    asset->SetSampleRate (AFgetrate (fileRef, AF_DEFAULT_TRACK));
    asset->SetSampleFrames (sampleFrames);
    asset->SetNDataBytes (sampleFrames * sampleSize / 8);
}


void
AeWaveFile::afReadInstParams (AFfilehandle fileRef)
{
    if (AFgetinstids (fileRef, NULL))
    {
	if (!fKeymap)
	    newKeymapAsset ();

	assert (fKeymap);

	fKeymap->SetKeyMin (AFgetinstparamlong (fileRef, AF_DEFAULT_INST,
						AF_INST_MIDI_LONOTE));
	fKeymap->SetKeyMax (AFgetinstparamlong (fileRef, AF_DEFAULT_INST,
						AF_INST_MIDI_HINOTE));
	fKeymap->SetKeyBase (AFgetinstparamlong (fileRef, AF_DEFAULT_INST,
						 AF_INST_MIDI_BASENOTE));
	fKeymap->SetVelMin (AFgetinstparamlong (fileRef, AF_DEFAULT_INST,
						AF_INST_MIDI_LOVELOCITY));
	fKeymap->SetVelMax (AFgetinstparamlong (fileRef, AF_DEFAULT_INST,
						AF_INST_MIDI_HIVELOCITY));
	fKeymap->SetDetune (AFgetinstparamlong (fileRef, AF_DEFAULT_INST,
						AF_INST_NUMCENTS_DETUNE));
    }
}

void
AeWaveFile::afReadRaw16Params (AFfilehandle fileRef, AeRaw16WaveAsset * asset)
{
    assert (fileRef != AF_NULL_FILEHANDLE);
    assert (asset);

    AeLoopAsset * loop = new AeLoopAsset ("");
    afReadLoop (fileRef, loop);
    asset->SetLoop (loop);
}


void
AeWaveFile::afReadLoop (AFfilehandle fileRef, AeLoopAsset * asset)
{
    long loopID;
    long loopMode;
    long loopStart;
    long loopEnd;

    assert (fileRef != AF_NULL_FILEHANDLE);
    assert (asset);

    loopID = AFgetinstparamlong (fileRef, AF_DEFAULT_INST, AF_INST_SUSLOOPID);

    loopMode = AFgetloopmode (fileRef, AF_DEFAULT_INST, loopID);

    if (loopMode == AF_LOOP_MODE_FORW)
    {
	loopStart = AFgetloopstart (fileRef, AF_DEFAULT_INST, loopID);
	loopEnd   = AFgetloopend (fileRef, AF_DEFAULT_INST, loopID);
    
	asset->SetStart (loopStart);
	asset->SetEnd (loopEnd);
	asset->SetCount (-1);		// make if loop forever
    }
}


void
AeWaveFile::afReadADPCMParams (AFfilehandle fileRef, AeADPCMWaveAsset * asset)
{
    long	miscCnt;
    long *	miscIDs;
    long	miscType;
    long	miscSize;
    void *	miscData;
    void *	miscDataPtr;
    char *	miscName;
    long	applType;
    int		i;
 
    assert (fileRef != AF_NULL_FILEHANDLE);
    assert (asset);

    miscCnt = AFgetmiscids(fileRef, NULL);
    miscIDs = (long *)malloc (miscCnt * sizeof(long));
    FailNIL (miscIDs);

    AFgetmiscids (fileRef, miscIDs);

    for (i=0; i<miscCnt; i++)
    {
	miscType = AFgetmisctype (fileRef, miscIDs[i]);

	if (miscType == AF_MISC_AIFF_APPL)
	{
	    miscSize = AFgetmiscsize (fileRef, miscIDs[i]);
	    miscData = malloc (miscSize);
	    FailNIL (miscData);
	    miscDataPtr = miscData;

	    AFreadmisc (fileRef, miscIDs[i], miscData, miscSize);

	    applType = afReadLong (miscData);

	    if (applType == 'stoc')
	    {
		miscData = afReadPString (miscData, miscName);

		if (!strcmp (LOOP_NAME, miscName))
		{
		    AeADPCMLoopAsset * loop = new AeADPCMLoopAsset ("");
		    afReadADPCMLoop (miscData, loop);		    
		    asset->SetLoop (loop);
		}
		else if (!strcmp (CODE_NAME, miscName))
		{
		    AeADPCMBookAsset * book = new AeADPCMBookAsset ("");
		    afReadADPCMBook (miscData, book);
		    asset->SetBook (book);
		}

		if (miscName)
		    free (miscName);
	    }
	    
	    if (miscDataPtr)
		free (miscDataPtr);
	}
    }

    if (miscIDs)
	free (miscIDs);
}


void
AeWaveFile::afReadADPCMLoop (void * data, AeADPCMLoopAsset * asset)
{
    short	version;
    short	nloops;
    ALADPCMloop loopChunk;
    int		i;

    assert (data);
    assert (asset);

    version = afReadShort (data);

    if (version == VERSION)
    {
	nloops = afReadShort (data);

	if (nloops > 1)
	{
	    ReportError (kAeFileTooManyLoops);
	    nloops = 1;
	}
                        
	for (i=0; i<nloops; i++)
	    memcpy (&loopChunk, (char *)data, sizeof (ALADPCMloop));
                        
	asset->SetStart (loopChunk.start);
	asset->SetEnd (loopChunk.end);
	asset->SetCount (loopChunk.count);
	asset->SetStateData (sizeof (ADPCM_STATE), loopChunk.state);
    }
    else
	ReportError (kAeFileBadLoopVersion);
}


void
AeWaveFile::afReadADPCMBook (void * data, AeADPCMBookAsset * asset)
{
    short	version;
    short 	order;
    short 	npredictors;
    int		bookSize;

    assert (data);
    assert (asset);

    version = afReadShort (data);

    if (version == VERSION)
    {
	order = afReadShort (data);
	npredictors = afReadShort (data);
	bookSize = npredictors * order * ADPCMVSIZE;
	asset->SetBook (order, npredictors, ADPCMVSIZE, (short *)data);
    }
    else
	ReportError (kAeFileBadBookVersion);
}


void *
AeWaveFile::afReadPString (void * data, char *& string)
{
    int len = *(char *)data;

    string = (char *)malloc (len + 1);

    strncpy (string, (char *)data+1, len);

    string[len] = 0;

    return (void *)((char *)data + len + 1);
}


long
AeWaveFile::afReadLong (void * data)
{
    long l = *((long *)data);
    char * p = (char *)data;

    p += sizeof (long);
    return l;
}
    
short
AeWaveFile::afReadShort (void * data)
{
    short s = *((short *)data);
    char * p = (char *)data;

    p += sizeof (long);
    return s;
}
    

AeErr
AeWaveFile::aeRead (void)
{
    FILE *		fileRef;
    long        	offset;
    int         	i;
    Chunk       	FormChunk;
    CommonChunk 	comm;
    ChunkHeader 	Header;
    char *      	nameChunk;
    SoundDataChunk      data;
    ALADPCMloop 	loopChunk;
    int         	done=0;
    long        	skip;
    long        	ts;
    int         	num;
    short       	nmarkers;
    Marker      	*markers;
    unsigned long 	compressionType;
    long		sampleFrames, nbytes;
    double		sampleRate;
    AeLoopAsset *	loop = NULL;
    AeADPCMBookAsset *	book = NULL;
    AeErr		err = kAeNoErr;


    // open the file for reading
    if ((fileRef = fopen(fFullName, "r")) == NULL)
    {
	err = kAeFileCantOpen;
	goto Abort;
    }

    // read the form chunk
    fread(&FormChunk, sizeof(FormChunk), 1, fileRef);
    
    if ((FormChunk.ckID != IFF_ID_FORM) ||
        ((FormChunk.formType != IFF_ID_AIFC) &&
        (FormChunk.formType != IFF_ID_AIFF))) {
	err = kAeFileNoSupport;
	goto Abort;
    }

    // read file chunks until there are no more
    while (!done)
    {
        if ((num = fread(&Header, sizeof(ChunkHeader), 1, fileRef)) < 1)
	    break;

        skip = (Header.ckSize + 1) & ~1; /* account for pad byte */
        
        switch (Header.ckID)
	{
            case (IFF_ID_COMM):
		offset = ftell(fileRef);
                
		num = fread (&comm, sizeof(CommonChunk), 1, fileRef);
		if (num < 1) {
		    err = kAeFileBadRead;
		    goto Abort;
		}

		fseek(fileRef, offset + skip, SEEK_SET);
                break;
                
            case (IFF_ID_MARK):
                offset = ftell(fileRef);
		aeReadMarkers (fileRef, &markers, &nmarkers);
                fseek(fileRef, offset + skip, SEEK_SET);
                break;
            
            case (IFF_ID_SSND):
                offset = ftell(fileRef);

                fread(&data, sizeof (data), 1, fileRef);
                assert(data.offset == 0);
                assert(data.blockSize == 0);             
 		nbytes = Header.ckSize - sizeof (data);

                fseek(fileRef, offset + skip, SEEK_SET);
                break;
                
            case (IFF_ID_INST):
                offset = ftell(fileRef);
		aeReadInstParams (fileRef);
		fseek(fileRef, offset + skip, SEEK_SET);
                break;

            case (IFF_ID_APPL):
                offset = ftell(fileRef);

                fread(&ts, sizeof(ts), 1, fileRef);
                if (ts == 'stoc')
		{
                    nameChunk = aeReadPString(fileRef);

                    if (!strcmp(LOOP_NAME, nameChunk))
		    {
			loop = (AeLoopAsset *)new AeADPCMLoopAsset ("");
			aeReadADPCMLoop (fileRef, (AeADPCMLoopAsset *)loop);
                    }
		    else if (!strcmp(CODE_NAME, nameChunk))
		    {
			book = new AeADPCMBookAsset ("");
			aeReadADPCMBook (fileRef, book);
                    }

		    if (nameChunk)
			free (nameChunk);
                }
                
                fseek(fileRef, offset + Header.ckSize, SEEK_SET);
                break;
                
            default:                
                /* skip chunks we don't know about */
                fseek(fileRef, skip, SEEK_CUR);                
                break;
        }        
    }

    if (FormChunk.formType != IFF_ID_AIFF)
	compressionType = comm.compressionTypeH<<16 | comm.compressionTypeL;
    else
	compressionType = 'NONE';
                    
    if (compressionType == 'NONE')
    {
	fWave = (AeWaveAsset *)new AeRaw16WaveAsset (this);
	loop = new AeLoopAsset ("");
	aeReadLoop (loop, markers, nmarkers);
	fWave->SetLoop (loop);
    }

    else if (compressionType == 'VAPC')
    {
	fWave = (AeWaveAsset *)new AeADPCMWaveAsset (this);
	
	if (!loop)
	    loop = (AeLoopAsset *)new AeADPCMLoopAsset ("");
	fWave->SetLoop ((AeADPCMLoopAsset *)loop);
	
	if (book)
	    ((AeADPCMWaveAsset *)fWave)->SetBook (book);
	else
	{
	    assert (False);		// adpcm files must have books
	    err = kAeFileBadRead;
	}
    }
    else
    {
	err = kAeFileNoSupport;
	goto Abort;
    }

    sampleFrames = (comm.numFramesH<<16) + comm.numFramesL;
    sampleRate = _AFConvertFromIeeeExtended (comm.sampleRate);

    fWave->SetSampleSize (comm.sampleSize);
    fWave->SetSampleFrames (sampleFrames);
    fWave->SetSampleRate (sampleRate);
    fWave->SetNDataBytes (nbytes);

Abort:
    if (fileRef)
	fclose(fileRef);    

    return err;
}


void
AeWaveFile::aeReadInstParams (FILE * fileRef)
{
    InstrumentChunk     inst;

    fread (&inst, sizeof(InstrumentChunk), 1, fileRef);

    if (!fKeymap)
	newKeymapAsset ();

    assert (fKeymap);

    fKeymap->SetKeyMin (inst.lowNote);
    fKeymap->SetKeyMax (inst.highNote);
    fKeymap->SetKeyBase (inst.baseNote);
    fKeymap->SetVelMin (inst.lowVelocity);
    fKeymap->SetVelMax (inst.highVelocity);
    fKeymap->SetDetune (inst.detune);

    fLoop = inst.sustainLoop;
}



// Set up the loop point from the Marker definitions.
// Note: only pay attention to a Sustain loop in forward mode
void
AeWaveFile::aeReadLoop (AeLoopAsset * asset, Marker * markers, short nmarkers)
{
    long        start;
    long        end;
        
    if (fLoop.playMode == ForwardLooping)
    {
	if (findMarkerSample (&start, fLoop.beginLoop, markers, nmarkers))
	    ReportError (kAeFileBadMarker);
            
	if (findMarkerSample (&end, fLoop.endLoop, markers, nmarkers))
	    ReportError (kAeFileBadMarker);
            
	asset->SetStart (start);
	asset->SetEnd (end);
	asset->SetCount (-1);		// default to loop forever
    }
}


void
AeWaveFile::aeReadADPCMLoop (FILE * fileRef, AeADPCMLoopAsset * asset)
{
    short	version;
    short 	nloops;
    ALADPCMloop	loopChunk;
    int		i;

    assert (fileRef);
    assert (asset);

    fread(&version, sizeof(short), 1, fileRef);

    if (version == VERSION)
    {
	fread (&nloops, sizeof(short), 1, fileRef);

	if (nloops > 1)
	{
	    ReportError (kAeFileTooManyLoops);
	    nloops = 1;
	}
                        
	for (i=0; i<nloops; i++)
	    fread (&loopChunk, sizeof(ALADPCMloop),1, fileRef);
                       
	asset->SetStart (loopChunk.start);
	asset->SetEnd (loopChunk.end);
	asset->SetCount (loopChunk.count);
	asset->SetStateData (sizeof(ADPCM_STATE), loopChunk.state);
    }
    else
	ReportError (kAeFileBadLoopVersion);
}


void
AeWaveFile::aeReadADPCMBook (FILE * fileRef, AeADPCMBookAsset * asset)
{
    short	version;
    short	order;
    short	npredictors;
    int		bookSize;
    short *	bookData;

    assert (fileRef);
    assert (asset);

    fread(&version, sizeof(short), 1, fileRef);

    if (version == VERSION)
    {
	fread (&order, sizeof(short), 1, fileRef);
	fread (&npredictors, sizeof(short), 1, fileRef);

	bookSize = npredictors*order*ADPCMVSIZE;
	bookData = (short *)malloc(bookSize*sizeof(short));
	FailNIL (bookData);

	fread (bookData, sizeof(short), bookSize, fileRef);

	asset->SetBook (order, npredictors, ADPCMVSIZE, bookData);

	free (bookData);
    }
    else
	ReportError (kAeFileBadBookVersion);
}


void
AeWaveFile::aeReadMarkers (FILE * fileRef, Marker ** markers, short * nmarkers)
{
    char *	nameChunk;
    int		i;

    assert (fileRef);

    fread(nmarkers, sizeof(short), 1, fileRef);

    *markers = (Marker *)calloc(*nmarkers, sizeof(Marker));
    for (i=0; i<*nmarkers; i++)
    {
	fread (&(*markers)[i], sizeof(Marker), 1, fileRef);

	if (nameChunk = aeReadPString(fileRef))
	    free(nameChunk);            // Junk the marker name
    }
}


int
AeWaveFile::findMarkerSample(long *sample, MarkerID loopPoint, Marker *markers, int nmarkers)
{
    for (int i=0; i<nmarkers; i++)
    {
        if (loopPoint == markers[i].id)
	{
            *sample = (markers[i].positionH<<16) + markers[i].positionL;
            return 0;
        }
    }

    return 1;
}

char *
AeWaveFile::aeReadPString (FILE * fileRef)
{
    unsigned char c;
    char        *st;

    assert (fileRef);

    fread(&c, 1, 1, fileRef);
    st = (char *) malloc(c+1);
    fread(st, c, 1, fileRef);
    *(st+c) = 0;
    
    // Read the pad byte if necessary
    if (!(c & 1))
        fread(&c, 1, 1, fileRef);

    return st;
}



AeErr
AeWaveFile::afReadSampleData (char * & buffer, long & nbytes)
{
    AFfilehandle	fileRef;
    long		sampleFmt;
    long       		sampleSize;
    long		sampleFrames;
    long		readFrames;
    AeErr		err = kAeNoErr;

    if ((fileRef = AFopenfile (fFullName, "r", NULL)) == AF_NULL_FILEHANDLE)
    {
	err = kAeFileCantOpen;
	goto Abort;
    }

    AFgetsampfmt (fileRef, AF_DEFAULT_TRACK, &sampleFmt, &sampleSize);

    sampleFrames = AFgetframecnt (fileRef, AF_DEFAULT_TRACK);

    // currently we only handles sample sizes in multiples of 8
    assert ((sampleSize % 8) == 0);

    nbytes = sampleFrames * sampleSize / 8;
    buffer = (char *)malloc (nbytes);

    readFrames = AFreadframes (fileRef, AF_DEFAULT_TRACK, buffer, sampleFrames);

    // if we didn't read all the samples, pretend that we didn't
    // read any data since no data clearly indicates a problem
    // rather than partially good data.
    assert (readFrames == sampleFrames);
    
Abort:
    if (fileRef != AF_NULL_FILEHANDLE)
	AFclosefile (fileRef);

    return err;
    
}


AeErr
AeWaveFile::aeReadSampleData (char *& buffer, long & nbytes)
{
    FILE *		fileRef;
    long        	offset;
    Chunk       	FormChunk;
    ChunkHeader 	Header;
    SoundDataChunk      data;
    int         	done = 0;
    long        	skip, nbytesRead;
    int         	num;
    AeErr		err = kAeNoErr;

    // open the file for reading
    if ((fileRef = fopen(fFullName, "r")) == NULL)
    {
	err = kAeFileCantOpen;
	goto Abort;
    }

    // read the form chunk
    fread (&FormChunk, sizeof(FormChunk), 1, fileRef);
    
    if ((FormChunk.ckID != IFF_ID_FORM) ||
        ((FormChunk.formType != IFF_ID_AIFC) &&
        (FormChunk.formType != IFF_ID_AIFF))) {
	err = kAeFileNoSupport;
	goto Abort;
    }

    // read file chunks until we find the sample sound chunk
    while (!done)
    {
        if ((num = fread(&Header, sizeof(ChunkHeader), 1, fileRef)) < 1)
	    break;

        skip = (Header.ckSize + 1) & ~1; /* account for pad byte */
        
        switch (Header.ckID)
	{
            case (IFF_ID_SSND):
                offset = ftell (fileRef);
                fread (&data, sizeof (data), 1, fileRef);

                assert (data.offset == 0);
                assert (data.blockSize == 0);
              
		nbytes = Header.ckSize - sizeof (data);
		buffer = (char *)malloc (nbytes);
		FailNIL (buffer);

		nbytesRead = fread (buffer, sizeof(char), nbytes, fileRef);
		assert (nbytesRead == nbytes);

                fseek (fileRef, offset + skip, SEEK_SET);

		done = True;
                break;
              
		// skip chunks we don't care about
            default:                
                fseek(fileRef, skip, SEEK_CUR);                
                break;
        }        
    }

Abort:
    if (fileRef)
	fclose (fileRef);    

    return err;    
}


void
AeWaveFile::ReportError (AeErr err)
{
    switch (err)
    {
	case kAeFileTooManyLoops:
	    cout << "warning: multiple loop points found in " << fFileName;
	    cout << ". only 1 loop supported\n";
	    break;

	case kAeFileBadLoopVersion:
	    cout << "warning: non-identical loop chunk versions in ";
	    cout << fFileName << '\n';
	    break;

	case kAeFileBadBookVersion:
	    cout << "warning: bad codebook chunk version in ";
	    cout << fFileName << '\n';
	    break;

	case kAeFileBadMarker:
	    cout << "warning: expected loop marker not found in ";
	    cout << fFileName << '\n';
	    break;

	default:
	    AeFile::ReportError (err);
	    break;
    }

    cout.flush ();
}