tinywavein_c.h 15.2 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
/*
 * Copyright (c) 2019-2020 Cadence Design Systems, Inc.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/*****************************************************************************
 (C) Copyright Ericsson AB and Fraunhofer Gesellschaft zur Förderung der
 angewandten Forschung e.V. for its Fraunhofer IIS 2018

 All Rights Reserved. This software and/or program is protected by copyright
 law and international treaties and may solely be used in connection with an
 respective Software Evaluation Agreement between the copyright owners and you.

 No part of this software may be reproduced in any form without the written
 permission of the copyright owners
******************************************************************************/

#ifndef __TINYWAVEIN_C_H__
#define __TINYWAVEIN_C_H__

/*#define SUPPORT_BWF*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) || defined(__arm__) || defined(__XTENSA__) ||            \
    defined(__aarch64__)
#define __TWI_LE /* _T_iny _W_ave _I_n _L_ittle _E_ndian */
#endif

#if defined(__POWERPC__)
#define __TWI_BE /* _T_iny _W_ave _I_n _B_ig _E_ndian */
#endif

#if !defined(__TWI_LE) && !defined(__TWI_BE)
#error unknown processor
#endif

#define __TWI_SUCCESS (0)
#define __TWI_ERROR (-1)

#ifdef SUPPORT_BWF
typedef struct
{
    float loudnessVal;
    float loudnessRange;
    float maxTruePeakLevel;
    float maxMomentaryLoudnes;
    float maxShortTermLoudness;
} WAVEIN_LOUDNESSINFO;
#endif

typedef struct __tinyWaveInHandle
{
    FILE *       theFile;
    fpos_t       dataChunkPos;
    unsigned int position;
    unsigned int length;
    unsigned int bps;
#ifdef SUPPORT_BWF
    WAVEIN_LOUDNESSINFO *loudnessInfo;
#endif
} __tinyWaveInHandle, WAVEFILEIN;

typedef struct
{
    short        compressionCode;
    short        numberOfChannels;
    unsigned int sampleRate;
    unsigned int averageBytesPerSecond;
    short        blockAlign;
    short        bitsPerSample;
    /* short extraFormatBytes ; */
} SWavInfo;

#ifdef SUPPORT_BWF
typedef struct
{
    unsigned char  description[256];
    unsigned char  originator[32];
    unsigned char  originatorReference[32];
    unsigned char  originatorDate[10]; /* ASCII: <<yyyy:mm:dd>> */
    unsigned char  originationTime[8]; /* ASCII: <<hh:mm:ss>> */
    unsigned int   timeReferenceLow;
    unsigned int   timeReferenceHigh;
    unsigned short version;
    unsigned char  UMID[64]; /* Binary Bytes of SMPTE UMID */

    signed short loudnessVal;
    signed short loudnessRange;
    signed short maxTruePeakLevel;
    signed short maxMomentaryLoudnes;
    signed short maxShortTermLoudness;

    unsigned char Reserved[180];

    unsigned char codingHistory; /* ASCII: <<History coding>> */
} SBwfWav;
#endif

typedef struct
{
    char         chunkID[4];
    unsigned int chunkSize;
    /* long dataOffset ; */ /* never used */
} SChunk;

/* local wrapper, always returns correct endian */
static size_t fread_LE(void *ptr, size_t size, size_t nmemb, FILE *stream);

#ifdef __TWI_BE
static short BigEndian16(short v);
static int   BigEndian32(int v);
#endif

/*!
 *  \brief Read header from a WAVEfile. Host endianess is handled accordingly.
 *  \fp filepointer of type FILE*.
 *  \wavinfo SWavInfo struct where the decoded header info is stored into.
 *  \return 0 on success and non-zero on failure.
 *
 */
