src/audio/SDL_audiocvt.c
author Sam Lantinga <slouken@libsdl.org>
Fri, 22 Sep 2017 08:51:45 -0700
changeset 11519 535b0c8ba4ce
parent 11517 beb96c015b30
child 11541 433786fcf04a
permissions -rw-r--r--
Fixed memory leak when HAVE_ALLOCA isn't defined
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@11517
   467
static int
icculus@11517
   468
ResamplerPadding(const int inrate, const int outrate)
icculus@11517
   469
{
icculus@11517
   470
    return (inrate > outrate) ? (int) SDL_ceil(((float) (RESAMPLER_SAMPLES_PER_ZERO_CROSSING * inrate) / ((float) outrate))) : RESAMPLER_SAMPLES_PER_ZERO_CROSSING;
icculus@11517
   471
}
icculus@11405
   472
icculus@11517
   473
/* lpadding and rpadding are expected to be buffers of (ResamplePadding(inrate, outrate) * chans * sizeof (float)) bytes. */
icculus@10799
   474
static int
icculus@11508
   475
SDL_ResampleAudio(const int chans, const int inrate, const int outrate,
icculus@11517
   476
                        float *lpadding, float *rpadding, const float *inbuf,
icculus@10799
   477
                        const int inbuflen, float *outbuf, const int outbuflen)
icculus@10799
   478
{
icculus@11508
   479
    const float outtimeincr = 1.0f / ((float) outrate);
icculus@11508
   480
    const float ratio = ((float) outrate) / ((float) inrate);
icculus@11517
   481
    const int paddinglen = ResamplerPadding(inrate, outrate);
icculus@10817
   482
    const int framelen = chans * (int)sizeof (float);
icculus@11508
   483
    const int inframes = inbuflen / framelen;
icculus@11508
   484
    const int wantedoutframes = (int) ((inbuflen / framelen) * ratio);  /* outbuflen isn't total to write, it's total available. */
icculus@11508
   485
    const int maxoutframes = outbuflen / framelen;
icculus@11508
   486
    const int outframes = (wantedoutframes < maxoutframes) ? wantedoutframes : maxoutframes;
icculus@11508
   487
    float *dst = outbuf;
icculus@11508
   488
    float outtime = 0.0f;
icculus@11508
   489
    int i, j, chan;
icculus@10799
   490
icculus@11508
   491
    for (i = 0; i < outframes; i++) {
icculus@11508
   492
        const int srcindex = (int) (outtime * inrate);
icculus@11508
   493
        const float finrate = (float) inrate;
icculus@11508
   494
        const float intime = ((float) srcindex) / finrate;
icculus@11508
   495
        const float innexttime = ((float) (srcindex + 1)) / finrate;
icculus@10799
   496
icculus@11508
   497
        const float interpolation1 = 1.0f - (innexttime - outtime) / (innexttime - intime);
icculus@11508
   498
        const int filterindex1 = (int) (interpolation1 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING);
icculus@11508
   499
        const float interpolation2 = 1.0f - interpolation1;
icculus@11508
   500
        const int filterindex2 = interpolation2 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING;
icculus@10833
   501
icculus@11508
   502
        for (chan = 0; chan < chans; chan++) {
icculus@11508
   503
            float outsample = 0.0f;
icculus@11508
   504
icculus@11508
   505
            /* do this twice to calculate the sample, once for the "left wing" and then same for the right. */
icculus@11508
   506
            /* !!! FIXME: do both wings in one loop */
icculus@11508
   507
            for (j = 0; (filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) {
icculus@11508
   508
                const int srcframe = srcindex - j;
icculus@11517
   509
                /* !!! FIXME: we can bubble this conditional out of here by doing a pre loop. */
icculus@11517
   510
                const float insample = (srcframe < 0) ? lpadding[((paddinglen + srcframe) * chans) + chan] : inbuf[(srcframe * chans) + chan];
icculus@11508
   511
                outsample += (insample * (ResamplerFilter[filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)] + (interpolation1 * ResamplerFilterDifference[filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)])));
icculus@10840
   512
            }
icculus@11508
   513
icculus@11508
   514
            for (j = 0; (filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) {
icculus@11508
   515
                const int srcframe = srcindex + 1 + j;
icculus@11517
   516
                /* !!! FIXME: we can bubble this conditional out of here by doing a post loop. */
icculus@11517
   517
                const float insample = (srcframe >= inframes) ? rpadding[((srcframe - inframes) * chans) + chan] : inbuf[(srcframe * chans) + chan];
icculus@11508
   518
                outsample += (insample * (ResamplerFilter[filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)] + (interpolation2 * ResamplerFilterDifference[filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)])));
icculus@10840
   519
            }
icculus@11508
   520
            *(dst++) = outsample;
icculus@10799
   521
        }
icculus@10833
   522
icculus@11508
   523
        outtime += outtimeincr;
icculus@10799
   524
    }
icculus@10799
   525
icculus@11508
   526
    return outframes * chans * sizeof (float);
icculus@10799
   527
}
icculus@10799
   528
slouken@1895
   529
int
slouken@1895
   530
SDL_ConvertAudio(SDL_AudioCVT * cvt)
slouken@0
   531
{
icculus@3021
   532
    /* !!! FIXME: (cvt) should be const; stack-copy it here. */
icculus@3021
   533
    /* !!! FIXME: (actually, we can't...len_cvt needs to be updated. Grr.) */
icculus@3021
   534
slouken@1895
   535
    /* Make sure there's data to convert */
slouken@1895
   536
    if (cvt->buf == NULL) {
icculus@10575
   537
        return SDL_SetError("No buffer allocated for conversion");
slouken@1895
   538
    }
icculus@10575
   539
slouken@1895
   540
    /* Return okay if no conversion is necessary */
slouken@1895
   541
    cvt->len_cvt = cvt->len;
slouken@1895
   542
    if (cvt->filters[0] == NULL) {
icculus@10575
   543
        return 0;
slouken@1895
   544
    }
slouken@0
   545
slouken@1895
   546
    /* Set up the conversion and go! */
slouken@1895
   547
    cvt->filter_index = 0;
slouken@1895
   548
    cvt->filters[0] (cvt, cvt->src_format);
icculus@10575
   549
    return 0;
slouken@0
   550
}
slouken@0
   551
icculus@10575
   552
static void SDLCALL
icculus@10575
   553
SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format)
icculus@10575
   554
{
slouken@10579
   555
#if DEBUG_CONVERT
slouken@10579
   556
    printf("Converting byte order\n");
slouken@10579
   557
#endif
icculus@1982
   558
icculus@10575
   559
    switch (SDL_AUDIO_BITSIZE(format)) {
icculus@10575
   560
        #define CASESWAP(b) \
icculus@10575
   561
            case b: { \
icculus@10575
   562
                Uint##b *ptr = (Uint##b *) cvt->buf; \
icculus@10575
   563
                int i; \
icculus@10575
   564
                for (i = cvt->len_cvt / sizeof (*ptr); i; --i, ++ptr) { \
icculus@10575
   565
                    *ptr = SDL_Swap##b(*ptr); \
icculus@10575
   566
                } \
icculus@10575
   567
                break; \
icculus@10575
   568
            }
icculus@1982
   569
icculus@10575
   570
        CASESWAP(16);
icculus@10575
   571
        CASESWAP(32);
icculus@10575
   572
        CASESWAP(64);
icculus@10575
   573
icculus@10575
   574
        #undef CASESWAP
icculus@10575
   575
icculus@10575
   576
        default: SDL_assert(!"unhandled byteswap datatype!"); break;
icculus@10575
   577
    }
icculus@10575
   578
icculus@10575
   579
    if (cvt->filters[++cvt->filter_index]) {
icculus@10575
   580
        /* flip endian flag for data. */
icculus@10575
   581
        if (format & SDL_AUDIO_MASK_ENDIAN) {
icculus@10575
   582
            format &= ~SDL_AUDIO_MASK_ENDIAN;
icculus@10575
   583
        } else {
icculus@10575
   584
            format |= SDL_AUDIO_MASK_ENDIAN;
icculus@10575
   585
        }
icculus@10575
   586
        cvt->filters[cvt->filter_index](cvt, format);
icculus@10575
   587
    }
icculus@1982
   588
}
icculus@1982
   589
