Add SDL_ConvertAudioSamples() helper function

This commit is contained in:
Sylvain
2023-01-23 08:24:49 +01:00
committed by Sam Lantinga
parent 7b50bae524
commit 052b14eb65
8 changed files with 124 additions and 57 deletions

View File

@@ -1662,3 +1662,73 @@ void SDL_CalculateAudioSpec(SDL_AudioSpec *spec)
spec->size *= spec->samples;
}
int SDL_ConvertAudioSamples(
SDL_AudioFormat src_format, Uint8 src_channels, int src_rate, int src_len, Uint8 *src_data,
SDL_AudioFormat dst_format, Uint8 dst_channels, int dst_rate, int *dst_len, Uint8 **dst_data)
{
int ret = -1;
SDL_AudioStream *stream = NULL;
int src_samplesize, dst_samplesize;
int real_dst_len;
if (src_len < 0) {
return SDL_InvalidParamError("src_len");
}
if (src_data == NULL) {
return SDL_InvalidParamError("src_data");
}
if (dst_len == NULL) {
return SDL_InvalidParamError("dst_len");
}
if (dst_data == NULL) {
return SDL_InvalidParamError("dst_data");
}
*dst_len = 0;
*dst_data = NULL;
stream = SDL_CreateAudioStream(src_format, src_channels, src_rate, dst_format, dst_channels, dst_rate);
if (stream == NULL) {
goto end;
}
src_samplesize = (SDL_AUDIO_BITSIZE(src_format) / 8) * src_channels;
dst_samplesize = (SDL_AUDIO_BITSIZE(dst_format) / 8) * dst_channels;
src_len &= ~(src_samplesize - 1);
*dst_len = dst_samplesize * (src_len / src_samplesize);
if (src_rate < dst_rate) {
const double mult = ((double)dst_rate) / ((double)src_rate);
*dst_len *= (int) SDL_ceil(mult);
}
*dst_len &= ~(dst_samplesize - 1);
*dst_data = (Uint8 *)SDL_malloc(*dst_len);
if (*dst_data == NULL) {
goto end;
}
if (SDL_PutAudioStreamData(stream, src_data, src_len) < 0 ||
SDL_FlushAudioStream(stream) < 0) {
goto end;
}
real_dst_len = SDL_GetAudioStreamData(stream, *dst_data, *dst_len);
if (real_dst_len < 0) {
goto end;
}
*dst_len = real_dst_len;
ret = 0;
end:
if (ret != 0) {
SDL_free(*dst_data);
*dst_len = 0;
*dst_data = NULL;
}
SDL_DestroyAudioStream(stream);
return ret;
}

View File

@@ -841,6 +841,7 @@ SDL3_0.0.0 {
SDL_PlayAudioDevice;
SDL_aligned_alloc;
SDL_aligned_free;
SDL_ConvertAudioSamples;
# extra symbols go here (don't modify this line)
local: *;
};

View File

@@ -868,3 +868,4 @@
#define SDL_PlayAudioDevice SDL_PlayAudioDevice_REAL
#define SDL_aligned_alloc SDL_aligned_alloc_REAL
#define SDL_aligned_free SDL_aligned_free_REAL
#define SDL_ConvertAudioSamples SDL_ConvertAudioSamples_REAL

View File

@@ -913,3 +913,4 @@ SDL_DYNAPI_PROC(int,SDL_GetRenderVSync,(SDL_Renderer *a, int *b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_PlayAudioDevice,(SDL_AudioDeviceID a),(a),)
SDL_DYNAPI_PROC(void*,SDL_aligned_alloc,(size_t a, size_t b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_aligned_free,(void *a),(a),)
SDL_DYNAPI_PROC(int,SDL_ConvertAudioSamples,(SDL_AudioFormat a, Uint8 b, int c, int d, Uint8 *e, SDL_AudioFormat f, Uint8 g, int h, int *i, Uint8 **j),(a,b,c,d,e,f,g,h,i,j),return)