src/audio/SDL_audiocvt.c
author Ryan C. Gordon <icculus@icculus.org>
Thu, 21 Sep 2017 02:51:14 -0400
changeset 11508 a8382e3d0b54
parent 11406 f40c2dedaded
child 11517 beb96c015b30
permissions -rw-r--r--
audio: Replaced the resampler. Again.

This time it's using real math from a real whitepaper instead of my previous
amateur, fast-but-low-quality attempt. The new resampler does "bandlimited
interpolation," as described here: https://ccrma.stanford.edu/~jos/resample/

The output appears to sound cleaner, especially at high frequencies, and of
course works with non-power-of-two rate conversions.

There are some obvious optimizations to be done to this still, and there is
other fallout: this doesn't resample a buffer in-place, the 2-channels-Sint16
fast path is gone because this resampler does a _lot_ of floating point math.
There is a nasty hack to make it work with SDL_AudioCVT.

It's possible these issues are solvable, but they aren't solved as of yet.
Still, I hope this effort is slouching in the right direction.
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
icculus@11319
    25
#include "SDL.h"
slouken@0
    26
#include "SDL_audio.h"
icculus@1982
    27
#include "SDL_audio_c.h"
slouken@0
    28
slouken@10773
    29
#include "SDL_loadso.h"
icculus@6281
    30
#include "SDL_assert.h"
icculus@10757
    31
#include "../SDL_dataqueue.h"
icculus@10835
    32
#include "SDL_cpuinfo.h"
icculus@6281
    33
icculus@10835
    34
#ifdef __SSE3__
icculus@10835
    35
#define HAVE_SSE3_INTRINSICS 1
icculus@10832
    36
#endif
icculus@10832
    37
icculus@10832
    38
#if HAVE_SSE3_INTRINSICS
icculus@11405
    39
/* Convert from stereo to mono. Average left and right. */
icculus@10832
    40
static void SDLCALL
icculus@10832
    41
SDL_ConvertStereoToMono_SSE3(SDL_AudioCVT * cvt, SDL_AudioFormat format)
icculus@10832
    42
{
icculus@10832
    43
    float *dst = (float *) cvt->buf;
icculus@10832
    44
    const float *src = dst;
icculus@10832
    45
    int i = cvt->len_cvt / 8;
icculus@10832
    46
icculus@10832
    47
    LOG_DEBUG_CONVERT("stereo", "mono (using SSE3)");
icculus@10832
    48
    SDL_assert(format == AUDIO_F32SYS);
icculus@10832
    49
icculus@10832
    50
    /* We can only do this if dst is aligned to 16 bytes; since src is the
icculus@10832
    51
       same pointer and it moves by 2, it can't be forcibly aligned. */
icculus@10832
    52
    if ((((size_t) dst) & 15) == 0) {
icculus@10832
    53
        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
icculus@10832
    54
        const __m128 divby2 = _mm_set1_ps(0.5f);
icculus@10832
    55
        while (i >= 4) {   /* 4 * float32 */
icculus@10832
    56
            _mm_store_ps(dst, _mm_mul_ps(_mm_hadd_ps(_mm_load_ps(src), _mm_load_ps(src+4)), divby2));
icculus@10832
    57
            i -= 4; src += 8; dst += 4;
icculus@10832
    58
        }
icculus@10832
    59
    }
icculus@10832
    60
icculus@10832
    61
    /* Finish off any leftovers with scalar operations. */
icculus@10832
    62
    while (i) {
icculus@10832
    63
        *dst = (src[0] + src[1]) * 0.5f;
icculus@10832
    64
        dst++; i--; src += 2;
icculus@10832
    65
    }
icculus@10832
    66
icculus@10832
    67
    cvt->len_cvt /= 2;
icculus@10832
    68
    if (cvt->filters[++cvt->filter_index]) {
icculus@10832
    69
        cvt->filters[cvt->filter_index] (cvt, format);
icculus@10832
    70
    }
icculus@10832
    71
}
icculus@10832
    72
#endif
icculus@10832
    73
icculus@11405
    74
/* Convert from stereo to mono. Average left and right. */
icculus@1982
    75
static void SDLCALL
icculus@10793
    76
SDL_ConvertStereoToMono(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@0
    77
{
icculus@10575
    78
    float *dst = (float *) cvt->buf;
icculus@10575
    79
    const float *src = dst;
slouken@1895
    80
    int i;
slouken@0
    81
icculus@10575
    82
    LOG_DEBUG_CONVERT("stereo", "mono");
icculus@10575
    83
    SDL_assert(format == AUDIO_F32SYS);
slouken@0
    84
icculus@10575
    85
    for (i = cvt->len_cvt / 8; i; --i, src += 2) {
icculus@10831
    86
        *(dst++) = (src[0] + src[1]) * 0.5f;
slouken@1895
    87
    }
icculus@1982
    88
slouken@1895
    89
    cvt->len_cvt /= 2;
slouken@1895
    90
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
    91
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
    92
    }
slouken@0
    93
}
slouken@0
    94
icculus@1982
    95
icculus@11405
    96
/* Convert from 5.1 to stereo. Average left and right, distribute center, discard LFE. */
icculus@1982
    97
static void SDLCALL
icculus@10793
    98
SDL_Convert51ToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@942
    99
{
icculus@10575
   100
    float *dst = (float *) cvt->buf;
icculus@10575
   101
    const float *src = dst;
slouken@1895
   102
    int i;
slouken@942
   103
icculus@10793
   104
    LOG_DEBUG_CONVERT("5.1", "stereo");
icculus@10575
   105
    SDL_assert(format == AUDIO_F32SYS);
slouken@942
   106
icculus@11405
   107
    /* SDL's 5.1 layout: FL+FR+FC+LFE+BL+BR */
icculus@10575
   108
    for (i = cvt->len_cvt / (sizeof (float) * 6); i; --i, src += 6, dst += 2) {
icculus@11405
   109
        const float front_center_distributed = src[2] * 0.5f;
icculus@11405
   110
        dst[0] = (src[0] + front_center_distributed + src[4]) / 2.5f;  /* left */
icculus@11405
   111
        dst[1] = (src[1] + front_center_distributed + src[5]) / 2.5f;  /* right */
icculus@1982
   112
    }
slouken@942
   113
slouken@1895
   114
    cvt->len_cvt /= 3;
slouken@1895
   115
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
   116
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
   117
    }
slouken@942
   118
}
slouken@942
   119
slouken@942
   120
icculus@11405
   121
/* Convert from quad to stereo. Average left and right. */
icculus@11405
   122
static void SDLCALL
icculus@11405
   123
SDL_ConvertQuadToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
icculus@11405
   124
{
icculus@11405
   125
    float *dst = (float *) cvt->buf;
icculus@11405
   126
    const float *src = dst;
icculus@11405
   127
    int i;
icculus@11405
   128
icculus@11405
   129
    LOG_DEBUG_CONVERT("quad", "stereo");
icculus@11405
   130
    SDL_assert(format == AUDIO_F32SYS);
icculus@11405
   131
icculus@11405
   132
    for (i = cvt->len_cvt / (sizeof (float) * 4); i; --i, src += 4, dst += 2) {
icculus@11405
   133
        dst[0] = (src[0] + src[2]) * 0.5f; /* left */
icculus@11405
   134
        dst[1] = (src[1] + src[3]) * 0.5f; /* right */
icculus@11405
   135
    }
icculus@11405
   136
icculus@11405
   137
    cvt->len_cvt /= 3;
icculus@11405
   138
    if (cvt->filters[++cvt->filter_index]) {
icculus@11405
   139
        cvt->filters[cvt->filter_index] (cvt, format);
icculus@11405
   140
    }
icculus@11405
   141
}
icculus@11405
   142
icculus@11405
   143
icculus@11405
   144
/* Convert from 7.1 to 5.1. Distribute sides across front and back. */
icculus@11405
   145
static void SDLCALL
icculus@11405
   146
SDL_Convert71To51(SDL_AudioCVT * cvt, SDL_AudioFormat format)
icculus@11405
   147
{
icculus@11405
   148
    float *dst = (float *) cvt->buf;
icculus@11405
   149
    const float *src = dst;
icculus@11405
   150
    int i;
icculus@11405
   151
icculus@11405
   152
    LOG_DEBUG_CONVERT("7.1", "5.1");
icculus@11405
   153
    SDL_assert(format == AUDIO_F32SYS);
icculus@11405
   154
icculus@11405
   155
    for (i = cvt->len_cvt / (sizeof (float) * 8); i; --i, src += 8, dst += 6) {
icculus@11405
   156
        const float surround_left_distributed = src[6] * 0.5f;
icculus@11405
   157
        const float surround_right_distributed = src[7] * 0.5f;
icculus@11405
   158
        dst[0] = (src[0] + surround_left_distributed) / 1.5f;  /* FL */
icculus@11405
   159
        dst[1] = (src[1] + surround_right_distributed) / 1.5f;  /* FR */
icculus@11405
   160
        dst[2] = src[2] / 1.5f; /* CC */
icculus@11405
   161
        dst[3] = src[3] / 1.5f; /* LFE */
icculus@11405
   162
        dst[4] = (src[4] + surround_left_distributed) / 1.5f;  /* BL */
icculus@11405
   163
        dst[5] = (src[5] + surround_right_distributed) / 1.5f;  /* BR */
icculus@11405
   164
    }
icculus@11405
   165
icculus@11405
   166
    cvt->len_cvt /= 8;
icculus@11405
   167
    cvt->len_cvt *= 6;
icculus@11405
   168
    if (cvt->filters[++cvt->filter_index]) {
icculus@11405
   169
        cvt->filters[cvt->filter_index] (cvt, format);
icculus@11405
   170
    }
icculus@11405
   171
}
icculus@11405
   172
icculus@11405
   173
icculus@11405
   174
/* Convert from 5.1 to quad. Distribute center across front, discard LFE. */
icculus@1982
   175
static void SDLCALL
icculus@10793
   176
SDL_Convert51ToQuad(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@942
   177
{
icculus@10575
   178
    float *dst = (float *) cvt->buf;
icculus@10575
   179
    const float *src = dst;
slouken@1895
   180
    int i;
slouken@942
   181
icculus@10793
   182
    LOG_DEBUG_CONVERT("5.1", "quad");
icculus@10575
   183
    SDL_assert(format == AUDIO_F32SYS);
slouken@942
   184
icculus@11405
   185
    /* SDL's 4.0 layout: FL+FR+BL+BR */
icculus@11405
   186
    /* SDL's 5.1 layout: FL+FR+FC+LFE+BL+BR */
icculus@10575
   187
    for (i = cvt->len_cvt / (sizeof (float) * 6); i; --i, src += 6, dst += 4) {
icculus@11405
   188
        const float front_center_distributed = src[2] * 0.5f;
icculus@11405
   189
        dst[0] = (src[0] + front_center_distributed) / 1.5f;  /* FL */
icculus@11405
   190
        dst[1] = (src[1] + front_center_distributed) / 1.5f;  /* FR */
icculus@11405
   191
        dst[2] = src[4] / 1.5f;  /* BL */
icculus@11405
   192
        dst[3] = src[5] / 1.5f;  /* BR */
icculus@1982
   193
    }
slouken@942
   194
icculus@1982
   195
    cvt->len_cvt /= 6;
icculus@1982
   196
    cvt->len_cvt *= 4;
slouken@1895
   197
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
   198
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
   199
    }
slouken@942
   200
}
slouken@0
   201