slouken@11096
   590
static int
slouken@11096
   591
SDL_AddAudioCVTFilter(SDL_AudioCVT *cvt, const SDL_AudioFilter filter)
slouken@11096
   592
{
slouken@11096
   593
    if (cvt->filter_index >= SDL_AUDIOCVT_MAX_FILTERS) {
slouken@11096
   594
        return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS);
slouken@11096
   595
    }
slouken@11096
   596
    if (filter == NULL) {
slouken@11096
   597
        return SDL_SetError("Audio filter pointer is NULL");
slouken@11096
   598
    }
slouken@11096
   599
    cvt->filters[cvt->filter_index++] = filter;
slouken@11096
   600
    cvt->filters[cvt->filter_index] = NULL; /* Moving terminator */
slouken@11096
   601
    return 0;
slouken@11096
   602
}
icculus@1982
   603
icculus@1982
   604
static int
icculus@10575
   605
SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt)
icculus@1982
   606
{
icculus@10575
   607
    int retval = 0;  /* 0 == no conversion necessary. */
icculus@1982
   608
icculus@10575
   609
    if ((SDL_AUDIO_ISBIGENDIAN(src_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) {
slouken@11096
   610
        if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
slouken@11096
   611
            return -1;
slouken@11096
   612
        }
icculus@10575
   613
        retval = 1;  /* added a converter. */
icculus@10575
   614
    }
icculus@1982
   615
icculus@10575
   616
    if (!SDL_AUDIO_ISFLOAT(src_fmt)) {
icculus@10576
   617
        const Uint16 src_bitsize = SDL_AUDIO_BITSIZE(src_fmt);
icculus@10576
   618
        const Uint16 dst_bitsize = 32;
icculus@10575
   619
        SDL_AudioFilter filter = NULL;
icculus@10576
   620
icculus@10575
   621
        switch (src_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
icculus@10575
   622
            case AUDIO_S8: filter = SDL_Convert_S8_to_F32; break;
icculus@10575
   623
            case AUDIO_U8: filter = SDL_Convert_U8_to_F32; break;
icculus@10575
   624
            case AUDIO_S16: filter = SDL_Convert_S16_to_F32; break;
philipp@10591
   625
            case AUDIO_U16: filter = SDL_Convert_U16_to_F32; break;
icculus@10575
   626
            case AUDIO_S32: filter = SDL_Convert_S32_to_F32; break;
icculus@10575
   627
            default: SDL_assert(!"Unexpected audio format!"); break;
icculus@1982
   628
        }
icculus@1982
   629
icculus@10575
   630
        if (!filter) {
icculus@11319
   631
            return SDL_SetError("No conversion from source format to float available");
icculus@10575
   632
        }
icculus@10575
   633
slouken@11096
   634
        if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
slouken@11096
   635
            return -1;
slouken@11096
   636
        }
icculus@1982
   637
        if (src_bitsize < dst_bitsize) {
icculus@1982
   638
            const int mult = (dst_bitsize / src_bitsize);
icculus@1982
   639
            cvt->len_mult *= mult;
icculus@1982
   640
            cvt->len_ratio *= mult;
icculus@1982
   641
        } else if (src_bitsize > dst_bitsize) {
icculus@1982
   642
            cvt->len_ratio /= (src_bitsize / dst_bitsize);
icculus@1982
   643
        }
icculus@10576
   644
icculus@10575
   645
        retval = 1;  /* added a converter. */
icculus@1982
   646
    }
icculus@1982
   647
icculus@10575
   648
    return retval;
icculus@1982
   649
}
icculus@1982
   650
icculus@10575
   651
static int
icculus@10575
   652
SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt)
icculus@10575
   653
{
icculus@10575
   654
    int retval = 0;  /* 0 == no conversion necessary. */
icculus@3021
   655
icculus@10575
   656
    if (!SDL_AUDIO_ISFLOAT(dst_fmt)) {
icculus@10577
   657
        const Uint16 dst_bitsize = SDL_AUDIO_BITSIZE(dst_fmt);
icculus@10577
   658
        const Uint16 src_bitsize = 32;
icculus@10575
   659
        SDL_AudioFilter filter = NULL;
icculus@10575
   660
        switch (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
icculus@10575
   661
            case AUDIO_S8: filter = SDL_Convert_F32_to_S8; break;
icculus@10575
   662
            case AUDIO_U8: filter = SDL_Convert_F32_to_U8; break;
icculus@10575
   663
            case AUDIO_S16: filter = SDL_Convert_F32_to_S16; break;
philipp@10591
   664
            case AUDIO_U16: filter = SDL_Convert_F32_to_U16; break;
icculus@10575
   665
            case AUDIO_S32: filter = SDL_Convert_F32_to_S32; break;
icculus@10575
   666
            default: SDL_assert(!"Unexpected audio format!"); break;
icculus@10575
   667
        }
slouken@2716
   668
icculus@10575
   669
        if (!filter) {
icculus@11319
   670
            return SDL_SetError("No conversion from float to destination format available");
icculus@10575
   671
        }
icculus@10575
   672
slouken@11096
   673
        if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
slouken@11096
   674
            return -1;
slouken@11096
   675
        }
icculus@10575
   676
        if (src_bitsize < dst_bitsize) {
icculus@10575
   677
            const int mult = (dst_bitsize / src_bitsize);
icculus@10575
   678
            cvt->len_mult *= mult;
icculus@10575
   679
            cvt->len_ratio *= mult;
icculus@10575
   680
        } else if (src_bitsize > dst_bitsize) {
icculus@10575
   681
            cvt->len_ratio /= (src_bitsize / dst_bitsize);
icculus@10575
   682
        }
icculus@10575
   683
        retval = 1;  /* added a converter. */
icculus@10575
   684
    }
icculus@10575
   685
icculus@10575
   686
    if ((SDL_AUDIO_ISBIGENDIAN(dst_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) {
slouken@11096
   687
        if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
slouken@11096
   688
            return -1;
slouken@11096
   689
        }
icculus@10575
   690
        retval = 1;  /* added a converter. */
icculus@10575
   691
    }
icculus@10575
   692
icculus@10575
   693
    return retval;
icculus@3021
   694
}
slouken@2716
   695
icculus@10799
   696
static void
icculus@10799
   697
SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format)
icculus@10799
   698
{
icculus@11508
   699
    /* !!! 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
   700
       !!! 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
   701
       !!! FIXME in 2.1:   so we steal the ninth and tenth slot.  :( */
icculus@11517
   702
    const int inrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1];
icculus@11517
   703
    const int outrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS];
icculus@10799
   704
    const float *src = (const float *) cvt->buf;
icculus@10799
   705
    const int srclen = cvt->len_cvt;
icculus@11508
   706
    /*float *dst = (float *) cvt->buf;
icculus@11508
   707
    const int dstlen = (cvt->len * cvt->len_mult);*/
icculus@11508
   708
    /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
icculus@11508
   709
    float *dst = (float *) (cvt->buf + srclen);
icculus@11508
   710
    const int dstlen = (cvt->len * cvt->len_mult) - srclen;
icculus@11517
   711
    const int paddingsamples = (ResamplerPadding(inrate, outrate) * chans);
slouken@11519
   712
    float *padding;
icculus@10756
   713
icculus@10799
   714
    SDL_assert(format == AUDIO_F32SYS);
icculus@10799
   715
icculus@11517
   716
    /* we keep no streaming state here, so pad with silence on both ends. */
slouken@11519
   717
    padding = SDL_stack_alloc(float, paddingsamples);
slouken@11519
   718
    if (!padding) {
slouken@11519
   719
        SDL_OutOfMemory();
slouken@11519
   720
        return;
slouken@11519
   721
    }
