src/audio/SDL_audiocvt.c
author Ryan C. Gordon <icculus@icculus.org>
Mon, 23 Jan 2017 01:05:44 -0500
changeset 10835 0e9e7a128391
parent 10834 336efe4fc373
child 10839 64f7fccca56e
permissions -rw-r--r--
audio: Wired up new SSE code to build system.
slouken@0
     1
/*
slouken@5535
     2
  Simple DirectMedia Layer
slouken@10737
     3
  Copyright (C) 1997-2017 Sam Lantinga <slouken@libsdl.org>
slouken@0
     4
slouken@5535
     5
  This software is provided 'as-is', without any express or implied
slouken@5535
     6
  warranty.  In no event will the authors be held liable for any damages
slouken@5535
     7
  arising from the use of this software.
slouken@0
     8
slouken@5535
     9
  Permission is granted to anyone to use this software for any purpose,
slouken@5535
    10
  including commercial applications, and to alter it and redistribute it
slouken@5535
    11
  freely, subject to the following restrictions:
slouken@0
    12
slouken@5535
    13
  1. The origin of this software must not be misrepresented; you must not
slouken@5535
    14
     claim that you wrote the original software. If you use this software
slouken@5535
    15
     in a product, an acknowledgment in the product documentation would be
slouken@5535
    16
     appreciated but is not required.
slouken@5535
    17
  2. Altered source versions must be plainly marked as such, and must not be
slouken@5535
    18
     misrepresented as being the original software.
slouken@5535
    19
  3. This notice may not be removed or altered from any source distribution.
slouken@0
    20
*/
icculus@8093
    21
#include "../SDL_internal.h"
slouken@2728
    22
slouken@0
    23
/* Functions for audio drivers to perform runtime conversion of audio format */
slouken@0
    24
slouken@0
    25
#include "SDL_audio.h"
icculus@1982
    26
#include "SDL_audio_c.h"
slouken@0
    27
slouken@10773
    28
#include "SDL_loadso.h"
icculus@6281
    29
#include "SDL_assert.h"
icculus@10757
    30
#include "../SDL_dataqueue.h"
icculus@10835
    31
#include "SDL_cpuinfo.h"
icculus@6281
    32
icculus@10835
    33
#ifdef __SSE3__
icculus@10835
    34
#define HAVE_SSE3_INTRINSICS 1
icculus@10832
    35
#endif
icculus@10832
    36
icculus@10832
    37
#if HAVE_SSE3_INTRINSICS
icculus@10832
    38
/* Effectively mix right and left channels into a single channel */
icculus@10832
    39
static void SDLCALL
icculus@10832
    40
SDL_ConvertStereoToMono_SSE3(SDL_AudioCVT * cvt, SDL_AudioFormat format)
icculus@10832
    41
{
icculus@10832
    42
    float *dst = (float *) cvt->buf;
icculus@10832
    43
    const float *src = dst;
icculus@10832
    44
    int i = cvt->len_cvt / 8;
icculus@10832
    45
icculus@10832
    46
    LOG_DEBUG_CONVERT("stereo", "mono (using SSE3)");
icculus@10832
    47
    SDL_assert(format == AUDIO_F32SYS);
icculus@10832
    48
icculus@10832
    49
    /* We can only do this if dst is aligned to 16 bytes; since src is the
icculus@10832
    50
       same pointer and it moves by 2, it can't be forcibly aligned. */
icculus@10832
    51
    if ((((size_t) dst) & 15) == 0) {
icculus@10832
    52
        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
icculus@10832
    53
        const __m128 divby2 = _mm_set1_ps(0.5f);
icculus@10832
    54
        while (i >= 4) {   /* 4 * float32 */
icculus@10832
    55
            _mm_store_ps(dst, _mm_mul_ps(_mm_hadd_ps(_mm_load_ps(src), _mm_load_ps(src+4)), divby2));
icculus@10832
    56
            i -= 4; src += 8; dst += 4;
icculus@10832
    57
        }
icculus@10832
    58
    }
icculus@10832
    59
icculus@10832
    60
    /* Finish off any leftovers with scalar operations. */
icculus@10832
    61
    while (i) {
icculus@10832
    62
        *dst = (src[0] + src[1]) * 0.5f;
icculus@10832
    63
        dst++; i--; src += 2;
icculus@10832
    64
    }
icculus@10832
    65
icculus@10832
    66
    cvt->len_cvt /= 2;
icculus@10832
    67
    if (cvt->filters[++cvt->filter_index]) {
icculus@10832
    68
        cvt->filters[cvt->filter_index] (cvt, format);
icculus@10832
    69
    }
icculus@10832
    70
}
icculus@10832
    71
#endif
icculus@10832
    72
slouken@0
    73
/* Effectively mix right and left channels into a single channel */
icculus@1982
    74
static void SDLCALL
icculus@10793
    75
SDL_ConvertStereoToMono(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@0
    76
{
icculus@10575
    77
    float *dst = (float *) cvt->buf;
icculus@10575
    78
    const float *src = dst;
slouken@1895
    79
    int i;
slouken@0
    80
icculus@10575
    81
    LOG_DEBUG_CONVERT("stereo", "mono");
icculus@10575
    82
    SDL_assert(format == AUDIO_F32SYS);
slouken@0
    83
icculus@10575
    84
    for (i = cvt->len_cvt / 8; i; --i, src += 2) {
icculus@10831
    85
        *(dst++) = (src[0] + src[1]) * 0.5f;
slouken@1895
    86
    }
icculus@1982
    87
slouken@1895
    88
    cvt->len_cvt /= 2;
slouken@1895
    89
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
    90
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
    91
    }
slouken@0
    92
}
slouken@0
    93
icculus@1982
    94
icculus@10793
    95
/* Convert from 5.1 to stereo. Average left and right, discard subwoofer. */
icculus@1982
    96
static void SDLCALL
icculus@10793
    97
SDL_Convert51ToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@942
    98
{
icculus@10575
    99
    float *dst = (float *) cvt->buf;
icculus@10575
   100
    const float *src = dst;
slouken@1895
   101
    int i;
slouken@942
   102
icculus@10793
   103
    LOG_DEBUG_CONVERT("5.1", "stereo");
icculus@10575
   104
    SDL_assert(format == AUDIO_F32SYS);
slouken@942
   105
icculus@10793
   106
    /* this assumes FL+FR+FC+subwoof+BL+BR layout. */
icculus@10575
   107
    for (i = cvt->len_cvt / (sizeof (float) * 6); i; --i, src += 6, dst += 2) {
icculus@10793
   108
        const double front_center = (double) src[2];
icculus@10793
   109
        dst[0] = (float) ((src[0] + front_center + src[4]) / 3.0);  /* left */
icculus@10793
   110
        dst[1] = (float) ((src[1] + front_center + src[5]) / 3.0);  /* right */
icculus@1982
   111
    }
slouken@942
   112
slouken@1895
   113
    cvt->len_cvt /= 3;
slouken@1895
   114
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
   115
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
   116
    }
slouken@942
   117
}
slouken@942
   118
slouken@942
   119
icculus@10793
   120
/* Convert from 5.1 to quad */
icculus@1982
   121
static void SDLCALL
icculus@10793
   122
SDL_Convert51ToQuad(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@942
   123
{
icculus@10575
   124
    float *dst = (float *) cvt->buf;
icculus@10575
   125
    const float *src = dst;
slouken@1895
   126
    int i;
slouken@942
   127
icculus@10793
   128
    LOG_DEBUG_CONVERT("5.1", "quad");
icculus@10575
   129
    SDL_assert(format == AUDIO_F32SYS);
slouken@942
   130
icculus@10793
   131
    /* assumes quad is FL+FR+BL+BR layout and 5.1 is FL+FR+FC+subwoof+BL+BR */
icculus@10575
   132
    for (i = cvt->len_cvt / (sizeof (float) * 6); i; --i, src += 6, dst += 4) {
icculus@10793
   133
        /* FIXME: this is a good candidate for SIMD. */
icculus@10793
   134
        const double front_center = (double) src[2];
icculus@10793
   135
        dst[0] = (float) ((src[0] + front_center) * 0.5);  /* FL */
icculus@10793
   136
        dst[1] = (float) ((src[1] + front_center) * 0.5);  /* FR */
icculus@10793
   137
        dst[2] = (float) ((src[4] + front_center) * 0.5);  /* BL */
icculus@10793
   138
        dst[3] = (float) ((src[5] + front_center) * 0.5);  /* BR */
icculus@1982
   139
    }
slouken@942
   140
icculus@1982
   141
    cvt->len_cvt /= 6;
icculus@1982
   142
    cvt->len_cvt *= 4;
slouken@1895
   143
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
   144
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
   145
    }
slouken@942
   146
}
slouken@0
   147
icculus@10793
   148