icculus@10793
   202
icculus@11405
   203
/* Upmix mono to stereo (by duplication) */
icculus@1982
   204
static void SDLCALL
icculus@10793
   205
SDL_ConvertMonoToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@0
   206
{
icculus@10575
   207
    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
icculus@10575
   208
    float *dst = (float *) (cvt->buf + cvt->len_cvt * 2);
slouken@1895
   209
    int i;
slouken@0
   210
icculus@10575
   211
    LOG_DEBUG_CONVERT("mono", "stereo");
icculus@10575
   212
    SDL_assert(format == AUDIO_F32SYS);
slouken@0
   213
icculus@10575
   214
    for (i = cvt->len_cvt / sizeof (float); i; --i) {
icculus@10575
   215
        src--;
icculus@10575
   216
        dst -= 2;
icculus@10575
   217
        dst[0] = dst[1] = *src;
icculus@1982
   218
    }
slouken@0
   219
slouken@1895
   220
    cvt->len_cvt *= 2;
slouken@1895
   221
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
   222
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
   223
    }
slouken@0
   224
}
slouken@0
   225
slouken@942
   226
icculus@11405
   227
/* Upmix stereo to a pseudo-5.1 stream */
icculus@1982
   228
static void SDLCALL
icculus@10793
   229
SDL_ConvertStereoTo51(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@942
   230
{
slouken@1895
   231
    int i;
icculus@10575
   232
    float lf, rf, ce;
icculus@10575
   233
    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
icculus@10575
   234
    float *dst = (float *) (cvt->buf + cvt->len_cvt * 3);
slouken@942
   235
icculus@10575
   236
    LOG_DEBUG_CONVERT("stereo", "5.1");
icculus@10575
   237
    SDL_assert(format == AUDIO_F32SYS);
slouken@942
   238
icculus@11405
   239
    for (i = cvt->len_cvt / (sizeof(float) * 2); i; --i) {
icculus@10575
   240
        dst -= 6;
icculus@10575
   241
        src -= 2;
icculus@10575
   242
        lf = src[0];
icculus@10575
   243
        rf = src[1];
icculus@10793
   244
        ce = (lf + rf) * 0.5f;
icculus@11405
   245
        /* !!! FIXME: FL and FR may clip */
icculus@10793
   246
        dst[0] = lf + (lf - ce);  /* FL */
icculus@10793
   247
        dst[1] = rf + (rf - ce);  /* FR */
icculus@10793
   248
        dst[2] = ce;  /* FC */
icculus@11405
   249
        dst[3] = 0;   /* LFE (only meant for special LFE effects) */
icculus@10793
   250
        dst[4] = lf;  /* BL */
icculus@10793
   251
        dst[5] = rf;  /* BR */
icculus@10575
   252
    }
slouken@942
   253
slouken@1895
   254
    cvt->len_cvt *= 3;
slouken@1895
   255
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
   256
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
   257
    }
slouken@942
   258
}
slouken@942
   259
slouken@942
   260
icculus@11405
   261
/* Upmix quad to a pseudo-5.1 stream */
icculus@11405
   262
static void SDLCALL
icculus@11405
   263
SDL_ConvertQuadTo51(SDL_AudioCVT * cvt, SDL_AudioFormat format)
icculus@11405
   264
{
icculus@11405
   265
    int i;
icculus@11405
   266
    float lf, rf, lb, rb, ce;
icculus@11405
   267
    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
icculus@11405
   268
    float *dst = (float *) (cvt->buf + cvt->len_cvt * 3 / 2);
icculus@11405
   269
icculus@11405
   270
    LOG_DEBUG_CONVERT("quad", "5.1");
icculus@11405
   271
    SDL_assert(format == AUDIO_F32SYS);
icculus@11405
   272
    SDL_assert(cvt->len_cvt % (sizeof(float) * 4) == 0);
icculus@11405
   273
icculus@11405
   274
    for (i = cvt->len_cvt / (sizeof(float) * 4); i; --i) {
icculus@11405
   275
        dst -= 6;
icculus@11405
   276
        src -= 4;
icculus@11405
   277
        lf = src[0];
icculus@11405
   278
        rf = src[1];
icculus@11405
   279
        lb = src[2];
icculus@11405
   280
        rb = src[3];
icculus@11405
   281
        ce = (lf + rf) * 0.5f;
icculus@11405
   282
        /* !!! FIXME: FL and FR may clip */
icculus@11405
   283
        dst[0] = lf + (lf - ce);  /* FL */
icculus@11405
   284
        dst[1] = rf + (rf - ce);  /* FR */
icculus@11405
   285
        dst[2] = ce;  /* FC */
icculus@11405
   286
        dst[3] = 0;   /* LFE (only meant for special LFE effects) */
icculus@11405
   287
        dst[4] = lb;  /* BL */
icculus@11405
   288
        dst[5] = rb;  /* BR */
icculus@11405
   289
    }
icculus@11405
   290
icculus@11405
   291
    cvt->len_cvt = cvt->len_cvt * 3 / 2;
icculus@11405
   292
    if (cvt->filters[++cvt->filter_index]) {
icculus@11405
   293
        cvt->filters[cvt->filter_index] (cvt, format);
icculus@11405
   294
    }
icculus@11405
   295
}
icculus@11405
   296
icculus@11405
   297
icculus@11405
   298
/* Upmix stereo to a pseudo-4.0 stream (by duplication) */
icculus@1982
   299
static void SDLCALL
icculus@10793
   300
SDL_ConvertStereoToQuad(SDL_AudioCVT * cvt, SDL_AudioFormat format)
slouken@942
   301
{
icculus@10575
   302
    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
icculus@10575
   303
    float *dst = (float *) (cvt->buf + cvt->len_cvt * 2);
icculus@10793
   304
    float lf, rf;
slouken@1895
   305
    int i;
slouken@942
   306
icculus@10575
   307
    LOG_DEBUG_CONVERT("stereo", "quad");
icculus@10575
   308
    SDL_assert(format == AUDIO_F32SYS);
slouken@942
   309
icculus@11405
   310
    for (i = cvt->len_cvt / (sizeof(float) * 2); i; --i) {
icculus@10575
   311
        dst -= 4;
icculus@10575
   312
        src -= 2;
icculus@10575
   313
        lf = src[0];
icculus@10575
   314
        rf = src[1];
icculus@10793
   315
        dst[0] = lf;  /* FL */
icculus@10793
   316
        dst[1] = rf;  /* FR */
icculus@10793
   317
        dst[2] = lf;  /* BL */
icculus@10793
   318
        dst[3] = rf;  /* BR */
icculus@10575
   319
    }
slouken@942
   320
slouken@1895
   321
    cvt->len_cvt *= 2;
slouken@1895
   322
    if (cvt->filters[++cvt->filter_index]) {
slouken@1895
   323
        cvt->filters[cvt->filter_index] (cvt, format);
slouken@1895
   324
    }
slouken@0
   325
}
slouken@0
   326
icculus@11405
   327
icculus@11405
   328
/* Upmix 5.1 to 7.1 */
icculus@11405
   329
static void SDLCALL
icculus@11405
   330
SDL_Convert51To71(SDL_AudioCVT * cvt, SDL_AudioFormat format)
icculus@11405
   331
{
icculus@11405
   332
    float lf, rf, lb, rb, ls, rs;
icculus@11405
   333
    int i;
icculus@11405
   334
    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
icculus@11405
   335
    float *dst = (float *) (cvt->buf + cvt->len_cvt * 4 / 3);
icculus@11405
   336
icculus@11405
   337
    LOG_DEBUG_CONVERT("5.1", "7.1");
icculus@11405
   338
    SDL_assert(format == AUDIO_F32SYS);
icculus@11405
   339
    SDL_assert(cvt->len_cvt % (sizeof(float) * 6) == 0);
icculus@11405
   340
icculus@11405
   341
    for (i = cvt->len_cvt / (sizeof(float) * 6); i; --i) {
icculus@11405
   342
        dst -= 8;
icculus@11405
   343
        src -= 6;
icculus@11405
   344
        lf = src[0];
icculus@11405
   345
        rf = src[1];
icculus@11405
   346
        lb = src[4];
icculus@11405
   347
        rb = src[5];
icculus@11405
   348
        ls = (lf + lb) * 0.5f;
icculus@11405
   349
        rs = (rf + rb) * 0.5f;
icculus@11405
   350
        /* !!! FIXME: these four may clip */
icculus@11405
   351
        lf += lf - ls;
icculus@11405
   352
        rf += rf - ls;
icculus@11405
   353
        lb += lb - ls;
icculus@11405
   354
        rb += rb - ls;
icculus@11405
   355
        dst[3] = src[3];  /* LFE */
icculus@11405
   356
        dst[2] = src[2];  /* FC */
icculus@11405
   357
        dst[7] = rs; /* SR */
icculus@11405
   358
        dst[6] = ls; /* SL */
icculus@11405
   359
        dst[5] = rb;  /* BR */
icculus@11405
   360
        dst[4] = lb;  /* BL */
icculus@11405
   361
        dst[1] = rf;  /* FR */
icculus@11405
   362
        dst[0] = lf;  /* FL */
icculus@11405
   363
    }
icculus@11405
   364
icculus@11405
   365
    cvt->len_cvt = cvt->len_cvt * 4 / 3;
icculus@11405
   366
icculus@11405
   367
    if (cvt->filters[++cvt->filter_index]) {
icculus@11405
   368
        cvt->filters[cvt->filter_index] (cvt, format);
icculus@11405
   369
    }
icculus@11405
   370
}
icculus@11405
   371
icculus@11508
   372
/* SDL's resampler uses a "bandlimited interpolation" algorithm:
icculus@11508
   373
     https://ccrma.stanford.edu/~jos/resample/ */
icculus@11508
   374
icculus@11508
   375
#define RESAMPLER_ZERO_CROSSINGS 5
icculus@11508
   376
#define RESAMPLER_BITS_PER_SAMPLE 16
icculus@11508
   377
#define RESAMPLER_SAMPLES_PER_ZERO_CROSSING  (1 << ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1))
icculus@11508
   378
#define RESAMPLER_FILTER_SIZE ((RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS) + 1)
icculus@11508
   379
icculus@11508
   380
/* This is a "modified" bessel function, so you can't use POSIX j0() */
icculus@11508
   381
static double
icculus@11508
   382