icculus@11517
   722
    SDL_memset(padding, '\0', paddingsamples * sizeof (float));
icculus@10799
   723
icculus@11517
   724
    cvt->len_cvt = SDL_ResampleAudio(chans, inrate, outrate, padding, padding, src, srclen, dst, dstlen);
icculus@11508
   725
slouken@11519
   726
    SDL_stack_free(padding);
slouken@11519
   727
icculus@11508
   728
    SDL_memcpy(cvt->buf, dst, cvt->len_cvt);  /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
icculus@11508
   729
icculus@10799
   730
    if (cvt->filters[++cvt->filter_index]) {
icculus@10799
   731
        cvt->filters[cvt->filter_index](cvt, format);
icculus@10799
   732
    }
icculus@10799
   733
}
icculus@10799
   734
icculus@10799
   735
/* !!! FIXME: We only have this macro salsa because SDL_AudioCVT doesn't
icculus@10799
   736
   !!! FIXME:  store channel info, so we have to have function entry
icculus@10799
   737
   !!! FIXME:  points for each supported channel count and multiple
icculus@10799
   738
   !!! FIXME:  vs arbitrary. When we rev the ABI, clean this up. */
icculus@10756
   739
#define RESAMPLER_FUNCS(chans) \
icculus@10756
   740
    static void SDLCALL \
icculus@10799
   741
    SDL_ResampleCVT_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) { \
icculus@10799
   742
        SDL_ResampleCVT(cvt, chans, format); \
icculus@10756
   743
    }
icculus@10756
   744
RESAMPLER_FUNCS(1)
icculus@10756
   745
RESAMPLER_FUNCS(2)
icculus@10756
   746
RESAMPLER_FUNCS(4)
icculus@10756
   747
RESAMPLER_FUNCS(6)
icculus@10756
   748
RESAMPLER_FUNCS(8)
icculus@10756
   749
#undef RESAMPLER_FUNCS
icculus@10756
   750
icculus@10799
   751
static SDL_AudioFilter
icculus@10799
   752
ChooseCVTResampler(const int dst_channels)
icculus@3021
   753
{
icculus@10799
   754
    switch (dst_channels) {
icculus@10799
   755
        case 1: return SDL_ResampleCVT_c1;
icculus@10799
   756
        case 2: return SDL_ResampleCVT_c2;
icculus@10799
   757
        case 4: return SDL_ResampleCVT_c4;
icculus@10799
   758
        case 6: return SDL_ResampleCVT_c6;
icculus@10799
   759
        case 8: return SDL_ResampleCVT_c8;
icculus@10799
   760
        default: break;
icculus@3021
   761
    }
slouken@2716
   762
icculus@10799
   763
    return NULL;
icculus@10756
   764
}
icculus@10575
   765
icculus@3021
   766
static int
icculus@10756
   767
SDL_BuildAudioResampleCVT(SDL_AudioCVT * cvt, const int dst_channels,
icculus@10756
   768
                          const int src_rate, const int dst_rate)
icculus@3021
   769
{
icculus@10756
   770
    SDL_AudioFilter filter;
icculus@3021
   771
icculus@10756
   772
    if (src_rate == dst_rate) {
icculus@10756
   773
        return 0;  /* no conversion necessary. */
slouken@2716
   774
    }
slouken@2716
   775
icculus@10799
   776
    filter = ChooseCVTResampler(dst_channels);
icculus@10756
   777
    if (filter == NULL) {
icculus@10756
   778
        return SDL_SetError("No conversion available for these rates");
icculus@10756
   779
    }
icculus@10756
   780
icculus@11508
   781
    if (SDL_PrepareResampleFilter() < 0) {
icculus@11508
   782
        return -1;
icculus@11508
   783
    }
icculus@11508
   784
icculus@10756
   785
    /* Update (cvt) with filter details... */
slouken@11096
   786
    if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
slouken@11096
   787
        return -1;
slouken@11096
   788
    }
icculus@11508
   789
icculus@11508
   790
    /* !!! 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
   791
       !!! 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
   792
       !!! FIXME in 2.1:   so we steal the ninth and tenth slot.  :( */
icculus@11508
   793
    if (cvt->filter_index >= (SDL_AUDIOCVT_MAX_FILTERS-2)) {
icculus@11508
   794
        return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS-2);
icculus@11508
   795
    }
icculus@11508
   796
    cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1] = (SDL_AudioFilter) (size_t) src_rate;
icculus@11508
   797
    cvt->filters[SDL_AUDIOCVT_MAX_FILTERS] = (SDL_AudioFilter) (size_t) dst_rate;
icculus@11508
   798
icculus@10756
   799
    if (src_rate < dst_rate) {
icculus@10756
   800
        const double mult = ((double) dst_rate) / ((double) src_rate);
icculus@10756
   801
        cvt->len_mult *= (int) SDL_ceil(mult);
icculus@10756
   802
        cvt->len_ratio *= mult;
icculus@10756
   803
    } else {
icculus@10756
   804
        cvt->len_ratio /= ((double) src_rate) / ((double) dst_rate);
icculus@10756
   805
    }
icculus@10756
   806
icculus@11508
   807
    /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
icculus@11508
   808
    /* the buffer is big enough to hold the destination now, but
icculus@11508
   809
       we need it large enough to hold a separate scratch buffer. */
icculus@11508
   810
    cvt->len_mult *= 2;
icculus@11508
   811
icculus@10756
   812
    return 1;               /* added a converter. */
slouken@2716
   813
}
icculus@1982
   814
icculus@11097
   815
static SDL_bool
icculus@11097
   816
SDL_SupportedAudioFormat(const SDL_AudioFormat fmt)
icculus@11097
   817
{
icculus@11097
   818
    switch (fmt) {
icculus@11097
   819
        case AUDIO_U8:
icculus@11097
   820
        case AUDIO_S8:
icculus@11097
   821
        case AUDIO_U16LSB:
icculus@11097
   822
        case AUDIO_S16LSB:
icculus@11097
   823
        case AUDIO_U16MSB:
icculus@11097
   824
        case AUDIO_S16MSB:
icculus@11097
   825
        case AUDIO_S32LSB:
icculus@11097
   826
        case AUDIO_S32MSB:
icculus@11097
   827
        case AUDIO_F32LSB:
icculus@11097
   828
        case AUDIO_F32MSB:
icculus@11097
   829
            return SDL_TRUE;  /* supported. */
icculus@11097
   830
icculus@11097
   831
        default:
icculus@11097
   832
            break;
icculus@11097
   833
    }
icculus@11097
   834
icculus@11097
   835
    return SDL_FALSE;  /* unsupported. */
icculus@11097
   836
}
icculus@11097
   837
icculus@11097
   838
static SDL_bool
icculus@11097
   839
SDL_SupportedChannelCount(const int channels)
icculus@11097
   840
{
icculus@11097
   841
    switch (channels) {
icculus@11097
   842
        case 1:  /* mono */
icculus@11097
   843
        case 2:  /* stereo */
icculus@11097
   844
        case 4:  /* quad */
icculus@11097
   845
        case 6:  /* 5.1 */
icculus@11405
   846
        case 8:  /* 7.1 */
icculus@11405
   847
          return SDL_TRUE;  /* supported. */
icculus@11097
   848
icculus@11097
   849
        default:
icculus@11097
   850
            break;
icculus@11097
   851
    }
icculus@11097
   852
icculus@11097
   853
    return SDL_FALSE;  /* unsupported. */
icculus@11097
   854
}
icculus@11097
   855
icculus@1982
   856
icculus@1982
   857
/* Creates a set of audio filters to convert from one format to another.
icculus@11319
   858
   Returns 0 if no conversion is needed, 1 if the audio filter is set up,
icculus@11319
   859
   or -1 if an error like invalid parameter, unsupported format, etc. occurred.
slouken@0
   860
*/
slouken@1895
   861
slouken@1895
   862
int
slouken@1895
   863
SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
icculus@1982
   864
                  SDL_AudioFormat src_fmt, Uint8 src_channels, int src_rate,
icculus@1982
   865
                  SDL_AudioFormat dst_fmt, Uint8 dst_channels, int dst_rate)
slouken@0
   866
{
aschiffler@6819
   867
    /* Sanity check target pointer */
aschiffler@6819
   868
    if (cvt == NULL) {
icculus@7037
   869
        return SDL_InvalidParamError("cvt");
aschiffler@6819
   870
    }
slouken@7191
   871
slouken@10767
   872
    /* Make sure we zero out the audio conversion before error checking */
slouken@10767
   873
    SDL_zerop(cvt);
slouken@10767
   874
icculus@11097
   875
    if (!SDL_SupportedAudioFormat(src_fmt)) {
icculus@7037
   876
        return SDL_SetError("Invalid source format");
icculus@11097
   877
    } else if (!SDL_SupportedAudioFormat(dst_fmt)) {
icculus@7037
   878
        return SDL_SetError("Invalid destination format");
icculus@11097
   879
    } else if (!SDL_SupportedChannelCount(src_channels)) {
icculus@11097
   880
        return SDL_SetError("Invalid source channels");
icculus@11097
   881
    } else if (!SDL_SupportedChannelCount(dst_channels)) {
icculus@11097
   882
        return SDL_SetError("Invalid destination channels");
icculus@11097
   883
    } else if (src_rate == 0) {
icculus@11097
   884
        return SDL_SetError("Source rate is zero");
icculus@11097
   885
    } else if (dst_rate == 0) {
icculus@11097
   886
        return SDL_SetError("Destination rate is zero");
icculus@1982
   887
    }
icculus@3021
   888
slouken@10579
   889
#if DEBUG_CONVERT
icculus@1982
   890
    printf("Build format %04x->%04x, channels %u->%u, rate %d->%d\n",
slouken@1985
   891
           src_fmt, dst_fmt, src_channels, dst_channels, src_rate, dst_rate);
slouken@1985
   892
#endif
icculus@1982
   893
slouken@1895
   894
    /* Start off with no conversion necessary */
icculus@1982
   895
    cvt->src_format = src_fmt;
icculus@1982
   896
    cvt->dst_format = dst_fmt;
slouken@1895
   897
    cvt->needed = 0;
slouken@1895
   898
    cvt->filter_index = 0;
icculus@11508
   899
    SDL_zero(cvt->filters);
slouken@1895
   900
    cvt->len_mult = 1;
slouken@1895
   901
    cvt->len_ratio = 1.0;
icculus@3021
   902
    cvt->rate_incr = ((double) dst_rate) / ((double) src_rate);
slouken@0
   903
slouken@11406
   904
    /* Make sure we've chosen audio conversion functions (MMX, scalar, etc.) */
slouken@11406
   905
    SDL_ChooseAudioConverters();
slouken@11406
   906
icculus@10575
   907
    /* Type conversion goes like this now:
icculus@10575
   908
        - byteswap to CPU native format first if necessary.
icculus@10575
   909
        - convert to native Float32 if necessary.
icculus@10575
   910
        - resample and change channel count if necessary.
icculus@10575
   911
        - convert back to native format.
icculus@10575
   912
        - byteswap back to foreign format if necessary.
icculus@10575
   913
icculus@10575
   914
       The expectation is we can process data faster in float32
icculus@10575
   915
       (possibly with SIMD), and making several passes over the same
icculus@10756
   916
       buffer is likely to be CPU cache-friendly, avoiding the
icculus@10575
   917
       biggest performance hit in modern times. Previously we had
icculus@10575
   918
       (script-generated) custom converters for every data type and
icculus@10575
   919
       it was a bloat on SDL compile times and final library size. */
icculus@10575
   920
slouken@10767
   921
    /* see if we can skip float conversion entirely. */
slouken@10767
   922
    if (src_rate == dst_rate && src_channels == dst_channels) {
slouken@10767
   923
        if (src_fmt == dst_fmt) {
slouken@10767
   924
            return 0;
slouken@10767
   925
        }
slouken@10767
   926
slouken@10767
   927
        /* just a byteswap needed? */
slouken@10767
   928
        if ((src_fmt & ~SDL_AUDIO_MASK_ENDIAN) == (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN)) {
slouken@11096
   929
            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
slouken@11096
   930
                return -1;
slouken@11096
   931
            }
slouken@10767
   932
            cvt->needed = 1;
slouken@10767
   933
            return 1;
slouken@10767
   934
        }
icculus@10575
   935
    }
icculus@10575
   936
icculus@1982
   937
    /* Convert data types, if necessary. Updates (cvt). */
slouken@10767
   938
    if (SDL_BuildAudioTypeCVTToFloat(cvt, src_fmt) < 0) {
slouken@1985
   939
        return -1;              /* shouldn't happen, but just in case... */
icculus@3021
   940
    }
slouken@0
   941
icculus@1982
   942
    /* Channel conversion */
icculus@11405
   943
    if (src_channels < dst_channels) {
icculus@11405
   944
        /* Upmixing */
icculus@11405
   945
        /* Mono -> Stereo [-> ...] */
slouken@1895
   946
        if ((src_channels == 1) && (dst_channels > 1)) {
slouken@11096
   947
            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertMonoToStereo) < 0) {
slouken@11096
   948
                return -1;
slouken@11096
   949
            }
slouken@1895
   950
            cvt->len_mult *= 2;
slouken@1895
   951
            src_channels = 2;
slouken@1895
   952
            cvt->len_ratio *= 2;
slouken@1895
   953
        }
icculus@11405
   954
        /* [Mono ->] Stereo -> 5.1 [-> 7.1] */
icculus@11405
   955
        if ((src_channels == 2) && (dst_channels >= 6)) {
slouken@11096
   956
            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertStereoTo51) < 0) {
slouken@11096
   957
                return -1;
slouken@11096
   958
            }
slouken@1895
   959
            src_channels = 6;
slouken@1895
   960
            cvt->len_mult *= 3;
slouken@1895
   961
            cvt->len_ratio *= 3;
slouken@1895
   962
        }
icculus@11405
   963
        /* Quad -> 5.1 [-> 7.1] */
icculus@11405
   964
        if ((src_channels == 4) && (dst_channels >= 6)) {
icculus@11405
   965
            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertQuadTo51) < 0) {
icculus@11405
   966
                return -1;
icculus@11405
   967
            }
icculus@11405
   968
            src_channels = 6;
icculus@11405
   969
            cvt->len_mult = (cvt->len_mult * 3 + 1) / 2;
icculus@11405
   970
            cvt->len_ratio *= 1.5;
icculus@11405
   971
        }
icculus@11405
   972
        /* [[Mono ->] Stereo ->] 5.1 -> 7.1 */
icculus@11405
   973
        if ((src_channels == 6) && (dst_channels == 8)) {
icculus@11405
   974
            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51To71) < 0) {
icculus@11405
   975
                return -1;
icculus@11405
   976
            }
icculus@11405
   977
            src_channels = 8;
icculus@11405
   978
            cvt->len_mult = (cvt->len_mult * 4 + 2) / 3;
icculus@11405
   979
            /* Should be numerically exact with every valid input to this
icculus@11405
   980
               function */
icculus@11405
   981
            cvt->len_ratio = cvt->len_ratio * 4 / 3;
icculus@11405
   982
        }
icculus@11405
   983
        /* [Mono ->] Stereo -> Quad */
slouken@1895
   984
        if ((src_channels == 2) && (dst_channels == 4)) {
slouken@11096
   985
            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertStereoToQuad) < 0) {
slouken@11096
   986
                return -1;
slouken@11096
   987
            }
slouken@1895
   988
            src_channels = 4;
slouken@1895
   989
            cvt->len_mult *= 2;
slouken@1895
   990
            cvt->len_ratio *= 2;
slouken@1895
   991
        }