static WAVEFILEIN *OpenWav(const char *filename, unsigned int *samplerate, short *channels, unsigned int *samplesInFile,
                           short *bps)
{
    WAVEFILEIN *self;

    SChunk       fmt_chunk, data_chunk;
    int          offset;
    unsigned int tmpSize;
    char         tmpFormat[4];
    SWavInfo     wavinfo = {0, 0, 0, 0, 0, 0};

    self = (WAVEFILEIN *)calloc(1, sizeof(WAVEFILEIN));
    if (!self)
        goto bail; /* return NULL; */

    if (!filename)
        goto bail;
    if (!samplerate)
        goto bail;
    if (!channels)
        goto bail;
    if (!samplesInFile)
        goto bail;
    if (!bps)
        goto bail;

    self->theFile = fopen(filename, "rb");
    if (!self->theFile)
        goto bail;

    /* read RIFF-chunk */
    if (fread(tmpFormat, 1, 4, self->theFile) != 4)
    {
        goto bail;
    }

    if (strncmp("RIFF", tmpFormat, 4))
    {
        goto bail;
    }

    /* Read RIFF size. Ignored. */
    fread_LE(&tmpSize, 4, 1, self->theFile);

    /* read WAVE-chunk */
    if (fread(tmpFormat, 1, 4, self->theFile) != 4)
    {
        goto bail;
    }

    if (strncmp("WAVE", tmpFormat, 4))
    {
        goto bail;
    }

    /* read format/bext-chunk */
    if (fread(fmt_chunk.chunkID, 1, 4, self->theFile) != 4)
    {
        goto bail;
    }

#ifdef SUPPORT_BWF
    /* test for bext-chunk */
    if (!strncmp("bext", fmt_chunk.chunkID, 4))
    {
        /*unsigned int i;*/
        unsigned int bextSize = 0;

        if (fread_LE(&bextSize, 1, 4, self->theFile) != 4)
        {
            goto bail;
        }

        self->loudnessInfo = (WAVEIN_LOUDNESSINFO *)calloc(1, sizeof(WAVEIN_LOUDNESSINFO));

        if (bextSize >= 602)
        { /* minimum size bext-data, w/o 'CodingHistory' */
            int          i;
            signed short readBuf = 0;
            signed int   nulbuf  = 0;

            /* first skip all descriptive data */
            for (i = 0; i < 412; i++)
            {
                if (fread_LE(&nulbuf, 1, 1, self->theFile) != 1)
                {
                    goto bail;
                }
                bextSize -= 1;
            }
            /* second, read loudness data */
            fread_LE(&readBuf, 2, 1, self->theFile);
            bextSize -= 2;
            self->loudnessInfo->loudnessVal = (float)readBuf * 0.01f;

            fread_LE(&readBuf, 2, 1, self->theFile);
            bextSize -= 2;
            self->loudnessInfo->loudnessRange = (float)readBuf * 0.01f;

            fread_LE(&readBuf, 2, 1, self->theFile);
            bextSize -= 2;
            self->loudnessInfo->maxTruePeakLevel = (float)readBuf * 0.01f;

            fread_LE(&readBuf, 2, 1, self->theFile);
            bextSize -= 2;
            self->loudnessInfo->maxMomentaryLoudnes = (float)readBuf * 0.01f;

            fread_LE(&readBuf, 2, 1, self->theFile);
            bextSize -= 2;
            self->loudnessInfo->maxShortTermLoudness = (float)readBuf * 0.01f;

            /* skip reserved data */
            for (i = 0; i < 180; i++)
            {
                if (fread_LE(&nulbuf, 1, 1, self->theFile) != 1)
                {
                    goto bail;
                }
                bextSize -= 1;
            }
        }

        /* skip remaining data */
        while (bextSize)
        {
            int nulbuf;
            if (fread_LE(&nulbuf, 1, 1, self->theFile) != 1)
            {
                goto bail;
            }
            bextSize -= 1;
        }

        /* read next chunk header */
        if (fread(fmt_chunk.chunkID, 1, 4, self->theFile) != 4)
        {
            goto bail;
        }
    }
#endif

    /* skip some potential chunks up to fmt chunk */
    
    while (strncmp("fmt ", fmt_chunk.chunkID, 4) != 0)
    {
        unsigned int chunkSize = 0;

        if (fread_LE(&chunkSize, 1, 4, self->theFile) != 4)
        {
            goto bail;
        }

        /* skip chunk data */
        while (chunkSize)
        {
            int nulbuf;
            if (fread_LE(&nulbuf, 1, 1, self->theFile) != 1)
            {
                goto bail;
            }
            chunkSize -= 1;
        }

        /* read next chunk header */
        if (fread(fmt_chunk.chunkID, 1, 4, self->theFile) != 4)
        {
            goto bail;
        }
    }

    /* go on with fmt-chunk */
    if (strncmp("fmt ", fmt_chunk.chunkID, 4))
    {
        goto bail;
    }

    if (fread_LE(&fmt_chunk.chunkSize, 4, 1, self->theFile) != 1)
    { /* should be 16 for PCM-format (uncompressed) */
        goto bail;
    }


    /* read  info */
    fread_LE(&(wavinfo.compressionCode), 2, 1, self->theFile);
    fread_LE(&(wavinfo.numberOfChannels), 2, 1, self->theFile);
    fread_LE(&(wavinfo.sampleRate), 4, 1, self->theFile);
    fread_LE(&(wavinfo.averageBytesPerSecond), 4, 1, self->theFile);
    fread_LE(&(wavinfo.blockAlign), 2, 1, self->theFile);
    fread_LE(&(wavinfo.bitsPerSample), 2, 1, self->theFile);

    if (wavinfo.compressionCode == -2)
    {
        fseek(self->theFile, 8, SEEK_CUR);                         // skip channel mask
        fread_LE(&(wavinfo.compressionCode), 2, 1, self->theFile); // part of GUID
        fseek(self->theFile, 14, SEEK_CUR);                        // skip rest of GUID
        offset = fmt_chunk.chunkSize - 40;
    }
    else
        offset = fmt_chunk.chunkSize - 16;

    if (wavinfo.compressionCode == 0x01)
    {
        if ((wavinfo.bitsPerSample != 16) && (wavinfo.bitsPerSample != 24) && (wavinfo.bitsPerSample != 32))
            /* we do only support 16,24 and 32 bit PCM audio */
            goto bail;
    }
    else
    {
        /* if(wavinfo.bitsPerSample != 32) */
        printf("compressioncode: %02x\n", wavinfo.compressionCode);
        puts("Error! We only support 16,24 and 32 bit PCM audio");
        exit(1);
        goto bail;
    }

    /* Skip rest of fmt header if any. */
    for (; offset > 0; offset--)
    {
        fread(&tmpSize, 1, 1, self->theFile);
    }

    do
    {

        /* Read data chunk ID */
        if (fread(data_chunk.chunkID, 1, 4, self->theFile) != 4)
        {
            goto bail;
        }

        /* Read chunk length. */

        if (fread_LE(&offset, 4, 1, self->theFile) != 1)
        {
            goto bail;
        }

        /* Check for data chunk signature. */
        if (strncmp("data", data_chunk.chunkID, 4) == 0)
        {
            data_chunk.chunkSize = offset;
            break;
        }

        /* unused 1 byte present, if size is odd */
        /* see https://www.daubnet.com/en/file-format-riff */
        if (offset % 2)
        {
            offset++;
        }

        /* Jump over non data chunk. */
        for (; offset > 0; offset--)
        {
            fread(&tmpSize, 1, 1, self->theFile);
        }

    } while (!feof(self->theFile));

    /* success so far */
    *samplerate    = wavinfo.sampleRate;
    *channels      = wavinfo.numberOfChannels;
    *samplesInFile = data_chunk.chunkSize / wavinfo.numberOfChannels;
    *samplesInFile /= ((wavinfo.bitsPerSample + 7) / 8);
    *bps = wavinfo.bitsPerSample;

    self->position = 0;
    self->bps      = wavinfo.bitsPerSample;
    self->length   = *samplesInFile * wavinfo.numberOfChannels;

    fgetpos(self->theFile, &self->dataChunkPos);

    return self;

bail:
    free(self);
    return NULL;
}