bessel(const double x)
icculus@11508
   383
{
icculus@11508
   384
    const double xdiv2 = x / 2.0;
icculus@11508
   385
    double i0 = 1.0f;
icculus@11508
   386
    double f = 1.0f;
icculus@11508
   387
    int i = 1;
icculus@11508
   388
icculus@11508
   389
    while (SDL_TRUE) {
icculus@11508
   390
        const double diff = SDL_pow(xdiv2, i * 2) / SDL_pow(f, 2);
icculus@11508
   391
        if (diff < 1.0e-21f) {
icculus@11508
   392
            break;
icculus@11508
   393
        }
icculus@11508
   394
        i0 += diff;
icculus@11508
   395
        i++;
icculus@11508
   396
        f *= (double) i;
icculus@11508
   397
    }
icculus@11508
   398
icculus@11508
   399
    return i0;
icculus@11508
   400
}
icculus@11508
   401
icculus@11508
   402
/* build kaiser table with cardinal sine applied to it, and array of differences between elements. */
icculus@11508
   403
static void
icculus@11508
   404
kaiser_and_sinc(float *table, float *diffs, const int tablelen, const double beta)
icculus@11508
   405
{
icculus@11508
   406
    const int lenm1 = tablelen - 1;
icculus@11508
   407
    const int lenm1div2 = lenm1 / 2;
icculus@11508
   408
    int i;
icculus@11508
   409
icculus@11508
   410
    table[0] = 1.0f;
icculus@11508
   411
    for (i = 1; i < tablelen; i++) {
icculus@11508
   412
        const double kaiser = bessel(beta * SDL_sqrt(1.0 - SDL_pow(((i - lenm1) / 2.0) / lenm1div2, 2.0))) / bessel(beta);
icculus@11508
   413
        table[tablelen - i] = (float) kaiser;
icculus@11508
   414
    }
icculus@11508
   415
icculus@11508
   416
    for (i = 1; i < tablelen; i++) {
icculus@11508
   417
        const float x = (((float) i) / ((float) RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) * ((float) M_PI);
icculus@11508
   418
        table[i] *= SDL_sinf(x) / x;
icculus@11508
   419
        diffs[i - 1] = table[i] - table[i - 1];
icculus@11508
   420
    }
icculus@11508
   421
    diffs[lenm1] = 0.0f;
icculus@11508
   422
}
icculus@11508
   423
icculus@11508
   424
icculus@11508
   425
static SDL_SpinLock ResampleFilterSpinlock = 0;
icculus@11508
   426
static float *ResamplerFilter = NULL;
icculus@11508
   427
static float *ResamplerFilterDifference = NULL;
icculus@11508
   428
icculus@11508
   429
int
icculus@11508
   430
SDL_PrepareResampleFilter(void)
icculus@11508
   431
{
icculus@11508
   432
    SDL_AtomicLock(&ResampleFilterSpinlock);
icculus@11508
   433
    if (!ResamplerFilter) {
icculus@11508
   434
        /* if dB > 50, beta=(0.1102 * (dB - 8.7)), according to Matlab. */
icculus@11508
   435
        const double dB = 80.0;
icculus@11508
   436
        const double beta = 0.1102 * (dB - 8.7);
icculus@11508
   437
        const size_t alloclen = RESAMPLER_FILTER_SIZE * sizeof (float);
icculus@11508
   438
icculus@11508
   439
        ResamplerFilter = (float *) SDL_malloc(alloclen);
icculus@11508
   440
        if (!ResamplerFilter) {
icculus@11508
   441
            SDL_AtomicUnlock(&ResampleFilterSpinlock);
icculus@11508
   442
            return SDL_OutOfMemory();
icculus@11508
   443
        }
icculus@11508
   444
icculus@11508
   445
        ResamplerFilterDifference = (float *) SDL_malloc(alloclen);
icculus@11508
   446
        if (!ResamplerFilterDifference) {
icculus@11508
   447
            SDL_free(ResamplerFilter);
icculus@11508
   448
            ResamplerFilter = NULL;
icculus@11508
   449
            SDL_AtomicUnlock(&ResampleFilterSpinlock);
icculus@11508
   450
            return SDL_OutOfMemory();
icculus@11508
   451
        }
icculus@11508
   452
        kaiser_and_sinc(ResamplerFilter, ResamplerFilterDifference, RESAMPLER_FILTER_SIZE, beta);
icculus@11508
   453
    }
icculus@11508
   454
    SDL_AtomicUnlock(&ResampleFilterSpinlock);
icculus@11508
   455
    return 0;
icculus@11508
   456
}
icculus@11508
   457
icculus@11508
   458
void
icculus@11508
   459
SDL_FreeResampleFilter(void)
icculus@11508
   460
{
icculus@11508
   461
    SDL_free(ResamplerFilter);
icculus@11508
   462
    SDL_free(ResamplerFilterDifference);
icculus@11508
   463
    ResamplerFilter = NULL;
icculus@11508
   464
    ResamplerFilterDifference = NULL;
icculus@11508
   465
}
icculus@11508
   466
icculus@11405
   467
icculus@10799
   468
static int
icculus@11508
   469
SDL_ResampleAudio(const int chans, const int inrate, const int outrate,
icculus@10799
   470
                        float *last_sample, const float *inbuf,
icculus@10799
   471
                        const int inbuflen, float *outbuf, const int outbuflen)
icculus@10799
   472
{
icculus@11508
   473
    const float outtimeincr = 1.0f / ((float) outrate);
icculus@11508
   474
    const float ratio = ((float) outrate) / ((float) inrate);
icculus@11508
   475
    /*const int padding_len = (ratio < 1.0f) ? (int) SDL_ceilf(((float) (RESAMPLER_SAMPLES_PER_ZERO_CROSSING * inrate) / ((float) outrate))) : RESAMPLER_SAMPLES_PER_ZERO_CROSSING;*/
icculus@10817
   476
    const int framelen = chans * (int)sizeof (float);
icculus@11508
   477
    const int inframes = inbuflen / framelen;
icculus@11508
   478
    const int wantedoutframes = (int) ((inbuflen / framelen) * ratio);  /* outbuflen isn't total to write, it's total available. */
icculus@11508
   479
    const int maxoutframes = outbuflen / framelen;
icculus@11508
   480
    const int outframes = (wantedoutframes < maxoutframes) ? wantedoutframes : maxoutframes;
icculus@11508
   481
    float *dst = outbuf;
icculus@11508
   482
    float outtime = 0.0f;
icculus@11508
   483
    int i, j, chan;
icculus@10799
   484
icculus@11508
   485
    for (i = 0; i < outframes; i++) {
icculus@11508
   486
        const int srcindex = (int) (outtime * inrate);
icculus@11508
   487
        const float finrate = (float) inrate;
icculus@11508
   488
        const float intime = ((float) srcindex) / finrate;
icculus@11508
   489
        const float innexttime = ((float) (srcindex + 1)) / finrate;
icculus@10799
   490
icculus@11508
   491
        const float interpolation1 = 1.0f - (innexttime - outtime) / (innexttime - intime);
icculus@11508
   492
        const int filterindex1 = (int) (interpolation1 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING);
icculus@11508
   493
        const float interpolation2 = 1.0f - interpolation1;
icculus@11508
   494
        const int filterindex2 = interpolation2 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING;
icculus@10833
   495
icculus@11508
   496
        for (chan = 0; chan < chans; chan++) {
icculus@11508
   497
            float outsample = 0.0f;
icculus@11508
   498
icculus@11508
   499
            /* do this twice to calculate the sample, once for the "left wing" and then same for the right. */
icculus@11508
   500
            /* !!! FIXME: do both wings in one loop */
icculus@11508
   501
            for (j = 0; (filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) {
icculus@11508
   502
                /* !!! FIXME: insample uses zero for padding samples, but it should use prior state from last_sample. */
icculus@11508
   503
                const int srcframe = srcindex - j;
icculus@11508
   504
                const float insample = (srcframe < 0) ? 0.0f : inbuf[(srcframe * chans) + chan];  /* !!! FIXME: we can bubble this conditional out of here by doing a pre loop. */
icculus@11508
   505
                outsample += (insample * (ResamplerFilter[filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)] + (interpolation1 * ResamplerFilterDifference[filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)])));
icculus@10840
   506
            }
icculus@11508
   507
icculus@11508
   508
            for (j = 0; (filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) {
icculus@11508
   509
                const int srcframe = srcindex + 1 + j;
icculus@11508
   510
                /* !!! FIXME: insample uses zero for padding samples, but it should use prior state from last_sample. */
icculus@11508
   511
                const float insample = (srcframe >= inframes) ? 0.0f : inbuf[(srcframe * chans) + chan];  /* !!! FIXME: we can bubble this conditional out of here by doing a post loop. */
icculus@11508
   512
                outsample += (insample * (ResamplerFilter[filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)] + (interpolation2 * ResamplerFilterDifference[filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)])));
icculus@10840
   513
            }
icculus@11508
   514
            *(dst++) = outsample;
icculus@10799
   515
        }
icculus@10833
   516
icculus@11508
   517
        outtime += outtimeincr;
icculus@10799
   518
    }
icculus@10799
   519
icculus@11508
   520
    return outframes * chans * sizeof (float);
icculus@10799
   521
}
icculus@10799
   522
slouken@1895
   523
int
slouken@1895
   524
SDL_ConvertAudio(SDL_AudioCVT * cvt)
slouken@0
   525
{
icculus@3021
   526
    /* !!! FIXME: (cvt) should be const; stack-copy it here. */
icculus@3021
   527
    /* !!! FIXME: (actually, we can't...len_cvt needs to be updated. Grr.) */
icculus@3021
   528
slouken@1895
   529
    /* Make sure there's data to convert */
slouken@1895
   530
    if (cvt->buf == NULL) {
icculus@10575
   531
        return SDL_SetError("No buffer allocated for conversion");
slouken@1895
   532
    }
icculus@10575
   533
slouken@1895
   534
    /* Return okay if no conversion is necessary */
slouken@1895
   535
    cvt->len_cvt = cvt->len;
slouken@1895
   536
    if (cvt->filters[0] == NULL) {
icculus@10575
   537
        return 0;
slouken@1895
   538
    }
slouken@0
   539
slouken@1895
   540
    /* Set up the conversion and go! */
slouken@1895
   541
    cvt->filter_index = 0;
slouken@1895
   542
    cvt->filters[0] (cvt, cvt->src_format);
icculus@10575
   543
    return 0;
slouken@0
   544
}
slouken@0
   545
icculus@10575
   546
static void SDLCALL
icculus@10575
   547
SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format)
icculus@10575
   548
{
slouken@10579
   549
#if DEBUG_CONVERT
slouken@10579
   550
    printf("Converting byte order\n");
slouken@10579
   551
#endif
icculus@1982
   552
icculus@10575
   553
    switch (SDL_AUDIO_BITSIZE(format)) {
icculus@10575
   554
        #define CASESWAP(b) \
icculus@10575
   555
            case b: { \
icculus@10575
   556
                Uint##b *ptr = (Uint##b *) cvt->buf; \
icculus@10575
   557
                int i; \
icculus@10575
   558
                for (i = cvt->len_cvt / sizeof (*ptr); i; --i, ++ptr) { \
icculus@10575
   559
                    *ptr = SDL_Swap##b(*ptr); \
icculus@10575
   560
                } \
icculus@10575
   561
                break; \
icculus@10575
   562
            }
icculus@1982
   563
icculus@10575
   564
        CASESWAP(16);
icculus@10575
   565
        CASESWAP(32);
icculus@10575
   566
        CASESWAP(64);
icculus@10575
   567
icculus@10575
   568
        #undef CASESWAP
icculus@10575
   569
icculus@10575
   570
        default: SDL_assert(!"unhandled byteswap datatype!"); break;
icculus@10575
   571
    }
icculus@10575
   572
icculus@10575
   573
    if (cvt->filters[++cvt->filter_index]) {
icculus@10575
   574
        /* flip endian flag for data. */
icculus@10575
   575
        if (format & SDL_AUDIO_MASK_ENDIAN) {
icculus@10575
   576
            format &= ~SDL_AUDIO_MASK_ENDIAN;
icculus@10575
   577
        } else {
icculus@10575
   578
            format |= SDL_AUDIO_MASK_ENDIAN;
icculus@10575
   579
        }
icculus@10575
   580
        cvt->filters[cvt->filter_index](cvt, format);
icculus@10575
   581
    }
icculus@1982
   582
}
icculus@1982
   583
slouken@11096
   584
static int
slouken@11096
   585
SDL_AddAudioCVTFilter(SDL_AudioCVT *cvt, const SDL_AudioFilter filter)
slouken@11096
   586
{
slouken@11096
   587
    if (cvt->filter_index >= SDL_AUDIOCVT_MAX_FILTERS) {
slouken@11096
   588
        return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS);
slouken@11096
   589
    }
slouken@11096
   590
    if (filter == NULL) {
slouken@11096
   591
        return SDL_SetError("Audio filter pointer is NULL");
slouken@11096
   592
    }
slouken@11096
   593
    cvt->filters[cvt->filter_index++] = filter;
slouken@11096
   594
    cvt->filters[cvt->filter_index] = NULL; /* Moving terminator */
slouken@11096
   595
    return 0;
slouken@11096
   596
}
icculus@1982
   597
icculus@1982
   598
static int
icculus@10575
   599
SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt)
icculus@1982
   600
{
icculus@10575
   601
    int retval = 0;  /* 0 == no conversion necessary. */
icculus@1982
   602
icculus@10575
   603
    if ((SDL_AUDIO_ISBIGENDIAN(src_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) {
slouken@11096
   604
        if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
slouken@11096
   605
            return -1;
slouken@11096
   606
        }
icculus@10575
   607
        retval = 1;  /* added a converter. */
icculus@10575
   608
    }
icculus@1982
   609
icculus@10575
   610
    if (!SDL_AUDIO_ISFLOAT(src_fmt)) {
icculus@10576
   611
        const Uint16 src_bitsize = SDL_AUDIO_BITSIZE(src_fmt);
icculus@10576
   612
        const Uint16 dst_bitsize = 32;
icculus@10575
   613
        SDL_AudioFilter filter = NULL;
icculus@10576
   614
icculus@10575
   615
        switch (src_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
icculus@10575
   616
            case AUDIO_S8: filter = SDL_Convert_S8_to_F32; break;
icculus@10575
   617
            case AUDIO_U8: filter = SDL_Convert_U8_to_F32; break;
icculus@10575
   618
            case AUDIO_S16: filter = SDL_Convert_S16_to_F32; break;
philipp@10591
   619
            case AUDIO_U16: filter = SDL_Convert_U16_to_F32; break;
icculus@10575
   620
            case AUDIO_S32: filter = SDL_Convert_S32_to_F32; break;
icculus@10575
   621
            default: SDL_assert(!"Unexpected audio format!"); break;
icculus@1982
   622
        }
icculus@1982
   623
icculus@10575
   624
        if (!filter) {
icculus@11319
   625
            return SDL_SetError("No conversion from source format to float available");
icculus@10575
   626
        }
icculus@10575
   627
slouken@11096
   628
        if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
slouken@11096
   629
            return -1;
slouken@11096
   630
        }
icculus@1982
   631
        if (src_bitsize < dst_bitsize) {
icculus@1982
   632
            const int mult = (dst_bitsize / src_bitsize);
icculus@1982
   633
            cvt->len_mult *= mult;
icculus@1982
   634
            cvt->len_ratio *= mult;
icculus@1982
   635
        } else if (src_bitsize > dst_bitsize) {
icculus@1982
   636
            cvt->len_ratio /= (src_bitsize / dst_bitsize);
icculus@1982
   637
        }
icculus@10576
   638
icculus@10575
   639
        retval = 1;  /* added a converter. */
icculus@1982
   640
    }
icculus@1982
   641
icculus@10575
   642
    return retval;
icculus@1982
   643
}
icculus@1982
   644
icculus@10575
   645
static int
icculus@10575
   646
SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt)
icculus@10575
   647
{
icculus@10575
   648
    int retval = 0;  /* 0 == no conversion necessary. */
icculus@3021
   649
icculus@10575
   650
    if (!SDL_AUDIO_ISFLOAT(dst_fmt)) {
icculus@10577
   651
        const Uint16 dst_bitsize = SDL_AUDIO_BITSIZE(dst_fmt);
icculus@10577
   652
        const Uint16 src_bitsize = 32;
icculus@10575
   653
        SDL_AudioFilter filter = NULL;
icculus@10575
   654
        switch (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
icculus@10575
   655
            case AUDIO_S8: filter = SDL_Convert_F32_to_S8; break;
icculus@10575
   656
            case AUDIO_U8: filter = SDL_Convert_F32_to_U8; break;
icculus@10575
   657
            case AUDIO_S16: filter = SDL_Convert_F32_to_S16; break;
philipp@10591
   658
            case AUDIO_U16: filter = SDL_Convert_F32_to_U16; break;
icculus@10575
   659
            case AUDIO_S32: filter = SDL_Convert_F32_to_S32; break;
icculus@10575
   660
            default: SDL_assert(!"Unexpected audio format!"); break;
icculus@10575
   661
        }
slouken@2716
   662
icculus@10575
   663
        if (!filter) {
icculus@11319
   664
            return SDL_SetError("No conversion from float to destination format available");
icculus@10575
   665
        }
icculus@10575
   666
slouken@11096
   667
        if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
slouken@11096
   668
            return -1;
slouken@11096
   669
        }
icculus@10575
   670
        if (src_bitsize < dst_bitsize) {
icculus@10575
   671
            const int mult = (dst_bitsize / src_bitsize);
icculus@10575
   672
            cvt->len_mult *= mult;
icculus@10575
   673
            cvt->len_ratio *= mult;
icculus@10575
   674
        } else if (src_bitsize > dst_bitsize) {
icculus@10575
   675
            cvt->len_ratio /= (src_bitsize / dst_bitsize);
icculus@10575
   676
        }
icculus@10575
   677
        retval = 1;  /* added a converter. */
icculus@10575
   678
    }
icculus@10575
   679
icculus@10575
   680
    if ((SDL_AUDIO_ISBIGENDIAN(dst_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) {
slouken@11096
   681
        if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
slouken@11096
   682
            return -1;
slouken@11096
   683
        }
icculus@10575
   684
        retval = 1;  /* added a converter. */
icculus@10575
   685
    }
icculus@10575
   686
icculus@10575
   687
    return retval;
icculus@3021
   688
}
slouken@2716
   689
icculus@10799
   690
static void
icculus@10799
   691
SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format)
icculus@10799
   692
{
icculus@11508
   693
    /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator).
icculus@11508
   694
       !!! FIXME in 2.1:   We need to store data for this resampler, because the cvt structure doesn't store the original sample rates,
icculus@11508
   695
       !!! FIXME in 2.1:   so we steal the ninth and tenth slot.  :( */
icculus@11508
   696
    const int srcrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1];
icculus@11508
   697
    const int dstrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS];
icculus@10799
   698
    const float *src = (const float *) cvt->buf;
icculus@10799
   699
    const int srclen = cvt->len_cvt;
icculus@11508
   700
    /*float *dst = (float *) cvt->buf;
icculus@11508
   701
    const int dstlen = (cvt->len * cvt->len_mult);*/
icculus@11508
   702
    /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
icculus@11508
   703
    float *dst = (float *) (cvt->buf + srclen);
icculus@11508
   704
    const int dstlen = (cvt->len * cvt->len_mult) - srclen;
icculus@10804
   705
    float state[8];
icculus@10756
   706
icculus@10799
   707
    SDL_assert(format == AUDIO_F32SYS);
icculus@10799
   708
icculus@11508
   709
    SDL_zero(state);
icculus@10799
   710
icculus@11508
   711
    cvt->len_cvt = SDL_ResampleAudio(chans, srcrate, dstrate, state, src, srclen, dst, dstlen);
icculus@11508
   712
icculus@11508
   713
    SDL_memcpy(cvt->buf, dst, cvt->len_cvt);  /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
icculus@11508
   714
icculus@10799
   715
    if (cvt->filters[++cvt->filter_index]) {
icculus@10799
   716
        cvt->filters[cvt->filter_index](cvt, format);
icculus@10799
   717
    }
icculus@10799
   718
}
icculus@10799
   719
icculus@10799
   720
/* !!! FIXME: We only have this macro salsa because SDL_AudioCVT doesn't
icculus@10799
   721
   !!! FIXME:  store channel info, so we have to have function entry
icculus@10799
   722
   !!! FIXME:  points for each supported channel count and multiple
icculus@10799
   723
   !!! FIXME:  vs arbitrary. When we rev the ABI, clean this up. */
icculus@10756
   724
#define RESAMPLER_FUNCS(chans) \
icculus@10756
   725
    static void SDLCALL \
icculus@10799
   726
    SDL_ResampleCVT_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) { \
icculus@10799
   727
        SDL_ResampleCVT(cvt, chans, format); \
icculus@10756
   728
    }
icculus@10756
   729
RESAMPLER_FUNCS(1)
icculus@10756
   730
RESAMPLER_FUNCS(2)
icculus@10756
   731
RESAMPLER_FUNCS(4)
icculus@10756
   732
RESAMPLER_FUNCS(6)
icculus@10756
   733
RESAMPLER_FUNCS(8)
icculus@10756
   734
#undef RESAMPLER_FUNCS
icculus@10756
   735
icculus@10799
   736
static SDL_AudioFilter
icculus@10799
   737
ChooseCVTResampler(const int dst_channels)
icculus@3021
   738
{
icculus@10799
   739
    switch (dst_channels) {
icculus@10799
   740
        case 1: return SDL_ResampleCVT_c1;
icculus@10799
   741
        case 2: return SDL_ResampleCVT_c2;
icculus@10799
   742
        case 4: return SDL_ResampleCVT_c4;
icculus@10799
   743
        case 6: return SDL_ResampleCVT_c6;
icculus@10799
   744
        case 8: return SDL_ResampleCVT_c8;
icculus@10799
   745
        default: break;
icculus@3021
   746
    }
slouken@2716
   747
icculus@10799
   748
    return NULL;
icculus@10756
   749
}
icculus@10575
   750
