vadpcm_enc.c 16 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
/*---------------------------------------------------------------------*
        Copyright (C) 1998 Nintendo.
        
        $RCSfile: vadpcm_enc.c,v $
        $Revision: 1.2 $
        $Date: 2003/02/21 05:48:43 $
 *---------------------------------------------------------------------*/
#include "vadpcm.h"

static char usage[] = "[-t -l min_loop_length] -c codebook aifcfile compressedfile";

#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif

main(int argc, char *argv[])
{
    extern char	*optarg;
    extern int	optind;	
    int 	c;

    char
        *progname = argv[0];

    short
        nloops = 0,
        numMarkers,
        *inBuffer,
        ts;
    
    int
        minLoopLength = MINLOOPLENGTH,
        ***coefTable = NULL,
        *state,
        order,
        npredictors,
        done = 0,
        truncate = 0,
        num,
        tableSize,
        nsam,
        left,
        newEnd,
        nRepeats,
        i,
        j,
        k;

    long
        nFrames,
        offset,
        cChunkPos,
        currentPos,
        soundPointer = 0,
        startPointer = 0,
        startSoundPointer = 0,
        cType,
        nBytes = 0;
    
    unsigned long
        loopEnd;

    char
        *compName = "VADPCM ~4-1",
        *appCodeName = "VADPCMCODES",
        *appLoopName = "VADPCMLOOPS";
    
    unsigned char
        strnLen;
    
    Chunk
        AppChunk,
        FormChunk;
    
    ChunkHeader
        CSndChunk,
        Header;
    
    CommonChunk
        CommChunk = {0};
    
    SoundDataChunk
        SndDChunk = {0};

    InstrumentChunk
        InstChunk = {0};

    Loop
        *loops = 0;

    ALADPCMloop
        *aloops;
    
    Marker
        *markers;

    CodeChunk
        cChunk; 
    
    char
        filename[1024];
    
    FILE
        *fhandle,
        *ifile,
        *ofile;

    if (argc<2){
        fprintf(stderr,"%s %s\n",progname,usage);
        exit(1);
    }
    
    while ((c=getopt(argc,argv,"tc:l:"))!=-1){
        switch (c) {
            case 'c':
                if (sscanf(optarg,"%s",filename)==1){
                    if ((fhandle = fopen(filename, "r"))==NULL){
                        fprintf(stderr,"Codebook file %s could not be opened\n",filename);
                        exit(1);
                    }
                    if (readcodebook(fhandle, &coefTable, &order, &npredictors) != 0){
                        fprintf(stderr,"Error reading codebook\n");
                        exit(1);
                    }
                }
                break;
            case 't':
                truncate = 1;
                break;
            case 'l':
                sscanf(optarg,"%d",&minLoopLength);
                break;
            default:
                break;
        }
    }
    
    if (coefTable==NULL){
        fprintf(stderr,"You should specify a coefficient codebook with the [-c] option\n");
        exit(1);
    }
    argv += optind-1;
    
    if ((ifile = fopen(argv[1], "r")) == NULL){
        fprintf(stderr,"%s: input file [%s] could not be opened.\n",progname, argv[1]);
        exit(1);
    }

    if ((ofile = fopen(argv[2], "w")) == NULL){
        fprintf(stderr,"%s: output file [%s] could not be opened.\n",progname, argv[2]);
        exit(1);
    }

    state = (int *) malloc(FRAMESIZE*sizeof(int));
    for (i=0; i<FRAMESIZE; i++)
        state[i] = 0;
    inBuffer = (short *) malloc(FRAMESIZE*sizeof(short));

    /*
     * Read the FORM chunk and check for AIFC file
     */
    fread(&FormChunk, sizeof(Chunk), 1, ifile);
    if ((htonl(FormChunk.ckID) != IFF_ID_FORM) ||  (htonl(FormChunk.formType) != IFF_ID_AIFC)) {
        if(htonl(FormChunk.formType) != IFF_ID_AIFF) {
            fprintf(stderr,"%s: [%s] is not an AIFF-C File\n",progname,argv[1]);
            exit(1);
        }
    }

    /*
     * Scan AIFC file for chunks. Read in the COMMON chunk.
     * Set-up a pointer to the sound data chunk. Read loop points
     * from the INST chunk.
     */
    while (!done) {

        num = fread(&Header, sizeof(ChunkHeader), 1, ifile);
        if (num < 1) {
            done = 1;
            break;
        }
        /*
         * Add the pad byte if necessary to the count
         */
        Header.ckSize  = (htonl(Header.ckSize)+1) & ~1;

        switch (htonl(Header.ckID)) {
            case (IFF_ID_COMM):

                offset = ftell(ifile);
                num = fread (&CommChunk, sizeof(CommonChunk), 1, ifile);
                if (num < 1) {
                    fprintf(stderr,"%s: error parsing file [%s]\n", progname, argv[1]);
                    done = 1;
                }                
                
                /*
                 * Check for a valid file format
                 */
                if(htonl(FormChunk.formType) != IFF_ID_AIFF) {
                    cType = (htons(CommChunk.compressionTypeH)<<16) + htons(CommChunk.compressionTypeL);
                    if (cType != 'NONE'){
                        fprintf(stderr,"%s: file [%s] contains compressed data. 0x%x\n",
                                progname, argv[1], cType);
                        exit(1);
		    }
                }
                if (htons(CommChunk.numChannels) != 1){
                    fprintf(stderr,"%s: file [%s] contains %ld channels, only 1 channel supported.\n",
                            progname, argv[1], htons(CommChunk.numChannels));
                    exit(1);
                }
                if (htons(CommChunk.sampleSize) != 16){
                    fprintf(stderr,"%s: file [%s] contains %ld bit samples, only 16 bit samples supported.\n",
                            progname, argv[1], htons(CommChunk.sampleSize));
                    exit(1);
                }
    
                fseek(ifile, offset + Header.ckSize, SEEK_SET);
                
                break;
            
            case (IFF_ID_SSND):
                offset = ftell(ifile);
                fread(&SndDChunk, sizeof (SndDChunk), 1, ifile);
                assert(SndDChunk.offset == 0);
                assert(SndDChunk.blockSize == 0);
                
                soundPointer = ftell(ifile);
                fseek(ifile, offset + Header.ckSize, SEEK_SET);
                break;

            case (IFF_ID_MARK):
                fprintf(stderr, "XXX Marker chunk!\n");
                offset = ftell(ifile);
                fread(&numMarkers, sizeof(short), 1, ifile);
                numMarkers = htons(numMarkers);
                markers = (Marker *) malloc(sizeof(Marker)*numMarkers);
                for (i=0; i<numMarkers; i++){
                    fread(&markers[i], sizeof(Marker), 1, ifile);
                    fread(&strnLen, 1, 1, ifile);
                    if (strnLen & 1)
                        fseek(ifile, strnLen, SEEK_CUR);
                    else
                        fseek(ifile, strnLen+1, SEEK_CUR);
                    markers[i].id = htons(markers[i].id);
                    markers[i].positionH = htons(markers[i].positionH);
                    markers[i].positionL = htons(markers[i].positionL);
                }

                fseek(ifile, offset + Header.ckSize, SEEK_SET);
                break;
                
            case (IFF_ID_INST):
                offset = ftell(ifile);

                fread(&InstChunk, sizeof(InstrumentChunk), 1, ifile);
                
                aloops = (ALADPCMloop *) malloc(2*sizeof(ALADPCMloop));
                loops = (Loop *) malloc(2*sizeof(Loop));
                if (htons(InstChunk.sustainLoop.playMode) == ForwardLooping){
                    loops[nloops].beginLoop = htons(InstChunk.sustainLoop.beginLoop);
                    loops[nloops].endLoop = htons(InstChunk.sustainLoop.endLoop);
                    nloops++;
                }
                if (htons(InstChunk.releaseLoop.playMode) == ForwardLooping){
                    loops[nloops].beginLoop = htons(InstChunk.releaseLoop.beginLoop);
                    loops[nloops].endLoop = htons(InstChunk.releaseLoop.endLoop);
                    nloops++;
                }
                
                fseek(ifile, offset + Header.ckSize, SEEK_SET);
                break;
                
            default:                
                /* skip chunks we don't know about */
                fseek(ifile, Header.ckSize, SEEK_CUR);                
                break;
        }        
    }
    /*
     * Set-up the output data file
     */

    FormChunk.formType = htonl(IFF_ID_AIFC);
    fwrite(&FormChunk, sizeof(Chunk), 1, ofile);

    Header.ckID = htonl('COMM');
    Header.ckSize = htonl(sizeof(CommChunk) + 12);
    fwrite(&Header, sizeof(Header), 1, ofile);
    CommChunk.compressionTypeH = htons('VA');
    CommChunk.compressionTypeL = htons('PC');

    cChunkPos = ftell(ofile);
    fwrite(&CommChunk, sizeof(CommonChunk), 1, ofile);
    strnLen = 11;
    fwrite(&strnLen, 1, 1, ofile);
    fwrite(compName, strnLen, 1, ofile);
    
    /*
     * Also write the instrument chunk to output file
     */
    Header.ckID = htonl('INST');
    Header.ckSize = htonl(20);
    fwrite(&Header, sizeof(Header), 1, ofile);
    fwrite(&InstChunk, sizeof(InstrumentChunk), 1, ofile);

    /*
     * Write the CODE application specific data chunk
     */
    tableSize = sizeof(short)*order*npredictors*VECTORSIZE;
    strnLen = 11;
    AppChunk.ckID = htonl('APPL');
    AppChunk.ckSize = htonl(tableSize + sizeof(long) + strnLen + 1 + sizeof(CodeChunk));
    AppChunk.formType = htonl('stoc');

    fwrite(&AppChunk, sizeof(AppChunk), 1, ofile);
    cChunk.version = htons(VERSION);
    cChunk.order = htons((short) order);
    cChunk.nEntries = htons((short) npredictors);
    fwrite(&strnLen, 1, 1, ofile);
    fwrite(appCodeName, strnLen, 1, ofile);
    fwrite(&cChunk, sizeof(CodeChunk), 1, ofile);
    for (i=0; i<npredictors; i++)
        for (j=0; j<order; j++)
            for (k=0; k<VECTORSIZE; k++){
                ts = htons(coefTable[i][k][j]);
                fwrite(&ts, sizeof(short), 1, ofile);
            }
    
    /*
     * Set up the input and output files to point to their
     * Sound data chunks and encode, recording the state for
     * each loop point
     */

    /*
     * The start points of the loops are in
     * sequential order.
     */
    currentPos = 0;
    if (soundPointer>0)
        fseek(ifile, soundPointer, SEEK_SET); 
    else {
        fprintf(stderr,"%s: Error in sound chunk",progname);
        exit(1);
    }

    /*
     * Write a space for the Sound data chunk - fill in data at end
     */
    soundPointer = ftell(ofile);
    fwrite(&CSndChunk, sizeof(ChunkHeader), 1, ofile);
    fwrite(&SndDChunk, sizeof(SoundDataChunk), 1, ofile);

    startSoundPointer = ftell(ifile);
    for (i=0; i<nloops; i++){
        if (lookupMarker(&aloops[i].start, loops[i].beginLoop, markers, numMarkers))
            fprintf(stderr, "%s: Start loop marker not found\n",progname);
        else 
            if (lookupMarker(&aloops[i].end, loops[i].endLoop, markers, numMarkers))
                fprintf(stderr, "%s: End loop marker not found\n",progname);
            else {
                /*
                 * Start pointer assuming 16 bit samples
                 */
                startPointer = startSoundPointer + aloops[i].start*sizeof(short);
                /*
                 * Check the length of the loop
                 */
                nRepeats = 0;
                newEnd = aloops[i].end;
                while ((newEnd - aloops[i].start) < minLoopLength){
                    nRepeats++;
                    newEnd += aloops[i].end - aloops[i].start;
                }
                
                while (currentPos <= aloops[i].start){
                    if (fread(inBuffer, sizeof(short), FRAMESIZE, ifile) == FRAMESIZE){
                        vencodeframe(ofile, inBuffer, state, coefTable, order, npredictors, FRAMESIZE);
                        currentPos += FRAMESIZE;
                        nBytes += FRAMEBYTES;
                    }
                    else {
                        fprintf(stderr,"%s: Not enough samples in file [%s]\n", progname, argv[1]);
                        exit(1);
                    }
                                        
                }

                /*
                 * Save the state for the start point
                 */
                for (j=0; j<FRAMESIZE; j++){
                    /*
                     * Have to clamp state just in case
                     */
                    if (state[j]>32767)
                        state[j] = 32767;
                    if (state[j]<-32767)
                        state[j] = -32767;
                    aloops[i].state[j] = (short) state[j];
                }
                aloops[i].count = -1; /* -1 is loop forever */

                /*
                 * If the loop length is to short repeat it
                 */

                while (nRepeats > 0){
                    for (; (currentPos+FRAMESIZE) < aloops[i].end; currentPos += FRAMESIZE)
                        if (fread(inBuffer, sizeof(short), FRAMESIZE, ifile) == FRAMESIZE){
                            vencodeframe(ofile, inBuffer, state, coefTable, order, npredictors, FRAMESIZE);
                            nBytes += FRAMEBYTES;
                        }
                    /*
                     * Patch up the end and start
                     */
                    left = aloops[i].end - currentPos;
                    fread(inBuffer, sizeof(short), left, ifile);
                    fseek(ifile, startPointer, SEEK_SET); 
                    fread(inBuffer + left, sizeof(short), FRAMESIZE - left, ifile);
                    vencodeframe(ofile, inBuffer, state, coefTable, order, npredictors, FRAMESIZE);
                    nBytes += FRAMEBYTES;
                    currentPos = aloops[i].start + FRAMESIZE - left;
                    nRepeats--;
                }
                /*
                 * Fix up the file pointer and the loop end point
                 */
                aloops[i].end = newEnd;
            }
    }

    /*
     * Finish up the rest of the file
     */
    nFrames = (CommChunk.numFramesH<<16) + CommChunk.numFramesL;
    fprintf(stderr, "nf %d\n", nFrames);
    if (truncate & (nloops!=0)){
        lookupMarker(&loopEnd, loops[nloops-1].endLoop, markers, numMarkers);
        nFrames = MIN(loopEnd+FRAMESIZE, nFrames);
    }
    
    while (currentPos<nFrames){
        if (nFrames-currentPos < FRAMESIZE){
            nsam = nFrames - currentPos;
        } else
            nsam = FRAMESIZE;
        if (fread(inBuffer, sizeof(short), nsam, ifile) == nsam){
            vencodeframe(ofile, inBuffer, state, coefTable, order, npredictors, nsam);
            currentPos += nsam;
            nBytes += FRAMEBYTES;
        } else{
            fprintf(stderr,"Missed a frame!\n");
            break;
        }
    }
    
    if (nBytes % 2){
        nBytes++;               /* Probably shouldn't be incremented.
        /*
         * Write a pad byte
         */
        ts = 0;
        fwrite(&ts, 1, 1, ofile);
    }
    
    /*
     * Write the LOOP application specific data chunk
     */
    if (nloops > 0){
        strnLen = 11;
        AppChunk.ckID = htonl('APPL');
        AppChunk.ckSize = htonl(nloops*sizeof(ALADPCMloop) + sizeof(long) + strnLen + 1 + 2*sizeof(short));
        AppChunk.formType = htonl('stoc');
        fwrite(&AppChunk, sizeof(AppChunk), 1, ofile);

        fwrite(&strnLen, 1, 1, ofile);
        fwrite(appLoopName, strnLen, 1, ofile);

        ts = htons(VERSION);
        fwrite(&ts, sizeof(short), 1, ofile);
        nloops = htons(nloops);
        fwrite(&nloops, sizeof(short), 1, ofile);
        nloops = htons(nloops);
        for (i=0; i<nloops; i++)
            fwrite(&aloops[i], sizeof(ALADPCMloop), 1, ofile);
    }
    
    /*
     * Fill in the data size for the compressed sound data
     */
    fseek(ofile, soundPointer, SEEK_SET);
    CSndChunk.ckID = htonl('SSND');
    CSndChunk.ckSize = htonl(nBytes + 8);
    fwrite(&CSndChunk, sizeof(ChunkHeader), 1, ofile);

    fseek(ofile, cChunkPos, SEEK_SET);
    nFrames = FRAMESIZE*nBytes/FRAMEBYTES;
    CommChunk.numFramesH = htons(nFrames)>>16;
    CommChunk.numFramesL = htons(nFrames & 0xffff);
    fwrite(&CommChunk, sizeof(CommonChunk), 1, ofile);

    fclose(ifile);
    fclose(ofile);
}