slouken@0
   149
/* Duplicate a mono channel to both stereo channels */
icculus@1982
   150
static void SDLCALL
icculus@10793
   151
SDL_ConvertMonoToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@0
   152
{
icculus@10575
   153
    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
icculus@10575
   154
    float *dst = (float *) (cvt->buf + cvt->len_cvt * 2);
slouken@1895
   155
    int i;
slouken@0
   156
icculus@10575
   157
    LOG_DEBUG_CONVERT("mono", "stereo");
icculus@10575
   158
    SDL_assert(format == AUDIO_F32SYS);
slouken@0
   159
icculus@10575
   160
    for (i = cvt->len_cvt / sizeof (float); i; --i) {
icculus@10575
   161
        src--;
icculus@10575
   162
        dst -= 2;
icculus@10575
   163
        dst[0] = dst[1] = *src;
icculus@1982
   164
    }
slouken@0
   165
slouken@1895
   166
    cvt->len_cvt *= 2;
slouken@1895
   167
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
   168
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
   169
    }
slouken@0
   170
}
slouken@0
   171
slouken@942
   172
slouken@942
   173
/* Duplicate a stereo channel to a pseudo-5.1 stream */
icculus@1982
   174
static void SDLCALL
icculus@10793
   175
SDL_ConvertStereoTo51(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@942
   176
{
slouken@1895
   177
    int i;
icculus@10575
   178
    float lf, rf, ce;
icculus@10575
   179
    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
icculus@10575
   180
    float *dst = (float *) (cvt->buf + cvt->len_cvt * 3);
slouken@942
   181
icculus@10575
   182
    LOG_DEBUG_CONVERT("stereo", "5.1");
icculus@10575
   183
    SDL_assert(format == AUDIO_F32SYS);
slouken@942
   184
icculus@10575
   185
    for (i = cvt->len_cvt / 8; i; --i) {
icculus@10575
   186
        dst -= 6;
icculus@10575
   187
        src -= 2;
icculus@10575
   188
        lf = src[0];
icculus@10575
   189
        rf = src[1];
icculus@10793
   190
        ce = (lf + rf) * 0.5f;
icculus@10793
   191
        dst[0] = lf + (lf - ce);  /* FL */
icculus@10793
   192
        dst[1] = rf + (rf - ce);  /* FR */
icculus@10793
   193
        dst[2] = ce;  /* FC */
icculus@10793
   194
        dst[3] = ce;  /* !!! FIXME: wrong! This is the subwoofer. */
icculus@10793
   195
        dst[4] = lf;  /* BL */
icculus@10793
   196
        dst[5] = rf;  /* BR */
icculus@10575
   197
    }
slouken@942
   198
slouken@1895
   199
    cvt->len_cvt *= 3;
slouken@1895
   200
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
   201
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
   202
    }
slouken@942
   203
}
slouken@942
   204
slouken@942
   205
slouken@942
   206
/* Duplicate a stereo channel to a pseudo-4.0 stream */
icculus@1982
   207
static void SDLCALL
icculus@10793
   208
SDL_ConvertStereoToQuad(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@942
   209
{
icculus@10575
   210
    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
icculus@10575
   211
    float *dst = (float *) (cvt->buf + cvt->len_cvt * 2);
icculus@10793
   212
    float lf, rf;
slouken@1895
   213
    int i;
slouken@942
   214
icculus@10575
   215
    LOG_DEBUG_CONVERT("stereo", "quad");
icculus@10575
   216
    SDL_assert(format == AUDIO_F32SYS);
slouken@942
   217
icculus@10575
   218
    for (i = cvt->len_cvt / 8; i; --i) {
icculus@10575
   219
        dst -= 4;
icculus@10575
   220
        src -= 2;
icculus@10575
   221
        lf = src[0];
icculus@10575
   222
        rf = src[1];
icculus@10793
   223
        dst[0] = lf;  /* FL */
icculus@10793
   224
        dst[1] = rf;  /* FR */
icculus@10793
   225
        dst[2] = lf;  /* BL */
icculus@10793
   226
        dst[3] = rf;  /* BR */
icculus@10575
   227
    }
slouken@942
   228
slouken@1895
   229
    cvt->len_cvt *= 2;
slouken@1895
   230
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
   231
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
   232
    }
slouken@0
   233
}
slouken@0
   234
icculus@10799
   235
static int
icculus@10799
   236
SDL_ResampleAudioSimple(const int chans, const double rate_incr,
icculus@10799
   237
                        float *last_sample, const float *inbuf,
icculus@10799
   238
                        const int inbuflen, float *outbuf, const int outbuflen)
icculus@10799
   239
{
icculus@10817
   240
    const int framelen = chans * (int)sizeof (float);
icculus@10799
   241
    const int total = (inbuflen / framelen);
icculus@10817
   242
    const int finalpos = (total * chans) - chans;
icculus@10817
   243
    const int dest_samples = (int)(((double)total) * rate_incr);
icculus@10799
   244
    const double src_incr = 1.0 / rate_incr;
icculus@10833
   245
    float *dst;
icculus@10833
   246
    double idx;
icculus@10799
   247
    int i;
icculus@10799
   248
icculus@10817
   249
    SDL_assert((dest_samples * framelen) <= outbuflen);
icculus@10799
   250
    SDL_assert((inbuflen % framelen) == 0);
icculus@10799
   251
icculus@10833
   252
    if (rate_incr > 1.0) {
icculus@10833
   253
        float *target = (outbuf + chans);
icculus@10833
   254
        const float *earlier_sample = &inbuf[finalpos];
icculus@10833
   255
        float final_sample[8];
icculus@10833
   256
        dst = outbuf + (dest_samples * chans);
icculus@10833
   257
        idx = (double) total;
icculus@10833
   258
icculus@10833
   259
        /* save this off so we can correctly maintain state between runs. */
icculus@10833
   260
        SDL_memcpy(final_sample, &inbuf[finalpos], framelen);
icculus@10833
   261
icculus@10833
   262
        while (dst > target) {
icculus@10833
   263
            const int pos = ((int) idx) * chans;
icculus@10833
   264
            const float *src = &inbuf[pos];
icculus@10833
   265
            SDL_assert(pos >= 0.0);
icculus@10833
   266
            for (i = chans - 1; i >= 0; i--) {
icculus@10833
   267
                const float val = *(--src);
icculus@10833
   268
                *(--dst) = (val + earlier_sample[i]) * 0.5f;
icculus@10833
   269
            }
icculus@10833
   270
            earlier_sample = src;
icculus@10833
   271
            idx -= src_incr;
icculus@10799
   272
        }
icculus@10833
   273
icculus@10833
   274
        /* do last sample, interpolated against previous run's state. */
icculus@10833
   275
        for (i = chans - 1; i >= 0; i--) {
icculus@10833
   276
            const float val = inbuf[i];
icculus@10833
   277
            *(--dst) = (val + last_sample[i]) * 0.5f;
icculus@10833
   278
        }
icculus@10833
   279
        SDL_memcpy(last_sample, final_sample, framelen);
icculus@10833
   280
        dst = (outbuf + (dest_samples * chans)) - 1;
icculus@10833
   281
    } else {
icculus@10833
   282
        float *target = (outbuf + (dest_samples * chans));
icculus@10833
   283
        dst = outbuf;
icculus@10833
   284
        idx = 0.0;
icculus@10833
   285
        while (dst < target) {
icculus@10833
   286
            const int pos = ((int) idx) * chans;
icculus@10833
   287
            const float *src = &inbuf[pos];
icculus@10833
   288
            SDL_assert(pos <= finalpos);
icculus@10833
   289
            for (i = 0; i < chans; i++) {
icculus@10833
   290
                const float val = *(src++);
icculus@10833
   291
                *(dst++) = (val + last_sample[i]) * 0.5f;
icculus@10833
   292
                last_sample[i] = val;
icculus@10833
   293
            }
icculus@10833
   294
            idx += src_incr;
icculus@10833
   295
        }
icculus@10799
   296
    }
icculus@10799
   297
icculus@10833
   298
    return (int) ((dst - outbuf) * ((int) sizeof (float)));
icculus@10799
   299
}
icculus@10799
   300
icculus@10834
   301
/* We keep one special-case fast path around for an extremely common audio format. */
icculus@10834
   302
static int
icculus@10834
   303
SDL_ResampleAudioSimple_si16_c2(const double rate_incr,
icculus@10834
   304
                        Sint16 *last_sample, const Sint16 *inbuf,
icculus@10834
   305
                        const int inbuflen, Sint16 *outbuf, const int outbuflen)