icculus@3021
   751
static int
icculus@10756
   752
SDL_BuildAudioResampleCVT(SDL_AudioCVT * cvt, const int dst_channels,
icculus@10756
   753
                          const int src_rate, const int dst_rate)
icculus@3021
   754
{
icculus@10756
   755
    SDL_AudioFilter filter;
icculus@3021
   756
icculus@10756
   757
    if (src_rate == dst_rate) {
icculus@10756
   758
        return 0;  /* no conversion necessary. */
slouken@2716
   759
    }
slouken@2716
   760
icculus@10799
   761
    filter = ChooseCVTResampler(dst_channels);
icculus@10756
   762
    if (filter == NULL) {
icculus@10756
   763
        return SDL_SetError("No conversion available for these rates");
icculus@10756
   764
    }
icculus@10756
   765
icculus@11508
   766
    if (SDL_PrepareResampleFilter() < 0) {
icculus@11508
   767
        return -1;
icculus@11508
   768
    }
icculus@11508
   769
icculus@10756
   770
    /* Update (cvt) with filter details... */
slouken@11096
   771
    if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
slouken@11096
   772
        return -1;
slouken@11096
   773
    }
icculus@11508
   774
icculus@11508
   775
    /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator).
icculus@11508
   776
       !!! FIXME in 2.1:   We need to store data for this resampler, because the cvt structure doesn't store the original sample rates,
icculus@11508
   777
       !!! FIXME in 2.1:   so we steal the ninth and tenth slot.  :( */
icculus@11508
   778
    if (cvt->filter_index >= (SDL_AUDIOCVT_MAX_FILTERS-2)) {
icculus@11508
   779
        return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS-2);
icculus@11508
   780
    }
icculus@11508
   781
    cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1] = (SDL_AudioFilter) (size_t) src_rate;
icculus@11508
   782
    cvt->filters[SDL_AUDIOCVT_MAX_FILTERS] = (SDL_AudioFilter) (size_t) dst_rate;
icculus@11508
   783
icculus@10756
   784
    if (src_rate < dst_rate) {
icculus@10756
   785
        const double mult = ((double) dst_rate) / ((double) src_rate);
icculus@10756
   786
        cvt->len_mult *= (int) SDL_ceil(mult);
icculus@10756
   787
        cvt->len_ratio *= mult;
icculus@10756
   788
    } else {
icculus@10756
   789
        cvt->len_ratio /= ((double) src_rate) / ((double) dst_rate);
icculus@10756
   790
    }
icculus@10756
   791
icculus@11508
   792
    /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
icculus@11508
   793
    /* the buffer is big enough to hold the destination now, but
icculus@11508
   794
       we need it large enough to hold a separate scratch buffer. */
icculus@11508
   795
    cvt->len_mult *= 2;
icculus@11508
   796
icculus@10756
   797
    return 1;               /* added a converter. */
slouken@2716
   798
}
icculus@1982
   799
icculus@11097
   800
static SDL_bool
icculus@11097
   801
SDL_SupportedAudioFormat(const SDL_AudioFormat fmt)
icculus@11097
   802
{
icculus@11097
   803
    switch (fmt) {
icculus@11097
   804
        case AUDIO_U8:
icculus@11097
   805
        case AUDIO_S8:
icculus@11097
   806
        case AUDIO_U16LSB:
icculus@11097
   807
        case AUDIO_S16LSB:
icculus@11097
   808
        case AUDIO_U16MSB:
icculus@11097
   809
        case AUDIO_S16MSB:
icculus@11097
   810
        case AUDIO_S32LSB:
icculus@11097
   811
        case AUDIO_S32MSB:
icculus@11097
   812
        case AUDIO_F32LSB:
icculus@11097
   813
        case AUDIO_F32MSB:
icculus@11097
   814
            return SDL_TRUE;  /* supported. */
icculus@11097
   815
icculus@11097
   816
        default:
icculus@11097
   817
            break;
icculus@11097
   818
    }
icculus@11097
   819
icculus@11097
   820
    return SDL_FALSE;  /* unsupported. */
icculus@11097
   821
}
icculus@11097
   822
icculus@11097
   823
static SDL_bool
icculus@11097
   824
SDL_SupportedChannelCount(const int channels)
icculus@11097
   825
{
icculus@11097
   826
    switch (channels) {
icculus@11097
   827
        case 1:  /* mono */
icculus@11097
   828
        case 2:  /* stereo */
icculus@11097
   829
        case 4:  /* quad */
icculus@11097
   830
        case 6:  /* 5.1 */
icculus@11405
   831
        case 8:  /* 7.1 */
icculus@11405
   832
          return SDL_TRUE;  /* supported. */
icculus@11097
   833
icculus@11097
   834
        default:
icculus@11097
   835
            break;
icculus@11097
   836
    }
icculus@11097
   837
icculus@11097
   838
    return SDL_FALSE;  /* unsupported. */
icculus@11097
   839
}
icculus@11097
   840
icculus@1982
   841
icculus@1982
   842
/* Creates a set of audio filters to convert from one format to another.
icculus@11319
   843
   Returns 0 if no conversion is needed, 1 if the audio filter is set up,
icculus@11319
   844
   or -1 if an error like invalid parameter, unsupported format, etc. occurred.
slouken@0
   845
*/
slouken@1895
   846
slouken@1895
   847
int
slouken@1895
   848
SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
icculus@1982
   849
                  SDL_AudioFormat src_fmt, Uint8 src_channels, int src_rate,
icculus@1982
   850
                  SDL_AudioFormat dst_fmt, Uint8 dst_channels, int dst_rate)
slouken@0
   851
{
aschiffler@6819
   852
    /* Sanity check target pointer */
aschiffler@6819
   853
    if (cvt == NULL) {
icculus@7037
   854
        return SDL_InvalidParamError("cvt");
aschiffler@6819
   855
    }
slouken@7191
   856
slouken@10767
   857
    /* Make sure we zero out the audio conversion before error checking */
slouken@10767
   858
    SDL_zerop(cvt);
slouken@10767
   859
icculus@11097
   860
    if (!SDL_SupportedAudioFormat(src_fmt)) {
icculus@7037
   861
        return SDL_SetError("Invalid source format");
icculus@11097
   862
    } else if (!SDL_SupportedAudioFormat(dst_fmt)) {
icculus@7037
   863
        return SDL_SetError("Invalid destination format");
icculus@11097
   864
    } else if (!SDL_SupportedChannelCount(src_channels)) {
icculus@11097
   865
        return SDL_SetError("Invalid source channels");
icculus@11097
   866
    } else if (!SDL_SupportedChannelCount(dst_channels)) {
icculus@11097
   867
        return SDL_SetError("Invalid destination channels");
icculus@11097
   868
    } else if (src_rate == 0) {
icculus@11097
   869
        return SDL_SetError("Source rate is zero");
icculus@11097
   870
    } else if (dst_rate == 0) {
icculus@11097
   871
        return SDL_SetError("Destination rate is zero");
icculus@1982
   872
    }
icculus@3021
   873
slouken@10579
   874
#if DEBUG_CONVERT
icculus@1982
   875
    printf("Build format %04x->%04x, channels %u->%u, rate %d->%d\n",
slouken@1985
   876
           src_fmt, dst_fmt, src_channels, dst_channels, src_rate, dst_rate);
slouken@1985
   877
#endif
icculus@1982
   878
slouken@1895
   879
    /* Start off with no conversion necessary */
icculus@1982
   880
    cvt->src_format = src_fmt;
icculus@1982
   881
    cvt->dst_format = dst_fmt;
slouken@1895
   882
    cvt->needed = 0;
slouken@1895
   883
    cvt->filter_index = 0;
icculus@11508
   884
    SDL_zero(cvt->filters);
slouken@1895
   885
    cvt->len_mult = 1;
slouken@1895
   886
    cvt->len_ratio = 1.0;
icculus@3021
   887
    cvt->rate_incr = ((double) dst_rate) / ((double) src_rate);
slouken@0
   888
slouken@11406
   889
    /* Make sure we've chosen audio conversion functions (MMX, scalar, etc.) */
slouken@11406
   890
    SDL_ChooseAudioConverters();
slouken@11406
   891
icculus@10575
   892
    /* Type conversion goes like this now:
icculus@10575
   893
        - byteswap to CPU native format first if necessary.
icculus@10575
   894
        - convert to native Float32 if necessary.
icculus@10575
   895
        - resample and change channel count if necessary.
icculus@10575
   896
        - convert back to native format.
icculus@10575
   897
        - byteswap back to foreign format if necessary.
icculus@10575
   898
icculus@10575
   899
       The expectation is we can process data faster in float32
icculus@10575
   900
       (possibly with SIMD), and making several passes over the same
icculus@10756
   901
       buffer is likely to be CPU cache-friendly, avoiding the
icculus@10575
   902
       biggest performance hit in modern times. Previously we had
icculus@10575
   903
       (script-generated) custom converters for every data type and
icculus@10575
   904
       it was a bloat on SDL compile times and final library size. */
icculus@10575
   905
slouken@10767
   906
    /* see if we can skip float conversion entirely. */
slouken@10767
   907
    if (src_rate == dst_rate && src_channels == dst_channels) {
slouken@10767
   908
        if (src_fmt == dst_fmt) {
slouken@10767
   909
            return 0;
slouken@10767
   910
        }
slouken@10767
   911
slouken@10767
   912
        /* just a byteswap needed? */
slouken@10767
   913
        if ((src_fmt & ~SDL_AUDIO_MASK_ENDIAN) == (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN)) {
slouken@11096
   914
            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
slouken@11096
   915
                return -1;
slouken@11096
   916
            }
slouken@10767
   917
            cvt->needed = 1;
slouken@10767
   918
            return 1;
slouken@10767
   919
        }
icculus@10575
   920
    }
icculus@10575
   921
icculus@1982
   922
    /* Convert data types, if necessary. Updates (cvt). */
slouken@10767
   923
    if (SDL_BuildAudioTypeCVTToFloat(cvt, src_fmt) < 0) {
slouken@1985
   924
        return -1;              /* shouldn't happen, but just in case... */
icculus@3021
   925
    }
slouken@0
   926
icculus@1982
   927
    /* Channel conversion */
icculus@11405
   928
    if (src_channels < dst_channels) {
icculus@11405
   929
        /* Upmixing */
icculus@11405
   930
        /* Mono -> Stereo [-> ...] */
slouken@1895
   931
        if ((src_channels == 1) && (dst_channels > 1)) {
slouken@11096
   932
            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertMonoToStereo) < 0) {
slouken@11096
   933
                return -1;
slouken@11096
   934
            }
slouken@1895
   935
            cvt->len_mult *= 2;
slouken@1895
   936
            src_channels = 2;
slouken@1895
   937
            cvt->len_ratio *= 2;
slouken@1895
   938
        }
icculus@11405
   939
        /* [Mono ->] Stereo -> 5.1 [-> 7.1] */
