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