icculus@11405
   992
    } else if (src_channels > dst_channels) {
icculus@11405
   993
        /* Downmixing */
icculus@11405
   994
        /* 7.1 -> 5.1 [-> Stereo [-> Mono]] */
icculus@11405
   995
        /* 7.1 -> 5.1 [-> Quad] */
icculus@11405
   996
        if ((src_channels == 8) && (dst_channels <= 6)) {
icculus@11405
   997
            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert71To51) < 0) {
slouken@11096
   998
                return -1;
slouken@11096
   999
            }
icculus@11405
  1000
            src_channels = 6;
icculus@11405
  1001
            cvt->len_ratio *= 0.75;
slouken@1895
  1002
        }
icculus@11405
  1003
        /* [7.1 ->] 5.1 -> Stereo [-> Mono] */
slouken@1895
  1004
        if ((src_channels == 6) && (dst_channels <= 2)) {
slouken@11096
  1005
            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51ToStereo) < 0) {
slouken@11096
  1006
                return -1;
slouken@11096
  1007
            }
slouken@1895
  1008
            src_channels = 2;
slouken@1895
  1009
            cvt->len_ratio /= 3;
slouken@1895
  1010
        }
icculus@11405
  1011
        /* 5.1 -> Quad */
slouken@1895
  1012
        if ((src_channels == 6) && (dst_channels == 4)) {
slouken@11096
  1013
            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51ToQuad) < 0) {
slouken@11096
  1014
                return -1;
slouken@11096
  1015
            }
slouken@1895
  1016
            src_channels = 4;
icculus@11405
  1017
            cvt->len_ratio = cvt->len_ratio * 2 / 3;
icculus@11405
  1018
        }
icculus@11405
  1019
        /* Quad -> Stereo [-> Mono] */
icculus@11405
  1020
        if ((src_channels == 4) && (dst_channels <= 2)) {
icculus@11405
  1021
            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertQuadToStereo) < 0) {
icculus@11405
  1022
                return -1;
icculus@11405
  1023
            }
icculus@11405
  1024
            src_channels = 2;
slouken@1895
  1025
            cvt->len_ratio /= 2;
slouken@1895
  1026
        }
icculus@11405
  1027
        /* [... ->] Stereo -> Mono */
icculus@11405
  1028
        if ((src_channels == 2) && (dst_channels == 1)) {
icculus@10832
  1029
            SDL_AudioFilter filter = NULL;
icculus@10832
  1030
icculus@10832
  1031
            #if HAVE_SSE3_INTRINSICS
icculus@10832
  1032
            if (SDL_HasSSE3()) {
icculus@10832
  1033
                filter = SDL_ConvertStereoToMono_SSE3;
icculus@10832
  1034
            }
icculus@10832
  1035
            #endif
icculus@10832
  1036
icculus@10832
  1037
            if (!filter) {
icculus@10832
  1038
                filter = SDL_ConvertStereoToMono;
icculus@10832
  1039
            }
icculus@10832
  1040
slouken@11096
  1041
            if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
slouken@11096
  1042
                return -1;
slouken@11096
  1043
            }
icculus@10832
  1044
icculus@11405
  1045
            src_channels = 1;
slouken@1895
  1046
            cvt->len_ratio /= 2;
slouken@1895
  1047
        }
slouken@1895
  1048
    }
slouken@0
  1049
icculus@11405
  1050
    if (src_channels != dst_channels) {
icculus@11405
  1051
        /* All combinations of supported channel counts should have been
icculus@11405
  1052
           handled by now, but let's be defensive */
icculus@11405
  1053
      return SDL_SetError("Invalid channel combination");
icculus@11405
  1054
    }
icculus@11405
  1055
    
icculus@3021
  1056
    /* Do rate conversion, if necessary. Updates (cvt). */
slouken@10767
  1057
    if (SDL_BuildAudioResampleCVT(cvt, dst_channels, src_rate, dst_rate) < 0) {
icculus@3021
  1058
        return -1;              /* shouldn't happen, but just in case... */
slouken@2716
  1059
    }
slouken@2716
  1060
icculus@10756
  1061
    /* Move to final data type. */
slouken@10767
  1062
    if (SDL_BuildAudioTypeCVTFromFloat(cvt, dst_fmt) < 0) {
icculus@10575
  1063
        return -1;              /* shouldn't happen, but just in case... */
slouken@1895
  1064
    }
icculus@10575
  1065
icculus@10575
  1066
    cvt->needed = (cvt->filter_index != 0);
slouken@1895
  1067
    return (cvt->needed);
slouken@0
  1068
}
slouken@1895
  1069
icculus@10842
  1070
typedef int (*SDL_ResampleAudioStreamFunc)(SDL_AudioStream *stream, const void *inbuf, const int inbuflen, void *outbuf, const int outbuflen);
slouken@10773
  1071
typedef void (*SDL_ResetAudioStreamResamplerFunc)(SDL_AudioStream *stream);
slouken@10773
  1072
typedef void (*SDL_CleanupAudioStreamResamplerFunc)(SDL_AudioStream *stream);
icculus@10757
  1073
icculus@10757
  1074
struct SDL_AudioStream
icculus@10757
  1075
{
icculus@10757
  1076
    SDL_AudioCVT cvt_before_resampling;
icculus@10757
  1077
    SDL_AudioCVT cvt_after_resampling;
icculus@10757
  1078
    SDL_DataQueue *queue;
icculus@10844
  1079
    Uint8 *work_buffer_base;  /* maybe unaligned pointer from SDL_realloc(). */
icculus@10757
  1080
    int work_buffer_len;
icculus@10757
  1081
    int src_sample_frame_size;
icculus@10757
  1082
    SDL_AudioFormat src_format;
icculus@10757
  1083
    Uint8 src_channels;
icculus@10757
  1084
    int src_rate;
icculus@10757
  1085
    int dst_sample_frame_size;
icculus@10757
  1086
    SDL_AudioFormat dst_format;
icculus@10757
  1087
    Uint8 dst_channels;
icculus@10757
  1088
    int dst_rate;
icculus@10757
  1089
    double rate_incr;
icculus@10757
  1090
    Uint8 pre_resample_channels;
slouken@10773
  1091
    int packetlen;
slouken@10773
  1092
    void *resampler_state;
slouken@10773
  1093
    SDL_ResampleAudioStreamFunc resampler_func;
slouken@10773
  1094
    SDL_ResetAudioStreamResamplerFunc reset_resampler_func;
slouken@10773
  1095
    SDL_CleanupAudioStreamResamplerFunc cleanup_resampler_func;
slouken@10773
  1096
};
slouken@10773
  1097
icculus@10851
  1098
static Uint8 *
icculus@10851
  1099
EnsureStreamBufferSize(SDL_AudioStream *stream, const int newlen)
icculus@10851
  1100
{
icculus@10851
  1101
    Uint8 *ptr;
icculus@10851
  1102
    size_t offset;
icculus@10851
  1103
icculus@10851
  1104
    if (stream->work_buffer_len >= newlen) {
icculus@10851
  1105
        ptr = stream->work_buffer_base;
icculus@10851
  1106
    } else {
icculus@10851
  1107
        ptr = (Uint8 *) SDL_realloc(stream->work_buffer_base, newlen + 32);
icculus@10851
  1108
        if (!ptr) {
icculus@10851
  1109
            SDL_OutOfMemory();
icculus@10851
  1110
            return NULL;
icculus@10851
  1111
        }
icculus@10851
  1112
        /* Make sure we're aligned to 16 bytes for SIMD code. */
icculus@10851
  1113
        stream->work_buffer_base = ptr;
icculus@10851
  1114
        stream->work_buffer_len = newlen;
icculus@10851
  1115
    }
icculus@10851
  1116
icculus@10851
  1117
    offset = ((size_t) ptr) & 15;
icculus@10851
  1118
    return offset ? ptr + (16 - offset) : ptr;
icculus@10851
  1119
}
icculus@10851
  1120
slouken@10777
  1121
#ifdef HAVE_LIBSAMPLERATE_H
slouken@10773
  1122