icculus@11405
   940
        if ((src_channels == 2) && (dst_channels >= 6)) {
slouken@11096
   941
            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertStereoTo51) < 0) {
slouken@11096
   942
                return -1;
slouken@11096
   943
            }
slouken@1895
   944
            src_channels = 6;
slouken@1895
   945
            cvt->len_mult *= 3;
slouken@1895
   946
            cvt->len_ratio *= 3;
slouken@1895
   947
        }
icculus@11405
   948
        /* Quad -> 5.1 [-> 7.1] */
icculus@11405
   949
        if ((src_channels == 4) && (dst_channels >= 6)) {
icculus@11405
   950
            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertQuadTo51) < 0) {
icculus@11405
   951
                return -1;
icculus@11405
   952
            }
icculus@11405
   953
            src_channels = 6;
icculus@11405
   954
            cvt->len_mult = (cvt->len_mult * 3 + 1) / 2;
icculus@11405
   955
            cvt->len_ratio *= 1.5;
icculus@11405
   956
        }
icculus@11405
   957
        /* [[Mono ->] Stereo ->] 5.1 -> 7.1 */
icculus@11405
   958
        if ((src_channels == 6) && (dst_channels == 8)) {
icculus@11405
   959
            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51To71) < 0) {
icculus@11405
   960
                return -1;
icculus@11405
   961
            }
icculus@11405
   962
            src_channels = 8;
icculus@11405
   963
            cvt->len_mult = (cvt->len_mult * 4 + 2) / 3;
icculus@11405
   964
            /* Should be numerically exact with every valid input to this
icculus@11405
   965
               function */
icculus@11405
   966
            cvt->len_ratio = cvt->len_ratio * 4 / 3;
icculus@11405
   967
        }
icculus@11405
   968
        /* [Mono ->] Stereo -> Quad */
slouken@1895
   969
        if ((src_channels == 2) && (dst_channels == 4)) {
slouken@11096
   970
            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertStereoToQuad) < 0) {
slouken@11096
   971
                return -1;
slouken@11096
   972
            }
slouken@1895
   973
            src_channels = 4;
slouken@1895
   974
            cvt->len_mult *= 2;
slouken@1895
   975
            cvt->len_ratio *= 2;
slouken@1895
   976
        }
icculus@11405
   977
    } else if (src_channels > dst_channels) {
icculus@11405
   978
        /* Downmixing */
icculus@11405
   979
        /* 7.1 -> 5.1 [-> Stereo [-> Mono]] */
icculus@11405
   980
        /* 7.1 -> 5.1 [-> Quad] */
icculus@11405
   981
        if ((src_channels == 8) && (dst_channels <= 6)) {
icculus@11405
   982
            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert71To51) < 0) {
slouken@11096
   983
                return -1;
slouken@11096
   984
            }
icculus@11405
   985
            src_channels = 6;
icculus@11405
   986
            cvt->len_ratio *= 0.75;
slouken@1895
   987
        }
icculus@11405
   988
        /* [7.1 ->] 5.1 -> Stereo [-> Mono] */
slouken@1895
   989
        if ((src_channels == 6) && (dst_channels <= 2)) {
slouken@11096
   990
            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51ToStereo) < 0) {
slouken@11096
   991
                return -1;
slouken@11096
   992
            }
slouken@1895
   993
            src_channels = 2;
slouken@1895
   994
            cvt->len_ratio /= 3;
slouken@1895
   995
        }
icculus@11405
   996
        /* 5.1 -> Quad */
slouken@1895
   997
        if ((src_channels == 6) && (dst_channels == 4)) {
slouken@11096
   998
            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51ToQuad) < 0) {
slouken@11096
   999
                return -1;
slouken@11096
  1000
            }
slouken@1895
  1001
            src_channels = 4;
icculus@11405
  1002
            cvt->len_ratio = cvt->len_ratio * 2 / 3;
icculus@11405
  1003
        }
icculus@11405
  1004
        /* Quad -> Stereo [-> Mono] */
icculus@11405
  1005
        if ((src_channels == 4) && (dst_channels <= 2)) {
icculus@11405
  1006
            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertQuadToStereo) < 0) {
icculus@11405
  1007
                return -1;
icculus@11405
  1008
            }
icculus@11405
  1009
            src_channels = 2;
slouken@1895
  1010
            cvt->len_ratio /= 2;
slouken@1895
  1011
        }
icculus@11405
  1012
        /* [... ->] Stereo -> Mono */
icculus@11405
  1013
        if ((src_channels == 2) && (dst_channels == 1)) {
icculus@10832
  1014
            SDL_AudioFilter filter = NULL;
icculus@10832
  1015
icculus@10832
  1016
            #if HAVE_SSE3_INTRINSICS
icculus@10832
  1017
            if (SDL_HasSSE3()) {
icculus@10832
  1018
                filter = SDL_ConvertStereoToMono_SSE3;
icculus@10832
  1019
            }
icculus@10832
  1020
            #endif
icculus@10832
  1021
icculus@10832
  1022
            if (!filter) {
icculus@10832
  1023
                filter = SDL_ConvertStereoToMono;
icculus@10832
  1024
            }
icculus@10832
  1025
slouken@11096
  1026
            if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
slouken@11096
  1027
                return -1;
slouken@11096
  1028
            }
icculus@10832
  1029
icculus@11405
  1030
            src_channels = 1;
slouken@1895
  1031
            cvt->len_ratio /= 2;
slouken@1895
  1032
        }
slouken@1895
  1033
    }
slouken@0
  1034
icculus@11405
  1035
    if (src_channels != dst_channels) {
icculus@11405
  1036
        /* All combinations of supported channel counts should have been
icculus@11405
  1037
           handled by now, but let's be defensive */
icculus@11405
  1038
      return SDL_SetError("Invalid channel combination");
icculus@11405
  1039
    }
icculus@11405
  1040
    
icculus@3021
  1041
    /* Do rate conversion, if necessary. Updates (cvt). */
slouken@10767
  1042
    if (SDL_BuildAudioResampleCVT(cvt, dst_channels, src_rate, dst_rate) < 0) {
icculus@3021
  1043
        return -1;              /* shouldn't happen, but just in case... */
slouken@2716
  1044
    }
slouken@2716
  1045
icculus@10756
  1046
    /* Move to final data type. */
slouken@10767
  1047
    if (SDL_BuildAudioTypeCVTFromFloat(cvt, dst_fmt) < 0) {
icculus@10575
  1048
        return -1;              /* shouldn't happen, but just in case... */
slouken@1895
  1049
    }
icculus@10575
  1050
icculus@10575
  1051
    cvt->needed = (cvt->filter_index != 0);
slouken@1895
  1052
    return (cvt->needed);
slouken@0
  1053
}
slouken@1895
  1054
icculus@10842
  1055
typedef int (*SDL_ResampleAudioStreamFunc)(SDL_AudioStream *stream, const void *inbuf, const int inbuflen, void *outbuf, const int outbuflen);
slouken@10773
  1056
typedef void (*SDL_ResetAudioStreamResamplerFunc)(SDL_AudioStream *stream);
slouken@10773
  1057
typedef void (*SDL_CleanupAudioStreamResamplerFunc)(SDL_AudioStream *stream);
icculus@10757
  1058
icculus@10757
  1059
struct SDL_AudioStream
icculus@10757
  1060
{
icculus@10757
  1061
    SDL_AudioCVT cvt_before_resampling;
icculus@10757
  1062
    SDL_AudioCVT cvt_after_resampling;
icculus@10757
  1063
    SDL_DataQueue *queue;
icculus@10844
  1064
    Uint8 *work_buffer_base;  /* maybe unaligned pointer from SDL_realloc(). */
icculus@10757
  1065
    int work_buffer_len;
icculus@10757
  1066
    int src_sample_frame_size;
icculus@10757
  1067
    SDL_AudioFormat src_format;
icculus@10757
  1068
    Uint8 src_channels;
icculus@10757
  1069
    int src_rate;
icculus@10757
  1070
    int dst_sample_frame_size;
icculus@10757
  1071
    SDL_AudioFormat dst_format;
icculus@10757
  1072
    Uint8 dst_channels;
icculus@10757
  1073
    int dst_rate;
icculus@10757
  1074
    double rate_incr;
icculus@10757
  1075
    Uint8 pre_resample_channels;
slouken@10773
  1076
    int packetlen;
slouken@10773
  1077
    void *resampler_state;
slouken@10773
  1078
    SDL_ResampleAudioStreamFunc resampler_func;
slouken@10773
  1079
    SDL_ResetAudioStreamResamplerFunc reset_resampler_func;
slouken@10773
  1080
    SDL_CleanupAudioStreamResamplerFunc cleanup_resampler_func;
slouken@10773
  1081
};
slouken@10773
  1082
icculus@10851
  1083
static Uint8 *
icculus@10851
  1084
EnsureStreamBufferSize(SDL_AudioStream *stream, const int newlen)
icculus@10851
  1085
{
icculus@10851
  1086
    Uint8 *ptr;
icculus@10851
  1087
    size_t offset;
icculus@10851
  1088
icculus@10851
  1089
    if (stream->work_buffer_len >= newlen) {
icculus@10851
  1090
        ptr = stream->work_buffer_base;
icculus@10851
  1091
    } else {
icculus@10851
  1092
        ptr = (Uint8 *) SDL_realloc(stream->work_buffer_base, newlen + 32);
icculus@10851
  1093
        if (!ptr) {
icculus@10851
  1094
            SDL_OutOfMemory();
icculus@10851
  1095
            return NULL;
icculus@10851
  1096
        }
icculus@10851
  1097
        /* Make sure we're aligned to 16 bytes for SIMD code. */
icculus@10851
  1098
        stream->work_buffer_base = ptr;
icculus@10851
  1099
        stream->work_buffer_len = newlen;
icculus@10851
  1100
    }
icculus@10851
  1101
icculus@10851
  1102
    offset = ((size_t) ptr) & 15;
icculus@10851
  1103
    return offset ? ptr + (16 - offset) : ptr;
icculus@10851
  1104
}
icculus@10851
  1105
slouken@10777
  1106
#ifdef HAVE_LIBSAMPLERATE_H
slouken@10773
  1107
static int
icculus@10842
  1108