#ifdef SUPPORT_BWF
static void ReadBWF(WAVEFILEIN *self, WAVEIN_LOUDNESSINFO **wavInLoudness)
{
    *wavInLoudness = self->loudnessInfo;
}
#endif

static int __ReadSample16(WAVEFILEIN *self, int *sample)
{
    size_t cnt;
    short  v = 0;

    cnt = fread(&v, 2, 1, self->theFile);

    if (cnt != 1)
    {
        return __TWI_ERROR;
    }

    self->position += 1;

#ifdef __TWI_BE
    v = BigEndian16(v);
#endif
    *sample = v;
    return __TWI_SUCCESS;
}

static int __ReadSample24(WAVEFILEIN *self, int *sample)
{
    size_t cnt;
    int    v = 0;

    cnt = fread(&v, 3, 1, self->theFile);

    if (cnt != 1)
    {
        return __TWI_ERROR;
    }

    self->position += 1;

#ifdef __TWI_BE
    v = BigEndian32(v);
#endif

    if (v >= 0x800000)
    {
        v |= 0xff000000;
    }

    *sample = v;

    return __TWI_SUCCESS;
}

static int __ReadSample32(WAVEFILEIN *self, int *sample)
{
    size_t cnt;
    int    v = 0;

    cnt = fread(&v, 4, 1, self->theFile);

    if (cnt != 1)
    {
        return __TWI_ERROR;
    }

    self->position += 1;

#ifdef __TWI_BE
    v = BigEndian32(v);
#endif

    *sample = v >> 8;

    return __TWI_SUCCESS;
}