icculus@10834
   306
{
icculus@10834
   307
    const int chans = 2;
icculus@10834
   308
    const int framelen = 4;  /* stereo 16 bit */
icculus@10834
   309
    const int total = (inbuflen / framelen);
icculus@10834
   310
    const int finalpos = (total * chans) - chans;
icculus@10834
   311
    const int dest_samples = (int)(((double)total) * rate_incr);
icculus@10834
   312
    const double src_incr = 1.0 / rate_incr;
icculus@10834
   313
    Sint16 *dst;
icculus@10834
   314
    double idx;
icculus@10834
   315
icculus@10834
   316
    SDL_assert((dest_samples * framelen) <= outbuflen);
icculus@10834
   317
    SDL_assert((inbuflen % framelen) == 0);
icculus@10834
   318
icculus@10834
   319
    if (rate_incr > 1.0) {
icculus@10834
   320
        Sint16 *target = (outbuf + chans);
icculus@10834
   321
        const Sint16 final_right = inbuf[finalpos+1];
icculus@10834
   322
        const Sint16 final_left = inbuf[finalpos];
icculus@10834
   323
        Sint16 earlier_right = inbuf[finalpos-1];
icculus@10834
   324
        Sint16 earlier_left = inbuf[finalpos-2];
icculus@10834
   325
        dst = outbuf + (dest_samples * chans);
icculus@10834
   326
        idx = (double) total;
icculus@10834
   327
icculus@10834
   328
        while (dst > target) {
icculus@10834
   329
            const int pos = ((int) idx) * chans;
icculus@10834
   330
            const Sint16 *src = &inbuf[pos];
icculus@10834
   331
            const Sint16 right = *(--src);
icculus@10834
   332
            const Sint16 left = *(--src);
icculus@10834
   333
            SDL_assert(pos >= 0.0);
icculus@10834
   334
            *(--dst) = (((Sint32) right) + ((Sint32) earlier_right)) >> 1;
icculus@10834
   335
            *(--dst) = (((Sint32) left) + ((Sint32) earlier_left)) >> 1;
icculus@10834
   336
            earlier_right = right;
icculus@10834
   337
            earlier_left = left;
icculus@10834
   338
            idx -= src_incr;
icculus@10834
   339
        }
icculus@10834
   340
icculus@10834
   341
        /* do last sample, interpolated against previous run's state. */
icculus@10834
   342
        *(--dst) = (((Sint32) inbuf[1]) + ((Sint32) last_sample[1])) >> 1;
icculus@10834
   343
        *(--dst) = (((Sint32) inbuf[0]) + ((Sint32) last_sample[0])) >> 1;
icculus@10834
   344
        last_sample[1] = final_right;
icculus@10834
   345
        last_sample[0] = final_left;
icculus@10834
   346
icculus@10834
   347
        dst = (outbuf + (dest_samples * chans)) - 1;
icculus@10834
   348
    } else {
icculus@10834
   349
        Sint16 *target = (outbuf + (dest_samples * chans));
icculus@10834
   350
        dst = outbuf;
icculus@10834
   351
        idx = 0.0;
icculus@10834
   352
        while (dst < target) {
icculus@10834
   353
            const int pos = ((int) idx) * chans;
icculus@10834
   354
            const Sint16 *src = &inbuf[pos];
icculus@10834
   355
            const Sint16 left = *(src++);
icculus@10834
   356
            const Sint16 right = *(src++);
icculus@10834
   357
            SDL_assert(pos <= finalpos);
icculus@10834
   358
            *(dst++) = (((Sint32) left) + ((Sint32) last_sample[0])) >> 1;
icculus@10834
   359
            *(dst++) = (((Sint32) right) + ((Sint32) last_sample[1])) >> 1;
icculus@10834
   360
            last_sample[0] = left;
icculus@10834
   361
            last_sample[1] = right;
icculus@10834
   362
            idx += src_incr;
icculus@10834
   363
        }
icculus@10834
   364
    }
icculus@10834
   365
icculus@10834
   366
    return (int) ((dst - outbuf) * ((int) sizeof (Sint16)));
icculus@10834
   367
}
icculus@10834
   368
icculus@10834
   369
static void SDLCALL
icculus@10834
   370
SDL_ResampleCVT_si16_c2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
icculus@10834
   371
{
icculus@10834
   372
    const Sint16 *src = (const Sint16 *) cvt->buf;
icculus@10834
   373
    const int srclen = cvt->len_cvt;
icculus@10834
   374
    Sint16 *dst = (Sint16 *) (cvt->buf + srclen);
icculus@10834
   375
    const int dstlen = (cvt->len * cvt->len_mult) - srclen;
icculus@10834
   376
    Sint16 state[2] = { src[0], src[1] };
icculus@10834
   377
icculus@10834
   378
    SDL_assert(format == AUDIO_S16SYS);
icculus@10834
   379
icculus@10834
   380
    cvt->len_cvt = SDL_ResampleAudioSimple_si16_c2(cvt->rate_incr, state, src, srclen, dst, dstlen);
icculus@10834
   381
    if (cvt->filters[++cvt->filter_index]) {
icculus@10834
   382
        cvt->filters[cvt->filter_index](cvt, format);
icculus@10834
   383
    }
icculus@10834
   384
}
icculus@10834
   385
slouken@0
   386
slouken@1895
   387
int
slouken@1895
   388
SDL_ConvertAudio(SDL_AudioCVT * cvt)
slouken@0
   389
{
icculus@3021
   390
    /* !!! FIXME: (cvt) should be const; stack-copy it here. */
icculus@3021
   391
    /* !!! FIXME: (actually, we can't...len_cvt needs to be updated. Grr.) */
icculus@3021
   392
slouken@1895
   393
    /* Make sure there's data to convert */
slouken@1895
   394
    if (cvt->buf == NULL) {
icculus@10575
   395
        return SDL_SetError("No buffer allocated for conversion");
slouken@1895
   396
    }
icculus@10575
   397
slouken@1895
   398
    /* Return okay if no conversion is necessary */
slouken@1895
   399
    cvt->len_cvt = cvt->len;
slouken@1895
   400
    if (cvt->filters[0] == NULL) {
icculus@10575
   401
        return 0;
slouken@1895
   402
    }
slouken@0
   403
slouken@1895
   404
    /* Set up the conversion and go! */
slouken@1895
   405
    cvt->filter_index = 0;
slouken@1895
   406
    cvt->filters[0] (cvt, cvt->src_format);
icculus@10575
   407
    return 0;
slouken@0
   408
}
slouken@0
   409
icculus@10575
   410
static void SDLCALL
icculus@10575
   411
SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format)
icculus@10575
   412
{
slouken@10579
   413
#if DEBUG_CONVERT
slouken@10579
   414
    printf("Converting byte order\n");
slouken@10579
   415
#endif
icculus@1982
   416
icculus@10575
   417
    switch (SDL_AUDIO_BITSIZE(format)) {
icculus@10575
   418
        #define CASESWAP(b) \
icculus@10575
   419
            case b: { \
icculus@10575
   420
                Uint##b *ptr = (Uint##b *) cvt->buf; \
icculus@10575
   421
                int i; \
icculus@10575
   422
                for (i = cvt->len_cvt / sizeof (*ptr); i; --i, ++ptr) { \
icculus@10575
   423
                    *ptr = SDL_Swap##b(*ptr); \
icculus@10575
   424
                } \
icculus@10575
   425
                break; \
icculus@10575
   426
            }
icculus@1982
   427
icculus@10575
   428
        CASESWAP(16);
icculus@10575
   429
        CASESWAP(32);
icculus@10575
   430
        CASESWAP(64);
icculus@10575
   431
icculus@10575
   432
        #undef CASESWAP
icculus@10575
   433
icculus@10575
   434
        default: SDL_assert(!"unhandled byteswap datatype!"); break;
icculus@10575
   435
    }
icculus@10575
   436
icculus@10575
   437
    if (cvt->filters[++cvt->filter_index]) {
icculus@10575
   438
        /* flip endian flag for data. */
icculus@10575
   439
        if (format & SDL_AUDIO_MASK_ENDIAN) {
icculus@10575
   440
            format &= ~SDL_AUDIO_MASK_ENDIAN;
icculus@10575
   441
        } else {
icculus@10575
   442
            format |= SDL_AUDIO_MASK_ENDIAN;
icculus@10575
   443
        }
icculus@10575
   444
        cvt->filters[cvt->filter_index](cvt, format);
icculus@10575
   445
    }
icculus@1982
   446
}
icculus@1982
   447
icculus@1982
   448
icculus@1982
   449
static int
icculus@10575
   450
SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt)
icculus@1982
   451
{
icculus@10575
   452
    int retval = 0;  /* 0 == no conversion necessary. */
icculus@1982
   453
icculus@10575
   454
    if ((SDL_AUDIO_ISBIGENDIAN(src_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) {
icculus@10575
   455
        cvt->filters[cvt->filter_index++] = SDL_Convert_Byteswap;
icculus@10575
   456
        retval = 1;  /* added a converter. */
icculus@10575
   457
    }
icculus@1982
   458
icculus@10575
   459
    if (!SDL_AUDIO_ISFLOAT(src_fmt)) {
icculus@10576
   460
        const Uint16 src_bitsize = SDL_AUDIO_BITSIZE(src_fmt);
icculus@10576
   461
        const Uint16 dst_bitsize = 32;
icculus@10575
   462
        SDL_AudioFilter filter = NULL;
icculus@10576
   463
icculus@10575
   464
        switch (src_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
icculus@10575
   465
            case AUDIO_S8: filter = SDL_Convert_S8_to_F32; break;
icculus@10575
   466
            case AUDIO_U8: filter = SDL_Convert_U8_to_F32; break;
icculus@10575
   467
            case AUDIO_S16: filter = SDL_Convert_S16_to_F32; break;
philipp@10591
   468
            case AUDIO_U16: filter = SDL_Convert_U16_to_F32; break;
icculus@10575
   469
            case AUDIO_S32: filter = SDL_Convert_S32_to_F32; break;
icculus@10575
   470
            default: SDL_assert(!"Unexpected audio format!"); break;
icculus@1982
   471
        }
icculus@1982
   472
icculus@10575
   473
        if (!filter) {
icculus@10575
   474
            return SDL_SetError("No conversion available for these formats");
icculus@10575
   475
        }
icculus@10575
   476
icculus@1982
   477
        cvt->filters[cvt->filter_index++] = filter;
icculus@1982
   478
        if (src_bitsize < dst_bitsize) {
icculus@1982
   479
            const int mult = (dst_bitsize / src_bitsize);
icculus@1982
   480
            cvt->len_mult *= mult;
icculus@1982
   481
            cvt->len_ratio *= mult;
icculus@1982
   482
        } else if (src_bitsize > dst_bitsize) {
icculus@1982
   483
            cvt->len_ratio /= (src_bitsize / dst_bitsize);
icculus@1982
   484
        }
icculus@10576
   485
icculus@10575
   486
        retval = 1;  /* added a converter. */
icculus@1982
   487
    }
icculus@1982
   488
icculus@10575
   489
    return retval;
icculus@1982
   490
}
icculus@1982
   491
icculus@10575
   492
static int
icculus@10575
   493
SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt)
icculus@10575
   494
{
icculus@10575
   495
    int retval = 0;  /* 0 == no conversion necessary. */
icculus@3021
   496
icculus@10575
   497
    if (!SDL_AUDIO_ISFLOAT(dst_fmt)) {
icculus@10577
   498
        const Uint16 dst_bitsize = SDL_AUDIO_BITSIZE(dst_fmt);
icculus@10577
   499
        const Uint16 src_bitsize = 32;
icculus@10575
   500
        SDL_AudioFilter filter = NULL;
icculus@10575
   501
        switch (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
icculus@10575
   502
            case AUDIO_S8: filter = SDL_Convert_F32_to_S8; break;
icculus@10575
   503
            case AUDIO_U8: filter = SDL_Convert_F32_to_U8; break;
icculus@10575
   504
            case AUDIO_S16: filter = SDL_Convert_F32_to_S16; break;
philipp@10591
   505
            case AUDIO_U16: filter = SDL_Convert_F32_to_U16; break;
icculus@10575
   506
            case AUDIO_S32: filter = SDL_Convert_F32_to_S32; break;
icculus@10575
   507
            default: SDL_assert(!"Unexpected audio format!"); break;
icculus@10575
   508
        }
slouken@2716
   509
icculus@10575
   510
        if (!filter) {
icculus@10575
   511
            return SDL_SetError("No conversion available for these formats");
icculus@10575
   512
        }
icculus@10575
   513
icculus@10575
   514
        cvt->filters[cvt->filter_index++] = filter;
icculus@10575
   515
        if (src_bitsize < dst_bitsize) {
icculus@10575
   516
            const int mult = (dst_bitsize / src_bitsize);
icculus@10575
   517
            cvt->len_mult *= mult;
icculus@10575
   518
            cvt->len_ratio *= mult;
icculus@10575
   519
        } else if (src_bitsize > dst_bitsize) {
icculus@10575
   520
            cvt->len_ratio /= (src_bitsize / dst_bitsize);
icculus@10575
   521
        }
icculus@10575
   522
        retval = 1;  /* added a converter. */
icculus@10575
   523
    }
icculus@10575
   524
icculus@10575
   525
    if ((SDL_AUDIO_ISBIGENDIAN(dst_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) {
icculus@10575
   526
        cvt->filters[cvt->filter_index++] = SDL_Convert_Byteswap;
icculus@10575
   527
        retval = 1;  /* added a converter. */
icculus@10575
   528
    }
icculus@10575
   529
icculus@10575
   530
    return retval;
icculus@3021
   531
}
slouken@2716
   532
icculus@10799
   533
static void
icculus@10799
   534
SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format)
icculus@10799
   535
{
icculus@10799
   536
    const float *src = (const float *) cvt->buf;
icculus@10799
   537
    const int srclen = cvt->len_cvt;
icculus@10833
   538
    float *dst = (float *) cvt->buf;
icculus@10833
   539
    const int dstlen = (cvt->len * cvt->len_mult);
icculus@10804
   540
    float state[8];
icculus@10756
   541
icculus@10799
   542
    SDL_assert(format == AUDIO_F32SYS);
icculus@10799
   543
slouken@10805
   544
    SDL_memcpy(state, src, chans*sizeof(*src));
icculus@10799
   545
icculus@10804
   546
    cvt->len_cvt = SDL_ResampleAudioSimple(chans, cvt->rate_incr, state, src, srclen, dst, dstlen);
icculus@10799
   547
    if (cvt->filters[++cvt->filter_index]) {
icculus@10799
   548
        cvt->filters[cvt->filter_index](cvt, format);
icculus@10799
   549
    }
icculus@10799
   550
}
icculus@10799
   551
icculus@10799
   552
/* !!! FIXME: We only have this macro salsa because SDL_AudioCVT doesn't
icculus@10799
   553
   !!! FIXME:  store channel info, so we have to have function entry
icculus@10799
   554
   !!! FIXME:  points for each supported channel count and multiple
icculus@10799
   555
   !!! FIXME:  vs arbitrary. When we rev the ABI, clean this up. */
icculus@10756
   556
#define RESAMPLER_FUNCS(chans) \
icculus@10756
   557
    static void SDLCALL \
icculus@10799
   558
    SDL_ResampleCVT_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) { \
icculus@10799
   559
        SDL_ResampleCVT(cvt, chans, format); \
icculus@10756
   560
    }
icculus@10756
   561
RESAMPLER_FUNCS(1)
icculus@10756
   562
RESAMPLER_FUNCS(2)
icculus@10756
   563
RESAMPLER_FUNCS(4)
icculus@10756
   564
RESAMPLER_FUNCS(6)
icculus@10756
   565
RESAMPLER_FUNCS(8)
icculus@10756
   566
#undef RESAMPLER_FUNCS
icculus@10756
   567
icculus@10799
   568
static SDL_AudioFilter
icculus@10799
   569
ChooseCVTResampler(const int dst_channels)
icculus@3021
   570
{
icculus@10799
   571
    switch (dst_channels) {
icculus@10799
   572
        case 1: return SDL_ResampleCVT_c1;
icculus@10799
   573
        case 2: return SDL_ResampleCVT_c2;
icculus@10799
   574
        case 4: return SDL_ResampleCVT_c4;
icculus@10799
   575
        case 6: return SDL_ResampleCVT_c6;
icculus@10799
   576
        case 8: return SDL_ResampleCVT_c8;
icculus@10799
   577
        default: break;
icculus@3021
   578
    }
slouken@2716
   579
icculus@10799
   580
    return NULL;
icculus@10756
   581
}
icculus@10575
   582
icculus@3021
   583
static int
icculus@10756
   584
SDL_BuildAudioResampleCVT(SDL_AudioCVT * cvt, const int dst_channels,
icculus@10756
   585
                          const int src_rate, const int dst_rate)
icculus@3021
   586
{
icculus@10756
   587
    SDL_AudioFilter filter;
icculus@3021
   588
icculus@10756
   589
    if (src_rate == dst_rate) {
icculus@10756
   590
        return 0;  /* no conversion necessary. */
slouken@2716
   591
    }
slouken@2716
   592
icculus@10799
   593
    filter = ChooseCVTResampler(dst_channels);
icculus@10756
   594
    if (filter == NULL) {
icculus@10756
   595
        return SDL_SetError("No conversion available for these rates");
icculus@10756
   596
    }
icculus@10756
   597
icculus@10756
   598
    /* Update (cvt) with filter details... */
icculus@10756
   599
    cvt->filters[cvt->filter_index++] = filter;
icculus@10756
   600
    if (src_rate < dst_rate) {
icculus@10756
   601
        const double mult = ((double) dst_rate) / ((double) src_rate);
icculus@10756
   602
        cvt->len_mult *= (int) SDL_ceil(mult);
icculus@10756
   603
        cvt->len_ratio *= mult;
icculus@10756
   604
    } else {
icculus@10756
   605
        cvt->len_ratio /= ((double) src_rate) / ((double) dst_rate);
icculus@10756
   606
    }
icculus@10756
   607
icculus@10756
   608
    return 1;               /* added a converter. */
slouken@2716
   609
}
icculus@1982
   610
icculus@1982
   611
icculus@1982
   612
/* Creates a set of audio filters to convert from one format to another.
icculus@1982
   613
   Returns -1 if the format conversion is not supported, 0 if there's
icculus@1982
   614
   no conversion needed, or 1 if the audio filter is set up.
slouken@0
   615
*/
slouken@1895
   616
slouken@1895
   617
int
slouken@1895
   618
SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
icculus@1982
   619
                  SDL_AudioFormat src_fmt, Uint8 src_channels, int src_rate,
icculus@1982
   620
                  SDL_AudioFormat dst_fmt, Uint8 dst_channels, int dst_rate)