SDL_ResampleAudioStream_SRC(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
slouken@10773
  1109
{
icculus@10842
  1110
    const float *inbuf = (const float *) _inbuf;
icculus@10842
  1111
    float *outbuf = (float *) _outbuf;
icculus@10799
  1112
    const int framelen = sizeof(float) * stream->pre_resample_channels;
icculus@10790
  1113
    SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
slouken@10773
  1114
    SRC_DATA data;
slouken@10773
  1115
    int result;
slouken@10773
  1116
icculus@10851
  1117
    if (inbuf == ((const float *) outbuf)) {  /* libsamplerate can't work in-place. */
icculus@10851
  1118
        Uint8 *ptr = EnsureStreamBufferSize(stream, inbuflen + outbuflen);
icculus@10851
  1119
        if (ptr == NULL) {
icculus@10851
  1120
            SDL_OutOfMemory();
icculus@10851
  1121
            return 0;
icculus@10851
  1122
        }
icculus@10851
  1123
        SDL_memcpy(ptr + outbuflen, ptr, inbuflen);
icculus@10851
  1124
        inbuf = (const float *) (ptr + outbuflen);
icculus@10851
  1125
        outbuf = (float *) ptr;
icculus@10851
  1126
    }
icculus@10851
  1127
slouken@10777
  1128
    data.data_in = (float *)inbuf; /* Older versions of libsamplerate had a non-const pointer, but didn't write to it */
icculus@10799
  1129
    data.input_frames = inbuflen / framelen;
slouken@10773
  1130
    data.input_frames_used = 0;
slouken@10773
  1131
slouken@10773
  1132
    data.data_out = outbuf;
icculus@10799
  1133
    data.output_frames = outbuflen / framelen;
slouken@10773
  1134
slouken@10773
  1135
    data.end_of_input = 0;
slouken@10773
  1136
    data.src_ratio = stream->rate_incr;
slouken@10773
  1137
icculus@10790
  1138
    result = SRC_src_process(state, &data);
slouken@10773
  1139
    if (result != 0) {
icculus@10790
  1140
        SDL_SetError("src_process() failed: %s", SRC_src_strerror(result));
slouken@10773
  1141
        return 0;
slouken@10773
  1142
    }
slouken@10773
  1143
slouken@10773
  1144
    /* If this fails, we need to store them off somewhere */
slouken@10773
  1145
    SDL_assert(data.input_frames_used == data.input_frames);
slouken@10773
  1146
slouken@10773
  1147
    return data.output_frames_gen * (sizeof(float) * stream->pre_resample_channels);
slouken@10773
  1148
}
slouken@10773
  1149
slouken@10773
  1150
static void
slouken@10773
  1151
SDL_ResetAudioStreamResampler_SRC(SDL_AudioStream *stream)
slouken@10773
  1152
{
icculus@10790
  1153
    SRC_src_reset((SRC_STATE *)stream->resampler_state);
slouken@10773
  1154
}
slouken@10773
  1155
slouken@10773
  1156
static void
slouken@10773
  1157
SDL_CleanupAudioStreamResampler_SRC(SDL_AudioStream *stream)
slouken@10773
  1158
{
icculus@10790
  1159
    SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
slouken@10773
  1160
    if (state) {
icculus@10790
  1161
        SRC_src_delete(state);
slouken@10773
  1162
    }
slouken@10773
  1163
slouken@10773
  1164
    stream->resampler_state = NULL;
slouken@10773
  1165
    stream->resampler_func = NULL;
slouken@10773
  1166
    stream->reset_resampler_func = NULL;
slouken@10773
  1167
    stream->cleanup_resampler_func = NULL;
slouken@10773
  1168
}
slouken@10773
  1169
slouken@10773
  1170
static SDL_bool
slouken@10773
  1171
SetupLibSampleRateResampling(SDL_AudioStream *stream)
slouken@10773
  1172
{
icculus@10790
  1173
    int result = 0;
icculus@10790
  1174
    SRC_STATE *state = NULL;
slouken@10773
  1175
icculus@10790
  1176
    if (SRC_available) {
icculus@10849
  1177
        state = SRC_src_new(SRC_converter, stream->pre_resample_channels, &result);
icculus@10790
  1178
        if (!state) {
icculus@10790
  1179
            SDL_SetError("src_new() failed: %s", SRC_src_strerror(result));
icculus@10790
  1180
        }
slouken@10773
  1181
    }
slouken@10773
  1182
icculus@10790
  1183
    if (!state) {
icculus@10790
  1184
        SDL_CleanupAudioStreamResampler_SRC(stream);
slouken@10773
  1185
        return SDL_FALSE;
slouken@10773
  1186
    }
slouken@10773
  1187
slouken@10773
  1188
    stream->resampler_state = state;
slouken@10773
  1189
    stream->resampler_func = SDL_ResampleAudioStream_SRC;
slouken@10773
  1190
    stream->reset_resampler_func = SDL_ResetAudioStreamResampler_SRC;
slouken@10773
  1191
    stream->cleanup_resampler_func = SDL_CleanupAudioStreamResampler_SRC;
slouken@10773
  1192
slouken@10773
  1193
    return SDL_TRUE;
slouken@10773
  1194
}
icculus@10790
  1195
#endif /* HAVE_LIBSAMPLERATE_H */
slouken@10773
  1196
slouken@10773
  1197
slouken@10773
  1198
typedef struct
slouken@10773
  1199
{
icculus@10757
  1200
    SDL_bool resampler_seeded;
icculus@10842
  1201
    union
icculus@10842
  1202
    {
icculus@10842
  1203
        float f[8];
icculus@10842
  1204
        Sint16 si16[2];
icculus@10842
  1205
    } resampler_state;
slouken@10773
  1206
} SDL_AudioStreamResamplerState;
slouken@10773
  1207
slouken@10773
  1208
static int
icculus@10842
  1209
SDL_ResampleAudioStream(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
slouken@10773
  1210
{
icculus@10842
  1211
    const float *inbuf = (const float *) _inbuf;
icculus@10842
  1212
    float *outbuf = (float *) _outbuf;
slouken@10773
  1213
    SDL_AudioStreamResamplerState *state = (SDL_AudioStreamResamplerState*)stream->resampler_state;
slouken@10773
  1214
    const int chans = (int)stream->pre_resample_channels;
slouken@10773
  1215
icculus@10842
  1216
    SDL_assert(chans <= SDL_arraysize(state->resampler_state.f));
slouken@10773
  1217
icculus@11508
  1218
    if (inbuf == ((const float *) outbuf)) {  /* !!! FIXME can't work in-place (for now!). */
icculus@11508
  1219
        Uint8 *ptr = EnsureStreamBufferSize(stream, inbuflen + outbuflen);
icculus@11508
  1220
        if (ptr == NULL) {
icculus@11508
  1221
            SDL_OutOfMemory();
icculus@11508
  1222
            return 0;
icculus@11508
  1223
        }
icculus@11508
  1224
        SDL_memcpy(ptr + outbuflen, ptr, inbuflen);
icculus@11508
  1225
        inbuf = (const float *) (ptr + outbuflen);
icculus@11508
  1226
        outbuf = (float *) ptr;
icculus@11508
  1227
    }
icculus@11508
  1228
slouken@10773
  1229
    if (!state->resampler_seeded) {
icculus@11508
  1230
        SDL_zero(state->resampler_state.f);
slouken@10773
  1231
        state->resampler_seeded = SDL_TRUE;
slouken@10773
  1232
    }
slouken@10773
  1233
icculus@11508
  1234
    return SDL_ResampleAudio(chans, stream->src_rate, stream->dst_rate, state->resampler_state.f, inbuf, inbuflen, outbuf, outbuflen);
slouken@10773
  1235
}
slouken@10773
  1236
slouken@10773
  1237
static void
slouken@10773
  1238
SDL_ResetAudioStreamResampler(SDL_AudioStream *stream)
slouken@10773
  1239
{
slouken@10773
  1240
    SDL_AudioStreamResamplerState *state = (SDL_AudioStreamResamplerState*)stream->resampler_state;
slouken@10773
  1241
    state->resampler_seeded = SDL_FALSE;
slouken@10773
  1242
}
slouken@10773
  1243
slouken@10773
  1244
static void
slouken@10773
  1245
SDL_CleanupAudioStreamResampler(SDL_AudioStream *stream)
slouken@10773
  1246
{
slouken@10773
  1247
    SDL_free(stream->resampler_state);
slouken@10773
  1248
}
icculus@10757
  1249
icculus@10789
  1250
SDL_AudioStream *
icculus@10789
  1251
SDL_NewAudioStream(const SDL_AudioFormat src_format,
icculus@10789
  1252
                   const Uint8 src_channels,
icculus@10789
  1253
                   const int src_rate,
icculus@10789
  1254
                   const SDL_AudioFormat dst_format,
icculus@10789
  1255
                   const Uint8 dst_channels,
icculus@10789
  1256
                   const int dst_rate)
icculus@10757
  1257
{
icculus@10757
  1258
    const int packetlen = 4096;  /* !!! FIXME: good enough for now. */
icculus@10757
  1259
    Uint8 pre_resample_channels;
icculus@10757
  1260
    SDL_AudioStream *retval;
icculus@10757
  1261
icculus@10757
  1262
    retval = (SDL_AudioStream *) SDL_calloc(1, sizeof (SDL_AudioStream));
icculus@10757
  1263
    if (!retval) {
icculus@10757
  1264
        return NULL;
icculus@10757
  1265
    }
icculus@10757
  1266
icculus@10757
  1267
    /* If increasing channels, do it after resampling, since we'd just
icculus@10757
  1268
       do more work to resample duplicate channels. If we're decreasing, do
icculus@10757
  1269
       it first so we resample the interpolated data instead of interpolating
icculus@10757
  1270
       the resampled data (!!! FIXME: decide if that works in practice, though!). */
icculus@10757
  1271
    pre_resample_channels = SDL_min(src_channels, dst_channels);
icculus@10757
  1272
icculus@10883
  1273
    retval->src_sample_frame_size = (SDL_AUDIO_BITSIZE(src_format) / 8) * src_channels;
icculus@10757
  1274
    retval->src_format = src_format;
icculus@10757
  1275
    retval->src_channels = src_channels;
icculus@10757
  1276
    retval->src_rate = src_rate;
icculus@10883
  1277
    retval->dst_sample_frame_size = (SDL_AUDIO_BITSIZE(dst_format) / 8) * dst_channels;
icculus@10757
  1278
    retval->dst_format = dst_format;
icculus@10757
  1279
    retval->dst_channels = dst_channels;
icculus@10757
  1280
    retval->dst_rate = dst_rate;
icculus@10757
  1281
    retval->pre_resample_channels = pre_resample_channels;
icculus@10757
  1282
    retval->packetlen = packetlen;
icculus@10757
  1283
    retval->rate_incr = ((double) dst_rate) / ((double) src_rate);
icculus@10757
  1284
icculus@10757
  1285
    /* Not resampling? It's an easy conversion (and maybe not even that!). */
icculus@10757
  1286
    if (src_rate == dst_rate) {
icculus@10757
  1287
        retval->cvt_before_resampling.needed = SDL_FALSE;
slouken@10773
  1288
        if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, src_format, src_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) {
slouken@10773
  1289
            SDL_FreeAudioStream(retval);
icculus@10757
  1290
            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
icculus@10757
  1291
        }
icculus@10757
  1292
    } else {
icculus@10757
  1293
        /* Don't resample at first. Just get us to Float32 format. */
icculus@10757
  1294
        /* !!! FIXME: convert to int32 on devices without hardware float. */
slouken@10773
  1295
        if (SDL_BuildAudioCVT(&retval->cvt_before_resampling, src_format, src_channels, src_rate, AUDIO_F32SYS, pre_resample_channels, src_rate) < 0) {
slouken@10773
  1296
            SDL_FreeAudioStream(retval);
icculus@10757
  1297
            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
icculus@10757
  1298
        }
icculus@10757
  1299
slouken@10777
  1300
#ifdef HAVE_LIBSAMPLERATE_H
slouken@10773
  1301
        SetupLibSampleRateResampling(retval);
slouken@10773
  1302
#endif
slouken@10773
  1303
slouken@10773
  1304
        if (!retval->resampler_func) {
slouken@10773
  1305
            retval->resampler_state = SDL_calloc(1, sizeof(SDL_AudioStreamResamplerState));
slouken@10773
  1306
            if (!retval->resampler_state) {
slouken@10773
  1307
                SDL_FreeAudioStream(retval);
slouken@10773
  1308
                SDL_OutOfMemory();
slouken@10773
  1309
                return NULL;
slouken@10773
  1310
            }
icculus@11508
  1311
icculus@11508
  1312
            if (SDL_PrepareResampleFilter() < 0) {
icculus@11508
  1313
                SDL_free(retval->resampler_state);
icculus@11508
  1314
                retval->resampler_state = NULL;
icculus@11508
  1315
                SDL_FreeAudioStream(retval);
icculus@11508
  1316
                return NULL;
icculus@11508
  1317
            }
icculus@11508
  1318
slouken@10773
  1319
            retval->resampler_func = SDL_ResampleAudioStream;
slouken@10773
  1320
            retval->reset_resampler_func = SDL_ResetAudioStreamResampler;
slouken@10773
  1321
            retval->cleanup_resampler_func = SDL_CleanupAudioStreamResampler;
slouken@10773
  1322
        }
slouken@10773
  1323
icculus@10757
  1324
        /* Convert us to the final format after resampling. */
slouken@10773
  1325
        if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, AUDIO_F32SYS, pre_resample_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) {
slouken@10773
  1326
            SDL_FreeAudioStream(retval);
icculus@10757
  1327
            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
icculus@10757
  1328
        }
icculus@10757
  1329
    }
icculus@10757
  1330
icculus@10757
  1331
    retval->queue = SDL_NewDataQueue(packetlen, packetlen * 2);
icculus@10757
  1332
    if (!retval->queue) {
slouken@10773
  1333
        SDL_FreeAudioStream(retval);
icculus@10757
  1334
        return NULL;  /* SDL_NewDataQueue should have called SDL_SetError. */
icculus@10757
  1335
    }
icculus@10757
  1336
icculus@10757
  1337
    return retval;
icculus@10757
  1338
}
icculus@10757
  1339