static int __ReadSampleInternal(WAVEFILEIN *self, int *sample, int scale)
{
    int err;

    if (!self)
    {
        return __TWI_ERROR;
    }

    switch (scale)
    {

    case 16: err = __ReadSample16(self, sample); break;

    case 24: err = __ReadSample24(self, sample); break;

    case 32: err = __ReadSample32(self, sample); break;

    default: err = __TWI_ERROR; break;
    }

    return err;
}

/* this function returns normalized values in the range +8388607..-8388608 */
static int ReadWavInt(WAVEFILEIN *self, int sampleBuffer[], unsigned int nSamplesToRead, unsigned int *nSamplesRead)
{
    unsigned int i;
    int          err = __TWI_SUCCESS;
    *nSamplesRead    = 0;

    if (!sampleBuffer)
    {
        return __TWI_ERROR;
    }

    /* check if we have enough samples left, if not,
       set nSamplesToRead to number of samples left. */
    if (self->position + nSamplesToRead > self->length)
    {
        nSamplesToRead = self->length - self->position;
    }

    for (i = 0; i < nSamplesToRead; i++)
    {

        int tmp;
        err = __ReadSampleInternal(self, &tmp, self->bps);
        if (err != __TWI_SUCCESS)
        {
            return err;
        }
        sampleBuffer[i] = tmp;
        *nSamplesRead += 1;
    }

    return __TWI_SUCCESS;
}

static int CloseWavIn(WAVEFILEIN *self)
{
    if (self)
    {
        if (self->theFile)
        {
            fclose(self->theFile);
        }
    }
    free(self);

    return __TWI_SUCCESS;
}
/*
static int ResetWavIn(WAVEFILEIN* self)
{
  if (self) {
    if (self->theFile) {
        fsetpos(self->theFile, &self->dataChunkPos);
        self->position = 0;
    }
  }
  return __TWI_SUCCESS;
}
*/
/*------------- local subs ----------------*/

static size_t fread_LE(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
#ifdef __TWI_LE
    return fread(ptr, size, nmemb, stream);
#endif
#ifdef __TWI_BE

    unsigned char  x[sizeof(int)];
    unsigned char *y = (unsigned char *)ptr;
    int            i;
    int            len;

    len = fread(x, size, nmemb, stream);

    for (i = 0; i < size * nmemb; i++)
    {
        *y++ = x[size * nmemb - i - 1];
    }

    return len;
#endif
}

#ifdef __TWI_BE
static short BigEndian16(short v)
{
    short a = (v & 0x0ff);
    short b = (v & 0x0ff00) >> 8;

    return a << 8 | b;
}

static int BigEndian32(int v)
{
    int a = (v & 0x0ff);
    int b = (v & 0x0ff00) >> 8;
    int c = (v & 0x0ff0000) >> 16;
    int d = (v & 0xff000000) >> 24;

    return a << 24 | b << 16 | c << 8 | d;
}
#endif

#endif /* __TINYWAVEIN_C_H__ */