slouken@0
   621
{
aschiffler@6819
   622
    /* Sanity check target pointer */
aschiffler@6819
   623
    if (cvt == NULL) {
icculus@7037
   624
        return SDL_InvalidParamError("cvt");
aschiffler@6819
   625
    }
slouken@7191
   626
slouken@10767
   627
    /* Make sure we zero out the audio conversion before error checking */
slouken@10767
   628
    SDL_zerop(cvt);
slouken@10767
   629
slouken@3491
   630
    /* there are no unsigned types over 16 bits, so catch this up front. */
icculus@1982
   631
    if ((SDL_AUDIO_BITSIZE(src_fmt) > 16) && (!SDL_AUDIO_ISSIGNED(src_fmt))) {
icculus@7037
   632
        return SDL_SetError("Invalid source format");
icculus@1982
   633
    }
icculus@1982
   634
    if ((SDL_AUDIO_BITSIZE(dst_fmt) > 16) && (!SDL_AUDIO_ISSIGNED(dst_fmt))) {
icculus@7037
   635
        return SDL_SetError("Invalid destination format");
icculus@1982
   636
    }
icculus@3021
   637
icculus@3021
   638
    /* prevent possible divisions by zero, etc. */
aschiffler@6819
   639
    if ((src_channels == 0) || (dst_channels == 0)) {
icculus@7037
   640
        return SDL_SetError("Source or destination channels is zero");
aschiffler@6819
   641
    }
icculus@3021
   642
    if ((src_rate == 0) || (dst_rate == 0)) {
icculus@7037
   643
        return SDL_SetError("Source or destination rate is zero");
icculus@3021
   644
    }
slouken@10579
   645
#if DEBUG_CONVERT
icculus@1982
   646
    printf("Build format %04x->%04x, channels %u->%u, rate %d->%d\n",
slouken@1985
   647
           src_fmt, dst_fmt, src_channels, dst_channels, src_rate, dst_rate);
slouken@1985
   648
#endif
icculus@1982
   649
slouken@1895
   650
    /* Start off with no conversion necessary */
icculus@1982
   651
    cvt->src_format = src_fmt;
icculus@1982
   652
    cvt->dst_format = dst_fmt;
slouken@1895
   653
    cvt->needed = 0;
slouken@1895
   654
    cvt->filter_index = 0;
slouken@1895
   655
    cvt->filters[0] = NULL;
slouken@1895
   656
    cvt->len_mult = 1;
slouken@1895
   657
    cvt->len_ratio = 1.0;
icculus@3021
   658
    cvt->rate_incr = ((double) dst_rate) / ((double) src_rate);
slouken@0
   659
icculus@10834
   660
    /* SDL now favors float32 as its preferred internal format, and considers
icculus@10834
   661
       everything else to be a degenerate case that we might have to make
icculus@10834
   662
       multiple passes over the data to convert to and from float32 as
icculus@10834
   663
       necessary. That being said, we keep one special case around for
icculus@10834
   664
       efficiency: stereo data in Sint16 format, in the native byte order,
icculus@10834
   665
       that only needs resampling. This is likely to be the most popular
icculus@10834
   666
       legacy format, that apps, hardware and the OS are likely to be able
icculus@10834
   667
       to process directly, so we handle this one case directly without
icculus@10834
   668
       unnecessary conversions. This means that apps on embedded devices
icculus@10834
   669
       without floating point hardware should consider aiming for this
icculus@10834
   670
       format as well. */
icculus@10834
   671
    if ((src_channels == 2) && (dst_channels == 2) && (src_fmt == AUDIO_S16SYS) && (dst_fmt == AUDIO_S16SYS) && (src_rate != dst_rate)) {
icculus@10834
   672
        cvt->needed = 1;
icculus@10834
   673
        cvt->filters[cvt->filter_index++] = SDL_ResampleCVT_si16_c2;
icculus@10834
   674
        if (src_rate < dst_rate) {
icculus@10834
   675
            const double mult = ((double) dst_rate) / ((double) src_rate);
icculus@10834
   676
            cvt->len_mult *= (int) SDL_ceil(mult);
icculus@10834
   677
            cvt->len_ratio *= mult;
icculus@10834
   678
        } else {
icculus@10834
   679
            cvt->len_ratio /= ((double) src_rate) / ((double) dst_rate);
icculus@10834
   680
        }
icculus@10834
   681
        return 1;
icculus@10834
   682
    }
icculus@10834
   683
icculus@10575
   684
    /* Type conversion goes like this now:
icculus@10575
   685
        - byteswap to CPU native format first if necessary.
icculus@10575
   686
        - convert to native Float32 if necessary.
icculus@10575
   687
        - resample and change channel count if necessary.
icculus@10575
   688
        - convert back to native format.
icculus@10575
   689
        - byteswap back to foreign format if necessary.
icculus@10575
   690
icculus@10575
   691
       The expectation is we can process data faster in float32
icculus@10575
   692
       (possibly with SIMD), and making several passes over the same
icculus@10756
   693
       buffer is likely to be CPU cache-friendly, avoiding the
icculus@10575
   694
       biggest performance hit in modern times. Previously we had
icculus@10575
   695
       (script-generated) custom converters for every data type and
icculus@10575
   696
       it was a bloat on SDL compile times and final library size. */
icculus@10575
   697
slouken@10767
   698
    /* see if we can skip float conversion entirely. */
slouken@10767
   699
    if (src_rate == dst_rate && src_channels == dst_channels) {
slouken@10767
   700
        if (src_fmt == dst_fmt) {
slouken@10767
   701
            return 0;
slouken@10767
   702
        }
slouken@10767
   703
slouken@10767
   704
        /* just a byteswap needed? */
slouken@10767
   705
        if ((src_fmt & ~SDL_AUDIO_MASK_ENDIAN) == (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN)) {
slouken@10767
   706
            cvt->filters[cvt->filter_index++] = SDL_Convert_Byteswap;
slouken@10767
   707
            cvt->needed = 1;
slouken@10767
   708
            return 1;
slouken@10767
   709
        }
icculus@10575
   710
    }
icculus@10575
   711
icculus@1982
   712
    /* Convert data types, if necessary. Updates (cvt). */
slouken@10767
   713
    if (SDL_BuildAudioTypeCVTToFloat(cvt, src_fmt) < 0) {
slouken@1985
   714
        return -1;              /* shouldn't happen, but just in case... */
icculus@3021
   715
    }
slouken@0
   716
icculus@1982
   717
    /* Channel conversion */
slouken@1895
   718
    if (src_channels != dst_channels) {
slouken@1895
   719
        if ((src_channels == 1) && (dst_channels > 1)) {
icculus@10793
   720
            cvt->filters[cvt->filter_index++] = SDL_ConvertMonoToStereo;
slouken@1895
   721
            cvt->len_mult *= 2;
slouken@1895
   722
            src_channels = 2;
slouken@1895
   723
            cvt->len_ratio *= 2;
slouken@1895
   724
        }
slouken@1895
   725
        if ((src_channels == 2) && (dst_channels == 6)) {
icculus@10793
   726
            cvt->filters[cvt->filter_index++] = SDL_ConvertStereoTo51;
slouken@1895
   727
            src_channels = 6;
slouken@1895
   728
            cvt->len_mult *= 3;
slouken@1895
   729
            cvt->len_ratio *= 3;
slouken@1895
   730
        }
slouken@1895
   731
        if ((src_channels == 2) && (dst_channels == 4)) {
icculus@10793
   732
            cvt->filters[cvt->filter_index++] = SDL_ConvertStereoToQuad;
slouken@1895
   733
            src_channels = 4;
slouken@1895
   734
            cvt->len_mult *= 2;
slouken@1895
   735
            cvt->len_ratio *= 2;
slouken@1895
   736
        }
slouken@1895
   737
        while ((src_channels * 2) <= dst_channels) {
icculus@10793
   738
            cvt->filters[cvt->filter_index++] = SDL_ConvertMonoToStereo;
slouken@1895
   739
            cvt->len_mult *= 2;
slouken@1895
   740
            src_channels *= 2;
slouken@1895
   741
            cvt->len_ratio *= 2;
slouken@1895
   742
        }
slouken@1895
   743
        if ((src_channels == 6) && (dst_channels <= 2)) {
icculus@10793
   744
            cvt->filters[cvt->filter_index++] = SDL_Convert51ToStereo;
slouken@1895
   745
            src_channels = 2;
slouken@1895
   746
            cvt->len_ratio /= 3;
slouken@1895
   747
        }
slouken@1895
   748
        if ((src_channels == 6) && (dst_channels == 4)) {
icculus@10793
   749
            cvt->filters[cvt->filter_index++] = SDL_Convert51ToQuad;
slouken@1895
   750
            src_channels = 4;
slouken@1895
   751
            cvt->len_ratio /= 2;
slouken@1895
   752
        }
slouken@1895
   753
        /* This assumes that 4 channel audio is in the format:
slouken@1895
   754
           Left {front/back} + Right {front/back}
slouken@1895
   755
           so converting to L/R stereo works properly.
slouken@1895
   756
         */
slouken@1895
   757
        while (((src_channels % 2) == 0) &&
slouken@1895
   758
               ((src_channels / 2) >= dst_channels)) {
icculus@10832
   759
            SDL_AudioFilter filter = NULL;
icculus@10832
   760
icculus@10832
   761
            #if HAVE_SSE3_INTRINSICS
icculus@10832
   762
            if (SDL_HasSSE3()) {
icculus@10832
   763
                filter = SDL_ConvertStereoToMono_SSE3;
icculus@10832
   764
            }
icculus@10832
   765
            #endif
icculus@10832
   766
icculus@10832
   767
            if (!filter) {
icculus@10832
   768
                filter = SDL_ConvertStereoToMono;
icculus@10832
   769
            }
icculus@10832
   770
icculus@10832
   771
            cvt->filters[cvt->filter_index++] = filter;
icculus@10832
   772
slouken@1895
   773
            src_channels /= 2;
slouken@1895
   774
            cvt->len_ratio /= 2;
slouken@1895
   775
        }
slouken@1895
   776
        if (src_channels != dst_channels) {
slouken@1895
   777
            /* Uh oh.. */ ;
slouken@1895
   778
        }
slouken@1895
   779
    }
slouken@0
   780
icculus@3021
   781
    /* Do rate conversion, if necessary. Updates (cvt). */
slouken@10767
   782
    if (SDL_BuildAudioResampleCVT(cvt, dst_channels, src_rate, dst_rate) < 0) {
icculus@3021
   783
        return -1;              /* shouldn't happen, but just in case... */
slouken@2716
   784
    }
slouken@2716
   785
icculus@10756
   786
    /* Move to final data type. */
slouken@10767
   787
    if (SDL_BuildAudioTypeCVTFromFloat(cvt, dst_fmt) < 0) {
icculus@10575
   788
        return -1;              /* shouldn't happen, but just in case... */
slouken@1895
   789
    }
icculus@10575
   790
icculus@10575
   791
    cvt->needed = (cvt->filter_index != 0);
slouken@1895
   792
    return (cvt->needed);
slouken@0
   793
}
slouken@1895
   794