icculus@10757
  1340
int
icculus@10757
  1341
SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, const Uint32 _buflen)
icculus@10757
  1342
{
icculus@10757
  1343
    int buflen = (int) _buflen;
icculus@10846
  1344
    const void *origbuf = buf;
icculus@10757
  1345
icculus@10844
  1346
    /* !!! FIXME: several converters can take advantage of SIMD, but only
icculus@10844
  1347
       !!! FIXME:  if the data is aligned to 16 bytes. EnsureStreamBufferSize()
icculus@10844
  1348
       !!! FIXME:  guarantees the buffer will align, but the
icculus@10844
  1349
       !!! FIXME:  converters will iterate over the data backwards if
icculus@10844
  1350
       !!! FIXME:  the output grows, and this means we won't align if buflen
icculus@10844
  1351
       !!! FIXME:  isn't a multiple of 16. In these cases, we should chop off
icculus@10844
  1352
       !!! FIXME:  a few samples at the end and convert them separately. */
icculus@10844
  1353
icculus@10757
  1354
    if (!stream) {
icculus@10757
  1355
        return SDL_InvalidParamError("stream");
icculus@10757
  1356
    } else if (!buf) {
icculus@10757
  1357
        return SDL_InvalidParamError("buf");
icculus@10757
  1358
    } else if (buflen == 0) {
icculus@10757
  1359
        return 0;  /* nothing to do. */
icculus@10757
  1360
    } else if ((buflen % stream->src_sample_frame_size) != 0) {
icculus@10757
  1361
        return SDL_SetError("Can't add partial sample frames");
icculus@10757
  1362
    }
icculus@10757
  1363
icculus@10757
  1364
    if (stream->cvt_before_resampling.needed) {
icculus@10757
  1365
        const int workbuflen = buflen * stream->cvt_before_resampling.len_mult;  /* will be "* 1" if not needed */
icculus@10844
  1366
        Uint8 *workbuf = EnsureStreamBufferSize(stream, workbuflen);
icculus@10757
  1367
        if (workbuf == NULL) {
icculus@10757
  1368
            return -1;  /* probably out of memory. */
icculus@10757
  1369
        }
icculus@10846
  1370
        SDL_assert(buf == origbuf);
icculus@10757
  1371
        SDL_memcpy(workbuf, buf, buflen);
icculus@10757
  1372
        stream->cvt_before_resampling.buf = workbuf;
icculus@10757
  1373
        stream->cvt_before_resampling.len = buflen;
icculus@10757
  1374
        if (SDL_ConvertAudio(&stream->cvt_before_resampling) == -1) {
icculus@10757
  1375
            return -1;   /* uhoh! */
icculus@10757
  1376
        }
icculus@10757
  1377
        buf = workbuf;
icculus@10757
  1378
        buflen = stream->cvt_before_resampling.len_cvt;
icculus@10757
  1379
    }
icculus@10757
  1380
icculus@10757
  1381
    if (stream->dst_rate != stream->src_rate) {
icculus@10757
  1382
        const int workbuflen = buflen * ((int) SDL_ceil(stream->rate_incr));
icculus@10844
  1383
        Uint8 *workbuf = EnsureStreamBufferSize(stream, workbuflen);
icculus@10757
  1384
        if (workbuf == NULL) {
icculus@10757
  1385
            return -1;  /* probably out of memory. */
icculus@10757
  1386
        }
icculus@10851
  1387
        /* don't SDL_memcpy(workbuf, buf, buflen) here; our resampler can work inplace or not,
icculus@10851
  1388
           libsamplerate needs buffers to be separate; either way, avoid a copy here if possible. */
icculus@10851
  1389
        if (buf != origbuf) {
icculus@10851
  1390
            buf = workbuf;  /* in case we realloc()'d the pointer. */
icculus@10843
  1391
        }
icculus@10851
  1392
        buflen = stream->resampler_func(stream, buf, buflen, workbuf, workbuflen);
icculus@10851
  1393
        buf = EnsureStreamBufferSize(stream, workbuflen);
icculus@10851
  1394
        SDL_assert(buf != NULL);  /* shouldn't be growing, just aligning. */
icculus@10757
  1395
    }
icculus@10757
  1396
icculus@10757
  1397
    if (stream->cvt_after_resampling.needed) {
icculus@10842
  1398
        const int workbuflen = buflen * stream->cvt_after_resampling.len_mult;  /* will be "* 1" if not needed */
icculus@10844
  1399
        Uint8 *workbuf = EnsureStreamBufferSize(stream, workbuflen);
icculus@10757
  1400
        if (workbuf == NULL) {
icculus@10757
  1401
            return -1;  /* probably out of memory. */
icculus@10757
  1402
        }
icculus@10846
  1403
        if (buf == origbuf) {  /* copy if we haven't before. */
icculus@11128
  1404
            SDL_memcpy(workbuf, origbuf, buflen);
icculus@10843
  1405
        }
icculus@10757
  1406
        stream->cvt_after_resampling.buf = workbuf;
icculus@10757
  1407
        stream->cvt_after_resampling.len = buflen;
icculus@10757
  1408
        if (SDL_ConvertAudio(&stream->cvt_after_resampling) == -1) {
icculus@10757
  1409
            return -1;   /* uhoh! */
icculus@10757
  1410
        }
icculus@10757
  1411
        buf = workbuf;
icculus@10757
  1412
        buflen = stream->cvt_after_resampling.len_cvt;
icculus@10757
  1413
    }
icculus@10757
  1414
icculus@10757
  1415
    return SDL_WriteToDataQueue(stream->queue, buf, buflen);
icculus@10757
  1416
}
icculus@10757
  1417
icculus@10757
  1418
void
icculus@10757
  1419
SDL_AudioStreamClear(SDL_AudioStream *stream)
icculus@10757
  1420
{
icculus@10757
  1421
    if (!stream) {
icculus@10757
  1422
        SDL_InvalidParamError("stream");
icculus@10757
  1423
    } else {
icculus@10757
  1424
        SDL_ClearDataQueue(stream->queue, stream->packetlen * 2);
icculus@10776
  1425
        if (stream->reset_resampler_func) {
icculus@10776
  1426
            stream->reset_resampler_func(stream);
icculus@10776
  1427
        }
icculus@10757
  1428
    }
icculus@10757
  1429
}
icculus@10757
  1430
icculus@10757
  1431
icculus@10757
  1432
/* get converted/resampled data from the stream */
icculus@10757
  1433
int
icculus@10764
  1434
SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, const Uint32 len)
icculus@10757
  1435
{
icculus@10757
  1436
    if (!stream) {
icculus@10757
  1437
        return SDL_InvalidParamError("stream");
icculus@10757
  1438
    } else if (!buf) {
icculus@10757
  1439
        return SDL_InvalidParamError("buf");
icculus@10757
  1440
    } else if (len == 0) {
icculus@10757
  1441
        return 0;  /* nothing to do. */
icculus@10757
  1442
    } else if ((len % stream->dst_sample_frame_size) != 0) {
icculus@10757
  1443
        return SDL_SetError("Can't request partial sample frames");
icculus@10757
  1444
    }
icculus@10757
  1445
icculus@10764
  1446
    return (int) SDL_ReadFromDataQueue(stream->queue, buf, len);
icculus@10757
  1447
}
icculus@10757
  1448
icculus@10757
  1449
/* number of converted/resampled bytes available */
icculus@10757
  1450
int
icculus@10757
  1451
SDL_AudioStreamAvailable(SDL_AudioStream *stream)
icculus@10757
  1452
{
icculus@10757
  1453
    return stream ? (int) SDL_CountDataQueue(stream->queue) : 0;
icculus@10757
  1454
}
icculus@10757
  1455
icculus@10757
  1456
/* dispose of a stream */
icculus@10757
  1457
void
icculus@10757
  1458
SDL_FreeAudioStream(SDL_AudioStream *stream)
icculus@10757
  1459
{
icculus@10757
  1460
    if (stream) {
slouken@10773
  1461
        if (stream->cleanup_resampler_func) {
slouken@10773
  1462
            stream->cleanup_resampler_func(stream);
slouken@10773
  1463
        }
icculus@10757
  1464
        SDL_FreeDataQueue(stream->queue);
icculus@10844
  1465
        SDL_free(stream->work_buffer_base);
icculus@10757
  1466
        SDL_free(stream);
icculus@10757
  1467
    }
icculus@10757
  1468
}
icculus@10757
  1469
icculus@10575
  1470
/* vi: set ts=4 sw=4 expandtab: */
slouken@2716
  1471