static int
icculus@10842
  1123
SDL_ResampleAudioStream_SRC(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
slouken@10773
  1124
{
icculus@10842
  1125
    const float *inbuf = (const float *) _inbuf;
icculus@10842
  1126
    float *outbuf = (float *) _outbuf;
icculus@10799
  1127
    const int framelen = sizeof(float) * stream->pre_resample_channels;
icculus@10790
  1128
    SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
slouken@10773
  1129
    SRC_DATA data;
slouken@10773
  1130
    int result;
slouken@10773
  1131
icculus@10851
  1132
    if (inbuf == ((const float *) outbuf)) {  /* libsamplerate can't work in-place. */
icculus@10851
  1133
        Uint8 *ptr = EnsureStreamBufferSize(stream, inbuflen + outbuflen);
icculus@10851
  1134
        if (ptr == NULL) {
icculus@10851
  1135
            SDL_OutOfMemory();
icculus@10851
  1136
            return 0;
icculus@10851
  1137
        }
icculus@10851
  1138
        SDL_memcpy(ptr + outbuflen, ptr, inbuflen);
icculus@10851
  1139
        inbuf = (const float *) (ptr + outbuflen);
icculus@10851
  1140
        outbuf = (float *) ptr;
icculus@10851
  1141
    }
icculus@10851
  1142
slouken@10777
  1143
    data.data_in = (float *)inbuf; /* Older versions of libsamplerate had a non-const pointer, but didn't write to it */
icculus@10799
  1144
    data.input_frames = inbuflen / framelen;
slouken@10773
  1145
    data.input_frames_used = 0;
slouken@10773
  1146
slouken@10773
  1147
    data.data_out = outbuf;
icculus@10799
  1148
    data.output_frames = outbuflen / framelen;
slouken@10773
  1149
slouken@10773
  1150
    data.end_of_input = 0;
slouken@10773
  1151
    data.src_ratio = stream->rate_incr;
slouken@10773
  1152
icculus@10790
  1153
    result = SRC_src_process(state, &data);
slouken@10773
  1154
    if (result != 0) {
icculus@10790
  1155
        SDL_SetError("src_process() failed: %s", SRC_src_strerror(result));
slouken@10773
  1156
        return 0;
slouken@10773
  1157
    }
slouken@10773
  1158
slouken@10773
  1159
    /* If this fails, we need to store them off somewhere */
slouken@10773
  1160
    SDL_assert(data.input_frames_used == data.input_frames);
slouken@10773
  1161
slouken@10773
  1162
    return data.output_frames_gen * (sizeof(float) * stream->pre_resample_channels);
slouken@10773
  1163
}
slouken@10773
  1164
slouken@10773
  1165
static void
slouken@10773
  1166
SDL_ResetAudioStreamResampler_SRC(SDL_AudioStream *stream)
slouken@10773
  1167
{
icculus@10790
  1168
    SRC_src_reset((SRC_STATE *)stream->resampler_state);
slouken@10773
  1169
}
slouken@10773
  1170
slouken@10773
  1171
static void
slouken@10773
  1172
SDL_CleanupAudioStreamResampler_SRC(SDL_AudioStream *stream)
slouken@10773
  1173
{
icculus@10790
  1174
    SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
slouken@10773
  1175
    if (state) {
icculus@10790
  1176
        SRC_src_delete(state);
slouken@10773
  1177
    }
slouken@10773
  1178
slouken@10773
  1179
    stream->resampler_state = NULL;
slouken@10773
  1180
    stream->resampler_func = NULL;
slouken@10773
  1181
    stream->reset_resampler_func = NULL;
slouken@10773
  1182
    stream->cleanup_resampler_func = NULL;
slouken@10773
  1183
}
slouken@10773
  1184
slouken@10773
  1185
static SDL_bool
slouken@10773
  1186
SetupLibSampleRateResampling(SDL_AudioStream *stream)
slouken@10773
  1187
{
icculus@10790
  1188
    int result = 0;
icculus@10790
  1189
    SRC_STATE *state = NULL;
slouken@10773
  1190
icculus@10790
  1191
    if (SRC_available) {
icculus@10849
  1192
        state = SRC_src_new(SRC_converter, stream->pre_resample_channels, &result);
icculus@10790
  1193
        if (!state) {
icculus@10790
  1194
            SDL_SetError("src_new() failed: %s", SRC_src_strerror(result));
icculus@10790
  1195
        }
slouken@10773
  1196
    }
slouken@10773
  1197
icculus@10790
  1198
    if (!state) {
icculus@10790
  1199
        SDL_CleanupAudioStreamResampler_SRC(stream);
slouken@10773
  1200
        return SDL_FALSE;
slouken@10773
  1201
    }
slouken@10773
  1202
slouken@10773
  1203
    stream->resampler_state = state;
slouken@10773
  1204
    stream->resampler_func = SDL_ResampleAudioStream_SRC;
slouken@10773
  1205
    stream->reset_resampler_func = SDL_ResetAudioStreamResampler_SRC;
slouken@10773
  1206
    stream->cleanup_resampler_func = SDL_CleanupAudioStreamResampler_SRC;
slouken@10773
  1207
slouken@10773
  1208
    return SDL_TRUE;
slouken@10773
  1209
}
icculus@10790
  1210
#endif /* HAVE_LIBSAMPLERATE_H */
slouken@10773
  1211
slouken@10773
  1212
slouken@10773
  1213
static int
icculus@10842
  1214
SDL_ResampleAudioStream(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
slouken@10773
  1215
{
icculus@10842
  1216
    const float *inbuf = (const float *) _inbuf;
icculus@10842
  1217
    float *outbuf = (float *) _outbuf;
icculus@11517
  1218
    const int chans = (int) stream->pre_resample_channels;
icculus@11517
  1219
    const int inrate = stream->src_rate;
icculus@11517
  1220
    const int outrate = stream->dst_rate;
icculus@11517
  1221
    const int paddingsamples = ResamplerPadding(inrate, outrate) * chans;
icculus@11517
  1222
    const int paddingbytes = paddingsamples * sizeof (float);
icculus@11517
  1223
    float *lpadding = (float *) stream->resampler_state;
slouken@11519
  1224
    float *rpadding;
icculus@11517
  1225
    int retval;
slouken@10773
  1226
icculus@11508
  1227
    if (inbuf == ((const float *) outbuf)) {  /* !!! FIXME can't work in-place (for now!). */
icculus@11508
  1228
        Uint8 *ptr = EnsureStreamBufferSize(stream, inbuflen + outbuflen);
icculus@11508
  1229
        if (ptr == NULL) {
icculus@11508
  1230
            SDL_OutOfMemory();
icculus@11508
  1231
            return 0;
icculus@11508
  1232
        }
icculus@11508
  1233
        SDL_memcpy(ptr + outbuflen, ptr, inbuflen);
icculus@11508
  1234
        inbuf = (const float *) (ptr + outbuflen);
icculus@11508
  1235
        outbuf = (float *) ptr;
icculus@11508
  1236
    }
icculus@11508
  1237
icculus@11517
  1238
    /* !!! FIXME: streaming current resamples on Put, because of probably good reasons I can't remember right now, but if we resample on Get, we'd be able to access legit right padding values. */
slouken@11519
  1239
    rpadding = SDL_stack_alloc(float, paddingsamples);
slouken@11519
  1240
    if (!rpadding) {
slouken@11519
  1241
        SDL_OutOfMemory();
slouken@11519
  1242
        return 0;
slouken@11519
  1243
    }
icculus@11517
  1244
    SDL_memset(rpadding, '\0', paddingbytes);
slouken@11519
  1245
icculus@11517
  1246
    retval = SDL_ResampleAudio(chans, inrate, outrate, lpadding, rpadding, inbuf, inbuflen, outbuf, outbuflen);
slouken@10773
  1247
slouken@11519
  1248
    SDL_stack_free(rpadding);
slouken@11519
  1249
icculus@11517
  1250
    /* update our left padding with end of current input, for next run. */
icculus@11517
  1251
    SDL_memcpy(lpadding, ((const Uint8 *) inbuf) + (inbuflen - paddingbytes), paddingbytes);
icculus@11517
  1252
icculus@11517
  1253
    return retval;
slouken@10773
  1254
}
slouken@10773
  1255
slouken@10773
  1256
static void
slouken@10773
  1257
SDL_ResetAudioStreamResampler(SDL_AudioStream *stream)
slouken@10773
  1258
{
icculus@11517
  1259
    /* set all the left padding to silence. */
icculus@11517
  1260
    const int inrate = stream->src_rate;
icculus@11517
  1261
    const int outrate = stream->dst_rate;
icculus@11517
  1262
    const int chans = (int) stream->pre_resample_channels;
icculus@11517
  1263
    const int len = ResamplerPadding(inrate, outrate) * chans;
icculus@11517
  1264
    SDL_memset(stream->resampler_state, '\0', len * sizeof (float));
slouken@10773
  1265
}
slouken@10773
  1266
slouken@10773
  1267
static void
slouken@10773
  1268
SDL_CleanupAudioStreamResampler(SDL_AudioStream *stream)
slouken@10773
  1269
{
slouken@10773
  1270
    SDL_free(stream->resampler_state);
slouken@10773
  1271
}
icculus@10757
  1272
icculus@10789
  1273
SDL_AudioStream *
icculus@10789
  1274
SDL_NewAudioStream(const SDL_AudioFormat src_format,
icculus@10789
  1275
                   const Uint8 src_channels,
icculus@10789
  1276
                   const int src_rate,
icculus@10789
  1277
                   const SDL_AudioFormat dst_format,
icculus@10789
  1278
                   const Uint8 dst_channels,
icculus@10789
  1279
                   const int dst_rate)
icculus@10757
  1280
{
icculus@10757
  1281
    const int packetlen = 4096;  /* !!! FIXME: good enough for now. */
icculus@10757
  1282
    Uint8 pre_resample_channels;
icculus@10757
  1283
    SDL_AudioStream *retval;
icculus@10757
  1284
icculus@10757
  1285
    retval = (SDL_AudioStream *) SDL_calloc(1, sizeof (SDL_AudioStream));
icculus@10757
  1286
    if (!retval) {
icculus@10757
  1287
        return NULL;
icculus@10757
  1288
    }
icculus@10757
  1289
icculus@10757
  1290
    /* If increasing channels, do it after resampling, since we'd just
icculus@10757
  1291
       do more work to resample duplicate channels. If we're decreasing, do
icculus@10757
  1292
       it first so we resample the interpolated data instead of interpolating
icculus@10757
  1293
       the resampled data (!!! FIXME: decide if that works in practice, though!). */
icculus@10757
  1294
    pre_resample_channels = SDL_min(src_channels, dst_channels);
icculus@10757
  1295
icculus@10883
  1296
    retval->src_sample_frame_size = (SDL_AUDIO_BITSIZE(src_format) / 8) * src_channels;
icculus@10757
  1297
    retval->src_format = src_format;
icculus@10757
  1298
    retval->src_channels = src_channels;
icculus@10757
  1299
    retval->src_rate = src_rate;
icculus@10883
  1300
    retval->dst_sample_frame_size = (SDL_AUDIO_BITSIZE(dst_format) / 8) * dst_channels;
icculus@10757
  1301
    retval->dst_format = dst_format;
icculus@10757
  1302
    retval->dst_channels = dst_channels;
icculus@10757
  1303
    retval->dst_rate = dst_rate;
icculus@10757
  1304
    retval->pre_resample_channels = pre_resample_channels;
icculus@10757
  1305
    retval->packetlen = packetlen;
icculus@10757
  1306
    retval->rate_incr = ((double) dst_rate) / ((double) src_rate);
icculus@10757
  1307
icculus@10757
  1308
    /* Not resampling? It's an easy conversion (and maybe not even that!). */
icculus@10757
  1309
    if (src_rate == dst_rate) {
icculus@10757
  1310
        retval->cvt_before_resampling.needed = SDL_FALSE;
slouken@10773
  1311
        if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, src_format, src_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) {
slouken@10773
  1312
            SDL_FreeAudioStream(retval);
icculus@10757
  1313
            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
icculus@10757
  1314
        }
icculus@10757
  1315
    } else {
icculus@10757
  1316
        /* Don't resample at first. Just get us to Float32 format. */
icculus@10757
  1317
        /* !!! FIXME: convert to int32 on devices without hardware float. */
slouken@10773
  1318
        if (SDL_BuildAudioCVT(&retval->cvt_before_resampling, src_format, src_channels, src_rate, AUDIO_F32SYS, pre_resample_channels, src_rate) < 0) {
slouken@10773
  1319
            SDL_FreeAudioStream(retval);
icculus@10757
  1320
            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
icculus@10757
  1321
        }
icculus@10757
  1322
slouken@10777
  1323
#ifdef HAVE_LIBSAMPLERATE_H
slouken@10773
  1324
        SetupLibSampleRateResampling(retval);
slouken@10773
  1325
#endif
slouken@10773
  1326
slouken@10773
  1327
        if (!retval->resampler_func) {
icculus@11517
  1328
            const int chans = (int) pre_resample_channels;
icculus@11517
  1329
            const int len = ResamplerPadding(src_rate, dst_rate) * chans;
icculus@11517
  1330
            retval->resampler_state = SDL_calloc(len, sizeof (float));
slouken@10773
  1331
            if (!retval->resampler_state) {
slouken@10773
  1332
                SDL_FreeAudioStream(retval);
slouken@10773
  1333
                SDL_OutOfMemory();
slouken@10773
  1334
                return NULL;
slouken@10773
  1335
            }
icculus@11508
  1336
icculus@11508
  1337
            if (SDL_PrepareResampleFilter() < 0) {
icculus@11508
  1338
                SDL_free(retval->resampler_state);
icculus@11508
  1339
                retval->resampler_state = NULL;
icculus@11508
  1340
                SDL_FreeAudioStream(retval);
icculus@11508
  1341
                return NULL;
icculus@11508
  1342
            }
icculus@11508
  1343
slouken@10773
  1344
            retval->resampler_func = SDL_ResampleAudioStream;
slouken@10773
  1345
            retval->reset_resampler_func = SDL_ResetAudioStreamResampler;
slouken@10773
  1346
            retval->cleanup_resampler_func = SDL_CleanupAudioStreamResampler;
slouken@10773
  1347
        }
slouken@10773
  1348
icculus@10757
  1349
        /* Convert us to the final format after resampling. */
slouken@10773
  1350
        if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, AUDIO_F32SYS, pre_resample_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) {
slouken@10773
  1351
            SDL_FreeAudioStream(retval);
icculus@10757
  1352
            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
icculus@10757
  1353
        }
icculus@10757
  1354
    }
icculus@10757
  1355
icculus@10757
  1356
    retval->queue = SDL_NewDataQueue(packetlen, packetlen * 2);
icculus@10757
  1357
    if (!retval->queue) {
slouken@10773
  1358
        SDL_FreeAudioStream(retval);
icculus@10757
  1359
        return NULL;  /* SDL_NewDataQueue should have called SDL_SetError. */
icculus@10757
  1360
    }
icculus@10757
  1361
icculus@10757
  1362
    return retval;
icculus@10757
  1363
}
icculus@10757
  1364