slouken@10773
   795
typedef int (*SDL_ResampleAudioStreamFunc)(SDL_AudioStream *stream, const float *inbuf, const int inbuflen, float *outbuf, const int outbuflen);
slouken@10773
   796
typedef void (*SDL_ResetAudioStreamResamplerFunc)(SDL_AudioStream *stream);
slouken@10773
   797
typedef void (*SDL_CleanupAudioStreamResamplerFunc)(SDL_AudioStream *stream);
icculus@10757
   798
icculus@10757
   799
struct SDL_AudioStream
icculus@10757
   800
{
icculus@10757
   801
    SDL_AudioCVT cvt_before_resampling;
icculus@10757
   802
    SDL_AudioCVT cvt_after_resampling;
icculus@10757
   803
    SDL_DataQueue *queue;
icculus@10757
   804
    Uint8 *work_buffer;
icculus@10757
   805
    int work_buffer_len;
icculus@10757
   806
    Uint8 *resample_buffer;
icculus@10757
   807
    int resample_buffer_len;
icculus@10757
   808
    int src_sample_frame_size;
icculus@10757
   809
    SDL_AudioFormat src_format;
icculus@10757
   810
    Uint8 src_channels;
icculus@10757
   811
    int src_rate;
icculus@10757
   812
    int dst_sample_frame_size;
icculus@10757
   813
    SDL_AudioFormat dst_format;
icculus@10757
   814
    Uint8 dst_channels;
icculus@10757
   815
    int dst_rate;
icculus@10757
   816
    double rate_incr;
icculus@10757
   817
    Uint8 pre_resample_channels;
slouken@10773
   818
    int packetlen;
slouken@10773
   819
    void *resampler_state;
slouken@10773
   820
    SDL_ResampleAudioStreamFunc resampler_func;
slouken@10773
   821
    SDL_ResetAudioStreamResamplerFunc reset_resampler_func;
slouken@10773
   822
    SDL_CleanupAudioStreamResamplerFunc cleanup_resampler_func;
slouken@10773
   823
};
slouken@10773
   824
slouken@10777
   825
#ifdef HAVE_LIBSAMPLERATE_H
slouken@10773
   826
static int
slouken@10773
   827
SDL_ResampleAudioStream_SRC(SDL_AudioStream *stream, const float *inbuf, const int inbuflen, float *outbuf, const int outbuflen)
slouken@10773
   828
{
icculus@10799
   829
    const int framelen = sizeof(float) * stream->pre_resample_channels;
icculus@10790
   830
    SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
slouken@10773
   831
    SRC_DATA data;
slouken@10773
   832
    int result;
slouken@10773
   833
slouken@10777
   834
    data.data_in = (float *)inbuf; /* Older versions of libsamplerate had a non-const pointer, but didn't write to it */
icculus@10799
   835
    data.input_frames = inbuflen / framelen;
slouken@10773
   836
    data.input_frames_used = 0;
slouken@10773
   837
slouken@10773
   838
    data.data_out = outbuf;
icculus@10799
   839
    data.output_frames = outbuflen / framelen;
slouken@10773
   840
slouken@10773
   841
    data.end_of_input = 0;
slouken@10773
   842
    data.src_ratio = stream->rate_incr;
slouken@10773
   843
icculus@10790
   844
    result = SRC_src_process(state, &data);
slouken@10773
   845
    if (result != 0) {
icculus@10790
   846
        SDL_SetError("src_process() failed: %s", SRC_src_strerror(result));
slouken@10773
   847
        return 0;
slouken@10773
   848
    }
slouken@10773
   849
slouken@10773
   850
    /* If this fails, we need to store them off somewhere */
slouken@10773
   851
    SDL_assert(data.input_frames_used == data.input_frames);
slouken@10773
   852
slouken@10773
   853
    return data.output_frames_gen * (sizeof(float) * stream->pre_resample_channels);
slouken@10773
   854
}
slouken@10773
   855
slouken@10773
   856
static void
slouken@10773
   857
SDL_ResetAudioStreamResampler_SRC(SDL_AudioStream *stream)
slouken@10773
   858
{
icculus@10790
   859
    SRC_src_reset((SRC_STATE *)stream->resampler_state);
slouken@10773
   860
}
slouken@10773
   861
slouken@10773
   862
static void
slouken@10773
   863
SDL_CleanupAudioStreamResampler_SRC(SDL_AudioStream *stream)
slouken@10773
   864
{
icculus@10790
   865
    SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
slouken@10773
   866
    if (state) {
icculus@10790
   867
        SRC_src_delete(state);
slouken@10773
   868
    }
slouken@10773
   869
slouken@10773
   870
    stream->resampler_state = NULL;
slouken@10773
   871
    stream->resampler_func = NULL;
slouken@10773
   872
    stream->reset_resampler_func = NULL;
slouken@10773
   873
    stream->cleanup_resampler_func = NULL;
slouken@10773
   874
}
slouken@10773
   875
slouken@10773
   876
static SDL_bool
slouken@10773
   877
SetupLibSampleRateResampling(SDL_AudioStream *stream)
slouken@10773
   878
{
icculus@10790
   879
    int result = 0;
icculus@10790
   880
    SRC_STATE *state = NULL;
slouken@10773
   881
icculus@10790
   882
    if (SRC_available) {
icculus@10790
   883
        state = SRC_src_new(SRC_SINC_FASTEST, stream->pre_resample_channels, &result);
icculus@10790
   884
        if (!state) {
icculus@10790
   885
            SDL_SetError("src_new() failed: %s", SRC_src_strerror(result));
icculus@10790
   886
        }
slouken@10773
   887
    }
slouken@10773
   888
icculus@10790
   889
    if (!state) {
icculus@10790
   890
        SDL_CleanupAudioStreamResampler_SRC(stream);
slouken@10773
   891
        return SDL_FALSE;
slouken@10773
   892
    }
slouken@10773
   893
slouken@10773
   894
    stream->resampler_state = state;
slouken@10773
   895
    stream->resampler_func = SDL_ResampleAudioStream_SRC;
slouken@10773
   896
    stream->reset_resampler_func = SDL_ResetAudioStreamResampler_SRC;
slouken@10773
   897
    stream->cleanup_resampler_func = SDL_CleanupAudioStreamResampler_SRC;
slouken@10773
   898
slouken@10773
   899
    return SDL_TRUE;
slouken@10773
   900
}
icculus@10790
   901
#endif /* HAVE_LIBSAMPLERATE_H */
slouken@10773
   902
slouken@10773
   903
slouken@10773
   904
typedef struct
slouken@10773
   905
{
icculus@10757
   906
    SDL_bool resampler_seeded;
icculus@10757
   907
    float resampler_state[8];
slouken@10773
   908
} SDL_AudioStreamResamplerState;
slouken@10773
   909
slouken@10773
   910
static int
slouken@10773
   911
SDL_ResampleAudioStream(SDL_AudioStream *stream, const float *inbuf, const int inbuflen, float *outbuf, const int outbuflen)
slouken@10773
   912
{
slouken@10773
   913
    SDL_AudioStreamResamplerState *state = (SDL_AudioStreamResamplerState*)stream->resampler_state;
slouken@10773
   914
    const int chans = (int)stream->pre_resample_channels;
slouken@10773
   915
icculus@10799
   916
    SDL_assert(chans <= SDL_arraysize(state->resampler_state));
slouken@10773
   917
slouken@10773
   918
    if (!state->resampler_seeded) {
icculus@10799
   919
        int i;
slouken@10773
   920
        for (i = 0; i < chans; i++) {
slouken@10773
   921
            state->resampler_state[i] = inbuf[i];
slouken@10773
   922
        }
slouken@10773
   923
        state->resampler_seeded = SDL_TRUE;
slouken@10773
   924
    }
slouken@10773
   925
icculus@10799
   926
    return SDL_ResampleAudioSimple(chans, stream->rate_incr, state->resampler_state, inbuf, inbuflen, outbuf, outbuflen);
slouken@10773
   927
}
slouken@10773
   928
slouken@10773
   929
static void
slouken@10773
   930
SDL_ResetAudioStreamResampler(SDL_AudioStream *stream)
slouken@10773
   931
{
slouken@10773
   932
    SDL_AudioStreamResamplerState *state = (SDL_AudioStreamResamplerState*)stream->resampler_state;
slouken@10773
   933
    state->resampler_seeded = SDL_FALSE;
slouken@10773
   934
}
slouken@10773
   935
slouken@10773
   936
static void
slouken@10773
   937
SDL_CleanupAudioStreamResampler(SDL_AudioStream *stream)
slouken@10773
   938
{
slouken@10773
   939
    SDL_free(stream->resampler_state);
slouken@10773
   940
}
icculus@10757
   941
icculus@10789
   942
SDL_AudioStream *
icculus@10789
   943
SDL_NewAudioStream(const SDL_AudioFormat src_format,
icculus@10789
   944
                   const Uint8 src_channels,
icculus@10789
   945
                   const int src_rate,
icculus@10789
   946
                   const SDL_AudioFormat dst_format,
icculus@10789
   947
                   const Uint8 dst_channels,
icculus@10789
   948
                   const int dst_rate)
icculus@10757
   949
{
icculus@10757
   950
    const int packetlen = 4096;  /* !!! FIXME: good enough for now. */
icculus@10757
   951
    Uint8 pre_resample_channels;
icculus@10757
   952
    SDL_AudioStream *retval;
icculus@10757
   953
icculus@10757
   954
    retval = (SDL_AudioStream *) SDL_calloc(1, sizeof (SDL_AudioStream));
icculus@10757
   955
    if (!retval) {
icculus@10757
   956
        return NULL;
icculus@10757
   957
    }
icculus@10757
   958
icculus@10757
   959
    /* If increasing channels, do it after resampling, since we'd just
icculus@10757
   960
       do more work to resample duplicate channels. If we're decreasing, do
icculus@10757
   961
       it first so we resample the interpolated data instead of interpolating
icculus@10757
   962
       the resampled data (!!! FIXME: decide if that works in practice, though!). */
icculus@10757
   963
    pre_resample_channels = SDL_min(src_channels, dst_channels);
icculus@10757
   964
icculus@10757
   965
    retval->src_sample_frame_size = SDL_AUDIO_BITSIZE(src_format) * src_channels;
icculus@10757
   966
    retval->src_format = src_format;
icculus@10757
   967
    retval->src_channels = src_channels;
icculus@10757
   968
    retval->src_rate = src_rate;
icculus@10757
   969
    retval->dst_sample_frame_size = SDL_AUDIO_BITSIZE(dst_format) * dst_channels;
icculus@10757
   970
    retval->dst_format = dst_format;
icculus@10757
   971
    retval->dst_channels = dst_channels;
icculus@10757
   972
    retval->dst_rate = dst_rate;
icculus@10757
   973
    retval->pre_resample_channels = pre_resample_channels;
icculus@10757
   974
    retval->packetlen = packetlen;
icculus@10757
   975
    retval->rate_incr = ((double) dst_rate) / ((double) src_rate);
icculus@10757
   976
icculus@10757
   977
    /* Not resampling? It's an easy conversion (and maybe not even that!). */
icculus@10757
   978
    if (src_rate == dst_rate) {
icculus@10757
   979
        retval->cvt_before_resampling.needed = SDL_FALSE;
icculus@10757
   980
        retval->cvt_before_resampling.len_mult = 1;
slouken@10773
   981
        if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, src_format, src_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) {
slouken@10773
   982
            SDL_FreeAudioStream(retval);
icculus@10757
   983
            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
icculus@10757
   984
        }
icculus@10757
   985
    } else {
icculus@10757
   986
        /* Don't resample at first. Just get us to Float32 format. */
icculus@10757
   987
        /* !!! FIXME: convert to int32 on devices without hardware float. */
slouken@10773
   988
        if (SDL_BuildAudioCVT(&retval->cvt_before_resampling, src_format, src_channels, src_rate, AUDIO_F32SYS, pre_resample_channels, src_rate) < 0) {
slouken@10773
   989
            SDL_FreeAudioStream(retval);
icculus@10757
   990
            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
icculus@10757
   991
        }
icculus@10757
   992
slouken@10777
   993
#ifdef HAVE_LIBSAMPLERATE_H
slouken@10773
   994
        SetupLibSampleRateResampling(retval);
slouken@10773
   995
#endif
slouken@10773
   996
slouken@10773
   997
        if (!retval->resampler_func) {
slouken@10773
   998
            retval->resampler_state = SDL_calloc(1, sizeof(SDL_AudioStreamResamplerState));
slouken@10773
   999
            if (!retval->resampler_state) {
slouken@10773
  1000
                SDL_FreeAudioStream(retval);
slouken@10773
  1001
                SDL_OutOfMemory();
slouken@10773
  1002
                return NULL;
slouken@10773
  1003
            }
slouken@10773
  1004
            retval->resampler_func = SDL_ResampleAudioStream;
slouken@10773
  1005
            retval->reset_resampler_func = SDL_ResetAudioStreamResampler;
slouken@10773
  1006
            retval->cleanup_resampler_func = SDL_CleanupAudioStreamResampler;
slouken@10773
  1007
        }
slouken@10773
  1008
icculus@10757
  1009
        /* Convert us to the final format after resampling. */
slouken@10773
  1010
        if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, AUDIO_F32SYS, pre_resample_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) {
slouken@10773
  1011
            SDL_FreeAudioStream(retval);
icculus@10757
  1012
            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
icculus@10757
  1013
        }
icculus@10757
  1014
    }
icculus@10757
  1015
icculus@10757
  1016
    retval->queue = SDL_NewDataQueue(packetlen, packetlen * 2);
icculus@10757
  1017
    if (!retval->queue) {
slouken@10773
  1018
        SDL_FreeAudioStream(retval);
icculus@10757
  1019
        return NULL;  /* SDL_NewDataQueue should have called SDL_SetError. */
icculus@10757
  1020
    }