icculus@10757
  1365
int
icculus@10757
  1366
SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, const Uint32 _buflen)
icculus@10757
  1367
{
icculus@10757
  1368
    int buflen = (int) _buflen;
icculus@10846
  1369
    const void *origbuf = buf;
icculus@10757
  1370
icculus@10844
  1371
    /* !!! FIXME: several converters can take advantage of SIMD, but only
icculus@10844
  1372
       !!! FIXME:  if the data is aligned to 16 bytes. EnsureStreamBufferSize()
icculus@10844
  1373
       !!! FIXME:  guarantees the buffer will align, but the
icculus@10844
  1374
       !!! FIXME:  converters will iterate over the data backwards if
icculus@10844
  1375
       !!! FIXME:  the output grows, and this means we won't align if buflen
icculus@10844
  1376
       !!! FIXME:  isn't a multiple of 16. In these cases, we should chop off
icculus@10844
  1377
       !!! FIXME:  a few samples at the end and convert them separately. */
icculus@10844
  1378
icculus@10757
  1379
    if (!stream) {
icculus@10757
  1380
        return SDL_InvalidParamError("stream");
icculus@10757
  1381
    } else if (!buf) {
icculus@10757
  1382
        return SDL_InvalidParamError("buf");
icculus@10757
  1383
    } else if (buflen == 0) {
icculus@10757
  1384
        return 0;  /* nothing to do. */
icculus@10757
  1385
    } else if ((buflen % stream->src_sample_frame_size) != 0) {
icculus@10757
  1386
        return SDL_SetError("Can't add partial sample frames");
icculus@10757
  1387
    }
icculus@10757
  1388
icculus@10757
  1389
    if (stream->cvt_before_resampling.needed) {
icculus@10757
  1390
        const int workbuflen = buflen * stream->cvt_before_resampling.len_mult;  /* will be "* 1" if not needed */
icculus@10844
  1391
        Uint8 *workbuf = EnsureStreamBufferSize(stream, workbuflen);
icculus@10757
  1392
        if (workbuf == NULL) {
icculus@10757
  1393
            return -1;  /* probably out of memory. */
icculus@10757
  1394
        }
icculus@10846
  1395
        SDL_assert(buf == origbuf);
icculus@10757
  1396
        SDL_memcpy(workbuf, buf, buflen);
icculus@10757
  1397
        stream->cvt_before_resampling.buf = workbuf;
icculus@10757
  1398
        stream->cvt_before_resampling.len = buflen;
icculus@10757
  1399
        if (SDL_ConvertAudio(&stream->cvt_before_resampling) == -1) {
icculus@10757
  1400
            return -1;   /* uhoh! */
icculus@10757
  1401
        }
icculus@10757
  1402
        buf = workbuf;
icculus@10757
  1403
        buflen = stream->cvt_before_resampling.len_cvt;
icculus@10757
  1404
    }
icculus@10757
  1405
icculus@10757
  1406
    if (stream->dst_rate != stream->src_rate) {
icculus@10757
  1407
        const int workbuflen = buflen * ((int) SDL_ceil(stream->rate_incr));
icculus@10844
  1408
        Uint8 *workbuf = EnsureStreamBufferSize(stream, workbuflen);
icculus@10757
  1409
        if (workbuf == NULL) {
icculus@10757
  1410
            return -1;  /* probably out of memory. */
icculus@10757
  1411
        }
icculus@10851
  1412
        /* don't SDL_memcpy(workbuf, buf, buflen) here; our resampler can work inplace or not,
icculus@10851
  1413
           libsamplerate needs buffers to be separate; either way, avoid a copy here if possible. */
icculus@10851
  1414
        if (buf != origbuf) {
icculus@10851
  1415
            buf = workbuf;  /* in case we realloc()'d the pointer. */
icculus@10843
  1416
        }
icculus@10851
  1417
        buflen = stream->resampler_func(stream, buf, buflen, workbuf, workbuflen);
icculus@10851
  1418
        buf = EnsureStreamBufferSize(stream, workbuflen);
icculus@10851
  1419
        SDL_assert(buf != NULL);  /* shouldn't be growing, just aligning. */
icculus@10757
  1420
    }
icculus@10757
  1421
icculus@10757
  1422
    if (stream->cvt_after_resampling.needed) {
icculus@10842
  1423
        const int workbuflen = buflen * stream->cvt_after_resampling.len_mult;  /* will be "* 1" if not needed */
icculus@10844
  1424
        Uint8 *workbuf = EnsureStreamBufferSize(stream, workbuflen);
icculus@10757
  1425
        if (workbuf == NULL) {
icculus@10757
  1426
            return -1;  /* probably out of memory. */
icculus@10757
  1427
        }
icculus@10846
  1428
        if (buf == origbuf) {  /* copy if we haven't before. */
icculus@11128
  1429
            SDL_memcpy(workbuf, origbuf, buflen);
icculus@10843
  1430
        }
icculus@10757
  1431
        stream->cvt_after_resampling.buf = workbuf;
icculus@10757
  1432
        stream->cvt_after_resampling.len = buflen;
icculus@10757
  1433
        if (SDL_ConvertAudio(&stream->cvt_after_resampling) == -1) {
icculus@10757
  1434
            return -1;   /* uhoh! */
icculus@10757
  1435
        }
icculus@10757
  1436
        buf = workbuf;
icculus@10757
  1437
        buflen = stream->cvt_after_resampling.len_cvt;
icculus@10757
  1438
    }
icculus@10757
  1439
icculus@10757
  1440
    return SDL_WriteToDataQueue(stream->queue, buf, buflen);
icculus@10757
  1441
}
icculus@10757
  1442