icculus@10757
  1021
icculus@10757
  1022
    return retval;
icculus@10757
  1023
}
icculus@10757
  1024
icculus@10757
  1025
static Uint8 *
icculus@10757
  1026
EnsureBufferSize(Uint8 **buf, int *len, const int newlen)
icculus@10757
  1027
{
icculus@10757
  1028
    if (*len < newlen) {
icculus@10757
  1029
        void *ptr = SDL_realloc(*buf, newlen);
icculus@10757
  1030
        if (!ptr) {
icculus@10757
  1031
            SDL_OutOfMemory();
icculus@10757
  1032
            return NULL;
icculus@10757
  1033
        }
icculus@10757
  1034
        *buf = (Uint8 *) ptr;
icculus@10757
  1035
        *len = newlen;
icculus@10757
  1036
    }
icculus@10757
  1037
    return *buf;
icculus@10757
  1038
}
icculus@10757
  1039
icculus@10757
  1040
int
icculus@10757
  1041
SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, const Uint32 _buflen)
icculus@10757
  1042
{
icculus@10757
  1043
    int buflen = (int) _buflen;
icculus@10757
  1044
icculus@10757
  1045
    if (!stream) {
icculus@10757
  1046
        return SDL_InvalidParamError("stream");
icculus@10757
  1047
    } else if (!buf) {
icculus@10757
  1048
        return SDL_InvalidParamError("buf");
icculus@10757
  1049
    } else if (buflen == 0) {
icculus@10757
  1050
        return 0;  /* nothing to do. */
icculus@10757
  1051
    } else if ((buflen % stream->src_sample_frame_size) != 0) {
icculus@10757
  1052
        return SDL_SetError("Can't add partial sample frames");
icculus@10757
  1053
    }
icculus@10757
  1054
icculus@10757
  1055
    if (stream->cvt_before_resampling.needed) {
icculus@10757
  1056
        const int workbuflen = buflen * stream->cvt_before_resampling.len_mult;  /* will be "* 1" if not needed */
icculus@10757
  1057
        Uint8 *workbuf = EnsureBufferSize(&stream->work_buffer, &stream->work_buffer_len, workbuflen);
icculus@10757
  1058
        if (workbuf == NULL) {
icculus@10757
  1059
            return -1;  /* probably out of memory. */
icculus@10757
  1060
        }
icculus@10757
  1061
        SDL_memcpy(workbuf, buf, buflen);
icculus@10757
  1062
        stream->cvt_before_resampling.buf = workbuf;
icculus@10757
  1063
        stream->cvt_before_resampling.len = buflen;
icculus@10757
  1064
        if (SDL_ConvertAudio(&stream->cvt_before_resampling) == -1) {
icculus@10757
  1065
            return -1;   /* uhoh! */
icculus@10757
  1066
        }
icculus@10757
  1067
        buf = workbuf;
icculus@10757
  1068
        buflen = stream->cvt_before_resampling.len_cvt;
icculus@10757
  1069
    }
icculus@10757
  1070
icculus@10757
  1071
    if (stream->dst_rate != stream->src_rate) {
icculus@10757
  1072
        const int workbuflen = buflen * ((int) SDL_ceil(stream->rate_incr));
icculus@10757
  1073
        float *workbuf = (float *) EnsureBufferSize(&stream->resample_buffer, &stream->resample_buffer_len, workbuflen);
icculus@10757
  1074
        if (workbuf == NULL) {
icculus@10757
  1075
            return -1;  /* probably out of memory. */
icculus@10757
  1076
        }
slouken@10773
  1077
        buflen = stream->resampler_func(stream, (float *) buf, buflen, workbuf, workbuflen);
icculus@10757
  1078
        buf = workbuf;
icculus@10757
  1079
    }
icculus@10757
  1080
icculus@10757
  1081
    if (stream->cvt_after_resampling.needed) {
icculus@10757
  1082
        const int workbuflen = buflen * stream->cvt_before_resampling.len_mult;  /* will be "* 1" if not needed */
icculus@10757
  1083
        Uint8 *workbuf;
icculus@10757
  1084
icculus@10757
  1085
        if (buf == stream->resample_buffer) {
icculus@10757
  1086
            workbuf = EnsureBufferSize(&stream->resample_buffer, &stream->resample_buffer_len, workbuflen);
icculus@10757
  1087
        } else {
icculus@10757
  1088
            const int inplace = (buf == stream->work_buffer);
icculus@10757
  1089
            workbuf = EnsureBufferSize(&stream->work_buffer, &stream->work_buffer_len, workbuflen);
icculus@10757
  1090
            if (workbuf && !inplace) {
icculus@10757
  1091
                SDL_memcpy(workbuf, buf, buflen);
icculus@10757
  1092
            }
icculus@10757
  1093
        }
icculus@10757
  1094
icculus@10757
  1095
        if (workbuf == NULL) {
icculus@10757
  1096
            return -1;  /* probably out of memory. */
icculus@10757
  1097
        }
icculus@10757
  1098
icculus@10757
  1099
        stream->cvt_after_resampling.buf = workbuf;
icculus@10757
  1100
        stream->cvt_after_resampling.len = buflen;
icculus@10757
  1101
        if (SDL_ConvertAudio(&stream->cvt_after_resampling) == -1) {
icculus@10757
  1102
            return -1;   /* uhoh! */
icculus@10757
  1103
        }
icculus@10757
  1104
        buf = workbuf;
icculus@10757
  1105
        buflen = stream->cvt_after_resampling.len_cvt;
icculus@10757
  1106
    }
icculus@10757
  1107
icculus@10757
  1108
    return SDL_WriteToDataQueue(stream->queue, buf, buflen);
icculus@10757
  1109
}
icculus@10757
  1110
icculus@10757
  1111
void
icculus@10757
  1112
SDL_AudioStreamClear(SDL_AudioStream *stream)
icculus@10757
  1113
{
icculus@10757
  1114
    if (!stream) {
icculus@10757
  1115
        SDL_InvalidParamError("stream");
icculus@10757
  1116
    } else {
icculus@10757
  1117
        SDL_ClearDataQueue(stream->queue, stream->packetlen * 2);
icculus@10776
  1118
        if (stream->reset_resampler_func) {
icculus@10776
  1119
            stream->reset_resampler_func(stream);
icculus@10776
  1120
        }
icculus@10757
  1121
    }
icculus@10757
  1122
}
icculus@10757
  1123
icculus@10757
  1124
icculus@10757
  1125
/* get converted/resampled data from the stream */
icculus@10757
  1126
int
icculus@10764
  1127
SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, const Uint32 len)
icculus@10757
  1128
{
icculus@10757
  1129
    if (!stream) {
icculus@10757
  1130
        return SDL_InvalidParamError("stream");
icculus@10757
  1131
    } else if (!buf) {
icculus@10757
  1132
        return SDL_InvalidParamError("buf");
icculus@10757
  1133
    } else if (len == 0) {
icculus@10757
  1134
        return 0;  /* nothing to do. */
icculus@10757
  1135
    } else if ((len % stream->dst_sample_frame_size) != 0) {
icculus@10757
  1136
        return SDL_SetError("Can't request partial sample frames");
icculus@10757
  1137
    }
icculus@10757
  1138
icculus@10764
  1139
    return (int) SDL_ReadFromDataQueue(stream->queue, buf, len);
icculus@10757
  1140
}
icculus@10757
  1141
icculus@10757
  1142
/* number of converted/resampled bytes available */
icculus@10757
  1143
int
icculus@10757
  1144
SDL_AudioStreamAvailable(SDL_AudioStream *stream)
icculus@10757
  1145
{
icculus@10757
  1146
    return stream ? (int) SDL_CountDataQueue(stream->queue) : 0;
icculus@10757
  1147
}
icculus@10757
  1148
icculus@10757
  1149
/* dispose of a stream */
icculus@10757
  1150
void
icculus@10757
  1151
SDL_FreeAudioStream(SDL_AudioStream *stream)
icculus@10757
  1152
{
icculus@10757
  1153
    if (stream) {
slouken@10773
  1154
        if (stream->cleanup_resampler_func) {
slouken@10773
  1155
            stream->cleanup_resampler_func(stream);
slouken@10773
  1156
        }
icculus@10757
  1157
        SDL_FreeDataQueue(stream->queue);
icculus@10757
  1158
        SDL_free(stream->work_buffer);
icculus@10757
  1159
        SDL_free(stream->resample_buffer);
icculus@10757
  1160
        SDL_free(stream);
icculus@10757
  1161
    }
icculus@10757
  1162
}
icculus@10757
  1163
icculus@10575
  1164
/* vi: set ts=4 sw=4 expandtab: */
slouken@2716
  1165