icculus@10757
  1443
void
icculus@10757
  1444
SDL_AudioStreamClear(SDL_AudioStream *stream)
icculus@10757
  1445
{
icculus@10757
  1446
    if (!stream) {
icculus@10757
  1447
        SDL_InvalidParamError("stream");
icculus@10757
  1448
    } else {
icculus@10757
  1449
        SDL_ClearDataQueue(stream->queue, stream->packetlen * 2);
icculus@10776
  1450
        if (stream->reset_resampler_func) {
icculus@10776
  1451
            stream->reset_resampler_func(stream);
icculus@10776
  1452
        }
icculus@10757
  1453
    }
icculus@10757
  1454
}
icculus@10757
  1455
icculus@10757
  1456
icculus@10757
  1457
/* get converted/resampled data from the stream */
icculus@10757
  1458
int
icculus@10764
  1459
SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, const Uint32 len)
icculus@10757
  1460
{
icculus@10757
  1461
    if (!stream) {
icculus@10757
  1462
        return SDL_InvalidParamError("stream");
icculus@10757
  1463
    } else if (!buf) {
icculus@10757
  1464
        return SDL_InvalidParamError("buf");
icculus@10757
  1465
    } else if (len == 0) {
icculus@10757
  1466
        return 0;  /* nothing to do. */
icculus@10757
  1467
    } else if ((len % stream->dst_sample_frame_size) != 0) {
icculus@10757
  1468
        return SDL_SetError("Can't request partial sample frames");
icculus@10757
  1469
    }
icculus@10757
  1470
icculus@10764
  1471
    return (int) SDL_ReadFromDataQueue(stream->queue, buf, len);
icculus@10757
  1472
}
icculus@10757
  1473
icculus@10757
  1474
/* number of converted/resampled bytes available */
icculus@10757
  1475
int
icculus@10757
  1476
SDL_AudioStreamAvailable(SDL_AudioStream *stream)
icculus@10757
  1477
{
icculus@10757
  1478
    return stream ? (int) SDL_CountDataQueue(stream->queue) : 0;
icculus@10757
  1479
}
icculus@10757
  1480
icculus@10757
  1481
/* dispose of a stream */
icculus@10757
  1482
void
icculus@10757
  1483
SDL_FreeAudioStream(SDL_AudioStream *stream)
icculus@10757
  1484
{
icculus@10757
  1485
    if (stream) {
slouken@10773
  1486
        if (stream->cleanup_resampler_func) {
slouken@10773
  1487
            stream->cleanup_resampler_func(stream);
slouken@10773
  1488
        }
icculus@10757
  1489
        SDL_FreeDataQueue(stream->queue);
icculus@10844
  1490
        SDL_free(stream->work_buffer_base);
icculus@10757
  1491
        SDL_free(stream);
icculus@10757
  1492
    }
icculus@10757
  1493
}
icculus@10757
  1494
icculus@10575
  1495
/* vi: set ts=4 sw=4 expandtab: */
slouken@2716
  1496