Update for SDL3 coding style (#6717)

I updated .clang-format and ran clang-format 14 over the src and test directories to standardize the code base.

In general I let clang-format have it's way, and added markup to prevent formatting of code that would break or be completely unreadable if formatted.

The script I ran for the src directory is added as build-scripts/clang-format-src.sh

This fixes:
#6592
#6593
#6594
This commit is contained in:
Sam Lantinga
2022-11-30 12:51:59 -08:00
committed by GitHub
parent 14b902faca
commit 5750bcb174
781 changed files with 51659 additions and 55763 deletions

View File

@@ -16,8 +16,8 @@ AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: All AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: AllDefinitions AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine AlwaysBreakTemplateDeclarations: MultiLine
@@ -35,7 +35,7 @@ BraceWrapping:
AfterUnion: true AfterUnion: true
AfterExternBlock: false AfterExternBlock: false
BeforeElse: false BeforeElse: false
BeforeWhile: true BeforeWhile: false
IndentBraces: false IndentBraces: false
SplitEmptyFunction: true SplitEmptyFunction: true
SplitEmptyRecord: true SplitEmptyRecord: true
@@ -48,7 +48,7 @@ IncludeBlocks: Preserve
# clang-format version 4.0 through 12.0: # clang-format version 4.0 through 12.0:
#SortIncludes: false #SortIncludes: false
# clang-format version 13.0+: # clang-format version 13.0+:
#SortIncludes: Never SortIncludes: Never
# No length limit, in case it breaks macros, you can # No length limit, in case it breaks macros, you can
# disable it with /* clang-format off/on */ comments # disable it with /* clang-format off/on */ comments
@@ -62,7 +62,8 @@ IndentGotoLabels: true
IndentPPDirectives: None IndentPPDirectives: None
IndentExternBlock: NoIndent IndentExternBlock: NoIndent
SpaceAfterCStyleCast: true PointerAlignment: Right
SpaceAfterCStyleCast: false
SpacesInCStyleCastParentheses: false SpacesInCStyleCastParentheses: false
SpacesInConditionalStatement: false SpacesInConditionalStatement: false
SpacesInContainerLiterals: true SpacesInContainerLiterals: true

View File

@@ -0,0 +1,32 @@
#!/bin/sh
cd "$(dirname $0)/../src"
echo "Running clang-format in $(pwd)"
find . -regex '.*\.[chm]p*' -exec clang-format -i {} \;
# Revert third-party code
git checkout \
events/imKStoUCS.* \
hidapi \
joystick/controller_type.c \
joystick/controller_type.h \
joystick/hidapi/steam/controller_constants.h \
joystick/hidapi/steam/controller_structs.h \
libm \
stdlib/SDL_malloc.c \
stdlib/SDL_qsort.c \
stdlib/SDL_strtokr.c \
video/arm \
video/khronos \
video/x11/edid-parse.c \
video/yuv2rgb
clang-format -i hidapi/SDL_hidapi.c
# Revert generated code
git checkout dynapi/SDL_dynapi_overrides.h
git checkout dynapi/SDL_dynapi_procs.h
git checkout render/metal/SDL_shaders_metal_*.h
echo "clang-format complete!"

View File

@@ -44,7 +44,7 @@
/* Initialization/Cleanup routines */ /* Initialization/Cleanup routines */
#if !SDL_TIMERS_DISABLED #if !SDL_TIMERS_DISABLED
# include "timer/SDL_timer_c.h" #include "timer/SDL_timer_c.h"
#endif #endif
#if SDL_VIDEO_DRIVER_WINDOWS #if SDL_VIDEO_DRIVER_WINDOWS
extern int SDL_HelperWindowCreate(void); extern int SDL_HelperWindowCreate(void);
@@ -99,7 +99,6 @@ SDL_NORETURN void SDL_ExitProcess(int exitcode)
#endif #endif
} }
/* The initialized subsystems */ /* The initialized subsystems */
#ifdef SDL_MAIN_NEEDED #ifdef SDL_MAIN_NEEDED
static SDL_bool SDL_MainIsReady = SDL_FALSE; static SDL_bool SDL_MainIsReady = SDL_FALSE;
@@ -107,11 +106,10 @@ static SDL_bool SDL_MainIsReady = SDL_FALSE;
static SDL_bool SDL_MainIsReady = SDL_TRUE; static SDL_bool SDL_MainIsReady = SDL_TRUE;
#endif #endif
static SDL_bool SDL_bInMainQuit = SDL_FALSE; static SDL_bool SDL_bInMainQuit = SDL_FALSE;
static Uint8 SDL_SubsystemRefCount[ 32 ]; static Uint8 SDL_SubsystemRefCount[32];
/* Private helper to increment a subsystem's ref counter. */ /* Private helper to increment a subsystem's ref counter. */
static void static void SDL_PrivateSubsystemRefCountIncr(Uint32 subsystem)
SDL_PrivateSubsystemRefCountIncr(Uint32 subsystem)
{ {
const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem);
SDL_assert((subsystem_index < 0) || (SDL_SubsystemRefCount[subsystem_index] < 255)); SDL_assert((subsystem_index < 0) || (SDL_SubsystemRefCount[subsystem_index] < 255));
@@ -121,8 +119,7 @@ SDL_PrivateSubsystemRefCountIncr(Uint32 subsystem)
} }
/* Private helper to decrement a subsystem's ref counter. */ /* Private helper to decrement a subsystem's ref counter. */
static void static void SDL_PrivateSubsystemRefCountDecr(Uint32 subsystem)
SDL_PrivateSubsystemRefCountDecr(Uint32 subsystem)
{ {
const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem);
if ((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] > 0)) { if ((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] > 0)) {
@@ -131,8 +128,7 @@ SDL_PrivateSubsystemRefCountDecr(Uint32 subsystem)
} }
/* Private helper to check if a system needs init. */ /* Private helper to check if a system needs init. */
static SDL_bool static SDL_bool SDL_PrivateShouldInitSubsystem(Uint32 subsystem)
SDL_PrivateShouldInitSubsystem(Uint32 subsystem)
{ {
const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem);
SDL_assert((subsystem_index < 0) || (SDL_SubsystemRefCount[subsystem_index] < 255)); SDL_assert((subsystem_index < 0) || (SDL_SubsystemRefCount[subsystem_index] < 255));
@@ -140,8 +136,8 @@ SDL_PrivateShouldInitSubsystem(Uint32 subsystem)
} }
/* Private helper to check if a system needs to be quit. */ /* Private helper to check if a system needs to be quit. */
static SDL_bool static SDL_bool SDL_PrivateShouldQuitSubsystem(Uint32 subsystem)
SDL_PrivateShouldQuitSubsystem(Uint32 subsystem) { {
const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem);
if ((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] == 0)) { if ((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] == 0)) {
return SDL_FALSE; return SDL_FALSE;
@@ -153,14 +149,12 @@ SDL_PrivateShouldQuitSubsystem(Uint32 subsystem) {
return (((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] == 1)) || SDL_bInMainQuit) ? SDL_TRUE : SDL_FALSE; return (((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] == 1)) || SDL_bInMainQuit) ? SDL_TRUE : SDL_FALSE;
} }
void void SDL_SetMainReady(void)
SDL_SetMainReady(void)
{ {
SDL_MainIsReady = SDL_TRUE; SDL_MainIsReady = SDL_TRUE;
} }
int int SDL_InitSubSystem(Uint32 flags)
SDL_InitSubSystem(Uint32 flags)
{ {
Uint32 flags_initialized = 0; Uint32 flags_initialized = 0;
@@ -182,13 +176,13 @@ SDL_InitSubSystem(Uint32 flags)
flags |= SDL_INIT_JOYSTICK; flags |= SDL_INIT_JOYSTICK;
} }
if ((flags & (SDL_INIT_VIDEO|SDL_INIT_JOYSTICK|SDL_INIT_AUDIO))) { if ((flags & (SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO))) {
/* video or joystick or audio implies events */ /* video or joystick or audio implies events */
flags |= SDL_INIT_EVENTS; flags |= SDL_INIT_EVENTS;
} }
#if SDL_VIDEO_DRIVER_WINDOWS #if SDL_VIDEO_DRIVER_WINDOWS
if ((flags & (SDL_INIT_HAPTIC|SDL_INIT_JOYSTICK))) { if ((flags & (SDL_INIT_HAPTIC | SDL_INIT_JOYSTICK))) {
if (SDL_HelperWindowCreate() < 0) { if (SDL_HelperWindowCreate() < 0) {
goto quit_and_error; goto quit_and_error;
} }
@@ -326,7 +320,7 @@ SDL_InitSubSystem(Uint32 flags)
#endif #endif
} }
(void) flags_initialized; /* make static analysis happy, since this only gets used in error cases. */ (void)flags_initialized; /* make static analysis happy, since this only gets used in error cases. */
return 0; return 0;
@@ -335,14 +329,12 @@ quit_and_error:
return -1; return -1;
} }
int int SDL_Init(Uint32 flags)
SDL_Init(Uint32 flags)
{ {
return SDL_InitSubSystem(flags); return SDL_InitSubSystem(flags);
} }
void void SDL_QuitSubSystem(Uint32 flags)
SDL_QuitSubSystem(Uint32 flags)
{ {
/* Shut down requested initialized subsystems */ /* Shut down requested initialized subsystems */
#if !SDL_SENSOR_DISABLED #if !SDL_SENSOR_DISABLED
@@ -459,8 +451,7 @@ SDL_WasInit(Uint32 flags)
return initialized; return initialized;
} }
void void SDL_Quit(void)
SDL_Quit(void)
{ {
SDL_bInMainQuit = SDL_TRUE; SDL_bInMainQuit = SDL_TRUE;
@@ -486,7 +477,7 @@ SDL_Quit(void)
/* Now that every subsystem has been quit, we reset the subsystem refcount /* Now that every subsystem has been quit, we reset the subsystem refcount
* and the list of initialized subsystems. * and the list of initialized subsystems.
*/ */
SDL_memset( SDL_SubsystemRefCount, 0x0, sizeof(SDL_SubsystemRefCount) ); SDL_memset(SDL_SubsystemRefCount, 0x0, sizeof(SDL_SubsystemRefCount));
SDL_TLSCleanup(); SDL_TLSCleanup();
@@ -494,13 +485,13 @@ SDL_Quit(void)
} }
/* Get the library version number */ /* Get the library version number */
void void SDL_GetVersion(SDL_version *ver)
SDL_GetVersion(SDL_version * ver)
{ {
static SDL_bool check_hint = SDL_TRUE; static SDL_bool check_hint = SDL_TRUE;
static SDL_bool legacy_version = SDL_FALSE; static SDL_bool legacy_version = SDL_FALSE;
if (ver == NULL) { return; if (ver == NULL) {
return;
} }
SDL_VERSION(ver); SDL_VERSION(ver);

View File

@@ -40,8 +40,7 @@
/* The size of the stack buffer to use for rendering assert messages. */ /* The size of the stack buffer to use for rendering assert messages. */
#define SDL_MAX_ASSERT_MESSAGE_STACK 256 #define SDL_MAX_ASSERT_MESSAGE_STACK 256
static SDL_assert_state SDLCALL static SDL_assert_state SDLCALL SDL_PromptAssertion(const SDL_assert_data *data, void *userdata);
SDL_PromptAssertion(const SDL_assert_data *data, void *userdata);
/* /*
* We keep all triggered assertions in a singly-linked list so we can * We keep all triggered assertions in a singly-linked list so we can
@@ -57,12 +56,10 @@ static SDL_AssertionHandler assertion_handler = SDL_PromptAssertion;
static void *assertion_userdata = NULL; static void *assertion_userdata = NULL;
#ifdef __GNUC__ #ifdef __GNUC__
static void static void debug_print(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
debug_print(const char *fmt, ...) __attribute__((format (printf, 1, 2)));
#endif #endif
static void static void debug_print(const char *fmt, ...)
debug_print(const char *fmt, ...)
{ {
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);
@@ -70,7 +67,6 @@ debug_print(const char *fmt, ...)
va_end(ap); va_end(ap);
} }
static void SDL_AddAssertionToReport(SDL_assert_data *data) static void SDL_AddAssertionToReport(SDL_assert_data *data)
{ {
/* (data) is always a static struct defined with the assert macros, so /* (data) is always a static struct defined with the assert macros, so
@@ -83,18 +79,18 @@ static void SDL_AddAssertionToReport(SDL_assert_data *data)
} }
#if defined(__WIN32__) || defined(__GDK__) #if defined(__WIN32__) || defined(__GDK__)
#define ENDLINE "\r\n" #define ENDLINE "\r\n"
#else #else
#define ENDLINE "\n" #define ENDLINE "\n"
#endif #endif
static int SDL_RenderAssertMessage(char *buf, size_t buf_len, const SDL_assert_data *data) { static int SDL_RenderAssertMessage(char *buf, size_t buf_len, const SDL_assert_data *data)
{
return SDL_snprintf(buf, buf_len, return SDL_snprintf(buf, buf_len,
"Assertion failure at %s (%s:%d), triggered %u %s:" ENDLINE " '%s'", "Assertion failure at %s (%s:%d), triggered %u %s:" ENDLINE " '%s'",
data->function, data->filename, data->linenum, data->function, data->filename, data->linenum,
data->trigger_count, (data->trigger_count == 1) ? "time" : "times", data->trigger_count, (data->trigger_count == 1) ? "time" : "times",
data->condition data->condition);
);
} }
static void SDL_GenerateAssertionReport(void) static void SDL_GenerateAssertionReport(void)
@@ -124,7 +120,6 @@ static void SDL_GenerateAssertionReport(void)
} }
} }
/* This is not declared in any header, although it is shared between some /* This is not declared in any header, although it is shared between some
parts of SDL, because we don't want anything calling it without an parts of SDL, because we don't want anything calling it without an
extremely good reason. */ extremely good reason. */
@@ -134,9 +129,8 @@ extern void SDL_ExitProcess(int exitcode);
#endif #endif
extern SDL_NORETURN void SDL_ExitProcess(int exitcode); extern SDL_NORETURN void SDL_ExitProcess(int exitcode);
#if defined(__WATCOMC__) #if defined(__WATCOMC__)
static void SDL_AbortAssertion (void); static void SDL_AbortAssertion(void);
#pragma aux SDL_AbortAssertion aborts; #pragma aux SDL_AbortAssertion aborts;
#endif #endif
static SDL_NORETURN void SDL_AbortAssertion(void) static SDL_NORETURN void SDL_AbortAssertion(void)
@@ -145,8 +139,7 @@ static SDL_NORETURN void SDL_AbortAssertion(void)
SDL_ExitProcess(42); SDL_ExitProcess(42);
} }
static SDL_assert_state SDLCALL static SDL_assert_state SDLCALL SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
{ {
const char *envr; const char *envr;
SDL_assert_state state = SDL_ASSERTION_ABORT; SDL_assert_state state = SDL_ASSERTION_ABORT;
@@ -168,7 +161,7 @@ SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
size_t buf_len = sizeof(stack_buf); size_t buf_len = sizeof(stack_buf);
int len; int len;
(void) userdata; /* unused in default handler. */ (void)userdata; /* unused in default handler. */
/* Assume the output will fit... */ /* Assume the output will fit... */
len = SDL_RenderAssertMessage(message, buf_len, data); len = SDL_RenderAssertMessage(message, buf_len, data);
@@ -247,8 +240,9 @@ SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
} else { } else {
#if defined(__EMSCRIPTEN__) #if defined(__EMSCRIPTEN__)
/* This is nasty, but we can't block on a custom UI. */ /* This is nasty, but we can't block on a custom UI. */
for ( ; ; ) { for (;;) {
SDL_bool okay = SDL_TRUE; SDL_bool okay = SDL_TRUE;
/* *INDENT-OFF* */ /* clang-format off */
char *buf = (char *) EM_ASM_INT({ char *buf = (char *) EM_ASM_INT({
var str = var str =
UTF8ToString($0) + '\n\n' + UTF8ToString($0) + '\n\n' +
@@ -259,12 +253,14 @@ SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
} }
return allocate(intArrayFromString(reply), 'i8', ALLOC_NORMAL); return allocate(intArrayFromString(reply), 'i8', ALLOC_NORMAL);
}, message); }, message);
/* *INDENT-ON* */ /* clang-format on */
if (SDL_strcmp(buf, "a") == 0) { if (SDL_strcmp(buf, "a") == 0) {
state = SDL_ASSERTION_ABORT; state = SDL_ASSERTION_ABORT;
/* (currently) no break functionality on Emscripten #if 0 /* (currently) no break functionality on Emscripten */
} else if (SDL_strcmp(buf, "b") == 0) { } else if (SDL_strcmp(buf, "b") == 0) {
state = SDL_ASSERTION_BREAK; */ state = SDL_ASSERTION_BREAK;
#endif
} else if (SDL_strcmp(buf, "r") == 0) { } else if (SDL_strcmp(buf, "r") == 0) {
state = SDL_ASSERTION_RETRY; state = SDL_ASSERTION_RETRY;
} else if (SDL_strcmp(buf, "i") == 0) { } else if (SDL_strcmp(buf, "i") == 0) {
@@ -282,11 +278,11 @@ SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
} }
#elif defined(HAVE_STDIO_H) #elif defined(HAVE_STDIO_H)
/* this is a little hacky. */ /* this is a little hacky. */
for ( ; ; ) { for (;;) {
char buf[32]; char buf[32];
fprintf(stderr, "Abort/Break/Retry/Ignore/AlwaysIgnore? [abriA] : "); fprintf(stderr, "Abort/Break/Retry/Ignore/AlwaysIgnore? [abriA] : ");
fflush(stderr); fflush(stderr);
if (fgets(buf, sizeof (buf), stdin) == NULL) { if (fgets(buf, sizeof(buf), stdin) == NULL) {
break; break;
} }
@@ -322,7 +318,6 @@ SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
return state; return state;
} }
SDL_assert_state SDL_assert_state
SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file, SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file,
int line) int line)
@@ -363,7 +358,8 @@ SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file,
} else if (assertion_running == 3) { /* Abort asserted! */ } else if (assertion_running == 3) { /* Abort asserted! */
SDL_ExitProcess(42); SDL_ExitProcess(42);
} else { } else {
while (1) { /* do nothing but spin; what else can you do?! */ } while (1) { /* do nothing but spin; what else can you do?! */
}
} }
} }
@@ -371,8 +367,7 @@ SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file,
state = assertion_handler(data, assertion_userdata); state = assertion_handler(data, assertion_userdata);
} }
switch (state) switch (state) {
{
case SDL_ASSERTION_ALWAYS_IGNORE: case SDL_ASSERTION_ALWAYS_IGNORE:
state = SDL_ASSERTION_IGNORE; state = SDL_ASSERTION_IGNORE;
data->always_ignore = 1; data->always_ignore = 1;
@@ -397,7 +392,6 @@ SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file,
return state; return state;
} }
void SDL_AssertionsQuit(void) void SDL_AssertionsQuit(void)
{ {
#if SDL_ASSERT_LEVEL > 0 #if SDL_ASSERT_LEVEL > 0
@@ -432,7 +426,7 @@ void SDL_ResetAssertionReport(void)
SDL_assert_data *next = NULL; SDL_assert_data *next = NULL;
SDL_assert_data *item; SDL_assert_data *item;
for (item = triggered_assertions; item != NULL; item = next) { for (item = triggered_assertions; item != NULL; item = next) {
next = (SDL_assert_data *) item->next; next = (SDL_assert_data *)item->next;
item->always_ignore = SDL_FALSE; item->always_ignore = SDL_FALSE;
item->trigger_count = 0; item->trigger_count = 0;
item->next = NULL; item->next = NULL;

View File

@@ -39,8 +39,7 @@ struct SDL_DataQueue
size_t queued_bytes; /* number of bytes of data in the queue. */ size_t queued_bytes; /* number of bytes of data in the queue. */
}; };
static void static void SDL_FreeDataQueueList(SDL_DataQueuePacket *packet)
SDL_FreeDataQueueList(SDL_DataQueuePacket *packet)
{ {
while (packet) { while (packet) {
SDL_DataQueuePacket *next = packet->next; SDL_DataQueuePacket *next = packet->next;
@@ -49,13 +48,12 @@ SDL_FreeDataQueueList(SDL_DataQueuePacket *packet)
} }
} }
/* this all expects that you managed thread safety elsewhere. */ /* this all expects that you managed thread safety elsewhere. */
SDL_DataQueue * SDL_DataQueue *
SDL_NewDataQueue(const size_t _packetlen, const size_t initialslack) SDL_NewDataQueue(const size_t _packetlen, const size_t initialslack)
{ {
SDL_DataQueue *queue = (SDL_DataQueue *) SDL_malloc(sizeof (SDL_DataQueue)); SDL_DataQueue *queue = (SDL_DataQueue *)SDL_malloc(sizeof(SDL_DataQueue));
if (queue == NULL) { if (queue == NULL) {
SDL_OutOfMemory(); SDL_OutOfMemory();
@@ -69,7 +67,7 @@ SDL_NewDataQueue(const size_t _packetlen, const size_t initialslack)
queue->packet_size = packetlen; queue->packet_size = packetlen;
for (i = 0; i < wantpackets; i++) { for (i = 0; i < wantpackets; i++) {
SDL_DataQueuePacket *packet = (SDL_DataQueuePacket *) SDL_malloc(sizeof (SDL_DataQueuePacket) + packetlen); SDL_DataQueuePacket *packet = (SDL_DataQueuePacket *)SDL_malloc(sizeof(SDL_DataQueuePacket) + packetlen);
if (packet) { /* don't care if this fails, we'll deal later. */ if (packet) { /* don't care if this fails, we'll deal later. */
packet->datalen = 0; packet->datalen = 0;
packet->startpos = 0; packet->startpos = 0;
@@ -82,8 +80,7 @@ SDL_NewDataQueue(const size_t _packetlen, const size_t initialslack)
return queue; return queue;
} }
void void SDL_FreeDataQueue(SDL_DataQueue *queue)
SDL_FreeDataQueue(SDL_DataQueue *queue)
{ {
if (queue) { if (queue) {
SDL_FreeDataQueueList(queue->head); SDL_FreeDataQueueList(queue->head);
@@ -92,11 +89,10 @@ SDL_FreeDataQueue(SDL_DataQueue *queue)
} }
} }
void void SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack)
SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack)
{ {
const size_t packet_size = queue ? queue->packet_size : 1; const size_t packet_size = queue ? queue->packet_size : 1;
const size_t slackpackets = (slack + (packet_size-1)) / packet_size; const size_t slackpackets = (slack + (packet_size - 1)) / packet_size;
SDL_DataQueuePacket *packet; SDL_DataQueuePacket *packet;
SDL_DataQueuePacket *prev = NULL; SDL_DataQueuePacket *prev = NULL;
size_t i; size_t i;
@@ -135,8 +131,7 @@ SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack)
SDL_FreeDataQueueList(packet); /* free extra packets */ SDL_FreeDataQueueList(packet); /* free extra packets */
} }
static SDL_DataQueuePacket * static SDL_DataQueuePacket *AllocateDataQueuePacket(SDL_DataQueue *queue)
AllocateDataQueuePacket(SDL_DataQueue *queue)
{ {
SDL_DataQueuePacket *packet; SDL_DataQueuePacket *packet;
@@ -148,7 +143,7 @@ AllocateDataQueuePacket(SDL_DataQueue *queue)
queue->pool = packet->next; queue->pool = packet->next;
} else { } else {
/* Have to allocate a new one! */ /* Have to allocate a new one! */
packet = (SDL_DataQueuePacket *) SDL_malloc(sizeof (SDL_DataQueuePacket) + queue->packet_size); packet = (SDL_DataQueuePacket *)SDL_malloc(sizeof(SDL_DataQueuePacket) + queue->packet_size);
if (packet == NULL) { if (packet == NULL) {
return NULL; return NULL;
} }
@@ -168,12 +163,10 @@ AllocateDataQueuePacket(SDL_DataQueue *queue)
return packet; return packet;
} }
int SDL_WriteToDataQueue(SDL_DataQueue *queue, const void *_data, const size_t _len)
int
SDL_WriteToDataQueue(SDL_DataQueue *queue, const void *_data, const size_t _len)
{ {
size_t len = _len; size_t len = _len;
const Uint8 *data = (const Uint8 *) _data; const Uint8 *data = (const Uint8 *)_data;
const size_t packet_size = queue ? queue->packet_size : 0; const size_t packet_size = queue ? queue->packet_size : 0;
SDL_DataQueuePacket *orighead; SDL_DataQueuePacket *orighead;
SDL_DataQueuePacket *origtail; SDL_DataQueuePacket *origtail;
@@ -227,7 +220,7 @@ size_t
SDL_PeekIntoDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len) SDL_PeekIntoDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len)
{ {
size_t len = _len; size_t len = _len;
Uint8 *buf = (Uint8 *) _buf; Uint8 *buf = (Uint8 *)_buf;
Uint8 *ptr = buf; Uint8 *ptr = buf;
SDL_DataQueuePacket *packet; SDL_DataQueuePacket *packet;
@@ -245,14 +238,14 @@ SDL_PeekIntoDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len)
len -= cpy; len -= cpy;
} }
return (size_t) (ptr - buf); return (size_t)(ptr - buf);
} }
size_t size_t
SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len) SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len)
{ {
size_t len = _len; size_t len = _len;
Uint8 *buf = (Uint8 *) _buf; Uint8 *buf = (Uint8 *)_buf;
Uint8 *ptr = buf; Uint8 *ptr = buf;
SDL_DataQueuePacket *packet; SDL_DataQueuePacket *packet;
@@ -285,7 +278,7 @@ SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len)
queue->tail = NULL; /* in case we drained the queue entirely. */ queue->tail = NULL; /* in case we drained the queue entirely. */
} }
return (size_t) (ptr - buf); return (size_t)(ptr - buf);
} }
size_t size_t
@@ -334,4 +327,3 @@ SDL_ReserveSpaceInDataQueue(SDL_DataQueue *queue, const size_t len)
} }
/* vi: set ts=4 sw=4 expandtab: */ /* vi: set ts=4 sw=4 expandtab: */

View File

@@ -52,4 +52,3 @@ void *SDL_ReserveSpaceInDataQueue(SDL_DataQueue *queue, const size_t len);
#endif /* SDL_dataqueue_h_ */ #endif /* SDL_dataqueue_h_ */
/* vi: set ts=4 sw=4 expandtab: */ /* vi: set ts=4 sw=4 expandtab: */

View File

@@ -24,8 +24,7 @@
#include "SDL_error_c.h" #include "SDL_error_c.h"
int int SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{ {
/* Ignore call if invalid format pointer was passed */ /* Ignore call if invalid format pointer was passed */
if (fmt != NULL) { if (fmt != NULL) {
@@ -51,7 +50,6 @@ SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
} }
} }
if (SDL_LogGetPriority(SDL_LOG_CATEGORY_ERROR) <= SDL_LOG_PRIORITY_DEBUG) { if (SDL_LogGetPriority(SDL_LOG_CATEGORY_ERROR) <= SDL_LOG_PRIORITY_DEBUG) {
/* If we are in debug mode, print out the error message */ /* If we are in debug mode, print out the error message */
SDL_LogDebug(SDL_LOG_CATEGORY_ERROR, "%s", error->str); SDL_LogDebug(SDL_LOG_CATEGORY_ERROR, "%s", error->str);
@@ -69,15 +67,13 @@ SDL_GetError(void)
return error->error ? error->str : ""; return error->error ? error->str : "";
} }
void void SDL_ClearError(void)
SDL_ClearError(void)
{ {
SDL_GetErrBuf()->error = 0; SDL_GetErrBuf()->error = 0;
} }
/* Very common errors go here */ /* Very common errors go here */
int int SDL_Error(SDL_errorcode code)
SDL_Error(SDL_errorcode code)
{ {
switch (code) { switch (code) {
case SDL_ENOMEM: case SDL_ENOMEM:
@@ -96,8 +92,7 @@ SDL_Error(SDL_errorcode code)
} }
#ifdef TEST_ERROR #ifdef TEST_ERROR
int int main(int argc, char *argv[])
main(int argc, char *argv[])
{ {
char buffer[BUFSIZ + 1]; char buffer[BUFSIZ + 1];
@@ -112,7 +107,6 @@ main(int argc, char *argv[])
} }
#endif #endif
char * char *
SDL_GetErrorMsg(char *errstr, int maxlen) SDL_GetErrorMsg(char *errstr, int maxlen)
{ {

View File

@@ -20,8 +20,6 @@
*/ */
#include "SDL_internal.h" #include "SDL_internal.h"
/* convert the guid to a printable string */ /* convert the guid to a printable string */
void SDL_GUIDToString(SDL_GUID guid, char *pszGUID, int cbGUID) void SDL_GUIDToString(SDL_GUID guid, char *pszGUID, int cbGUID)
{ {
@@ -32,7 +30,7 @@ void SDL_GUIDToString(SDL_GUID guid, char *pszGUID, int cbGUID)
return; return;
} }
for (i = 0; i < sizeof(guid.data) && i < (cbGUID-1)/2; i++) { for (i = 0; i < sizeof(guid.data) && i < (cbGUID - 1) / 2; i++) {
/* each input byte writes 2 ascii chars, and might write a null byte. */ /* each input byte writes 2 ascii chars, and might write a null byte. */
/* If we don't have room for next input byte, stop */ /* If we don't have room for next input byte, stop */
unsigned char c = guid.data[i]; unsigned char c = guid.data[i];
@@ -71,7 +69,7 @@ static unsigned char nibble(unsigned char c)
SDL_GUID SDL_GUIDFromString(const char *pchGUID) SDL_GUID SDL_GUIDFromString(const char *pchGUID)
{ {
SDL_GUID guid; SDL_GUID guid;
int maxoutputbytes= sizeof(guid); int maxoutputbytes = sizeof(guid);
size_t len = SDL_strlen(pchGUID); size_t len = SDL_strlen(pchGUID);
Uint8 *p; Uint8 *p;
size_t i; size_t i;
@@ -82,8 +80,8 @@ SDL_GUID SDL_GUIDFromString(const char *pchGUID)
SDL_memset(&guid, 0x00, sizeof(guid)); SDL_memset(&guid, 0x00, sizeof(guid));
p = (Uint8 *)&guid; p = (Uint8 *)&guid;
for (i = 0; (i < len) && ((p - (Uint8 *)&guid) < maxoutputbytes); i+=2, p++) { for (i = 0; (i < len) && ((p - (Uint8 *)&guid) < maxoutputbytes); i += 2, p++) {
*p = (nibble((unsigned char)pchGUID[i]) << 4) | nibble((unsigned char)pchGUID[i+1]); *p = (nibble((unsigned char)pchGUID[i]) << 4) | nibble((unsigned char)pchGUID[i + 1]);
} }
return guid; return guid;

View File

@@ -22,17 +22,18 @@
#include "SDL_hints_c.h" #include "SDL_hints_c.h"
/* Assuming there aren't many hints set and they aren't being queried in /* Assuming there aren't many hints set and they aren't being queried in
critical performance paths, we'll just use linked lists here. critical performance paths, we'll just use linked lists here.
*/ */
typedef struct SDL_HintWatch { typedef struct SDL_HintWatch
{
SDL_HintCallback callback; SDL_HintCallback callback;
void *userdata; void *userdata;
struct SDL_HintWatch *next; struct SDL_HintWatch *next;
} SDL_HintWatch; } SDL_HintWatch;
typedef struct SDL_Hint { typedef struct SDL_Hint
{
char *name; char *name;
char *value; char *value;
SDL_HintPriority priority; SDL_HintPriority priority;
@@ -66,7 +67,7 @@ SDL_SetHintWithPriority(const char *name, const char *value,
} }
if (hint->value != value && if (hint->value != value &&
(value == NULL || !hint->value || SDL_strcmp(hint->value, value) != 0)) { (value == NULL || !hint->value || SDL_strcmp(hint->value, value) != 0)) {
for (entry = hint->callbacks; entry; ) { for (entry = hint->callbacks; entry;) {
/* Save the next entry in case this one is deleted */ /* Save the next entry in case this one is deleted */
SDL_HintWatch *next = entry->next; SDL_HintWatch *next = entry->next;
entry->callback(entry->userdata, name, hint->value, value); entry->callback(entry->userdata, name, hint->value, value);
@@ -111,7 +112,7 @@ SDL_ResetHint(const char *name)
if ((env == NULL && hint->value != NULL) || if ((env == NULL && hint->value != NULL) ||
(env != NULL && hint->value == NULL) || (env != NULL && hint->value == NULL) ||
(env != NULL && SDL_strcmp(env, hint->value) != 0)) { (env != NULL && SDL_strcmp(env, hint->value) != 0)) {
for (entry = hint->callbacks; entry; ) { for (entry = hint->callbacks; entry;) {
/* Save the next entry in case this one is deleted */ /* Save the next entry in case this one is deleted */
SDL_HintWatch *next = entry->next; SDL_HintWatch *next = entry->next;
entry->callback(entry->userdata, name, hint->value, env); entry->callback(entry->userdata, name, hint->value, env);
@@ -127,8 +128,7 @@ SDL_ResetHint(const char *name)
return SDL_FALSE; return SDL_FALSE;
} }
void void SDL_ResetHints(void)
SDL_ResetHints(void)
{ {
const char *env; const char *env;
SDL_Hint *hint; SDL_Hint *hint;
@@ -139,7 +139,7 @@ SDL_ResetHints(void)
if ((env == NULL && hint->value != NULL) || if ((env == NULL && hint->value != NULL) ||
(env != NULL && hint->value == NULL) || (env != NULL && hint->value == NULL) ||
(env != NULL && SDL_strcmp(env, hint->value) != 0)) { (env != NULL && SDL_strcmp(env, hint->value) != 0)) {
for (entry = hint->callbacks; entry; ) { for (entry = hint->callbacks; entry;) {
/* Save the next entry in case this one is deleted */ /* Save the next entry in case this one is deleted */
SDL_HintWatch *next = entry->next; SDL_HintWatch *next = entry->next;
entry->callback(entry->userdata, hint->name, hint->value, env); entry->callback(entry->userdata, hint->name, hint->value, env);
@@ -195,8 +195,7 @@ SDL_GetHintBoolean(const char *name, SDL_bool default_value)
return SDL_GetStringBoolean(hint, default_value); return SDL_GetStringBoolean(hint, default_value);
} }
void void SDL_AddHintCallback(const char *name, SDL_HintCallback callback, void *userdata)
SDL_AddHintCallback(const char *name, SDL_HintCallback callback, void *userdata)
{ {
SDL_Hint *hint; SDL_Hint *hint;
SDL_HintWatch *entry; SDL_HintWatch *entry;
@@ -257,8 +256,7 @@ SDL_AddHintCallback(const char *name, SDL_HintCallback callback, void *userdata)
callback(userdata, name, value, value); callback(userdata, name, value, value);
} }
void void SDL_DelHintCallback(const char *name, SDL_HintCallback callback, void *userdata)
SDL_DelHintCallback(const char *name, SDL_HintCallback callback, void *userdata)
{ {
SDL_Hint *hint; SDL_Hint *hint;
SDL_HintWatch *entry, *prev; SDL_HintWatch *entry, *prev;
@@ -294,7 +292,7 @@ void SDL_ClearHints(void)
SDL_free(hint->name); SDL_free(hint->name);
SDL_free(hint->value); SDL_free(hint->value);
for (entry = hint->callbacks; entry; ) { for (entry = hint->callbacks; entry;) {
SDL_HintWatch *freeable = entry; SDL_HintWatch *freeable = entry;
entry = entry->next; entry = entry->next;
SDL_free(freeable); SDL_free(freeable);

View File

@@ -41,8 +41,13 @@
#endif #endif
#define SDL_MAX_SMALL_ALLOC_STACKSIZE 128 #define SDL_MAX_SMALL_ALLOC_STACKSIZE 128
#define SDL_small_alloc(type, count, pisstack) ( (*(pisstack) = ((sizeof(type)*(count)) < SDL_MAX_SMALL_ALLOC_STACKSIZE)), (*(pisstack) ? SDL_stack_alloc(type, count) : (type*)SDL_malloc(sizeof(type)*(count))) ) #define SDL_small_alloc(type, count, pisstack) ((*(pisstack) = ((sizeof(type) * (count)) < SDL_MAX_SMALL_ALLOC_STACKSIZE)), (*(pisstack) ? SDL_stack_alloc(type, count) : (type *)SDL_malloc(sizeof(type) * (count))))
#define SDL_small_free(ptr, isstack) if ((isstack)) { SDL_stack_free(ptr); } else { SDL_free(ptr); } #define SDL_small_free(ptr, isstack) \
if ((isstack)) { \
SDL_stack_free(ptr); \
} else { \
SDL_free(ptr); \
}
#include "dynapi/SDL_dynapi.h" #include "dynapi/SDL_dynapi.h"
@@ -68,44 +73,43 @@
#include <stdio.h> #include <stdio.h>
#endif #endif
#if defined(HAVE_STDLIB_H) #if defined(HAVE_STDLIB_H)
# include <stdlib.h> #include <stdlib.h>
#elif defined(HAVE_MALLOC_H) #elif defined(HAVE_MALLOC_H)
# include <malloc.h> #include <malloc.h>
#endif #endif
#if defined(HAVE_STDDEF_H) #if defined(HAVE_STDDEF_H)
# include <stddef.h> #include <stddef.h>
#endif #endif
#if defined(HAVE_STDARG_H) #if defined(HAVE_STDARG_H)
# include <stdarg.h> #include <stdarg.h>
#endif #endif
#ifdef HAVE_STRING_H #ifdef HAVE_STRING_H
# ifdef HAVE_MEMORY_H #ifdef HAVE_MEMORY_H
# include <memory.h> #include <memory.h>
# endif #endif
# include <string.h> #include <string.h>
#endif #endif
#ifdef HAVE_STRINGS_H #ifdef HAVE_STRINGS_H
# include <strings.h> #include <strings.h>
#endif #endif
#ifdef HAVE_WCHAR_H #ifdef HAVE_WCHAR_H
# include <wchar.h> #include <wchar.h>
#endif #endif
#if defined(HAVE_INTTYPES_H) #if defined(HAVE_INTTYPES_H)
# include <inttypes.h> #include <inttypes.h>
#elif defined(HAVE_STDINT_H) #elif defined(HAVE_STDINT_H)
# include <stdint.h> #include <stdint.h>
#endif #endif
#ifdef HAVE_CTYPE_H #ifdef HAVE_CTYPE_H
# include <ctype.h> #include <ctype.h>
#endif #endif
#ifdef HAVE_MATH_H #ifdef HAVE_MATH_H
# include <math.h> #include <math.h>
#endif #endif
#ifdef HAVE_FLOAT_H #ifdef HAVE_FLOAT_H
# include <float.h> #include <float.h>
#endif #endif
/* If you run into a warning that O_CLOEXEC is redefined, update the SDL configuration header for your platform to add HAVE_O_CLOEXEC */ /* If you run into a warning that O_CLOEXEC is redefined, update the SDL configuration header for your platform to add HAVE_O_CLOEXEC */
#ifndef HAVE_O_CLOEXEC #ifndef HAVE_O_CLOEXEC
#define O_CLOEXEC 0 #define O_CLOEXEC 0

View File

@@ -23,10 +23,9 @@
#include "./SDL_list.h" #include "./SDL_list.h"
/* Push */ /* Push */
int int SDL_ListAdd(SDL_ListNode **head, void *ent)
SDL_ListAdd(SDL_ListNode **head, void *ent)
{ {
SDL_ListNode *node = SDL_malloc(sizeof (*node)); SDL_ListNode *node = SDL_malloc(sizeof(*node));
if (node == NULL) { if (node == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
@@ -39,8 +38,7 @@ SDL_ListAdd(SDL_ListNode **head, void *ent)
} }
/* Pop from end as a FIFO (if add with SDL_ListAdd) */ /* Pop from end as a FIFO (if add with SDL_ListAdd) */
void void SDL_ListPop(SDL_ListNode **head, void **ent)
SDL_ListPop(SDL_ListNode **head, void **ent)
{ {
SDL_ListNode **ptr = head; SDL_ListNode **ptr = head;
@@ -61,8 +59,7 @@ SDL_ListPop(SDL_ListNode **head, void **ent)
*ptr = NULL; *ptr = NULL;
} }
void void SDL_ListRemove(SDL_ListNode **head, void *ent)
SDL_ListRemove(SDL_ListNode **head, void *ent)
{ {
SDL_ListNode **ptr = head; SDL_ListNode **ptr = head;
@@ -77,8 +74,7 @@ SDL_ListRemove(SDL_ListNode **head, void *ent)
} }
} }
void void SDL_ListClear(SDL_ListNode **head)
SDL_ListClear(SDL_ListNode **head)
{ {
SDL_ListNode *l = *head; SDL_ListNode *l = *head;
*head = NULL; *head = NULL;

View File

@@ -28,7 +28,6 @@ typedef struct SDL_ListNode
struct SDL_ListNode *next; struct SDL_ListNode *next;
} SDL_ListNode; } SDL_ListNode;
int SDL_ListAdd(SDL_ListNode **head, void *ent); int SDL_ListAdd(SDL_ListNode **head, void *ent);
void SDL_ListPop(SDL_ListNode **head, void **ent); void SDL_ListPop(SDL_ListNode **head, void **ent);
void SDL_ListRemove(SDL_ListNode **head, void *ent); void SDL_ListRemove(SDL_ListNode **head, void *ent);

View File

@@ -38,7 +38,6 @@
#include "stdlib/SDL_vacopy.h" #include "stdlib/SDL_vacopy.h"
/* The size of the stack buffer to use for rendering log messages. */ /* The size of the stack buffer to use for rendering log messages. */
#define SDL_MAX_LOG_MESSAGE_STACK 256 #define SDL_MAX_LOG_MESSAGE_STACK 256
@@ -102,8 +101,7 @@ static int SDL_android_priority[SDL_NUM_LOG_PRIORITIES] = {
}; };
#endif /* __ANDROID__ */ #endif /* __ANDROID__ */
void void SDL_LogInit(void)
SDL_LogInit(void)
{ {
if (log_function_mutex == NULL) { if (log_function_mutex == NULL) {
/* if this fails we'll try to continue without it. */ /* if this fails we'll try to continue without it. */
@@ -111,8 +109,7 @@ SDL_LogInit(void)
} }
} }
void void SDL_LogQuit(void)
SDL_LogQuit(void)
{ {
SDL_LogResetPriorities(); SDL_LogResetPriorities();
if (log_function_mutex) { if (log_function_mutex) {
@@ -121,8 +118,7 @@ SDL_LogQuit(void)
} }
} }
void void SDL_LogSetAllPriority(SDL_LogPriority priority)
SDL_LogSetAllPriority(SDL_LogPriority priority)
{ {
SDL_LogLevel *entry; SDL_LogLevel *entry;
@@ -134,8 +130,7 @@ SDL_LogSetAllPriority(SDL_LogPriority priority)
SDL_application_priority = priority; SDL_application_priority = priority;
} }
void void SDL_LogSetPriority(int category, SDL_LogPriority priority)
SDL_LogSetPriority(int category, SDL_LogPriority priority)
{ {
SDL_LogLevel *entry; SDL_LogLevel *entry;
@@ -178,8 +173,7 @@ SDL_LogGetPriority(int category)
} }
} }
void void SDL_LogResetPriorities(void)
SDL_LogResetPriorities(void)
{ {
SDL_LogLevel *entry; SDL_LogLevel *entry;
@@ -195,8 +189,7 @@ SDL_LogResetPriorities(void)
SDL_test_priority = DEFAULT_TEST_PRIORITY; SDL_test_priority = DEFAULT_TEST_PRIORITY;
} }
void void SDL_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
SDL_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{ {
va_list ap; va_list ap;
@@ -205,8 +198,7 @@ SDL_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
va_end(ap); va_end(ap);
} }
void void SDL_LogVerbose(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
SDL_LogVerbose(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{ {
va_list ap; va_list ap;
@@ -215,8 +207,7 @@ SDL_LogVerbose(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
va_end(ap); va_end(ap);
} }
void void SDL_LogDebug(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
SDL_LogDebug(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{ {
va_list ap; va_list ap;
@@ -225,8 +216,7 @@ SDL_LogDebug(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
va_end(ap); va_end(ap);
} }
void void SDL_LogInfo(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
SDL_LogInfo(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{ {
va_list ap; va_list ap;
@@ -235,8 +225,7 @@ SDL_LogInfo(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
va_end(ap); va_end(ap);
} }
void void SDL_LogWarn(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
SDL_LogWarn(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{ {
va_list ap; va_list ap;
@@ -245,8 +234,7 @@ SDL_LogWarn(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
va_end(ap); va_end(ap);
} }
void void SDL_LogError(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
SDL_LogError(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{ {
va_list ap; va_list ap;
@@ -255,8 +243,7 @@ SDL_LogError(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
va_end(ap); va_end(ap);
} }
void void SDL_LogCritical(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
SDL_LogCritical(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{ {
va_list ap; va_list ap;
@@ -265,8 +252,7 @@ SDL_LogCritical(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
va_end(ap); va_end(ap);
} }
void void SDL_LogMessage(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
SDL_LogMessage(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{ {
va_list ap; va_list ap;
@@ -276,8 +262,7 @@ SDL_LogMessage(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING
} }
#ifdef __ANDROID__ #ifdef __ANDROID__
static const char * static const char *GetCategoryPrefix(int category)
GetCategoryPrefix(int category)
{ {
if (category < SDL_LOG_CATEGORY_RESERVED1) { if (category < SDL_LOG_CATEGORY_RESERVED1) {
return SDL_category_prefixes[category]; return SDL_category_prefixes[category];
@@ -289,8 +274,7 @@ GetCategoryPrefix(int category)
} }
#endif /* __ANDROID__ */ #endif /* __ANDROID__ */
void void SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list ap)
SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list ap)
{ {
char *message = NULL; char *message = NULL;
char stack_buf[SDL_MAX_LOG_MESSAGE_STACK]; char stack_buf[SDL_MAX_LOG_MESSAGE_STACK];
@@ -342,9 +326,9 @@ SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list
} }
/* Chop off final endline. */ /* Chop off final endline. */
if ((len > 0) && (message[len-1] == '\n')) { if ((len > 0) && (message[len - 1] == '\n')) {
message[--len] = '\0'; message[--len] = '\0';
if ((len > 0) && (message[len-1] == '\r')) { /* catch "\r\n", too. */ if ((len > 0) && (message[len - 1] == '\r')) { /* catch "\r\n", too. */
message[--len] = '\0'; message[--len] = '\0';
} }
} }
@@ -373,8 +357,7 @@ static int consoleAttached = 0;
static HANDLE stderrHandle = NULL; static HANDLE stderrHandle = NULL;
#endif #endif
static void SDLCALL static void SDLCALL SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
const char *message) const char *message)
{ {
#if defined(__WIN32__) || defined(__WINRT__) || defined(__GDK__) #if defined(__WIN32__) || defined(__WINRT__) || defined(__GDK__)
@@ -438,7 +421,7 @@ SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
#if !defined(HAVE_STDIO_H) && !defined(__WINRT__) && !defined(__GDK__) #if !defined(HAVE_STDIO_H) && !defined(__WINRT__) && !defined(__GDK__)
/* Screen output to stderr, if console was attached. */ /* Screen output to stderr, if console was attached. */
if (consoleAttached == 1) { if (consoleAttached == 1) {
if (!WriteConsole(stderrHandle, tstr, (DWORD) SDL_tcslen(tstr), &charsWritten, NULL)) { if (!WriteConsole(stderrHandle, tstr, (DWORD)SDL_tcslen(tstr), &charsWritten, NULL)) {
OutputDebugString(TEXT("Error calling WriteConsole\r\n")); OutputDebugString(TEXT("Error calling WriteConsole\r\n"));
if (GetLastError() == ERROR_NOT_ENOUGH_MEMORY) { if (GetLastError() == ERROR_NOT_ENOUGH_MEMORY) {
OutputDebugString(TEXT("Insufficient heap memory to write message\r\n")); OutputDebugString(TEXT("Insufficient heap memory to write message\r\n"));
@@ -446,7 +429,7 @@ SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
} }
} else if (consoleAttached == 2) { } else if (consoleAttached == 2) {
if (!WriteFile(stderrHandle, output, (DWORD) SDL_strlen(output), &charsWritten, NULL)) { if (!WriteFile(stderrHandle, output, (DWORD)SDL_strlen(output), &charsWritten, NULL)) {
OutputDebugString(TEXT("Error calling WriteFile\r\n")); OutputDebugString(TEXT("Error calling WriteFile\r\n"));
} }
} }
@@ -472,17 +455,17 @@ SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
} }
#elif defined(__PSP__) || defined(__PS2__) #elif defined(__PSP__) || defined(__PS2__)
{ {
FILE* pFile; FILE *pFile;
pFile = fopen ("SDL_Log.txt", "a"); pFile = fopen("SDL_Log.txt", "a");
fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message); fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message);
fclose (pFile); fclose(pFile);
} }
#elif defined(__VITA__) #elif defined(__VITA__)
{ {
FILE* pFile; FILE *pFile;
pFile = fopen ("ux0:/data/SDL_Log.txt", "a"); pFile = fopen("ux0:/data/SDL_Log.txt", "a");
fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message); fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message);
fclose (pFile); fclose(pFile);
} }
#elif defined(__3DS__) #elif defined(__3DS__)
{ {
@@ -503,8 +486,7 @@ SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
#endif #endif
} }
void void SDL_LogGetOutputFunction(SDL_LogOutputFunction *callback, void **userdata)
SDL_LogGetOutputFunction(SDL_LogOutputFunction *callback, void **userdata)
{ {
if (callback) { if (callback) {
*callback = SDL_log_function; *callback = SDL_log_function;
@@ -514,8 +496,7 @@ SDL_LogGetOutputFunction(SDL_LogOutputFunction *callback, void **userdata)
} }
} }
void void SDL_LogSetOutputFunction(SDL_LogOutputFunction callback, void *userdata)
SDL_LogSetOutputFunction(SDL_LogOutputFunction callback, void *userdata)
{ {
SDL_log_function = callback; SDL_log_function = callback;
SDL_log_userdata = userdata; SDL_log_userdata = userdata;

View File

@@ -20,7 +20,6 @@
*/ */
#include "SDL_internal.h" #include "SDL_internal.h"
#if defined(_MSC_VER) && (_MSC_VER >= 1500) #if defined(_MSC_VER) && (_MSC_VER >= 1500)
#include <intrin.h> #include <intrin.h>
#define HAVE_MSC_ATOMICS 1 #define HAVE_MSC_ATOMICS 1
@@ -36,19 +35,20 @@
/* The __atomic_load_n() intrinsic showed up in different times for different compilers. */ /* The __atomic_load_n() intrinsic showed up in different times for different compilers. */
#if defined(__clang__) #if defined(__clang__)
# if __has_builtin(__atomic_load_n) || defined(HAVE_GCC_ATOMICS) #if __has_builtin(__atomic_load_n) || defined(HAVE_GCC_ATOMICS)
/* !!! FIXME: this advertises as available in the NDK but uses an external symbol we don't have. /* !!! FIXME: this advertises as available in the NDK but uses an external symbol we don't have.
It might be in a later NDK or we might need an extra library? --ryan. */ It might be in a later NDK or we might need an extra library? --ryan. */
# if !defined(__ANDROID__) #if !defined(__ANDROID__)
# define HAVE_ATOMIC_LOAD_N 1 #define HAVE_ATOMIC_LOAD_N 1
# endif #endif
# endif #endif
#elif defined(__GNUC__) #elif defined(__GNUC__)
# if (__GNUC__ >= 5) #if (__GNUC__ >= 5)
# define HAVE_ATOMIC_LOAD_N 1 #define HAVE_ATOMIC_LOAD_N 1
# endif #endif
#endif #endif
/* *INDENT-OFF* */ /* clang-format off */
#if defined(__WATCOMC__) && defined(__386__) #if defined(__WATCOMC__) && defined(__386__)
SDL_COMPILE_TIME_ASSERT(intsize, 4==sizeof(int)); SDL_COMPILE_TIME_ASSERT(intsize, 4==sizeof(int));
#define HAVE_WATCOM_ATOMICS #define HAVE_WATCOM_ATOMICS
@@ -73,7 +73,9 @@ extern __inline int _SDL_xadd_watcom(volatile int *a, int v);
parm [ecx] [eax] \ parm [ecx] [eax] \
value [eax] \ value [eax] \
modify exact [eax]; modify exact [eax];
#endif /* __WATCOMC__ && __386__ */ #endif /* __WATCOMC__ && __386__ */
/* *INDENT-ON* */ /* clang-format on */
/* /*
If any of the operations are not provided then we must emulate some If any of the operations are not provided then we must emulate some
@@ -105,16 +107,14 @@ extern __inline int _SDL_xadd_watcom(volatile int *a, int v);
#if EMULATE_CAS #if EMULATE_CAS
static SDL_SpinLock locks[32]; static SDL_SpinLock locks[32];
static SDL_INLINE void static SDL_INLINE void enterLock(void *a)
enterLock(void *a)
{ {
uintptr_t index = ((((uintptr_t)a) >> 3) & 0x1f); uintptr_t index = ((((uintptr_t)a) >> 3) & 0x1f);
SDL_AtomicLock(&locks[index]); SDL_AtomicLock(&locks[index]);
} }
static SDL_INLINE void static SDL_INLINE void leaveLock(void *a)
leaveLock(void *a)
{ {
uintptr_t index = ((((uintptr_t)a) >> 3) & 0x1f); uintptr_t index = ((((uintptr_t)a) >> 3) & 0x1f);
@@ -122,7 +122,6 @@ leaveLock(void *a)
} }
#endif #endif
SDL_bool SDL_bool
SDL_AtomicCAS(SDL_atomic_t *a, int oldval, int newval) SDL_AtomicCAS(SDL_atomic_t *a, int oldval, int newval)
{ {
@@ -132,9 +131,9 @@ SDL_AtomicCAS(SDL_atomic_t *a, int oldval, int newval)
#elif defined(HAVE_WATCOM_ATOMICS) #elif defined(HAVE_WATCOM_ATOMICS)
return (SDL_bool)_SDL_cmpxchg_watcom(&a->value, newval, oldval); return (SDL_bool)_SDL_cmpxchg_watcom(&a->value, newval, oldval);
#elif defined(HAVE_GCC_ATOMICS) #elif defined(HAVE_GCC_ATOMICS)
return (SDL_bool) __sync_bool_compare_and_swap(&a->value, oldval, newval); return (SDL_bool)__sync_bool_compare_and_swap(&a->value, oldval, newval);
#elif defined(__MACOS__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */ #elif defined(__MACOS__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */
return (SDL_bool) OSAtomicCompareAndSwap32Barrier(oldval, newval, &a->value); return (SDL_bool)OSAtomicCompareAndSwap32Barrier(oldval, newval, &a->value);
#elif defined(__SOLARIS__) #elif defined(__SOLARIS__)
return (SDL_bool)((int)atomic_cas_uint((volatile uint_t *)&a->value, (uint_t)oldval, (uint_t)newval) == oldval); return (SDL_bool)((int)atomic_cas_uint((volatile uint_t *)&a->value, (uint_t)oldval, (uint_t)newval) == oldval);
#elif EMULATE_CAS #elif EMULATE_CAS
@@ -149,7 +148,7 @@ SDL_AtomicCAS(SDL_atomic_t *a, int oldval, int newval)
return retval; return retval;
#else #else
#error Please define your platform. #error Please define your platform.
#endif #endif
} }
@@ -163,9 +162,9 @@ SDL_AtomicCASPtr(void **a, void *oldval, void *newval)
#elif defined(HAVE_GCC_ATOMICS) #elif defined(HAVE_GCC_ATOMICS)
return __sync_bool_compare_and_swap(a, oldval, newval); return __sync_bool_compare_and_swap(a, oldval, newval);
#elif defined(__MACOS__) && defined(__LP64__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */ #elif defined(__MACOS__) && defined(__LP64__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */
return (SDL_bool) OSAtomicCompareAndSwap64Barrier((int64_t)oldval, (int64_t)newval, (int64_t*) a); return (SDL_bool)OSAtomicCompareAndSwap64Barrier((int64_t)oldval, (int64_t)newval, (int64_t *)a);
#elif defined(__MACOS__) && !defined(__LP64__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */ #elif defined(__MACOS__) && !defined(__LP64__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */
return (SDL_bool) OSAtomicCompareAndSwap32Barrier((int32_t)oldval, (int32_t)newval, (int32_t*) a); return (SDL_bool)OSAtomicCompareAndSwap32Barrier((int32_t)oldval, (int32_t)newval, (int32_t *)a);
#elif defined(__SOLARIS__) #elif defined(__SOLARIS__)
return (SDL_bool)(atomic_cas_ptr(a, oldval, newval) == oldval); return (SDL_bool)(atomic_cas_ptr(a, oldval, newval) == oldval);
#elif EMULATE_CAS #elif EMULATE_CAS
@@ -180,12 +179,11 @@ SDL_AtomicCASPtr(void **a, void *oldval, void *newval)
return retval; return retval;
#else #else
#error Please define your platform. #error Please define your platform.
#endif #endif
} }
int int SDL_AtomicSet(SDL_atomic_t *a, int v)
SDL_AtomicSet(SDL_atomic_t *a, int v)
{ {
#ifdef HAVE_MSC_ATOMICS #ifdef HAVE_MSC_ATOMICS
SDL_COMPILE_TIME_ASSERT(atomic_set, sizeof(long) == sizeof(a->value)); SDL_COMPILE_TIME_ASSERT(atomic_set, sizeof(long) == sizeof(a->value));
@@ -205,7 +203,7 @@ SDL_AtomicSet(SDL_atomic_t *a, int v)
#endif #endif
} }
void* void *
SDL_AtomicSetPtr(void **a, void *v) SDL_AtomicSetPtr(void **a, void *v)
{ {
#if defined(HAVE_MSC_ATOMICS) #if defined(HAVE_MSC_ATOMICS)
@@ -225,8 +223,7 @@ SDL_AtomicSetPtr(void **a, void *v)
#endif #endif
} }
int int SDL_AtomicAdd(SDL_atomic_t *a, int v)
SDL_AtomicAdd(SDL_atomic_t *a, int v)
{ {
#ifdef HAVE_MSC_ATOMICS #ifdef HAVE_MSC_ATOMICS
SDL_COMPILE_TIME_ASSERT(atomic_add, sizeof(long) == sizeof(a->value)); SDL_COMPILE_TIME_ASSERT(atomic_add, sizeof(long) == sizeof(a->value));
@@ -238,7 +235,7 @@ SDL_AtomicAdd(SDL_atomic_t *a, int v)
#elif defined(__SOLARIS__) #elif defined(__SOLARIS__)
int pv = a->value; int pv = a->value;
membar_consumer(); membar_consumer();
atomic_add_int((volatile uint_t*)&a->value, v); atomic_add_int((volatile uint_t *)&a->value, v);
return pv; return pv;
#else #else
int value; int value;
@@ -249,8 +246,7 @@ SDL_AtomicAdd(SDL_atomic_t *a, int v)
#endif #endif
} }
int int SDL_AtomicGet(SDL_atomic_t *a)
SDL_AtomicGet(SDL_atomic_t *a)
{ {
#ifdef HAVE_ATOMIC_LOAD_N #ifdef HAVE_ATOMIC_LOAD_N
return __atomic_load_n(&a->value, __ATOMIC_SEQ_CST); return __atomic_load_n(&a->value, __ATOMIC_SEQ_CST);
@@ -298,14 +294,12 @@ SDL_AtomicGetPtr(void **a)
#error This file should be built in arm mode so the mcr instruction is available for memory barriers #error This file should be built in arm mode so the mcr instruction is available for memory barriers
#endif #endif
void void SDL_MemoryBarrierReleaseFunction(void)
SDL_MemoryBarrierReleaseFunction(void)
{ {
SDL_MemoryBarrierRelease(); SDL_MemoryBarrierRelease();
} }
void void SDL_MemoryBarrierAcquireFunction(void)
SDL_MemoryBarrierAcquireFunction(void)
{ {
SDL_MemoryBarrierAcquire(); SDL_MemoryBarrierAcquire();
} }

View File

@@ -24,7 +24,6 @@
#include "../core/windows/SDL_windows.h" #include "../core/windows/SDL_windows.h"
#endif #endif
#if !defined(HAVE_GCC_ATOMICS) && defined(__SOLARIS__) #if !defined(HAVE_GCC_ATOMICS) && defined(__SOLARIS__)
#include <atomic.h> #include <atomic.h>
#endif #endif
@@ -45,6 +44,7 @@
#include <libkern/OSAtomic.h> #include <libkern/OSAtomic.h>
#endif #endif
/* *INDENT-OFF* */ /* clang-format off */
#if defined(__WATCOMC__) && defined(__386__) #if defined(__WATCOMC__) && defined(__386__)
SDL_COMPILE_TIME_ASSERT(locksize, 4==sizeof(SDL_SpinLock)); SDL_COMPILE_TIME_ASSERT(locksize, 4==sizeof(SDL_SpinLock));
extern __inline int _SDL_xchg_watcom(volatile int *a, int v); extern __inline int _SDL_xchg_watcom(volatile int *a, int v);
@@ -54,6 +54,7 @@ extern __inline int _SDL_xchg_watcom(volatile int *a, int v);
value [eax] \ value [eax] \
modify exact [eax]; modify exact [eax];
#endif /* __WATCOMC__ && __386__ */ #endif /* __WATCOMC__ && __386__ */
/* *INDENT-ON* */ /* clang-format on */
/* This function is where all the magic happens... */ /* This function is where all the magic happens... */
SDL_bool SDL_bool
@@ -99,30 +100,38 @@ SDL_AtomicTryLock(SDL_SpinLock *lock)
#if defined(__RISCOS__) #if defined(__RISCOS__)
if (__cpucap_have_rex()) { if (__cpucap_have_rex()) {
__asm__ __volatile__ ( __asm__ __volatile__(
"ldrex %0, [%2]\nteq %0, #0\nstrexeq %0, %1, [%2]" "ldrex %0, [%2]\nteq %0, #0\nstrexeq %0, %1, [%2]"
: "=&r" (result) : "r" (1), "r" (lock) : "cc", "memory"); : "=&r"(result)
: "r"(1), "r"(lock)
: "cc", "memory");
return result == 0; return result == 0;
} }
#endif #endif
__asm__ __volatile__ ( __asm__ __volatile__(
"swp %0, %1, [%2]\n" "swp %0, %1, [%2]\n"
: "=&r,&r" (result) : "r,0" (1), "r,r" (lock) : "memory"); : "=&r,&r"(result)
: "r,0"(1), "r,r"(lock)
: "memory");
return result == 0; return result == 0;
#elif defined(__GNUC__) && defined(__arm__) #elif defined(__GNUC__) && defined(__arm__)
int result; int result;
__asm__ __volatile__ ( __asm__ __volatile__(
"ldrex %0, [%2]\nteq %0, #0\nstrexeq %0, %1, [%2]" "ldrex %0, [%2]\nteq %0, #0\nstrexeq %0, %1, [%2]"
: "=&r" (result) : "r" (1), "r" (lock) : "cc", "memory"); : "=&r"(result)
: "r"(1), "r"(lock)
: "cc", "memory");
return result == 0; return result == 0;
#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
int result; int result;
__asm__ __volatile__( __asm__ __volatile__(
"lock ; xchgl %0, (%1)\n" "lock ; xchgl %0, (%1)\n"
: "=r" (result) : "r" (lock), "0" (1) : "cc", "memory"); : "=r"(result)
: "r"(lock), "0"(1)
: "cc", "memory");
return result == 0; return result == 0;
#elif defined(__MACOS__) || defined(__IOS__) || defined(__TVOS__) #elif defined(__MACOS__) || defined(__IOS__) || defined(__TVOS__)
@@ -147,7 +156,9 @@ SDL_AtomicTryLock(SDL_SpinLock *lock)
res = SDL_TRUE; res = SDL_TRUE;
} }
// enable interuption // enable interuption
if (oldintr) { EIntr(); } if (oldintr) {
EIntr();
}
return res; return res;
#else #else
#error Please implement for your platform. #error Please implement for your platform.
@@ -155,8 +166,7 @@ SDL_AtomicTryLock(SDL_SpinLock *lock)
#endif #endif
} }
void void SDL_AtomicLock(SDL_SpinLock *lock)
SDL_AtomicLock(SDL_SpinLock *lock)
{ {
int iterations = 0; int iterations = 0;
/* FIXME: Should we have an eventual timeout? */ /* FIXME: Should we have an eventual timeout? */
@@ -171,8 +181,7 @@ SDL_AtomicLock(SDL_SpinLock *lock)
} }
} }
void void SDL_AtomicUnlock(SDL_SpinLock *lock)
SDL_AtomicUnlock(SDL_SpinLock *lock)
{ {
#if HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET #if HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET
__sync_lock_release(lock); __sync_lock_release(lock);
@@ -185,7 +194,7 @@ SDL_AtomicUnlock(SDL_SpinLock *lock)
*lock = 0; *lock = 0;
#elif defined(__WATCOMC__) && defined(__386__) #elif defined(__WATCOMC__) && defined(__386__)
SDL_CompilerBarrier (); SDL_CompilerBarrier();
*lock = 0; *lock = 0;
#elif defined(__SOLARIS__) #elif defined(__SOLARIS__)

View File

@@ -100,22 +100,20 @@ static const AudioBootStrap *const bootstrap[] = {
NULL NULL
}; };
#ifdef HAVE_LIBSAMPLERATE_H #ifdef HAVE_LIBSAMPLERATE_H
#ifdef SDL_LIBSAMPLERATE_DYNAMIC #ifdef SDL_LIBSAMPLERATE_DYNAMIC
static void *SRC_lib = NULL; static void *SRC_lib = NULL;
#endif #endif
SDL_bool SRC_available = SDL_FALSE; SDL_bool SRC_available = SDL_FALSE;
int SRC_converter = 0; int SRC_converter = 0;
SRC_STATE* (*SRC_src_new)(int converter_type, int channels, int *error) = NULL; SRC_STATE *(*SRC_src_new)(int converter_type, int channels, int *error) = NULL;
int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data) = NULL; int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data) = NULL;
int (*SRC_src_reset)(SRC_STATE *state) = NULL; int (*SRC_src_reset)(SRC_STATE *state) = NULL;
SRC_STATE* (*SRC_src_delete)(SRC_STATE *state) = NULL; SRC_STATE *(*SRC_src_delete)(SRC_STATE *state) = NULL;
const char* (*SRC_src_strerror)(int error) = NULL; const char *(*SRC_src_strerror)(int error) = NULL;
int (*SRC_src_simple)(SRC_DATA *data, int converter_type, int channels) = NULL; int (*SRC_src_simple)(SRC_DATA *data, int converter_type, int channels) = NULL;
static SDL_bool static SDL_bool LoadLibSampleRate(void)
LoadLibSampleRate(void)
{ {
const char *hint = SDL_GetHint(SDL_HINT_AUDIO_RESAMPLING_MODE); const char *hint = SDL_GetHint(SDL_HINT_AUDIO_RESAMPLING_MODE);
@@ -142,12 +140,14 @@ LoadLibSampleRate(void)
return SDL_FALSE; return SDL_FALSE;
} }
/* *INDENT-OFF* */ /* clang-format off */
SRC_src_new = (SRC_STATE* (*)(int converter_type, int channels, int *error))SDL_LoadFunction(SRC_lib, "src_new"); SRC_src_new = (SRC_STATE* (*)(int converter_type, int channels, int *error))SDL_LoadFunction(SRC_lib, "src_new");
SRC_src_process = (int (*)(SRC_STATE *state, SRC_DATA *data))SDL_LoadFunction(SRC_lib, "src_process"); SRC_src_process = (int (*)(SRC_STATE *state, SRC_DATA *data))SDL_LoadFunction(SRC_lib, "src_process");
SRC_src_reset = (int(*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_reset"); SRC_src_reset = (int(*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_reset");
SRC_src_delete = (SRC_STATE* (*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_delete"); SRC_src_delete = (SRC_STATE* (*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_delete");
SRC_src_strerror = (const char* (*)(int error))SDL_LoadFunction(SRC_lib, "src_strerror"); SRC_src_strerror = (const char* (*)(int error))SDL_LoadFunction(SRC_lib, "src_strerror");
SRC_src_simple = (int(*)(SRC_DATA *data, int converter_type, int channels))SDL_LoadFunction(SRC_lib, "src_simple"); SRC_src_simple = (int(*)(SRC_DATA *data, int converter_type, int channels))SDL_LoadFunction(SRC_lib, "src_simple");
/* *INDENT-ON* */ /* clang-format on */
if (!SRC_src_new || !SRC_src_process || !SRC_src_reset || !SRC_src_delete || !SRC_src_strerror || !SRC_src_simple) { if (!SRC_src_new || !SRC_src_process || !SRC_src_reset || !SRC_src_delete || !SRC_src_strerror || !SRC_src_simple) {
SDL_UnloadObject(SRC_lib); SDL_UnloadObject(SRC_lib);
@@ -167,8 +167,7 @@ LoadLibSampleRate(void)
return SDL_TRUE; return SDL_TRUE;
} }
static void static void UnloadLibSampleRate(void)
UnloadLibSampleRate(void)
{ {
#ifdef SDL_LIBSAMPLERATE_DYNAMIC #ifdef SDL_LIBSAMPLERATE_DYNAMIC
if (SRC_lib != NULL) { if (SRC_lib != NULL) {
@@ -186,8 +185,7 @@ UnloadLibSampleRate(void)
} }
#endif #endif
static SDL_AudioDevice * static SDL_AudioDevice *get_audio_device(SDL_AudioDeviceID id)
get_audio_device(SDL_AudioDeviceID id)
{ {
id--; id--;
if ((id >= SDL_arraysize(open_devices)) || (open_devices[id] == NULL)) { if ((id >= SDL_arraysize(open_devices)) || (open_devices[id] == NULL)) {
@@ -198,82 +196,67 @@ get_audio_device(SDL_AudioDeviceID id)
return open_devices[id]; return open_devices[id];
} }
/* stubs for audio drivers that don't need a specific entry point... */ /* stubs for audio drivers that don't need a specific entry point... */
static void static void SDL_AudioDetectDevices_Default(void)
SDL_AudioDetectDevices_Default(void)
{ {
/* you have to write your own implementation if these assertions fail. */ /* you have to write your own implementation if these assertions fail. */
SDL_assert(current_audio.impl.OnlyHasDefaultOutputDevice); SDL_assert(current_audio.impl.OnlyHasDefaultOutputDevice);
SDL_assert(current_audio.impl.OnlyHasDefaultCaptureDevice || !current_audio.impl.HasCaptureSupport); SDL_assert(current_audio.impl.OnlyHasDefaultCaptureDevice || !current_audio.impl.HasCaptureSupport);
SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, NULL, (void *) ((size_t) 0x1)); SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, NULL, (void *)((size_t)0x1));
if (current_audio.impl.HasCaptureSupport) { if (current_audio.impl.HasCaptureSupport) {
SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, NULL, (void *) ((size_t) 0x2)); SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, NULL, (void *)((size_t)0x2));
} }
} }
static void static void SDL_AudioThreadInit_Default(_THIS)
SDL_AudioThreadInit_Default(_THIS)
{ /* no-op. */ { /* no-op. */
} }
static void static void SDL_AudioThreadDeinit_Default(_THIS)
SDL_AudioThreadDeinit_Default(_THIS)
{ /* no-op. */ { /* no-op. */
} }
static void static void SDL_AudioWaitDevice_Default(_THIS)
SDL_AudioWaitDevice_Default(_THIS)
{ /* no-op. */ { /* no-op. */
} }
static void static void SDL_AudioPlayDevice_Default(_THIS)
SDL_AudioPlayDevice_Default(_THIS)
{ /* no-op. */ { /* no-op. */
} }
static Uint8 * static Uint8 *SDL_AudioGetDeviceBuf_Default(_THIS)
SDL_AudioGetDeviceBuf_Default(_THIS)
{ {
return NULL; return NULL;
} }
static int static int SDL_AudioCaptureFromDevice_Default(_THIS, void *buffer, int buflen)
SDL_AudioCaptureFromDevice_Default(_THIS, void *buffer, int buflen)
{ {
return -1; /* just fail immediately. */ return -1; /* just fail immediately. */
} }
static void static void SDL_AudioFlushCapture_Default(_THIS)
SDL_AudioFlushCapture_Default(_THIS)
{ /* no-op. */ { /* no-op. */
} }
static void static void SDL_AudioCloseDevice_Default(_THIS)
SDL_AudioCloseDevice_Default(_THIS)
{ /* no-op. */ { /* no-op. */
} }
static void static void SDL_AudioDeinitialize_Default(void)
SDL_AudioDeinitialize_Default(void)
{ /* no-op. */ { /* no-op. */
} }
static void static void SDL_AudioFreeDeviceHandle_Default(void *handle)
SDL_AudioFreeDeviceHandle_Default(void *handle)
{ /* no-op. */ { /* no-op. */
} }
static int SDL_AudioOpenDevice_Default(_THIS, const char *devname)
static int
SDL_AudioOpenDevice_Default(_THIS, const char *devname)
{ {
return SDL_Unsupported(); return SDL_Unsupported();
} }
static SDL_INLINE SDL_bool static SDL_INLINE SDL_bool is_in_audio_device_thread(SDL_AudioDevice *device)
is_in_audio_device_thread(SDL_AudioDevice * device)
{ {
/* The device thread locks the same mutex, but not through the public API. /* The device thread locks the same mutex, but not through the public API.
This check is in case the application, in the audio callback, This check is in case the application, in the audio callback,
@@ -286,31 +269,27 @@ is_in_audio_device_thread(SDL_AudioDevice * device)
return SDL_FALSE; return SDL_FALSE;
} }
static void static void SDL_AudioLockDevice_Default(SDL_AudioDevice *device)
SDL_AudioLockDevice_Default(SDL_AudioDevice * device)
{ {
if (!is_in_audio_device_thread(device)) { if (!is_in_audio_device_thread(device)) {
SDL_LockMutex(device->mixer_lock); SDL_LockMutex(device->mixer_lock);
} }
} }
static void static void SDL_AudioUnlockDevice_Default(SDL_AudioDevice *device)
SDL_AudioUnlockDevice_Default(SDL_AudioDevice * device)
{ {
if (!is_in_audio_device_thread(device)) { if (!is_in_audio_device_thread(device)) {
SDL_UnlockMutex(device->mixer_lock); SDL_UnlockMutex(device->mixer_lock);
} }
} }
static void static void finish_audio_entry_points_init(void)
finish_audio_entry_points_init(void)
{ {
/* /*
* Fill in stub functions for unused driver entry points. This lets us * Fill in stub functions for unused driver entry points. This lets us
* blindly call them without having to check for validity first. * blindly call them without having to check for validity first.
*/ */
#define FILL_STUB(x) \ #define FILL_STUB(x) \
if (current_audio.impl.x == NULL) { \ if (current_audio.impl.x == NULL) { \
current_audio.impl.x = SDL_Audio##x##_Default; \ current_audio.impl.x = SDL_Audio##x##_Default; \
@@ -332,11 +311,9 @@ finish_audio_entry_points_init(void)
#undef FILL_STUB #undef FILL_STUB
} }
/* device hotplug support... */ /* device hotplug support... */
static int static int add_audio_device(const char *name, SDL_AudioSpec *spec, void *handle, SDL_AudioDeviceItem **devices, int *devCount)
add_audio_device(const char *name, SDL_AudioSpec *spec, void *handle, SDL_AudioDeviceItem **devices, int *devCount)
{ {
int retval = -1; int retval = -1;
SDL_AudioDeviceItem *item; SDL_AudioDeviceItem *item;
@@ -346,7 +323,7 @@ add_audio_device(const char *name, SDL_AudioSpec *spec, void *handle, SDL_AudioD
SDL_assert(handle != NULL); /* we reserve NULL, audio backends can't use it. */ SDL_assert(handle != NULL); /* we reserve NULL, audio backends can't use it. */
SDL_assert(name != NULL); SDL_assert(name != NULL);
item = (SDL_AudioDeviceItem *) SDL_malloc(sizeof (SDL_AudioDeviceItem)); item = (SDL_AudioDeviceItem *)SDL_malloc(sizeof(SDL_AudioDeviceItem));
if (!item) { if (!item) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -377,7 +354,7 @@ add_audio_device(const char *name, SDL_AudioSpec *spec, void *handle, SDL_AudioD
if (dupenum) { if (dupenum) {
const size_t len = SDL_strlen(name) + 16; const size_t len = SDL_strlen(name) + 16;
char *replacement = (char *) SDL_malloc(len); char *replacement = (char *)SDL_malloc(len);
if (!replacement) { if (!replacement) {
SDL_UnlockMutex(current_audio.detectionLock); SDL_UnlockMutex(current_audio.detectionLock);
SDL_free(item->original_name); SDL_free(item->original_name);
@@ -399,21 +376,18 @@ add_audio_device(const char *name, SDL_AudioSpec *spec, void *handle, SDL_AudioD
return retval; return retval;
} }
static SDL_INLINE int static SDL_INLINE int add_capture_device(const char *name, SDL_AudioSpec *spec, void *handle)
add_capture_device(const char *name, SDL_AudioSpec *spec, void *handle)
{ {
SDL_assert(current_audio.impl.HasCaptureSupport); SDL_assert(current_audio.impl.HasCaptureSupport);
return add_audio_device(name, spec, handle, &current_audio.inputDevices, &current_audio.inputDeviceCount); return add_audio_device(name, spec, handle, &current_audio.inputDevices, &current_audio.inputDeviceCount);
} }
static SDL_INLINE int static SDL_INLINE int add_output_device(const char *name, SDL_AudioSpec *spec, void *handle)
add_output_device(const char *name, SDL_AudioSpec *spec, void *handle)
{ {
return add_audio_device(name, spec, handle, &current_audio.outputDevices, &current_audio.outputDeviceCount); return add_audio_device(name, spec, handle, &current_audio.outputDevices, &current_audio.outputDeviceCount);
} }
static void static void free_device_list(SDL_AudioDeviceItem **devices, int *devCount)
free_device_list(SDL_AudioDeviceItem **devices, int *devCount)
{ {
SDL_AudioDeviceItem *item, *next; SDL_AudioDeviceItem *item, *next;
for (item = *devices; item != NULL; item = next) { for (item = *devices; item != NULL; item = next) {
@@ -432,10 +406,8 @@ free_device_list(SDL_AudioDeviceItem **devices, int *devCount)
*devCount = 0; *devCount = 0;
} }
/* The audio backends call this when a new device is plugged in. */ /* The audio backends call this when a new device is plugged in. */
void void SDL_AddAudioDevice(const SDL_bool iscapture, const char *name, SDL_AudioSpec *spec, void *handle)
SDL_AddAudioDevice(const SDL_bool iscapture, const char *name, SDL_AudioSpec *spec, void *handle)
{ {
const int device_index = iscapture ? add_capture_device(name, spec, handle) : add_output_device(name, spec, handle); const int device_index = iscapture ? add_capture_device(name, spec, handle) : add_output_device(name, spec, handle);
if (device_index != -1) { if (device_index != -1) {
@@ -481,8 +453,7 @@ void SDL_OpenedAudioDeviceDisconnected(SDL_AudioDevice *device)
} }
} }
static void static void mark_device_removed(void *handle, SDL_AudioDeviceItem *devices, SDL_bool *removedFlag)
mark_device_removed(void *handle, SDL_AudioDeviceItem *devices, SDL_bool *removedFlag)
{ {
SDL_AudioDeviceItem *item; SDL_AudioDeviceItem *item;
SDL_assert(handle != NULL); SDL_assert(handle != NULL);
@@ -496,8 +467,7 @@ mark_device_removed(void *handle, SDL_AudioDeviceItem *devices, SDL_bool *remove
} }
/* The audio backends call this when a device is removed from the system. */ /* The audio backends call this when a device is removed from the system. */
void void SDL_RemoveAudioDevice(const SDL_bool iscapture, void *handle)
SDL_RemoveAudioDevice(const SDL_bool iscapture, void *handle)
{ {
int device_index; int device_index;
SDL_AudioDevice *device = NULL; SDL_AudioDevice *device = NULL;
@@ -540,15 +510,12 @@ SDL_RemoveAudioDevice(const SDL_bool iscapture, void *handle)
current_audio.impl.FreeDeviceHandle(handle); current_audio.impl.FreeDeviceHandle(handle);
} }
/* buffer queueing support... */ /* buffer queueing support... */
static void SDLCALL static void SDLCALL SDL_BufferQueueDrainCallback(void *userdata, Uint8 *stream, int len)
SDL_BufferQueueDrainCallback(void *userdata, Uint8 *stream, int len)
{ {
/* this function always holds the mixer lock before being called. */ /* this function always holds the mixer lock before being called. */
SDL_AudioDevice *device = (SDL_AudioDevice *) userdata; SDL_AudioDevice *device = (SDL_AudioDevice *)userdata;
size_t dequeued; size_t dequeued;
SDL_assert(device != NULL); /* this shouldn't ever happen, right?! */ SDL_assert(device != NULL); /* this shouldn't ever happen, right?! */
@@ -557,7 +524,7 @@ SDL_BufferQueueDrainCallback(void *userdata, Uint8 *stream, int len)
dequeued = SDL_ReadFromDataQueue(device->buffer_queue, stream, len); dequeued = SDL_ReadFromDataQueue(device->buffer_queue, stream, len);
stream += dequeued; stream += dequeued;
len -= (int) dequeued; len -= (int)dequeued;
if (len > 0) { /* fill any remaining space in the stream with silence. */ if (len > 0) { /* fill any remaining space in the stream with silence. */
SDL_assert(SDL_CountDataQueue(device->buffer_queue) == 0); SDL_assert(SDL_CountDataQueue(device->buffer_queue) == 0);
@@ -565,11 +532,10 @@ SDL_BufferQueueDrainCallback(void *userdata, Uint8 *stream, int len)
} }
} }
static void SDLCALL static void SDLCALL SDL_BufferQueueFillCallback(void *userdata, Uint8 *stream, int len)
SDL_BufferQueueFillCallback(void *userdata, Uint8 *stream, int len)
{ {
/* this function always holds the mixer lock before being called. */ /* this function always holds the mixer lock before being called. */
SDL_AudioDevice *device = (SDL_AudioDevice *) userdata; SDL_AudioDevice *device = (SDL_AudioDevice *)userdata;
SDL_assert(device != NULL); /* this shouldn't ever happen, right?! */ SDL_assert(device != NULL); /* this shouldn't ever happen, right?! */
SDL_assert(device->iscapture); /* this shouldn't ever happen, right?! */ SDL_assert(device->iscapture); /* this shouldn't ever happen, right?! */
@@ -581,8 +547,7 @@ SDL_BufferQueueFillCallback(void *userdata, Uint8 *stream, int len)
SDL_WriteToDataQueue(device->buffer_queue, stream, len); SDL_WriteToDataQueue(device->buffer_queue, stream, len);
} }
int int SDL_QueueAudio(SDL_AudioDeviceID devid, const void *data, Uint32 len)
SDL_QueueAudio(SDL_AudioDeviceID devid, const void *data, Uint32 len)
{ {
SDL_AudioDevice *device = get_audio_device(devid); SDL_AudioDevice *device = get_audio_device(devid);
int rc = 0; int rc = 0;
@@ -610,15 +575,15 @@ SDL_DequeueAudio(SDL_AudioDeviceID devid, void *data, Uint32 len)
SDL_AudioDevice *device = get_audio_device(devid); SDL_AudioDevice *device = get_audio_device(devid);
Uint32 rc; Uint32 rc;
if ( (len == 0) || /* nothing to do? */ if ((len == 0) || /* nothing to do? */
(!device) || /* called with bogus device id */ (!device) || /* called with bogus device id */
(!device->iscapture) || /* playback devices can't dequeue */ (!device->iscapture) || /* playback devices can't dequeue */
(device->callbackspec.callback != SDL_BufferQueueFillCallback) ) { /* not set for queueing */ (device->callbackspec.callback != SDL_BufferQueueFillCallback)) { /* not set for queueing */
return 0; /* just report zero bytes dequeued. */ return 0; /* just report zero bytes dequeued. */
} }
current_audio.impl.LockDevice(device); current_audio.impl.LockDevice(device);
rc = (Uint32) SDL_ReadFromDataQueue(device->buffer_queue, data, len); rc = (Uint32)SDL_ReadFromDataQueue(device->buffer_queue, data, len);
current_audio.impl.UnlockDevice(device); current_audio.impl.UnlockDevice(device);
return rc; return rc;
} }
@@ -635,18 +600,16 @@ SDL_GetQueuedAudioSize(SDL_AudioDeviceID devid)
/* Nothing to do unless we're set up for queueing. */ /* Nothing to do unless we're set up for queueing. */
if (device->callbackspec.callback == SDL_BufferQueueDrainCallback || if (device->callbackspec.callback == SDL_BufferQueueDrainCallback ||
device->callbackspec.callback == SDL_BufferQueueFillCallback) device->callbackspec.callback == SDL_BufferQueueFillCallback) {
{
current_audio.impl.LockDevice(device); current_audio.impl.LockDevice(device);
retval = (Uint32) SDL_CountDataQueue(device->buffer_queue); retval = (Uint32)SDL_CountDataQueue(device->buffer_queue);
current_audio.impl.UnlockDevice(device); current_audio.impl.UnlockDevice(device);
} }
return retval; return retval;
} }
void void SDL_ClearQueuedAudio(SDL_AudioDeviceID devid)
SDL_ClearQueuedAudio(SDL_AudioDeviceID devid)
{ {
SDL_AudioDevice *device = get_audio_device(devid); SDL_AudioDevice *device = get_audio_device(devid);
@@ -663,12 +626,10 @@ SDL_ClearQueuedAudio(SDL_AudioDeviceID devid)
current_audio.impl.UnlockDevice(device); current_audio.impl.UnlockDevice(device);
} }
/* The general mixing thread function */ /* The general mixing thread function */
static int SDLCALL static int SDLCALL SDL_RunAudio(void *devicep)
SDL_RunAudio(void *devicep)
{ {
SDL_AudioDevice *device = (SDL_AudioDevice *) devicep; SDL_AudioDevice *device = (SDL_AudioDevice *)devicep;
void *udata = device->callbackspec.userdata; void *udata = device->callbackspec.userdata;
SDL_AudioCallback callback = device->callbackspec.callback; SDL_AudioCallback callback = device->callbackspec.callback;
int data_len = 0; int data_len = 0;
@@ -727,7 +688,7 @@ SDL_RunAudio(void *devicep)
/* if this fails...oh well. We'll play silence here. */ /* if this fails...oh well. We'll play silence here. */
SDL_AudioStreamPut(device->stream, data, data_len); SDL_AudioStreamPut(device->stream, data, data_len);
while (SDL_AudioStreamAvailable(device->stream) >= ((int) device->spec.size)) { while (SDL_AudioStreamAvailable(device->stream) >= ((int)device->spec.size)) {
int got; int got;
data = SDL_AtomicGet(&device->enabled) ? current_audio.impl.GetDeviceBuf(device) : NULL; data = SDL_AtomicGet(&device->enabled) ? current_audio.impl.GetDeviceBuf(device) : NULL;
got = SDL_AudioStreamGet(device->stream, data ? data : device->work_buffer, device->spec.size); got = SDL_AudioStreamGet(device->stream, data ? data : device->work_buffer, device->spec.size);
@@ -765,11 +726,10 @@ SDL_RunAudio(void *devicep)
/* !!! FIXME: this needs to deal with device spec changes. */ /* !!! FIXME: this needs to deal with device spec changes. */
/* The general capture thread function */ /* The general capture thread function */
static int SDLCALL static int SDLCALL SDL_CaptureAudio(void *devicep)
SDL_CaptureAudio(void *devicep)
{ {
SDL_AudioDevice *device = (SDL_AudioDevice *) devicep; SDL_AudioDevice *device = (SDL_AudioDevice *)devicep;
const int silence = (int) device->spec.silence; const int silence = (int)device->spec.silence;
const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq); const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq);
const int data_len = device->spec.size; const int data_len = device->spec.size;
Uint8 *data; Uint8 *data;
@@ -845,7 +805,7 @@ SDL_CaptureAudio(void *devicep)
/* if this fails...oh well. */ /* if this fails...oh well. */
SDL_AudioStreamPut(device->stream, data, data_len); SDL_AudioStreamPut(device->stream, data, data_len);
while (SDL_AudioStreamAvailable(device->stream) >= ((int) device->callbackspec.size)) { while (SDL_AudioStreamAvailable(device->stream) >= ((int)device->callbackspec.size)) {
const int got = SDL_AudioStreamGet(device->stream, device->work_buffer, device->callbackspec.size); const int got = SDL_AudioStreamGet(device->stream, device->work_buffer, device->callbackspec.size);
SDL_assert((got < 0) || (got == device->callbackspec.size)); SDL_assert((got < 0) || (got == device->callbackspec.size));
if (got != device->callbackspec.size) { if (got != device->callbackspec.size) {
@@ -876,11 +836,11 @@ SDL_CaptureAudio(void *devicep)
return 0; return 0;
} }
static SDL_AudioFormat SDL_ParseAudioFormat(const char *string)
static SDL_AudioFormat
SDL_ParseAudioFormat(const char *string)
{ {
#define CHECK_FMT_STRING(x) if (SDL_strcmp(string, #x) == 0) return AUDIO_##x #define CHECK_FMT_STRING(x) \
if (SDL_strcmp(string, #x) == 0) \
return AUDIO_##x
CHECK_FMT_STRING(U8); CHECK_FMT_STRING(U8);
CHECK_FMT_STRING(S8); CHECK_FMT_STRING(S8);
CHECK_FMT_STRING(U16LSB); CHECK_FMT_STRING(U16LSB);
@@ -903,8 +863,7 @@ SDL_ParseAudioFormat(const char *string)
return 0; return 0;
} }
int int SDL_GetNumAudioDrivers(void)
SDL_GetNumAudioDrivers(void)
{ {
return SDL_arraysize(bootstrap) - 1; return SDL_arraysize(bootstrap) - 1;
} }
@@ -918,8 +877,7 @@ SDL_GetAudioDriver(int index)
return NULL; return NULL;
} }
int int SDL_AudioInit(const char *driver_name)
SDL_AudioInit(const char *driver_name)
{ {
int i; int i;
SDL_bool initialized = SDL_FALSE, tried_to_init = SDL_FALSE; SDL_bool initialized = SDL_FALSE, tried_to_init = SDL_FALSE;
@@ -1025,8 +983,7 @@ SDL_GetCurrentAudioDriver()
} }
/* Clean out devices that we've removed but had to keep around for stability. */ /* Clean out devices that we've removed but had to keep around for stability. */
static void static void clean_out_device_list(SDL_AudioDeviceItem **devices, int *devCount, SDL_bool *removedFlag)
clean_out_device_list(SDL_AudioDeviceItem **devices, int *devCount, SDL_bool *removedFlag)
{ {
SDL_AudioDeviceItem *item = *devices; SDL_AudioDeviceItem *item = *devices;
SDL_AudioDeviceItem *prev = NULL; SDL_AudioDeviceItem *prev = NULL;
@@ -1057,9 +1014,7 @@ clean_out_device_list(SDL_AudioDeviceItem **devices, int *devCount, SDL_bool *re
*removedFlag = SDL_FALSE; *removedFlag = SDL_FALSE;
} }
int SDL_GetNumAudioDevices(int iscapture)
int
SDL_GetNumAudioDevices(int iscapture)
{ {
int retval = 0; int retval = 0;
@@ -1082,7 +1037,6 @@ SDL_GetNumAudioDevices(int iscapture)
return retval; return retval;
} }
const char * const char *
SDL_GetAudioDeviceName(int index, int iscapture) SDL_GetAudioDeviceName(int index, int iscapture)
{ {
@@ -1113,9 +1067,7 @@ SDL_GetAudioDeviceName(int index, int iscapture)
return retval; return retval;
} }
int SDL_GetAudioDeviceSpec(int index, int iscapture, SDL_AudioSpec *spec)
int
SDL_GetAudioDeviceSpec(int index, int iscapture, SDL_AudioSpec *spec)
{ {
SDL_AudioDeviceItem *item; SDL_AudioDeviceItem *item;
int i, retval; int i, retval;
@@ -1146,9 +1098,7 @@ SDL_GetAudioDeviceSpec(int index, int iscapture, SDL_AudioSpec *spec)
return retval; return retval;
} }
int SDL_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
int
SDL_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
{ {
if (spec == NULL) { if (spec == NULL) {
return SDL_InvalidParamError("spec"); return SDL_InvalidParamError("spec");
@@ -1164,9 +1114,7 @@ SDL_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
return current_audio.impl.GetDefaultAudioInfo(name, spec, iscapture); return current_audio.impl.GetDefaultAudioInfo(name, spec, iscapture);
} }
static void close_audio_device(SDL_AudioDevice *device)
static void
close_audio_device(SDL_AudioDevice * device)
{ {
if (!device) { if (!device) {
return; return;
@@ -1207,14 +1155,12 @@ close_audio_device(SDL_AudioDevice * device)
SDL_free(device); SDL_free(device);
} }
/* /*
* Sanity check desired AudioSpec for SDL_OpenAudio() in (orig). * Sanity check desired AudioSpec for SDL_OpenAudio() in (orig).
* Fills in a sanitized copy in (prepared). * Fills in a sanitized copy in (prepared).
* Returns non-zero if okay, zero on fatal parameters in (orig). * Returns non-zero if okay, zero on fatal parameters in (orig).
*/ */
static int static int prepare_audiospec(const SDL_AudioSpec *orig, SDL_AudioSpec *prepared)
prepare_audiospec(const SDL_AudioSpec * orig, SDL_AudioSpec * prepared)
{ {
SDL_copyp(prepared, orig); SDL_copyp(prepared, orig);
@@ -1234,7 +1180,7 @@ prepare_audiospec(const SDL_AudioSpec * orig, SDL_AudioSpec * prepared)
if (orig->channels == 0) { if (orig->channels == 0) {
const char *env = SDL_getenv("SDL_AUDIO_CHANNELS"); const char *env = SDL_getenv("SDL_AUDIO_CHANNELS");
if ((!env) || ((prepared->channels = (Uint8) SDL_atoi(env)) == 0)) { if ((!env) || ((prepared->channels = (Uint8)SDL_atoi(env)) == 0)) {
prepared->channels = 2; /* a reasonable default */ prepared->channels = 2; /* a reasonable default */
} }
} else if (orig->channels > 8) { } else if (orig->channels > 8) {
@@ -1244,7 +1190,7 @@ prepare_audiospec(const SDL_AudioSpec * orig, SDL_AudioSpec * prepared)
if (orig->samples == 0) { if (orig->samples == 0) {
const char *env = SDL_getenv("SDL_AUDIO_SAMPLES"); const char *env = SDL_getenv("SDL_AUDIO_SAMPLES");
if ((!env) || ((prepared->samples = (Uint16) SDL_atoi(env)) == 0)) { if ((!env) || ((prepared->samples = (Uint16)SDL_atoi(env)) == 0)) {
/* Pick a default of ~46 ms at desired frequency */ /* Pick a default of ~46 ms at desired frequency */
/* !!! FIXME: remove this when the non-Po2 resampling is in. */ /* !!! FIXME: remove this when the non-Po2 resampling is in. */
const int samples = (prepared->freq / 1000) * 46; const int samples = (prepared->freq / 1000) * 46;
@@ -1262,9 +1208,8 @@ prepare_audiospec(const SDL_AudioSpec * orig, SDL_AudioSpec * prepared)
return 1; return 1;
} }
static SDL_AudioDeviceID static SDL_AudioDeviceID open_audio_device(const char *devname, int iscapture,
open_audio_device(const char *devname, int iscapture, const SDL_AudioSpec *desired, SDL_AudioSpec *obtained,
const SDL_AudioSpec * desired, SDL_AudioSpec * obtained,
int allowed_changes, int min_id) int allowed_changes, int min_id)
{ {
const SDL_bool is_internal_thread = (desired->callback == NULL); const SDL_bool is_internal_thread = (desired->callback == NULL);
@@ -1377,7 +1322,7 @@ open_audio_device(const char *devname, int iscapture,
} }
} }
device = (SDL_AudioDevice *) SDL_calloc(1, sizeof (SDL_AudioDevice)); device = (SDL_AudioDevice *)SDL_calloc(1, sizeof(SDL_AudioDevice));
if (device == NULL) { if (device == NULL) {
SDL_OutOfMemory(); SDL_OutOfMemory();
SDL_UnlockMutex(current_audio.detectionLock); SDL_UnlockMutex(current_audio.detectionLock);
@@ -1493,7 +1438,7 @@ open_audio_device(const char *devname, int iscapture,
} }
SDL_assert(device->work_buffer_len > 0); SDL_assert(device->work_buffer_len > 0);
device->work_buffer = (Uint8 *) SDL_malloc(device->work_buffer_len); device->work_buffer = (Uint8 *)SDL_malloc(device->work_buffer_len);
if (device->work_buffer == NULL) { if (device->work_buffer == NULL) {
close_audio_device(device); close_audio_device(device);
SDL_UnlockMutex(current_audio.detectionLock); SDL_UnlockMutex(current_audio.detectionLock);
@@ -1511,7 +1456,7 @@ open_audio_device(const char *devname, int iscapture,
const size_t stacksize = is_internal_thread ? 64 * 1024 : 0; const size_t stacksize = is_internal_thread ? 64 * 1024 : 0;
char threadname[64]; char threadname[64];
SDL_snprintf(threadname, sizeof (threadname), "SDLAudio%c%d", (iscapture) ? 'C' : 'P', (int) device->id); SDL_snprintf(threadname, sizeof(threadname), "SDLAudio%c%d", (iscapture) ? 'C' : 'P', (int)device->id);
device->thread = SDL_CreateThreadInternal(iscapture ? SDL_CaptureAudio : SDL_RunAudio, threadname, stacksize, device); device->thread = SDL_CreateThreadInternal(iscapture ? SDL_CaptureAudio : SDL_RunAudio, threadname, stacksize, device);
if (device->thread == NULL) { if (device->thread == NULL) {
@@ -1526,9 +1471,7 @@ open_audio_device(const char *devname, int iscapture,
return device->id; return device->id;
} }
int SDL_OpenAudio(SDL_AudioSpec *desired, SDL_AudioSpec *obtained)
int
SDL_OpenAudio(SDL_AudioSpec * desired, SDL_AudioSpec * obtained)
{ {
SDL_AudioDeviceID id = 0; SDL_AudioDeviceID id = 0;
@@ -1564,7 +1507,7 @@ SDL_OpenAudio(SDL_AudioSpec * desired, SDL_AudioSpec * obtained)
SDL_AudioDeviceID SDL_AudioDeviceID
SDL_OpenAudioDevice(const char *device, int iscapture, SDL_OpenAudioDevice(const char *device, int iscapture,
const SDL_AudioSpec * desired, SDL_AudioSpec * obtained, const SDL_AudioSpec *desired, SDL_AudioSpec *obtained,
int allowed_changes) int allowed_changes)
{ {
return open_audio_device(device, iscapture, desired, obtained, return open_audio_device(device, iscapture, desired, obtained,
@@ -1586,15 +1529,13 @@ SDL_GetAudioDeviceStatus(SDL_AudioDeviceID devid)
return status; return status;
} }
SDL_AudioStatus SDL_AudioStatus
SDL_GetAudioStatus(void) SDL_GetAudioStatus(void)
{ {
return SDL_GetAudioDeviceStatus(1); return SDL_GetAudioDeviceStatus(1);
} }
void void SDL_PauseAudioDevice(SDL_AudioDeviceID devid, int pause_on)
SDL_PauseAudioDevice(SDL_AudioDeviceID devid, int pause_on)
{ {
SDL_AudioDevice *device = get_audio_device(devid); SDL_AudioDevice *device = get_audio_device(devid);
if (device) { if (device) {
@@ -1604,15 +1545,12 @@ SDL_PauseAudioDevice(SDL_AudioDeviceID devid, int pause_on)
} }
} }
void void SDL_PauseAudio(int pause_on)
SDL_PauseAudio(int pause_on)
{ {
SDL_PauseAudioDevice(1, pause_on); SDL_PauseAudioDevice(1, pause_on);
} }
void SDL_LockAudioDevice(SDL_AudioDeviceID devid)
void
SDL_LockAudioDevice(SDL_AudioDeviceID devid)
{ {
/* Obtain a lock on the mixing buffers */ /* Obtain a lock on the mixing buffers */
SDL_AudioDevice *device = get_audio_device(devid); SDL_AudioDevice *device = get_audio_device(devid);
@@ -1621,14 +1559,12 @@ SDL_LockAudioDevice(SDL_AudioDeviceID devid)
} }
} }
void void SDL_LockAudio(void)
SDL_LockAudio(void)
{ {
SDL_LockAudioDevice(1); SDL_LockAudioDevice(1);
} }
void void SDL_UnlockAudioDevice(SDL_AudioDeviceID devid)
SDL_UnlockAudioDevice(SDL_AudioDeviceID devid)
{ {
/* Obtain a lock on the mixing buffers */ /* Obtain a lock on the mixing buffers */
SDL_AudioDevice *device = get_audio_device(devid); SDL_AudioDevice *device = get_audio_device(devid);
@@ -1637,26 +1573,22 @@ SDL_UnlockAudioDevice(SDL_AudioDeviceID devid)
} }
} }
void void SDL_UnlockAudio(void)
SDL_UnlockAudio(void)
{ {
SDL_UnlockAudioDevice(1); SDL_UnlockAudioDevice(1);
} }
void void SDL_CloseAudioDevice(SDL_AudioDeviceID devid)
SDL_CloseAudioDevice(SDL_AudioDeviceID devid)
{ {
close_audio_device(get_audio_device(devid)); close_audio_device(get_audio_device(devid));
} }
void void SDL_CloseAudio(void)
SDL_CloseAudio(void)
{ {
SDL_CloseAudioDevice(1); SDL_CloseAudioDevice(1);
} }
void void SDL_AudioQuit(void)
SDL_AudioQuit(void)
{ {
SDL_AudioDeviceID i; SDL_AudioDeviceID i;
@@ -1688,26 +1620,26 @@ SDL_AudioQuit(void)
static int format_idx; static int format_idx;
static int format_idx_sub; static int format_idx_sub;
static SDL_AudioFormat format_list[NUM_FORMATS][NUM_FORMATS] = { static SDL_AudioFormat format_list[NUM_FORMATS][NUM_FORMATS] = {
{AUDIO_U8, AUDIO_S8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, { AUDIO_U8, AUDIO_S8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB,
AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB}, AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB },
{AUDIO_S8, AUDIO_U8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, { AUDIO_S8, AUDIO_U8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB,
AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB}, AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB },
{AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S32LSB, { AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S32LSB,
AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8}, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8 },
{AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S32MSB, { AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S32MSB,
AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8}, AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8 },
{AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_S32LSB, { AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_S32LSB,
AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8}, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8 },
{AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_S32MSB, { AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_S32MSB,
AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8}, AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8 },
{AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S16LSB, { AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S16LSB,
AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8}, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8 },
{AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S16MSB, { AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S16MSB,
AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8}, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8 },
{AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_S16LSB, { AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_S16LSB,
AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8}, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8 },
{AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_S16MSB, { AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_S16MSB,
AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8}, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8 },
}; };
SDL_AudioFormat SDL_AudioFormat
@@ -1731,8 +1663,7 @@ SDL_NextAudioFormat(void)
return format_list[format_idx][format_idx_sub++]; return format_list[format_idx][format_idx_sub++];
} }
Uint8 Uint8 SDL_SilenceValueForFormat(const SDL_AudioFormat format)
SDL_SilenceValueForFormat(const SDL_AudioFormat format)
{ {
switch (format) { switch (format) {
/* !!! FIXME: 0x80 isn't perfect for U16, but we can't fit 0x8000 in a /* !!! FIXME: 0x80 isn't perfect for U16, but we can't fit 0x8000 in a
@@ -1743,14 +1674,14 @@ SDL_SilenceValueForFormat(const SDL_AudioFormat format)
case AUDIO_U8: case AUDIO_U8:
return 0x80; return 0x80;
default: break; default:
break;
} }
return 0x00; return 0x00;
} }
void void SDL_CalculateAudioSpec(SDL_AudioSpec *spec)
SDL_CalculateAudioSpec(SDL_AudioSpec * spec)
{ {
spec->silence = SDL_SilenceValueForFormat(spec->format); spec->silence = SDL_SilenceValueForFormat(spec->format);
spec->size = SDL_AUDIO_BITSIZE(spec->format) / 8; spec->size = SDL_AUDIO_BITSIZE(spec->format) / 8;
@@ -1758,13 +1689,11 @@ SDL_CalculateAudioSpec(SDL_AudioSpec * spec)
spec->size *= spec->samples; spec->size *= spec->samples;
} }
/* /*
* Moved here from SDL_mixer.c, since it relies on internals of an opened * Moved here from SDL_mixer.c, since it relies on internals of an opened
* audio device (and is deprecated, by the way!). * audio device (and is deprecated, by the way!).
*/ */
void void SDL_MixAudio(Uint8 *dst, const Uint8 *src, Uint32 len, int volume)
SDL_MixAudio(Uint8 * dst, const Uint8 * src, Uint32 len, int volume)
{ {
/* Mix the user-level audio format */ /* Mix the user-level audio format */
SDL_AudioDevice *device = get_audio_device(1); SDL_AudioDevice *device = get_audio_device(1);

View File

@@ -40,11 +40,11 @@
#include "samplerate.h" #include "samplerate.h"
extern SDL_bool SRC_available; extern SDL_bool SRC_available;
extern int SRC_converter; extern int SRC_converter;
extern SRC_STATE* (*SRC_src_new)(int converter_type, int channels, int *error); extern SRC_STATE *(*SRC_src_new)(int converter_type, int channels, int *error);
extern int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data); extern int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data);
extern int (*SRC_src_reset)(SRC_STATE *state); extern int (*SRC_src_reset)(SRC_STATE *state);
extern SRC_STATE* (*SRC_src_delete)(SRC_STATE *state); extern SRC_STATE *(*SRC_src_delete)(SRC_STATE *state);
extern const char* (*SRC_src_strerror)(int error); extern const char *(*SRC_src_strerror)(int error);
extern int (*SRC_src_simple)(SRC_DATA *data, int converter_type, int channels); extern int (*SRC_src_simple)(SRC_DATA *data, int converter_type, int channels);
#endif #endif
@@ -54,7 +54,7 @@ extern SDL_AudioFormat SDL_NextAudioFormat(void);
/* Function to calculate the size and silence for a SDL_AudioSpec */ /* Function to calculate the size and silence for a SDL_AudioSpec */
extern Uint8 SDL_SilenceValueForFormat(const SDL_AudioFormat format); extern Uint8 SDL_SilenceValueForFormat(const SDL_AudioFormat format);
extern void SDL_CalculateAudioSpec(SDL_AudioSpec * spec); extern void SDL_CalculateAudioSpec(SDL_AudioSpec *spec);
/* Choose the audio filter functions below */ /* Choose the audio filter functions below */
extern void SDL_ChooseAudioConverters(void); extern void SDL_ChooseAudioConverters(void);

File diff suppressed because it is too large Load Diff

View File

@@ -1059,4 +1059,3 @@ static const float ResamplerFilterDifference[RESAMPLER_FILTER_SIZE] = {
}; };
/* vi: set ts=4 sw=4 expandtab: */ /* vi: set ts=4 sw=4 expandtab: */

View File

@@ -44,16 +44,16 @@
#define HAVE_AVX_INTRINSICS 1 #define HAVE_AVX_INTRINSICS 1
#endif #endif
#if defined __clang__ #if defined __clang__
# if (!__has_attribute(target)) #if (!__has_attribute(target))
# undef HAVE_AVX_INTRINSICS #undef HAVE_AVX_INTRINSICS
# endif #endif
# if (defined(_MSC_VER) || defined(__SCE__)) && !defined(__AVX__) #if (defined(_MSC_VER) || defined(__SCE__)) && !defined(__AVX__)
# undef HAVE_AVX_INTRINSICS #undef HAVE_AVX_INTRINSICS
# endif #endif
#elif defined __GNUC__ #elif defined __GNUC__
# if (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 9) #if (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 9)
# undef HAVE_AVX_INTRINSICS #undef HAVE_AVX_INTRINSICS
# endif #endif
#endif #endif
/* /*
@@ -91,11 +91,10 @@
#if HAVE_SSE3_INTRINSICS #if HAVE_SSE3_INTRINSICS
/* Convert from stereo to mono. Average left and right. */ /* Convert from stereo to mono. Average left and right. */
static void SDLCALL static void SDLCALL SDL_ConvertStereoToMono_SSE3(SDL_AudioCVT *cvt, SDL_AudioFormat format)
SDL_ConvertStereoToMono_SSE3(SDL_AudioCVT * cvt, SDL_AudioFormat format)
{ {
const __m128 divby2 = _mm_set1_ps(0.5f); const __m128 divby2 = _mm_set1_ps(0.5f);
float *dst = (float *) cvt->buf; float *dst = (float *)cvt->buf;
const float *src = dst; const float *src = dst;
int i = cvt->len_cvt / 8; int i = cvt->len_cvt / 8;
@@ -106,31 +105,34 @@ SDL_ConvertStereoToMono_SSE3(SDL_AudioCVT * cvt, SDL_AudioFormat format)
Just use unaligned load/stores, if the memory at runtime is Just use unaligned load/stores, if the memory at runtime is
aligned it'll be just as fast on modern processors */ aligned it'll be just as fast on modern processors */
while (i >= 4) { /* 4 * float32 */ while (i >= 4) { /* 4 * float32 */
_mm_storeu_ps(dst, _mm_mul_ps(_mm_hadd_ps(_mm_loadu_ps(src), _mm_loadu_ps(src+4)), divby2)); _mm_storeu_ps(dst, _mm_mul_ps(_mm_hadd_ps(_mm_loadu_ps(src), _mm_loadu_ps(src + 4)), divby2));
i -= 4; src += 8; dst += 4; i -= 4;
src += 8;
dst += 4;
} }
/* Finish off any leftovers with scalar operations. */ /* Finish off any leftovers with scalar operations. */
while (i) { while (i) {
*dst = (src[0] + src[1]) * 0.5f; *dst = (src[0] + src[1]) * 0.5f;
dst++; i--; src += 2; dst++;
i--;
src += 2;
} }
cvt->len_cvt /= 2; cvt->len_cvt /= 2;
if (cvt->filters[++cvt->filter_index]) { if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index] (cvt, format); cvt->filters[cvt->filter_index](cvt, format);
} }
} }
#endif #endif
#if HAVE_SSE_INTRINSICS #if HAVE_SSE_INTRINSICS
/* Convert from mono to stereo. Duplicate to stereo left and right. */ /* Convert from mono to stereo. Duplicate to stereo left and right. */
static void SDLCALL static void SDLCALL SDL_ConvertMonoToStereo_SSE(SDL_AudioCVT *cvt, SDL_AudioFormat format)
SDL_ConvertMonoToStereo_SSE(SDL_AudioCVT * cvt, SDL_AudioFormat format)
{ {
float *dst = ((float *) (cvt->buf + (cvt->len_cvt * 2))) - 8; float *dst = ((float *)(cvt->buf + (cvt->len_cvt * 2))) - 8;
const float *src = ((const float *) (cvt->buf + cvt->len_cvt)) - 4; const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 4;
int i = cvt->len_cvt / sizeof (float); int i = cvt->len_cvt / sizeof(float);
LOG_DEBUG_CONVERT("mono", "stereo (using SSE)"); LOG_DEBUG_CONVERT("mono", "stereo (using SSE)");
SDL_assert(format == AUDIO_F32SYS); SDL_assert(format == AUDIO_F32SYS);
@@ -142,39 +144,40 @@ SDL_ConvertMonoToStereo_SSE(SDL_AudioCVT * cvt, SDL_AudioFormat format)
while (i >= 4) { /* 4 * float32 */ while (i >= 4) { /* 4 * float32 */
const __m128 input = _mm_loadu_ps(src); /* A B C D */ const __m128 input = _mm_loadu_ps(src); /* A B C D */
_mm_storeu_ps(dst, _mm_unpacklo_ps(input, input)); /* A A B B */ _mm_storeu_ps(dst, _mm_unpacklo_ps(input, input)); /* A A B B */
_mm_storeu_ps(dst+4, _mm_unpackhi_ps(input, input)); /* C C D D */ _mm_storeu_ps(dst + 4, _mm_unpackhi_ps(input, input)); /* C C D D */
i -= 4; src -= 4; dst -= 8; i -= 4;
src -= 4;
dst -= 8;
} }
/* Finish off any leftovers with scalar operations. */ /* Finish off any leftovers with scalar operations. */
src += 3; dst += 6; /* adjust for smaller buffers. */ src += 3;
dst += 6; /* adjust for smaller buffers. */
while (i) { /* convert backwards, since output is growing in-place. */ while (i) { /* convert backwards, since output is growing in-place. */
const float srcFC = src[0]; const float srcFC = src[0];
dst[1] /* FR */ = srcFC; dst[1] /* FR */ = srcFC;
dst[0] /* FL */ = srcFC; dst[0] /* FL */ = srcFC;
i--; src--; dst -= 2; i--;
src--;
dst -= 2;
} }
cvt->len_cvt *= 2; cvt->len_cvt *= 2;
if (cvt->filters[++cvt->filter_index]) { if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index] (cvt, format); cvt->filters[cvt->filter_index](cvt, format);
} }
} }
#endif #endif
/* Include the autogenerated channel converters... */ /* Include the autogenerated channel converters... */
#include "SDL_audio_channel_converters.h" #include "SDL_audio_channel_converters.h"
/* SDL's resampler uses a "bandlimited interpolation" algorithm: /* SDL's resampler uses a "bandlimited interpolation" algorithm:
https://ccrma.stanford.edu/~jos/resample/ */ https://ccrma.stanford.edu/~jos/resample/ */
#include "SDL_audio_resampler_filter.h" #include "SDL_audio_resampler_filter.h"
static int static int ResamplerPadding(const int inrate, const int outrate)
ResamplerPadding(const int inrate, const int outrate)
{ {
if (inrate == outrate) { if (inrate == outrate) {
return 0; return 0;
@@ -186,8 +189,7 @@ ResamplerPadding(const int inrate, const int outrate)
} }
/* lpadding and rpadding are expected to be buffers of (ResamplePadding(inrate, outrate) * chans * sizeof (float)) bytes. */ /* lpadding and rpadding are expected to be buffers of (ResamplePadding(inrate, outrate) * chans * sizeof (float)) bytes. */
static int static int SDL_ResampleAudio(const int chans, const int inrate, const int outrate,
SDL_ResampleAudio(const int chans, const int inrate, const int outrate,
const float *lpadding, const float *rpadding, const float *lpadding, const float *rpadding,
const float *inbuf, const int inbuflen, const float *inbuf, const int inbuflen,
float *outbuf, const int outbuflen) float *outbuf, const int outbuflen)
@@ -197,12 +199,12 @@ SDL_ResampleAudio(const int chans, const int inrate, const int outrate,
on CPUs that need a software fallback for double calculations. */ on CPUs that need a software fallback for double calculations. */
typedef float ResampleFloatType; typedef float ResampleFloatType;
const ResampleFloatType finrate = (ResampleFloatType) inrate; const ResampleFloatType finrate = (ResampleFloatType)inrate;
const ResampleFloatType ratio = ((float) outrate) / ((float) inrate); const ResampleFloatType ratio = ((float)outrate) / ((float)inrate);
const int paddinglen = ResamplerPadding(inrate, outrate); const int paddinglen = ResamplerPadding(inrate, outrate);
const int framelen = chans * (int)sizeof (float); const int framelen = chans * (int)sizeof(float);
const int inframes = inbuflen / framelen; const int inframes = inbuflen / framelen;
const int wantedoutframes = (int) ((inbuflen / framelen) * ratio); /* outbuflen isn't total to write, it's total available. */ const int wantedoutframes = (int)((inbuflen / framelen) * ratio); /* outbuflen isn't total to write, it's total available. */
const int maxoutframes = outbuflen / framelen; const int maxoutframes = outbuflen / framelen;
const int outframes = SDL_min(wantedoutframes, maxoutframes); const int outframes = SDL_min(wantedoutframes, maxoutframes);
ResampleFloatType outtime = 0.0f; ResampleFloatType outtime = 0.0f;
@@ -210,14 +212,14 @@ SDL_ResampleAudio(const int chans, const int inrate, const int outrate,
int i, j, chan; int i, j, chan;
for (i = 0; i < outframes; i++) { for (i = 0; i < outframes; i++) {
const int srcindex = (int) (outtime * inrate); const int srcindex = (int)(outtime * inrate);
const ResampleFloatType intime = ((ResampleFloatType) srcindex) / finrate; const ResampleFloatType intime = ((ResampleFloatType)srcindex) / finrate;
const ResampleFloatType innexttime = ((ResampleFloatType) (srcindex + 1)) / finrate; const ResampleFloatType innexttime = ((ResampleFloatType)(srcindex + 1)) / finrate;
const ResampleFloatType indeltatime = innexttime - intime; const ResampleFloatType indeltatime = innexttime - intime;
const ResampleFloatType interpolation1 = (indeltatime == 0.0f) ? 1.0f : (1.0f - ((innexttime - outtime) / indeltatime)); const ResampleFloatType interpolation1 = (indeltatime == 0.0f) ? 1.0f : (1.0f - ((innexttime - outtime) / indeltatime));
const int filterindex1 = (int) (interpolation1 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING); const int filterindex1 = (int)(interpolation1 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING);
const ResampleFloatType interpolation2 = 1.0f - interpolation1; const ResampleFloatType interpolation2 = 1.0f - interpolation1;
const int filterindex2 = (int) (interpolation2 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING); const int filterindex2 = (int)(interpolation2 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING);
for (chan = 0; chan < chans; chan++) { for (chan = 0; chan < chans; chan++) {
float outsample = 0.0f; float outsample = 0.0f;
@@ -242,14 +244,13 @@ SDL_ResampleAudio(const int chans, const int inrate, const int outrate,
*(dst++) = outsample; *(dst++) = outsample;
} }
outtime = ((ResampleFloatType) i) / ((ResampleFloatType) outrate); outtime = ((ResampleFloatType)i) / ((ResampleFloatType)outrate);
} }
return outframes * chans * sizeof(float); return outframes * chans * sizeof(float);
} }
int int SDL_ConvertAudio(SDL_AudioCVT *cvt)
SDL_ConvertAudio(SDL_AudioCVT * cvt)
{ {
/* !!! FIXME: (cvt) should be const; stack-copy it here. */ /* !!! FIXME: (cvt) should be const; stack-copy it here. */
/* !!! FIXME: (actually, we can't...len_cvt needs to be updated. Grr.) */ /* !!! FIXME: (actually, we can't...len_cvt needs to be updated. Grr.) */
@@ -267,23 +268,23 @@ SDL_ConvertAudio(SDL_AudioCVT * cvt)
/* Set up the conversion and go! */ /* Set up the conversion and go! */
cvt->filter_index = 0; cvt->filter_index = 0;
cvt->filters[0] (cvt, cvt->src_format); cvt->filters[0](cvt, cvt->src_format);
return 0; return 0;
} }
static void SDLCALL static void SDLCALL SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format)
SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{ {
#if DEBUG_CONVERT #if DEBUG_CONVERT
SDL_Log("SDL_AUDIO_CONVERT: Converting byte order\n"); SDL_Log("SDL_AUDIO_CONVERT: Converting byte order\n");
#endif #endif
switch (SDL_AUDIO_BITSIZE(format)) { switch (SDL_AUDIO_BITSIZE(format)) {
#define CASESWAP(b) \ #define CASESWAP(b) \
case b: { \ case b: \
Uint##b *ptr = (Uint##b *) cvt->buf; \ { \
Uint##b *ptr = (Uint##b *)cvt->buf; \
int i; \ int i; \
for (i = cvt->len_cvt / sizeof (*ptr); i; --i, ++ptr) { \ for (i = cvt->len_cvt / sizeof(*ptr); i; --i, ++ptr) { \
*ptr = SDL_Swap##b(*ptr); \ *ptr = SDL_Swap##b(*ptr); \
} \ } \
break; \ break; \
@@ -293,9 +294,11 @@ SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format)
CASESWAP(32); CASESWAP(32);
CASESWAP(64); CASESWAP(64);
#undef CASESWAP #undef CASESWAP
default: SDL_assert(!"unhandled byteswap datatype!"); break; default:
SDL_assert(!"unhandled byteswap datatype!");
break;
} }
if (cvt->filters[++cvt->filter_index]) { if (cvt->filters[++cvt->filter_index]) {
@@ -309,8 +312,7 @@ SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format)
} }
} }
static int static int SDL_AddAudioCVTFilter(SDL_AudioCVT *cvt, const SDL_AudioFilter filter)
SDL_AddAudioCVTFilter(SDL_AudioCVT *cvt, const SDL_AudioFilter filter)
{ {
if (cvt->filter_index >= SDL_AUDIOCVT_MAX_FILTERS) { if (cvt->filter_index >= SDL_AUDIOCVT_MAX_FILTERS) {
return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS); return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS);
@@ -321,8 +323,7 @@ SDL_AddAudioCVTFilter(SDL_AudioCVT *cvt, const SDL_AudioFilter filter)
return 0; return 0;
} }
static int static int SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt)
SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt)
{ {
int retval = 0; /* 0 == no conversion necessary. */ int retval = 0; /* 0 == no conversion necessary. */
@@ -339,12 +340,24 @@ SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt)
SDL_AudioFilter filter = NULL; SDL_AudioFilter filter = NULL;
switch (src_fmt & ~SDL_AUDIO_MASK_ENDIAN) { switch (src_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
case AUDIO_S8: filter = SDL_Convert_S8_to_F32; break; case AUDIO_S8:
case AUDIO_U8: filter = SDL_Convert_U8_to_F32; break; filter = SDL_Convert_S8_to_F32;
case AUDIO_S16: filter = SDL_Convert_S16_to_F32; break; break;
case AUDIO_U16: filter = SDL_Convert_U16_to_F32; break; case AUDIO_U8:
case AUDIO_S32: filter = SDL_Convert_S32_to_F32; break; filter = SDL_Convert_U8_to_F32;
default: SDL_assert(!"Unexpected audio format!"); break; break;
case AUDIO_S16:
filter = SDL_Convert_S16_to_F32;
break;
case AUDIO_U16:
filter = SDL_Convert_U16_to_F32;
break;
case AUDIO_S32:
filter = SDL_Convert_S32_to_F32;
break;
default:
SDL_assert(!"Unexpected audio format!");
break;
} }
if (!filter) { if (!filter) {
@@ -368,8 +381,7 @@ SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt)
return retval; return retval;
} }
static int static int SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt)
SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt)
{ {
int retval = 0; /* 0 == no conversion necessary. */ int retval = 0; /* 0 == no conversion necessary. */
@@ -378,12 +390,24 @@ SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt)
const Uint16 src_bitsize = 32; const Uint16 src_bitsize = 32;
SDL_AudioFilter filter = NULL; SDL_AudioFilter filter = NULL;
switch (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN) { switch (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
case AUDIO_S8: filter = SDL_Convert_F32_to_S8; break; case AUDIO_S8:
case AUDIO_U8: filter = SDL_Convert_F32_to_U8; break; filter = SDL_Convert_F32_to_S8;
case AUDIO_S16: filter = SDL_Convert_F32_to_S16; break; break;
case AUDIO_U16: filter = SDL_Convert_F32_to_U16; break; case AUDIO_U8:
case AUDIO_S32: filter = SDL_Convert_F32_to_S32; break; filter = SDL_Convert_F32_to_U8;
default: SDL_assert(!"Unexpected audio format!"); break; break;
case AUDIO_S16:
filter = SDL_Convert_F32_to_S16;
break;
case AUDIO_U16:
filter = SDL_Convert_F32_to_U16;
break;
case AUDIO_S32:
filter = SDL_Convert_F32_to_S32;
break;
default:
SDL_assert(!"Unexpected audio format!");
break;
} }
if (!filter) { if (!filter) {
@@ -416,12 +440,11 @@ SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt)
#ifdef HAVE_LIBSAMPLERATE_H #ifdef HAVE_LIBSAMPLERATE_H
static void static void SDL_ResampleCVT_SRC(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format)
SDL_ResampleCVT_SRC(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format)
{ {
const float *src = (const float *) cvt->buf; const float *src = (const float *)cvt->buf;
const int srclen = cvt->len_cvt; const int srclen = cvt->len_cvt;
float *dst = (float *) (cvt->buf + srclen); float *dst = (float *)(cvt->buf + srclen);
const int dstlen = (cvt->len * cvt->len_mult) - srclen; const int dstlen = (cvt->len * cvt->len_mult) - srclen;
const int framelen = sizeof(float) * chans; const int framelen = sizeof(float) * chans;
int result = 0; int result = 0;
@@ -438,12 +461,12 @@ SDL_ResampleCVT_SRC(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat fo
data.src_ratio = cvt->rate_incr; data.src_ratio = cvt->rate_incr;
result = SRC_src_simple(&data, SRC_converter, chans); /* Simple API converts the whole buffer at once. No need for initialization. */ result = SRC_src_simple(&data, SRC_converter, chans); /* Simple API converts the whole buffer at once. No need for initialization. */
/* !!! FIXME: Handle library failures? */ /* !!! FIXME: Handle library failures? */
#ifdef DEBUG_CONVERT #ifdef DEBUG_CONVERT
if (result != 0) { if (result != 0) {
SDL_Log("src_simple() failed: %s", SRC_src_strerror(result)); SDL_Log("src_simple() failed: %s", SRC_src_strerror(result));
} }
#endif #endif
cvt->len_cvt = data.output_frames_gen * framelen; cvt->len_cvt = data.output_frames_gen * framelen;
@@ -456,20 +479,19 @@ SDL_ResampleCVT_SRC(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat fo
#endif /* HAVE_LIBSAMPLERATE_H */ #endif /* HAVE_LIBSAMPLERATE_H */
static void static void SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format)
SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format)
{ {
/* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator). /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator).
!!! FIXME in 2.1: We need to store data for this resampler, because the cvt structure doesn't store the original sample rates, !!! FIXME in 2.1: We need to store data for this resampler, because the cvt structure doesn't store the original sample rates,
!!! FIXME in 2.1: so we steal the ninth and tenth slot. :( */ !!! FIXME in 2.1: so we steal the ninth and tenth slot. :( */
const int inrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1]; const int inrate = (int)(size_t)cvt->filters[SDL_AUDIOCVT_MAX_FILTERS - 1];
const int outrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS]; const int outrate = (int)(size_t)cvt->filters[SDL_AUDIOCVT_MAX_FILTERS];
const float *src = (const float *) cvt->buf; const float *src = (const float *)cvt->buf;
const int srclen = cvt->len_cvt; const int srclen = cvt->len_cvt;
/*float *dst = (float *) cvt->buf; /*float *dst = (float *) cvt->buf;
const int dstlen = (cvt->len * cvt->len_mult);*/ const int dstlen = (cvt->len * cvt->len_mult);*/
/* !!! FIXME: remove this if we can get the resampler to work in-place again. */ /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
float *dst = (float *) (cvt->buf + srclen); float *dst = (float *)(cvt->buf + srclen);
const int dstlen = (cvt->len * cvt->len_mult) - srclen; const int dstlen = (cvt->len * cvt->len_mult) - srclen;
const int requestedpadding = ResamplerPadding(inrate, outrate); const int requestedpadding = ResamplerPadding(inrate, outrate);
int paddingsamples; int paddingsamples;
@@ -483,7 +505,7 @@ SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format
SDL_assert(format == AUDIO_F32SYS); SDL_assert(format == AUDIO_F32SYS);
/* we keep no streaming state here, so pad with silence on both ends. */ /* we keep no streaming state here, so pad with silence on both ends. */
padding = (float *) SDL_calloc(paddingsamples ? paddingsamples : 1, sizeof (float)); padding = (float *)SDL_calloc(paddingsamples ? paddingsamples : 1, sizeof(float));
if (padding == NULL) { if (padding == NULL) {
SDL_OutOfMemory(); SDL_OutOfMemory();
return; return;
@@ -506,7 +528,8 @@ SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format
!!! FIXME: vs arbitrary. When we rev the ABI, clean this up. */ !!! FIXME: vs arbitrary. When we rev the ABI, clean this up. */
#define RESAMPLER_FUNCS(chans) \ #define RESAMPLER_FUNCS(chans) \
static void SDLCALL \ static void SDLCALL \
SDL_ResampleCVT_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) { \ SDL_ResampleCVT_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) \
{ \
SDL_ResampleCVT(cvt, chans, format); \ SDL_ResampleCVT(cvt, chans, format); \
} }
RESAMPLER_FUNCS(1) RESAMPLER_FUNCS(1)
@@ -519,7 +542,8 @@ RESAMPLER_FUNCS(8)
#ifdef HAVE_LIBSAMPLERATE_H #ifdef HAVE_LIBSAMPLERATE_H
#define RESAMPLER_FUNCS(chans) \ #define RESAMPLER_FUNCS(chans) \
static void SDLCALL \ static void SDLCALL \
SDL_ResampleCVT_SRC_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) { \ SDL_ResampleCVT_SRC_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) \
{ \
SDL_ResampleCVT_SRC(cvt, chans, format); \ SDL_ResampleCVT_SRC(cvt, chans, format); \
} }
RESAMPLER_FUNCS(1) RESAMPLER_FUNCS(1)
@@ -530,36 +554,46 @@ RESAMPLER_FUNCS(8)
#undef RESAMPLER_FUNCS #undef RESAMPLER_FUNCS
#endif /* HAVE_LIBSAMPLERATE_H */ #endif /* HAVE_LIBSAMPLERATE_H */
static SDL_AudioFilter static SDL_AudioFilter ChooseCVTResampler(const int dst_channels)
ChooseCVTResampler(const int dst_channels)
{ {
#ifdef HAVE_LIBSAMPLERATE_H #ifdef HAVE_LIBSAMPLERATE_H
if (SRC_available) { if (SRC_available) {
switch (dst_channels) { switch (dst_channels) {
case 1: return SDL_ResampleCVT_SRC_c1; case 1:
case 2: return SDL_ResampleCVT_SRC_c2; return SDL_ResampleCVT_SRC_c1;
case 4: return SDL_ResampleCVT_SRC_c4; case 2:
case 6: return SDL_ResampleCVT_SRC_c6; return SDL_ResampleCVT_SRC_c2;
case 8: return SDL_ResampleCVT_SRC_c8; case 4:
default: break; return SDL_ResampleCVT_SRC_c4;
case 6:
return SDL_ResampleCVT_SRC_c6;
case 8:
return SDL_ResampleCVT_SRC_c8;
default:
break;
} }
} }
#endif /* HAVE_LIBSAMPLERATE_H */ #endif /* HAVE_LIBSAMPLERATE_H */
switch (dst_channels) { switch (dst_channels) {
case 1: return SDL_ResampleCVT_c1; case 1:
case 2: return SDL_ResampleCVT_c2; return SDL_ResampleCVT_c1;
case 4: return SDL_ResampleCVT_c4; case 2:
case 6: return SDL_ResampleCVT_c6; return SDL_ResampleCVT_c2;
case 8: return SDL_ResampleCVT_c8; case 4:
default: break; return SDL_ResampleCVT_c4;
case 6:
return SDL_ResampleCVT_c6;
case 8:
return SDL_ResampleCVT_c8;
default:
break;
} }
return NULL; return NULL;
} }
static int static int SDL_BuildAudioResampleCVT(SDL_AudioCVT *cvt, const int dst_channels,
SDL_BuildAudioResampleCVT(SDL_AudioCVT * cvt, const int dst_channels,
const int src_rate, const int dst_rate) const int src_rate, const int dst_rate)
{ {
SDL_AudioFilter filter; SDL_AudioFilter filter;
@@ -581,18 +615,18 @@ SDL_BuildAudioResampleCVT(SDL_AudioCVT * cvt, const int dst_channels,
/* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator). /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator).
!!! FIXME in 2.1: We need to store data for this resampler, because the cvt structure doesn't store the original sample rates, !!! FIXME in 2.1: We need to store data for this resampler, because the cvt structure doesn't store the original sample rates,
!!! FIXME in 2.1: so we steal the ninth and tenth slot. :( */ !!! FIXME in 2.1: so we steal the ninth and tenth slot. :( */
if (cvt->filter_index >= (SDL_AUDIOCVT_MAX_FILTERS-2)) { if (cvt->filter_index >= (SDL_AUDIOCVT_MAX_FILTERS - 2)) {
return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS - 2); return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS - 2);
} }
cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1] = (SDL_AudioFilter) (uintptr_t) src_rate; cvt->filters[SDL_AUDIOCVT_MAX_FILTERS - 1] = (SDL_AudioFilter)(uintptr_t)src_rate;
cvt->filters[SDL_AUDIOCVT_MAX_FILTERS] = (SDL_AudioFilter) (uintptr_t) dst_rate; cvt->filters[SDL_AUDIOCVT_MAX_FILTERS] = (SDL_AudioFilter)(uintptr_t)dst_rate;
if (src_rate < dst_rate) { if (src_rate < dst_rate) {
const double mult = ((double) dst_rate) / ((double) src_rate); const double mult = ((double)dst_rate) / ((double)src_rate);
cvt->len_mult *= (int) SDL_ceil(mult); cvt->len_mult *= (int)SDL_ceil(mult);
cvt->len_ratio *= mult; cvt->len_ratio *= mult;
} else { } else {
cvt->len_ratio /= ((double) src_rate) / ((double) dst_rate); cvt->len_ratio /= ((double)src_rate) / ((double)dst_rate);
} }
/* !!! FIXME: remove this if we can get the resampler to work in-place again. */ /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
@@ -603,8 +637,7 @@ SDL_BuildAudioResampleCVT(SDL_AudioCVT * cvt, const int dst_channels,
return 1; /* added a converter. */ return 1; /* added a converter. */
} }
static SDL_bool static SDL_bool SDL_SupportedAudioFormat(const SDL_AudioFormat fmt)
SDL_SupportedAudioFormat(const SDL_AudioFormat fmt)
{ {
switch (fmt) { switch (fmt) {
case AUDIO_U8: case AUDIO_U8:
@@ -626,20 +659,17 @@ SDL_SupportedAudioFormat(const SDL_AudioFormat fmt)
return SDL_FALSE; /* unsupported. */ return SDL_FALSE; /* unsupported. */
} }
static SDL_bool static SDL_bool SDL_SupportedChannelCount(const int channels)
SDL_SupportedChannelCount(const int channels)
{ {
return ((channels >= 1) && (channels <= 8)) ? SDL_TRUE : SDL_FALSE; return ((channels >= 1) && (channels <= 8)) ? SDL_TRUE : SDL_FALSE;
} }
/* Creates a set of audio filters to convert from one format to another. /* Creates a set of audio filters to convert from one format to another.
Returns 0 if no conversion is needed, 1 if the audio filter is set up, Returns 0 if no conversion is needed, 1 if the audio filter is set up,
or -1 if an error like invalid parameter, unsupported format, etc. occurred. or -1 if an error like invalid parameter, unsupported format, etc. occurred.
*/ */
int int SDL_BuildAudioCVT(SDL_AudioCVT *cvt,
SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
SDL_AudioFormat src_fmt, Uint8 src_channels, int src_rate, SDL_AudioFormat src_fmt, Uint8 src_channels, int src_rate,
SDL_AudioFormat dst_fmt, Uint8 dst_channels, int dst_rate) SDL_AudioFormat dst_fmt, Uint8 dst_channels, int dst_rate)
{ {
@@ -691,7 +721,7 @@ SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
SDL_zeroa(cvt->filters); SDL_zeroa(cvt->filters);
cvt->len_mult = 1; cvt->len_mult = 1;
cvt->len_ratio = 1.0; cvt->len_ratio = 1.0;
cvt->rate_incr = ((double) dst_rate) / ((double) src_rate); cvt->rate_incr = ((double)dst_rate) / ((double)src_rate);
/* Make sure we've chosen audio conversion functions (SIMD, scalar, etc.) */ /* Make sure we've chosen audio conversion functions (SIMD, scalar, etc.) */
SDL_ChooseAudioConverters(); SDL_ChooseAudioConverters();
@@ -734,14 +764,13 @@ SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
return -1; /* shouldn't happen, but just in case... */ return -1; /* shouldn't happen, but just in case... */
} }
/* Channel conversion */ /* Channel conversion */
/* SDL_SupportedChannelCount should have caught these asserts, or we added a new format and forgot to update the table. */ /* SDL_SupportedChannelCount should have caught these asserts, or we added a new format and forgot to update the table. */
SDL_assert(src_channels <= SDL_arraysize(channel_converters)); SDL_assert(src_channels <= SDL_arraysize(channel_converters));
SDL_assert(dst_channels <= SDL_arraysize(channel_converters[0])); SDL_assert(dst_channels <= SDL_arraysize(channel_converters[0]));
channel_converter = channel_converters[src_channels-1][dst_channels-1]; channel_converter = channel_converters[src_channels - 1][dst_channels - 1];
if ((channel_converter == NULL) != (src_channels == dst_channels)) { if ((channel_converter == NULL) != (src_channels == dst_channels)) {
/* All combinations of supported channel counts should have been handled by now, but let's be defensive */ /* All combinations of supported channel counts should have been handled by now, but let's be defensive */
return SDL_SetError("Invalid channel combination"); return SDL_SetError("Invalid channel combination");
@@ -749,16 +778,24 @@ SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
/* swap in some SIMD versions for a few of these. */ /* swap in some SIMD versions for a few of these. */
if (channel_converter == SDL_ConvertStereoToMono) { if (channel_converter == SDL_ConvertStereoToMono) {
SDL_AudioFilter filter = NULL; SDL_AudioFilter filter = NULL;
#if HAVE_SSE3_INTRINSICS #if HAVE_SSE3_INTRINSICS
if (!filter && SDL_HasSSE3()) { filter = SDL_ConvertStereoToMono_SSE3; } if (!filter && SDL_HasSSE3()) {
#endif filter = SDL_ConvertStereoToMono_SSE3;
if (filter) { channel_converter = filter; } }
#endif
if (filter) {
channel_converter = filter;
}
} else if (channel_converter == SDL_ConvertMonoToStereo) { } else if (channel_converter == SDL_ConvertMonoToStereo) {
SDL_AudioFilter filter = NULL; SDL_AudioFilter filter = NULL;
#if HAVE_SSE_INTRINSICS #if HAVE_SSE_INTRINSICS
if (!filter && SDL_HasSSE()) { filter = SDL_ConvertMonoToStereo_SSE; } if (!filter && SDL_HasSSE()) {
#endif filter = SDL_ConvertMonoToStereo_SSE;
if (filter) { channel_converter = filter; } }
#endif
if (filter) {
channel_converter = filter;
}
} }
if (SDL_AddAudioCVTFilter(cvt, channel_converter) < 0) { if (SDL_AddAudioCVTFilter(cvt, channel_converter) < 0) {
@@ -766,7 +803,7 @@ SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
} }
if (src_channels < dst_channels) { if (src_channels < dst_channels) {
cvt->len_mult = ((cvt->len_mult * dst_channels) + (src_channels-1)) / src_channels; cvt->len_mult = ((cvt->len_mult * dst_channels) + (src_channels - 1)) / src_channels;
} }
cvt->len_ratio = (cvt->len_ratio * dst_channels) / src_channels; cvt->len_ratio = (cvt->len_ratio * dst_channels) / src_channels;
@@ -821,8 +858,7 @@ struct _SDL_AudioStream
SDL_CleanupAudioStreamResamplerFunc cleanup_resampler_func; SDL_CleanupAudioStreamResamplerFunc cleanup_resampler_func;
}; };
static Uint8 * static Uint8 *EnsureStreamBufferSize(SDL_AudioStream *stream, const int newlen)
EnsureStreamBufferSize(SDL_AudioStream *stream, const int newlen)
{ {
Uint8 *ptr; Uint8 *ptr;
size_t offset; size_t offset;
@@ -830,7 +866,7 @@ EnsureStreamBufferSize(SDL_AudioStream *stream, const int newlen)
if (stream->work_buffer_len >= newlen) { if (stream->work_buffer_len >= newlen) {
ptr = stream->work_buffer_base; ptr = stream->work_buffer_base;
} else { } else {
ptr = (Uint8 *) SDL_realloc(stream->work_buffer_base, newlen + 32); ptr = (Uint8 *)SDL_realloc(stream->work_buffer_base, newlen + 32);
if (ptr == NULL) { if (ptr == NULL) {
SDL_OutOfMemory(); SDL_OutOfMemory();
return NULL; return NULL;
@@ -840,22 +876,21 @@ EnsureStreamBufferSize(SDL_AudioStream *stream, const int newlen)
stream->work_buffer_len = newlen; stream->work_buffer_len = newlen;
} }
offset = ((size_t) ptr) & 15; offset = ((size_t)ptr) & 15;
return offset ? ptr + (16 - offset) : ptr; return offset ? ptr + (16 - offset) : ptr;
} }
#ifdef HAVE_LIBSAMPLERATE_H #ifdef HAVE_LIBSAMPLERATE_H
static int static int SDL_ResampleAudioStream_SRC(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
SDL_ResampleAudioStream_SRC(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
{ {
const float *inbuf = (const float *) _inbuf; const float *inbuf = (const float *)_inbuf;
float *outbuf = (float *) _outbuf; float *outbuf = (float *)_outbuf;
const int framelen = sizeof(float) * stream->pre_resample_channels; const int framelen = sizeof(float) * stream->pre_resample_channels;
SRC_STATE *state = (SRC_STATE *)stream->resampler_state; SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
SRC_DATA data; SRC_DATA data;
int result; int result;
SDL_assert(inbuf != ((const float *) outbuf)); /* SDL_AudioStreamPut() shouldn't allow in-place resamples. */ SDL_assert(inbuf != ((const float *)outbuf)); /* SDL_AudioStreamPut() shouldn't allow in-place resamples. */
data.data_in = (float *)inbuf; /* Older versions of libsamplerate had a non-const pointer, but didn't write to it */ data.data_in = (float *)inbuf; /* Older versions of libsamplerate had a non-const pointer, but didn't write to it */
data.input_frames = inbuflen / framelen; data.input_frames = inbuflen / framelen;
@@ -879,14 +914,12 @@ SDL_ResampleAudioStream_SRC(SDL_AudioStream *stream, const void *_inbuf, const i
return data.output_frames_gen * (sizeof(float) * stream->pre_resample_channels); return data.output_frames_gen * (sizeof(float) * stream->pre_resample_channels);
} }
static void static void SDL_ResetAudioStreamResampler_SRC(SDL_AudioStream *stream)
SDL_ResetAudioStreamResampler_SRC(SDL_AudioStream *stream)
{ {
SRC_src_reset((SRC_STATE *)stream->resampler_state); SRC_src_reset((SRC_STATE *)stream->resampler_state);
} }
static void static void SDL_CleanupAudioStreamResampler_SRC(SDL_AudioStream *stream)
SDL_CleanupAudioStreamResampler_SRC(SDL_AudioStream *stream)
{ {
SRC_STATE *state = (SRC_STATE *)stream->resampler_state; SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
if (state) { if (state) {
@@ -899,8 +932,7 @@ SDL_CleanupAudioStreamResampler_SRC(SDL_AudioStream *stream)
stream->cleanup_resampler_func = NULL; stream->cleanup_resampler_func = NULL;
} }
static SDL_bool static SDL_bool SetupLibSampleRateResampling(SDL_AudioStream *stream)
SetupLibSampleRateResampling(SDL_AudioStream *stream)
{ {
int result = 0; int result = 0;
SRC_STATE *state = NULL; SRC_STATE *state = NULL;
@@ -926,42 +958,38 @@ SetupLibSampleRateResampling(SDL_AudioStream *stream)
} }
#endif /* HAVE_LIBSAMPLERATE_H */ #endif /* HAVE_LIBSAMPLERATE_H */
static int SDL_ResampleAudioStream(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
static int
SDL_ResampleAudioStream(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
{ {
const Uint8 *inbufend = ((const Uint8 *) _inbuf) + inbuflen; const Uint8 *inbufend = ((const Uint8 *)_inbuf) + inbuflen;
const float *inbuf = (const float *) _inbuf; const float *inbuf = (const float *)_inbuf;
float *outbuf = (float *) _outbuf; float *outbuf = (float *)_outbuf;
const int chans = (int) stream->pre_resample_channels; const int chans = (int)stream->pre_resample_channels;
const int inrate = stream->src_rate; const int inrate = stream->src_rate;
const int outrate = stream->dst_rate; const int outrate = stream->dst_rate;
const int paddingsamples = stream->resampler_padding_samples; const int paddingsamples = stream->resampler_padding_samples;
const int paddingbytes = paddingsamples * sizeof (float); const int paddingbytes = paddingsamples * sizeof(float);
float *lpadding = (float *) stream->resampler_state; float *lpadding = (float *)stream->resampler_state;
const float *rpadding = (const float *) inbufend; /* we set this up so there are valid padding samples at the end of the input buffer. */ const float *rpadding = (const float *)inbufend; /* we set this up so there are valid padding samples at the end of the input buffer. */
const int cpy = SDL_min(inbuflen, paddingbytes); const int cpy = SDL_min(inbuflen, paddingbytes);
int retval; int retval;
SDL_assert(inbuf != ((const float *) outbuf)); /* SDL_AudioStreamPut() shouldn't allow in-place resamples. */ SDL_assert(inbuf != ((const float *)outbuf)); /* SDL_AudioStreamPut() shouldn't allow in-place resamples. */
retval = SDL_ResampleAudio(chans, inrate, outrate, lpadding, rpadding, inbuf, inbuflen, outbuf, outbuflen); retval = SDL_ResampleAudio(chans, inrate, outrate, lpadding, rpadding, inbuf, inbuflen, outbuf, outbuflen);
/* update our left padding with end of current input, for next run. */ /* update our left padding with end of current input, for next run. */
SDL_memcpy((lpadding + paddingsamples) - (cpy / sizeof (float)), inbufend - cpy, cpy); SDL_memcpy((lpadding + paddingsamples) - (cpy / sizeof(float)), inbufend - cpy, cpy);
return retval; return retval;
} }
static void static void SDL_ResetAudioStreamResampler(SDL_AudioStream *stream)
SDL_ResetAudioStreamResampler(SDL_AudioStream *stream)
{ {
/* set all the padding to silence. */ /* set all the padding to silence. */
const int len = stream->resampler_padding_samples; const int len = stream->resampler_padding_samples;
SDL_memset(stream->resampler_state, '\0', len * sizeof (float)); SDL_memset(stream->resampler_state, '\0', len * sizeof(float));
} }
static void static void SDL_CleanupAudioStreamResampler(SDL_AudioStream *stream)
SDL_CleanupAudioStreamResampler(SDL_AudioStream *stream)
{ {
SDL_free(stream->resampler_state); SDL_free(stream->resampler_state);
} }
@@ -978,7 +1006,7 @@ SDL_NewAudioStream(const SDL_AudioFormat src_format,
Uint8 pre_resample_channels; Uint8 pre_resample_channels;
SDL_AudioStream *retval; SDL_AudioStream *retval;
retval = (SDL_AudioStream *) SDL_calloc(1, sizeof (SDL_AudioStream)); retval = (SDL_AudioStream *)SDL_calloc(1, sizeof(SDL_AudioStream));
if (retval == NULL) { if (retval == NULL) {
SDL_OutOfMemory(); SDL_OutOfMemory();
return NULL; return NULL;
@@ -1001,9 +1029,9 @@ SDL_NewAudioStream(const SDL_AudioFormat src_format,
retval->dst_rate = dst_rate; retval->dst_rate = dst_rate;
retval->pre_resample_channels = pre_resample_channels; retval->pre_resample_channels = pre_resample_channels;
retval->packetlen = packetlen; retval->packetlen = packetlen;
retval->rate_incr = ((double) dst_rate) / ((double) src_rate); retval->rate_incr = ((double)dst_rate) / ((double)src_rate);
retval->resampler_padding_samples = ResamplerPadding(retval->src_rate, retval->dst_rate) * pre_resample_channels; retval->resampler_padding_samples = ResamplerPadding(retval->src_rate, retval->dst_rate) * pre_resample_channels;
retval->resampler_padding = (float *) SDL_calloc(retval->resampler_padding_samples ? retval->resampler_padding_samples : 1, sizeof (float)); retval->resampler_padding = (float *)SDL_calloc(retval->resampler_padding_samples ? retval->resampler_padding_samples : 1, sizeof(float));
if (retval->resampler_padding == NULL) { if (retval->resampler_padding == NULL) {
SDL_FreeAudioStream(retval); SDL_FreeAudioStream(retval);
@@ -1013,7 +1041,7 @@ SDL_NewAudioStream(const SDL_AudioFormat src_format,
retval->staging_buffer_size = ((retval->resampler_padding_samples / retval->pre_resample_channels) * retval->src_sample_frame_size); retval->staging_buffer_size = ((retval->resampler_padding_samples / retval->pre_resample_channels) * retval->src_sample_frame_size);
if (retval->staging_buffer_size > 0) { if (retval->staging_buffer_size > 0) {
retval->staging_buffer = (Uint8 *) SDL_malloc(retval->staging_buffer_size); retval->staging_buffer = (Uint8 *)SDL_malloc(retval->staging_buffer_size);
if (retval->staging_buffer == NULL) { if (retval->staging_buffer == NULL) {
SDL_FreeAudioStream(retval); SDL_FreeAudioStream(retval);
SDL_OutOfMemory(); SDL_OutOfMemory();
@@ -1041,7 +1069,7 @@ SDL_NewAudioStream(const SDL_AudioFormat src_format,
#endif #endif
if (!retval->resampler_func) { if (!retval->resampler_func) {
retval->resampler_state = SDL_calloc(retval->resampler_padding_samples, sizeof (float)); retval->resampler_state = SDL_calloc(retval->resampler_padding_samples, sizeof(float));
if (!retval->resampler_state) { if (!retval->resampler_state) {
SDL_FreeAudioStream(retval); SDL_FreeAudioStream(retval);
SDL_OutOfMemory(); SDL_OutOfMemory();
@@ -1069,8 +1097,7 @@ SDL_NewAudioStream(const SDL_AudioFormat src_format,
return retval; return retval;
} }
static int static int SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, int *maxputbytes)
SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, int *maxputbytes)
{ {
int buflen = len; int buflen = len;
int workbuflen; int workbuflen;
@@ -1089,7 +1116,7 @@ SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, in
!!! FIXME: a few samples at the end and convert them separately. */ !!! FIXME: a few samples at the end and convert them separately. */
/* no padding prepended on first run. */ /* no padding prepended on first run. */
neededpaddingbytes = stream->resampler_padding_samples * sizeof (float); neededpaddingbytes = stream->resampler_padding_samples * sizeof(float);
paddingbytes = stream->first_run ? 0 : neededpaddingbytes; paddingbytes = stream->first_run ? 0 : neededpaddingbytes;
stream->first_run = SDL_FALSE; stream->first_run = SDL_FALSE;
@@ -1101,12 +1128,12 @@ SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, in
if (stream->dst_rate != stream->src_rate) { if (stream->dst_rate != stream->src_rate) {
/* resamples can't happen in place, so make space for second buf. */ /* resamples can't happen in place, so make space for second buf. */
const int framesize = stream->pre_resample_channels * sizeof (float); const int framesize = stream->pre_resample_channels * sizeof(float);
const int frames = workbuflen / framesize; const int frames = workbuflen / framesize;
resamplebuflen = ((int) SDL_ceil(frames * stream->rate_incr)) * framesize; resamplebuflen = ((int)SDL_ceil(frames * stream->rate_incr)) * framesize;
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: will resample %d bytes to %d (ratio=%.6f)\n", workbuflen, resamplebuflen, stream->rate_incr); SDL_Log("AUDIOSTREAM: will resample %d bytes to %d (ratio=%.6f)\n", workbuflen, resamplebuflen, stream->rate_incr);
#endif #endif
workbuflen += resamplebuflen; workbuflen += resamplebuflen;
} }
@@ -1117,9 +1144,9 @@ SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, in
workbuflen += neededpaddingbytes; workbuflen += neededpaddingbytes;
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: Putting %d bytes of preconverted audio, need %d byte work buffer\n", buflen, workbuflen); SDL_Log("AUDIOSTREAM: Putting %d bytes of preconverted audio, need %d byte work buffer\n", buflen, workbuflen);
#endif #endif
workbuf = EnsureStreamBufferSize(stream, workbuflen); workbuf = EnsureStreamBufferSize(stream, workbuflen);
if (workbuf == NULL) { if (workbuf == NULL) {
@@ -1138,9 +1165,9 @@ SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, in
} }
buflen = stream->cvt_before_resampling.len_cvt; buflen = stream->cvt_before_resampling.len_cvt;
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: After initial conversion we have %d bytes\n", buflen); SDL_Log("AUDIOSTREAM: After initial conversion we have %d bytes\n", buflen);
#endif #endif
} }
if (stream->dst_rate != stream->src_rate) { if (stream->dst_rate != stream->src_rate) {
@@ -1165,9 +1192,9 @@ SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, in
buflen = 0; buflen = 0;
} }
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: After resampling we have %d bytes\n", buflen); SDL_Log("AUDIOSTREAM: After resampling we have %d bytes\n", buflen);
#endif #endif
} }
if (stream->cvt_after_resampling.needed && (buflen > 0)) { if (stream->cvt_after_resampling.needed && (buflen > 0)) {
@@ -1178,14 +1205,14 @@ SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, in
} }
buflen = stream->cvt_after_resampling.len_cvt; buflen = stream->cvt_after_resampling.len_cvt;
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: After final conversion we have %d bytes\n", buflen); SDL_Log("AUDIOSTREAM: After final conversion we have %d bytes\n", buflen);
#endif #endif
} }
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: Final output is %d bytes\n", buflen); SDL_Log("AUDIOSTREAM: Final output is %d bytes\n", buflen);
#endif #endif
if (maxputbytes) { if (maxputbytes) {
const int maxbytes = *maxputbytes; const int maxbytes = *maxputbytes;
@@ -1199,8 +1226,7 @@ SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, in
return buflen ? SDL_WriteToDataQueue(stream->queue, resamplebuf, buflen) : 0; return buflen ? SDL_WriteToDataQueue(stream->queue, resamplebuf, buflen) : 0;
} }
int int SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len)
SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len)
{ {
/* !!! FIXME: several converters can take advantage of SIMD, but only /* !!! FIXME: several converters can take advantage of SIMD, but only
!!! FIXME: if the data is aligned to 16 bytes. EnsureStreamBufferSize() !!! FIXME: if the data is aligned to 16 bytes. EnsureStreamBufferSize()
@@ -1210,9 +1236,9 @@ SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len)
!!! FIXME: isn't a multiple of 16. In these cases, we should chop off !!! FIXME: isn't a multiple of 16. In these cases, we should chop off
!!! FIXME: a few samples at the end and convert them separately. */ !!! FIXME: a few samples at the end and convert them separately. */
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: wants to put %d preconverted bytes\n", buflen); SDL_Log("AUDIOSTREAM: wants to put %d preconverted bytes\n", buflen);
#endif #endif
if (stream == NULL) { if (stream == NULL) {
return SDL_InvalidParamError("stream"); return SDL_InvalidParamError("stream");
@@ -1230,9 +1256,9 @@ SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len)
if (!stream->cvt_before_resampling.needed && if (!stream->cvt_before_resampling.needed &&
(stream->dst_rate == stream->src_rate) && (stream->dst_rate == stream->src_rate) &&
!stream->cvt_after_resampling.needed) { !stream->cvt_after_resampling.needed) {
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: no conversion needed at all, queueing %d bytes.\n", len); SDL_Log("AUDIOSTREAM: no conversion needed at all, queueing %d bytes.\n", len);
#endif #endif
return SDL_WriteToDataQueue(stream->queue, buf, len); return SDL_WriteToDataQueue(stream->queue, buf, len);
} }
@@ -1273,9 +1299,9 @@ int SDL_AudioStreamFlush(SDL_AudioStream *stream)
return SDL_InvalidParamError("stream"); return SDL_InvalidParamError("stream");
} }
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: flushing! staging_buffer_filled=%d bytes\n", stream->staging_buffer_filled); SDL_Log("AUDIOSTREAM: flushing! staging_buffer_filled=%d bytes\n", stream->staging_buffer_filled);
#endif #endif
/* shouldn't use a staging buffer if we're not resampling. */ /* shouldn't use a staging buffer if we're not resampling. */
SDL_assert((stream->dst_rate != stream->src_rate) || (stream->staging_buffer_filled == 0)); SDL_assert((stream->dst_rate != stream->src_rate) || (stream->staging_buffer_filled == 0));
@@ -1293,11 +1319,11 @@ int SDL_AudioStreamFlush(SDL_AudioStream *stream)
if (actual_input_frames > 0) { /* don't bother if nothing to flush. */ if (actual_input_frames > 0) { /* don't bother if nothing to flush. */
/* This is how many bytes we're expecting without silence appended. */ /* This is how many bytes we're expecting without silence appended. */
int flush_remaining = ((int) SDL_ceil(actual_input_frames * stream->rate_incr)) * stream->dst_sample_frame_size; int flush_remaining = ((int)SDL_ceil(actual_input_frames * stream->rate_incr)) * stream->dst_sample_frame_size;
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: flushing with padding to get max %d bytes!\n", flush_remaining); SDL_Log("AUDIOSTREAM: flushing with padding to get max %d bytes!\n", flush_remaining);
#endif #endif
SDL_memset(stream->staging_buffer + filled, '\0', stream->staging_buffer_size - filled); SDL_memset(stream->staging_buffer + filled, '\0', stream->staging_buffer_size - filled);
if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, &flush_remaining) < 0) { if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, &flush_remaining) < 0) {
@@ -1321,12 +1347,11 @@ int SDL_AudioStreamFlush(SDL_AudioStream *stream)
} }
/* get converted/resampled data from the stream */ /* get converted/resampled data from the stream */
int int SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, int len)
SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, int len)
{ {
#if DEBUG_AUDIOSTREAM #if DEBUG_AUDIOSTREAM
SDL_Log("AUDIOSTREAM: want to get %d converted bytes\n", len); SDL_Log("AUDIOSTREAM: want to get %d converted bytes\n", len);
#endif #endif
if (stream == NULL) { if (stream == NULL) {
return SDL_InvalidParamError("stream"); return SDL_InvalidParamError("stream");
@@ -1345,14 +1370,12 @@ SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, int len)
} }
/* number of converted/resampled bytes available */ /* number of converted/resampled bytes available */
int int SDL_AudioStreamAvailable(SDL_AudioStream *stream)
SDL_AudioStreamAvailable(SDL_AudioStream *stream)
{ {
return stream ? (int)SDL_CountDataQueue(stream->queue) : 0; return stream ? (int)SDL_CountDataQueue(stream->queue) : 0;
} }
void void SDL_AudioStreamClear(SDL_AudioStream *stream)
SDL_AudioStreamClear(SDL_AudioStream *stream)
{ {
if (stream == NULL) { if (stream == NULL) {
SDL_InvalidParamError("stream"); SDL_InvalidParamError("stream");
@@ -1367,8 +1390,7 @@ SDL_AudioStreamClear(SDL_AudioStream *stream)
} }
/* dispose of a stream */ /* dispose of a stream */
void void SDL_FreeAudioStream(SDL_AudioStream *stream)
SDL_FreeAudioStream(SDL_AudioStream *stream)
{ {
if (stream) { if (stream) {
if (stream->cleanup_resampler_func) { if (stream->cleanup_resampler_func) {

View File

@@ -45,8 +45,7 @@
#define _PATH_DEV_AUDIO "/dev/audio" #define _PATH_DEV_AUDIO "/dev/audio"
#endif #endif
static void static void test_device(const int iscapture, const char *fname, int flags, int (*test)(int fd))
test_device(const int iscapture, const char *fname, int flags, int (*test) (int fd))
{ {
struct stat sb; struct stat sb;
if ((stat(fname, &sb) == 0) && (S_ISCHR(sb.st_mode))) { if ((stat(fname, &sb) == 0) && (S_ISCHR(sb.st_mode))) {
@@ -64,20 +63,18 @@ test_device(const int iscapture, const char *fname, int flags, int (*test) (int
* information, making this information inaccessible at * information, making this information inaccessible at
* enumeration time * enumeration time
*/ */
SDL_AddAudioDevice(iscapture, fname, NULL, (void *) (uintptr_t) dummyhandle); SDL_AddAudioDevice(iscapture, fname, NULL, (void *)(uintptr_t)dummyhandle);
} }
} }
} }
} }
static int static int test_stub(int fd)
test_stub(int fd)
{ {
return 1; return 1;
} }
static void static void SDL_EnumUnixAudioDevices_Internal(const int iscapture, const int classic, int (*test)(int))
SDL_EnumUnixAudioDevices_Internal(const int iscapture, const int classic, int (*test)(int))
{ {
const int flags = iscapture ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT; const int flags = iscapture ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT;
const char *audiodev; const char *audiodev;
@@ -96,9 +93,7 @@ SDL_EnumUnixAudioDevices_Internal(const int iscapture, const int classic, int (*
struct stat sb; struct stat sb;
/* Added support for /dev/sound/\* in Linux 2.4 */ /* Added support for /dev/sound/\* in Linux 2.4 */
if (((stat("/dev/sound", &sb) == 0) && S_ISDIR(sb.st_mode)) if (((stat("/dev/sound", &sb) == 0) && S_ISDIR(sb.st_mode)) && ((stat(_PATH_DEV_DSP24, &sb) == 0) && S_ISCHR(sb.st_mode))) {
&& ((stat(_PATH_DEV_DSP24, &sb) == 0)
&& S_ISCHR(sb.st_mode))) {
audiodev = _PATH_DEV_DSP24; audiodev = _PATH_DEV_DSP24;
} else { } else {
audiodev = _PATH_DEV_DSP; audiodev = _PATH_DEV_DSP;
@@ -118,8 +113,7 @@ SDL_EnumUnixAudioDevices_Internal(const int iscapture, const int classic, int (*
} }
} }
void void SDL_EnumUnixAudioDevices(const int classic, int (*test)(int))
SDL_EnumUnixAudioDevices(const int classic, int (*test)(int))
{ {
SDL_EnumUnixAudioDevices_Internal(SDL_TRUE, classic, test); SDL_EnumUnixAudioDevices_Internal(SDL_TRUE, classic, test);
SDL_EnumUnixAudioDevices_Internal(SDL_FALSE, classic, test); SDL_EnumUnixAudioDevices_Internal(SDL_FALSE, classic, test);

View File

@@ -32,8 +32,8 @@
#define OPEN_FLAGS_OUTPUT O_WRONLY #define OPEN_FLAGS_OUTPUT O_WRONLY
#define OPEN_FLAGS_INPUT O_RDONLY #define OPEN_FLAGS_INPUT O_RDONLY
#else #else
#define OPEN_FLAGS_OUTPUT (O_WRONLY|O_NONBLOCK) #define OPEN_FLAGS_OUTPUT (O_WRONLY | O_NONBLOCK)
#define OPEN_FLAGS_INPUT (O_RDONLY|O_NONBLOCK) #define OPEN_FLAGS_INPUT (O_RDONLY | O_NONBLOCK)
#endif #endif
extern void SDL_EnumUnixAudioDevices(const int classic, int (*test)(int)); extern void SDL_EnumUnixAudioDevices(const int classic, int (*test)(int));

File diff suppressed because it is too large Load Diff

View File

@@ -78,13 +78,11 @@ static const Uint8 mix8[] = {
}; };
/* The volume ranges from 0 - 128 */ /* The volume ranges from 0 - 128 */
#define ADJUST_VOLUME(s, v) (s = (s*v)/SDL_MIX_MAXVOLUME) #define ADJUST_VOLUME(s, v) (s = (s * v) / SDL_MIX_MAXVOLUME)
#define ADJUST_VOLUME_U8(s, v) (s = (((s-128)*v)/SDL_MIX_MAXVOLUME)+128) #define ADJUST_VOLUME_U8(s, v) (s = (((s - 128) * v) / SDL_MIX_MAXVOLUME) + 128)
#define ADJUST_VOLUME_U16(s, v) (s = (((s-32768)*v)/SDL_MIX_MAXVOLUME)+32768) #define ADJUST_VOLUME_U16(s, v) (s = (((s - 32768) * v) / SDL_MIX_MAXVOLUME) + 32768)
void SDL_MixAudioFormat(Uint8 *dst, const Uint8 *src, SDL_AudioFormat format,
void
SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
Uint32 len, int volume) Uint32 len, int volume)
{ {
if (volume == 0) { if (volume == 0) {
@@ -104,8 +102,7 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
++dst; ++dst;
++src; ++src;
} }
} } break;
break;
case AUDIO_S8: case AUDIO_S8:
{ {
@@ -115,8 +112,8 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
const int max_audioval = SDL_MAX_SINT8; const int max_audioval = SDL_MAX_SINT8;
const int min_audioval = SDL_MIN_SINT8; const int min_audioval = SDL_MIN_SINT8;
src8 = (Sint8 *) src; src8 = (Sint8 *)src;
dst8 = (Sint8 *) dst; dst8 = (Sint8 *)dst;
while (len--) { while (len--) {
src_sample = *src8; src_sample = *src8;
ADJUST_VOLUME(src_sample, volume); ADJUST_VOLUME(src_sample, volume);
@@ -130,8 +127,7 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
++dst8; ++dst8;
++src8; ++src8;
} }
} } break;
break;
case AUDIO_S16LSB: case AUDIO_S16LSB:
{ {
@@ -155,8 +151,7 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
*(Sint16 *)dst = SDL_SwapLE16(dst_sample); *(Sint16 *)dst = SDL_SwapLE16(dst_sample);
dst += 2; dst += 2;
} }
} } break;
break;
case AUDIO_S16MSB: case AUDIO_S16MSB:
{ {
@@ -180,8 +175,7 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
*(Sint16 *)dst = SDL_SwapBE16(dst_sample); *(Sint16 *)dst = SDL_SwapBE16(dst_sample);
dst += 2; dst += 2;
} }
} } break;
break;
case AUDIO_U16LSB: case AUDIO_U16LSB:
{ {
@@ -206,8 +200,7 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
*(Uint16 *)dst = SDL_SwapLE16(dst_sample); *(Uint16 *)dst = SDL_SwapLE16(dst_sample);
dst += 2; dst += 2;
} }
} } break;
break;
case AUDIO_U16MSB: case AUDIO_U16MSB:
{ {
@@ -232,13 +225,12 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
*(Uint16 *)dst = SDL_SwapBE16(dst_sample); *(Uint16 *)dst = SDL_SwapBE16(dst_sample);
dst += 2; dst += 2;
} }
} } break;
break;
case AUDIO_S32LSB: case AUDIO_S32LSB:
{ {
const Uint32 *src32 = (Uint32 *) src; const Uint32 *src32 = (Uint32 *)src;
Uint32 *dst32 = (Uint32 *) dst; Uint32 *dst32 = (Uint32 *)dst;
Sint64 src1, src2; Sint64 src1, src2;
Sint64 dst_sample; Sint64 dst_sample;
const Sint64 max_audioval = SDL_MAX_SINT32; const Sint64 max_audioval = SDL_MAX_SINT32;
@@ -246,25 +238,24 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
len /= 4; len /= 4;
while (len--) { while (len--) {
src1 = (Sint64) ((Sint32) SDL_SwapLE32(*src32)); src1 = (Sint64)((Sint32)SDL_SwapLE32(*src32));
src32++; src32++;
ADJUST_VOLUME(src1, volume); ADJUST_VOLUME(src1, volume);
src2 = (Sint64) ((Sint32) SDL_SwapLE32(*dst32)); src2 = (Sint64)((Sint32)SDL_SwapLE32(*dst32));
dst_sample = src1 + src2; dst_sample = src1 + src2;
if (dst_sample > max_audioval) { if (dst_sample > max_audioval) {
dst_sample = max_audioval; dst_sample = max_audioval;
} else if (dst_sample < min_audioval) { } else if (dst_sample < min_audioval) {
dst_sample = min_audioval; dst_sample = min_audioval;
} }
*(dst32++) = SDL_SwapLE32((Uint32) ((Sint32) dst_sample)); *(dst32++) = SDL_SwapLE32((Uint32)((Sint32)dst_sample));
} }
} } break;
break;
case AUDIO_S32MSB: case AUDIO_S32MSB:
{ {
const Uint32 *src32 = (Uint32 *) src; const Uint32 *src32 = (Uint32 *)src;
Uint32 *dst32 = (Uint32 *) dst; Uint32 *dst32 = (Uint32 *)dst;
Sint64 src1, src2; Sint64 src1, src2;
Sint64 dst_sample; Sint64 dst_sample;
const Sint64 max_audioval = SDL_MAX_SINT32; const Sint64 max_audioval = SDL_MAX_SINT32;
@@ -272,27 +263,26 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
len /= 4; len /= 4;
while (len--) { while (len--) {
src1 = (Sint64) ((Sint32) SDL_SwapBE32(*src32)); src1 = (Sint64)((Sint32)SDL_SwapBE32(*src32));
src32++; src32++;
ADJUST_VOLUME(src1, volume); ADJUST_VOLUME(src1, volume);
src2 = (Sint64) ((Sint32) SDL_SwapBE32(*dst32)); src2 = (Sint64)((Sint32)SDL_SwapBE32(*dst32));
dst_sample = src1 + src2; dst_sample = src1 + src2;
if (dst_sample > max_audioval) { if (dst_sample > max_audioval) {
dst_sample = max_audioval; dst_sample = max_audioval;
} else if (dst_sample < min_audioval) { } else if (dst_sample < min_audioval) {
dst_sample = min_audioval; dst_sample = min_audioval;
} }
*(dst32++) = SDL_SwapBE32((Uint32) ((Sint32) dst_sample)); *(dst32++) = SDL_SwapBE32((Uint32)((Sint32)dst_sample));
} }
} } break;
break;
case AUDIO_F32LSB: case AUDIO_F32LSB:
{ {
const float fmaxvolume = 1.0f / ((float) SDL_MIX_MAXVOLUME); const float fmaxvolume = 1.0f / ((float)SDL_MIX_MAXVOLUME);
const float fvolume = (float) volume; const float fvolume = (float)volume;
const float *src32 = (float *) src; const float *src32 = (float *)src;
float *dst32 = (float *) dst; float *dst32 = (float *)dst;
float src1, src2; float src1, src2;
double dst_sample; double dst_sample;
/* !!! FIXME: are these right? */ /* !!! FIXME: are these right? */
@@ -305,23 +295,22 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
src2 = SDL_SwapFloatLE(*dst32); src2 = SDL_SwapFloatLE(*dst32);
src32++; src32++;
dst_sample = ((double) src1) + ((double) src2); dst_sample = ((double)src1) + ((double)src2);
if (dst_sample > max_audioval) { if (dst_sample > max_audioval) {
dst_sample = max_audioval; dst_sample = max_audioval;
} else if (dst_sample < min_audioval) { } else if (dst_sample < min_audioval) {
dst_sample = min_audioval; dst_sample = min_audioval;
} }
*(dst32++) = SDL_SwapFloatLE((float) dst_sample); *(dst32++) = SDL_SwapFloatLE((float)dst_sample);
} }
} } break;
break;
case AUDIO_F32MSB: case AUDIO_F32MSB:
{ {
const float fmaxvolume = 1.0f / ((float) SDL_MIX_MAXVOLUME); const float fmaxvolume = 1.0f / ((float)SDL_MIX_MAXVOLUME);
const float fvolume = (float) volume; const float fvolume = (float)volume;
const float *src32 = (float *) src; const float *src32 = (float *)src;
float *dst32 = (float *) dst; float *dst32 = (float *)dst;
float src1, src2; float src1, src2;
double dst_sample; double dst_sample;
/* !!! FIXME: are these right? */ /* !!! FIXME: are these right? */
@@ -334,16 +323,15 @@ SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format,
src2 = SDL_SwapFloatBE(*dst32); src2 = SDL_SwapFloatBE(*dst32);
src32++; src32++;
dst_sample = ((double) src1) + ((double) src2); dst_sample = ((double)src1) + ((double)src2);
if (dst_sample > max_audioval) { if (dst_sample > max_audioval) {
dst_sample = max_audioval; dst_sample = max_audioval;
} else if (dst_sample < min_audioval) { } else if (dst_sample < min_audioval) {
dst_sample = min_audioval; dst_sample = min_audioval;
} }
*(dst32++) = SDL_SwapFloatBE((float) dst_sample); *(dst32++) = SDL_SwapFloatBE((float)dst_sample);
} }
} } break;
break;
default: /* If this happens... FIXME! */ default: /* If this happens... FIXME! */
SDL_SetError("SDL_MixAudioFormat(): unknown audio format"); SDL_SetError("SDL_MixAudioFormat(): unknown audio format");

View File

@@ -62,21 +62,21 @@ extern void SDL_OpenedAudioDeviceDisconnected(SDL_AudioDevice *device);
typedef struct SDL_AudioDriverImpl typedef struct SDL_AudioDriverImpl
{ {
void (*DetectDevices) (void); void (*DetectDevices)(void);
int (*OpenDevice) (_THIS, const char *devname); int (*OpenDevice)(_THIS, const char *devname);
void (*ThreadInit) (_THIS); /* Called by audio thread at start */ void (*ThreadInit)(_THIS); /* Called by audio thread at start */
void (*ThreadDeinit) (_THIS); /* Called by audio thread at end */ void (*ThreadDeinit)(_THIS); /* Called by audio thread at end */
void (*WaitDevice) (_THIS); void (*WaitDevice)(_THIS);
void (*PlayDevice) (_THIS); void (*PlayDevice)(_THIS);
Uint8 *(*GetDeviceBuf) (_THIS); Uint8 *(*GetDeviceBuf)(_THIS);
int (*CaptureFromDevice) (_THIS, void *buffer, int buflen); int (*CaptureFromDevice)(_THIS, void *buffer, int buflen);
void (*FlushCapture) (_THIS); void (*FlushCapture)(_THIS);
void (*CloseDevice) (_THIS); void (*CloseDevice)(_THIS);
void (*LockDevice) (_THIS); void (*LockDevice)(_THIS);
void (*UnlockDevice) (_THIS); void (*UnlockDevice)(_THIS);
void (*FreeDeviceHandle) (void *handle); /**< SDL is done with handle from SDL_AddAudioDevice() */ void (*FreeDeviceHandle)(void *handle); /**< SDL is done with handle from SDL_AddAudioDevice() */
void (*Deinitialize) (void); void (*Deinitialize)(void);
int (*GetDefaultAudioInfo) (char **name, SDL_AudioSpec *spec, int iscapture); int (*GetDefaultAudioInfo)(char **name, SDL_AudioSpec *spec, int iscapture);
/* !!! FIXME: add pause(), so we can optimize instead of mixing silence. */ /* !!! FIXME: add pause(), so we can optimize instead of mixing silence. */
@@ -89,7 +89,6 @@ typedef struct SDL_AudioDriverImpl
SDL_bool SupportsNonPow2Samples; SDL_bool SupportsNonPow2Samples;
} SDL_AudioDriverImpl; } SDL_AudioDriverImpl;
typedef struct SDL_AudioDeviceItem typedef struct SDL_AudioDeviceItem
{ {
void *handle; void *handle;
@@ -100,7 +99,6 @@ typedef struct SDL_AudioDeviceItem
struct SDL_AudioDeviceItem *next; struct SDL_AudioDeviceItem *next;
} SDL_AudioDeviceItem; } SDL_AudioDeviceItem;
typedef struct SDL_AudioDriver typedef struct SDL_AudioDriver
{ {
/* * * */ /* * * */
@@ -123,7 +121,6 @@ typedef struct SDL_AudioDriver
SDL_AudioDeviceItem *inputDevices; SDL_AudioDeviceItem *inputDevices;
} SDL_AudioDriver; } SDL_AudioDriver;
/* Define the SDL audio driver structure */ /* Define the SDL audio driver structure */
struct SDL_AudioDevice struct SDL_AudioDevice
{ {
@@ -174,7 +171,7 @@ typedef struct AudioBootStrap
{ {
const char *name; const char *name;
const char *desc; const char *desc;
SDL_bool (*init) (SDL_AudioDriverImpl * impl); SDL_bool (*init)(SDL_AudioDriverImpl *impl);
SDL_bool demand_only; /* 1==request explicitly, or it won't be available. */ SDL_bool demand_only; /* 1==request explicitly, or it won't be available. */
} AudioBootStrap; } AudioBootStrap;

View File

@@ -41,8 +41,7 @@
* Returns 0 on success, or -1 if the multiplication overflows, in which case f1 * Returns 0 on success, or -1 if the multiplication overflows, in which case f1
* does not get modified. * does not get modified.
*/ */
static int static int SafeMult(size_t *f1, size_t f2)
SafeMult(size_t *f1, size_t f2)
{ {
if (*f1 > 0 && SIZE_MAX / *f1 <= f2) { if (*f1 > 0 && SIZE_MAX / *f1 <= f2) {
return -1; return -1;
@@ -64,21 +63,24 @@ typedef struct ADPCM_DecoderState
void *cstate; /* Decoding state for each channel. */ void *cstate; /* Decoding state for each channel. */
/* ADPCM data. */ /* ADPCM data. */
struct { struct
{
Uint8 *data; Uint8 *data;
size_t size; size_t size;
size_t pos; size_t pos;
} input; } input;
/* Current ADPCM block in the ADPCM data above. */ /* Current ADPCM block in the ADPCM data above. */
struct { struct
{
Uint8 *data; Uint8 *data;
size_t size; size_t size;
size_t pos; size_t pos;
} block; } block;
/* Decoded 16-bit PCM data. */ /* Decoded 16-bit PCM data. */
struct { struct
{
Sint16 *data; Sint16 *data;
size_t size; size_t size;
size_t pos; size_t pos;
@@ -100,8 +102,7 @@ typedef struct MS_ADPCM_ChannelState
} MS_ADPCM_ChannelState; } MS_ADPCM_ChannelState;
#ifdef SDL_WAVE_DEBUG_LOG_FORMAT #ifdef SDL_WAVE_DEBUG_LOG_FORMAT
static void static void WaveDebugLogFormat(WaveFile *file)
WaveDebugLogFormat(WaveFile *file)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
const char *fmtstr = "WAVE file: %s, %u Hz, %s, %u bits, %u %s/s"; const char *fmtstr = "WAVE file: %s, %u Hz, %s, %u bits, %u %s/s";
@@ -135,9 +136,14 @@ WaveDebugLogFormat(WaveFile *file)
break; break;
} }
#define SDL_WAVE_DEBUG_CHANNELCFG(STR, CODE) case CODE: wavechannel = STR; break; #define SDL_WAVE_DEBUG_CHANNELCFG(STR, CODE) \
#define SDL_WAVE_DEBUG_CHANNELSTR(STR, CODE) if (format->channelmask & CODE) { \ case CODE: \
SDL_strlcat(channelstr, channelstr[0] ? "-" STR : STR, sizeof(channelstr));} wavechannel = STR; \
break;
#define SDL_WAVE_DEBUG_CHANNELSTR(STR, CODE) \
if (format->channelmask & CODE) { \
SDL_strlcat(channelstr, channelstr[0] ? "-" STR : STR, sizeof(channelstr)); \
}
if (format->formattag == EXTENSIBLE_CODE && format->channelmask > 0) { if (format->formattag == EXTENSIBLE_CODE && format->channelmask > 0) {
switch (format->channelmask) { switch (format->channelmask) {
@@ -224,8 +230,7 @@ WaveDebugLogFormat(WaveFile *file)
#endif #endif
#ifdef SDL_WAVE_DEBUG_DUMP_FORMAT #ifdef SDL_WAVE_DEBUG_DUMP_FORMAT
static void static void WaveDebugDumpFormat(WaveFile *file, Uint32 rifflen, Uint32 fmtlen, Uint32 datalen)
WaveDebugDumpFormat(WaveFile *file, Uint32 rifflen, Uint32 fmtlen, Uint32 datalen)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
const char *fmtstr1 = "WAVE chunk dump:\n" const char *fmtstr1 = "WAVE chunk dump:\n"
@@ -315,8 +320,7 @@ WaveDebugDumpFormat(WaveFile *file, Uint32 rifflen, Uint32 fmtlen, Uint32 datale
} }
#endif #endif
static Sint64 static Sint64 WaveAdjustToFactValue(WaveFile *file, Sint64 sampleframes)
WaveAdjustToFactValue(WaveFile *file, Sint64 sampleframes)
{ {
if (file->fact.status == 2) { if (file->fact.status == 2) {
if (file->facthint == FactStrict && sampleframes < file->fact.samplelength) { if (file->facthint == FactStrict && sampleframes < file->fact.samplelength) {
@@ -329,8 +333,7 @@ WaveAdjustToFactValue(WaveFile *file, Sint64 sampleframes)
return sampleframes; return sampleframes;
} }
static int static int MS_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
MS_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
const size_t blockheadersize = (size_t)file->format.channels * 7; const size_t blockheadersize = (size_t)file->format.channels * 7;
@@ -369,8 +372,7 @@ MS_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
return 0; return 0;
} }
static int static int MS_ADPCM_Init(WaveFile *file, size_t datalength)
MS_ADPCM_Init(WaveFile *file, size_t datalength)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
WaveChunk *chunk = &file->chunk; WaveChunk *chunk = &file->chunk;
@@ -378,7 +380,7 @@ MS_ADPCM_Init(WaveFile *file, size_t datalength)
const size_t blockdatasize = (size_t)format->blockalign - blockheadersize; const size_t blockdatasize = (size_t)format->blockalign - blockheadersize;
const size_t blockframebitsize = (size_t)format->bitspersample * format->channels; const size_t blockframebitsize = (size_t)format->bitspersample * format->channels;
const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize; const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize;
const Sint16 presetcoeffs[14] = {256, 0, 512, -256, 0, 0, 192, 64, 240, 0, 460, -208, 392, -232}; const Sint16 presetcoeffs[14] = { 256, 0, 512, -256, 0, 0, 192, 64, 240, 0, 460, -208, 392, -232 };
size_t i, coeffcount; size_t i, coeffcount;
MS_ADPCM_CoeffData *coeffdata; MS_ADPCM_CoeffData *coeffdata;
@@ -488,8 +490,7 @@ MS_ADPCM_Init(WaveFile *file, size_t datalength)
return 0; return 0;
} }
static Sint16 static Sint16 MS_ADPCM_ProcessNibble(MS_ADPCM_ChannelState *cstate, Sint32 sample1, Sint32 sample2, Uint8 nybble)
MS_ADPCM_ProcessNibble(MS_ADPCM_ChannelState *cstate, Sint32 sample1, Sint32 sample2, Uint8 nybble)
{ {
const Sint32 max_audioval = 32767; const Sint32 max_audioval = 32767;
const Sint32 min_audioval = -32768; const Sint32 min_audioval = -32768;
@@ -525,8 +526,7 @@ MS_ADPCM_ProcessNibble(MS_ADPCM_ChannelState *cstate, Sint32 sample1, Sint32 sam
return (Sint16)new_sample; return (Sint16)new_sample;
} }
static int static int MS_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
MS_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
{ {
Uint8 coeffindex; Uint8 coeffindex;
const Uint32 channels = state->channels; const Uint32 channels = state->channels;
@@ -586,8 +586,7 @@ MS_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
* will always contain full sample frames (same sample count for each channel). * will always contain full sample frames (same sample count for each channel).
* Incomplete sample frames are discarded. * Incomplete sample frames are discarded.
*/ */
static int static int MS_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
MS_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
{ {
Uint16 nybble = 0; Uint16 nybble = 0;
Sint16 sample1, sample2; Sint16 sample1, sample2;
@@ -634,8 +633,7 @@ MS_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
return 0; return 0;
} }
static int static int MS_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
MS_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
{ {
int result; int result;
size_t bytesleft, outputsize; size_t bytesleft, outputsize;
@@ -734,8 +732,7 @@ MS_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
return 0; return 0;
} }
static int static int IMA_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
IMA_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
const size_t blockheadersize = (size_t)format->channels * 4; const size_t blockheadersize = (size_t)format->channels * 4;
@@ -788,8 +785,7 @@ IMA_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
return 0; return 0;
} }
static int static int IMA_ADPCM_Init(WaveFile *file, size_t datalength)
IMA_ADPCM_Init(WaveFile *file, size_t datalength)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
WaveChunk *chunk = &file->chunk; WaveChunk *chunk = &file->chunk;
@@ -854,8 +850,7 @@ IMA_ADPCM_Init(WaveFile *file, size_t datalength)
return 0; return 0;
} }
static Sint16 static Sint16 IMA_ADPCM_ProcessNibble(Sint8 *cindex, Sint16 lastsample, Uint8 nybble)
IMA_ADPCM_ProcessNibble(Sint8 *cindex, Sint16 lastsample, Uint8 nybble)
{ {
const Sint32 max_audioval = 32767; const Sint32 max_audioval = 32767;
const Sint32 min_audioval = -32768; const Sint32 min_audioval = -32768;
@@ -924,12 +919,11 @@ IMA_ADPCM_ProcessNibble(Sint8 *cindex, Sint16 lastsample, Uint8 nybble)
return (Sint16)sample; return (Sint16)sample;
} }
static int static int IMA_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
IMA_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
{ {
Sint16 step; Sint16 step;
Uint32 c; Uint32 c;
Uint8 *cstate = (Uint8 *) state->cstate; Uint8 *cstate = (Uint8 *)state->cstate;
for (c = 0; c < state->channels; c++) { for (c = 0; c < state->channels; c++) {
size_t o = state->block.pos + c * 4; size_t o = state->block.pos + c * 4;
@@ -947,7 +941,7 @@ IMA_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
/* Reserved byte in block header, should be 0. */ /* Reserved byte in block header, should be 0. */
if (state->block.data[o + 3] != 0) { if (state->block.data[o + 3] != 0) {
/* Uh oh, corrupt data? Buggy code? */ ; /* Uh oh, corrupt data? Buggy code? */;
} }
} }
@@ -964,8 +958,7 @@ IMA_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
* contains full sample frames (same sample count for each channel). * contains full sample frames (same sample count for each channel).
* Incomplete sample frames are discarded. * Incomplete sample frames are discarded.
*/ */
static int static int IMA_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
IMA_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
{ {
size_t i; size_t i;
int retval = 0; int retval = 0;
@@ -1034,8 +1027,7 @@ IMA_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
return retval; return retval;
} }
static int static int IMA_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
IMA_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
{ {
int result; int result;
size_t bytesleft, outputsize; size_t bytesleft, outputsize;
@@ -1138,8 +1130,7 @@ IMA_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
return 0; return 0;
} }
static int static int LAW_Init(WaveFile *file, size_t datalength)
LAW_Init(WaveFile *file, size_t datalength)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
@@ -1167,8 +1158,7 @@ LAW_Init(WaveFile *file, size_t datalength)
return 0; return 0;
} }
static int static int LAW_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
LAW_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
{ {
#ifdef SDL_WAVE_LAW_LUT #ifdef SDL_WAVE_LAW_LUT
const Sint16 alaw_lut[256] = { const Sint16 alaw_lut[256] = {
@@ -1310,8 +1300,7 @@ LAW_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
return 0; return 0;
} }
static int static int PCM_Init(WaveFile *file, size_t datalength)
PCM_Init(WaveFile *file, size_t datalength)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
@@ -1354,8 +1343,7 @@ PCM_Init(WaveFile *file, size_t datalength)
return 0; return 0;
} }
static int static int PCM_ConvertSint24ToSint32(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
PCM_ConvertSint24ToSint32(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
WaveChunk *chunk = &file->chunk; WaveChunk *chunk = &file->chunk;
@@ -1406,8 +1394,7 @@ PCM_ConvertSint24ToSint32(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
return 0; return 0;
} }
static int static int PCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
PCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
WaveChunk *chunk = &file->chunk; WaveChunk *chunk = &file->chunk;
@@ -1449,8 +1436,7 @@ PCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
return 0; return 0;
} }
static WaveRiffSizeHint static WaveRiffSizeHint WaveGetRiffSizeHint()
WaveGetRiffSizeHint()
{ {
const char *hint = SDL_GetHint(SDL_HINT_WAVE_RIFF_CHUNK_SIZE); const char *hint = SDL_GetHint(SDL_HINT_WAVE_RIFF_CHUNK_SIZE);
@@ -1469,8 +1455,7 @@ WaveGetRiffSizeHint()
return RiffSizeNoHint; return RiffSizeNoHint;
} }
static WaveTruncationHint static WaveTruncationHint WaveGetTruncationHint()
WaveGetTruncationHint()
{ {
const char *hint = SDL_GetHint(SDL_HINT_WAVE_TRUNCATION); const char *hint = SDL_GetHint(SDL_HINT_WAVE_TRUNCATION);
@@ -1489,8 +1474,7 @@ WaveGetTruncationHint()
return TruncNoHint; return TruncNoHint;
} }
static WaveFactChunkHint static WaveFactChunkHint WaveGetFactChunkHint()
WaveGetFactChunkHint()
{ {
const char *hint = SDL_GetHint(SDL_HINT_WAVE_FACT_CHUNK); const char *hint = SDL_GetHint(SDL_HINT_WAVE_FACT_CHUNK);
@@ -1509,8 +1493,7 @@ WaveGetFactChunkHint()
return FactNoHint; return FactNoHint;
} }
static void static void WaveFreeChunkData(WaveChunk *chunk)
WaveFreeChunkData(WaveChunk *chunk)
{ {
if (chunk->data != NULL) { if (chunk->data != NULL) {
SDL_free(chunk->data); SDL_free(chunk->data);
@@ -1519,8 +1502,7 @@ WaveFreeChunkData(WaveChunk *chunk)
chunk->size = 0; chunk->size = 0;
} }
static int static int WaveNextChunk(SDL_RWops *src, WaveChunk *chunk)
WaveNextChunk(SDL_RWops *src, WaveChunk *chunk)
{ {
Uint32 chunkheader[2]; Uint32 chunkheader[2];
Sint64 nextposition = chunk->position + chunk->length; Sint64 nextposition = chunk->position + chunk->length;
@@ -1552,8 +1534,7 @@ WaveNextChunk(SDL_RWops *src, WaveChunk *chunk)
return 0; return 0;
} }
static int static int WaveReadPartialChunkData(SDL_RWops *src, WaveChunk *chunk, size_t length)
WaveReadPartialChunkData(SDL_RWops *src, WaveChunk *chunk, size_t length)
{ {
WaveFreeChunkData(chunk); WaveFreeChunkData(chunk);
@@ -1562,7 +1543,7 @@ WaveReadPartialChunkData(SDL_RWops *src, WaveChunk *chunk, size_t length)
} }
if (length > 0) { if (length > 0) {
chunk->data = (Uint8 *) SDL_malloc(length); chunk->data = (Uint8 *)SDL_malloc(length);
if (chunk->data == NULL) { if (chunk->data == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -1581,30 +1562,32 @@ WaveReadPartialChunkData(SDL_RWops *src, WaveChunk *chunk, size_t length)
return 0; return 0;
} }
static int static int WaveReadChunkData(SDL_RWops *src, WaveChunk *chunk)
WaveReadChunkData(SDL_RWops *src, WaveChunk *chunk)
{ {
return WaveReadPartialChunkData(src, chunk, chunk->length); return WaveReadPartialChunkData(src, chunk, chunk->length);
} }
typedef struct WaveExtensibleGUID { typedef struct WaveExtensibleGUID
{
Uint16 encoding; Uint16 encoding;
Uint8 guid[16]; Uint8 guid[16];
} WaveExtensibleGUID; } WaveExtensibleGUID;
/* Some of the GUIDs that are used by WAVEFORMATEXTENSIBLE. */ /* Some of the GUIDs that are used by WAVEFORMATEXTENSIBLE. */
#define WAVE_FORMATTAG_GUID(tag) {(tag) & 0xff, (tag) >> 8, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113} #define WAVE_FORMATTAG_GUID(tag) \
{ \
(tag) & 0xff, (tag) >> 8, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113 \
}
static WaveExtensibleGUID extensible_guids[] = { static WaveExtensibleGUID extensible_guids[] = {
{PCM_CODE, WAVE_FORMATTAG_GUID(PCM_CODE)}, { PCM_CODE, WAVE_FORMATTAG_GUID(PCM_CODE) },
{MS_ADPCM_CODE, WAVE_FORMATTAG_GUID(MS_ADPCM_CODE)}, { MS_ADPCM_CODE, WAVE_FORMATTAG_GUID(MS_ADPCM_CODE) },
{IEEE_FLOAT_CODE, WAVE_FORMATTAG_GUID(IEEE_FLOAT_CODE)}, { IEEE_FLOAT_CODE, WAVE_FORMATTAG_GUID(IEEE_FLOAT_CODE) },
{ALAW_CODE, WAVE_FORMATTAG_GUID(ALAW_CODE)}, { ALAW_CODE, WAVE_FORMATTAG_GUID(ALAW_CODE) },
{MULAW_CODE, WAVE_FORMATTAG_GUID(MULAW_CODE)}, { MULAW_CODE, WAVE_FORMATTAG_GUID(MULAW_CODE) },
{IMA_ADPCM_CODE, WAVE_FORMATTAG_GUID(IMA_ADPCM_CODE)} { IMA_ADPCM_CODE, WAVE_FORMATTAG_GUID(IMA_ADPCM_CODE) }
}; };
static Uint16 static Uint16 WaveGetFormatGUIDEncoding(WaveFormat *format)
WaveGetFormatGUIDEncoding(WaveFormat *format)
{ {
size_t i; size_t i;
for (i = 0; i < SDL_arraysize(extensible_guids); i++) { for (i = 0; i < SDL_arraysize(extensible_guids); i++) {
@@ -1615,8 +1598,7 @@ WaveGetFormatGUIDEncoding(WaveFormat *format)
return UNKNOWN_CODE; return UNKNOWN_CODE;
} }
static int static int WaveReadFormat(WaveFile *file)
WaveReadFormat(WaveFile *file)
{ {
WaveChunk *chunk = &file->chunk; WaveChunk *chunk = &file->chunk;
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
@@ -1677,8 +1659,7 @@ WaveReadFormat(WaveFile *file)
return 0; return 0;
} }
static int static int WaveCheckFormat(WaveFile *file, size_t datalength)
WaveCheckFormat(WaveFile *file, size_t datalength)
{ {
WaveFormat *format = &file->format; WaveFormat *format = &file->format;
@@ -1785,8 +1766,7 @@ WaveCheckFormat(WaveFile *file, size_t datalength)
return 0; return 0;
} }
static int static int WaveLoad(SDL_RWops *src, WaveFile *file, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len)
WaveLoad(SDL_RWops *src, WaveFile *file, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len)
{ {
int result; int result;
Uint32 chunkcount = 0; Uint32 chunkcount = 0;
@@ -2148,8 +2128,7 @@ SDL_LoadWAV_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_b
/* Since the WAV memory is allocated in the shared library, it must also /* Since the WAV memory is allocated in the shared library, it must also
be freed here. (Necessary under Win32, VC++) be freed here. (Necessary under Win32, VC++)
*/ */
void void SDL_FreeWAV(Uint8 *audio_buf)
SDL_FreeWAV(Uint8 *audio_buf)
{ {
SDL_free(audio_buf); SDL_free(audio_buf);
} }

View File

@@ -70,7 +70,8 @@ typedef struct WaveFormat
} WaveFormat; } WaveFormat;
/* Stores information on the fact chunk. */ /* Stores information on the fact chunk. */
typedef struct WaveFact { typedef struct WaveFact
{
/* Represents the state of the fact chunk in the WAVE file. /* Represents the state of the fact chunk in the WAVE file.
* Set to -1 if the fact chunk is invalid. * Set to -1 if the fact chunk is invalid.
* Set to 0 if the fact chunk is not present * Set to 0 if the fact chunk is not present
@@ -101,7 +102,8 @@ typedef struct WaveChunk
} WaveChunk; } WaveChunk;
/* Controls how the size of the RIFF chunk affects the loading of a WAVE file. */ /* Controls how the size of the RIFF chunk affects the loading of a WAVE file. */
typedef enum WaveRiffSizeHint { typedef enum WaveRiffSizeHint
{
RiffSizeNoHint, RiffSizeNoHint,
RiffSizeForce, RiffSizeForce,
RiffSizeIgnoreZero, RiffSizeIgnoreZero,
@@ -110,7 +112,8 @@ typedef enum WaveRiffSizeHint {
} WaveRiffSizeHint; } WaveRiffSizeHint;
/* Controls how a truncated WAVE file is handled. */ /* Controls how a truncated WAVE file is handled. */
typedef enum WaveTruncationHint { typedef enum WaveTruncationHint
{
TruncNoHint, TruncNoHint,
TruncVeryStrict, TruncVeryStrict,
TruncStrict, TruncStrict,
@@ -119,7 +122,8 @@ typedef enum WaveTruncationHint {
} WaveTruncationHint; } WaveTruncationHint;
/* Controls how the fact chunk affects the loading of a WAVE file. */ /* Controls how the fact chunk affects the loading of a WAVE file. */
typedef enum WaveFactChunkHint { typedef enum WaveFactChunkHint
{
FactNoHint, FactNoHint,
FactTruncate, FactTruncate,
FactStrict, FactStrict,

View File

@@ -28,17 +28,17 @@
/* Debug */ /* Debug */
#if 0 #if 0
# define LOGI(...) SDL_Log(__VA_ARGS__); #define LOGI(...) SDL_Log(__VA_ARGS__);
#else #else
# define LOGI(...) #define LOGI(...)
#endif #endif
typedef struct AAUDIO_Data typedef struct AAUDIO_Data
{ {
AAudioStreamBuilder *builder; AAudioStreamBuilder *builder;
void *handle; void *handle;
#define SDL_PROC(ret,func,params) ret (*func) params; #define SDL_PROC(ret, func, params) ret(*func) params;
# include "SDL_aaudiofuncs.h" #include "SDL_aaudiofuncs.h"
#undef SDL_PROC #undef SDL_PROC
} AAUDIO_Data; } AAUDIO_Data;
static AAUDIO_Data ctx; static AAUDIO_Data ctx;
@@ -48,10 +48,10 @@ static SDL_AudioDevice *captureDevice = NULL;
static int aaudio_LoadFunctions(AAUDIO_Data *data) static int aaudio_LoadFunctions(AAUDIO_Data *data)
{ {
#define SDL_PROC(ret,func,params) \ #define SDL_PROC(ret, func, params) \
do { \ do { \
data->func = SDL_LoadFunction(data->handle, #func); \ data->func = SDL_LoadFunction(data->handle, #func); \
if (! data->func) { \ if (!data->func) { \
return SDL_SetError("Couldn't load AAUDIO function %s: %s", #func, SDL_GetError()); \ return SDL_SetError("Couldn't load AAUDIO function %s: %s", #func, SDL_GetError()); \
} \ } \
} while (0); } while (0);
@@ -60,16 +60,15 @@ static int aaudio_LoadFunctions(AAUDIO_Data *data)
return 0; return 0;
} }
void aaudio_errorCallback( AAudioStream *stream, void *userData, aaudio_result_t error ); void aaudio_errorCallback(AAudioStream *stream, void *userData, aaudio_result_t error);
void aaudio_errorCallback( AAudioStream *stream, void *userData, aaudio_result_t error ) void aaudio_errorCallback(AAudioStream *stream, void *userData, aaudio_result_t error)
{ {
LOGI( "SDL aaudio_errorCallback: %d - %s", error, ctx.AAudio_convertResultToText( error ) ); LOGI("SDL aaudio_errorCallback: %d - %s", error, ctx.AAudio_convertResultToText(error));
} }
#define LIB_AAUDIO_SO "libaaudio.so" #define LIB_AAUDIO_SO "libaaudio.so"
static int static int aaudio_OpenDevice(_THIS, const char *devname)
aaudio_OpenDevice(_THIS, const char *devname)
{ {
struct SDL_PrivateAudioData *private; struct SDL_PrivateAudioData *private;
SDL_bool iscapture = this->iscapture; SDL_bool iscapture = this->iscapture;
@@ -92,7 +91,7 @@ aaudio_OpenDevice(_THIS, const char *devname)
audioDevice = this; audioDevice = this;
} }
this->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, (sizeof *this->hidden)); this->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, (sizeof *this->hidden));
if (this->hidden == NULL) { if (this->hidden == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -114,7 +113,7 @@ aaudio_OpenDevice(_THIS, const char *devname)
ctx.AAudioStreamBuilder_setFormat(ctx.builder, format); ctx.AAudioStreamBuilder_setFormat(ctx.builder, format);
} }
ctx.AAudioStreamBuilder_setErrorCallback( ctx.builder, aaudio_errorCallback, private ); ctx.AAudioStreamBuilder_setErrorCallback(ctx.builder, aaudio_errorCallback, private);
LOGI("AAudio Try to open %u hz %u bit chan %u %s samples %u", LOGI("AAudio Try to open %u hz %u bit chan %u %s samples %u",
this->spec.freq, SDL_AUDIO_BITSIZE(this->spec.format), this->spec.freq, SDL_AUDIO_BITSIZE(this->spec.format),
@@ -146,7 +145,7 @@ aaudio_OpenDevice(_THIS, const char *devname)
/* Allocate mixing buffer */ /* Allocate mixing buffer */
if (!iscapture) { if (!iscapture) {
private->mixlen = this->spec.size; private->mixlen = this->spec.size;
private->mixbuf = (Uint8 *) SDL_malloc(private->mixlen); private->mixbuf = (Uint8 *)SDL_malloc(private->mixlen);
if (private->mixbuf == NULL) { if (private->mixbuf == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -165,8 +164,7 @@ aaudio_OpenDevice(_THIS, const char *devname)
return 0; return 0;
} }
static void static void aaudio_CloseDevice(_THIS)
aaudio_CloseDevice(_THIS)
{ {
struct SDL_PrivateAudioData *private = this->hidden; struct SDL_PrivateAudioData *private = this->hidden;
aaudio_result_t res; aaudio_result_t res;
@@ -200,15 +198,13 @@ aaudio_CloseDevice(_THIS)
SDL_free(this->hidden); SDL_free(this->hidden);
} }
static Uint8 * static Uint8 *aaudio_GetDeviceBuf(_THIS)
aaudio_GetDeviceBuf(_THIS)
{ {
struct SDL_PrivateAudioData *private = this->hidden; struct SDL_PrivateAudioData *private = this->hidden;
return private->mixbuf; return private->mixbuf;
} }
static void static void aaudio_PlayDevice(_THIS)
aaudio_PlayDevice(_THIS)
{ {
struct SDL_PrivateAudioData *private = this->hidden; struct SDL_PrivateAudioData *private = this->hidden;
aaudio_result_t res; aaudio_result_t res;
@@ -233,8 +229,7 @@ aaudio_PlayDevice(_THIS)
#endif #endif
} }
static int static int aaudio_CaptureFromDevice(_THIS, void *buffer, int buflen)
aaudio_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
struct SDL_PrivateAudioData *private = this->hidden; struct SDL_PrivateAudioData *private = this->hidden;
aaudio_result_t res; aaudio_result_t res;
@@ -248,8 +243,7 @@ aaudio_CaptureFromDevice(_THIS, void *buffer, int buflen)
return res * private->frame_size; return res * private->frame_size;
} }
static void static void aaudio_Deinitialize(void)
aaudio_Deinitialize(void)
{ {
LOGI(__func__); LOGI(__func__);
if (ctx.handle) { if (ctx.handle) {
@@ -267,8 +261,7 @@ aaudio_Deinitialize(void)
LOGI("End AAUDIO %s", SDL_GetError()); LOGI("End AAUDIO %s", SDL_GetError());
} }
static SDL_bool static SDL_bool aaudio_Init(SDL_AudioDriverImpl *impl)
aaudio_Init(SDL_AudioDriverImpl *impl)
{ {
aaudio_result_t res; aaudio_result_t res;
LOGI(__func__); LOGI(__func__);
@@ -343,7 +336,7 @@ void aaudio_PauseDevices(void)
/* TODO: Handle multiple devices? */ /* TODO: Handle multiple devices? */
struct SDL_PrivateAudioData *private; struct SDL_PrivateAudioData *private;
if (audioDevice != NULL && audioDevice->hidden != NULL) { if (audioDevice != NULL && audioDevice->hidden != NULL) {
private = (struct SDL_PrivateAudioData *) audioDevice->hidden; private = (struct SDL_PrivateAudioData *)audioDevice->hidden;
if (private->stream) { if (private->stream) {
aaudio_result_t res = ctx.AAudioStream_requestPause(private->stream); aaudio_result_t res = ctx.AAudioStream_requestPause(private->stream);
@@ -364,7 +357,7 @@ void aaudio_PauseDevices(void)
} }
if (captureDevice != NULL && captureDevice->hidden != NULL) { if (captureDevice != NULL && captureDevice->hidden != NULL) {
private = (struct SDL_PrivateAudioData *) captureDevice->hidden; private = (struct SDL_PrivateAudioData *)captureDevice->hidden;
if (private->stream) { if (private->stream) {
/* Pause() isn't implemented for 'capture', use Stop() */ /* Pause() isn't implemented for 'capture', use Stop() */
@@ -392,7 +385,7 @@ void aaudio_ResumeDevices(void)
/* TODO: Handle multiple devices? */ /* TODO: Handle multiple devices? */
struct SDL_PrivateAudioData *private; struct SDL_PrivateAudioData *private;
if (audioDevice != NULL && audioDevice->hidden != NULL) { if (audioDevice != NULL && audioDevice->hidden != NULL) {
private = (struct SDL_PrivateAudioData *) audioDevice->hidden; private = (struct SDL_PrivateAudioData *)audioDevice->hidden;
if (private->resume) { if (private->resume) {
SDL_AtomicSet(&audioDevice->paused, 0); SDL_AtomicSet(&audioDevice->paused, 0);
@@ -410,7 +403,7 @@ void aaudio_ResumeDevices(void)
} }
if (captureDevice != NULL && captureDevice->hidden != NULL) { if (captureDevice != NULL && captureDevice->hidden != NULL) {
private = (struct SDL_PrivateAudioData *) captureDevice->hidden; private = (struct SDL_PrivateAudioData *)captureDevice->hidden;
if (private->resume) { if (private->resume) {
SDL_AtomicSet(&captureDevice->paused, 0); SDL_AtomicSet(&captureDevice->paused, 0);
@@ -433,24 +426,24 @@ void aaudio_ResumeDevices(void)
None of the standard state queries indicate any problem in my testing. And the error callback doesn't actually get called. None of the standard state queries indicate any problem in my testing. And the error callback doesn't actually get called.
But, AAudioStream_getTimestamp() does return AAUDIO_ERROR_INVALID_STATE But, AAudioStream_getTimestamp() does return AAUDIO_ERROR_INVALID_STATE
*/ */
SDL_bool aaudio_DetectBrokenPlayState( void ) SDL_bool aaudio_DetectBrokenPlayState(void)
{ {
struct SDL_PrivateAudioData *private; struct SDL_PrivateAudioData *private;
int64_t framePosition, timeNanoseconds; int64_t framePosition, timeNanoseconds;
aaudio_result_t res; aaudio_result_t res;
if (audioDevice == NULL || !audioDevice->hidden ) { if (audioDevice == NULL || !audioDevice->hidden) {
return SDL_FALSE; return SDL_FALSE;
} }
private = audioDevice->hidden; private = audioDevice->hidden;
res = ctx.AAudioStream_getTimestamp( private->stream, CLOCK_MONOTONIC, &framePosition, &timeNanoseconds ); res = ctx.AAudioStream_getTimestamp(private->stream, CLOCK_MONOTONIC, &framePosition, &timeNanoseconds);
if ( res == AAUDIO_ERROR_INVALID_STATE ) { if (res == AAUDIO_ERROR_INVALID_STATE) {
aaudio_stream_state_t currentState = ctx.AAudioStream_getState( private->stream ); aaudio_stream_state_t currentState = ctx.AAudioStream_getState(private->stream);
/* AAudioStream_getTimestamp() will also return AAUDIO_ERROR_INVALID_STATE while the stream is still initially starting. But we only care if it silently went invalid while playing. */ /* AAudioStream_getTimestamp() will also return AAUDIO_ERROR_INVALID_STATE while the stream is still initially starting. But we only care if it silently went invalid while playing. */
if ( currentState == AAUDIO_STREAM_STATE_STARTED ) { if (currentState == AAUDIO_STREAM_STATE_STARTED) {
LOGI( "SDL aaudio_DetectBrokenPlayState: detected invalid audio device state: AAudioStream_getTimestamp result=%d, framePosition=%lld, timeNanoseconds=%lld, getState=%d", (int)res, (long long)framePosition, (long long)timeNanoseconds, (int)currentState ); LOGI("SDL aaudio_DetectBrokenPlayState: detected invalid audio device state: AAudioStream_getTimestamp result=%d, framePosition=%lld, timeNanoseconds=%lld, getState=%d", (int)res, (long long)framePosition, (long long)timeNanoseconds, (int)currentState);
return SDL_TRUE; return SDL_TRUE;
} }
} }

View File

@@ -47,7 +47,6 @@ void aaudio_ResumeDevices(void);
void aaudio_PauseDevices(void); void aaudio_PauseDevices(void);
SDL_bool aaudio_DetectBrokenPlayState(void); SDL_bool aaudio_DetectBrokenPlayState(void);
#endif /* _SDL_aaudio_h */ #endif /* _SDL_aaudio_h */
/* vi: set ts=4 sw=4 expandtab: */ /* vi: set ts=4 sw=4 expandtab: */

View File

@@ -19,62 +19,61 @@
3. This notice may not be removed or altered from any source distribution. 3. This notice may not be removed or altered from any source distribution.
*/ */
#define SDL_PROC_UNUSED(ret,func,params) #define SDL_PROC_UNUSED(ret, func, params)
SDL_PROC(const char *, AAudio_convertResultToText, (aaudio_result_t returnCode)) SDL_PROC(const char *, AAudio_convertResultToText, (aaudio_result_t returnCode))
SDL_PROC(const char *, AAudio_convertStreamStateToText, (aaudio_stream_state_t state)) SDL_PROC(const char *, AAudio_convertStreamStateToText, (aaudio_stream_state_t state))
SDL_PROC(aaudio_result_t, AAudio_createStreamBuilder, (AAudioStreamBuilder** builder)) SDL_PROC(aaudio_result_t, AAudio_createStreamBuilder, (AAudioStreamBuilder * *builder))
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setDeviceId, (AAudioStreamBuilder* builder, int32_t deviceId)) SDL_PROC_UNUSED(void, AAudioStreamBuilder_setDeviceId, (AAudioStreamBuilder * builder, int32_t deviceId))
SDL_PROC(void, AAudioStreamBuilder_setSampleRate, (AAudioStreamBuilder* builder, int32_t sampleRate)) SDL_PROC(void, AAudioStreamBuilder_setSampleRate, (AAudioStreamBuilder * builder, int32_t sampleRate))
SDL_PROC(void, AAudioStreamBuilder_setChannelCount, (AAudioStreamBuilder* builder, int32_t channelCount)) SDL_PROC(void, AAudioStreamBuilder_setChannelCount, (AAudioStreamBuilder * builder, int32_t channelCount))
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setSamplesPerFrame, (AAudioStreamBuilder* builder, int32_t samplesPerFrame)) SDL_PROC_UNUSED(void, AAudioStreamBuilder_setSamplesPerFrame, (AAudioStreamBuilder * builder, int32_t samplesPerFrame))
SDL_PROC(void, AAudioStreamBuilder_setFormat, (AAudioStreamBuilder* builder, aaudio_format_t format)) SDL_PROC(void, AAudioStreamBuilder_setFormat, (AAudioStreamBuilder * builder, aaudio_format_t format))
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setSharingMode, (AAudioStreamBuilder* builder, aaudio_sharing_mode_t sharingMode)) SDL_PROC_UNUSED(void, AAudioStreamBuilder_setSharingMode, (AAudioStreamBuilder * builder, aaudio_sharing_mode_t sharingMode))
SDL_PROC(void, AAudioStreamBuilder_setDirection, (AAudioStreamBuilder* builder, aaudio_direction_t direction)) SDL_PROC(void, AAudioStreamBuilder_setDirection, (AAudioStreamBuilder * builder, aaudio_direction_t direction))
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setBufferCapacityInFrames, (AAudioStreamBuilder* builder, int32_t numFrames)) SDL_PROC_UNUSED(void, AAudioStreamBuilder_setBufferCapacityInFrames, (AAudioStreamBuilder * builder, int32_t numFrames))
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setPerformanceMode, (AAudioStreamBuilder* builder, aaudio_performance_mode_t mode)) SDL_PROC_UNUSED(void, AAudioStreamBuilder_setPerformanceMode, (AAudioStreamBuilder * builder, aaudio_performance_mode_t mode))
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setUsage, (AAudioStreamBuilder* builder, aaudio_usage_t usage)) /* API 28 */ SDL_PROC_UNUSED(void, AAudioStreamBuilder_setUsage, (AAudioStreamBuilder * builder, aaudio_usage_t usage)) /* API 28 */
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setContentType, (AAudioStreamBuilder* builder, aaudio_content_type_t contentType)) /* API 28 */ SDL_PROC_UNUSED(void, AAudioStreamBuilder_setContentType, (AAudioStreamBuilder * builder, aaudio_content_type_t contentType)) /* API 28 */
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setInputPreset, (AAudioStreamBuilder* builder, aaudio_input_preset_t inputPreset)) /* API 28 */ SDL_PROC_UNUSED(void, AAudioStreamBuilder_setInputPreset, (AAudioStreamBuilder * builder, aaudio_input_preset_t inputPreset)) /* API 28 */
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setAllowedCapturePolicy, (AAudioStreamBuilder* builder, aaudio_allowed_capture_policy_t capturePolicy)) /* API 29 */ SDL_PROC_UNUSED(void, AAudioStreamBuilder_setAllowedCapturePolicy, (AAudioStreamBuilder * builder, aaudio_allowed_capture_policy_t capturePolicy)) /* API 29 */
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setSessionId, (AAudioStreamBuilder* builder, aaudio_session_id_t sessionId)) /* API 28 */ SDL_PROC_UNUSED(void, AAudioStreamBuilder_setSessionId, (AAudioStreamBuilder * builder, aaudio_session_id_t sessionId)) /* API 28 */
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setPrivacySensitive, (AAudioStreamBuilder* builder, bool privacySensitive)) /* API 30 */ SDL_PROC_UNUSED(void, AAudioStreamBuilder_setPrivacySensitive, (AAudioStreamBuilder * builder, bool privacySensitive)) /* API 30 */
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setDataCallback, (AAudioStreamBuilder* builder, AAudioStream_dataCallback callback, void *userData)) SDL_PROC_UNUSED(void, AAudioStreamBuilder_setDataCallback, (AAudioStreamBuilder * builder, AAudioStream_dataCallback callback, void *userData))
SDL_PROC_UNUSED(void, AAudioStreamBuilder_setFramesPerDataCallback, (AAudioStreamBuilder* builder, int32_t numFrames)) SDL_PROC_UNUSED(void, AAudioStreamBuilder_setFramesPerDataCallback, (AAudioStreamBuilder * builder, int32_t numFrames))
SDL_PROC(void, AAudioStreamBuilder_setErrorCallback, (AAudioStreamBuilder* builder, AAudioStream_errorCallback callback, void *userData)) SDL_PROC(void, AAudioStreamBuilder_setErrorCallback, (AAudioStreamBuilder * builder, AAudioStream_errorCallback callback, void *userData))
SDL_PROC(aaudio_result_t , AAudioStreamBuilder_openStream, (AAudioStreamBuilder* builder, AAudioStream** stream)) SDL_PROC(aaudio_result_t, AAudioStreamBuilder_openStream, (AAudioStreamBuilder * builder, AAudioStream **stream))
SDL_PROC(aaudio_result_t , AAudioStreamBuilder_delete, (AAudioStreamBuilder* builder)) SDL_PROC(aaudio_result_t, AAudioStreamBuilder_delete, (AAudioStreamBuilder * builder))
SDL_PROC_UNUSED(aaudio_result_t , AAudioStream_release, (AAudioStream* stream)) /* API 30 */ SDL_PROC_UNUSED(aaudio_result_t, AAudioStream_release, (AAudioStream * stream)) /* API 30 */
SDL_PROC(aaudio_result_t , AAudioStream_close, (AAudioStream* stream)) SDL_PROC(aaudio_result_t, AAudioStream_close, (AAudioStream * stream))
SDL_PROC(aaudio_result_t , AAudioStream_requestStart, (AAudioStream* stream)) SDL_PROC(aaudio_result_t, AAudioStream_requestStart, (AAudioStream * stream))
SDL_PROC(aaudio_result_t , AAudioStream_requestPause, (AAudioStream* stream)) SDL_PROC(aaudio_result_t, AAudioStream_requestPause, (AAudioStream * stream))
SDL_PROC_UNUSED(aaudio_result_t , AAudioStream_requestFlush, (AAudioStream* stream)) SDL_PROC_UNUSED(aaudio_result_t, AAudioStream_requestFlush, (AAudioStream * stream))
SDL_PROC(aaudio_result_t , AAudioStream_requestStop, (AAudioStream* stream)) SDL_PROC(aaudio_result_t, AAudioStream_requestStop, (AAudioStream * stream))
SDL_PROC(aaudio_stream_state_t, AAudioStream_getState, (AAudioStream* stream)) SDL_PROC(aaudio_stream_state_t, AAudioStream_getState, (AAudioStream * stream))
SDL_PROC_UNUSED(aaudio_result_t, AAudioStream_waitForStateChange, (AAudioStream* stream, aaudio_stream_state_t inputState, aaudio_stream_state_t *nextState, int64_t timeoutNanoseconds)) SDL_PROC_UNUSED(aaudio_result_t, AAudioStream_waitForStateChange, (AAudioStream * stream, aaudio_stream_state_t inputState, aaudio_stream_state_t *nextState, int64_t timeoutNanoseconds))
SDL_PROC(aaudio_result_t, AAudioStream_read, (AAudioStream* stream, void *buffer, int32_t numFrames, int64_t timeoutNanoseconds)) SDL_PROC(aaudio_result_t, AAudioStream_read, (AAudioStream * stream, void *buffer, int32_t numFrames, int64_t timeoutNanoseconds))
SDL_PROC(aaudio_result_t, AAudioStream_write, (AAudioStream* stream, const void *buffer, int32_t numFrames, int64_t timeoutNanoseconds)) SDL_PROC(aaudio_result_t, AAudioStream_write, (AAudioStream * stream, const void *buffer, int32_t numFrames, int64_t timeoutNanoseconds))
SDL_PROC_UNUSED(aaudio_result_t, AAudioStream_setBufferSizeInFrames, (AAudioStream* stream, int32_t numFrames)) SDL_PROC_UNUSED(aaudio_result_t, AAudioStream_setBufferSizeInFrames, (AAudioStream * stream, int32_t numFrames))
SDL_PROC_UNUSED(int32_t, AAudioStream_getBufferSizeInFrames, (AAudioStream* stream)) SDL_PROC_UNUSED(int32_t, AAudioStream_getBufferSizeInFrames, (AAudioStream * stream))
SDL_PROC_UNUSED(int32_t, AAudioStream_getFramesPerBurst, (AAudioStream* stream)) SDL_PROC_UNUSED(int32_t, AAudioStream_getFramesPerBurst, (AAudioStream * stream))
SDL_PROC_UNUSED(int32_t, AAudioStream_getBufferCapacityInFrames, (AAudioStream* stream)) SDL_PROC_UNUSED(int32_t, AAudioStream_getBufferCapacityInFrames, (AAudioStream * stream))
SDL_PROC_UNUSED(int32_t, AAudioStream_getFramesPerDataCallback, (AAudioStream* stream)) SDL_PROC_UNUSED(int32_t, AAudioStream_getFramesPerDataCallback, (AAudioStream * stream))
SDL_PROC(int32_t, AAudioStream_getXRunCount, (AAudioStream* stream)) SDL_PROC(int32_t, AAudioStream_getXRunCount, (AAudioStream * stream))
SDL_PROC(int32_t, AAudioStream_getSampleRate, (AAudioStream* stream)) SDL_PROC(int32_t, AAudioStream_getSampleRate, (AAudioStream * stream))
SDL_PROC(int32_t, AAudioStream_getChannelCount, (AAudioStream* stream)) SDL_PROC(int32_t, AAudioStream_getChannelCount, (AAudioStream * stream))
SDL_PROC_UNUSED(int32_t, AAudioStream_getSamplesPerFrame, (AAudioStream* stream)) SDL_PROC_UNUSED(int32_t, AAudioStream_getSamplesPerFrame, (AAudioStream * stream))
SDL_PROC_UNUSED(int32_t, AAudioStream_getDeviceId, (AAudioStream* stream)) SDL_PROC_UNUSED(int32_t, AAudioStream_getDeviceId, (AAudioStream * stream))
SDL_PROC(aaudio_format_t, AAudioStream_getFormat, (AAudioStream* stream)) SDL_PROC(aaudio_format_t, AAudioStream_getFormat, (AAudioStream * stream))
SDL_PROC_UNUSED(aaudio_sharing_mode_t, AAudioStream_getSharingMode, (AAudioStream* stream)) SDL_PROC_UNUSED(aaudio_sharing_mode_t, AAudioStream_getSharingMode, (AAudioStream * stream))
SDL_PROC_UNUSED(aaudio_performance_mode_t, AAudioStream_getPerformanceMode, (AAudioStream* stream)) SDL_PROC_UNUSED(aaudio_performance_mode_t, AAudioStream_getPerformanceMode, (AAudioStream * stream))
SDL_PROC_UNUSED(aaudio_direction_t, AAudioStream_getDirection, (AAudioStream* stream)) SDL_PROC_UNUSED(aaudio_direction_t, AAudioStream_getDirection, (AAudioStream * stream))
SDL_PROC_UNUSED(int64_t, AAudioStream_getFramesWritten, (AAudioStream* stream)) SDL_PROC_UNUSED(int64_t, AAudioStream_getFramesWritten, (AAudioStream * stream))
SDL_PROC_UNUSED(int64_t, AAudioStream_getFramesRead, (AAudioStream* stream)) SDL_PROC_UNUSED(int64_t, AAudioStream_getFramesRead, (AAudioStream * stream))
SDL_PROC_UNUSED(aaudio_session_id_t, AAudioStream_getSessionId, (AAudioStream* stream)) /* API 28 */ SDL_PROC_UNUSED(aaudio_session_id_t, AAudioStream_getSessionId, (AAudioStream * stream)) /* API 28 */
SDL_PROC(aaudio_result_t, AAudioStream_getTimestamp, (AAudioStream* stream, clockid_t clockid, int64_t *framePosition, int64_t *timeNanoseconds)) SDL_PROC(aaudio_result_t, AAudioStream_getTimestamp, (AAudioStream * stream, clockid_t clockid, int64_t *framePosition, int64_t *timeNanoseconds))
SDL_PROC_UNUSED(aaudio_usage_t, AAudioStream_getUsage, (AAudioStream* stream)) /* API 28 */ SDL_PROC_UNUSED(aaudio_usage_t, AAudioStream_getUsage, (AAudioStream * stream)) /* API 28 */
SDL_PROC_UNUSED(aaudio_content_type_t, AAudioStream_getContentType, (AAudioStream* stream)) /* API 28 */ SDL_PROC_UNUSED(aaudio_content_type_t, AAudioStream_getContentType, (AAudioStream * stream)) /* API 28 */
SDL_PROC_UNUSED(aaudio_input_preset_t, AAudioStream_getInputPreset, (AAudioStream* stream)) /* API 28 */ SDL_PROC_UNUSED(aaudio_input_preset_t, AAudioStream_getInputPreset, (AAudioStream * stream)) /* API 28 */
SDL_PROC_UNUSED(aaudio_allowed_capture_policy_t, AAudioStream_getAllowedCapturePolicy, ( AAudioStream* stream)) /* API 29 */ SDL_PROC_UNUSED(aaudio_allowed_capture_policy_t, AAudioStream_getAllowedCapturePolicy, (AAudioStream * stream)) /* API 29 */
SDL_PROC_UNUSED(bool, AAudioStream_isPrivacySensitive, (AAudioStream* stream)) /* API 30 */ SDL_PROC_UNUSED(bool, AAudioStream_isPrivacySensitive, (AAudioStream * stream)) /* API 30 */

View File

@@ -43,64 +43,46 @@
#ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC #ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC
#endif #endif
static int (*ALSA_snd_pcm_open) static int (*ALSA_snd_pcm_open)(snd_pcm_t **, const char *, snd_pcm_stream_t, int);
(snd_pcm_t **, const char *, snd_pcm_stream_t, int); static int (*ALSA_snd_pcm_close)(snd_pcm_t *pcm);
static int (*ALSA_snd_pcm_close) (snd_pcm_t * pcm); static snd_pcm_sframes_t (*ALSA_snd_pcm_writei)(snd_pcm_t *, const void *, snd_pcm_uframes_t);
static snd_pcm_sframes_t (*ALSA_snd_pcm_writei) static snd_pcm_sframes_t (*ALSA_snd_pcm_readi)(snd_pcm_t *, void *, snd_pcm_uframes_t);
(snd_pcm_t *, const void *, snd_pcm_uframes_t); static int (*ALSA_snd_pcm_recover)(snd_pcm_t *, int, int);
static snd_pcm_sframes_t (*ALSA_snd_pcm_readi) static int (*ALSA_snd_pcm_prepare)(snd_pcm_t *);
(snd_pcm_t *, void *, snd_pcm_uframes_t); static int (*ALSA_snd_pcm_drain)(snd_pcm_t *);
static int (*ALSA_snd_pcm_recover) (snd_pcm_t *, int, int); static const char *(*ALSA_snd_strerror)(int);
static int (*ALSA_snd_pcm_prepare) (snd_pcm_t *); static size_t (*ALSA_snd_pcm_hw_params_sizeof)(void);
static int (*ALSA_snd_pcm_drain) (snd_pcm_t *); static size_t (*ALSA_snd_pcm_sw_params_sizeof)(void);
static const char *(*ALSA_snd_strerror) (int); static void (*ALSA_snd_pcm_hw_params_copy)(snd_pcm_hw_params_t *, const snd_pcm_hw_params_t *);
static size_t(*ALSA_snd_pcm_hw_params_sizeof) (void); static int (*ALSA_snd_pcm_hw_params_any)(snd_pcm_t *, snd_pcm_hw_params_t *);
static size_t(*ALSA_snd_pcm_sw_params_sizeof) (void); static int (*ALSA_snd_pcm_hw_params_set_access)(snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_access_t);
static void (*ALSA_snd_pcm_hw_params_copy) static int (*ALSA_snd_pcm_hw_params_set_format)(snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_format_t);
(snd_pcm_hw_params_t *, const snd_pcm_hw_params_t *); static int (*ALSA_snd_pcm_hw_params_set_channels)(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int);
static int (*ALSA_snd_pcm_hw_params_any) (snd_pcm_t *, snd_pcm_hw_params_t *); static int (*ALSA_snd_pcm_hw_params_get_channels)(const snd_pcm_hw_params_t *, unsigned int *);
static int (*ALSA_snd_pcm_hw_params_set_access) static int (*ALSA_snd_pcm_hw_params_set_rate_near)(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *);
(snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_access_t); static int (*ALSA_snd_pcm_hw_params_set_period_size_near)(snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_uframes_t *, int *);
static int (*ALSA_snd_pcm_hw_params_set_format) static int (*ALSA_snd_pcm_hw_params_get_period_size)(const snd_pcm_hw_params_t *, snd_pcm_uframes_t *, int *);
(snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_format_t); static int (*ALSA_snd_pcm_hw_params_set_periods_min)(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *);
static int (*ALSA_snd_pcm_hw_params_set_channels) static int (*ALSA_snd_pcm_hw_params_set_periods_first)(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *);
(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int); static int (*ALSA_snd_pcm_hw_params_get_periods)(const snd_pcm_hw_params_t *, unsigned int *, int *);
static int (*ALSA_snd_pcm_hw_params_get_channels) static int (*ALSA_snd_pcm_hw_params_set_buffer_size_near)(snd_pcm_t *pcm, snd_pcm_hw_params_t *, snd_pcm_uframes_t *);
(const snd_pcm_hw_params_t *, unsigned int *); static int (*ALSA_snd_pcm_hw_params_get_buffer_size)(const snd_pcm_hw_params_t *, snd_pcm_uframes_t *);
static int (*ALSA_snd_pcm_hw_params_set_rate_near) static int (*ALSA_snd_pcm_hw_params)(snd_pcm_t *, snd_pcm_hw_params_t *);
(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *); static int (*ALSA_snd_pcm_sw_params_current)(snd_pcm_t *,
static int (*ALSA_snd_pcm_hw_params_set_period_size_near)
(snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_uframes_t *, int *);
static int (*ALSA_snd_pcm_hw_params_get_period_size)
(const snd_pcm_hw_params_t *, snd_pcm_uframes_t *, int *);
static int (*ALSA_snd_pcm_hw_params_set_periods_min)
(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *);
static int (*ALSA_snd_pcm_hw_params_set_periods_first)
(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *);
static int (*ALSA_snd_pcm_hw_params_get_periods)
(const snd_pcm_hw_params_t *, unsigned int *, int *);
static int (*ALSA_snd_pcm_hw_params_set_buffer_size_near)
(snd_pcm_t *pcm, snd_pcm_hw_params_t *, snd_pcm_uframes_t *);
static int (*ALSA_snd_pcm_hw_params_get_buffer_size)
(const snd_pcm_hw_params_t *, snd_pcm_uframes_t *);
static int (*ALSA_snd_pcm_hw_params) (snd_pcm_t *, snd_pcm_hw_params_t *);
static int (*ALSA_snd_pcm_sw_params_current) (snd_pcm_t *,
snd_pcm_sw_params_t *); snd_pcm_sw_params_t *);
static int (*ALSA_snd_pcm_sw_params_set_start_threshold) static int (*ALSA_snd_pcm_sw_params_set_start_threshold)(snd_pcm_t *, snd_pcm_sw_params_t *, snd_pcm_uframes_t);
(snd_pcm_t *, snd_pcm_sw_params_t *, snd_pcm_uframes_t); static int (*ALSA_snd_pcm_sw_params)(snd_pcm_t *, snd_pcm_sw_params_t *);
static int (*ALSA_snd_pcm_sw_params) (snd_pcm_t *, snd_pcm_sw_params_t *); static int (*ALSA_snd_pcm_nonblock)(snd_pcm_t *, int);
static int (*ALSA_snd_pcm_nonblock) (snd_pcm_t *, int);
static int (*ALSA_snd_pcm_wait)(snd_pcm_t *, int); static int (*ALSA_snd_pcm_wait)(snd_pcm_t *, int);
static int (*ALSA_snd_pcm_sw_params_set_avail_min) static int (*ALSA_snd_pcm_sw_params_set_avail_min)(snd_pcm_t *, snd_pcm_sw_params_t *, snd_pcm_uframes_t);
(snd_pcm_t *, snd_pcm_sw_params_t *, snd_pcm_uframes_t);
static int (*ALSA_snd_pcm_reset)(snd_pcm_t *); static int (*ALSA_snd_pcm_reset)(snd_pcm_t *);
static int (*ALSA_snd_device_name_hint) (int, const char *, void ***); static int (*ALSA_snd_device_name_hint)(int, const char *, void ***);
static char* (*ALSA_snd_device_name_get_hint) (const void *, const char *); static char *(*ALSA_snd_device_name_get_hint)(const void *, const char *);
static int (*ALSA_snd_device_name_free_hint) (void **); static int (*ALSA_snd_device_name_free_hint)(void **);
static snd_pcm_sframes_t (*ALSA_snd_pcm_avail)(snd_pcm_t *); static snd_pcm_sframes_t (*ALSA_snd_pcm_avail)(snd_pcm_t *);
#ifdef SND_CHMAP_API_VERSION #ifdef SND_CHMAP_API_VERSION
static snd_pcm_chmap_t* (*ALSA_snd_pcm_get_chmap) (snd_pcm_t *); static snd_pcm_chmap_t *(*ALSA_snd_pcm_get_chmap)(snd_pcm_t *);
static int (*ALSA_snd_pcm_chmap_print) (const snd_pcm_chmap_t *map, size_t maxlen, char *buf); static int (*ALSA_snd_pcm_chmap_print)(const snd_pcm_chmap_t *map, size_t maxlen, char *buf);
#endif #endif
#ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC #ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC
@@ -110,8 +92,7 @@ static int (*ALSA_snd_pcm_chmap_print) (const snd_pcm_chmap_t *map, size_t maxle
static const char *alsa_library = SDL_AUDIO_DRIVER_ALSA_DYNAMIC; static const char *alsa_library = SDL_AUDIO_DRIVER_ALSA_DYNAMIC;
static void *alsa_handle = NULL; static void *alsa_handle = NULL;
static int static int load_alsa_sym(const char *fn, void **addr)
load_alsa_sym(const char *fn, void **addr)
{ {
*addr = SDL_LoadFunction(alsa_handle, fn); *addr = SDL_LoadFunction(alsa_handle, fn);
if (*addr == NULL) { if (*addr == NULL) {
@@ -124,13 +105,13 @@ load_alsa_sym(const char *fn, void **addr)
/* cast funcs to char* first, to please GCC's strict aliasing rules. */ /* cast funcs to char* first, to please GCC's strict aliasing rules. */
#define SDL_ALSA_SYM(x) \ #define SDL_ALSA_SYM(x) \
if (!load_alsa_sym(#x, (void **) (char *) &ALSA_##x)) return -1 if (!load_alsa_sym(#x, (void **)(char *)&ALSA_##x)) \
return -1
#else #else
#define SDL_ALSA_SYM(x) ALSA_##x = x #define SDL_ALSA_SYM(x) ALSA_##x = x
#endif #endif
static int static int load_alsa_syms(void)
load_alsa_syms(void)
{ {
SDL_ALSA_SYM(snd_pcm_open); SDL_ALSA_SYM(snd_pcm_open);
SDL_ALSA_SYM(snd_pcm_close); SDL_ALSA_SYM(snd_pcm_close);
@@ -180,8 +161,7 @@ load_alsa_syms(void)
#ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC #ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC
static void static void UnloadALSALibrary(void)
UnloadALSALibrary(void)
{ {
if (alsa_handle != NULL) { if (alsa_handle != NULL) {
SDL_UnloadObject(alsa_handle); SDL_UnloadObject(alsa_handle);
@@ -189,8 +169,7 @@ UnloadALSALibrary(void)
} }
} }
static int static int LoadALSALibrary(void)
LoadALSALibrary(void)
{ {
int retval = 0; int retval = 0;
if (alsa_handle == NULL) { if (alsa_handle == NULL) {
@@ -210,13 +189,11 @@ LoadALSALibrary(void)
#else #else
static void static void UnloadALSALibrary(void)
UnloadALSALibrary(void)
{ {
} }
static int static int LoadALSALibrary(void)
LoadALSALibrary(void)
{ {
load_alsa_syms(); load_alsa_syms();
return 0; return 0;
@@ -224,8 +201,7 @@ LoadALSALibrary(void)
#endif /* SDL_AUDIO_DRIVER_ALSA_DYNAMIC */ #endif /* SDL_AUDIO_DRIVER_ALSA_DYNAMIC */
static const char * static const char *get_audio_device(void *handle, const int channels)
get_audio_device(void *handle, const int channels)
{ {
const char *device; const char *device;
@@ -248,13 +224,11 @@ get_audio_device(void *handle, const int channels)
return "default"; return "default";
} }
/* This function waits until it is possible to write a full sound buffer */ /* This function waits until it is possible to write a full sound buffer */
static void static void ALSA_WaitDevice(_THIS)
ALSA_WaitDevice(_THIS)
{ {
#if SDL_ALSA_NON_BLOCKING #if SDL_ALSA_NON_BLOCKING
const snd_pcm_sframes_t needed = (snd_pcm_sframes_t) this->spec.samples; const snd_pcm_sframes_t needed = (snd_pcm_sframes_t)this->spec.samples;
while (SDL_AtomicGet(&this->enabled)) { while (SDL_AtomicGet(&this->enabled)) {
const snd_pcm_sframes_t rc = ALSA_snd_pcm_avail(this->hidden->pcm_handle); const snd_pcm_sframes_t rc = ALSA_snd_pcm_avail(this->hidden->pcm_handle);
if ((rc < 0) && (rc != -EAGAIN)) { if ((rc < 0) && (rc != -EAGAIN)) {
@@ -273,7 +247,6 @@ ALSA_WaitDevice(_THIS)
#endif #endif
} }
/* !!! FIXME: is there a channel swizzler in alsalib instead? */ /* !!! FIXME: is there a channel swizzler in alsalib instead? */
/* /*
* https://bugzilla.libsdl.org/show_bug.cgi?id=110 * https://bugzilla.libsdl.org/show_bug.cgi?id=110
@@ -281,16 +254,20 @@ ALSA_WaitDevice(_THIS)
* and for Windows DirectX [and CoreAudio], this is FL-FR-C-LFE-RL-RR" * and for Windows DirectX [and CoreAudio], this is FL-FR-C-LFE-RL-RR"
*/ */
#define SWIZ6(T) \ #define SWIZ6(T) \
static void swizzle_alsa_channels_6_##T(void *buffer, const Uint32 bufferlen) { \ static void swizzle_alsa_channels_6_##T(void *buffer, const Uint32 bufferlen) \
T *ptr = (T *) buffer; \ { \
T *ptr = (T *)buffer; \
Uint32 i; \ Uint32 i; \
for (i = 0; i < bufferlen; i++, ptr += 6) { \ for (i = 0; i < bufferlen; i++, ptr += 6) { \
T tmp; \ T tmp; \
tmp = ptr[2]; ptr[2] = ptr[4]; ptr[4] = tmp; \ tmp = ptr[2]; \
tmp = ptr[3]; ptr[3] = ptr[5]; ptr[5] = tmp; \ ptr[2] = ptr[4]; \
ptr[4] = tmp; \
tmp = ptr[3]; \
ptr[3] = ptr[5]; \
ptr[5] = tmp; \
} \ } \
} }
/* !!! FIXME: is there a channel swizzler in alsalib instead? */ /* !!! FIXME: is there a channel swizzler in alsalib instead? */
/* !!! FIXME: this screams for a SIMD shuffle operation. */ /* !!! FIXME: this screams for a SIMD shuffle operation. */
@@ -300,8 +277,9 @@ static void swizzle_alsa_channels_6_##T(void *buffer, const Uint32 bufferlen) {
* and for Windows DirectX [and CoreAudio], this is FL-FR-C-LFE-SL-SR-RL-RR" * and for Windows DirectX [and CoreAudio], this is FL-FR-C-LFE-SL-SR-RL-RR"
*/ */
#define SWIZ8(T) \ #define SWIZ8(T) \
static void swizzle_alsa_channels_8_##T(void *buffer, const Uint32 bufferlen) { \ static void swizzle_alsa_channels_8_##T(void *buffer, const Uint32 bufferlen) \
T *ptr = (T *) buffer; \ { \
T *ptr = (T *)buffer; \
Uint32 i; \ Uint32 i; \
for (i = 0; i < bufferlen; i++, ptr += 6) { \ for (i = 0; i < bufferlen; i++, ptr += 6) { \
const T center = ptr[2]; \ const T center = ptr[2]; \
@@ -317,7 +295,7 @@ static void swizzle_alsa_channels_8_##T(void *buffer, const Uint32 bufferlen) {
ptr[6] = side_left; \ ptr[6] = side_left; \
ptr[7] = side_right; \ ptr[7] = side_right; \
} \ } \
} }
#define CHANNEL_SWIZZLE(x) \ #define CHANNEL_SWIZZLE(x) \
x(Uint64) \ x(Uint64) \
@@ -332,53 +310,59 @@ CHANNEL_SWIZZLE(SWIZ8)
#undef SWIZ6 #undef SWIZ6
#undef SWIZ8 #undef SWIZ8
/* /*
* Called right before feeding this->hidden->mixbuf to the hardware. Swizzle * Called right before feeding this->hidden->mixbuf to the hardware. Swizzle
* channels from Windows/Mac order to the format alsalib will want. * channels from Windows/Mac order to the format alsalib will want.
*/ */
static void static void swizzle_alsa_channels(_THIS, void *buffer, Uint32 bufferlen)
swizzle_alsa_channels(_THIS, void *buffer, Uint32 bufferlen)
{ {
switch (this->spec.channels) { switch (this->spec.channels) {
#define CHANSWIZ(chans) \ #define CHANSWIZ(chans) \
case chans: \ case chans: \
switch ((this->spec.format & (0xFF))) { \ switch ((this->spec.format & (0xFF))) { \
case 8: swizzle_alsa_channels_##chans##_Uint8(buffer, bufferlen); break; \ case 8: \
case 16: swizzle_alsa_channels_##chans##_Uint16(buffer, bufferlen); break; \ swizzle_alsa_channels_##chans##_Uint8(buffer, bufferlen); \
case 32: swizzle_alsa_channels_##chans##_Uint32(buffer, bufferlen); break; \ break; \
case 64: swizzle_alsa_channels_##chans##_Uint64(buffer, bufferlen); break; \ case 16: \
default: SDL_assert(!"unhandled bitsize"); break; \ swizzle_alsa_channels_##chans##_Uint16(buffer, bufferlen); \
break; \
case 32: \
swizzle_alsa_channels_##chans##_Uint32(buffer, bufferlen); \
break; \
case 64: \
swizzle_alsa_channels_##chans##_Uint64(buffer, bufferlen); \
break; \
default: \
SDL_assert(!"unhandled bitsize"); \
break; \
} \ } \
return; return;
CHANSWIZ(6); CHANSWIZ(6);
CHANSWIZ(8); CHANSWIZ(8);
#undef CHANSWIZ #undef CHANSWIZ
default: break; default:
break;
} }
} }
#ifdef SND_CHMAP_API_VERSION #ifdef SND_CHMAP_API_VERSION
/* Some devices have the right channel map, no swizzling necessary */ /* Some devices have the right channel map, no swizzling necessary */
static void static void no_swizzle(_THIS, void *buffer, Uint32 bufferlen)
no_swizzle(_THIS, void *buffer, Uint32 bufferlen)
{ {
} }
#endif /* SND_CHMAP_API_VERSION */ #endif /* SND_CHMAP_API_VERSION */
static void ALSA_PlayDevice(_THIS)
static void
ALSA_PlayDevice(_THIS)
{ {
const Uint8 *sample_buf = (const Uint8 *) this->hidden->mixbuf; const Uint8 *sample_buf = (const Uint8 *)this->hidden->mixbuf;
const int frame_size = ((SDL_AUDIO_BITSIZE(this->spec.format)) / 8) * const int frame_size = ((SDL_AUDIO_BITSIZE(this->spec.format)) / 8) *
this->spec.channels; this->spec.channels;
snd_pcm_uframes_t frames_left = ((snd_pcm_uframes_t) this->spec.samples); snd_pcm_uframes_t frames_left = ((snd_pcm_uframes_t)this->spec.samples);
this->hidden->swizzle_func(this, this->hidden->mixbuf, frames_left); this->hidden->swizzle_func(this, this->hidden->mixbuf, frames_left);
while ( frames_left > 0 && SDL_AtomicGet(&this->enabled) ) { while (frames_left > 0 && SDL_AtomicGet(&this->enabled)) {
int status = ALSA_snd_pcm_writei(this->hidden->pcm_handle, int status = ALSA_snd_pcm_writei(this->hidden->pcm_handle,
sample_buf, frames_left); sample_buf, frames_left);
@@ -410,16 +394,14 @@ ALSA_PlayDevice(_THIS)
} }
} }
static Uint8 * static Uint8 *ALSA_GetDeviceBuf(_THIS)
ALSA_GetDeviceBuf(_THIS)
{ {
return this->hidden->mixbuf; return this->hidden->mixbuf;
} }
static int static int ALSA_CaptureFromDevice(_THIS, void *buffer, int buflen)
ALSA_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
Uint8 *sample_buf = (Uint8 *) buffer; Uint8 *sample_buf = (Uint8 *)buffer;
const int frame_size = ((SDL_AUDIO_BITSIZE(this->spec.format)) / 8) * const int frame_size = ((SDL_AUDIO_BITSIZE(this->spec.format)) / 8) *
this->spec.channels; this->spec.channels;
const int total_frames = buflen / frame_size; const int total_frames = buflen / frame_size;
@@ -428,7 +410,7 @@ ALSA_CaptureFromDevice(_THIS, void *buffer, int buflen)
SDL_assert((buflen % frame_size) == 0); SDL_assert((buflen % frame_size) == 0);
while ( frames_left > 0 && SDL_AtomicGet(&this->enabled) ) { while (frames_left > 0 && SDL_AtomicGet(&this->enabled)) {
int status; int status;
status = ALSA_snd_pcm_readi(this->hidden->pcm_handle, status = ALSA_snd_pcm_readi(this->hidden->pcm_handle,
@@ -459,14 +441,12 @@ ALSA_CaptureFromDevice(_THIS, void *buffer, int buflen)
return (total_frames - frames_left) * frame_size; return (total_frames - frames_left) * frame_size;
} }
static void static void ALSA_FlushCapture(_THIS)
ALSA_FlushCapture(_THIS)
{ {
ALSA_snd_pcm_reset(this->hidden->pcm_handle); ALSA_snd_pcm_reset(this->hidden->pcm_handle);
} }
static void static void ALSA_CloseDevice(_THIS)
ALSA_CloseDevice(_THIS)
{ {
if (this->hidden->pcm_handle) { if (this->hidden->pcm_handle) {
/* Wait for the submitted audio to drain /* Wait for the submitted audio to drain
@@ -481,8 +461,7 @@ ALSA_CloseDevice(_THIS)
SDL_free(this->hidden); SDL_free(this->hidden);
} }
static int static int ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params)
ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params)
{ {
int status; int status;
snd_pcm_hw_params_t *hwparams; snd_pcm_hw_params_t *hwparams;
@@ -497,7 +476,7 @@ ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params)
persize = this->spec.samples; persize = this->spec.samples;
status = ALSA_snd_pcm_hw_params_set_period_size_near( status = ALSA_snd_pcm_hw_params_set_period_size_near(
this->hidden->pcm_handle, hwparams, &persize, NULL); this->hidden->pcm_handle, hwparams, &persize, NULL);
if ( status < 0 ) { if (status < 0) {
return -1; return -1;
} }
@@ -505,26 +484,26 @@ ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params)
periods = 2; periods = 2;
status = ALSA_snd_pcm_hw_params_set_periods_min( status = ALSA_snd_pcm_hw_params_set_periods_min(
this->hidden->pcm_handle, hwparams, &periods, NULL); this->hidden->pcm_handle, hwparams, &periods, NULL);
if ( status < 0 ) { if (status < 0) {
return -1; return -1;
} }
status = ALSA_snd_pcm_hw_params_set_periods_first( status = ALSA_snd_pcm_hw_params_set_periods_first(
this->hidden->pcm_handle, hwparams, &periods, NULL); this->hidden->pcm_handle, hwparams, &periods, NULL);
if ( status < 0 ) { if (status < 0) {
return -1; return -1;
} }
/* "set" the hardware with the desired parameters */ /* "set" the hardware with the desired parameters */
status = ALSA_snd_pcm_hw_params(this->hidden->pcm_handle, hwparams); status = ALSA_snd_pcm_hw_params(this->hidden->pcm_handle, hwparams);
if ( status < 0 ) { if (status < 0) {
return -1; return -1;
} }
this->spec.samples = persize; this->spec.samples = persize;
/* This is useful for debugging */ /* This is useful for debugging */
if ( SDL_getenv("SDL_AUDIO_ALSA_DEBUG") ) { if (SDL_getenv("SDL_AUDIO_ALSA_DEBUG")) {
snd_pcm_uframes_t bufsize; snd_pcm_uframes_t bufsize;
ALSA_snd_pcm_hw_params_get_buffer_size(hwparams, &bufsize); ALSA_snd_pcm_hw_params_get_buffer_size(hwparams, &bufsize);
@@ -537,8 +516,7 @@ ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params)
return 0; return 0;
} }
static int static int ALSA_OpenDevice(_THIS, const char *devname)
ALSA_OpenDevice(_THIS, const char *devname)
{ {
int status = 0; int status = 0;
SDL_bool iscapture = this->iscapture; SDL_bool iscapture = this->iscapture;
@@ -704,18 +682,18 @@ ALSA_OpenDevice(_THIS, const char *devname)
/* Allocate mixing buffer */ /* Allocate mixing buffer */
if (!iscapture) { if (!iscapture) {
this->hidden->mixlen = this->spec.size; this->hidden->mixlen = this->spec.size;
this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); this->hidden->mixbuf = (Uint8 *)SDL_malloc(this->hidden->mixlen);
if (this->hidden->mixbuf == NULL) { if (this->hidden->mixbuf == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
SDL_memset(this->hidden->mixbuf, this->spec.silence, this->hidden->mixlen); SDL_memset(this->hidden->mixbuf, this->spec.silence, this->hidden->mixlen);
} }
#if !SDL_ALSA_NON_BLOCKING #if !SDL_ALSA_NON_BLOCKING
if (!iscapture) { if (!iscapture) {
ALSA_snd_pcm_nonblock(pcm_handle, 0); ALSA_snd_pcm_nonblock(pcm_handle, 0);
} }
#endif #endif
/* We're ready to rock and roll. :-) */ /* We're ready to rock and roll. :-) */
return 0; return 0;
@@ -728,10 +706,9 @@ typedef struct ALSA_Device
struct ALSA_Device *next; struct ALSA_Device *next;
} ALSA_Device; } ALSA_Device;
static void static void add_device(const int iscapture, const char *name, void *hint, ALSA_Device **pSeen)
add_device(const int iscapture, const char *name, void *hint, ALSA_Device **pSeen)
{ {
ALSA_Device *dev = SDL_malloc(sizeof (ALSA_Device)); ALSA_Device *dev = SDL_malloc(sizeof(ALSA_Device));
char *desc; char *desc;
char *handle = NULL; char *handle = NULL;
char *ptr; char *ptr;
@@ -751,7 +728,7 @@ add_device(const int iscapture, const char *name, void *hint, ALSA_Device **pSee
return; return;
} }
} else { } else {
desc = (char *) name; desc = (char *)name;
} }
SDL_assert(name != NULL); SDL_assert(name != NULL);
@@ -788,11 +765,9 @@ add_device(const int iscapture, const char *name, void *hint, ALSA_Device **pSee
*pSeen = dev; *pSeen = dev;
} }
static ALSA_Device *hotplug_devices = NULL; static ALSA_Device *hotplug_devices = NULL;
static void static void ALSA_HotplugIteration(void)
ALSA_HotplugIteration(void)
{ {
void **hints = NULL; void **hints = NULL;
ALSA_Device *dev; ALSA_Device *dev;
@@ -807,7 +782,7 @@ ALSA_HotplugIteration(void)
int bestmatch = 0xFFFF; int bestmatch = 0xFFFF;
size_t match_len = 0; size_t match_len = 0;
int defaultdev = -1; int defaultdev = -1;
static const char * const prefixes[] = { static const char *const prefixes[] = {
"hw:", "sysdefault:", "default:", NULL "hw:", "sysdefault:", "default:", NULL
}; };
@@ -876,7 +851,7 @@ ALSA_HotplugIteration(void)
prev = NULL; prev = NULL;
for (dev = unseen; dev; dev = next) { for (dev = unseen; dev; dev = next) {
next = dev->next; next = dev->next;
if ( (SDL_strcmp(dev->name, name) == 0) && (((isinput) && dev->iscapture) || ((isoutput) && !dev->iscapture)) ) { if ((SDL_strcmp(dev->name, name) == 0) && (((isinput) && dev->iscapture) || ((isoutput) && !dev->iscapture))) {
if (prev) { if (prev) {
prev->next = next; prev->next = next;
} else { } else {
@@ -925,8 +900,7 @@ ALSA_HotplugIteration(void)
static SDL_atomic_t ALSA_hotplug_shutdown; static SDL_atomic_t ALSA_hotplug_shutdown;
static SDL_Thread *ALSA_hotplug_thread; static SDL_Thread *ALSA_hotplug_thread;
static int SDLCALL static int SDLCALL ALSA_HotplugThread(void *arg)
ALSA_HotplugThread(void *arg)
{ {
SDL_SetThreadPriority(SDL_THREAD_PRIORITY_LOW); SDL_SetThreadPriority(SDL_THREAD_PRIORITY_LOW);
@@ -944,8 +918,7 @@ ALSA_HotplugThread(void *arg)
} }
#endif #endif
static void static void ALSA_DetectDevices(void)
ALSA_DetectDevices(void)
{ {
ALSA_HotplugIteration(); /* run once now before a thread continues to check. */ ALSA_HotplugIteration(); /* run once now before a thread continues to check. */
@@ -956,8 +929,7 @@ ALSA_DetectDevices(void)
#endif #endif
} }
static void static void ALSA_Deinitialize(void)
ALSA_Deinitialize(void)
{ {
ALSA_Device *dev; ALSA_Device *dev;
ALSA_Device *next; ALSA_Device *next;
@@ -982,8 +954,7 @@ ALSA_Deinitialize(void)
UnloadALSALibrary(); UnloadALSALibrary();
} }
static SDL_bool static SDL_bool ALSA_Init(SDL_AudioDriverImpl *impl)
ALSA_Init(SDL_AudioDriverImpl * impl)
{ {
if (LoadALSALibrary() < 0) { if (LoadALSALibrary() < 0) {
return SDL_FALSE; return SDL_FALSE;
@@ -1006,7 +977,6 @@ ALSA_Init(SDL_AudioDriverImpl * impl)
return SDL_TRUE; /* this audio target is available. */ return SDL_TRUE; /* this audio target is available. */
} }
AudioBootStrap ALSA_bootstrap = { AudioBootStrap ALSA_bootstrap = {
"alsa", "ALSA PCM audio", ALSA_Init, SDL_FALSE "alsa", "ALSA PCM audio", ALSA_Init, SDL_FALSE
}; };

View File

@@ -31,11 +31,10 @@
#include <android/log.h> #include <android/log.h>
static SDL_AudioDevice* audioDevice = NULL; static SDL_AudioDevice *audioDevice = NULL;
static SDL_AudioDevice* captureDevice = NULL; static SDL_AudioDevice *captureDevice = NULL;
static int static int ANDROIDAUDIO_OpenDevice(_THIS, const char *devname)
ANDROIDAUDIO_OpenDevice(_THIS, const char *devname)
{ {
SDL_AudioFormat test_format; SDL_AudioFormat test_format;
SDL_bool iscapture = this->iscapture; SDL_bool iscapture = this->iscapture;
@@ -49,7 +48,7 @@ ANDROIDAUDIO_OpenDevice(_THIS, const char *devname)
audioDevice = this; audioDevice = this;
} }
this->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, (sizeof *this->hidden)); this->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, (sizeof *this->hidden));
if (this->hidden == NULL) { if (this->hidden == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -77,32 +76,27 @@ ANDROIDAUDIO_OpenDevice(_THIS, const char *devname)
return 0; return 0;
} }
static void static void ANDROIDAUDIO_PlayDevice(_THIS)
ANDROIDAUDIO_PlayDevice(_THIS)
{ {
Android_JNI_WriteAudioBuffer(); Android_JNI_WriteAudioBuffer();
} }
static Uint8 * static Uint8 *ANDROIDAUDIO_GetDeviceBuf(_THIS)
ANDROIDAUDIO_GetDeviceBuf(_THIS)
{ {
return Android_JNI_GetAudioBuffer(); return Android_JNI_GetAudioBuffer();
} }
static int static int ANDROIDAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
ANDROIDAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
return Android_JNI_CaptureAudioBuffer(buffer, buflen); return Android_JNI_CaptureAudioBuffer(buffer, buflen);
} }
static void static void ANDROIDAUDIO_FlushCapture(_THIS)
ANDROIDAUDIO_FlushCapture(_THIS)
{ {
Android_JNI_FlushCapturedAudio(); Android_JNI_FlushCapturedAudio();
} }
static void static void ANDROIDAUDIO_CloseDevice(_THIS)
ANDROIDAUDIO_CloseDevice(_THIS)
{ {
/* At this point SDL_CloseAudioDevice via close_audio_device took care of terminating the audio thread /* At this point SDL_CloseAudioDevice via close_audio_device took care of terminating the audio thread
so it's safe to terminate the Java side buffer and AudioTrack so it's safe to terminate the Java side buffer and AudioTrack
@@ -118,8 +112,7 @@ ANDROIDAUDIO_CloseDevice(_THIS)
SDL_free(this->hidden); SDL_free(this->hidden);
} }
static SDL_bool static SDL_bool ANDROIDAUDIO_Init(SDL_AudioDriverImpl *impl)
ANDROIDAUDIO_Init(SDL_AudioDriverImpl * impl)
{ {
/* Set the function pointers */ /* Set the function pointers */
impl->OpenDevice = ANDROIDAUDIO_OpenDevice; impl->OpenDevice = ANDROIDAUDIO_OpenDevice;
@@ -147,7 +140,7 @@ void ANDROIDAUDIO_PauseDevices(void)
/* TODO: Handle multiple devices? */ /* TODO: Handle multiple devices? */
struct SDL_PrivateAudioData *private; struct SDL_PrivateAudioData *private;
if (audioDevice != NULL && audioDevice->hidden != NULL) { if (audioDevice != NULL && audioDevice->hidden != NULL) {
private = (struct SDL_PrivateAudioData *) audioDevice->hidden; private = (struct SDL_PrivateAudioData *)audioDevice->hidden;
if (SDL_AtomicGet(&audioDevice->paused)) { if (SDL_AtomicGet(&audioDevice->paused)) {
/* The device is already paused, leave it alone */ /* The device is already paused, leave it alone */
private->resume = SDL_FALSE; private->resume = SDL_FALSE;
@@ -159,7 +152,7 @@ void ANDROIDAUDIO_PauseDevices(void)
} }
if (captureDevice != NULL && captureDevice->hidden != NULL) { if (captureDevice != NULL && captureDevice->hidden != NULL) {
private = (struct SDL_PrivateAudioData *) captureDevice->hidden; private = (struct SDL_PrivateAudioData *)captureDevice->hidden;
if (SDL_AtomicGet(&captureDevice->paused)) { if (SDL_AtomicGet(&captureDevice->paused)) {
/* The device is already paused, leave it alone */ /* The device is already paused, leave it alone */
private->resume = SDL_FALSE; private->resume = SDL_FALSE;
@@ -177,7 +170,7 @@ void ANDROIDAUDIO_ResumeDevices(void)
/* TODO: Handle multiple devices? */ /* TODO: Handle multiple devices? */
struct SDL_PrivateAudioData *private; struct SDL_PrivateAudioData *private;
if (audioDevice != NULL && audioDevice->hidden != NULL) { if (audioDevice != NULL && audioDevice->hidden != NULL) {
private = (struct SDL_PrivateAudioData *) audioDevice->hidden; private = (struct SDL_PrivateAudioData *)audioDevice->hidden;
if (private->resume) { if (private->resume) {
SDL_AtomicSet(&audioDevice->paused, 0); SDL_AtomicSet(&audioDevice->paused, 0);
private->resume = SDL_FALSE; private->resume = SDL_FALSE;
@@ -186,7 +179,7 @@ void ANDROIDAUDIO_ResumeDevices(void)
} }
if (captureDevice != NULL && captureDevice->hidden != NULL) { if (captureDevice != NULL && captureDevice->hidden != NULL) {
private = (struct SDL_PrivateAudioData *) captureDevice->hidden; private = (struct SDL_PrivateAudioData *)captureDevice->hidden;
if (private->resume) { if (private->resume) {
SDL_AtomicSet(&captureDevice->paused, 0); SDL_AtomicSet(&captureDevice->paused, 0);
private->resume = SDL_FALSE; private->resume = SDL_FALSE;
@@ -203,4 +196,3 @@ void ANDROIDAUDIO_PauseDevices(void) {}
#endif /* SDL_AUDIO_DRIVER_ANDROID */ #endif /* SDL_AUDIO_DRIVER_ANDROID */
/* vi: set ts=4 sw=4 expandtab: */ /* vi: set ts=4 sw=4 expandtab: */

View File

@@ -32,21 +32,20 @@
#define DEBUG_COREAUDIO 0 #define DEBUG_COREAUDIO 0
#if DEBUG_COREAUDIO #if DEBUG_COREAUDIO
#define CHECK_RESULT(msg) \ #define CHECK_RESULT(msg) \
if (result != noErr) { \ if (result != noErr) { \
printf("COREAUDIO: Got error %d from '%s'!\n", (int) result, msg); \ printf("COREAUDIO: Got error %d from '%s'!\n", (int)result, msg); \
SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \ SDL_SetError("CoreAudio error (%s): %d", msg, (int)result); \
return 0; \ return 0; \
} }
#else #else
#define CHECK_RESULT(msg) \ #define CHECK_RESULT(msg) \
if (result != noErr) { \ if (result != noErr) { \
SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \ SDL_SetError("CoreAudio error (%s): %d", msg, (int)result); \
return 0; \ return 0; \
} }
#endif #endif
#if MACOSX_COREAUDIO #if MACOSX_COREAUDIO
static const AudioObjectPropertyAddress devlist_address = { static const AudioObjectPropertyAddress devlist_address = {
kAudioHardwarePropertyDevices, kAudioHardwarePropertyDevices,
@@ -66,10 +65,9 @@ typedef struct AudioDeviceList
static AudioDeviceList *output_devs = NULL; static AudioDeviceList *output_devs = NULL;
static AudioDeviceList *capture_devs = NULL; static AudioDeviceList *capture_devs = NULL;
static SDL_bool static SDL_bool add_to_internal_dev_list(const int iscapture, AudioDeviceID devId)
add_to_internal_dev_list(const int iscapture, AudioDeviceID devId)
{ {
AudioDeviceList *item = (AudioDeviceList *) SDL_malloc(sizeof (AudioDeviceList)); AudioDeviceList *item = (AudioDeviceList *)SDL_malloc(sizeof(AudioDeviceList));
if (item == NULL) { if (item == NULL) {
return SDL_FALSE; return SDL_FALSE;
} }
@@ -85,16 +83,14 @@ add_to_internal_dev_list(const int iscapture, AudioDeviceID devId)
return SDL_TRUE; return SDL_TRUE;
} }
static void static void addToDevList(const char *name, SDL_AudioSpec *spec, const int iscapture, AudioDeviceID devId, void *data)
addToDevList(const char *name, SDL_AudioSpec *spec, const int iscapture, AudioDeviceID devId, void *data)
{ {
if (add_to_internal_dev_list(iscapture, devId)) { if (add_to_internal_dev_list(iscapture, devId)) {
SDL_AddAudioDevice(iscapture, name, spec, (void *) ((size_t) devId)); SDL_AddAudioDevice(iscapture, name, spec, (void *)((size_t)devId));
} }
} }
static void static void build_device_list(int iscapture, addDevFn addfn, void *addfndata)
build_device_list(int iscapture, addDevFn addfn, void *addfndata)
{ {
OSStatus result = noErr; OSStatus result = noErr;
UInt32 size = 0; UInt32 size = 0;
@@ -107,7 +103,7 @@ build_device_list(int iscapture, addDevFn addfn, void *addfndata)
if (result != kAudioHardwareNoError) if (result != kAudioHardwareNoError)
return; return;
devs = (AudioDeviceID *) alloca(size); devs = (AudioDeviceID *)alloca(size);
if (devs == NULL) if (devs == NULL)
return; return;
@@ -116,7 +112,7 @@ build_device_list(int iscapture, addDevFn addfn, void *addfndata)
if (result != kAudioHardwareNoError) if (result != kAudioHardwareNoError)
return; return;
max = size / sizeof (AudioDeviceID); max = size / sizeof(AudioDeviceID);
for (i = 0; i < max; i++) { for (i = 0; i < max; i++) {
CFStringRef cfstr = NULL; CFStringRef cfstr = NULL;
char *ptr = NULL; char *ptr = NULL;
@@ -146,7 +142,7 @@ build_device_list(int iscapture, addDevFn addfn, void *addfndata)
if (result != noErr) if (result != noErr)
continue; continue;
buflist = (AudioBufferList *) SDL_malloc(size); buflist = (AudioBufferList *)SDL_malloc(size);
if (buflist == NULL) if (buflist == NULL)
continue; continue;
@@ -166,13 +162,13 @@ build_device_list(int iscapture, addDevFn addfn, void *addfndata)
if (spec.channels == 0) if (spec.channels == 0)
continue; continue;
size = sizeof (sampleRate); size = sizeof(sampleRate);
result = AudioObjectGetPropertyData(dev, &freqaddr, 0, NULL, &size, &sampleRate); result = AudioObjectGetPropertyData(dev, &freqaddr, 0, NULL, &size, &sampleRate);
if (result == noErr) { if (result == noErr) {
spec.freq = (int) sampleRate; spec.freq = (int)sampleRate;
} }
size = sizeof (CFStringRef); size = sizeof(CFStringRef);
result = AudioObjectGetPropertyData(dev, &nameaddr, 0, NULL, &size, &cfstr); result = AudioObjectGetPropertyData(dev, &nameaddr, 0, NULL, &size, &cfstr);
if (result != kAudioHardwareNoError) if (result != kAudioHardwareNoError)
continue; continue;
@@ -180,10 +176,9 @@ build_device_list(int iscapture, addDevFn addfn, void *addfndata)
len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr), len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr),
kCFStringEncodingUTF8); kCFStringEncodingUTF8);
ptr = (char *) SDL_malloc(len + 1); ptr = (char *)SDL_malloc(len + 1);
usable = ((ptr != NULL) && usable = ((ptr != NULL) &&
(CFStringGetCString (CFStringGetCString(cfstr, ptr, len + 1, kCFStringEncodingUTF8)));
(cfstr, ptr, len + 1, kCFStringEncodingUTF8)));
CFRelease(cfstr); CFRelease(cfstr);
@@ -202,7 +197,7 @@ build_device_list(int iscapture, addDevFn addfn, void *addfndata)
#if DEBUG_COREAUDIO #if DEBUG_COREAUDIO
printf("COREAUDIO: Found %s device #%d: '%s' (devid %d)\n", printf("COREAUDIO: Found %s device #%d: '%s' (devid %d)\n",
((iscapture) ? "capture" : "output"), ((iscapture) ? "capture" : "output"),
(int) i, ptr, (int) dev); (int)i, ptr, (int)dev);
#endif #endif
addfn(ptr, &spec, iscapture, dev, addfndata); addfn(ptr, &spec, iscapture, dev, addfndata);
} }
@@ -210,8 +205,7 @@ build_device_list(int iscapture, addDevFn addfn, void *addfndata)
} }
} }
static void static void free_audio_device_list(AudioDeviceList **list)
free_audio_device_list(AudioDeviceList **list)
{ {
AudioDeviceList *item = *list; AudioDeviceList *item = *list;
while (item) { while (item) {
@@ -222,17 +216,15 @@ free_audio_device_list(AudioDeviceList **list)
*list = NULL; *list = NULL;
} }
static void static void COREAUDIO_DetectDevices(void)
COREAUDIO_DetectDevices(void)
{ {
build_device_list(SDL_TRUE, addToDevList, NULL); build_device_list(SDL_TRUE, addToDevList, NULL);
build_device_list(SDL_FALSE, addToDevList, NULL); build_device_list(SDL_FALSE, addToDevList, NULL);
} }
static void static void build_device_change_list(const char *name, SDL_AudioSpec *spec, const int iscapture, AudioDeviceID devId, void *data)
build_device_change_list(const char *name, SDL_AudioSpec *spec, const int iscapture, AudioDeviceID devId, void *data)
{ {
AudioDeviceList **list = (AudioDeviceList **) data; AudioDeviceList **list = (AudioDeviceList **)data;
AudioDeviceList *item; AudioDeviceList *item;
for (item = *list; item != NULL; item = item->next) { for (item = *list; item != NULL; item = item->next) {
if (item->devid == devId) { if (item->devid == devId) {
@@ -242,11 +234,10 @@ build_device_change_list(const char *name, SDL_AudioSpec *spec, const int iscapt
} }
add_to_internal_dev_list(iscapture, devId); /* new device, add it. */ add_to_internal_dev_list(iscapture, devId); /* new device, add it. */
SDL_AddAudioDevice(iscapture, name, spec, (void *) ((size_t) devId)); SDL_AddAudioDevice(iscapture, name, spec, (void *)((size_t)devId));
} }
static void static void reprocess_device_list(const int iscapture, AudioDeviceList **list)
reprocess_device_list(const int iscapture, AudioDeviceList **list)
{ {
AudioDeviceList *item; AudioDeviceList *item;
AudioDeviceList *prev = NULL; AudioDeviceList *prev = NULL;
@@ -263,7 +254,7 @@ reprocess_device_list(const int iscapture, AudioDeviceList **list)
if (item->alive) { if (item->alive) {
prev = item; prev = item;
} else { } else {
SDL_RemoveAudioDevice(iscapture, (void *) ((size_t) item->devid)); SDL_RemoveAudioDevice(iscapture, (void *)((size_t)item->devid));
if (prev) { if (prev) {
prev->next = item->next; prev->next = item->next;
} else { } else {
@@ -276,8 +267,7 @@ reprocess_device_list(const int iscapture, AudioDeviceList **list)
} }
/* this is called when the system's list of available audio devices changes. */ /* this is called when the system's list of available audio devices changes. */
static OSStatus static OSStatus device_list_changed(AudioObjectID systemObj, UInt32 num_addr, const AudioObjectPropertyAddress *addrs, void *data)
device_list_changed(AudioObjectID systemObj, UInt32 num_addr, const AudioObjectPropertyAddress *addrs, void *data)
{ {
reprocess_device_list(SDL_TRUE, &capture_devs); reprocess_device_list(SDL_TRUE, &capture_devs);
reprocess_device_list(SDL_FALSE, &output_devs); reprocess_device_list(SDL_FALSE, &output_devs);
@@ -285,7 +275,6 @@ device_list_changed(AudioObjectID systemObj, UInt32 num_addr, const AudioObjectP
} }
#endif #endif
static int open_playback_devices; static int open_playback_devices;
static int open_capture_devices; static int open_capture_devices;
static int num_open_devices; static int num_open_devices;
@@ -337,16 +326,14 @@ static void interruption_begin(_THIS)
static void interruption_end(_THIS) static void interruption_end(_THIS)
{ {
if (this != NULL && this->hidden != NULL && this->hidden->audioQueue != NULL if (this != NULL && this->hidden != NULL && this->hidden->audioQueue != NULL && this->hidden->interrupted && AudioQueueStart(this->hidden->audioQueue, NULL) == AVAudioSessionErrorCodeNone) {
&& this->hidden->interrupted
&& AudioQueueStart(this->hidden->audioQueue, NULL) == AVAudioSessionErrorCodeNone) {
this->hidden->interrupted = SDL_FALSE; this->hidden->interrupted = SDL_FALSE;
} }
} }
@interface SDLInterruptionListener : NSObject @interface SDLInterruptionListener : NSObject
@property (nonatomic, assign) SDL_AudioDevice *device; @property(nonatomic, assign) SDL_AudioDevice *device;
@end @end
@@ -354,7 +341,7 @@ static void interruption_end(_THIS)
- (void)audioSessionInterruption:(NSNotification *)note - (void)audioSessionInterruption:(NSNotification *)note
{ {
@synchronized (self) { @synchronized(self) {
NSNumber *type = note.userInfo[AVAudioSessionInterruptionTypeKey]; NSNumber *type = note.userInfo[AVAudioSessionInterruptionTypeKey];
if (type.unsignedIntegerValue == AVAudioSessionInterruptionTypeBegan) { if (type.unsignedIntegerValue == AVAudioSessionInterruptionTypeBegan) {
interruption_begin(self.device); interruption_begin(self.device);
@@ -366,7 +353,7 @@ static void interruption_end(_THIS)
- (void)applicationBecameActive:(NSNotification *)note - (void)applicationBecameActive:(NSNotification *)note
{ {
@synchronized (self) { @synchronized(self) {
interruption_end(self.device); interruption_end(self.device);
} }
} }
@@ -502,9 +489,9 @@ static BOOL update_audio_session(_THIS, SDL_bool open, SDL_bool allow_playandrec
this->hidden->interruption_listener = CFBridgingRetain(listener); this->hidden->interruption_listener = CFBridgingRetain(listener);
} else { } else {
SDLInterruptionListener *listener = nil; SDLInterruptionListener *listener = nil;
listener = (SDLInterruptionListener *) CFBridgingRelease(this->hidden->interruption_listener); listener = (SDLInterruptionListener *)CFBridgingRelease(this->hidden->interruption_listener);
[center removeObserver:listener]; [center removeObserver:listener];
@synchronized (listener) { @synchronized(listener) {
listener.device = NULL; listener.device = NULL;
} }
} }
@@ -514,12 +501,10 @@ static BOOL update_audio_session(_THIS, SDL_bool open, SDL_bool allow_playandrec
} }
#endif #endif
/* The AudioQueue callback */ /* The AudioQueue callback */
static void static void outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer)
outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer)
{ {
SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData; SDL_AudioDevice *this = (SDL_AudioDevice *)inUserData;
/* This flag is set before this->mixer_lock is destroyed during /* This flag is set before this->mixer_lock is destroyed during
shutdown, so check it before grabbing the mutex, and then check it shutdown, so check it before grabbing the mutex, and then check it
@@ -540,7 +525,7 @@ outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffe
SDL_memset(inBuffer->mAudioData, this->spec.silence, inBuffer->mAudioDataBytesCapacity); SDL_memset(inBuffer->mAudioData, this->spec.silence, inBuffer->mAudioDataBytesCapacity);
} else if (this->stream) { } else if (this->stream) {
UInt32 remaining = inBuffer->mAudioDataBytesCapacity; UInt32 remaining = inBuffer->mAudioDataBytesCapacity;
Uint8 *ptr = (Uint8 *) inBuffer->mAudioData; Uint8 *ptr = (Uint8 *)inBuffer->mAudioData;
while (remaining > 0) { while (remaining > 0) {
if (SDL_AudioStreamAvailable(this->stream) == 0) { if (SDL_AudioStreamAvailable(this->stream) == 0) {
@@ -566,7 +551,7 @@ outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffe
} }
} else { } else {
UInt32 remaining = inBuffer->mAudioDataBytesCapacity; UInt32 remaining = inBuffer->mAudioDataBytesCapacity;
Uint8 *ptr = (Uint8 *) inBuffer->mAudioData; Uint8 *ptr = (Uint8 *)inBuffer->mAudioData;
while (remaining > 0) { while (remaining > 0) {
UInt32 len; UInt32 len;
@@ -581,8 +566,7 @@ outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffe
if (len > remaining) { if (len > remaining) {
len = remaining; len = remaining;
} }
SDL_memcpy(ptr, (char *)this->hidden->buffer + SDL_memcpy(ptr, (char *)this->hidden->buffer + this->hidden->bufferOffset, len);
this->hidden->bufferOffset, len);
ptr = ptr + len; ptr = ptr + len;
remaining -= len; remaining -= len;
this->hidden->bufferOffset += len; this->hidden->bufferOffset += len;
@@ -596,12 +580,11 @@ outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffe
SDL_UnlockMutex(this->mixer_lock); SDL_UnlockMutex(this->mixer_lock);
} }
static void static void inputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer,
inputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer,
const AudioTimeStamp *inStartTime, UInt32 inNumberPacketDescriptions, const AudioTimeStamp *inStartTime, UInt32 inNumberPacketDescriptions,
const AudioStreamPacketDescription *inPacketDescs) const AudioStreamPacketDescription *inPacketDescs)
{ {
SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData; SDL_AudioDevice *this = (SDL_AudioDevice *)inUserData;
if (SDL_AtomicGet(&this->shutdown)) { if (SDL_AtomicGet(&this->shutdown)) {
return; /* don't do anything. */ return; /* don't do anything. */
@@ -609,7 +592,7 @@ inputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer
/* ignore unless we're active. */ /* ignore unless we're active. */
if (!SDL_AtomicGet(&this->paused) && SDL_AtomicGet(&this->enabled)) { if (!SDL_AtomicGet(&this->paused) && SDL_AtomicGet(&this->enabled)) {
const Uint8 *ptr = (const Uint8 *) inBuffer->mAudioData; const Uint8 *ptr = (const Uint8 *)inBuffer->mAudioData;
UInt32 remaining = inBuffer->mAudioDataByteSize; UInt32 remaining = inBuffer->mAudioDataByteSize;
while (remaining > 0) { while (remaining > 0) {
UInt32 len = this->hidden->bufferSize - this->hidden->bufferOffset; UInt32 len = this->hidden->bufferSize - this->hidden->bufferOffset;
@@ -634,22 +617,19 @@ inputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer
AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL); AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
} }
#if MACOSX_COREAUDIO #if MACOSX_COREAUDIO
static const AudioObjectPropertyAddress alive_address = static const AudioObjectPropertyAddress alive_address = {
{
kAudioDevicePropertyDeviceIsAlive, kAudioDevicePropertyDeviceIsAlive,
kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMain kAudioObjectPropertyElementMain
}; };
static OSStatus static OSStatus device_unplugged(AudioObjectID devid, UInt32 num_addr, const AudioObjectPropertyAddress *addrs, void *data)
device_unplugged(AudioObjectID devid, UInt32 num_addr, const AudioObjectPropertyAddress *addrs, void *data)
{ {
SDL_AudioDevice *this = (SDL_AudioDevice *) data; SDL_AudioDevice *this = (SDL_AudioDevice *)data;
SDL_bool dead = SDL_FALSE; SDL_bool dead = SDL_FALSE;
UInt32 isAlive = 1; UInt32 isAlive = 1;
UInt32 size = sizeof (isAlive); UInt32 size = sizeof(isAlive);
OSStatus error; OSStatus error;
if (!SDL_AtomicGet(&this->enabled)) { if (!SDL_AtomicGet(&this->enabled)) {
@@ -673,20 +653,18 @@ device_unplugged(AudioObjectID devid, UInt32 num_addr, const AudioObjectProperty
} }
/* macOS calls this when the default device changed (if we have a default device open). */ /* macOS calls this when the default device changed (if we have a default device open). */
static OSStatus static OSStatus default_device_changed(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses, void *inUserData)
default_device_changed(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses, void *inUserData)
{ {
SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData; SDL_AudioDevice *this = (SDL_AudioDevice *)inUserData;
#if DEBUG_COREAUDIO #if DEBUG_COREAUDIO
printf("COREAUDIO: default device changed for SDL audio device %p!\n", this); printf("COREAUDIO: default device changed for SDL audio device %p!\n", this);
#endif #endif
SDL_AtomicSet(&this->hidden->device_change_flag, 1); /* let the audioqueue thread pick up on this when safe to do so. */ SDL_AtomicSet(&this->hidden->device_change_flag, 1); /* let the audioqueue thread pick up on this when safe to do so. */
return noErr; return noErr;
} }
#endif #endif
static void static void COREAUDIO_CloseDevice(_THIS)
COREAUDIO_CloseDevice(_THIS)
{ {
const SDL_bool iscapture = this->iscapture; const SDL_bool iscapture = this->iscapture;
int i; int i;
@@ -726,7 +704,7 @@ COREAUDIO_CloseDevice(_THIS)
if (open_devices[i] == this) { if (open_devices[i] == this) {
--num_open_devices; --num_open_devices;
if (i < num_open_devices) { if (i < num_open_devices) {
SDL_memmove(&open_devices[i], &open_devices[i+1], sizeof(open_devices[i])*(num_open_devices - i)); SDL_memmove(&open_devices[i], &open_devices[i + 1], sizeof(open_devices[i]) * (num_open_devices - i));
} }
break; break;
} }
@@ -748,12 +726,11 @@ COREAUDIO_CloseDevice(_THIS)
} }
#if MACOSX_COREAUDIO #if MACOSX_COREAUDIO
static int static int prepare_device(_THIS)
prepare_device(_THIS)
{ {
void *handle = this->handle; void *handle = this->handle;
SDL_bool iscapture = this->iscapture; SDL_bool iscapture = this->iscapture;
AudioDeviceID devid = (AudioDeviceID) ((size_t) handle); AudioDeviceID devid = (AudioDeviceID)((size_t)handle);
OSStatus result = noErr; OSStatus result = noErr;
UInt32 size = 0; UInt32 size = 0;
UInt32 alive = 0; UInt32 alive = 0;
@@ -766,23 +743,20 @@ prepare_device(_THIS)
}; };
if (handle == NULL) { if (handle == NULL) {
size = sizeof (AudioDeviceID); size = sizeof(AudioDeviceID);
addr.mSelector = addr.mSelector =
((iscapture) ? kAudioHardwarePropertyDefaultInputDevice : ((iscapture) ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice);
kAudioHardwarePropertyDefaultOutputDevice);
result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr,
0, NULL, &size, &devid); 0, NULL, &size, &devid);
CHECK_RESULT("AudioHardwareGetProperty (default device)"); CHECK_RESULT("AudioHardwareGetProperty (default device)");
} }
addr.mSelector = kAudioDevicePropertyDeviceIsAlive; addr.mSelector = kAudioDevicePropertyDeviceIsAlive;
addr.mScope = iscapture ? kAudioDevicePropertyScopeInput : addr.mScope = iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
kAudioDevicePropertyScopeOutput;
size = sizeof (alive); size = sizeof(alive);
result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &alive); result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &alive);
CHECK_RESULT CHECK_RESULT("AudioDeviceGetProperty (kAudioDevicePropertyDeviceIsAlive)");
("AudioDeviceGetProperty (kAudioDevicePropertyDeviceIsAlive)");
if (!alive) { if (!alive) {
SDL_SetError("CoreAudio: requested device exists, but isn't alive."); SDL_SetError("CoreAudio: requested device exists, but isn't alive.");
@@ -790,7 +764,7 @@ prepare_device(_THIS)
} }
addr.mSelector = kAudioDevicePropertyHogMode; addr.mSelector = kAudioDevicePropertyHogMode;
size = sizeof (pid); size = sizeof(pid);
result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &pid); result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &pid);
/* some devices don't support this property, so errors are fine here. */ /* some devices don't support this property, so errors are fine here. */
@@ -803,8 +777,7 @@ prepare_device(_THIS)
return 1; return 1;
} }
static int static int assign_device_to_audioqueue(_THIS)
assign_device_to_audioqueue(_THIS)
{ {
const AudioObjectPropertyAddress prop = { const AudioObjectPropertyAddress prop = {
kAudioDevicePropertyDeviceUID, kAudioDevicePropertyDeviceUID,
@@ -814,7 +787,7 @@ assign_device_to_audioqueue(_THIS)
OSStatus result; OSStatus result;
CFStringRef devuid; CFStringRef devuid;
UInt32 devuidsize = sizeof (devuid); UInt32 devuidsize = sizeof(devuid);
result = AudioObjectGetPropertyData(this->hidden->deviceID, &prop, 0, NULL, &devuidsize, &devuid); result = AudioObjectGetPropertyData(this->hidden->deviceID, &prop, 0, NULL, &devuidsize, &devuid);
CHECK_RESULT("AudioObjectGetPropertyData (kAudioDevicePropertyDeviceUID)"); CHECK_RESULT("AudioObjectGetPropertyData (kAudioDevicePropertyDeviceUID)");
result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_CurrentDevice, &devuid, devuidsize); result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_CurrentDevice, &devuid, devuidsize);
@@ -824,8 +797,7 @@ assign_device_to_audioqueue(_THIS)
} }
#endif #endif
static int static int prepare_audioqueue(_THIS)
prepare_audioqueue(_THIS)
{ {
const AudioStreamBasicDescription *strdesc = &this->hidden->strdesc; const AudioStreamBasicDescription *strdesc = &this->hidden->strdesc;
const int iscapture = this->iscapture; const int iscapture = this->iscapture;
@@ -833,7 +805,8 @@ prepare_audioqueue(_THIS)
int i, numAudioBuffers = 2; int i, numAudioBuffers = 2;
AudioChannelLayout layout; AudioChannelLayout layout;
double MINIMUM_AUDIO_BUFFER_TIME_MS; double MINIMUM_AUDIO_BUFFER_TIME_MS;
const double msecs = (this->spec.samples / ((double) this->spec.freq)) * 1000.0;; const double msecs = (this->spec.samples / ((double)this->spec.freq)) * 1000.0;
;
SDL_assert(CFRunLoopGetCurrent() != NULL); SDL_assert(CFRunLoopGetCurrent() != NULL);
@@ -845,7 +818,7 @@ prepare_audioqueue(_THIS)
CHECK_RESULT("AudioQueueNewOutput"); CHECK_RESULT("AudioQueueNewOutput");
} }
#if MACOSX_COREAUDIO #if MACOSX_COREAUDIO
if (!assign_device_to_audioqueue(this)) { if (!assign_device_to_audioqueue(this)) {
return 0; return 0;
} }
@@ -859,7 +832,7 @@ prepare_audioqueue(_THIS)
/* If this fails, oh well, we won't notice a device had an extraordinary event take place. */ /* If this fails, oh well, we won't notice a device had an extraordinary event take place. */
AudioObjectAddPropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this); AudioObjectAddPropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this);
} }
#endif #endif
/* Calculate the final parameters for this audio specification */ /* Calculate the final parameters for this audio specification */
SDL_CalculateAudioSpec(&this->spec); SDL_CalculateAudioSpec(&this->spec);
@@ -921,7 +894,7 @@ prepare_audioqueue(_THIS)
} }
this->hidden->numAudioBuffers = numAudioBuffers; this->hidden->numAudioBuffers = numAudioBuffers;
this->hidden->audioBuffer = SDL_calloc(1, sizeof (AudioQueueBufferRef) * numAudioBuffers); this->hidden->audioBuffer = SDL_calloc(1, sizeof(AudioQueueBufferRef) * numAudioBuffers);
if (this->hidden->audioBuffer == NULL) { if (this->hidden->audioBuffer == NULL) {
SDL_OutOfMemory(); SDL_OutOfMemory();
return 0; return 0;
@@ -948,13 +921,12 @@ prepare_audioqueue(_THIS)
return 1; return 1;
} }
static int static int audioqueue_thread(void *arg)
audioqueue_thread(void *arg)
{ {
SDL_AudioDevice *this = (SDL_AudioDevice *) arg; SDL_AudioDevice *this = (SDL_AudioDevice *)arg;
int rc; int rc;
#if MACOSX_COREAUDIO #if MACOSX_COREAUDIO
const AudioObjectPropertyAddress default_device_address = { const AudioObjectPropertyAddress default_device_address = {
this->iscapture ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice, this->iscapture ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeGlobal,
@@ -965,7 +937,7 @@ audioqueue_thread(void *arg)
/* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */ /* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */
AudioObjectAddPropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this); AudioObjectAddPropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this);
} }
#endif #endif
rc = prepare_audioqueue(this); rc = prepare_audioqueue(this);
if (!rc) { if (!rc) {
@@ -982,14 +954,14 @@ audioqueue_thread(void *arg)
while (!SDL_AtomicGet(&this->shutdown)) { while (!SDL_AtomicGet(&this->shutdown)) {
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1); CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1);
#if MACOSX_COREAUDIO #if MACOSX_COREAUDIO
if ((this->handle == NULL) && SDL_AtomicGet(&this->hidden->device_change_flag)) { if ((this->handle == NULL) && SDL_AtomicGet(&this->hidden->device_change_flag)) {
const AudioDeviceID prev_devid = this->hidden->deviceID; const AudioDeviceID prev_devid = this->hidden->deviceID;
SDL_AtomicSet(&this->hidden->device_change_flag, 0); SDL_AtomicSet(&this->hidden->device_change_flag, 0);
#if DEBUG_COREAUDIO #if DEBUG_COREAUDIO
printf("COREAUDIO: audioqueue_thread is trying to switch to new default device!\n"); printf("COREAUDIO: audioqueue_thread is trying to switch to new default device!\n");
#endif #endif
/* if any of this fails, there's not much to do but wait to see if the user gives up /* if any of this fails, there's not much to do but wait to see if the user gives up
and quits (flagging the audioqueue for shutdown), or toggles to some other system and quits (flagging the audioqueue for shutdown), or toggles to some other system
@@ -1007,26 +979,25 @@ audioqueue_thread(void *arg)
} }
} }
} }
#endif #endif
} }
if (!this->iscapture) { /* Drain off any pending playback. */ if (!this->iscapture) { /* Drain off any pending playback. */
const CFTimeInterval secs = (((this->spec.size / (SDL_AUDIO_BITSIZE(this->spec.format) / 8)) / this->spec.channels) / ((CFTimeInterval) this->spec.freq)) * 2.0; const CFTimeInterval secs = (((this->spec.size / (SDL_AUDIO_BITSIZE(this->spec.format) / 8)) / this->spec.channels) / ((CFTimeInterval)this->spec.freq)) * 2.0;
CFRunLoopRunInMode(kCFRunLoopDefaultMode, secs, 0); CFRunLoopRunInMode(kCFRunLoopDefaultMode, secs, 0);
} }
#if MACOSX_COREAUDIO #if MACOSX_COREAUDIO
if (this->handle == NULL) { if (this->handle == NULL) {
/* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */ /* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */
AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this); AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this);
} }
#endif #endif
return 0; return 0;
} }
static int static int COREAUDIO_OpenDevice(_THIS, const char *devname)
COREAUDIO_OpenDevice(_THIS, const char *devname)
{ {
AudioStreamBasicDescription *strdesc; AudioStreamBasicDescription *strdesc;
SDL_AudioFormat test_format; SDL_AudioFormat test_format;
@@ -1062,7 +1033,7 @@ COREAUDIO_OpenDevice(_THIS, const char *devname)
/* Stop CoreAudio from doing expensive audio rate conversion */ /* Stop CoreAudio from doing expensive audio rate conversion */
@autoreleasepool { @autoreleasepool {
AVAudioSession* session = [AVAudioSession sharedInstance]; AVAudioSession *session = [AVAudioSession sharedInstance];
[session setPreferredSampleRate:this->spec.freq error:nil]; [session setPreferredSampleRate:this->spec.freq error:nil];
this->spec.freq = (int)session.sampleRate; this->spec.freq = (int)session.sampleRate;
#if TARGET_OS_TV #if TARGET_OS_TV
@@ -1151,10 +1122,9 @@ COREAUDIO_OpenDevice(_THIS, const char *devname)
} }
#if !MACOSX_COREAUDIO #if !MACOSX_COREAUDIO
static int static int COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
{ {
AVAudioSession* session = [AVAudioSession sharedInstance]; AVAudioSession *session = [AVAudioSession sharedInstance];
if (name != NULL) { if (name != NULL) {
*name = NULL; *name = NULL;
@@ -1165,8 +1135,7 @@ COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
return 0; return 0;
} }
#else /* MACOSX_COREAUDIO */ #else /* MACOSX_COREAUDIO */
static int static int COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
{ {
AudioDeviceID devid; AudioDeviceID devid;
AudioBufferList *buflist; AudioBufferList *buflist;
@@ -1205,7 +1174,7 @@ COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
/* Get the Device ID */ /* Get the Device ID */
cfstr = NULL; cfstr = NULL;
size = sizeof (AudioDeviceID); size = sizeof(AudioDeviceID);
result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr,
0, NULL, &size, &devid); 0, NULL, &size, &devid);
@@ -1215,7 +1184,7 @@ COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
if (name != NULL) { if (name != NULL) {
/* Use the Device ID to get the name */ /* Use the Device ID to get the name */
size = sizeof (CFStringRef); size = sizeof(CFStringRef);
result = AudioObjectGetPropertyData(devid, &nameaddr, 0, NULL, &size, &cfstr); result = AudioObjectGetPropertyData(devid, &nameaddr, 0, NULL, &size, &cfstr);
if (result != noErr) { if (result != noErr) {
@@ -1224,7 +1193,7 @@ COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr), len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr),
kCFStringEncodingUTF8); kCFStringEncodingUTF8);
devname = (char *) SDL_malloc(len + 1); devname = (char *)SDL_malloc(len + 1);
usable = ((devname != NULL) && usable = ((devname != NULL) &&
(CFStringGetCString(cfstr, devname, len + 1, kCFStringEncodingUTF8))); (CFStringGetCString(cfstr, devname, len + 1, kCFStringEncodingUTF8)));
CFRelease(cfstr); CFRelease(cfstr);
@@ -1256,13 +1225,13 @@ COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
return SDL_SetError("%s: Default Device Sample Rate not found", "coreaudio"); return SDL_SetError("%s: Default Device Sample Rate not found", "coreaudio");
} }
spec->freq = (int) sampleRate; spec->freq = (int)sampleRate;
result = AudioObjectGetPropertyDataSize(devid, &bufaddr, 0, NULL, &size); result = AudioObjectGetPropertyDataSize(devid, &bufaddr, 0, NULL, &size);
if (result != noErr) if (result != noErr)
return SDL_SetError("%s: Default Device Data Size not found", "coreaudio"); return SDL_SetError("%s: Default Device Data Size not found", "coreaudio");
buflist = (AudioBufferList *) SDL_malloc(size); buflist = (AudioBufferList *)SDL_malloc(size);
if (buflist == NULL) if (buflist == NULL)
return SDL_SetError("%s: Default Device Buffer List not found", "coreaudio"); return SDL_SetError("%s: Default Device Buffer List not found", "coreaudio");
@@ -1286,8 +1255,7 @@ COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
} }
#endif /* MACOSX_COREAUDIO */ #endif /* MACOSX_COREAUDIO */
static void static void COREAUDIO_Deinitialize(void)
COREAUDIO_Deinitialize(void)
{ {
#if MACOSX_COREAUDIO #if MACOSX_COREAUDIO
AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &devlist_address, device_list_changed, NULL); AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &devlist_address, device_list_changed, NULL);
@@ -1296,8 +1264,7 @@ COREAUDIO_Deinitialize(void)
#endif #endif
} }
static SDL_bool static SDL_bool COREAUDIO_Init(SDL_AudioDriverImpl *impl)
COREAUDIO_Init(SDL_AudioDriverImpl * impl)
{ {
/* Set the function pointers */ /* Set the function pointers */
impl->OpenDevice = COREAUDIO_OpenDevice; impl->OpenDevice = COREAUDIO_OpenDevice;

View File

@@ -41,21 +41,20 @@ static SDL_bool SupportsIMMDevice = SDL_FALSE;
#endif /* HAVE_MMDEVICEAPI_H */ #endif /* HAVE_MMDEVICEAPI_H */
/* DirectX function pointers for audio */ /* DirectX function pointers for audio */
static void* DSoundDLL = NULL; static void *DSoundDLL = NULL;
typedef HRESULT (WINAPI *fnDirectSoundCreate8)(LPGUID,LPDIRECTSOUND*,LPUNKNOWN); typedef HRESULT(WINAPI *fnDirectSoundCreate8)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
typedef HRESULT (WINAPI *fnDirectSoundEnumerateW)(LPDSENUMCALLBACKW, LPVOID); typedef HRESULT(WINAPI *fnDirectSoundEnumerateW)(LPDSENUMCALLBACKW, LPVOID);
typedef HRESULT (WINAPI *fnDirectSoundCaptureCreate8)(LPCGUID,LPDIRECTSOUNDCAPTURE8 *,LPUNKNOWN); typedef HRESULT(WINAPI *fnDirectSoundCaptureCreate8)(LPCGUID, LPDIRECTSOUNDCAPTURE8 *, LPUNKNOWN);
typedef HRESULT (WINAPI *fnDirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW,LPVOID); typedef HRESULT(WINAPI *fnDirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW, LPVOID);
static fnDirectSoundCreate8 pDirectSoundCreate8 = NULL; static fnDirectSoundCreate8 pDirectSoundCreate8 = NULL;
static fnDirectSoundEnumerateW pDirectSoundEnumerateW = NULL; static fnDirectSoundEnumerateW pDirectSoundEnumerateW = NULL;
static fnDirectSoundCaptureCreate8 pDirectSoundCaptureCreate8 = NULL; static fnDirectSoundCaptureCreate8 pDirectSoundCaptureCreate8 = NULL;
static fnDirectSoundCaptureEnumerateW pDirectSoundCaptureEnumerateW = NULL; static fnDirectSoundCaptureEnumerateW pDirectSoundCaptureEnumerateW = NULL;
static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
static void static void DSOUND_Unload(void)
DSOUND_Unload(void)
{ {
pDirectSoundCreate8 = NULL; pDirectSoundCreate8 = NULL;
pDirectSoundEnumerateW = NULL; pDirectSoundEnumerateW = NULL;
@@ -68,9 +67,7 @@ DSOUND_Unload(void)
} }
} }
static int DSOUND_Load(void)
static int
DSOUND_Load(void)
{ {
int loaded = 0; int loaded = 0;
@@ -80,17 +77,19 @@ DSOUND_Load(void)
if (DSoundDLL == NULL) { if (DSoundDLL == NULL) {
SDL_SetError("DirectSound: failed to load DSOUND.DLL"); SDL_SetError("DirectSound: failed to load DSOUND.DLL");
} else { } else {
/* Now make sure we have DirectX 8 or better... */ /* Now make sure we have DirectX 8 or better... */
#define DSOUNDLOAD(f) { \ #define DSOUNDLOAD(f) \
p##f = (fn##f) SDL_LoadFunction(DSoundDLL, #f); \ { \
if (!p##f) loaded = 0; \ p##f = (fn##f)SDL_LoadFunction(DSoundDLL, #f); \
if (!p##f) \
loaded = 0; \
} }
loaded = 1; /* will reset if necessary. */ loaded = 1; /* will reset if necessary. */
DSOUNDLOAD(DirectSoundCreate8); DSOUNDLOAD(DirectSoundCreate8);
DSOUNDLOAD(DirectSoundEnumerateW); DSOUNDLOAD(DirectSoundEnumerateW);
DSOUNDLOAD(DirectSoundCaptureCreate8); DSOUNDLOAD(DirectSoundCaptureCreate8);
DSOUNDLOAD(DirectSoundCaptureEnumerateW); DSOUNDLOAD(DirectSoundCaptureEnumerateW);
#undef DSOUNDLOAD #undef DSOUNDLOAD
if (!loaded) { if (!loaded) {
SDL_SetError("DirectSound: System doesn't appear to have DX8."); SDL_SetError("DirectSound: System doesn't appear to have DX8.");
@@ -104,8 +103,7 @@ DSOUND_Load(void)
return loaded; return loaded;
} }
static int static int SetDSerror(const char *function, int code)
SetDSerror(const char *function, int code)
{ {
const char *error; const char *error;
@@ -151,14 +149,12 @@ SetDSerror(const char *function, int code)
return SDL_SetError("%s: %s (0x%x)", function, error, code); return SDL_SetError("%s: %s (0x%x)", function, error, code);
} }
static void static void DSOUND_FreeDeviceHandle(void *handle)
DSOUND_FreeDeviceHandle(void *handle)
{ {
SDL_free(handle); SDL_free(handle);
} }
static int static int DSOUND_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
DSOUND_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
{ {
#if HAVE_MMDEVICEAPI_H #if HAVE_MMDEVICEAPI_H
if (SupportsIMMDevice) { if (SupportsIMMDevice) {
@@ -168,15 +164,14 @@ DSOUND_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
return SDL_Unsupported(); return SDL_Unsupported();
} }
static BOOL CALLBACK static BOOL CALLBACK FindAllDevs(LPGUID guid, LPCWSTR desc, LPCWSTR module, LPVOID data)
FindAllDevs(LPGUID guid, LPCWSTR desc, LPCWSTR module, LPVOID data)
{ {
const int iscapture = (int) ((size_t) data); const int iscapture = (int)((size_t)data);
if (guid != NULL) { /* skip default device */ if (guid != NULL) { /* skip default device */
char *str = WIN_LookupAudioDeviceName(desc, guid); char *str = WIN_LookupAudioDeviceName(desc, guid);
if (str != NULL) { if (str != NULL) {
LPGUID cpyguid = (LPGUID) SDL_malloc(sizeof (GUID)); LPGUID cpyguid = (LPGUID)SDL_malloc(sizeof(GUID));
SDL_memcpy(cpyguid, guid, sizeof (GUID)); SDL_memcpy(cpyguid, guid, sizeof(GUID));
/* Note that spec is NULL, because we are required to connect to the /* Note that spec is NULL, because we are required to connect to the
* device before getting the channel mask and output format, making * device before getting the channel mask and output format, making
@@ -189,8 +184,7 @@ FindAllDevs(LPGUID guid, LPCWSTR desc, LPCWSTR module, LPVOID data)
return TRUE; /* keep enumerating. */ return TRUE; /* keep enumerating. */
} }
static void static void DSOUND_DetectDevices(void)
DSOUND_DetectDevices(void)
{ {
#if HAVE_MMDEVICEAPI_H #if HAVE_MMDEVICEAPI_H
if (SupportsIMMDevice) { if (SupportsIMMDevice) {
@@ -204,9 +198,7 @@ DSOUND_DetectDevices(void)
#endif /* HAVE_MMDEVICEAPI_H*/ #endif /* HAVE_MMDEVICEAPI_H*/
} }
static void DSOUND_WaitDevice(_THIS)
static void
DSOUND_WaitDevice(_THIS)
{ {
DWORD status = 0; DWORD status = 0;
DWORD cursor = 0; DWORD cursor = 0;
@@ -263,8 +255,7 @@ DSOUND_WaitDevice(_THIS)
} }
} }
static void static void DSOUND_PlayDevice(_THIS)
DSOUND_PlayDevice(_THIS)
{ {
/* Unlock the buffer, allowing it to play */ /* Unlock the buffer, allowing it to play */
if (this->hidden->locked_buf) { if (this->hidden->locked_buf) {
@@ -274,8 +265,7 @@ DSOUND_PlayDevice(_THIS)
} }
} }
static Uint8 * static Uint8 *DSOUND_GetDeviceBuf(_THIS)
DSOUND_GetDeviceBuf(_THIS)
{ {
DWORD cursor = 0; DWORD cursor = 0;
DWORD junk = 0; DWORD junk = 0;
@@ -316,14 +306,13 @@ DSOUND_GetDeviceBuf(_THIS)
/* Lock the audio buffer */ /* Lock the audio buffer */
result = IDirectSoundBuffer_Lock(this->hidden->mixbuf, cursor, result = IDirectSoundBuffer_Lock(this->hidden->mixbuf, cursor,
this->spec.size, this->spec.size,
(LPVOID *) & this->hidden->locked_buf, (LPVOID *)&this->hidden->locked_buf,
&rawlen, NULL, &junk, 0); &rawlen, NULL, &junk, 0);
if (result == DSERR_BUFFERLOST) { if (result == DSERR_BUFFERLOST) {
IDirectSoundBuffer_Restore(this->hidden->mixbuf); IDirectSoundBuffer_Restore(this->hidden->mixbuf);
result = IDirectSoundBuffer_Lock(this->hidden->mixbuf, cursor, result = IDirectSoundBuffer_Lock(this->hidden->mixbuf, cursor,
this->spec.size, this->spec.size,
(LPVOID *) & this-> (LPVOID *)&this->hidden->locked_buf, &rawlen, NULL,
hidden->locked_buf, &rawlen, NULL,
&junk, 0); &junk, 0);
} }
if (result != DS_OK) { if (result != DS_OK) {
@@ -333,8 +322,7 @@ DSOUND_GetDeviceBuf(_THIS)
return this->hidden->locked_buf; return this->hidden->locked_buf;
} }
static int static int DSOUND_CaptureFromDevice(_THIS, void *buffer, int buflen)
DSOUND_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
struct SDL_PrivateAudioData *h = this->hidden; struct SDL_PrivateAudioData *h = this->hidden;
DWORD junk, cursor, ptr1len, ptr2len; DWORD junk, cursor, ptr1len, ptr2len;
@@ -377,8 +365,7 @@ DSOUND_CaptureFromDevice(_THIS, void *buffer, int buflen)
return ptr1len; return ptr1len;
} }
static void static void DSOUND_FlushCapture(_THIS)
DSOUND_FlushCapture(_THIS)
{ {
struct SDL_PrivateAudioData *h = this->hidden; struct SDL_PrivateAudioData *h = this->hidden;
DWORD junk, cursor; DWORD junk, cursor;
@@ -387,8 +374,7 @@ DSOUND_FlushCapture(_THIS)
} }
} }
static void static void DSOUND_CloseDevice(_THIS)
DSOUND_CloseDevice(_THIS)
{ {
if (this->hidden->mixbuf != NULL) { if (this->hidden->mixbuf != NULL) {
IDirectSoundBuffer_Stop(this->hidden->mixbuf); IDirectSoundBuffer_Stop(this->hidden->mixbuf);
@@ -411,8 +397,7 @@ DSOUND_CloseDevice(_THIS)
number of audio chunks available in the created buffer. This is for number of audio chunks available in the created buffer. This is for
playback devices, not capture. playback devices, not capture.
*/ */
static int static int CreateSecondary(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt)
CreateSecondary(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt)
{ {
LPDIRECTSOUND sndObj = this->hidden->sound; LPDIRECTSOUND sndObj = this->hidden->sound;
LPDIRECTSOUNDBUFFER *sndbuf = &this->hidden->mixbuf; LPDIRECTSOUNDBUFFER *sndbuf = &this->hidden->mixbuf;
@@ -436,14 +421,14 @@ CreateSecondary(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt)
/* Silence the initial audio buffer */ /* Silence the initial audio buffer */
result = IDirectSoundBuffer_Lock(*sndbuf, 0, format.dwBufferBytes, result = IDirectSoundBuffer_Lock(*sndbuf, 0, format.dwBufferBytes,
(LPVOID *) & pvAudioPtr1, &dwAudioBytes1, (LPVOID *)&pvAudioPtr1, &dwAudioBytes1,
(LPVOID *) & pvAudioPtr2, &dwAudioBytes2, (LPVOID *)&pvAudioPtr2, &dwAudioBytes2,
DSBLOCK_ENTIREBUFFER); DSBLOCK_ENTIREBUFFER);
if (result == DS_OK) { if (result == DS_OK) {
SDL_memset(pvAudioPtr1, this->spec.silence, dwAudioBytes1); SDL_memset(pvAudioPtr1, this->spec.silence, dwAudioBytes1);
IDirectSoundBuffer_Unlock(*sndbuf, IDirectSoundBuffer_Unlock(*sndbuf,
(LPVOID) pvAudioPtr1, dwAudioBytes1, (LPVOID)pvAudioPtr1, dwAudioBytes1,
(LPVOID) pvAudioPtr2, dwAudioBytes2); (LPVOID)pvAudioPtr2, dwAudioBytes2);
} }
/* We're ready to go */ /* We're ready to go */
@@ -454,8 +439,7 @@ CreateSecondary(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt)
number of audio chunks available in the created buffer. This is for number of audio chunks available in the created buffer. This is for
capture devices, not playback. capture devices, not playback.
*/ */
static int static int CreateCaptureBuffer(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt)
CreateCaptureBuffer(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt)
{ {
LPDIRECTSOUNDCAPTURE capture = this->hidden->capture; LPDIRECTSOUNDCAPTURE capture = this->hidden->capture;
LPDIRECTSOUNDCAPTUREBUFFER *capturebuf = &this->hidden->capturebuf; LPDIRECTSOUNDCAPTUREBUFFER *capturebuf = &this->hidden->capturebuf;
@@ -463,7 +447,7 @@ CreateCaptureBuffer(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt)
HRESULT result; HRESULT result;
SDL_zero(format); SDL_zero(format);
format.dwSize = sizeof (format); format.dwSize = sizeof(format);
format.dwFlags = DSCBCAPS_WAVEMAPPED; format.dwFlags = DSCBCAPS_WAVEMAPPED;
format.dwBufferBytes = bufsize; format.dwBufferBytes = bufsize;
format.lpwfxFormat = wfmt; format.lpwfxFormat = wfmt;
@@ -494,15 +478,14 @@ CreateCaptureBuffer(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt)
return 0; return 0;
} }
static int static int DSOUND_OpenDevice(_THIS, const char *devname)
DSOUND_OpenDevice(_THIS, const char *devname)
{ {
const DWORD numchunks = 8; const DWORD numchunks = 8;
HRESULT result; HRESULT result;
SDL_bool tried_format = SDL_FALSE; SDL_bool tried_format = SDL_FALSE;
SDL_bool iscapture = this->iscapture; SDL_bool iscapture = this->iscapture;
SDL_AudioFormat test_format; SDL_AudioFormat test_format;
LPGUID guid = (LPGUID) this->handle; LPGUID guid = (LPGUID)this->handle;
DWORD bufsize; DWORD bufsize;
/* Initialize all variables that we clean on shutdown */ /* Initialize all variables that we clean on shutdown */
@@ -548,8 +531,8 @@ DSOUND_OpenDevice(_THIS, const char *devname)
bufsize = numchunks * this->spec.size; bufsize = numchunks * this->spec.size;
if ((bufsize < DSBSIZE_MIN) || (bufsize > DSBSIZE_MAX)) { if ((bufsize < DSBSIZE_MIN) || (bufsize > DSBSIZE_MAX)) {
SDL_SetError("Sound buffer size must be between %d and %d", SDL_SetError("Sound buffer size must be between %d and %d",
(int) ((DSBSIZE_MIN < numchunks) ? 1 : DSBSIZE_MIN / numchunks), (int)((DSBSIZE_MIN < numchunks) ? 1 : DSBSIZE_MIN / numchunks),
(int) (DSBSIZE_MAX / numchunks)); (int)(DSBSIZE_MAX / numchunks));
} else { } else {
int rc; int rc;
WAVEFORMATEXTENSIBLE wfmt; WAVEFORMATEXTENSIBLE wfmt;
@@ -565,8 +548,7 @@ DSOUND_OpenDevice(_THIS, const char *devname)
} }
wfmt.Samples.wValidBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format); wfmt.Samples.wValidBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format);
switch (this->spec.channels) switch (this->spec.channels) {
{
case 3: /* 3.0 (or 2.1) */ case 3: /* 3.0 (or 2.1) */
wfmt.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER; wfmt.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER;
break; break;
@@ -601,7 +583,7 @@ DSOUND_OpenDevice(_THIS, const char *devname)
wfmt.Format.nBlockAlign = wfmt.Format.nChannels * (wfmt.Format.wBitsPerSample / 8); wfmt.Format.nBlockAlign = wfmt.Format.nChannels * (wfmt.Format.wBitsPerSample / 8);
wfmt.Format.nAvgBytesPerSec = wfmt.Format.nSamplesPerSec * wfmt.Format.nBlockAlign; wfmt.Format.nAvgBytesPerSec = wfmt.Format.nSamplesPerSec * wfmt.Format.nBlockAlign;
rc = iscapture ? CreateCaptureBuffer(this, bufsize, (WAVEFORMATEX*) &wfmt) : CreateSecondary(this, bufsize, (WAVEFORMATEX*) &wfmt); rc = iscapture ? CreateCaptureBuffer(this, bufsize, (WAVEFORMATEX *)&wfmt) : CreateSecondary(this, bufsize, (WAVEFORMATEX *)&wfmt);
if (rc == 0) { if (rc == 0) {
this->hidden->num_buffers = numchunks; this->hidden->num_buffers = numchunks;
break; break;
@@ -626,9 +608,7 @@ DSOUND_OpenDevice(_THIS, const char *devname)
return 0; /* good to go. */ return 0; /* good to go. */
} }
static void DSOUND_Deinitialize(void)
static void
DSOUND_Deinitialize(void)
{ {
#if HAVE_MMDEVICEAPI_H #if HAVE_MMDEVICEAPI_H
if (SupportsIMMDevice) { if (SupportsIMMDevice) {
@@ -639,9 +619,7 @@ DSOUND_Deinitialize(void)
DSOUND_Unload(); DSOUND_Unload();
} }
static SDL_bool DSOUND_Init(SDL_AudioDriverImpl *impl)
static SDL_bool
DSOUND_Init(SDL_AudioDriverImpl * impl)
{ {
if (!DSOUND_Load()) { if (!DSOUND_Load()) {
return SDL_FALSE; return SDL_FALSE;

View File

@@ -40,14 +40,12 @@
#define DISKENVR_IODELAY "SDL_DISKAUDIODELAY" #define DISKENVR_IODELAY "SDL_DISKAUDIODELAY"
/* This function waits until it is possible to write a full sound buffer */ /* This function waits until it is possible to write a full sound buffer */
static void static void DISKAUDIO_WaitDevice(_THIS)
DISKAUDIO_WaitDevice(_THIS)
{ {
SDL_Delay(_this->hidden->io_delay); SDL_Delay(_this->hidden->io_delay);
} }
static void static void DISKAUDIO_PlayDevice(_THIS)
DISKAUDIO_PlayDevice(_THIS)
{ {
const size_t written = SDL_RWwrite(_this->hidden->io, const size_t written = SDL_RWwrite(_this->hidden->io,
_this->hidden->mixbuf, _this->hidden->mixbuf,
@@ -62,14 +60,12 @@ DISKAUDIO_PlayDevice(_THIS)
#endif #endif
} }
static Uint8 * static Uint8 *DISKAUDIO_GetDeviceBuf(_THIS)
DISKAUDIO_GetDeviceBuf(_THIS)
{ {
return _this->hidden->mixbuf; return _this->hidden->mixbuf;
} }
static int static int DISKAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
DISKAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
struct SDL_PrivateAudioData *h = _this->hidden; struct SDL_PrivateAudioData *h = _this->hidden;
const int origbuflen = buflen; const int origbuflen = buflen;
@@ -78,8 +74,8 @@ DISKAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
if (h->io) { if (h->io) {
const size_t br = SDL_RWread(h->io, buffer, 1, buflen); const size_t br = SDL_RWread(h->io, buffer, 1, buflen);
buflen -= (int) br; buflen -= (int)br;
buffer = ((Uint8 *) buffer) + br; buffer = ((Uint8 *)buffer) + br;
if (buflen > 0) { /* EOF (or error, but whatever). */ if (buflen > 0) { /* EOF (or error, but whatever). */
SDL_RWclose(h->io); SDL_RWclose(h->io);
h->io = NULL; h->io = NULL;
@@ -92,15 +88,12 @@ DISKAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
return origbuflen; return origbuflen;
} }
static void static void DISKAUDIO_FlushCapture(_THIS)
DISKAUDIO_FlushCapture(_THIS)
{ {
/* no op...we don't advance the file pointer or anything. */ /* no op...we don't advance the file pointer or anything. */
} }
static void DISKAUDIO_CloseDevice(_THIS)
static void
DISKAUDIO_CloseDevice(_THIS)
{ {
if (_this->hidden->io != NULL) { if (_this->hidden->io != NULL) {
SDL_RWclose(_this->hidden->io); SDL_RWclose(_this->hidden->io);
@@ -109,9 +102,7 @@ DISKAUDIO_CloseDevice(_THIS)
SDL_free(_this->hidden); SDL_free(_this->hidden);
} }
static const char *get_filename(const SDL_bool iscapture, const char *devname)
static const char *
get_filename(const SDL_bool iscapture, const char *devname)
{ {
if (devname == NULL) { if (devname == NULL) {
devname = SDL_getenv(iscapture ? DISKENVR_INFILE : DISKENVR_OUTFILE); devname = SDL_getenv(iscapture ? DISKENVR_INFILE : DISKENVR_OUTFILE);
@@ -122,8 +113,7 @@ get_filename(const SDL_bool iscapture, const char *devname)
return devname; return devname;
} }
static int static int DISKAUDIO_OpenDevice(_THIS, const char *devname)
DISKAUDIO_OpenDevice(_THIS, const char *devname)
{ {
void *handle = _this->handle; void *handle = _this->handle;
/* handle != NULL means "user specified the placeholder name on the fake detected device list" */ /* handle != NULL means "user specified the placeholder name on the fake detected device list" */
@@ -152,7 +142,7 @@ DISKAUDIO_OpenDevice(_THIS, const char *devname)
/* Allocate mixing buffer */ /* Allocate mixing buffer */
if (!iscapture) { if (!iscapture) {
_this->hidden->mixbuf = (Uint8 *) SDL_malloc(_this->spec.size); _this->hidden->mixbuf = (Uint8 *)SDL_malloc(_this->spec.size);
if (_this->hidden->mixbuf == NULL) { if (_this->hidden->mixbuf == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -169,15 +159,13 @@ DISKAUDIO_OpenDevice(_THIS, const char *devname)
return 0; return 0;
} }
static void static void DISKAUDIO_DetectDevices(void)
DISKAUDIO_DetectDevices(void)
{ {
SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, NULL, (void *) 0x1); SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, NULL, (void *)0x1);
SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, NULL, (void *) 0x2); SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, NULL, (void *)0x2);
} }
static SDL_bool static SDL_bool DISKAUDIO_Init(SDL_AudioDriverImpl *impl)
DISKAUDIO_Init(SDL_AudioDriverImpl * impl)
{ {
/* Set the function pointers */ /* Set the function pointers */
impl->OpenDevice = DISKAUDIO_OpenDevice; impl->OpenDevice = DISKAUDIO_OpenDevice;

View File

@@ -40,16 +40,12 @@
#include "../SDL_audiodev_c.h" #include "../SDL_audiodev_c.h"
#include "SDL_dspaudio.h" #include "SDL_dspaudio.h"
static void DSP_DetectDevices(void)
static void
DSP_DetectDevices(void)
{ {
SDL_EnumUnixAudioDevices(0, NULL); SDL_EnumUnixAudioDevices(0, NULL);
} }
static void DSP_CloseDevice(_THIS)
static void
DSP_CloseDevice(_THIS)
{ {
if (this->hidden->audio_fd >= 0) { if (this->hidden->audio_fd >= 0) {
close(this->hidden->audio_fd); close(this->hidden->audio_fd);
@@ -58,9 +54,7 @@ DSP_CloseDevice(_THIS)
SDL_free(this->hidden); SDL_free(this->hidden);
} }
static int DSP_OpenDevice(_THIS, const char *devname)
static int
DSP_OpenDevice(_THIS, const char *devname)
{ {
SDL_bool iscapture = this->iscapture; SDL_bool iscapture = this->iscapture;
const int flags = ((iscapture) ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT); const int flags = ((iscapture) ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT);
@@ -203,7 +197,8 @@ DSP_OpenDevice(_THIS, const char *devname)
SDL_CalculateAudioSpec(&this->spec); SDL_CalculateAudioSpec(&this->spec);
/* Determine the power of two of the fragment size */ /* Determine the power of two of the fragment size */
for (frag_spec = 0; (0x01U << frag_spec) < this->spec.size; ++frag_spec); for (frag_spec = 0; (0x01U << frag_spec) < this->spec.size; ++frag_spec)
;
if ((0x01U << frag_spec) != this->spec.size) { if ((0x01U << frag_spec) != this->spec.size) {
return SDL_SetError("Fragment size must be a power of two"); return SDL_SetError("Fragment size must be a power of two");
} }
@@ -231,7 +226,7 @@ DSP_OpenDevice(_THIS, const char *devname)
/* Allocate mixing buffer */ /* Allocate mixing buffer */
if (!iscapture) { if (!iscapture) {
this->hidden->mixlen = this->spec.size; this->hidden->mixlen = this->spec.size;
this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); this->hidden->mixbuf = (Uint8 *)SDL_malloc(this->hidden->mixlen);
if (this->hidden->mixbuf == NULL) { if (this->hidden->mixbuf == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -242,9 +237,7 @@ DSP_OpenDevice(_THIS, const char *devname)
return 0; return 0;
} }
static void DSP_PlayDevice(_THIS)
static void
DSP_PlayDevice(_THIS)
{ {
struct SDL_PrivateAudioData *h = this->hidden; struct SDL_PrivateAudioData *h = this->hidden;
if (write(h->audio_fd, h->mixbuf, h->mixlen) == -1) { if (write(h->audio_fd, h->mixbuf, h->mixlen) == -1) {
@@ -256,27 +249,24 @@ DSP_PlayDevice(_THIS)
#endif #endif
} }
static Uint8 * static Uint8 *DSP_GetDeviceBuf(_THIS)
DSP_GetDeviceBuf(_THIS)
{ {
return this->hidden->mixbuf; return this->hidden->mixbuf;
} }
static int static int DSP_CaptureFromDevice(_THIS, void *buffer, int buflen)
DSP_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
return (int)read(this->hidden->audio_fd, buffer, buflen); return (int)read(this->hidden->audio_fd, buffer, buflen);
} }
static void static void DSP_FlushCapture(_THIS)
DSP_FlushCapture(_THIS)
{ {
struct SDL_PrivateAudioData *h = this->hidden; struct SDL_PrivateAudioData *h = this->hidden;
audio_buf_info info; audio_buf_info info;
if (ioctl(h->audio_fd, SNDCTL_DSP_GETISPACE, &info) == 0) { if (ioctl(h->audio_fd, SNDCTL_DSP_GETISPACE, &info) == 0) {
while (info.bytes > 0) { while (info.bytes > 0) {
char buf[512]; char buf[512];
const size_t len = SDL_min(sizeof (buf), info.bytes); const size_t len = SDL_min(sizeof(buf), info.bytes);
const ssize_t br = read(h->audio_fd, buf, len); const ssize_t br = read(h->audio_fd, buf, len);
if (br <= 0) { if (br <= 0) {
break; break;
@@ -287,16 +277,14 @@ DSP_FlushCapture(_THIS)
} }
static SDL_bool InitTimeDevicesExist = SDL_FALSE; static SDL_bool InitTimeDevicesExist = SDL_FALSE;
static int static int look_for_devices_test(int fd)
look_for_devices_test(int fd)
{ {
InitTimeDevicesExist = SDL_TRUE; /* note that _something_ exists. */ InitTimeDevicesExist = SDL_TRUE; /* note that _something_ exists. */
/* Don't add to the device list, we're just seeing if any devices exist. */ /* Don't add to the device list, we're just seeing if any devices exist. */
return 0; return 0;
} }
static SDL_bool static SDL_bool DSP_Init(SDL_AudioDriverImpl *impl)
DSP_Init(SDL_AudioDriverImpl * impl)
{ {
InitTimeDevicesExist = SDL_FALSE; InitTimeDevicesExist = SDL_FALSE;
SDL_EnumUnixAudioDevices(0, look_for_devices_test); SDL_EnumUnixAudioDevices(0, look_for_devices_test);
@@ -320,7 +308,6 @@ DSP_Init(SDL_AudioDriverImpl * impl)
return SDL_TRUE; /* this audio target is available. */ return SDL_TRUE; /* this audio target is available. */
} }
AudioBootStrap DSP_bootstrap = { AudioBootStrap DSP_bootstrap = {
"dsp", "OSS /dev/dsp standard audio", DSP_Init, SDL_FALSE "dsp", "OSS /dev/dsp standard audio", DSP_Init, SDL_FALSE
}; };

View File

@@ -25,15 +25,14 @@
#include "../SDL_audio_c.h" #include "../SDL_audio_c.h"
#include "SDL_dummyaudio.h" #include "SDL_dummyaudio.h"
static int static int DUMMYAUDIO_OpenDevice(_THIS, const char *devname)
DUMMYAUDIO_OpenDevice(_THIS, const char *devname)
{ {
_this->hidden = (void *) 0x1; /* just something non-NULL */ _this->hidden = (void *)0x1; /* just something non-NULL */
return 0; /* always succeeds. */ return 0; /* always succeeds. */
} }
static int static int DUMMYAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
DUMMYAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
/* Delay to make this sort of simulate real audio input. */ /* Delay to make this sort of simulate real audio input. */
SDL_Delay((_this->spec.samples * 1000) / _this->spec.freq); SDL_Delay((_this->spec.samples * 1000) / _this->spec.freq);
@@ -43,8 +42,7 @@ DUMMYAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
return buflen; return buflen;
} }
static SDL_bool static SDL_bool DUMMYAUDIO_Init(SDL_AudioDriverImpl *impl)
DUMMYAUDIO_Init(SDL_AudioDriverImpl * impl)
{ {
/* Set the function pointers */ /* Set the function pointers */
impl->OpenDevice = DUMMYAUDIO_OpenDevice; impl->OpenDevice = DUMMYAUDIO_OpenDevice;

View File

@@ -32,10 +32,10 @@
!!! FIXME: true always once pthread support becomes widespread. Revisit this code !!! FIXME: true always once pthread support becomes widespread. Revisit this code
!!! FIXME: at some point and see what needs to be done for that! */ !!! FIXME: at some point and see what needs to be done for that! */
static void static void FeedAudioDevice(_THIS, const void *buf, const int buflen)
FeedAudioDevice(_THIS, const void *buf, const int buflen)
{ {
const int framelen = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels; const int framelen = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels;
/* *INDENT-OFF* */ /* clang-format off */
MAIN_THREAD_EM_ASM({ MAIN_THREAD_EM_ASM({
var SDL3 = Module['SDL3']; var SDL3 = Module['SDL3'];
var numChannels = SDL3.audio.currentOutputBuffer['numberOfChannels']; var numChannels = SDL3.audio.currentOutputBuffer['numberOfChannels'];
@@ -50,10 +50,10 @@ FeedAudioDevice(_THIS, const void *buf, const int buflen)
} }
} }
}, buf, buflen / framelen); }, buf, buflen / framelen);
/* *INDENT-ON* */ /* clang-format on */
} }
static void static void HandleAudioProcess(_THIS)
HandleAudioProcess(_THIS)
{ {
SDL_AudioCallback callback = this->callbackspec.callback; SDL_AudioCallback callback = this->callbackspec.callback;
const int stream_len = this->callbackspec.size; const int stream_len = this->callbackspec.size;
@@ -74,7 +74,7 @@ HandleAudioProcess(_THIS)
callback(this->callbackspec.userdata, this->work_buffer, stream_len); callback(this->callbackspec.userdata, this->work_buffer, stream_len);
} else { /* streaming/converting */ } else { /* streaming/converting */
int got; int got;
while (SDL_AudioStreamAvailable(this->stream) < ((int) this->spec.size)) { while (SDL_AudioStreamAvailable(this->stream) < ((int)this->spec.size)) {
callback(this->callbackspec.userdata, this->work_buffer, stream_len); callback(this->callbackspec.userdata, this->work_buffer, stream_len);
if (SDL_AudioStreamPut(this->stream, this->work_buffer, stream_len) == -1) { if (SDL_AudioStreamPut(this->stream, this->work_buffer, stream_len) == -1) {
SDL_AudioStreamClear(this->stream); SDL_AudioStreamClear(this->stream);
@@ -93,8 +93,7 @@ HandleAudioProcess(_THIS)
FeedAudioDevice(this, this->work_buffer, this->spec.size); FeedAudioDevice(this, this->work_buffer, this->spec.size);
} }
static void static void HandleCaptureProcess(_THIS)
HandleCaptureProcess(_THIS)
{ {
SDL_AudioCallback callback = this->callbackspec.callback; SDL_AudioCallback callback = this->callbackspec.callback;
const int stream_len = this->callbackspec.size; const int stream_len = this->callbackspec.size;
@@ -105,6 +104,7 @@ HandleCaptureProcess(_THIS)
return; return;
} }
/* *INDENT-OFF* */ /* clang-format off */
MAIN_THREAD_EM_ASM({ MAIN_THREAD_EM_ASM({
var SDL3 = Module['SDL3']; var SDL3 = Module['SDL3'];
var numChannels = SDL3.capture.currentCaptureBuffer.numberOfChannels; var numChannels = SDL3.capture.currentCaptureBuffer.numberOfChannels;
@@ -125,6 +125,7 @@ HandleCaptureProcess(_THIS)
} }
} }
}, this->work_buffer, (this->spec.size / sizeof (float)) / this->spec.channels); }, this->work_buffer, (this->spec.size / sizeof (float)) / this->spec.channels);
/* *INDENT-ON* */ /* clang-format on */
/* okay, we've got an interleaved float32 array in C now. */ /* okay, we've got an interleaved float32 array in C now. */
@@ -147,10 +148,9 @@ HandleCaptureProcess(_THIS)
} }
} }
static void EMSCRIPTENAUDIO_CloseDevice(_THIS)
static void
EMSCRIPTENAUDIO_CloseDevice(_THIS)
{ {
/* *INDENT-OFF* */ /* clang-format off */
MAIN_THREAD_EM_ASM({ MAIN_THREAD_EM_ASM({
var SDL3 = Module['SDL3']; var SDL3 = Module['SDL3'];
if ($0) { if ($0) {
@@ -189,14 +189,14 @@ EMSCRIPTENAUDIO_CloseDevice(_THIS)
SDL3.audioContext = undefined; SDL3.audioContext = undefined;
} }
}, this->iscapture); }, this->iscapture);
/* *INDENT-ON* */ /* clang-format on */
#if 0 /* !!! FIXME: currently not used. Can we move some stuff off the SDL3 namespace? --ryan. */ #if 0 /* !!! FIXME: currently not used. Can we move some stuff off the SDL3 namespace? --ryan. */
SDL_free(this->hidden); SDL_free(this->hidden);
#endif #endif
} }
static int static int EMSCRIPTENAUDIO_OpenDevice(_THIS, const char *devname)
EMSCRIPTENAUDIO_OpenDevice(_THIS, const char *devname)
{ {
SDL_AudioFormat test_format; SDL_AudioFormat test_format;
SDL_bool iscapture = this->iscapture; SDL_bool iscapture = this->iscapture;
@@ -204,6 +204,7 @@ EMSCRIPTENAUDIO_OpenDevice(_THIS, const char *devname)
/* based on parts of library_sdl.js */ /* based on parts of library_sdl.js */
/* *INDENT-OFF* */ /* clang-format off */
/* create context */ /* create context */
result = MAIN_THREAD_EM_ASM_INT({ result = MAIN_THREAD_EM_ASM_INT({
if (typeof(Module['SDL3']) === 'undefined') { if (typeof(Module['SDL3']) === 'undefined') {
@@ -228,6 +229,8 @@ EMSCRIPTENAUDIO_OpenDevice(_THIS, const char *devname)
} }
return SDL3.audioContext === undefined ? -1 : 0; return SDL3.audioContext === undefined ? -1 : 0;
}, iscapture); }, iscapture);
/* *INDENT-ON* */ /* clang-format on */
if (result < 0) { if (result < 0) {
return SDL_SetError("Web Audio API is not available!"); return SDL_SetError("Web Audio API is not available!");
} }
@@ -267,6 +270,7 @@ EMSCRIPTENAUDIO_OpenDevice(_THIS, const char *devname)
SDL_CalculateAudioSpec(&this->spec); SDL_CalculateAudioSpec(&this->spec);
/* *INDENT-OFF* */ /* clang-format off */
if (iscapture) { if (iscapture) {
/* The idea is to take the capture media stream, hook it up to an /* The idea is to take the capture media stream, hook it up to an
audio graph where we can pass it through a ScriptProcessorNode audio graph where we can pass it through a ScriptProcessorNode
@@ -338,17 +342,16 @@ EMSCRIPTENAUDIO_OpenDevice(_THIS, const char *devname)
SDL3.audio.scriptProcessorNode['connect'](SDL3.audioContext['destination']); SDL3.audio.scriptProcessorNode['connect'](SDL3.audioContext['destination']);
}, this->spec.channels, this->spec.samples, HandleAudioProcess, this); }, this->spec.channels, this->spec.samples, HandleAudioProcess, this);
} }
/* *INDENT-ON* */ /* clang-format on */
return 0; return 0;
} }
static void static void EMSCRIPTENAUDIO_LockOrUnlockDeviceWithNoMixerLock(SDL_AudioDevice *device)
EMSCRIPTENAUDIO_LockOrUnlockDeviceWithNoMixerLock(SDL_AudioDevice * device)
{ {
} }
static SDL_bool static SDL_bool EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl *impl)
EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl * impl)
{ {
SDL_bool available, capture_available; SDL_bool available, capture_available;
@@ -362,6 +365,7 @@ EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl * impl)
impl->LockDevice = impl->UnlockDevice = EMSCRIPTENAUDIO_LockOrUnlockDeviceWithNoMixerLock; impl->LockDevice = impl->UnlockDevice = EMSCRIPTENAUDIO_LockOrUnlockDeviceWithNoMixerLock;
impl->ProvidesOwnCallbackThread = SDL_TRUE; impl->ProvidesOwnCallbackThread = SDL_TRUE;
/* *INDENT-OFF* */ /* clang-format off */
/* check availability */ /* check availability */
available = MAIN_THREAD_EM_ASM_INT({ available = MAIN_THREAD_EM_ASM_INT({
if (typeof(AudioContext) !== 'undefined') { if (typeof(AudioContext) !== 'undefined') {
@@ -371,11 +375,13 @@ EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl * impl)
} }
return false; return false;
}); });
/* *INDENT-ON* */ /* clang-format on */
if (!available) { if (!available) {
SDL_SetError("No audio context available"); SDL_SetError("No audio context available");
} }
/* *INDENT-OFF* */ /* clang-format off */
capture_available = available && MAIN_THREAD_EM_ASM_INT({ capture_available = available && MAIN_THREAD_EM_ASM_INT({
if ((typeof(navigator.mediaDevices) !== 'undefined') && (typeof(navigator.mediaDevices.getUserMedia) !== 'undefined')) { if ((typeof(navigator.mediaDevices) !== 'undefined') && (typeof(navigator.mediaDevices.getUserMedia) !== 'undefined')) {
return true; return true;
@@ -384,6 +390,7 @@ EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl * impl)
} }
return false; return false;
}); });
/* *INDENT-ON* */ /* clang-format on */
impl->HasCaptureSupport = capture_available ? SDL_TRUE : SDL_FALSE; impl->HasCaptureSupport = capture_available ? SDL_TRUE : SDL_FALSE;
impl->OnlyHasDefaultCaptureDevice = capture_available ? SDL_TRUE : SDL_FALSE; impl->OnlyHasDefaultCaptureDevice = capture_available ? SDL_TRUE : SDL_FALSE;

View File

@@ -41,8 +41,7 @@ extern "C"
/* !!! FIXME: have the callback call the higher level to avoid code dupe. */ /* !!! FIXME: have the callback call the higher level to avoid code dupe. */
/* The Haiku callback for handling the audio buffer */ /* The Haiku callback for handling the audio buffer */
static void static void FillSound(void *device, void *stream, size_t len,
FillSound(void *device, void *stream, size_t len,
const media_raw_audio_format & format) const media_raw_audio_format & format)
{ {
SDL_AudioDevice *audio = (SDL_AudioDevice *) device; SDL_AudioDevice *audio = (SDL_AudioDevice *) device;
@@ -84,8 +83,7 @@ FillSound(void *device, void *stream, size_t len,
SDL_UnlockMutex(audio->mixer_lock); SDL_UnlockMutex(audio->mixer_lock);
} }
static void static void HAIKUAUDIO_CloseDevice(_THIS)
HAIKUAUDIO_CloseDevice(_THIS)
{ {
if (_this->hidden->audio_obj) { if (_this->hidden->audio_obj) {
_this->hidden->audio_obj->Stop(); _this->hidden->audio_obj->Stop();
@@ -99,8 +97,7 @@ static const int sig_list[] = {
SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGWINCH, 0 SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGWINCH, 0
}; };
static inline void static inline void MaskSignals(sigset_t * omask)
MaskSignals(sigset_t * omask)
{ {
sigset_t mask; sigset_t mask;
int i; int i;
@@ -112,15 +109,13 @@ MaskSignals(sigset_t * omask)
sigprocmask(SIG_BLOCK, &mask, omask); sigprocmask(SIG_BLOCK, &mask, omask);
} }
static inline void static inline void UnmaskSignals(sigset_t * omask)
UnmaskSignals(sigset_t * omask)
{ {
sigprocmask(SIG_SETMASK, omask, NULL); sigprocmask(SIG_SETMASK, omask, NULL);
} }
static int static int HAIKUAUDIO_OpenDevice(_THIS, const char *devname)
HAIKUAUDIO_OpenDevice(_THIS, const char *devname)
{ {
media_raw_audio_format format; media_raw_audio_format format;
SDL_AudioFormat test_format; SDL_AudioFormat test_format;
@@ -207,14 +202,12 @@ HAIKUAUDIO_OpenDevice(_THIS, const char *devname)
return 0; return 0;
} }
static void static void HAIKUAUDIO_Deinitialize(void)
HAIKUAUDIO_Deinitialize(void)
{ {
SDL_QuitBeApp(); SDL_QuitBeApp();
} }
static SDL_bool static SDL_bool HAIKUAUDIO_Init(SDL_AudioDriverImpl * impl)
HAIKUAUDIO_Init(SDL_AudioDriverImpl * impl)
{ {
/* Initialize the Be Application, if it's not already started */ /* Initialize the Be Application, if it's not already started */
if (SDL_InitBeApp() < 0) { if (SDL_InitBeApp() < 0) {

View File

@@ -26,36 +26,33 @@
#include "SDL_jackaudio.h" #include "SDL_jackaudio.h"
#include "../../thread/SDL_systhread.h" #include "../../thread/SDL_systhread.h"
static jack_client_t *(*JACK_jack_client_open)(const char *, jack_options_t, jack_status_t *, ...);
static jack_client_t * (*JACK_jack_client_open) (const char *, jack_options_t, jack_status_t *, ...); static int (*JACK_jack_client_close)(jack_client_t *);
static int (*JACK_jack_client_close) (jack_client_t *); static void (*JACK_jack_on_shutdown)(jack_client_t *, JackShutdownCallback, void *);
static void (*JACK_jack_on_shutdown) (jack_client_t *, JackShutdownCallback, void *); static int (*JACK_jack_activate)(jack_client_t *);
static int (*JACK_jack_activate) (jack_client_t *); static int (*JACK_jack_deactivate)(jack_client_t *);
static int (*JACK_jack_deactivate) (jack_client_t *); static void *(*JACK_jack_port_get_buffer)(jack_port_t *, jack_nframes_t);
static void * (*JACK_jack_port_get_buffer) (jack_port_t *, jack_nframes_t); static int (*JACK_jack_port_unregister)(jack_client_t *, jack_port_t *);
static int (*JACK_jack_port_unregister) (jack_client_t *, jack_port_t *); static void (*JACK_jack_free)(void *);
static void (*JACK_jack_free) (void *); static const char **(*JACK_jack_get_ports)(jack_client_t *, const char *, const char *, unsigned long);
static const char ** (*JACK_jack_get_ports) (jack_client_t *, const char *, const char *, unsigned long); static jack_nframes_t (*JACK_jack_get_sample_rate)(jack_client_t *);
static jack_nframes_t (*JACK_jack_get_sample_rate) (jack_client_t *); static jack_nframes_t (*JACK_jack_get_buffer_size)(jack_client_t *);
static jack_nframes_t (*JACK_jack_get_buffer_size) (jack_client_t *); static jack_port_t *(*JACK_jack_port_register)(jack_client_t *, const char *, const char *, unsigned long, unsigned long);
static jack_port_t * (*JACK_jack_port_register) (jack_client_t *, const char *, const char *, unsigned long, unsigned long); static jack_port_t *(*JACK_jack_port_by_name)(jack_client_t *, const char *);
static jack_port_t * (*JACK_jack_port_by_name) (jack_client_t *, const char *); static const char *(*JACK_jack_port_name)(const jack_port_t *);
static const char * (*JACK_jack_port_name) (const jack_port_t *); static const char *(*JACK_jack_port_type)(const jack_port_t *);
static const char * (*JACK_jack_port_type) (const jack_port_t *); static int (*JACK_jack_connect)(jack_client_t *, const char *, const char *);
static int (*JACK_jack_connect) (jack_client_t *, const char *, const char *); static int (*JACK_jack_set_process_callback)(jack_client_t *, JackProcessCallback, void *);
static int (*JACK_jack_set_process_callback) (jack_client_t *, JackProcessCallback, void *);
static int load_jack_syms(void); static int load_jack_syms(void);
#ifdef SDL_AUDIO_DRIVER_JACK_DYNAMIC #ifdef SDL_AUDIO_DRIVER_JACK_DYNAMIC
static const char *jack_library = SDL_AUDIO_DRIVER_JACK_DYNAMIC; static const char *jack_library = SDL_AUDIO_DRIVER_JACK_DYNAMIC;
static void *jack_handle = NULL; static void *jack_handle = NULL;
/* !!! FIXME: this is copy/pasted in several places now */ /* !!! FIXME: this is copy/pasted in several places now */
static int static int load_jack_sym(const char *fn, void **addr)
load_jack_sym(const char *fn, void **addr)
{ {
*addr = SDL_LoadFunction(jack_handle, fn); *addr = SDL_LoadFunction(jack_handle, fn);
if (*addr == NULL) { if (*addr == NULL) {
@@ -68,10 +65,10 @@ load_jack_sym(const char *fn, void **addr)
/* cast funcs to char* first, to please GCC's strict aliasing rules. */ /* cast funcs to char* first, to please GCC's strict aliasing rules. */
#define SDL_JACK_SYM(x) \ #define SDL_JACK_SYM(x) \
if (!load_jack_sym(#x, (void **) (char *) &JACK_##x)) return -1 if (!load_jack_sym(#x, (void **)(char *)&JACK_##x)) \
return -1
static void static void UnloadJackLibrary(void)
UnloadJackLibrary(void)
{ {
if (jack_handle != NULL) { if (jack_handle != NULL) {
SDL_UnloadObject(jack_handle); SDL_UnloadObject(jack_handle);
@@ -79,8 +76,7 @@ UnloadJackLibrary(void)
} }
} }
static int static int LoadJackLibrary(void)
LoadJackLibrary(void)
{ {
int retval = 0; int retval = 0;
if (jack_handle == NULL) { if (jack_handle == NULL) {
@@ -102,13 +98,11 @@ LoadJackLibrary(void)
#define SDL_JACK_SYM(x) JACK_##x = x #define SDL_JACK_SYM(x) JACK_##x = x
static void static void UnloadJackLibrary(void)
UnloadJackLibrary(void)
{ {
} }
static int static int LoadJackLibrary(void)
LoadJackLibrary(void)
{ {
load_jack_syms(); load_jack_syms();
return 0; return 0;
@@ -116,9 +110,7 @@ LoadJackLibrary(void)
#endif /* SDL_AUDIO_DRIVER_JACK_DYNAMIC */ #endif /* SDL_AUDIO_DRIVER_JACK_DYNAMIC */
static int load_jack_syms(void)
static int
load_jack_syms(void)
{ {
SDL_JACK_SYM(jack_client_open); SDL_JACK_SYM(jack_client_open);
SDL_JACK_SYM(jack_client_close); SDL_JACK_SYM(jack_client_close);
@@ -140,23 +132,20 @@ load_jack_syms(void)
return 0; return 0;
} }
static void jackShutdownCallback(void *arg) /* JACK went away; device is lost. */
static void
jackShutdownCallback(void *arg) /* JACK went away; device is lost. */
{ {
SDL_AudioDevice *this = (SDL_AudioDevice *) arg; SDL_AudioDevice *this = (SDL_AudioDevice *)arg;
SDL_OpenedAudioDeviceDisconnected(this); SDL_OpenedAudioDeviceDisconnected(this);
SDL_SemPost(this->hidden->iosem); /* unblock the SDL thread. */ SDL_SemPost(this->hidden->iosem); /* unblock the SDL thread. */
} }
// !!! FIXME: implement and register these! // !!! FIXME: implement and register these!
//typedef int(* JackSampleRateCallback)(jack_nframes_t nframes, void *arg) // typedef int(* JackSampleRateCallback)(jack_nframes_t nframes, void *arg)
//typedef int(* JackBufferSizeCallback)(jack_nframes_t nframes, void *arg) // typedef int(* JackBufferSizeCallback)(jack_nframes_t nframes, void *arg)
static int static int jackProcessPlaybackCallback(jack_nframes_t nframes, void *arg)
jackProcessPlaybackCallback(jack_nframes_t nframes, void *arg)
{ {
SDL_AudioDevice *this = (SDL_AudioDevice *) arg; SDL_AudioDevice *this = (SDL_AudioDevice *)arg;
jack_port_t **ports = this->hidden->sdlports; jack_port_t **ports = this->hidden->sdlports;
const int total_channels = this->spec.channels; const int total_channels = this->spec.channels;
const int total_frames = this->spec.samples; const int total_frames = this->spec.samples;
@@ -168,9 +157,9 @@ jackProcessPlaybackCallback(jack_nframes_t nframes, void *arg)
} }
for (channelsi = 0; channelsi < total_channels; channelsi++) { for (channelsi = 0; channelsi < total_channels; channelsi++) {
float *dst = (float *) JACK_jack_port_get_buffer(ports[channelsi], nframes); float *dst = (float *)JACK_jack_port_get_buffer(ports[channelsi], nframes);
if (dst) { if (dst) {
const float *src = ((float *) this->hidden->iobuffer) + channelsi; const float *src = ((float *)this->hidden->iobuffer) + channelsi;
int framesi; int framesi;
for (framesi = 0; framesi < total_frames; framesi++) { for (framesi = 0; framesi < total_frames; framesi++) {
*(dst++) = *src; *(dst++) = *src;
@@ -180,13 +169,11 @@ jackProcessPlaybackCallback(jack_nframes_t nframes, void *arg)
} }
SDL_SemPost(this->hidden->iosem); /* tell SDL thread we're done; refill the buffer. */ SDL_SemPost(this->hidden->iosem); /* tell SDL thread we're done; refill the buffer. */
return 0; /* success */ return 0;
} }
/* This function waits until it is possible to write a full sound buffer */ /* This function waits until it is possible to write a full sound buffer */
static void static void JACK_WaitDevice(_THIS)
JACK_WaitDevice(_THIS)
{ {
if (SDL_AtomicGet(&this->enabled)) { if (SDL_AtomicGet(&this->enabled)) {
if (SDL_SemWait(this->hidden->iosem) == -1) { if (SDL_SemWait(this->hidden->iosem) == -1) {
@@ -195,17 +182,14 @@ JACK_WaitDevice(_THIS)
} }
} }
static Uint8 * static Uint8 *JACK_GetDeviceBuf(_THIS)
JACK_GetDeviceBuf(_THIS)
{ {
return (Uint8 *) this->hidden->iobuffer; return (Uint8 *)this->hidden->iobuffer;
} }
static int jackProcessCaptureCallback(jack_nframes_t nframes, void *arg)
static int
jackProcessCaptureCallback(jack_nframes_t nframes, void *arg)
{ {
SDL_AudioDevice *this = (SDL_AudioDevice *) arg; SDL_AudioDevice *this = (SDL_AudioDevice *)arg;
if (SDL_AtomicGet(&this->enabled)) { if (SDL_AtomicGet(&this->enabled)) {
jack_port_t **ports = this->hidden->sdlports; jack_port_t **ports = this->hidden->sdlports;
const int total_channels = this->spec.channels; const int total_channels = this->spec.channels;
@@ -213,9 +197,9 @@ jackProcessCaptureCallback(jack_nframes_t nframes, void *arg)
int channelsi; int channelsi;
for (channelsi = 0; channelsi < total_channels; channelsi++) { for (channelsi = 0; channelsi < total_channels; channelsi++) {
const float *src = (const float *) JACK_jack_port_get_buffer(ports[channelsi], nframes); const float *src = (const float *)JACK_jack_port_get_buffer(ports[channelsi], nframes);
if (src) { if (src) {
float *dst = ((float *) this->hidden->iobuffer) + channelsi; float *dst = ((float *)this->hidden->iobuffer) + channelsi;
int framesi; int framesi;
for (framesi = 0; framesi < total_frames; framesi++) { for (framesi = 0; framesi < total_frames; framesi++) {
*dst = *(src++); *dst = *(src++);
@@ -226,11 +210,10 @@ jackProcessCaptureCallback(jack_nframes_t nframes, void *arg)
} }
SDL_SemPost(this->hidden->iosem); /* tell SDL thread we're done; new buffer is ready! */ SDL_SemPost(this->hidden->iosem); /* tell SDL thread we're done; new buffer is ready! */
return 0; /* success */ return 0;
} }
static int static int JACK_CaptureFromDevice(_THIS, void *buffer, int buflen)
JACK_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
SDL_assert(buflen == this->spec.size); /* we always fill a full buffer. */ SDL_assert(buflen == this->spec.size); /* we always fill a full buffer. */
@@ -243,15 +226,12 @@ JACK_CaptureFromDevice(_THIS, void *buffer, int buflen)
return buflen; return buflen;
} }
static void static void JACK_FlushCapture(_THIS)
JACK_FlushCapture(_THIS)
{ {
SDL_SemWait(this->hidden->iosem); SDL_SemWait(this->hidden->iosem);
} }
static void JACK_CloseDevice(_THIS)
static void
JACK_CloseDevice(_THIS)
{ {
if (this->hidden->client) { if (this->hidden->client) {
JACK_jack_deactivate(this->hidden->client); JACK_jack_deactivate(this->hidden->client);
@@ -276,8 +256,7 @@ JACK_CloseDevice(_THIS)
SDL_free(this->hidden); SDL_free(this->hidden);
} }
static int static int JACK_OpenDevice(_THIS, const char *devname)
JACK_OpenDevice(_THIS, const char *devname)
{ {
/* Note that JACK uses "output" for capture devices (they output audio /* Note that JACK uses "output" for capture devices (they output audio
data to us) and "input" for playback (we input audio data to them). data to us) and "input" for playback (we input audio data to them).
@@ -297,7 +276,7 @@ JACK_OpenDevice(_THIS, const char *devname)
int i; int i;
/* Initialize all variables that we clean on shutdown */ /* Initialize all variables that we clean on shutdown */
this->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, sizeof (*this->hidden)); this->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, sizeof(*this->hidden));
if (this->hidden == NULL) { if (this->hidden == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -325,7 +304,7 @@ JACK_OpenDevice(_THIS, const char *devname)
const char *type = JACK_jack_port_type(dport); const char *type = JACK_jack_port_type(dport);
const int len = SDL_strlen(type); const int len = SDL_strlen(type);
/* See if type ends with "audio" */ /* See if type ends with "audio" */
if (len >= 5 && !SDL_memcmp(type+len-5, "audio", 5)) { if (len >= 5 && !SDL_memcmp(type + len - 5, "audio", 5)) {
audio_ports[channels++] = i; audio_ports[channels++] = i;
} }
} }
@@ -333,7 +312,6 @@ JACK_OpenDevice(_THIS, const char *devname)
return SDL_SetError("No physical JACK ports available"); return SDL_SetError("No physical JACK ports available");
} }
/* !!! FIXME: docs say about buffer size: "This size may change, clients that depend on it must register a bufsize_callback so they will be notified if it does." */ /* !!! FIXME: docs say about buffer size: "This size may change, clients that depend on it must register a bufsize_callback so they will be notified if it does." */
/* Jack pretty much demands what it wants. */ /* Jack pretty much demands what it wants. */
@@ -349,20 +327,20 @@ JACK_OpenDevice(_THIS, const char *devname)
return -1; /* error was set by SDL_CreateSemaphore */ return -1; /* error was set by SDL_CreateSemaphore */
} }
this->hidden->iobuffer = (float *) SDL_calloc(1, this->spec.size); this->hidden->iobuffer = (float *)SDL_calloc(1, this->spec.size);
if (!this->hidden->iobuffer) { if (!this->hidden->iobuffer) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
/* Build SDL's ports, which we will connect to the device ports. */ /* Build SDL's ports, which we will connect to the device ports. */
this->hidden->sdlports = (jack_port_t **) SDL_calloc(channels, sizeof (jack_port_t *)); this->hidden->sdlports = (jack_port_t **)SDL_calloc(channels, sizeof(jack_port_t *));
if (this->hidden->sdlports == NULL) { if (this->hidden->sdlports == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
for (i = 0; i < channels; i++) { for (i = 0; i < channels; i++) {
char portname[32]; char portname[32];
SDL_snprintf(portname, sizeof (portname), "sdl_jack_%s_%d", sdlportstr, i); SDL_snprintf(portname, sizeof(portname), "sdl_jack_%s_%d", sdlportstr, i);
this->hidden->sdlports[i] = JACK_jack_port_register(client, portname, JACK_DEFAULT_AUDIO_TYPE, sdlportflags, 0); this->hidden->sdlports[i] = JACK_jack_port_register(client, portname, JACK_DEFAULT_AUDIO_TYPE, sdlportflags, 0);
if (this->hidden->sdlports[i] == NULL) { if (this->hidden->sdlports[i] == NULL) {
return SDL_SetError("jack_port_register failed"); return SDL_SetError("jack_port_register failed");
@@ -397,14 +375,12 @@ JACK_OpenDevice(_THIS, const char *devname)
return 0; return 0;
} }
static void static void JACK_Deinitialize(void)
JACK_Deinitialize(void)
{ {
UnloadJackLibrary(); UnloadJackLibrary();
} }
static SDL_bool static SDL_bool JACK_Init(SDL_AudioDriverImpl *impl)
JACK_Init(SDL_AudioDriverImpl * impl)
{ {
if (LoadJackLibrary() < 0) { if (LoadJackLibrary() < 0) {
return SDL_FALSE; return SDL_FALSE;

View File

@@ -22,7 +22,6 @@
#ifdef SDL_AUDIO_DRIVER_N3DS #ifdef SDL_AUDIO_DRIVER_N3DS
/* N3DS Audio driver */ /* N3DS Audio driver */
#include "../SDL_sysaudio.h" #include "../SDL_sysaudio.h"
@@ -36,32 +35,27 @@ static SDL_AudioDevice *audio_device;
static void FreePrivateData(_THIS); static void FreePrivateData(_THIS);
static int FindAudioFormat(_THIS); static int FindAudioFormat(_THIS);
static SDL_INLINE void static SDL_INLINE void contextLock(_THIS)
contextLock(_THIS)
{ {
LightLock_Lock(&this->hidden->lock); LightLock_Lock(&this->hidden->lock);
} }
static SDL_INLINE void static SDL_INLINE void contextUnlock(_THIS)
contextUnlock(_THIS)
{ {
LightLock_Unlock(&this->hidden->lock); LightLock_Unlock(&this->hidden->lock);
} }
static void static void N3DSAUD_LockAudio(_THIS)
N3DSAUD_LockAudio(_THIS)
{ {
contextLock(this); contextLock(this);
} }
static void static void N3DSAUD_UnlockAudio(_THIS)
N3DSAUD_UnlockAudio(_THIS)
{ {
contextUnlock(this); contextUnlock(this);
} }
static void static void N3DSAUD_DspHook(DSP_HookType hook)
N3DSAUD_DspHook(DSP_HookType hook)
{ {
if (hook == DSPHOOK_ONCANCEL) { if (hook == DSPHOOK_ONCANCEL) {
contextLock(audio_device); contextLock(audio_device);
@@ -72,12 +66,11 @@ N3DSAUD_DspHook(DSP_HookType hook)
} }
} }
static void static void AudioFrameFinished(void *device)
AudioFrameFinished(void *device)
{ {
bool shouldBroadcast = false; bool shouldBroadcast = false;
unsigned i; unsigned i;
SDL_AudioDevice *this = (SDL_AudioDevice *) device; SDL_AudioDevice *this = (SDL_AudioDevice *)device;
contextLock(this); contextLock(this);
@@ -95,13 +88,12 @@ AudioFrameFinished(void *device)
contextUnlock(this); contextUnlock(this);
} }
static int static int N3DSAUDIO_OpenDevice(_THIS, const char *devname)
N3DSAUDIO_OpenDevice(_THIS, const char *devname)
{ {
Result ndsp_init_res; Result ndsp_init_res;
Uint8 *data_vaddr; Uint8 *data_vaddr;
float mix[12]; float mix[12];
this->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, sizeof *this->hidden); this->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, sizeof *this->hidden);
if (this->hidden == NULL) { if (this->hidden == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
@@ -140,14 +132,14 @@ N3DSAUDIO_OpenDevice(_THIS, const char *devname)
} }
this->hidden->mixlen = this->spec.size; this->hidden->mixlen = this->spec.size;
this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->spec.size); this->hidden->mixbuf = (Uint8 *)SDL_malloc(this->spec.size);
if (this->hidden->mixbuf == NULL) { if (this->hidden->mixbuf == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);
data_vaddr = (Uint8 *) linearAlloc(this->hidden->mixlen * NUM_BUFFERS); data_vaddr = (Uint8 *)linearAlloc(this->hidden->mixlen * NUM_BUFFERS);
if (data_vaddr == NULL) { if (data_vaddr == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -186,8 +178,7 @@ N3DSAUDIO_OpenDevice(_THIS, const char *devname)
return 0; return 0;
} }
static int static int N3DSAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
N3DSAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
/* Delay to make this sort of simulate real audio input. */ /* Delay to make this sort of simulate real audio input. */
SDL_Delay((this->spec.samples * 1000) / this->spec.freq); SDL_Delay((this->spec.samples * 1000) / this->spec.freq);
@@ -197,8 +188,7 @@ N3DSAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
return buflen; return buflen;
} }
static void static void N3DSAUDIO_PlayDevice(_THIS)
N3DSAUDIO_PlayDevice(_THIS)
{ {
size_t nextbuf; size_t nextbuf;
size_t sampleLen; size_t sampleLen;
@@ -217,15 +207,14 @@ N3DSAUDIO_PlayDevice(_THIS)
contextUnlock(this); contextUnlock(this);
memcpy((void *) this->hidden->waveBuf[nextbuf].data_vaddr, memcpy((void *)this->hidden->waveBuf[nextbuf].data_vaddr,
this->hidden->mixbuf, sampleLen); this->hidden->mixbuf, sampleLen);
DSP_FlushDataCache(this->hidden->waveBuf[nextbuf].data_vaddr, sampleLen); DSP_FlushDataCache(this->hidden->waveBuf[nextbuf].data_vaddr, sampleLen);
ndspChnWaveBufAdd(0, &this->hidden->waveBuf[nextbuf]); ndspChnWaveBufAdd(0, &this->hidden->waveBuf[nextbuf]);
} }
static void static void N3DSAUDIO_WaitDevice(_THIS)
N3DSAUDIO_WaitDevice(_THIS)
{ {
contextLock(this); contextLock(this);
while (!this->hidden->isCancelled && while (!this->hidden->isCancelled &&
@@ -235,14 +224,12 @@ N3DSAUDIO_WaitDevice(_THIS)
contextUnlock(this); contextUnlock(this);
} }
static Uint8 * static Uint8 *N3DSAUDIO_GetDeviceBuf(_THIS)
N3DSAUDIO_GetDeviceBuf(_THIS)
{ {
return this->hidden->mixbuf; return this->hidden->mixbuf;
} }
static void static void N3DSAUDIO_CloseDevice(_THIS)
N3DSAUDIO_CloseDevice(_THIS)
{ {
contextLock(this); contextLock(this);
@@ -262,8 +249,7 @@ N3DSAUDIO_CloseDevice(_THIS)
FreePrivateData(this); FreePrivateData(this);
} }
static void static void N3DSAUDIO_ThreadInit(_THIS)
N3DSAUDIO_ThreadInit(_THIS)
{ {
s32 current_priority; s32 current_priority;
svcGetThreadPriority(&current_priority, CUR_THREAD_HANDLE); svcGetThreadPriority(&current_priority, CUR_THREAD_HANDLE);
@@ -273,8 +259,7 @@ N3DSAUDIO_ThreadInit(_THIS)
svcSetThreadPriority(CUR_THREAD_HANDLE, current_priority); svcSetThreadPriority(CUR_THREAD_HANDLE, current_priority);
} }
static SDL_bool static SDL_bool N3DSAUDIO_Init(SDL_AudioDriverImpl *impl)
N3DSAUDIO_Init(SDL_AudioDriverImpl *impl)
{ {
/* Set the function pointers */ /* Set the function pointers */
impl->OpenDevice = N3DSAUDIO_OpenDevice; impl->OpenDevice = N3DSAUDIO_OpenDevice;
@@ -304,15 +289,14 @@ AudioBootStrap N3DSAUDIO_bootstrap = {
/** /**
* Cleans up all allocated memory, safe to call with null pointers * Cleans up all allocated memory, safe to call with null pointers
*/ */
static void static void FreePrivateData(_THIS)
FreePrivateData(_THIS)
{ {
if (!this->hidden) { if (!this->hidden) {
return; return;
} }
if (this->hidden->waveBuf[0].data_vaddr) { if (this->hidden->waveBuf[0].data_vaddr) {
linearFree((void *) this->hidden->waveBuf[0].data_vaddr); linearFree((void *)this->hidden->waveBuf[0].data_vaddr);
} }
if (this->hidden->mixbuf) { if (this->hidden->mixbuf) {
@@ -324,8 +308,7 @@ FreePrivateData(_THIS)
this->hidden = NULL; this->hidden = NULL;
} }
static int static int FindAudioFormat(_THIS)
FindAudioFormat(_THIS)
{ {
SDL_bool found_valid_format = SDL_FALSE; SDL_bool found_valid_format = SDL_FALSE;
Uint16 test_format = SDL_FirstAudioFormat(this->spec.format); Uint16 test_format = SDL_FirstAudioFormat(this->spec.format);

View File

@@ -43,15 +43,12 @@
/* #define DEBUG_AUDIO */ /* #define DEBUG_AUDIO */
static void static void NETBSDAUDIO_DetectDevices(void)
NETBSDAUDIO_DetectDevices(void)
{ {
SDL_EnumUnixAudioDevices(0, NULL); SDL_EnumUnixAudioDevices(0, NULL);
} }
static void NETBSDAUDIO_Status(_THIS)
static void
NETBSDAUDIO_Status(_THIS)
{ {
#ifdef DEBUG_AUDIO #ifdef DEBUG_AUDIO
/* *INDENT-OFF* */ /* clang-format off */ /* *INDENT-OFF* */ /* clang-format off */
@@ -117,12 +114,11 @@ NETBSDAUDIO_Status(_THIS)
this->spec.format, this->spec.format,
this->spec.size); this->spec.size);
/* *INDENT-ON* */ /* clang-format on */ /* *INDENT-ON* */ /* clang-format on */
#endif /* DEBUG_AUDIO */ #endif /* DEBUG_AUDIO */
} }
static void NETBSDAUDIO_PlayDevice(_THIS)
static void
NETBSDAUDIO_PlayDevice(_THIS)
{ {
struct SDL_PrivateAudioData *h = this->hidden; struct SDL_PrivateAudioData *h = this->hidden;
int written; int written;
@@ -141,17 +137,14 @@ NETBSDAUDIO_PlayDevice(_THIS)
#endif #endif
} }
static Uint8 * static Uint8 *NETBSDAUDIO_GetDeviceBuf(_THIS)
NETBSDAUDIO_GetDeviceBuf(_THIS)
{ {
return this->hidden->mixbuf; return this->hidden->mixbuf;
} }
static int NETBSDAUDIO_CaptureFromDevice(_THIS, void *_buffer, int buflen)
static int
NETBSDAUDIO_CaptureFromDevice(_THIS, void *_buffer, int buflen)
{ {
Uint8 *buffer = (Uint8 *) _buffer; Uint8 *buffer = (Uint8 *)_buffer;
int br; int br;
br = read(this->hidden->audio_fd, buffer, buflen); br = read(this->hidden->audio_fd, buffer, buflen);
@@ -167,8 +160,7 @@ NETBSDAUDIO_CaptureFromDevice(_THIS, void *_buffer, int buflen)
return 0; return 0;
} }
static void static void NETBSDAUDIO_FlushCapture(_THIS)
NETBSDAUDIO_FlushCapture(_THIS)
{ {
audio_info_t info; audio_info_t info;
size_t remain; size_t remain;
@@ -178,9 +170,9 @@ NETBSDAUDIO_FlushCapture(_THIS)
return; /* oh well. */ return; /* oh well. */
} }
remain = (size_t) (info.record.samples * (SDL_AUDIO_BITSIZE(this->spec.format) / 8)); remain = (size_t)(info.record.samples * (SDL_AUDIO_BITSIZE(this->spec.format) / 8));
while (remain > 0) { while (remain > 0) {
const size_t len = SDL_min(sizeof (buf), remain); const size_t len = SDL_min(sizeof(buf), remain);
const int br = read(this->hidden->audio_fd, buf, len); const int br = read(this->hidden->audio_fd, buf, len);
if (br <= 0) { if (br <= 0) {
return; /* oh well. */ return; /* oh well. */
@@ -189,8 +181,7 @@ NETBSDAUDIO_FlushCapture(_THIS)
} }
} }
static void static void NETBSDAUDIO_CloseDevice(_THIS)
NETBSDAUDIO_CloseDevice(_THIS)
{ {
if (this->hidden->audio_fd >= 0) { if (this->hidden->audio_fd >= 0) {
close(this->hidden->audio_fd); close(this->hidden->audio_fd);
@@ -199,8 +190,7 @@ NETBSDAUDIO_CloseDevice(_THIS)
SDL_free(this->hidden); SDL_free(this->hidden);
} }
static int static int NETBSDAUDIO_OpenDevice(_THIS, const char *devname)
NETBSDAUDIO_OpenDevice(_THIS, const char *devname)
{ {
SDL_bool iscapture = this->iscapture; SDL_bool iscapture = this->iscapture;
SDL_AudioFormat test_format; SDL_AudioFormat test_format;
@@ -239,8 +229,7 @@ NETBSDAUDIO_OpenDevice(_THIS, const char *devname)
* Use the device's native sample rate so the kernel doesn't have to * Use the device's native sample rate so the kernel doesn't have to
* resample. * resample.
*/ */
this->spec.freq = iscapture ? this->spec.freq = iscapture ? hwinfo.record.sample_rate : hwinfo.play.sample_rate;
hwinfo.record.sample_rate : hwinfo.play.sample_rate;
} }
#endif #endif
@@ -305,7 +294,7 @@ NETBSDAUDIO_OpenDevice(_THIS, const char *devname)
if (!iscapture) { if (!iscapture) {
/* Allocate mixing buffer */ /* Allocate mixing buffer */
this->hidden->mixlen = this->spec.size; this->hidden->mixlen = this->spec.size;
this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); this->hidden->mixbuf = (Uint8 *)SDL_malloc(this->hidden->mixlen);
if (this->hidden->mixbuf == NULL) { if (this->hidden->mixbuf == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -318,8 +307,7 @@ NETBSDAUDIO_OpenDevice(_THIS, const char *devname)
return 0; return 0;
} }
static SDL_bool static SDL_bool NETBSDAUDIO_Init(SDL_AudioDriverImpl *impl)
NETBSDAUDIO_Init(SDL_AudioDriverImpl * impl)
{ {
/* Set the function pointers */ /* Set the function pointers */
impl->DetectDevices = NETBSDAUDIO_DetectDevices; impl->DetectDevices = NETBSDAUDIO_DetectDevices;
@@ -336,7 +324,6 @@ NETBSDAUDIO_Init(SDL_AudioDriverImpl * impl)
return SDL_TRUE; /* this audio target is available. */ return SDL_TRUE; /* this audio target is available. */
} }
AudioBootStrap NETBSDAUDIO_bootstrap = { AudioBootStrap NETBSDAUDIO_bootstrap = {
"netbsd", "NetBSD audio", NETBSDAUDIO_Init, SDL_FALSE "netbsd", "NetBSD audio", NETBSDAUDIO_Init, SDL_FALSE
}; };

View File

@@ -38,8 +38,8 @@
#if 0 #if 0
#define LOG_TAG "SDL_openslES" #define LOG_TAG "SDL_openslES"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
//#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG,__VA_ARGS__) //#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG,__VA_ARGS__)
#define LOGV(...) #define LOGV(...)
#else #else
@@ -127,8 +127,7 @@ static void openslES_DestroyEngine(void)
} }
} }
static int static int openslES_CreateEngine(void)
openslES_CreateEngine(void)
{ {
const SLInterfaceID ids[1] = { SL_IID_VOLUME }; const SLInterfaceID ids[1] = { SL_IID_VOLUME };
const SLboolean req[1] = { SL_BOOLEAN_FALSE }; const SLboolean req[1] = { SL_BOOLEAN_FALSE };
@@ -182,17 +181,15 @@ error:
} }
/* this callback handler is called every time a buffer finishes recording */ /* this callback handler is called every time a buffer finishes recording */
static void static void bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
{ {
struct SDL_PrivateAudioData *audiodata = (struct SDL_PrivateAudioData *) context; struct SDL_PrivateAudioData *audiodata = (struct SDL_PrivateAudioData *)context;
LOGV("SLES: Recording Callback"); LOGV("SLES: Recording Callback");
SDL_SemPost(audiodata->playsem); SDL_SemPost(audiodata->playsem);
} }
static void static void openslES_DestroyPCMRecorder(_THIS)
openslES_DestroyPCMRecorder(_THIS)
{ {
struct SDL_PrivateAudioData *audiodata = this->hidden; struct SDL_PrivateAudioData *audiodata = this->hidden;
SLresult result; SLresult result;
@@ -223,8 +220,7 @@ openslES_DestroyPCMRecorder(_THIS)
} }
} }
static int static int openslES_CreatePCMRecorder(_THIS)
openslES_CreatePCMRecorder(_THIS)
{ {
struct SDL_PrivateAudioData *audiodata = this->hidden; struct SDL_PrivateAudioData *audiodata = this->hidden;
SLDataFormat_PCM format_pcm; SLDataFormat_PCM format_pcm;
@@ -322,7 +318,7 @@ openslES_CreatePCMRecorder(_THIS)
} }
/* Create the sound buffers */ /* Create the sound buffers */
audiodata->mixbuff = (Uint8 *) SDL_malloc(NUM_BUFFERS * this->spec.size); audiodata->mixbuff = (Uint8 *)SDL_malloc(NUM_BUFFERS * this->spec.size);
if (audiodata->mixbuff == NULL) { if (audiodata->mixbuff == NULL) {
LOGE("mixbuffer allocate - out of memory"); LOGE("mixbuffer allocate - out of memory");
goto failed; goto failed;
@@ -362,17 +358,15 @@ failed:
} }
/* this callback handler is called every time a buffer finishes playing */ /* this callback handler is called every time a buffer finishes playing */
static void static void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
{ {
struct SDL_PrivateAudioData *audiodata = (struct SDL_PrivateAudioData *) context; struct SDL_PrivateAudioData *audiodata = (struct SDL_PrivateAudioData *)context;
LOGV("SLES: Playback Callback"); LOGV("SLES: Playback Callback");
SDL_SemPost(audiodata->playsem); SDL_SemPost(audiodata->playsem);
} }
static void static void openslES_DestroyPCMPlayer(_THIS)
openslES_DestroyPCMPlayer(_THIS)
{ {
struct SDL_PrivateAudioData *audiodata = this->hidden; struct SDL_PrivateAudioData *audiodata = this->hidden;
SLresult result; SLresult result;
@@ -404,8 +398,7 @@ openslES_DestroyPCMPlayer(_THIS)
} }
} }
static int static int openslES_CreatePCMPlayer(_THIS)
openslES_CreatePCMPlayer(_THIS)
{ {
struct SDL_PrivateAudioData *audiodata = this->hidden; struct SDL_PrivateAudioData *audiodata = this->hidden;
SLDataLocator_AndroidSimpleBufferQueue loc_bufq; SLDataLocator_AndroidSimpleBufferQueue loc_bufq;
@@ -433,7 +426,7 @@ openslES_CreatePCMPlayer(_THIS)
if (!test_format) { if (!test_format) {
/* Didn't find a compatible format : */ /* Didn't find a compatible format : */
LOGI( "No compatible audio format, using signed 16-bit audio" ); LOGI("No compatible audio format, using signed 16-bit audio");
test_format = AUDIO_S16SYS; test_format = AUDIO_S16SYS;
} }
this->spec.format = test_format; this->spec.format = test_format;
@@ -465,8 +458,7 @@ openslES_CreatePCMPlayer(_THIS)
format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
} }
switch (this->spec.channels) switch (this->spec.channels) {
{
case 1: case 1:
format_pcm.channelMask = SL_SPEAKER_FRONT_LEFT; format_pcm.channelMask = SL_SPEAKER_FRONT_LEFT;
break; break;
@@ -511,7 +503,7 @@ openslES_CreatePCMPlayer(_THIS)
} }
audioSrc.pLocator = &loc_bufq; audioSrc.pLocator = &loc_bufq;
audioSrc.pFormat = SDL_AUDIO_ISFLOAT(this->spec.format) ? (void*)&format_pcm_ex : (void*)&format_pcm; audioSrc.pFormat = SDL_AUDIO_ISFLOAT(this->spec.format) ? (void *)&format_pcm_ex : (void *)&format_pcm;
/* configure audio sink */ /* configure audio sink */
loc_outmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; loc_outmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
@@ -572,7 +564,7 @@ openslES_CreatePCMPlayer(_THIS)
} }
/* Create the sound buffers */ /* Create the sound buffers */
audiodata->mixbuff = (Uint8 *) SDL_malloc(NUM_BUFFERS * this->spec.size); audiodata->mixbuff = (Uint8 *)SDL_malloc(NUM_BUFFERS * this->spec.size);
if (audiodata->mixbuff == NULL) { if (audiodata->mixbuff == NULL) {
LOGE("mixbuffer allocate - out of memory"); LOGE("mixbuffer allocate - out of memory");
goto failed; goto failed;
@@ -595,10 +587,9 @@ failed:
return -1; return -1;
} }
static int static int openslES_OpenDevice(_THIS, const char *devname)
openslES_OpenDevice(_THIS, const char *devname)
{ {
this->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, (sizeof *this->hidden)); this->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, (sizeof *this->hidden));
if (this->hidden == NULL) { if (this->hidden == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -624,12 +615,10 @@ openslES_OpenDevice(_THIS, const char *devname)
} else { } else {
return SDL_SetError("Open device failed!"); return SDL_SetError("Open device failed!");
} }
} }
} }
static void static void openslES_WaitDevice(_THIS)
openslES_WaitDevice(_THIS)
{ {
struct SDL_PrivateAudioData *audiodata = this->hidden; struct SDL_PrivateAudioData *audiodata = this->hidden;
@@ -639,8 +628,7 @@ openslES_WaitDevice(_THIS)
SDL_SemWait(audiodata->playsem); SDL_SemWait(audiodata->playsem);
} }
static void static void openslES_PlayDevice(_THIS)
openslES_PlayDevice(_THIS)
{ {
struct SDL_PrivateAudioData *audiodata = this->hidden; struct SDL_PrivateAudioData *audiodata = this->hidden;
SLresult result; SLresult result;
@@ -674,8 +662,7 @@ openslES_PlayDevice(_THIS)
/* */ /* */
/* okay.. */ /* okay.. */
static Uint8 * static Uint8 *openslES_GetDeviceBuf(_THIS)
openslES_GetDeviceBuf(_THIS)
{ {
struct SDL_PrivateAudioData *audiodata = this->hidden; struct SDL_PrivateAudioData *audiodata = this->hidden;
@@ -683,8 +670,7 @@ openslES_GetDeviceBuf(_THIS)
return audiodata->pmixbuff[audiodata->next_buffer]; return audiodata->pmixbuff[audiodata->next_buffer];
} }
static int static int openslES_CaptureFromDevice(_THIS, void *buffer, int buflen)
openslES_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
struct SDL_PrivateAudioData *audiodata = this->hidden; struct SDL_PrivateAudioData *audiodata = this->hidden;
SLresult result; SLresult result;
@@ -711,8 +697,7 @@ openslES_CaptureFromDevice(_THIS, void *buffer, int buflen)
return this->spec.size; return this->spec.size;
} }
static void static void openslES_CloseDevice(_THIS)
openslES_CloseDevice(_THIS)
{ {
/* struct SDL_PrivateAudioData *audiodata = this->hidden; */ /* struct SDL_PrivateAudioData *audiodata = this->hidden; */
@@ -727,8 +712,7 @@ openslES_CloseDevice(_THIS)
SDL_free(this->hidden); SDL_free(this->hidden);
} }
static SDL_bool static SDL_bool openslES_Init(SDL_AudioDriverImpl *impl)
openslES_Init(SDL_AudioDriverImpl * impl)
{ {
LOGI("openslES_Init() called"); LOGI("openslES_Init() called");

View File

@@ -123,8 +123,7 @@ static int pipewire_version_patch;
static const char *pipewire_library = SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC; static const char *pipewire_library = SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC;
static void *pipewire_handle = NULL; static void *pipewire_handle = NULL;
static int static int pipewire_dlsym(const char *fn, void **addr)
pipewire_dlsym(const char *fn, void **addr)
{ {
*addr = SDL_LoadFunction(pipewire_handle, fn); *addr = SDL_LoadFunction(pipewire_handle, fn);
if (*addr == NULL) { if (*addr == NULL) {
@@ -140,8 +139,7 @@ pipewire_dlsym(const char *fn, void **addr)
return -1; \ return -1; \
} }
static int static int load_pipewire_library()
load_pipewire_library()
{ {
if ((pipewire_handle = SDL_LoadObject(pipewire_library))) { if ((pipewire_handle = SDL_LoadObject(pipewire_library))) {
return 0; return 0;
@@ -150,8 +148,7 @@ load_pipewire_library()
return -1; return -1;
} }
static void static void unload_pipewire_library()
unload_pipewire_library()
{ {
if (pipewire_handle) { if (pipewire_handle) {
SDL_UnloadObject(pipewire_handle); SDL_UnloadObject(pipewire_handle);
@@ -163,21 +160,18 @@ unload_pipewire_library()
#define SDL_PIPEWIRE_SYM(x) PIPEWIRE_##x = x #define SDL_PIPEWIRE_SYM(x) PIPEWIRE_##x = x
static int static int load_pipewire_library()
load_pipewire_library()
{ {
return 0; return 0;
} }
static void static void unload_pipewire_library()
unload_pipewire_library()
{ /* Nothing to do */ { /* Nothing to do */
} }
#endif /* SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC */ #endif /* SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC */
static int static int load_pipewire_syms()
load_pipewire_syms()
{ {
SDL_PIPEWIRE_SYM(pw_get_library_version); SDL_PIPEWIRE_SYM(pw_get_library_version);
SDL_PIPEWIRE_SYM(pw_init); SDL_PIPEWIRE_SYM(pw_init);
@@ -219,8 +213,7 @@ pipewire_version_at_least(int major, int minor, int patch)
(pipewire_version_major > major || pipewire_version_minor > minor || pipewire_version_patch >= patch); (pipewire_version_major > major || pipewire_version_minor > minor || pipewire_version_patch >= patch);
} }
static int static int init_pipewire_library()
init_pipewire_library()
{ {
if (!load_pipewire_library()) { if (!load_pipewire_library()) {
if (!load_pipewire_syms()) { if (!load_pipewire_syms()) {
@@ -242,8 +235,7 @@ init_pipewire_library()
return -1; return -1;
} }
static void static void deinit_pipewire_library()
deinit_pipewire_library()
{ {
PIPEWIRE_pw_deinit(); PIPEWIRE_pw_deinit();
unload_pipewire_library(); unload_pipewire_library();
@@ -304,8 +296,7 @@ static char *pipewire_default_sink_id = NULL;
static char *pipewire_default_source_id = NULL; static char *pipewire_default_source_id = NULL;
/* The active node list */ /* The active node list */
static SDL_bool static SDL_bool io_list_check_add(struct io_node *node)
io_list_check_add(struct io_node *node)
{ {
struct io_node *n; struct io_node *n;
SDL_bool ret = SDL_TRUE; SDL_bool ret = SDL_TRUE;
@@ -330,8 +321,7 @@ dup_found:
return ret; return ret;
} }
static void static void io_list_remove(Uint32 id)
io_list_remove(Uint32 id)
{ {
struct io_node *n, *temp; struct io_node *n, *temp;
@@ -351,8 +341,7 @@ io_list_remove(Uint32 id)
} }
} }
static void static void io_list_sort()
io_list_sort()
{ {
struct io_node *default_sink = NULL, *default_source = NULL; struct io_node *default_sink = NULL, *default_source = NULL;
struct io_node *n, *temp; struct io_node *n, *temp;
@@ -377,8 +366,7 @@ io_list_sort()
} }
} }
static void static void io_list_clear()
io_list_clear()
{ {
struct io_node *n, *temp; struct io_node *n, *temp;
@@ -388,7 +376,7 @@ io_list_clear()
} }
} }
static struct io_node* static struct io_node *
io_list_get_by_id(Uint32 id) io_list_get_by_id(Uint32 id)
{ {
struct io_node *n, *temp; struct io_node *n, *temp;
@@ -400,7 +388,7 @@ io_list_get_by_id(Uint32 id)
return NULL; return NULL;
} }
static struct io_node* static struct io_node *
io_list_get_by_path(char *path) io_list_get_by_path(char *path)
{ {
struct io_node *n, *temp; struct io_node *n, *temp;
@@ -412,8 +400,7 @@ io_list_get_by_path(char *path)
return NULL; return NULL;
} }
static void static void node_object_destroy(struct node_object *node)
node_object_destroy(struct node_object *node)
{ {
SDL_assert(node); SDL_assert(node);
@@ -425,15 +412,13 @@ node_object_destroy(struct node_object *node)
} }
/* The pending node list */ /* The pending node list */
static void static void pending_list_add(struct node_object *node)
pending_list_add(struct node_object *node)
{ {
SDL_assert(node); SDL_assert(node);
spa_list_append(&hotplug_pending_list, &node->link); spa_list_append(&hotplug_pending_list, &node->link);
} }
static void static void pending_list_remove(Uint32 id)
pending_list_remove(Uint32 id)
{ {
struct node_object *node, *temp; struct node_object *node, *temp;
@@ -444,8 +429,7 @@ pending_list_remove(Uint32 id)
} }
} }
static void static void pending_list_clear()
pending_list_clear()
{ {
struct node_object *node, *temp; struct node_object *node, *temp;
@@ -454,8 +438,7 @@ pending_list_clear()
} }
} }
static void * static void *node_object_new(Uint32 id, const char *type, Uint32 version, const void *funcs, const struct pw_core_events *core_events)
node_object_new(Uint32 id, const char *type, Uint32 version, const void *funcs, const struct pw_core_events *core_events)
{ {
struct pw_proxy *proxy; struct pw_proxy *proxy;
struct node_object *node; struct node_object *node;
@@ -484,8 +467,7 @@ node_object_new(Uint32 id, const char *type, Uint32 version, const void *funcs,
} }
/* Core sync points */ /* Core sync points */
static void static void core_events_hotplug_init_callback(void *object, uint32_t id, int seq)
core_events_hotplug_init_callback(void *object, uint32_t id, int seq)
{ {
if (id == PW_ID_CORE && seq == hotplug_init_seq_val) { if (id == PW_ID_CORE && seq == hotplug_init_seq_val) {
/* This core listener is no longer needed. */ /* This core listener is no longer needed. */
@@ -497,8 +479,7 @@ core_events_hotplug_init_callback(void *object, uint32_t id, int seq)
} }
} }
static void static void core_events_interface_callback(void *object, uint32_t id, int seq)
core_events_interface_callback(void *object, uint32_t id, int seq)
{ {
struct node_object *node = object; struct node_object *node = object;
struct io_node *io = node->userdata; struct io_node *io = node->userdata;
@@ -516,8 +497,7 @@ core_events_interface_callback(void *object, uint32_t id, int seq)
} }
} }
static void static void core_events_metadata_callback(void *object, uint32_t id, int seq)
core_events_metadata_callback(void *object, uint32_t id, int seq)
{ {
struct node_object *node = object; struct node_object *node = object;
@@ -530,8 +510,7 @@ static const struct pw_core_events hotplug_init_core_events = { PW_VERSION_CORE_
static const struct pw_core_events interface_core_events = { PW_VERSION_CORE_EVENTS, .done = core_events_interface_callback }; static const struct pw_core_events interface_core_events = { PW_VERSION_CORE_EVENTS, .done = core_events_interface_callback };
static const struct pw_core_events metadata_core_events = { PW_VERSION_CORE_EVENTS, .done = core_events_metadata_callback }; static const struct pw_core_events metadata_core_events = { PW_VERSION_CORE_EVENTS, .done = core_events_metadata_callback };
static void static void hotplug_core_sync(struct node_object *node)
hotplug_core_sync(struct node_object *node)
{ {
/* /*
* Node sync events *must* come before the hotplug init sync events or the initial * Node sync events *must* come before the hotplug init sync events or the initial
@@ -547,8 +526,7 @@ hotplug_core_sync(struct node_object *node)
} }
/* Helpers for retrieving values from params */ /* Helpers for retrieving values from params */
static SDL_bool static SDL_bool get_range_param(const struct spa_pod *param, Uint32 key, int *def, int *min, int *max)
get_range_param(const struct spa_pod *param, Uint32 key, int *def, int *min, int *max)
{ {
const struct spa_pod_prop *prop; const struct spa_pod_prop *prop;
struct spa_pod *value; struct spa_pod *value;
@@ -581,8 +559,7 @@ get_range_param(const struct spa_pod *param, Uint32 key, int *def, int *min, int
return SDL_FALSE; return SDL_FALSE;
} }
static SDL_bool static SDL_bool get_int_param(const struct spa_pod *param, Uint32 key, int *val)
get_int_param(const struct spa_pod *param, Uint32 key, int *val)
{ {
const struct spa_pod_prop *prop; const struct spa_pod_prop *prop;
Sint32 v; Sint32 v;
@@ -601,8 +578,7 @@ get_int_param(const struct spa_pod *param, Uint32 key, int *val)
} }
/* Interface node callbacks */ /* Interface node callbacks */
static void static void node_event_info(void *object, const struct pw_node_info *info)
node_event_info(void *object, const struct pw_node_info *info)
{ {
struct node_object *node = object; struct node_object *node = object;
struct io_node *io = node->userdata; struct io_node *io = node->userdata;
@@ -624,8 +600,7 @@ node_event_info(void *object, const struct pw_node_info *info)
} }
} }
static void static void node_event_param(void *object, int seq, uint32_t id, uint32_t index, uint32_t next, const struct spa_pod *param)
node_event_param(void *object, int seq, uint32_t id, uint32_t index, uint32_t next, const struct spa_pod *param)
{ {
struct node_object *node = object; struct node_object *node = object;
struct io_node *io = node->userdata; struct io_node *io = node->userdata;
@@ -650,8 +625,7 @@ node_event_param(void *object, int seq, uint32_t id, uint32_t index, uint32_t ne
static const struct pw_node_events interface_node_events = { PW_VERSION_NODE_EVENTS, .info = node_event_info, static const struct pw_node_events interface_node_events = { PW_VERSION_NODE_EVENTS, .info = node_event_info,
.param = node_event_param }; .param = node_event_param };
static char* static char *get_name_from_json(const char *json)
get_name_from_json(const char *json)
{ {
struct spa_json parser[2]; struct spa_json parser[2];
char key[7]; /* "name" */ char key[7]; /* "name" */
@@ -673,8 +647,7 @@ get_name_from_json(const char *json)
} }
/* Metadata node callback */ /* Metadata node callback */
static int static int metadata_property(void *object, Uint32 subject, const char *key, const char *type, const char *value)
metadata_property(void *object, Uint32 subject, const char *key, const char *type, const char *value)
{ {
struct node_object *node = object; struct node_object *node = object;
@@ -700,8 +673,7 @@ metadata_property(void *object, Uint32 subject, const char *key, const char *typ
static const struct pw_metadata_events metadata_node_events = { PW_VERSION_METADATA_EVENTS, .property = metadata_property }; static const struct pw_metadata_events metadata_node_events = { PW_VERSION_METADATA_EVENTS, .property = metadata_property };
/* Global registry callbacks */ /* Global registry callbacks */
static void static void registry_event_global_callback(void *object, uint32_t id, uint32_t permissions, const char *type, uint32_t version,
registry_event_global_callback(void *object, uint32_t id, uint32_t permissions, const char *type, uint32_t version,
const struct spa_dict *props) const struct spa_dict *props)
{ {
struct node_object *node; struct node_object *node;
@@ -772,8 +744,7 @@ registry_event_global_callback(void *object, uint32_t id, uint32_t permissions,
} }
} }
static void static void registry_event_remove_callback(void *object, uint32_t id)
registry_event_remove_callback(void *object, uint32_t id)
{ {
io_list_remove(id); io_list_remove(id);
pending_list_remove(id); pending_list_remove(id);
@@ -783,8 +754,7 @@ static const struct pw_registry_events registry_events = { PW_VERSION_REGISTRY_E
.global_remove = registry_event_remove_callback }; .global_remove = registry_event_remove_callback };
/* The hotplug thread */ /* The hotplug thread */
static int static int hotplug_loop_init()
hotplug_loop_init()
{ {
int res; int res;
@@ -827,8 +797,7 @@ hotplug_loop_init()
return 0; return 0;
} }
static void static void hotplug_loop_destroy()
hotplug_loop_destroy()
{ {
if (hotplug_loop) { if (hotplug_loop) {
PIPEWIRE_pw_thread_loop_stop(hotplug_loop); PIPEWIRE_pw_thread_loop_stop(hotplug_loop);
@@ -870,8 +839,7 @@ hotplug_loop_destroy()
} }
} }
static void static void PIPEWIRE_DetectDevices()
PIPEWIRE_DetectDevices()
{ {
struct io_node *io; struct io_node *io;
@@ -913,8 +881,7 @@ static const enum spa_audio_channel PIPEWIRE_channel_map_8[] = { SPA_AUDIO_CHANN
#define COPY_CHANNEL_MAP(c) SDL_memcpy(info->position, PIPEWIRE_channel_map_##c, sizeof(PIPEWIRE_channel_map_##c)) #define COPY_CHANNEL_MAP(c) SDL_memcpy(info->position, PIPEWIRE_channel_map_##c, sizeof(PIPEWIRE_channel_map_##c))
static void static void initialize_spa_info(const SDL_AudioSpec *spec, struct spa_audio_info_raw *info)
initialize_spa_info(const SDL_AudioSpec *spec, struct spa_audio_info_raw *info)
{ {
info->channels = spec->channels; info->channels = spec->channels;
info->rate = spec->freq; info->rate = spec->freq;
@@ -981,8 +948,7 @@ initialize_spa_info(const SDL_AudioSpec *spec, struct spa_audio_info_raw *info)
} }
} }
static void static void output_callback(void *data)
output_callback(void *data)
{ {
struct pw_buffer *pw_buf; struct pw_buffer *pw_buf;
struct spa_buffer *spa_buf; struct spa_buffer *spa_buf;
@@ -1047,8 +1013,7 @@ output_callback(void *data)
PIPEWIRE_pw_stream_queue_buffer(stream, pw_buf); PIPEWIRE_pw_stream_queue_buffer(stream, pw_buf);
} }
static void static void input_callback(void *data)
input_callback(void *data)
{ {
struct pw_buffer *pw_buf; struct pw_buffer *pw_buf;
struct spa_buffer *spa_buf; struct spa_buffer *spa_buf;
@@ -1103,8 +1068,7 @@ input_callback(void *data)
PIPEWIRE_pw_stream_queue_buffer(stream, pw_buf); PIPEWIRE_pw_stream_queue_buffer(stream, pw_buf);
} }
static void static void stream_add_buffer_callback(void *data, struct pw_buffer *buffer)
stream_add_buffer_callback(void *data, struct pw_buffer *buffer)
{ {
_THIS = data; _THIS = data;
@@ -1134,8 +1098,7 @@ stream_add_buffer_callback(void *data, struct pw_buffer *buffer)
PIPEWIRE_pw_thread_loop_signal(this->hidden->loop, false); PIPEWIRE_pw_thread_loop_signal(this->hidden->loop, false);
} }
static void static void stream_state_changed_callback(void *data, enum pw_stream_state old, enum pw_stream_state state, const char *error)
stream_state_changed_callback(void *data, enum pw_stream_state old, enum pw_stream_state state, const char *error)
{ {
_THIS = data; _THIS = data;
@@ -1157,8 +1120,7 @@ static const struct pw_stream_events stream_input_events = { PW_VERSION_STREAM_
.add_buffer = stream_add_buffer_callback, .add_buffer = stream_add_buffer_callback,
.process = input_callback }; .process = input_callback };
static int static int PIPEWIRE_OpenDevice(_THIS, const char *devname)
PIPEWIRE_OpenDevice(_THIS, const char *devname)
{ {
/* /*
* NOTE: The PW_STREAM_FLAG_RT_PROCESS flag can be set to call the stream * NOTE: The PW_STREAM_FLAG_RT_PROCESS flag can be set to call the stream
@@ -1341,8 +1303,7 @@ static void PIPEWIRE_CloseDevice(_THIS)
SDL_free(this->hidden); SDL_free(this->hidden);
} }
static int static int PIPEWIRE_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
PIPEWIRE_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
{ {
struct io_node *node; struct io_node *node;
char *target; char *target;
@@ -1380,8 +1341,7 @@ failed:
return ret; return ret;
} }
static void static void PIPEWIRE_Deinitialize()
PIPEWIRE_Deinitialize()
{ {
if (pipewire_initialized) { if (pipewire_initialized) {
hotplug_loop_destroy(); hotplug_loop_destroy();
@@ -1390,8 +1350,7 @@ PIPEWIRE_Deinitialize()
} }
} }
static SDL_bool static SDL_bool PIPEWIRE_Init(SDL_AudioDriverImpl *impl)
PIPEWIRE_Init(SDL_AudioDriverImpl *impl)
{ {
if (!pipewire_initialized) { if (!pipewire_initialized) {
if (init_pipewire_library() < 0) { if (init_pipewire_library() < 0) {

View File

@@ -33,8 +33,7 @@
/* The tag name used by PS2 audio */ /* The tag name used by PS2 audio */
#define PS2AUDIO_DRIVER_NAME "ps2" #define PS2AUDIO_DRIVER_NAME "ps2"
static int static int PS2AUDIO_OpenDevice(_THIS, const char *devname)
PS2AUDIO_OpenDevice(_THIS, const char *devname)
{ {
int i, mixlen; int i, mixlen;
struct audsrv_fmt_t format; struct audsrv_fmt_t format;
@@ -46,7 +45,6 @@ PS2AUDIO_OpenDevice(_THIS, const char *devname)
} }
SDL_zerop(this->hidden); SDL_zerop(this->hidden);
/* These are the native supported audio PS2 configs */ /* These are the native supported audio PS2 configs */
switch (this->spec.freq) { switch (this->spec.freq) {
case 11025: case 11025:
@@ -89,7 +87,7 @@ PS2AUDIO_OpenDevice(_THIS, const char *devname)
be a multiple of 64 bytes. Our sample count is already a multiple of be a multiple of 64 bytes. Our sample count is already a multiple of
64, so spec->size should be a multiple of 64 as well. */ 64, so spec->size should be a multiple of 64 as well. */
mixlen = this->spec.size * NUM_BUFFERS; mixlen = this->spec.size * NUM_BUFFERS;
this->hidden->rawbuf = (Uint8 *) memalign(64, mixlen); this->hidden->rawbuf = (Uint8 *)memalign(64, mixlen);
if (this->hidden->rawbuf == NULL) { if (this->hidden->rawbuf == NULL) {
return SDL_SetError("Couldn't allocate mixing buffer"); return SDL_SetError("Couldn't allocate mixing buffer");
} }
@@ -152,7 +150,7 @@ static void PS2AUDIO_Deinitialize(void)
deinit_audio_driver(); deinit_audio_driver();
} }
static SDL_bool PS2AUDIO_Init(SDL_AudioDriverImpl * impl) static SDL_bool PS2AUDIO_Init(SDL_AudioDriverImpl *impl)
{ {
if (init_audio_driver() < 0) { if (init_audio_driver() < 0) {
return SDL_FALSE; return SDL_FALSE;

View File

@@ -38,8 +38,7 @@
/* The tag name used by PSP audio */ /* The tag name used by PSP audio */
#define PSPAUDIO_DRIVER_NAME "psp" #define PSPAUDIO_DRIVER_NAME "psp"
static int static int PSPAUDIO_OpenDevice(_THIS, const char *devname)
PSPAUDIO_OpenDevice(_THIS, const char *devname)
{ {
int format, mixlen, i; int format, mixlen, i;
@@ -86,7 +85,7 @@ PSPAUDIO_OpenDevice(_THIS, const char *devname)
be a multiple of 64 bytes. Our sample count is already a multiple of be a multiple of 64 bytes. Our sample count is already a multiple of
64, so spec->size should be a multiple of 64 as well. */ 64, so spec->size should be a multiple of 64 as well. */
mixlen = this->spec.size * NUM_BUFFERS; mixlen = this->spec.size * NUM_BUFFERS;
this->hidden->rawbuf = (Uint8 *) memalign(64, mixlen); this->hidden->rawbuf = (Uint8 *)memalign(64, mixlen);
if (this->hidden->rawbuf == NULL) { if (this->hidden->rawbuf == NULL) {
return SDL_SetError("Couldn't allocate mixing buffer"); return SDL_SetError("Couldn't allocate mixing buffer");
} }
@@ -155,8 +154,7 @@ static void PSPAUDIO_ThreadInit(_THIS)
} }
} }
static SDL_bool static SDL_bool PSPAUDIO_Init(SDL_AudioDriverImpl *impl)
PSPAUDIO_Init(SDL_AudioDriverImpl * impl)
{ {
/* Set the function pointers */ /* Set the function pointers */
impl->OpenDevice = PSPAUDIO_OpenDevice; impl->OpenDevice = PSPAUDIO_OpenDevice;

View File

@@ -29,7 +29,8 @@
#define NUM_BUFFERS 2 #define NUM_BUFFERS 2
struct SDL_PrivateAudioData { struct SDL_PrivateAudioData
{
/* The hardware output channel. */ /* The hardware output channel. */
int channel; int channel;
/* The raw allocated mixing buffer. */ /* The raw allocated mixing buffer. */

View File

@@ -45,81 +45,79 @@
/* should we include monitors in the device list? Set at SDL_Init time */ /* should we include monitors in the device list? Set at SDL_Init time */
static SDL_bool include_monitors = SDL_FALSE; static SDL_bool include_monitors = SDL_FALSE;
#if (PA_API_VERSION < 12) #if (PA_API_VERSION < 12)
/** Return non-zero if the passed state is one of the connected states */ /** Return non-zero if the passed state is one of the connected states */
static SDL_INLINE int PA_CONTEXT_IS_GOOD(pa_context_state_t x) { static SDL_INLINE int PA_CONTEXT_IS_GOOD(pa_context_state_t x)
{
return x == PA_CONTEXT_CONNECTING || x == PA_CONTEXT_AUTHORIZING || x == PA_CONTEXT_SETTING_NAME || x == PA_CONTEXT_READY; return x == PA_CONTEXT_CONNECTING || x == PA_CONTEXT_AUTHORIZING || x == PA_CONTEXT_SETTING_NAME || x == PA_CONTEXT_READY;
} }
/** Return non-zero if the passed state is one of the connected states */ /** Return non-zero if the passed state is one of the connected states */
static SDL_INLINE int PA_STREAM_IS_GOOD(pa_stream_state_t x) { static SDL_INLINE int PA_STREAM_IS_GOOD(pa_stream_state_t x)
{
return x == PA_STREAM_CREATING || x == PA_STREAM_READY; return x == PA_STREAM_CREATING || x == PA_STREAM_READY;
} }
#endif /* pulseaudio <= 0.9.10 */ #endif /* pulseaudio <= 0.9.10 */
static const char *(*PULSEAUDIO_pa_get_library_version)(void);
static const char *(*PULSEAUDIO_pa_get_library_version) (void); static pa_channel_map *(*PULSEAUDIO_pa_channel_map_init_auto)(
static pa_channel_map *(*PULSEAUDIO_pa_channel_map_init_auto) (
pa_channel_map *, unsigned, pa_channel_map_def_t); pa_channel_map *, unsigned, pa_channel_map_def_t);
static const char * (*PULSEAUDIO_pa_strerror) (int); static const char *(*PULSEAUDIO_pa_strerror)(int);
static pa_mainloop * (*PULSEAUDIO_pa_mainloop_new) (void); static pa_mainloop *(*PULSEAUDIO_pa_mainloop_new)(void);
static pa_mainloop_api * (*PULSEAUDIO_pa_mainloop_get_api) (pa_mainloop *); static pa_mainloop_api *(*PULSEAUDIO_pa_mainloop_get_api)(pa_mainloop *);
static int (*PULSEAUDIO_pa_mainloop_iterate) (pa_mainloop *, int, int *); static int (*PULSEAUDIO_pa_mainloop_iterate)(pa_mainloop *, int, int *);
static int (*PULSEAUDIO_pa_mainloop_run) (pa_mainloop *, int *); static int (*PULSEAUDIO_pa_mainloop_run)(pa_mainloop *, int *);
static void (*PULSEAUDIO_pa_mainloop_quit) (pa_mainloop *, int); static void (*PULSEAUDIO_pa_mainloop_quit)(pa_mainloop *, int);
static void (*PULSEAUDIO_pa_mainloop_free) (pa_mainloop *); static void (*PULSEAUDIO_pa_mainloop_free)(pa_mainloop *);
static pa_operation_state_t (*PULSEAUDIO_pa_operation_get_state) ( static pa_operation_state_t (*PULSEAUDIO_pa_operation_get_state)(
const pa_operation *); const pa_operation *);
static void (*PULSEAUDIO_pa_operation_cancel) (pa_operation *); static void (*PULSEAUDIO_pa_operation_cancel)(pa_operation *);
static void (*PULSEAUDIO_pa_operation_unref) (pa_operation *); static void (*PULSEAUDIO_pa_operation_unref)(pa_operation *);
static pa_context * (*PULSEAUDIO_pa_context_new) (pa_mainloop_api *, static pa_context *(*PULSEAUDIO_pa_context_new)(pa_mainloop_api *,
const char *); const char *);
static int (*PULSEAUDIO_pa_context_connect) (pa_context *, const char *, static int (*PULSEAUDIO_pa_context_connect)(pa_context *, const char *,
pa_context_flags_t, const pa_spawn_api *); pa_context_flags_t, const pa_spawn_api *);
static pa_operation * (*PULSEAUDIO_pa_context_get_sink_info_list) (pa_context *, pa_sink_info_cb_t, void *); static pa_operation *(*PULSEAUDIO_pa_context_get_sink_info_list)(pa_context *, pa_sink_info_cb_t, void *);
static pa_operation * (*PULSEAUDIO_pa_context_get_source_info_list) (pa_context *, pa_source_info_cb_t, void *); static pa_operation *(*PULSEAUDIO_pa_context_get_source_info_list)(pa_context *, pa_source_info_cb_t, void *);
static pa_operation * (*PULSEAUDIO_pa_context_get_sink_info_by_index) (pa_context *, uint32_t, pa_sink_info_cb_t, void *); static pa_operation *(*PULSEAUDIO_pa_context_get_sink_info_by_index)(pa_context *, uint32_t, pa_sink_info_cb_t, void *);
static pa_operation * (*PULSEAUDIO_pa_context_get_source_info_by_index) (pa_context *, uint32_t, pa_source_info_cb_t, void *); static pa_operation *(*PULSEAUDIO_pa_context_get_source_info_by_index)(pa_context *, uint32_t, pa_source_info_cb_t, void *);
static pa_context_state_t (*PULSEAUDIO_pa_context_get_state) (const pa_context *); static pa_context_state_t (*PULSEAUDIO_pa_context_get_state)(const pa_context *);
static pa_operation * (*PULSEAUDIO_pa_context_subscribe) (pa_context *, pa_subscription_mask_t, pa_context_success_cb_t, void *); static pa_operation *(*PULSEAUDIO_pa_context_subscribe)(pa_context *, pa_subscription_mask_t, pa_context_success_cb_t, void *);
static void (*PULSEAUDIO_pa_context_set_subscribe_callback) (pa_context *, pa_context_subscribe_cb_t, void *); static void (*PULSEAUDIO_pa_context_set_subscribe_callback)(pa_context *, pa_context_subscribe_cb_t, void *);
static void (*PULSEAUDIO_pa_context_disconnect) (pa_context *); static void (*PULSEAUDIO_pa_context_disconnect)(pa_context *);
static void (*PULSEAUDIO_pa_context_unref) (pa_context *); static void (*PULSEAUDIO_pa_context_unref)(pa_context *);
static pa_stream * (*PULSEAUDIO_pa_stream_new) (pa_context *, const char *, static pa_stream *(*PULSEAUDIO_pa_stream_new)(pa_context *, const char *,
const pa_sample_spec *, const pa_channel_map *); const pa_sample_spec *, const pa_channel_map *);
static int (*PULSEAUDIO_pa_stream_connect_playback) (pa_stream *, const char *, static int (*PULSEAUDIO_pa_stream_connect_playback)(pa_stream *, const char *,
const pa_buffer_attr *, pa_stream_flags_t, const pa_cvolume *, pa_stream *); const pa_buffer_attr *, pa_stream_flags_t, const pa_cvolume *, pa_stream *);
static int (*PULSEAUDIO_pa_stream_connect_record) (pa_stream *, const char *, static int (*PULSEAUDIO_pa_stream_connect_record)(pa_stream *, const char *,
const pa_buffer_attr *, pa_stream_flags_t); const pa_buffer_attr *, pa_stream_flags_t);
static pa_stream_state_t (*PULSEAUDIO_pa_stream_get_state) (const pa_stream *); static pa_stream_state_t (*PULSEAUDIO_pa_stream_get_state)(const pa_stream *);
static size_t (*PULSEAUDIO_pa_stream_writable_size) (const pa_stream *); static size_t (*PULSEAUDIO_pa_stream_writable_size)(const pa_stream *);
static size_t (*PULSEAUDIO_pa_stream_readable_size) (const pa_stream *); static size_t (*PULSEAUDIO_pa_stream_readable_size)(const pa_stream *);
static int (*PULSEAUDIO_pa_stream_write) (pa_stream *, const void *, size_t, static int (*PULSEAUDIO_pa_stream_write)(pa_stream *, const void *, size_t,
pa_free_cb_t, int64_t, pa_seek_mode_t); pa_free_cb_t, int64_t, pa_seek_mode_t);
static pa_operation * (*PULSEAUDIO_pa_stream_drain) (pa_stream *, static pa_operation *(*PULSEAUDIO_pa_stream_drain)(pa_stream *,
pa_stream_success_cb_t, void *); pa_stream_success_cb_t, void *);
static int (*PULSEAUDIO_pa_stream_peek) (pa_stream *, const void **, size_t *); static int (*PULSEAUDIO_pa_stream_peek)(pa_stream *, const void **, size_t *);
static int (*PULSEAUDIO_pa_stream_drop) (pa_stream *); static int (*PULSEAUDIO_pa_stream_drop)(pa_stream *);
static pa_operation * (*PULSEAUDIO_pa_stream_flush) (pa_stream *, static pa_operation *(*PULSEAUDIO_pa_stream_flush)(pa_stream *,
pa_stream_success_cb_t, void *); pa_stream_success_cb_t, void *);
static int (*PULSEAUDIO_pa_stream_disconnect) (pa_stream *); static int (*PULSEAUDIO_pa_stream_disconnect)(pa_stream *);
static void (*PULSEAUDIO_pa_stream_unref) (pa_stream *); static void (*PULSEAUDIO_pa_stream_unref)(pa_stream *);
static void (*PULSEAUDIO_pa_stream_set_write_callback)(pa_stream *, pa_stream_request_cb_t, void *); static void (*PULSEAUDIO_pa_stream_set_write_callback)(pa_stream *, pa_stream_request_cb_t, void *);
static pa_operation * (*PULSEAUDIO_pa_context_get_server_info)(pa_context *, pa_server_info_cb_t, void *); static pa_operation *(*PULSEAUDIO_pa_context_get_server_info)(pa_context *, pa_server_info_cb_t, void *);
static int load_pulseaudio_syms(void); static int load_pulseaudio_syms(void);
#ifdef SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC #ifdef SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC
static const char *pulseaudio_library = SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC; static const char *pulseaudio_library = SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC;
static void *pulseaudio_handle = NULL; static void *pulseaudio_handle = NULL;
static int static int load_pulseaudio_sym(const char *fn, void **addr)
load_pulseaudio_sym(const char *fn, void **addr)
{ {
*addr = SDL_LoadFunction(pulseaudio_handle, fn); *addr = SDL_LoadFunction(pulseaudio_handle, fn);
if (*addr == NULL) { if (*addr == NULL) {
@@ -132,10 +130,10 @@ load_pulseaudio_sym(const char *fn, void **addr)
/* cast funcs to char* first, to please GCC's strict aliasing rules. */ /* cast funcs to char* first, to please GCC's strict aliasing rules. */
#define SDL_PULSEAUDIO_SYM(x) \ #define SDL_PULSEAUDIO_SYM(x) \
if (!load_pulseaudio_sym(#x, (void **) (char *) &PULSEAUDIO_##x)) return -1 if (!load_pulseaudio_sym(#x, (void **)(char *)&PULSEAUDIO_##x)) \
return -1
static void static void UnloadPulseAudioLibrary(void)
UnloadPulseAudioLibrary(void)
{ {
if (pulseaudio_handle != NULL) { if (pulseaudio_handle != NULL) {
SDL_UnloadObject(pulseaudio_handle); SDL_UnloadObject(pulseaudio_handle);
@@ -143,8 +141,7 @@ UnloadPulseAudioLibrary(void)
} }
} }
static int static int LoadPulseAudioLibrary(void)
LoadPulseAudioLibrary(void)
{ {
int retval = 0; int retval = 0;
if (pulseaudio_handle == NULL) { if (pulseaudio_handle == NULL) {
@@ -166,13 +163,11 @@ LoadPulseAudioLibrary(void)
#define SDL_PULSEAUDIO_SYM(x) PULSEAUDIO_##x = x #define SDL_PULSEAUDIO_SYM(x) PULSEAUDIO_##x = x
static void static void UnloadPulseAudioLibrary(void)
UnloadPulseAudioLibrary(void)
{ {
} }
static int static int LoadPulseAudioLibrary(void)
LoadPulseAudioLibrary(void)
{ {
load_pulseaudio_syms(); load_pulseaudio_syms();
return 0; return 0;
@@ -180,9 +175,7 @@ LoadPulseAudioLibrary(void)
#endif /* SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC */ #endif /* SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC */
static int load_pulseaudio_syms(void)
static int
load_pulseaudio_syms(void)
{ {
SDL_PULSEAUDIO_SYM(pa_get_library_version); SDL_PULSEAUDIO_SYM(pa_get_library_version);
SDL_PULSEAUDIO_SYM(pa_mainloop_new); SDL_PULSEAUDIO_SYM(pa_mainloop_new);
@@ -225,15 +218,13 @@ load_pulseaudio_syms(void)
return 0; return 0;
} }
static SDL_INLINE int static SDL_INLINE int squashVersion(const int major, const int minor, const int patch)
squashVersion(const int major, const int minor, const int patch)
{ {
return ((major & 0xFF) << 16) | ((minor & 0xFF) << 8) | (patch & 0xFF); return ((major & 0xFF) << 16) | ((minor & 0xFF) << 8) | (patch & 0xFF);
} }
/* Workaround for older pulse: pa_context_new() must have non-NULL appname */ /* Workaround for older pulse: pa_context_new() must have non-NULL appname */
static const char * static const char *getAppName(void)
getAppName(void)
{ {
const char *retval = SDL_GetHint(SDL_HINT_AUDIO_DEVICE_APP_NAME); const char *retval = SDL_GetHint(SDL_HINT_AUDIO_DEVICE_APP_NAME);
if (retval && *retval) { if (retval && *retval) {
@@ -257,8 +248,7 @@ getAppName(void)
return retval; return retval;
} }
static void static void WaitForPulseOperation(pa_mainloop *mainloop, pa_operation *o)
WaitForPulseOperation(pa_mainloop *mainloop, pa_operation *o)
{ {
/* This checks for NO errors currently. Either fix that, check results elsewhere, or do things you don't care about. */ /* This checks for NO errors currently. Either fix that, check results elsewhere, or do things you don't care about. */
if (mainloop && o) { if (mainloop && o) {
@@ -270,8 +260,7 @@ WaitForPulseOperation(pa_mainloop *mainloop, pa_operation *o)
} }
} }
static void static void DisconnectFromPulseServer(pa_mainloop *mainloop, pa_context *context)
DisconnectFromPulseServer(pa_mainloop *mainloop, pa_context *context)
{ {
if (context) { if (context) {
PULSEAUDIO_pa_context_disconnect(context); PULSEAUDIO_pa_context_disconnect(context);
@@ -282,8 +271,7 @@ DisconnectFromPulseServer(pa_mainloop *mainloop, pa_context *context)
} }
} }
static int static int ConnectToPulseServer_Internal(pa_mainloop **_mainloop, pa_context **_context)
ConnectToPulseServer_Internal(pa_mainloop **_mainloop, pa_context **_context)
{ {
pa_mainloop *mainloop = NULL; pa_mainloop *mainloop = NULL;
pa_context *context = NULL; pa_context *context = NULL;
@@ -334,8 +322,7 @@ ConnectToPulseServer_Internal(pa_mainloop **_mainloop, pa_context **_context)
return 0; /* connected and ready! */ return 0; /* connected and ready! */
} }
static int static int ConnectToPulseServer(pa_mainloop **_mainloop, pa_context **_context)
ConnectToPulseServer(pa_mainloop **_mainloop, pa_context **_context)
{ {
const int retval = ConnectToPulseServer_Internal(_mainloop, _context); const int retval = ConnectToPulseServer_Internal(_mainloop, _context);
if (retval < 0) { if (retval < 0) {
@@ -344,23 +331,20 @@ ConnectToPulseServer(pa_mainloop **_mainloop, pa_context **_context)
return retval; return retval;
} }
/* This function waits until it is possible to write a full sound buffer */ /* This function waits until it is possible to write a full sound buffer */
static void static void PULSEAUDIO_WaitDevice(_THIS)
PULSEAUDIO_WaitDevice(_THIS)
{ {
/* this is a no-op; we wait in PULSEAUDIO_PlayDevice now. */ /* this is a no-op; we wait in PULSEAUDIO_PlayDevice now. */
} }
static void WriteCallback(pa_stream *p, size_t nbytes, void *userdata) static void WriteCallback(pa_stream *p, size_t nbytes, void *userdata)
{ {
struct SDL_PrivateAudioData *h = (struct SDL_PrivateAudioData *) userdata; struct SDL_PrivateAudioData *h = (struct SDL_PrivateAudioData *)userdata;
/*printf("PULSEAUDIO WRITE CALLBACK! nbytes=%u\n", (unsigned int) nbytes);*/ /*printf("PULSEAUDIO WRITE CALLBACK! nbytes=%u\n", (unsigned int) nbytes);*/
h->bytes_requested += nbytes; h->bytes_requested += nbytes;
} }
static void static void PULSEAUDIO_PlayDevice(_THIS)
PULSEAUDIO_PlayDevice(_THIS)
{ {
struct SDL_PrivateAudioData *h = this->hidden; struct SDL_PrivateAudioData *h = this->hidden;
int available = h->mixlen; int available = h->mixlen;
@@ -395,15 +379,12 @@ PULSEAUDIO_PlayDevice(_THIS)
/*printf("PULSEAUDIO PLAYDEVICE END! written=%d\n", written);*/ /*printf("PULSEAUDIO PLAYDEVICE END! written=%d\n", written);*/
} }
static Uint8 * static Uint8 *PULSEAUDIO_GetDeviceBuf(_THIS)
PULSEAUDIO_GetDeviceBuf(_THIS)
{ {
return this->hidden->mixbuf; return this->hidden->mixbuf;
} }
static int PULSEAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
static int
PULSEAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
struct SDL_PrivateAudioData *h = this->hidden; struct SDL_PrivateAudioData *h = this->hidden;
const void *data = NULL; const void *data = NULL;
@@ -437,12 +418,13 @@ PULSEAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
/* a new fragment is available! */ /* a new fragment is available! */
PULSEAUDIO_pa_stream_peek(h->stream, &data, &nbytes); PULSEAUDIO_pa_stream_peek(h->stream, &data, &nbytes);
SDL_assert(nbytes > 0); SDL_assert(nbytes > 0);
if (data == NULL) { /* NULL==buffer had a hole. Ignore that. */ /* If data == NULL, then the buffer had a hole, ignore that */
if (data == NULL) {
PULSEAUDIO_pa_stream_drop(h->stream); /* drop this fragment. */ PULSEAUDIO_pa_stream_drop(h->stream); /* drop this fragment. */
} else { } else {
/* store this fragment's data, start feeding it to SDL. */ /* store this fragment's data, start feeding it to SDL. */
/*printf("PULSEAUDIO: captured %d new bytes\n", (int) nbytes);*/ /*printf("PULSEAUDIO: captured %d new bytes\n", (int) nbytes);*/
h->capturebuf = (const Uint8 *) data; h->capturebuf = (const Uint8 *)data;
h->capturelen = nbytes; h->capturelen = nbytes;
} }
} }
@@ -450,8 +432,7 @@ PULSEAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
return -1; /* not enabled? */ return -1; /* not enabled? */
} }
static void static void PULSEAUDIO_FlushCapture(_THIS)
PULSEAUDIO_FlushCapture(_THIS)
{ {
struct SDL_PrivateAudioData *h = this->hidden; struct SDL_PrivateAudioData *h = this->hidden;
const void *data = NULL; const void *data = NULL;
@@ -481,8 +462,7 @@ PULSEAUDIO_FlushCapture(_THIS)
} }
} }
static void static void PULSEAUDIO_CloseDevice(_THIS)
PULSEAUDIO_CloseDevice(_THIS)
{ {
if (this->hidden->stream) { if (this->hidden->stream) {
if (this->hidden->capturebuf != NULL) { if (this->hidden->capturebuf != NULL) {
@@ -498,28 +478,25 @@ PULSEAUDIO_CloseDevice(_THIS)
SDL_free(this->hidden); SDL_free(this->hidden);
} }
static void static void SinkDeviceNameCallback(pa_context *c, const pa_sink_info *i, int is_last, void *data)
SinkDeviceNameCallback(pa_context *c, const pa_sink_info *i, int is_last, void *data)
{ {
if (i) { if (i) {
char **devname = (char **) data; char **devname = (char **)data;
*devname = SDL_strdup(i->name); *devname = SDL_strdup(i->name);
} }
} }
static void static void SourceDeviceNameCallback(pa_context *c, const pa_source_info *i, int is_last, void *data)
SourceDeviceNameCallback(pa_context *c, const pa_source_info *i, int is_last, void *data)
{ {
if (i) { if (i) {
char **devname = (char **) data; char **devname = (char **)data;
*devname = SDL_strdup(i->name); *devname = SDL_strdup(i->name);
} }
} }
static SDL_bool static SDL_bool FindDeviceName(struct SDL_PrivateAudioData *h, const SDL_bool iscapture, void *handle)
FindDeviceName(struct SDL_PrivateAudioData *h, const SDL_bool iscapture, void *handle)
{ {
const uint32_t idx = ((uint32_t) ((intptr_t) handle)) - 1; const uint32_t idx = ((uint32_t)((intptr_t)handle)) - 1;
if (handle == NULL) { /* NULL == default device. */ if (handle == NULL) { /* NULL == default device. */
return SDL_TRUE; return SDL_TRUE;
@@ -538,8 +515,7 @@ FindDeviceName(struct SDL_PrivateAudioData *h, const SDL_bool iscapture, void *h
return h->device_name != NULL; return h->device_name != NULL;
} }
static int static int PULSEAUDIO_OpenDevice(_THIS, const char *devname)
PULSEAUDIO_OpenDevice(_THIS, const char *devname)
{ {
struct SDL_PrivateAudioData *h = NULL; struct SDL_PrivateAudioData *h = NULL;
SDL_AudioFormat test_format; SDL_AudioFormat test_format;
@@ -604,7 +580,7 @@ PULSEAUDIO_OpenDevice(_THIS, const char *devname)
/* Allocate mixing buffer */ /* Allocate mixing buffer */
if (!iscapture) { if (!iscapture) {
h->mixlen = this->spec.size; h->mixlen = this->spec.size;
h->mixbuf = (Uint8 *) SDL_malloc(h->mixlen); h->mixbuf = (Uint8 *)SDL_malloc(h->mixlen);
if (h->mixbuf == NULL) { if (h->mixbuf == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -692,8 +668,7 @@ static char *default_source_name = NULL;
/* device handles are device index + 1, cast to void*, so we never pass a NULL. */ /* device handles are device index + 1, cast to void*, so we never pass a NULL. */
static SDL_AudioFormat static SDL_AudioFormat PulseFormatToSDLFormat(pa_sample_format_t format)
PulseFormatToSDLFormat(pa_sample_format_t format)
{ {
switch (format) { switch (format) {
case PA_SAMPLE_U8: case PA_SAMPLE_U8:
@@ -716,11 +691,10 @@ PulseFormatToSDLFormat(pa_sample_format_t format)
} }
/* This is called when PulseAudio adds an output ("sink") device. */ /* This is called when PulseAudio adds an output ("sink") device. */
static void static void SinkInfoCallback(pa_context *c, const pa_sink_info *i, int is_last, void *data)
SinkInfoCallback(pa_context *c, const pa_sink_info *i, int is_last, void *data)
{ {
SDL_AudioSpec spec; SDL_AudioSpec spec;
SDL_bool add = (SDL_bool) ((intptr_t) data); SDL_bool add = (SDL_bool)((intptr_t)data);
if (i) { if (i) {
spec.freq = i->sample_spec.rate; spec.freq = i->sample_spec.rate;
spec.channels = i->sample_spec.channels; spec.channels = i->sample_spec.channels;
@@ -732,7 +706,7 @@ SinkInfoCallback(pa_context *c, const pa_sink_info *i, int is_last, void *data)
spec.userdata = NULL; spec.userdata = NULL;
if (add) { if (add) {
SDL_AddAudioDevice(SDL_FALSE, i->description, &spec, (void *) ((intptr_t) i->index+1)); SDL_AddAudioDevice(SDL_FALSE, i->description, &spec, (void *)((intptr_t)i->index + 1));
} }
if (default_sink_path != NULL && SDL_strcmp(i->name, default_sink_path) == 0) { if (default_sink_path != NULL && SDL_strcmp(i->name, default_sink_path) == 0) {
@@ -745,11 +719,10 @@ SinkInfoCallback(pa_context *c, const pa_sink_info *i, int is_last, void *data)
} }
/* This is called when PulseAudio adds a capture ("source") device. */ /* This is called when PulseAudio adds a capture ("source") device. */
static void static void SourceInfoCallback(pa_context *c, const pa_source_info *i, int is_last, void *data)
SourceInfoCallback(pa_context *c, const pa_source_info *i, int is_last, void *data)
{ {
SDL_AudioSpec spec; SDL_AudioSpec spec;
SDL_bool add = (SDL_bool) ((intptr_t) data); SDL_bool add = (SDL_bool)((intptr_t)data);
if (i) { if (i) {
/* Maybe skip "monitor" sources. These are just output from other sinks. */ /* Maybe skip "monitor" sources. These are just output from other sinks. */
if (include_monitors || (i->monitor_of_sink == PA_INVALID_INDEX)) { if (include_monitors || (i->monitor_of_sink == PA_INVALID_INDEX)) {
@@ -763,7 +736,7 @@ SourceInfoCallback(pa_context *c, const pa_source_info *i, int is_last, void *da
spec.userdata = NULL; spec.userdata = NULL;
if (add) { if (add) {
SDL_AddAudioDevice(SDL_TRUE, i->description, &spec, (void *) ((intptr_t) i->index+1)); SDL_AddAudioDevice(SDL_TRUE, i->description, &spec, (void *)((intptr_t)i->index + 1));
} }
if (default_source_path != NULL && SDL_strcmp(i->name, default_source_path) == 0) { if (default_source_path != NULL && SDL_strcmp(i->name, default_source_path) == 0) {
@@ -776,8 +749,7 @@ SourceInfoCallback(pa_context *c, const pa_source_info *i, int is_last, void *da
} }
} }
static void static void ServerInfoCallback(pa_context *c, const pa_server_info *i, void *data)
ServerInfoCallback(pa_context *c, const pa_server_info *i, void *data)
{ {
if (default_sink_path != NULL) { if (default_sink_path != NULL) {
SDL_free(default_sink_path); SDL_free(default_sink_path);
@@ -790,8 +762,7 @@ ServerInfoCallback(pa_context *c, const pa_server_info *i, void *data)
} }
/* This is called when PulseAudio has a device connected/removed/changed. */ /* This is called when PulseAudio has a device connected/removed/changed. */
static void static void HotplugCallback(pa_context *c, pa_subscription_event_type_t t, uint32_t idx, void *data)
HotplugCallback(pa_context *c, pa_subscription_event_type_t t, uint32_t idx, void *data)
{ {
const SDL_bool added = ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_NEW); const SDL_bool added = ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_NEW);
const SDL_bool removed = ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE); const SDL_bool removed = ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE);
@@ -806,22 +777,21 @@ HotplugCallback(pa_context *c, pa_subscription_event_type_t t, uint32_t idx, voi
if (changed) { if (changed) {
PULSEAUDIO_pa_context_get_server_info(hotplug_context, ServerInfoCallback, NULL); PULSEAUDIO_pa_context_get_server_info(hotplug_context, ServerInfoCallback, NULL);
} }
PULSEAUDIO_pa_context_get_sink_info_by_index(hotplug_context, idx, SinkInfoCallback, (void*) ((intptr_t) added)); PULSEAUDIO_pa_context_get_sink_info_by_index(hotplug_context, idx, SinkInfoCallback, (void *)((intptr_t)added));
} else if ((added || changed) && source) { } else if ((added || changed) && source) {
if (changed) { if (changed) {
PULSEAUDIO_pa_context_get_server_info(hotplug_context, ServerInfoCallback, NULL); PULSEAUDIO_pa_context_get_server_info(hotplug_context, ServerInfoCallback, NULL);
} }
PULSEAUDIO_pa_context_get_source_info_by_index(hotplug_context, idx, SourceInfoCallback, (void*) ((intptr_t) added)); PULSEAUDIO_pa_context_get_source_info_by_index(hotplug_context, idx, SourceInfoCallback, (void *)((intptr_t)added));
} else if (removed && (sink || source)) { } else if (removed && (sink || source)) {
/* removes we can handle just with the device index. */ /* removes we can handle just with the device index. */
SDL_RemoveAudioDevice(source != 0, (void *) ((intptr_t) idx+1)); SDL_RemoveAudioDevice(source != 0, (void *)((intptr_t)idx + 1));
} }
} }
} }
/* this runs as a thread while the Pulse target is initialized to catch hotplug events. */ /* this runs as a thread while the Pulse target is initialized to catch hotplug events. */
static int SDLCALL static int SDLCALL HotplugThread(void *data)
HotplugThread(void *data)
{ {
pa_operation *o; pa_operation *o;
SDL_SetThreadPriority(SDL_THREAD_PRIORITY_LOW); SDL_SetThreadPriority(SDL_THREAD_PRIORITY_LOW);
@@ -832,19 +802,17 @@ HotplugThread(void *data)
return 0; return 0;
} }
static void static void PULSEAUDIO_DetectDevices()
PULSEAUDIO_DetectDevices()
{ {
WaitForPulseOperation(hotplug_mainloop, PULSEAUDIO_pa_context_get_server_info(hotplug_context, ServerInfoCallback, NULL)); WaitForPulseOperation(hotplug_mainloop, PULSEAUDIO_pa_context_get_server_info(hotplug_context, ServerInfoCallback, NULL));
WaitForPulseOperation(hotplug_mainloop, PULSEAUDIO_pa_context_get_sink_info_list(hotplug_context, SinkInfoCallback, (void*) ((intptr_t) SDL_TRUE))); WaitForPulseOperation(hotplug_mainloop, PULSEAUDIO_pa_context_get_sink_info_list(hotplug_context, SinkInfoCallback, (void *)((intptr_t)SDL_TRUE)));
WaitForPulseOperation(hotplug_mainloop, PULSEAUDIO_pa_context_get_source_info_list(hotplug_context, SourceInfoCallback, (void*) ((intptr_t) SDL_TRUE))); WaitForPulseOperation(hotplug_mainloop, PULSEAUDIO_pa_context_get_source_info_list(hotplug_context, SourceInfoCallback, (void *)((intptr_t)SDL_TRUE)));
/* ok, we have a sane list, let's set up hotplug notifications now... */ /* ok, we have a sane list, let's set up hotplug notifications now... */
hotplug_thread = SDL_CreateThreadInternal(HotplugThread, "PulseHotplug", 256 * 1024, NULL); hotplug_thread = SDL_CreateThreadInternal(HotplugThread, "PulseHotplug", 256 * 1024, NULL);
} }
static int static int PULSEAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
PULSEAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
{ {
int i; int i;
int numdevices; int numdevices;
@@ -875,8 +843,7 @@ PULSEAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
return SDL_SetError("Could not find default PulseAudio device"); return SDL_SetError("Could not find default PulseAudio device");
} }
static void static void PULSEAUDIO_Deinitialize(void)
PULSEAUDIO_Deinitialize(void)
{ {
if (hotplug_thread) { if (hotplug_thread) {
PULSEAUDIO_pa_mainloop_quit(hotplug_mainloop, 0); PULSEAUDIO_pa_mainloop_quit(hotplug_mainloop, 0);
@@ -908,8 +875,7 @@ PULSEAUDIO_Deinitialize(void)
UnloadPulseAudioLibrary(); UnloadPulseAudioLibrary();
} }
static SDL_bool static SDL_bool PULSEAUDIO_Init(SDL_AudioDriverImpl *impl)
PULSEAUDIO_Init(SDL_AudioDriverImpl * impl)
{ {
if (LoadPulseAudioLibrary() < 0) { if (LoadPulseAudioLibrary() < 0) {
return SDL_FALSE; return SDL_FALSE;

View File

@@ -50,7 +50,7 @@
#define SIO_DEVANY "default" #define SIO_DEVANY "default"
#endif #endif
static struct sio_hdl * (*SNDIO_sio_open)(const char *, unsigned int, int); static struct sio_hdl *(*SNDIO_sio_open)(const char *, unsigned int, int);
static void (*SNDIO_sio_close)(struct sio_hdl *); static void (*SNDIO_sio_close)(struct sio_hdl *);
static int (*SNDIO_sio_setpar)(struct sio_hdl *, struct sio_par *); static int (*SNDIO_sio_setpar)(struct sio_hdl *, struct sio_par *);
static int (*SNDIO_sio_getpar)(struct sio_hdl *, struct sio_par *); static int (*SNDIO_sio_getpar)(struct sio_hdl *, struct sio_par *);
@@ -68,8 +68,7 @@ static void (*SNDIO_sio_initpar)(struct sio_par *);
static const char *sndio_library = SDL_AUDIO_DRIVER_SNDIO_DYNAMIC; static const char *sndio_library = SDL_AUDIO_DRIVER_SNDIO_DYNAMIC;
static void *sndio_handle = NULL; static void *sndio_handle = NULL;
static int static int load_sndio_sym(const char *fn, void **addr)
load_sndio_sym(const char *fn, void **addr)
{ {
*addr = SDL_LoadFunction(sndio_handle, fn); *addr = SDL_LoadFunction(sndio_handle, fn);
if (*addr == NULL) { if (*addr == NULL) {
@@ -82,13 +81,13 @@ load_sndio_sym(const char *fn, void **addr)
/* cast funcs to char* first, to please GCC's strict aliasing rules. */ /* cast funcs to char* first, to please GCC's strict aliasing rules. */
#define SDL_SNDIO_SYM(x) \ #define SDL_SNDIO_SYM(x) \
if (!load_sndio_sym(#x, (void **) (char *) &SNDIO_##x)) return -1 if (!load_sndio_sym(#x, (void **)(char *)&SNDIO_##x)) \
return -1
#else #else
#define SDL_SNDIO_SYM(x) SNDIO_##x = x #define SDL_SNDIO_SYM(x) SNDIO_##x = x
#endif #endif
static int static int load_sndio_syms(void)
load_sndio_syms(void)
{ {
SDL_SNDIO_SYM(sio_open); SDL_SNDIO_SYM(sio_open);
SDL_SNDIO_SYM(sio_close); SDL_SNDIO_SYM(sio_close);
@@ -110,8 +109,7 @@ load_sndio_syms(void)
#ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC #ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
static void static void UnloadSNDIOLibrary(void)
UnloadSNDIOLibrary(void)
{ {
if (sndio_handle != NULL) { if (sndio_handle != NULL) {
SDL_UnloadObject(sndio_handle); SDL_UnloadObject(sndio_handle);
@@ -119,8 +117,7 @@ UnloadSNDIOLibrary(void)
} }
} }
static int static int LoadSNDIOLibrary(void)
LoadSNDIOLibrary(void)
{ {
int retval = 0; int retval = 0;
if (sndio_handle == NULL) { if (sndio_handle == NULL) {
@@ -140,13 +137,11 @@ LoadSNDIOLibrary(void)
#else #else
static void static void UnloadSNDIOLibrary(void)
UnloadSNDIOLibrary(void)
{ {
} }
static int static int LoadSNDIOLibrary(void)
LoadSNDIOLibrary(void)
{ {
load_sndio_syms(); load_sndio_syms();
return 0; return 0;
@@ -154,24 +149,19 @@ LoadSNDIOLibrary(void)
#endif /* SDL_AUDIO_DRIVER_SNDIO_DYNAMIC */ #endif /* SDL_AUDIO_DRIVER_SNDIO_DYNAMIC */
static void SNDIO_WaitDevice(_THIS)
static void
SNDIO_WaitDevice(_THIS)
{ {
/* no-op; SNDIO_sio_write() blocks if necessary. */ /* no-op; SNDIO_sio_write() blocks if necessary. */
} }
static void static void SNDIO_PlayDevice(_THIS)
SNDIO_PlayDevice(_THIS)
{ {
const int written = SNDIO_sio_write(this->hidden->dev, const int written = SNDIO_sio_write(this->hidden->dev,
this->hidden->mixbuf, this->hidden->mixbuf,
this->hidden->mixlen); this->hidden->mixlen);
/* If we couldn't write, assume fatal error for now */ /* If we couldn't write, assume fatal error for now */
if ( written == 0 ) { if (written == 0) {
SDL_OpenedAudioDeviceDisconnected(this); SDL_OpenedAudioDeviceDisconnected(this);
} }
#ifdef DEBUG_AUDIO #ifdef DEBUG_AUDIO
@@ -179,8 +169,7 @@ SNDIO_PlayDevice(_THIS)
#endif #endif
} }
static int static int SNDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
SNDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
size_t r; size_t r;
int revents; int revents;
@@ -189,8 +178,7 @@ SNDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
/* Emulate a blocking read */ /* Emulate a blocking read */
r = SNDIO_sio_read(this->hidden->dev, buffer, buflen); r = SNDIO_sio_read(this->hidden->dev, buffer, buflen);
while (r == 0 && !SNDIO_sio_eof(this->hidden->dev)) { while (r == 0 && !SNDIO_sio_eof(this->hidden->dev)) {
if ((nfds = SNDIO_sio_pollfd(this->hidden->dev, this->hidden->pfd, POLLIN)) <= 0 if ((nfds = SNDIO_sio_pollfd(this->hidden->dev, this->hidden->pfd, POLLIN)) <= 0 || poll(this->hidden->pfd, nfds, INFTIM) < 0) {
|| poll(this->hidden->pfd, nfds, INFTIM) < 0) {
return -1; return -1;
} }
revents = SNDIO_sio_revents(this->hidden->dev, this->hidden->pfd); revents = SNDIO_sio_revents(this->hidden->dev, this->hidden->pfd);
@@ -201,11 +189,10 @@ SNDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
break; break;
} }
} }
return (int) r; return (int)r;
} }
static void static void SNDIO_FlushCapture(_THIS)
SNDIO_FlushCapture(_THIS)
{ {
char buf[512]; char buf[512];
@@ -214,19 +201,17 @@ SNDIO_FlushCapture(_THIS)
} }
} }
static Uint8 * static Uint8 *SNDIO_GetDeviceBuf(_THIS)
SNDIO_GetDeviceBuf(_THIS)
{ {
return this->hidden->mixbuf; return this->hidden->mixbuf;
} }
static void static void SNDIO_CloseDevice(_THIS)
SNDIO_CloseDevice(_THIS)
{ {
if ( this->hidden->pfd != NULL ) { if (this->hidden->pfd != NULL) {
SDL_free(this->hidden->pfd); SDL_free(this->hidden->pfd);
} }
if ( this->hidden->dev != NULL ) { if (this->hidden->dev != NULL) {
SNDIO_sio_stop(this->hidden->dev); SNDIO_sio_stop(this->hidden->dev);
SNDIO_sio_close(this->hidden->dev); SNDIO_sio_close(this->hidden->dev);
} }
@@ -234,8 +219,7 @@ SNDIO_CloseDevice(_THIS)
SDL_free(this->hidden); SDL_free(this->hidden);
} }
static int static int SNDIO_OpenDevice(_THIS, const char *devname)
SNDIO_OpenDevice(_THIS, const char *devname)
{ {
SDL_AudioFormat test_format; SDL_AudioFormat test_format;
struct sio_par par; struct sio_par par;
@@ -325,7 +309,7 @@ SNDIO_OpenDevice(_THIS, const char *devname)
/* Allocate mixing buffer */ /* Allocate mixing buffer */
this->hidden->mixlen = this->spec.size; this->hidden->mixlen = this->spec.size;
this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); this->hidden->mixbuf = (Uint8 *)SDL_malloc(this->hidden->mixlen);
if (this->hidden->mixbuf == NULL) { if (this->hidden->mixbuf == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -339,21 +323,18 @@ SNDIO_OpenDevice(_THIS, const char *devname)
return 0; return 0;
} }
static void static void SNDIO_Deinitialize(void)
SNDIO_Deinitialize(void)
{ {
UnloadSNDIOLibrary(); UnloadSNDIOLibrary();
} }
static void static void SNDIO_DetectDevices(void)
SNDIO_DetectDevices(void)
{ {
SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, NULL, (void *) 0x1); SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, NULL, (void *)0x1);
SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, NULL, (void *) 0x2); SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, NULL, (void *)0x2);
} }
static SDL_bool static SDL_bool SNDIO_Init(SDL_AudioDriverImpl *impl)
SNDIO_Init(SDL_AudioDriverImpl * impl)
{ {
if (LoadSNDIOLibrary() < 0) { if (LoadSNDIOLibrary() < 0) {
return SDL_FALSE; return SDL_FALSE;

View File

@@ -39,8 +39,7 @@
#define SCE_AUDIO_SAMPLE_ALIGN(s) (((s) + 63) & ~63) #define SCE_AUDIO_SAMPLE_ALIGN(s) (((s) + 63) & ~63)
#define SCE_AUDIO_MAX_VOLUME 0x8000 #define SCE_AUDIO_MAX_VOLUME 0x8000
static int static int VITAAUD_OpenCaptureDevice(_THIS)
VITAAUD_OpenCaptureDevice(_THIS)
{ {
this->spec.freq = 16000; this->spec.freq = 16000;
this->spec.samples = 512; this->spec.samples = 512;
@@ -48,7 +47,7 @@ VITAAUD_OpenCaptureDevice(_THIS)
SDL_CalculateAudioSpec(&this->spec); SDL_CalculateAudioSpec(&this->spec);
this->hidden->port = sceAudioInOpenPort(SCE_AUDIO_IN_PORT_TYPE_VOICE , 512, 16000, SCE_AUDIO_IN_PARAM_FORMAT_S16_MONO); this->hidden->port = sceAudioInOpenPort(SCE_AUDIO_IN_PORT_TYPE_VOICE, 512, 16000, SCE_AUDIO_IN_PARAM_FORMAT_S16_MONO);
if (this->hidden->port < 0) { if (this->hidden->port < 0) {
return SDL_SetError("Couldn't open audio in port: %x", this->hidden->port); return SDL_SetError("Couldn't open audio in port: %x", this->hidden->port);
@@ -57,11 +56,10 @@ VITAAUD_OpenCaptureDevice(_THIS)
return 0; return 0;
} }
static int static int VITAAUD_OpenDevice(_THIS, const char *devname)
VITAAUD_OpenDevice(_THIS, const char *devname)
{ {
int format, mixlen, i, port = SCE_AUDIO_OUT_PORT_TYPE_MAIN; int format, mixlen, i, port = SCE_AUDIO_OUT_PORT_TYPE_MAIN;
int vols[2] = {SCE_AUDIO_MAX_VOLUME, SCE_AUDIO_MAX_VOLUME}; int vols[2] = { SCE_AUDIO_MAX_VOLUME, SCE_AUDIO_MAX_VOLUME };
SDL_AudioFormat test_format; SDL_AudioFormat test_format;
this->hidden = (struct SDL_PrivateAudioData *) this->hidden = (struct SDL_PrivateAudioData *)
@@ -96,7 +94,7 @@ VITAAUD_OpenDevice(_THIS, const char *devname)
be a multiple of 64 bytes. Our sample count is already a multiple of be a multiple of 64 bytes. Our sample count is already a multiple of
64, so spec->size should be a multiple of 64 as well. */ 64, so spec->size should be a multiple of 64 as well. */
mixlen = this->spec.size * NUM_BUFFERS; mixlen = this->spec.size * NUM_BUFFERS;
this->hidden->rawbuf = (Uint8 *) memalign(64, mixlen); this->hidden->rawbuf = (Uint8 *)memalign(64, mixlen);
if (this->hidden->rawbuf == NULL) { if (this->hidden->rawbuf == NULL) {
return SDL_SetError("Couldn't allocate mixing buffer"); return SDL_SetError("Couldn't allocate mixing buffer");
} }
@@ -119,7 +117,7 @@ VITAAUD_OpenDevice(_THIS, const char *devname)
return SDL_SetError("Couldn't open audio out port: %x", this->hidden->port); return SDL_SetError("Couldn't open audio out port: %x", this->hidden->port);
} }
sceAudioOutSetVolume(this->hidden->port, SCE_AUDIO_VOLUME_FLAG_L_CH|SCE_AUDIO_VOLUME_FLAG_R_CH, vols); sceAudioOutSetVolume(this->hidden->port, SCE_AUDIO_VOLUME_FLAG_L_CH | SCE_AUDIO_VOLUME_FLAG_R_CH, vols);
SDL_memset(this->hidden->rawbuf, 0, mixlen); SDL_memset(this->hidden->rawbuf, 0, mixlen);
for (i = 0; i < NUM_BUFFERS; i++) { for (i = 0; i < NUM_BUFFERS; i++) {
@@ -191,8 +189,7 @@ static void VITAAUD_ThreadInit(_THIS)
} }
} }
static SDL_bool static SDL_bool VITAAUD_Init(SDL_AudioDriverImpl *impl)
VITAAUD_Init(SDL_AudioDriverImpl * impl)
{ {
/* Set the function pointers */ /* Set the function pointers */
impl->OpenDevice = VITAAUD_OpenDevice; impl->OpenDevice = VITAAUD_OpenDevice;

View File

@@ -29,7 +29,8 @@
#define NUM_BUFFERS 2 #define NUM_BUFFERS 2
struct SDL_PrivateAudioData { struct SDL_PrivateAudioData
{
/* The hardware input/output port. */ /* The hardware input/output port. */
int port; int port;
/* The raw allocated mixing buffer. */ /* The raw allocated mixing buffer. */

View File

@@ -44,17 +44,15 @@
#endif #endif
/* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */ /* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483,{ 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } }; static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483, { 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0,{ 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } }; static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0, { 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } };
static void static void WASAPI_DetectDevices(void)
WASAPI_DetectDevices(void)
{ {
WASAPI_EnumerateEndpoints(); WASAPI_EnumerateEndpoints();
} }
static SDL_INLINE SDL_bool static SDL_INLINE SDL_bool WasapiFailed(_THIS, const HRESULT err)
WasapiFailed(_THIS, const HRESULT err)
{ {
if (err == S_OK) { if (err == S_OK) {
return SDL_FALSE; return SDL_FALSE;
@@ -71,24 +69,23 @@ WasapiFailed(_THIS, const HRESULT err)
return SDL_TRUE; return SDL_TRUE;
} }
static int static int UpdateAudioStream(_THIS, const SDL_AudioSpec *oldspec)
UpdateAudioStream(_THIS, const SDL_AudioSpec *oldspec)
{ {
/* Since WASAPI requires us to handle all audio conversion, and our /* Since WASAPI requires us to handle all audio conversion, and our
device format might have changed, we might have to add/remove/change device format might have changed, we might have to add/remove/change
the audio stream that the higher level uses to convert data, so the audio stream that the higher level uses to convert data, so
SDL keeps firing the callback as if nothing happened here. */ SDL keeps firing the callback as if nothing happened here. */
if ( (this->callbackspec.channels == this->spec.channels) && if ((this->callbackspec.channels == this->spec.channels) &&
(this->callbackspec.format == this->spec.format) && (this->callbackspec.format == this->spec.format) &&
(this->callbackspec.freq == this->spec.freq) && (this->callbackspec.freq == this->spec.freq) &&
(this->callbackspec.samples == this->spec.samples) ) { (this->callbackspec.samples == this->spec.samples)) {
/* no need to buffer/convert in an AudioStream! */ /* no need to buffer/convert in an AudioStream! */
SDL_FreeAudioStream(this->stream); SDL_FreeAudioStream(this->stream);
this->stream = NULL; this->stream = NULL;
} else if ( (oldspec->channels == this->spec.channels) && } else if ((oldspec->channels == this->spec.channels) &&
(oldspec->format == this->spec.format) && (oldspec->format == this->spec.format) &&
(oldspec->freq == this->spec.freq) ) { (oldspec->freq == this->spec.freq)) {
/* The existing audio stream is okay to keep using. */ /* The existing audio stream is okay to keep using. */
} else { } else {
/* replace the audiostream for new format */ /* replace the audiostream for new format */
@@ -113,7 +110,7 @@ UpdateAudioStream(_THIS, const SDL_AudioSpec *oldspec)
/* make sure our scratch buffer can cover the new device spec. */ /* make sure our scratch buffer can cover the new device spec. */
if (this->spec.size > this->work_buffer_len) { if (this->spec.size > this->work_buffer_len) {
Uint8 *ptr = (Uint8 *) SDL_realloc(this->work_buffer, this->spec.size); Uint8 *ptr = (Uint8 *)SDL_realloc(this->work_buffer, this->spec.size);
if (ptr == NULL) { if (ptr == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -124,11 +121,9 @@ UpdateAudioStream(_THIS, const SDL_AudioSpec *oldspec)
return 0; return 0;
} }
static void ReleaseWasapiDevice(_THIS); static void ReleaseWasapiDevice(_THIS);
static SDL_bool static SDL_bool RecoverWasapiDevice(_THIS)
RecoverWasapiDevice(_THIS)
{ {
ReleaseWasapiDevice(this); /* dump the lost device's handles. */ ReleaseWasapiDevice(this); /* dump the lost device's handles. */
@@ -151,8 +146,7 @@ RecoverWasapiDevice(_THIS)
return SDL_TRUE; /* okay, carry on with new device details! */ return SDL_TRUE; /* okay, carry on with new device details! */
} }
static SDL_bool static SDL_bool RecoverWasapiIfLost(_THIS)
RecoverWasapiIfLost(_THIS)
{ {
const int generation = this->hidden->default_device_generation; const int generation = this->hidden->default_device_generation;
SDL_bool lost = this->hidden->device_lost; SDL_bool lost = this->hidden->device_lost;
@@ -175,24 +169,22 @@ RecoverWasapiIfLost(_THIS)
return lost ? RecoverWasapiDevice(this) : SDL_TRUE; return lost ? RecoverWasapiDevice(this) : SDL_TRUE;
} }
static Uint8 * static Uint8 *WASAPI_GetDeviceBuf(_THIS)
WASAPI_GetDeviceBuf(_THIS)
{ {
/* get an endpoint buffer from WASAPI. */ /* get an endpoint buffer from WASAPI. */
BYTE *buffer = NULL; BYTE *buffer = NULL;
while (RecoverWasapiIfLost(this) && this->hidden->render) { while (RecoverWasapiIfLost(this) && this->hidden->render) {
if (!WasapiFailed(this, IAudioRenderClient_GetBuffer(this->hidden->render, this->spec.samples, &buffer))) { if (!WasapiFailed(this, IAudioRenderClient_GetBuffer(this->hidden->render, this->spec.samples, &buffer))) {
return (Uint8 *) buffer; return (Uint8 *)buffer;
} }
SDL_assert(buffer == NULL); SDL_assert(buffer == NULL);
} }
return (Uint8 *) buffer; return (Uint8 *)buffer;
} }
static void static void WASAPI_PlayDevice(_THIS)
WASAPI_PlayDevice(_THIS)
{ {
if (this->hidden->render != NULL) { /* definitely activated? */ if (this->hidden->render != NULL) { /* definitely activated? */
/* WasapiFailed() will mark the device for reacquisition or removal elsewhere. */ /* WasapiFailed() will mark the device for reacquisition or removal elsewhere. */
@@ -200,8 +192,7 @@ WASAPI_PlayDevice(_THIS)
} }
} }
static void static void WASAPI_WaitDevice(_THIS)
WASAPI_WaitDevice(_THIS)
{ {
while (RecoverWasapiIfLost(this) && this->hidden->client && this->hidden->event) { while (RecoverWasapiIfLost(this) && this->hidden->client && this->hidden->event) {
DWORD waitResult = WaitForSingleObjectEx(this->hidden->event, 200, FALSE); DWORD waitResult = WaitForSingleObjectEx(this->hidden->event, 200, FALSE);
@@ -228,8 +219,7 @@ WASAPI_WaitDevice(_THIS)
} }
} }
static int static int WASAPI_CaptureFromDevice(_THIS, void *buffer, int buflen)
WASAPI_CaptureFromDevice(_THIS, void *buffer, int buflen)
{ {
SDL_AudioStream *stream = this->hidden->capturestream; SDL_AudioStream *stream = this->hidden->capturestream;
const int avail = SDL_AudioStreamAvailable(stream); const int avail = SDL_AudioStreamAvailable(stream);
@@ -261,7 +251,7 @@ WASAPI_CaptureFromDevice(_THIS, void *buffer, int buflen)
if ((ret == AUDCLNT_S_BUFFER_EMPTY) || !frames) { if ((ret == AUDCLNT_S_BUFFER_EMPTY) || !frames) {
WASAPI_WaitDevice(this); WASAPI_WaitDevice(this);
} else if (ret == S_OK) { } else if (ret == S_OK) {
const int total = ((int) frames) * this->hidden->framesize; const int total = ((int)frames) * this->hidden->framesize;
const int cpy = SDL_min(buflen, total); const int cpy = SDL_min(buflen, total);
const int leftover = total - cpy; const int leftover = total - cpy;
const SDL_bool silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) ? SDL_TRUE : SDL_FALSE; const SDL_bool silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) ? SDL_TRUE : SDL_FALSE;
@@ -293,8 +283,7 @@ WASAPI_CaptureFromDevice(_THIS, void *buffer, int buflen)
return -1; /* unrecoverable error. */ return -1; /* unrecoverable error. */
} }
static void static void WASAPI_FlushCapture(_THIS)
WASAPI_FlushCapture(_THIS)
{ {
BYTE *ptr = NULL; BYTE *ptr = NULL;
UINT32 frames = 0; UINT32 frames = 0;
@@ -318,8 +307,7 @@ WASAPI_FlushCapture(_THIS)
SDL_AudioStreamClear(this->hidden->capturestream); SDL_AudioStreamClear(this->hidden->capturestream);
} }
static void static void ReleaseWasapiDevice(_THIS)
ReleaseWasapiDevice(_THIS)
{ {
if (this->hidden->client) { if (this->hidden->client) {
IAudioClient_Stop(this->hidden->client); IAudioClient_Stop(this->hidden->client);
@@ -358,20 +346,17 @@ ReleaseWasapiDevice(_THIS)
} }
} }
static void static void WASAPI_CloseDevice(_THIS)
WASAPI_CloseDevice(_THIS)
{ {
WASAPI_UnrefDevice(this); WASAPI_UnrefDevice(this);
} }
void void WASAPI_RefDevice(_THIS)
WASAPI_RefDevice(_THIS)
{ {
SDL_AtomicIncRef(&this->hidden->refcount); SDL_AtomicIncRef(&this->hidden->refcount);
} }
void void WASAPI_UnrefDevice(_THIS)
WASAPI_UnrefDevice(_THIS)
{ {
if (!SDL_AtomicDecRef(&this->hidden->refcount)) { if (!SDL_AtomicDecRef(&this->hidden->refcount)) {
return; return;
@@ -388,8 +373,7 @@ WASAPI_UnrefDevice(_THIS)
} }
/* This is called once a device is activated, possibly asynchronously. */ /* This is called once a device is activated, possibly asynchronously. */
int int WASAPI_PrepDevice(_THIS, const SDL_bool updatestream)
WASAPI_PrepDevice(_THIS, const SDL_bool updatestream)
{ {
/* !!! FIXME: we could request an exclusive mode stream, which is lower latency; /* !!! FIXME: we could request an exclusive mode stream, which is lower latency;
!!! it will write into the kernel's audio buffer directly instead of !!! it will write into the kernel's audio buffer directly instead of
@@ -435,7 +419,7 @@ WASAPI_PrepDevice(_THIS, const SDL_bool updatestream)
SDL_assert(waveformat != NULL); SDL_assert(waveformat != NULL);
this->hidden->waveformat = waveformat; this->hidden->waveformat = waveformat;
this->spec.channels = (Uint8) waveformat->nChannels; this->spec.channels = (Uint8)waveformat->nChannels;
/* Make sure we have a valid format that we can convert to whatever WASAPI wants. */ /* Make sure we have a valid format that we can convert to whatever WASAPI wants. */
wasapi_format = WaveFormatToSDLFormat(waveformat); wasapi_format = WaveFormatToSDLFormat(waveformat);
@@ -505,7 +489,7 @@ WASAPI_PrepDevice(_THIS, const SDL_bool updatestream)
return -1; /* already set SDL_Error */ return -1; /* already set SDL_Error */
} }
ret = IAudioClient_GetService(client, &SDL_IID_IAudioCaptureClient, (void**) &capture); ret = IAudioClient_GetService(client, &SDL_IID_IAudioCaptureClient, (void **)&capture);
if (FAILED(ret)) { if (FAILED(ret)) {
return WIN_SetErrorFromHRESULT("WASAPI can't get capture client service", ret); return WIN_SetErrorFromHRESULT("WASAPI can't get capture client service", ret);
} }
@@ -519,7 +503,7 @@ WASAPI_PrepDevice(_THIS, const SDL_bool updatestream)
WASAPI_FlushCapture(this); /* MSDN says you should flush capture endpoint right after startup. */ WASAPI_FlushCapture(this); /* MSDN says you should flush capture endpoint right after startup. */
} else { } else {
ret = IAudioClient_GetService(client, &SDL_IID_IAudioRenderClient, (void**) &render); ret = IAudioClient_GetService(client, &SDL_IID_IAudioRenderClient, (void **)&render);
if (FAILED(ret)) { if (FAILED(ret)) {
return WIN_SetErrorFromHRESULT("WASAPI can't get render client service", ret); return WIN_SetErrorFromHRESULT("WASAPI can't get render client service", ret);
} }
@@ -539,11 +523,9 @@ WASAPI_PrepDevice(_THIS, const SDL_bool updatestream)
return 0; /* good to go. */ return 0; /* good to go. */
} }
static int WASAPI_OpenDevice(_THIS, const char *devname)
static int
WASAPI_OpenDevice(_THIS, const char *devname)
{ {
LPCWSTR devid = (LPCWSTR) this->handle; LPCWSTR devid = (LPCWSTR)this->handle;
/* Initialize all variables that we clean on shutdown */ /* Initialize all variables that we clean on shutdown */
this->hidden = (struct SDL_PrivateAudioData *) this->hidden = (struct SDL_PrivateAudioData *)
@@ -579,26 +561,22 @@ WASAPI_OpenDevice(_THIS, const char *devname)
return 0; return 0;
} }
static void static void WASAPI_ThreadInit(_THIS)
WASAPI_ThreadInit(_THIS)
{ {
WASAPI_PlatformThreadInit(this); WASAPI_PlatformThreadInit(this);
} }
static void static void WASAPI_ThreadDeinit(_THIS)
WASAPI_ThreadDeinit(_THIS)
{ {
WASAPI_PlatformThreadDeinit(this); WASAPI_PlatformThreadDeinit(this);
} }
static void static void WASAPI_Deinitialize(void)
WASAPI_Deinitialize(void)
{ {
WASAPI_PlatformDeinit(); WASAPI_PlatformDeinit();
} }
static SDL_bool static SDL_bool WASAPI_Init(SDL_AudioDriverImpl *impl)
WASAPI_Init(SDL_AudioDriverImpl * impl)
{ {
if (WASAPI_PlatformInit() == -1) { if (WASAPI_PlatformInit() == -1) {
return SDL_FALSE; return SDL_FALSE;

View File

@@ -45,10 +45,9 @@ static pfnAvSetMmThreadCharacteristicsW pAvSetMmThreadCharacteristicsW = NULL;
static pfnAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL; static pfnAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL;
/* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */ /* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
static const IID SDL_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32,{ 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2 } }; static const IID SDL_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32, { 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2 } };
int int WASAPI_PlatformInit(void)
WASAPI_PlatformInit(void)
{ {
if (SDL_IMMDevice_Init() < 0) { if (SDL_IMMDevice_Init() < 0) {
return -1; /* This is set by SDL_IMMDevice_Init */ return -1; /* This is set by SDL_IMMDevice_Init */
@@ -56,15 +55,14 @@ WASAPI_PlatformInit(void)
libavrt = LoadLibrary(TEXT("avrt.dll")); /* this library is available in Vista and later. No WinXP, so have to LoadLibrary to use it for now! */ libavrt = LoadLibrary(TEXT("avrt.dll")); /* this library is available in Vista and later. No WinXP, so have to LoadLibrary to use it for now! */
if (libavrt) { if (libavrt) {
pAvSetMmThreadCharacteristicsW = (pfnAvSetMmThreadCharacteristicsW) GetProcAddress(libavrt, "AvSetMmThreadCharacteristicsW"); pAvSetMmThreadCharacteristicsW = (pfnAvSetMmThreadCharacteristicsW)GetProcAddress(libavrt, "AvSetMmThreadCharacteristicsW");
pAvRevertMmThreadCharacteristics = (pfnAvRevertMmThreadCharacteristics) GetProcAddress(libavrt, "AvRevertMmThreadCharacteristics"); pAvRevertMmThreadCharacteristics = (pfnAvRevertMmThreadCharacteristics)GetProcAddress(libavrt, "AvRevertMmThreadCharacteristics");
} }
return 0; return 0;
} }
void void WASAPI_PlatformDeinit(void)
WASAPI_PlatformDeinit(void)
{ {
if (libavrt) { if (libavrt) {
FreeLibrary(libavrt); FreeLibrary(libavrt);
@@ -77,8 +75,7 @@ WASAPI_PlatformDeinit(void)
SDL_IMMDevice_Quit(); SDL_IMMDevice_Quit();
} }
void void WASAPI_PlatformThreadInit(_THIS)
WASAPI_PlatformThreadInit(_THIS)
{ {
/* this thread uses COM. */ /* this thread uses COM. */
if (SUCCEEDED(WIN_CoInitialize())) { /* can't report errors, hope it worked! */ if (SUCCEEDED(WIN_CoInitialize())) { /* can't report errors, hope it worked! */
@@ -92,8 +89,7 @@ WASAPI_PlatformThreadInit(_THIS)
} }
} }
void void WASAPI_PlatformThreadDeinit(_THIS)
WASAPI_PlatformThreadDeinit(_THIS)
{ {
/* Set this thread back to normal priority. */ /* Set this thread back to normal priority. */
if (this->hidden->task && pAvRevertMmThreadCharacteristics) { if (this->hidden->task && pAvRevertMmThreadCharacteristics) {
@@ -107,8 +103,7 @@ WASAPI_PlatformThreadDeinit(_THIS)
} }
} }
int int WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
{ {
IMMDevice *device = NULL; IMMDevice *device = NULL;
HRESULT ret; HRESULT ret;
@@ -119,7 +114,7 @@ WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
} }
/* this is not async in standard win32, yay! */ /* this is not async in standard win32, yay! */
ret = IMMDevice_Activate(device, &SDL_IID_IAudioClient, CLSCTX_ALL, NULL, (void **) &this->hidden->client); ret = IMMDevice_Activate(device, &SDL_IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&this->hidden->client);
IMMDevice_Release(device); IMMDevice_Release(device);
if (FAILED(ret)) { if (FAILED(ret)) {
@@ -135,20 +130,17 @@ WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
return 0; /* good to go. */ return 0; /* good to go. */
} }
void void WASAPI_EnumerateEndpoints(void)
WASAPI_EnumerateEndpoints(void)
{ {
SDL_IMMDevice_EnumerateEndpoints(SDL_FALSE); SDL_IMMDevice_EnumerateEndpoints(SDL_FALSE);
} }
int int WASAPI_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
WASAPI_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
{ {
return SDL_IMMDevice_GetDefaultAudioInfo(name, spec, iscapture); return SDL_IMMDevice_GetDefaultAudioInfo(name, spec, iscapture);
} }
void void WASAPI_PlatformDeleteActivationHandler(void *handler)
WASAPI_PlatformDeleteActivationHandler(void *handler)
{ {
/* not asynchronous. */ /* not asynchronous. */
SDL_assert(!"This function should have only been called on WinRT."); SDL_assert(!"This function should have only been called on WinRT.");
@@ -157,4 +149,3 @@ WASAPI_PlatformDeleteActivationHandler(void *handler)
#endif /* SDL_AUDIO_DRIVER_WASAPI && !defined(__WINRT__) */ #endif /* SDL_AUDIO_DRIVER_WASAPI && !defined(__WINRT__) */
/* vi: set ts=4 sw=4 expandtab: */ /* vi: set ts=4 sw=4 expandtab: */

View File

@@ -51,13 +51,13 @@ using namespace Windows::Media::Devices;
using namespace Windows::Foundation; using namespace Windows::Foundation;
using namespace Microsoft::WRL; using namespace Microsoft::WRL;
static Platform::String^ SDL_PKEY_AudioEngine_DeviceFormat = L"{f19f064d-082c-4e27-bc73-6882a1bb8e4c} 0"; static Platform::String ^ SDL_PKEY_AudioEngine_DeviceFormat = L"{f19f064d-082c-4e27-bc73-6882a1bb8e4c} 0";
static void WASAPI_AddDevice(const SDL_bool iscapture, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid); static void WASAPI_AddDevice(const SDL_bool iscapture, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid);
static void WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid); static void WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid);
extern "C" { extern "C" {
SDL_atomic_t SDL_IMMDevice_DefaultPlaybackGeneration; SDL_atomic_t SDL_IMMDevice_DefaultPlaybackGeneration;
SDL_atomic_t SDL_IMMDevice_DefaultCaptureGeneration; SDL_atomic_t SDL_IMMDevice_DefaultCaptureGeneration;
} }
/* This is a list of device id strings we have inflight, so we have consistent pointers to the same device. */ /* This is a list of device id strings we have inflight, so we have consistent pointers to the same device. */
@@ -71,20 +71,20 @@ static DevIdList *deviceid_list = NULL;
class SDL_WasapiDeviceEventHandler class SDL_WasapiDeviceEventHandler
{ {
public: public:
SDL_WasapiDeviceEventHandler(const SDL_bool _iscapture); SDL_WasapiDeviceEventHandler(const SDL_bool _iscapture);
~SDL_WasapiDeviceEventHandler(); ~SDL_WasapiDeviceEventHandler();
void OnDeviceAdded(DeviceWatcher^ sender, DeviceInformation^ args); void OnDeviceAdded(DeviceWatcher ^ sender, DeviceInformation ^ args);
void OnDeviceRemoved(DeviceWatcher^ sender, DeviceInformationUpdate^ args); void OnDeviceRemoved(DeviceWatcher ^ sender, DeviceInformationUpdate ^ args);
void OnDeviceUpdated(DeviceWatcher^ sender, DeviceInformationUpdate^ args); void OnDeviceUpdated(DeviceWatcher ^ sender, DeviceInformationUpdate ^ args);
void OnEnumerationCompleted(DeviceWatcher^ sender, Platform::Object^ args); void OnEnumerationCompleted(DeviceWatcher ^ sender, Platform::Object ^ args);
void OnDefaultRenderDeviceChanged(Platform::Object^ sender, DefaultAudioRenderDeviceChangedEventArgs^ args); void OnDefaultRenderDeviceChanged(Platform::Object ^ sender, DefaultAudioRenderDeviceChangedEventArgs ^ args);
void OnDefaultCaptureDeviceChanged(Platform::Object^ sender, DefaultAudioCaptureDeviceChangedEventArgs^ args); void OnDefaultCaptureDeviceChanged(Platform::Object ^ sender, DefaultAudioCaptureDeviceChangedEventArgs ^ args);
SDL_semaphore* completed; SDL_semaphore *completed;
private: private:
const SDL_bool iscapture; const SDL_bool iscapture;
DeviceWatcher^ watcher; DeviceWatcher ^ watcher;
Windows::Foundation::EventRegistrationToken added_handler; Windows::Foundation::EventRegistrationToken added_handler;
Windows::Foundation::EventRegistrationToken removed_handler; Windows::Foundation::EventRegistrationToken removed_handler;
Windows::Foundation::EventRegistrationToken updated_handler; Windows::Foundation::EventRegistrationToken updated_handler;
@@ -93,29 +93,27 @@ private:
}; };
SDL_WasapiDeviceEventHandler::SDL_WasapiDeviceEventHandler(const SDL_bool _iscapture) SDL_WasapiDeviceEventHandler::SDL_WasapiDeviceEventHandler(const SDL_bool _iscapture)
: iscapture(_iscapture) : iscapture(_iscapture), completed(SDL_CreateSemaphore(0))
, completed(SDL_CreateSemaphore(0))
{ {
if (!completed) if (!completed)
return; // uhoh. return; // uhoh.
Platform::String^ selector = _iscapture ? MediaDevice::GetAudioCaptureSelector() : Platform::String ^ selector = _iscapture ? MediaDevice::GetAudioCaptureSelector() : MediaDevice::GetAudioRenderSelector();
MediaDevice::GetAudioRenderSelector(); Platform::Collections::Vector<Platform::String ^> properties;
Platform::Collections::Vector<Platform::String^> properties;
properties.Append(SDL_PKEY_AudioEngine_DeviceFormat); properties.Append(SDL_PKEY_AudioEngine_DeviceFormat);
watcher = DeviceInformation::CreateWatcher(selector, properties.GetView()); watcher = DeviceInformation::CreateWatcher(selector, properties.GetView());
if (!watcher) if (!watcher)
return; // uhoh. return; // uhoh.
// !!! FIXME: this doesn't need a lambda here, I think, if I make SDL_WasapiDeviceEventHandler a proper C++/CX class. --ryan. // !!! FIXME: this doesn't need a lambda here, I think, if I make SDL_WasapiDeviceEventHandler a proper C++/CX class. --ryan.
added_handler = watcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>([this](DeviceWatcher^ sender, DeviceInformation^ args) { OnDeviceAdded(sender, args); } ); added_handler = watcher->Added += ref new TypedEventHandler<DeviceWatcher ^, DeviceInformation ^>([this](DeviceWatcher ^ sender, DeviceInformation ^ args) { OnDeviceAdded(sender, args); });
removed_handler = watcher->Removed += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>([this](DeviceWatcher^ sender, DeviceInformationUpdate^ args) { OnDeviceRemoved(sender, args); } ); removed_handler = watcher->Removed += ref new TypedEventHandler<DeviceWatcher ^, DeviceInformationUpdate ^>([this](DeviceWatcher ^ sender, DeviceInformationUpdate ^ args) { OnDeviceRemoved(sender, args); });
updated_handler = watcher->Updated += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>([this](DeviceWatcher^ sender, DeviceInformationUpdate^ args) { OnDeviceUpdated(sender, args); } ); updated_handler = watcher->Updated += ref new TypedEventHandler<DeviceWatcher ^, DeviceInformationUpdate ^>([this](DeviceWatcher ^ sender, DeviceInformationUpdate ^ args) { OnDeviceUpdated(sender, args); });
completed_handler = watcher->EnumerationCompleted += ref new TypedEventHandler<DeviceWatcher^, Platform::Object^>([this](DeviceWatcher^ sender, Platform::Object^ args) { OnEnumerationCompleted(sender, args); } ); completed_handler = watcher->EnumerationCompleted += ref new TypedEventHandler<DeviceWatcher ^, Platform::Object ^>([this](DeviceWatcher ^ sender, Platform::Object ^ args) { OnEnumerationCompleted(sender, args); });
if (iscapture) { if (iscapture) {
default_changed_handler = MediaDevice::DefaultAudioCaptureDeviceChanged += ref new TypedEventHandler<Platform::Object^, DefaultAudioCaptureDeviceChangedEventArgs^>([this](Platform::Object^ sender, DefaultAudioCaptureDeviceChangedEventArgs^ args) { OnDefaultCaptureDeviceChanged(sender, args); } ); default_changed_handler = MediaDevice::DefaultAudioCaptureDeviceChanged += ref new TypedEventHandler<Platform::Object ^, DefaultAudioCaptureDeviceChangedEventArgs ^>([this](Platform::Object ^ sender, DefaultAudioCaptureDeviceChangedEventArgs ^ args) { OnDefaultCaptureDeviceChanged(sender, args); });
} else { } else {
default_changed_handler = MediaDevice::DefaultAudioRenderDeviceChanged += ref new TypedEventHandler<Platform::Object^, DefaultAudioRenderDeviceChangedEventArgs^>([this](Platform::Object^ sender, DefaultAudioRenderDeviceChangedEventArgs^ args) { OnDefaultRenderDeviceChanged(sender, args); } ); default_changed_handler = MediaDevice::DefaultAudioRenderDeviceChanged += ref new TypedEventHandler<Platform::Object ^, DefaultAudioRenderDeviceChangedEventArgs ^>([this](Platform::Object ^ sender, DefaultAudioRenderDeviceChangedEventArgs ^ args) { OnDefaultRenderDeviceChanged(sender, args); });
} }
watcher->Start(); watcher->Start();
} }
@@ -142,17 +140,16 @@ SDL_WasapiDeviceEventHandler::~SDL_WasapiDeviceEventHandler()
} }
} }
void void SDL_WasapiDeviceEventHandler::OnDeviceAdded(DeviceWatcher ^ sender, DeviceInformation ^ info)
SDL_WasapiDeviceEventHandler::OnDeviceAdded(DeviceWatcher^ sender, DeviceInformation^ info)
{ {
SDL_assert(sender == this->watcher); SDL_assert(sender == this->watcher);
char *utf8dev = WIN_StringToUTF8(info->Name->Data()); char *utf8dev = WIN_StringToUTF8(info->Name->Data());
if (utf8dev) { if (utf8dev) {
WAVEFORMATEXTENSIBLE fmt; WAVEFORMATEXTENSIBLE fmt;
Platform::Object^ obj = info->Properties->Lookup(SDL_PKEY_AudioEngine_DeviceFormat); Platform::Object ^ obj = info->Properties->Lookup(SDL_PKEY_AudioEngine_DeviceFormat);
if (obj) { if (obj) {
IPropertyValue^ property = (IPropertyValue^) obj; IPropertyValue ^ property = (IPropertyValue ^) obj;
Platform::Array<unsigned char>^ data; Platform::Array<unsigned char> ^ data;
property->GetUInt8Array(&data); property->GetUInt8Array(&data);
SDL_memcpy(&fmt, data->Data, SDL_min(data->Length, sizeof(WAVEFORMATEXTENSIBLE))); SDL_memcpy(&fmt, data->Data, SDL_min(data->Length, sizeof(WAVEFORMATEXTENSIBLE)));
} else { } else {
@@ -164,41 +161,35 @@ SDL_WasapiDeviceEventHandler::OnDeviceAdded(DeviceWatcher^ sender, DeviceInforma
} }
} }
void void SDL_WasapiDeviceEventHandler::OnDeviceRemoved(DeviceWatcher ^ sender, DeviceInformationUpdate ^ info)
SDL_WasapiDeviceEventHandler::OnDeviceRemoved(DeviceWatcher^ sender, DeviceInformationUpdate^ info)
{ {
SDL_assert(sender == this->watcher); SDL_assert(sender == this->watcher);
WASAPI_RemoveDevice(this->iscapture, info->Id->Data()); WASAPI_RemoveDevice(this->iscapture, info->Id->Data());
} }
void void SDL_WasapiDeviceEventHandler::OnDeviceUpdated(DeviceWatcher ^ sender, DeviceInformationUpdate ^ args)
SDL_WasapiDeviceEventHandler::OnDeviceUpdated(DeviceWatcher^ sender, DeviceInformationUpdate^ args)
{ {
SDL_assert(sender == this->watcher); SDL_assert(sender == this->watcher);
} }
void void SDL_WasapiDeviceEventHandler::OnEnumerationCompleted(DeviceWatcher ^ sender, Platform::Object ^ args)
SDL_WasapiDeviceEventHandler::OnEnumerationCompleted(DeviceWatcher^ sender, Platform::Object^ args)
{ {
SDL_assert(sender == this->watcher); SDL_assert(sender == this->watcher);
SDL_SemPost(this->completed); SDL_SemPost(this->completed);
} }
void void SDL_WasapiDeviceEventHandler::OnDefaultRenderDeviceChanged(Platform::Object ^ sender, DefaultAudioRenderDeviceChangedEventArgs ^ args)
SDL_WasapiDeviceEventHandler::OnDefaultRenderDeviceChanged(Platform::Object^ sender, DefaultAudioRenderDeviceChangedEventArgs^ args)
{ {
SDL_assert(this->iscapture); SDL_assert(this->iscapture);
SDL_AtomicAdd(&SDL_IMMDevice_DefaultPlaybackGeneration, 1); SDL_AtomicAdd(&SDL_IMMDevice_DefaultPlaybackGeneration, 1);
} }
void void SDL_WasapiDeviceEventHandler::OnDefaultCaptureDeviceChanged(Platform::Object ^ sender, DefaultAudioCaptureDeviceChangedEventArgs ^ args)
SDL_WasapiDeviceEventHandler::OnDefaultCaptureDeviceChanged(Platform::Object^ sender, DefaultAudioCaptureDeviceChangedEventArgs^ args)
{ {
SDL_assert(!this->iscapture); SDL_assert(!this->iscapture);
SDL_AtomicAdd(&SDL_IMMDevice_DefaultCaptureGeneration, 1); SDL_AtomicAdd(&SDL_IMMDevice_DefaultCaptureGeneration, 1);
} }
static SDL_WasapiDeviceEventHandler *playback_device_event_handler; static SDL_WasapiDeviceEventHandler *playback_device_event_handler;
static SDL_WasapiDeviceEventHandler *capture_device_event_handler; static SDL_WasapiDeviceEventHandler *capture_device_event_handler;
@@ -238,10 +229,11 @@ void WASAPI_EnumerateEndpoints(void)
SDL_SemWait(capture_device_event_handler->completed); SDL_SemWait(capture_device_event_handler->completed);
} }
struct SDL_WasapiActivationHandler : public RuntimeClass< RuntimeClassFlags< ClassicCom >, FtmBase, IActivateAudioInterfaceCompletionHandler > struct SDL_WasapiActivationHandler : public RuntimeClass<RuntimeClassFlags<ClassicCom>, FtmBase, IActivateAudioInterfaceCompletionHandler>
{ {
SDL_WasapiActivationHandler() : device(nullptr) {} SDL_WasapiActivationHandler() : device(nullptr) {}
STDMETHOD(ActivateCompleted)(IActivateAudioInterfaceAsyncOperation *operation); STDMETHOD(ActivateCompleted)
(IActivateAudioInterfaceAsyncOperation *operation);
SDL_AudioDevice *device; SDL_AudioDevice *device;
}; };
@@ -254,23 +246,20 @@ SDL_WasapiActivationHandler::ActivateCompleted(IActivateAudioInterfaceAsyncOpera
return S_OK; return S_OK;
} }
void void WASAPI_PlatformDeleteActivationHandler(void *handler)
WASAPI_PlatformDeleteActivationHandler(void *handler)
{ {
((SDL_WasapiActivationHandler *) handler)->Release(); ((SDL_WasapiActivationHandler *)handler)->Release();
} }
int int WASAPI_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
WASAPI_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
{ {
return SDL_Unsupported(); return SDL_Unsupported();
} }
int int WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
{ {
LPCWSTR devid = _this->hidden->devid; LPCWSTR devid = _this->hidden->devid;
Platform::String^ defdevid; Platform::String ^ defdevid;
if (devid == nullptr) { if (devid == nullptr) {
defdevid = _this->iscapture ? MediaDevice::GetDefaultAudioCaptureId(AudioDeviceRole::Default) : MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Default); defdevid = _this->iscapture ? MediaDevice::GetDefaultAudioCaptureId(AudioDeviceRole::Default) : MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Default);
@@ -337,22 +326,20 @@ WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
return 0; return 0;
} }
void void WASAPI_PlatformThreadInit(_THIS)
WASAPI_PlatformThreadInit(_THIS)
{ {
// !!! FIXME: set this thread to "Pro Audio" priority. // !!! FIXME: set this thread to "Pro Audio" priority.
} }
void void WASAPI_PlatformThreadDeinit(_THIS)
WASAPI_PlatformThreadDeinit(_THIS)
{ {
// !!! FIXME: set this thread to "Pro Audio" priority. // !!! FIXME: set this thread to "Pro Audio" priority.
} }
/* Everything below was copied from SDL_wasapi.c, before it got moved to SDL_immdevice.c! */ /* Everything below was copied from SDL_wasapi.c, before it got moved to SDL_immdevice.c! */
static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
extern "C" SDL_AudioFormat extern "C" SDL_AudioFormat
WaveFormatToSDLFormat(WAVEFORMATEX *waveformat) WaveFormatToSDLFormat(WAVEFORMATEX *waveformat)
@@ -376,8 +363,7 @@ WaveFormatToSDLFormat(WAVEFORMATEX *waveformat)
return 0; return 0;
} }
static void static void WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid)
WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid)
{ {
DevIdList *i; DevIdList *i;
DevIdList *next; DevIdList *next;
@@ -399,8 +385,7 @@ WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid)
} }
} }
static void static void WASAPI_AddDevice(const SDL_bool iscapture, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid)
WASAPI_AddDevice(const SDL_bool iscapture, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid)
{ {
DevIdList *devidlist; DevIdList *devidlist;
SDL_AudioSpec spec; SDL_AudioSpec spec;

View File

@@ -20,7 +20,6 @@
*/ */
#include "SDL_internal.h" #include "SDL_internal.h"
#ifdef __ANDROID__ #ifdef __ANDROID__
#include "SDL_android.h" #include "SDL_android.h"
@@ -45,7 +44,7 @@
#define SDL_JAVA_PREFIX org_libsdl_app #define SDL_JAVA_PREFIX org_libsdl_app
#define CONCAT1(prefix, class, function) CONCAT2(prefix, class, function) #define CONCAT1(prefix, class, function) CONCAT2(prefix, class, function)
#define CONCAT2(prefix, class, function) Java_ ## prefix ## _ ## class ## _ ## function #define CONCAT2(prefix, class, function) Java_##prefix##_##class##_##function
#define SDL_JAVA_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLActivity, function) #define SDL_JAVA_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLActivity, function)
#define SDL_JAVA_AUDIO_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLAudioManager, function) #define SDL_JAVA_AUDIO_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLAudioManager, function)
#define SDL_JAVA_CONTROLLER_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLControllerManager, function) #define SDL_JAVA_CONTROLLER_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLControllerManager, function)
@@ -156,11 +155,11 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeOrientationChanged)(
jint orientation); jint orientation);
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeAddTouch)( JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeAddTouch)(
JNIEnv* env, jclass cls, JNIEnv *env, jclass cls,
jint touchId, jstring name); jint touchId, jstring name);
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePermissionResult)( JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePermissionResult)(
JNIEnv* env, jclass cls, JNIEnv *env, jclass cls,
jint requestCode, jboolean result); jint requestCode, jboolean result);
static JNINativeMethod SDLActivity_tab[] = { static JNINativeMethod SDLActivity_tab[] = {
@@ -267,7 +266,6 @@ static JNINativeMethod SDLControllerManager_tab[] = {
{ "nativeRemoveHaptic", "(I)I", SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveHaptic) } { "nativeRemoveHaptic", "(I)I", SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveHaptic) }
}; };
/* Uncomment this to log messages entering and exiting methods in this file */ /* Uncomment this to log messages entering and exiting methods in this file */
/* #define DEBUG_JNI */ /* #define DEBUG_JNI */
@@ -278,7 +276,6 @@ static void checkJNIReady(void);
*******************************************************************************/ *******************************************************************************/
#include <jni.h> #include <jni.h>
/******************************************************************************* /*******************************************************************************
Globals Globals
*******************************************************************************/ *******************************************************************************/
@@ -389,8 +386,8 @@ static jobject javaAssetManagerRef = 0;
*/ */
/* Set local storage value */ /* Set local storage value */
static int static int Android_JNI_SetEnv(JNIEnv *env)
Android_JNI_SetEnv(JNIEnv *env) { {
int status = pthread_setspecific(mThreadKey, env); int status = pthread_setspecific(mThreadKey, env);
if (status < 0) { if (status < 0) {
__android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed pthread_setspecific() in Android_JNI_SetEnv() (err=%d)", status); __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed pthread_setspecific() in Android_JNI_SetEnv() (err=%d)", status);
@@ -399,7 +396,7 @@ Android_JNI_SetEnv(JNIEnv *env) {
} }
/* Get local storage value */ /* Get local storage value */
JNIEnv* Android_JNI_GetEnv(void) JNIEnv *Android_JNI_GetEnv(void)
{ {
/* Get JNIEnv from the Thread local storage */ /* Get JNIEnv from the Thread local storage */
JNIEnv *env = pthread_getspecific(mThreadKey); JNIEnv *env = pthread_getspecific(mThreadKey);
@@ -459,11 +456,10 @@ int Android_JNI_SetupThread(void)
} }
/* Destructor called for each thread where mThreadKey is not NULL */ /* Destructor called for each thread where mThreadKey is not NULL */
static void static void Android_JNI_ThreadDestroyed(void *value)
Android_JNI_ThreadDestroyed(void *value)
{ {
/* The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required */ /* The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required */
JNIEnv *env = (JNIEnv *) value; JNIEnv *env = (JNIEnv *)value;
if (env != NULL) { if (env != NULL) {
(*mJavaVM)->DetachCurrentThread(mJavaVM); (*mJavaVM)->DetachCurrentThread(mJavaVM);
Android_JNI_SetEnv(NULL); Android_JNI_SetEnv(NULL);
@@ -471,8 +467,7 @@ Android_JNI_ThreadDestroyed(void *value)
} }
/* Creation of local storage mThreadKey */ /* Creation of local storage mThreadKey */
static void static void Android_JNI_CreateKey(void)
Android_JNI_CreateKey(void)
{ {
int status = pthread_key_create(&mThreadKey, Android_JNI_ThreadDestroyed); int status = pthread_key_create(&mThreadKey, Android_JNI_ThreadDestroyed);
if (status < 0) { if (status < 0) {
@@ -480,8 +475,7 @@ Android_JNI_CreateKey(void)
} }
} }
static void static void Android_JNI_CreateKey_once(void)
Android_JNI_CreateKey_once(void)
{ {
int status = pthread_once(&key_once, Android_JNI_CreateKey); int status = pthread_once(&key_once, Android_JNI_CreateKey);
if (status < 0) { if (status < 0) {
@@ -489,8 +483,7 @@ Android_JNI_CreateKey_once(void)
} }
} }
static void static void register_methods(JNIEnv *env, const char *classname, JNINativeMethod *methods, int nb)
register_methods(JNIEnv *env, const char *classname, JNINativeMethod *methods, int nb)
{ {
jclass clazz = (*env)->FindClass(env, classname); jclass clazz = (*env)->FindClass(env, classname);
if (clazz == NULL || (*env)->RegisterNatives(env, clazz, methods, nb) < 0) { if (clazz == NULL || (*env)->RegisterNatives(env, clazz, methods, nb) < 0) {
@@ -568,7 +561,6 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(JNIEnv *env, jclass cl
__android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to create Android_ActivityMutex mutex"); __android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to create Android_ActivityMutex mutex");
} }
Android_PauseSem = SDL_CreateSemaphore(0); Android_PauseSem = SDL_CreateSemaphore(0);
if (Android_PauseSem == NULL) { if (Android_PauseSem == NULL) {
__android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to create Android_PauseSem semaphore"); __android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to create Android_PauseSem semaphore");
@@ -586,29 +578,29 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(JNIEnv *env, jclass cl
midClipboardSetText = (*env)->GetStaticMethodID(env, mActivityClass, "clipboardSetText", "(Ljava/lang/String;)V"); midClipboardSetText = (*env)->GetStaticMethodID(env, mActivityClass, "clipboardSetText", "(Ljava/lang/String;)V");
midCreateCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "createCustomCursor", "([IIIII)I"); midCreateCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "createCustomCursor", "([IIIII)I");
midDestroyCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "destroyCustomCursor", "(I)V"); midDestroyCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "destroyCustomCursor", "(I)V");
midGetContext = (*env)->GetStaticMethodID(env, mActivityClass, "getContext","()Landroid/content/Context;"); midGetContext = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/content/Context;");
midGetDisplayDPI = (*env)->GetStaticMethodID(env, mActivityClass, "getDisplayDPI", "()Landroid/util/DisplayMetrics;"); midGetDisplayDPI = (*env)->GetStaticMethodID(env, mActivityClass, "getDisplayDPI", "()Landroid/util/DisplayMetrics;");
midGetManifestEnvironmentVariables = (*env)->GetStaticMethodID(env, mActivityClass, "getManifestEnvironmentVariables", "()Z"); midGetManifestEnvironmentVariables = (*env)->GetStaticMethodID(env, mActivityClass, "getManifestEnvironmentVariables", "()Z");
midGetNativeSurface = (*env)->GetStaticMethodID(env, mActivityClass, "getNativeSurface","()Landroid/view/Surface;"); midGetNativeSurface = (*env)->GetStaticMethodID(env, mActivityClass, "getNativeSurface", "()Landroid/view/Surface;");
midInitTouch = (*env)->GetStaticMethodID(env, mActivityClass, "initTouch", "()V"); midInitTouch = (*env)->GetStaticMethodID(env, mActivityClass, "initTouch", "()V");
midIsAndroidTV = (*env)->GetStaticMethodID(env, mActivityClass, "isAndroidTV","()Z"); midIsAndroidTV = (*env)->GetStaticMethodID(env, mActivityClass, "isAndroidTV", "()Z");
midIsChromebook = (*env)->GetStaticMethodID(env, mActivityClass, "isChromebook", "()Z"); midIsChromebook = (*env)->GetStaticMethodID(env, mActivityClass, "isChromebook", "()Z");
midIsDeXMode = (*env)->GetStaticMethodID(env, mActivityClass, "isDeXMode", "()Z"); midIsDeXMode = (*env)->GetStaticMethodID(env, mActivityClass, "isDeXMode", "()Z");
midIsScreenKeyboardShown = (*env)->GetStaticMethodID(env, mActivityClass, "isScreenKeyboardShown","()Z"); midIsScreenKeyboardShown = (*env)->GetStaticMethodID(env, mActivityClass, "isScreenKeyboardShown", "()Z");
midIsTablet = (*env)->GetStaticMethodID(env, mActivityClass, "isTablet", "()Z"); midIsTablet = (*env)->GetStaticMethodID(env, mActivityClass, "isTablet", "()Z");
midManualBackButton = (*env)->GetStaticMethodID(env, mActivityClass, "manualBackButton", "()V"); midManualBackButton = (*env)->GetStaticMethodID(env, mActivityClass, "manualBackButton", "()V");
midMinimizeWindow = (*env)->GetStaticMethodID(env, mActivityClass, "minimizeWindow","()V"); midMinimizeWindow = (*env)->GetStaticMethodID(env, mActivityClass, "minimizeWindow", "()V");
midOpenURL = (*env)->GetStaticMethodID(env, mActivityClass, "openURL", "(Ljava/lang/String;)I"); midOpenURL = (*env)->GetStaticMethodID(env, mActivityClass, "openURL", "(Ljava/lang/String;)I");
midRequestPermission = (*env)->GetStaticMethodID(env, mActivityClass, "requestPermission", "(Ljava/lang/String;I)V"); midRequestPermission = (*env)->GetStaticMethodID(env, mActivityClass, "requestPermission", "(Ljava/lang/String;I)V");
midShowToast = (*env)->GetStaticMethodID(env, mActivityClass, "showToast", "(Ljava/lang/String;IIII)I"); midShowToast = (*env)->GetStaticMethodID(env, mActivityClass, "showToast", "(Ljava/lang/String;IIII)I");
midSendMessage = (*env)->GetStaticMethodID(env, mActivityClass, "sendMessage", "(II)Z"); midSendMessage = (*env)->GetStaticMethodID(env, mActivityClass, "sendMessage", "(II)Z");
midSetActivityTitle = (*env)->GetStaticMethodID(env, mActivityClass, "setActivityTitle","(Ljava/lang/String;)Z"); midSetActivityTitle = (*env)->GetStaticMethodID(env, mActivityClass, "setActivityTitle", "(Ljava/lang/String;)Z");
midSetCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "setCustomCursor", "(I)Z"); midSetCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "setCustomCursor", "(I)Z");
midSetOrientation = (*env)->GetStaticMethodID(env, mActivityClass, "setOrientation","(IIZLjava/lang/String;)V"); midSetOrientation = (*env)->GetStaticMethodID(env, mActivityClass, "setOrientation", "(IIZLjava/lang/String;)V");
midSetRelativeMouseEnabled = (*env)->GetStaticMethodID(env, mActivityClass, "setRelativeMouseEnabled", "(Z)Z"); midSetRelativeMouseEnabled = (*env)->GetStaticMethodID(env, mActivityClass, "setRelativeMouseEnabled", "(Z)Z");
midSetSystemCursor = (*env)->GetStaticMethodID(env, mActivityClass, "setSystemCursor", "(I)Z"); midSetSystemCursor = (*env)->GetStaticMethodID(env, mActivityClass, "setSystemCursor", "(I)Z");
midSetWindowStyle = (*env)->GetStaticMethodID(env, mActivityClass, "setWindowStyle","(Z)V"); midSetWindowStyle = (*env)->GetStaticMethodID(env, mActivityClass, "setWindowStyle", "(Z)V");
midShouldMinimizeOnFocusLoss = (*env)->GetStaticMethodID(env, mActivityClass, "shouldMinimizeOnFocusLoss","()Z"); midShouldMinimizeOnFocusLoss = (*env)->GetStaticMethodID(env, mActivityClass, "shouldMinimizeOnFocusLoss", "()Z");
midShowTextInput = (*env)->GetStaticMethodID(env, mActivityClass, "showTextInput", "(IIII)Z"); midShowTextInput = (*env)->GetStaticMethodID(env, mActivityClass, "showTextInput", "(IIII)Z");
midSupportsRelativeMouse = (*env)->GetStaticMethodID(env, mActivityClass, "supportsRelativeMouse", "()Z"); midSupportsRelativeMouse = (*env)->GetStaticMethodID(env, mActivityClass, "supportsRelativeMouse", "()Z");
@@ -777,7 +769,6 @@ JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeRunMain)(JNIEnv *env, jclass cls,
} }
argv[argc] = NULL; argv[argc] = NULL;
/* Run the application. */ /* Run the application. */
status = SDL_main(argc, argv); status = SDL_main(argc, argv);
@@ -821,16 +812,19 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
} }
/* Lock / Unlock Mutex */ /* Lock / Unlock Mutex */
void Android_ActivityMutex_Lock() { void Android_ActivityMutex_Lock()
{
SDL_LockMutex(Android_ActivityMutex); SDL_LockMutex(Android_ActivityMutex);
} }
void Android_ActivityMutex_Unlock() { void Android_ActivityMutex_Unlock()
{
SDL_UnlockMutex(Android_ActivityMutex); SDL_UnlockMutex(Android_ActivityMutex);
} }
/* Lock the Mutex when the Activity is in its 'Running' state */ /* Lock the Mutex when the Activity is in its 'Running' state */
void Android_ActivityMutex_Lock_Running() { void Android_ActivityMutex_Lock_Running()
{
int pauseSignaled = 0; int pauseSignaled = 0;
int resumeSignaled = 0; int resumeSignaled = 0;
@@ -891,18 +885,18 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeOrientationChanged)(
} }
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeAddTouch)( JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeAddTouch)(
JNIEnv* env, jclass cls, JNIEnv *env, jclass cls,
jint touchId, jstring name) jint touchId, jstring name)
{ {
const char *utfname = (*env)->GetStringUTFChars(env, name, NULL); const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
SDL_AddTouch((SDL_TouchID) touchId, SDL_TOUCH_DEVICE_DIRECT, utfname); SDL_AddTouch((SDL_TouchID)touchId, SDL_TOUCH_DEVICE_DIRECT, utfname);
(*env)->ReleaseStringUTFChars(env, name, utfname); (*env)->ReleaseStringUTFChars(env, name, utfname);
} }
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePermissionResult)( JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePermissionResult)(
JNIEnv* env, jclass cls, JNIEnv *env, jclass cls,
jint requestCode, jboolean result) jint requestCode, jboolean result)
{ {
bPermissionRequestResult = result; bPermissionRequestResult = result;
@@ -941,7 +935,6 @@ JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeHat)(
Android_OnHat(device_id, hat_id, x, y); Android_OnHat(device_id, hat_id, x, y);
} }
JNIEXPORT jint JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddJoystick)( JNIEXPORT jint JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddJoystick)(
JNIEnv *env, jclass jcls, JNIEnv *env, jclass jcls,
jint device_id, jstring device_name, jstring device_desc, jint device_id, jstring device_name, jstring device_desc,
@@ -992,7 +985,7 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceCreated)(JNIEnv *env, j
SDL_LockMutex(Android_ActivityMutex); SDL_LockMutex(Android_ActivityMutex);
if (Android_Window) { if (Android_Window) {
SDL_WindowData *data = (SDL_WindowData *) Android_Window->driverdata; SDL_WindowData *data = (SDL_WindowData *)Android_Window->driverdata;
data->native_window = Android_JNI_GetNativeWindow(); data->native_window = Android_JNI_GetNativeWindow();
if (data->native_window == NULL) { if (data->native_window == NULL) {
@@ -1011,11 +1004,11 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceChanged)(JNIEnv *env, j
#if SDL_VIDEO_OPENGL_EGL #if SDL_VIDEO_OPENGL_EGL
if (Android_Window) { if (Android_Window) {
SDL_VideoDevice *_this = SDL_GetVideoDevice(); SDL_VideoDevice *_this = SDL_GetVideoDevice();
SDL_WindowData *data = (SDL_WindowData *) Android_Window->driverdata; SDL_WindowData *data = (SDL_WindowData *)Android_Window->driverdata;
/* If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here */ /* If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here */
if (data->egl_surface == EGL_NO_SURFACE) { if (data->egl_surface == EGL_NO_SURFACE) {
data->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) data->native_window); data->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType)data->native_window);
} }
/* GL Context handling is done in the event loop because this function is run from the Java thread */ /* GL Context handling is done in the event loop because this function is run from the Java thread */
@@ -1036,10 +1029,10 @@ retry:
if (Android_Window) { if (Android_Window) {
SDL_VideoDevice *_this = SDL_GetVideoDevice(); SDL_VideoDevice *_this = SDL_GetVideoDevice();
SDL_WindowData *data = (SDL_WindowData *) Android_Window->driverdata; SDL_WindowData *data = (SDL_WindowData *)Android_Window->driverdata;
/* Wait for Main thread being paused and context un-activated to release 'egl_surface' */ /* Wait for Main thread being paused and context un-activated to release 'egl_surface' */
if (! data->backup_done) { if (!data->backup_done) {
nb_attempt -= 1; nb_attempt -= 1;
if (nb_attempt == 0) { if (nb_attempt == 0) {
SDL_SetError("Try to release egl_surface with context probably still active"); SDL_SetError("Try to release egl_surface with context probably still active");
@@ -1103,7 +1096,6 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost)(
SDL_StopTextInput(); SDL_StopTextInput();
} }
/* Touch */ /* Touch */
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)( JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
JNIEnv *env, jclass jcls, JNIEnv *env, jclass jcls,
@@ -1162,7 +1154,6 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeLocaleChanged)(
SDL_SendAppEvent(SDL_LOCALECHANGED); SDL_SendAppEvent(SDL_LOCALECHANGED);
} }
/* Send Quit event to "SDLThread" thread */ /* Send Quit event to "SDLThread" thread */
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSendQuit)( JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSendQuit)(
JNIEnv *env, jclass cls) JNIEnv *env, jclass cls)
@@ -1306,7 +1297,6 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetenv)(
(*env)->ReleaseStringUTFChars(env, name, utfname); (*env)->ReleaseStringUTFChars(env, name, utfname);
(*env)->ReleaseStringUTFChars(env, value, utfvalue); (*env)->ReleaseStringUTFChars(env, value, utfvalue);
} }
/******************************************************************************* /*******************************************************************************
@@ -1355,7 +1345,7 @@ static void LocalReferenceHolder_Cleanup(struct LocalReferenceHolder *refholder)
} }
} }
ANativeWindow* Android_JNI_GetNativeWindow(void) ANativeWindow *Android_JNI_GetNativeWindow(void)
{ {
ANativeWindow *anw = NULL; ANativeWindow *anw = NULL;
jobject s; jobject s;
@@ -1390,7 +1380,7 @@ void Android_JNI_SetOrientation(int w, int h, int resizable, const char *hint)
JNIEnv *env = Android_JNI_GetEnv(); JNIEnv *env = Android_JNI_GetEnv();
jstring jhint = (*env)->NewStringUTF(env, (hint ? hint : "")); jstring jhint = (*env)->NewStringUTF(env, (hint ? hint : ""));
(*env)->CallStaticVoidMethod(env, mActivityClass, midSetOrientation, w, h, (resizable? 1 : 0), jhint); (*env)->CallStaticVoidMethod(env, mActivityClass, midSetOrientation, w, h, (resizable ? 1 : 0), jhint);
(*env)->DeleteLocalRef(env, jhint); (*env)->DeleteLocalRef(env, jhint);
} }
@@ -1502,8 +1492,7 @@ int Android_JNI_OpenAudioDevice(int iscapture, SDL_AudioSpec *spec)
jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal); jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal);
(*env)->DeleteLocalRef(env, audioBufferLocal); (*env)->DeleteLocalRef(env, audioBufferLocal);
} }
} } break;
break;
case ENCODING_PCM_16BIT: case ENCODING_PCM_16BIT:
{ {
jshortArray audioBufferLocal = (*env)->NewShortArray(env, spec->samples * spec->channels); jshortArray audioBufferLocal = (*env)->NewShortArray(env, spec->samples * spec->channels);
@@ -1511,8 +1500,7 @@ int Android_JNI_OpenAudioDevice(int iscapture, SDL_AudioSpec *spec)
jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal); jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal);
(*env)->DeleteLocalRef(env, audioBufferLocal); (*env)->DeleteLocalRef(env, audioBufferLocal);
} }
} } break;
break;
case ENCODING_PCM_FLOAT: case ENCODING_PCM_FLOAT:
{ {
jfloatArray audioBufferLocal = (*env)->NewFloatArray(env, spec->samples * spec->channels); jfloatArray audioBufferLocal = (*env)->NewFloatArray(env, spec->samples * spec->channels);
@@ -1520,8 +1508,7 @@ int Android_JNI_OpenAudioDevice(int iscapture, SDL_AudioSpec *spec)
jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal); jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal);
(*env)->DeleteLocalRef(env, audioBufferLocal); (*env)->DeleteLocalRef(env, audioBufferLocal);
} }
} } break;
break;
default: default:
return SDL_SetError("Unexpected audio format from Java: %d\n", audioformat); return SDL_SetError("Unexpected audio format from Java: %d\n", audioformat);
} }
@@ -1579,7 +1566,6 @@ int Android_JNI_GetDisplayDPI(float *ddpi, float *xdpi, float *ydpi)
float nativeYdpi = (*env)->GetFloatField(env, jDisplayObj, fidYdpi); float nativeYdpi = (*env)->GetFloatField(env, jDisplayObj, fidYdpi);
int nativeDdpi = (*env)->GetIntField(env, jDisplayObj, fidDdpi); int nativeDdpi = (*env)->GetIntField(env, jDisplayObj, fidDdpi);
(*env)->DeleteLocalRef(env, jDisplayObj); (*env)->DeleteLocalRef(env, jDisplayObj);
(*env)->DeleteLocalRef(env, jDisplayClass); (*env)->DeleteLocalRef(env, jDisplayClass);
@@ -1596,7 +1582,7 @@ int Android_JNI_GetDisplayDPI(float *ddpi, float *xdpi, float *ydpi)
return 0; return 0;
} }
void * Android_JNI_GetAudioBuffer(void) void *Android_JNI_GetAudioBuffer(void)
{ {
return audioBufferPinned; return audioBufferPinned;
} }
@@ -1788,7 +1774,8 @@ static SDL_bool Android_JNI_ExceptionOccurred(SDL_bool silent)
return SDL_FALSE; return SDL_FALSE;
} }
static void Internal_Android_Create_AssetManager() { static void Internal_Android_Create_AssetManager()
{
struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__); struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
JNIEnv *env = Android_JNI_GetEnv(); JNIEnv *env = Android_JNI_GetEnv();
@@ -1826,7 +1813,8 @@ static void Internal_Android_Create_AssetManager() {
LocalReferenceHolder_Cleanup(&refs); LocalReferenceHolder_Cleanup(&refs);
} }
static void Internal_Android_Destroy_AssetManager() { static void Internal_Android_Destroy_AssetManager()
{
JNIEnv *env = Android_JNI_GetEnv(); JNIEnv *env = Android_JNI_GetEnv();
if (asset_manager) { if (asset_manager) {
@@ -1854,16 +1842,15 @@ int Android_JNI_FileOpen(SDL_RWops *ctx,
return -1; return -1;
} }
ctx->hidden.androidio.asset = (void *)asset;
ctx->hidden.androidio.asset = (void*) asset;
return 0; return 0;
} }
size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer, size_t Android_JNI_FileRead(SDL_RWops *ctx, void *buffer,
size_t size, size_t maxnum) size_t size, size_t maxnum)
{ {
size_t result; size_t result;
AAsset *asset = (AAsset*) ctx->hidden.androidio.asset; AAsset *asset = (AAsset *)ctx->hidden.androidio.asset;
result = AAsset_read(asset, buffer, size * maxnum); result = AAsset_read(asset, buffer, size * maxnum);
if (result > 0) { if (result > 0) {
@@ -1885,22 +1872,22 @@ size_t Android_JNI_FileWrite(SDL_RWops *ctx, const void *buffer,
Sint64 Android_JNI_FileSize(SDL_RWops *ctx) Sint64 Android_JNI_FileSize(SDL_RWops *ctx)
{ {
off64_t result; off64_t result;
AAsset *asset = (AAsset*) ctx->hidden.androidio.asset; AAsset *asset = (AAsset *)ctx->hidden.androidio.asset;
result = AAsset_getLength64(asset); result = AAsset_getLength64(asset);
return result; return result;
} }
Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence) Sint64 Android_JNI_FileSeek(SDL_RWops *ctx, Sint64 offset, int whence)
{ {
off64_t result; off64_t result;
AAsset *asset = (AAsset*) ctx->hidden.androidio.asset; AAsset *asset = (AAsset *)ctx->hidden.androidio.asset;
result = AAsset_seek64(asset, offset, whence); result = AAsset_seek64(asset, offset, whence);
return result; return result;
} }
int Android_JNI_FileClose(SDL_RWops *ctx) int Android_JNI_FileClose(SDL_RWops *ctx)
{ {
AAsset *asset = (AAsset*) ctx->hidden.androidio.asset; AAsset *asset = (AAsset *)ctx->hidden.androidio.asset;
AAsset_close(asset); AAsset_close(asset);
return 0; return 0;
} }
@@ -1914,7 +1901,7 @@ int Android_JNI_SetClipboardText(const char *text)
return 0; return 0;
} }
char* Android_JNI_GetClipboardText(void) char *Android_JNI_GetClipboardText(void)
{ {
JNIEnv *env = Android_JNI_GetEnv(); JNIEnv *env = Android_JNI_GetEnv();
char *text = NULL; char *text = NULL;
@@ -1963,7 +1950,6 @@ int Android_JNI_GetPowerInfo(int *plugged, int *charged, int *battery, int *seco
return -1; return -1;
} }
/* context = SDLActivity.getContext(); */ /* context = SDLActivity.getContext(); */
context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext); context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
@@ -2062,7 +2048,8 @@ int Android_JNI_GetPowerInfo(int *plugged, int *charged, int *battery, int *seco
} }
/* Add all touch devices */ /* Add all touch devices */
void Android_JNI_InitTouch() { void Android_JNI_InitTouch()
{
JNIEnv *env = Android_JNI_GetEnv(); JNIEnv *env = Android_JNI_GetEnv();
(*env)->CallStaticVoidMethod(env, mActivityClass, midInitTouch); (*env)->CallStaticVoidMethod(env, mActivityClass, midInitTouch);
} }
@@ -2094,7 +2081,6 @@ void Android_JNI_HapticStop(int device_id)
/* See SDLActivity.java for constants. */ /* See SDLActivity.java for constants. */
#define COMMAND_SET_KEEP_SCREEN_ON 5 #define COMMAND_SET_KEEP_SCREEN_ON 5
int SDL_AndroidSendMessage(Uint32 command, int param) int SDL_AndroidSendMessage(Uint32 command, int param)
{ {
if (command >= 0x8000) { if (command >= 0x8000) {
@@ -2124,7 +2110,7 @@ void Android_JNI_ShowTextInput(SDL_Rect *inputRect)
inputRect->x, inputRect->x,
inputRect->y, inputRect->y,
inputRect->w, inputRect->w,
inputRect->h ); inputRect->h);
} }
void Android_JNI_HideTextInput(void) void Android_JNI_HideTextInput(void)
@@ -2142,7 +2128,6 @@ SDL_bool Android_JNI_IsScreenKeyboardShown(void)
return is_shown; return is_shown;
} }
int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid) int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{ {
JNIEnv *env; JNIEnv *env;
@@ -2265,7 +2250,7 @@ int SDL_GetAndroidSDKVersion(void)
{ {
static int sdk_version; static int sdk_version;
if (!sdk_version) { if (!sdk_version) {
char sdk[PROP_VALUE_MAX] = {0}; char sdk[PROP_VALUE_MAX] = { 0 };
if (__system_property_get("ro.build.version.sdk", sdk) != 0) { if (__system_property_get("ro.build.version.sdk", sdk) != 0) {
sdk_version = SDL_atoi(sdk); sdk_version = SDL_atoi(sdk);
} }
@@ -2303,7 +2288,7 @@ void SDL_AndroidBackButton(void)
(*env)->CallStaticVoidMethod(env, mActivityClass, midManualBackButton); (*env)->CallStaticVoidMethod(env, mActivityClass, midManualBackButton);
} }
const char * SDL_AndroidGetInternalStoragePath(void) const char *SDL_AndroidGetInternalStoragePath(void)
{ {
static char *s_AndroidInternalFilesPath = NULL; static char *s_AndroidInternalFilesPath = NULL;
@@ -2396,7 +2381,7 @@ int SDL_AndroidGetExternalStorageState(void)
return stateFlags; return stateFlags;
} }
const char * SDL_AndroidGetExternalStoragePath(void) const char *SDL_AndroidGetExternalStoragePath(void)
{ {
static char *s_AndroidExternalFilesPath = NULL; static char *s_AndroidExternalFilesPath = NULL;
@@ -2446,7 +2431,7 @@ SDL_bool SDL_AndroidRequestPermission(const char *permission)
return Android_JNI_RequestPermission(permission); return Android_JNI_RequestPermission(permission);
} }
int SDL_AndroidShowToast(const char* message, int duration, int gravity, int xOffset, int yOffset) int SDL_AndroidShowToast(const char *message, int duration, int gravity, int xOffset, int yOffset)
{ {
return Android_JNI_ShowToast(message, duration, gravity, xOffset, yOffset); return Android_JNI_ShowToast(message, duration, gravity, xOffset, yOffset);
} }
@@ -2538,7 +2523,7 @@ SDL_bool Android_JNI_RequestPermission(const char *permission)
} }
/* Show toast notification */ /* Show toast notification */
int Android_JNI_ShowToast(const char* message, int duration, int gravity, int xOffset, int yOffset) int Android_JNI_ShowToast(const char *message, int duration, int gravity, int xOffset, int yOffset)
{ {
int result = 0; int result = 0;
JNIEnv *env = Android_JNI_GetEnv(); JNIEnv *env = Android_JNI_GetEnv();
@@ -2606,8 +2591,7 @@ int Android_JNI_GetLocale(char *buf, size_t buflen)
return 0; return 0;
} }
int int Android_JNI_OpenURL(const char *url)
Android_JNI_OpenURL(const char *url)
{ {
JNIEnv *env = Android_JNI_GetEnv(); JNIEnv *env = Android_JNI_GetEnv();
jstring jurl = (*env)->NewStringUTF(env, url); jstring jurl = (*env)->NewStringUTF(env, url);

View File

@@ -30,7 +30,6 @@ extern "C" {
#include <EGL/eglplatform.h> #include <EGL/eglplatform.h>
#include <android/native_window_jni.h> #include <android/native_window_jni.h>
/* Interface from the SDL library into the Android Java activity */ /* Interface from the SDL library into the Android Java activity */
extern void Android_JNI_SetActivityTitle(const char *title); extern void Android_JNI_SetActivityTitle(const char *title);
extern void Android_JNI_SetWindowStyle(SDL_bool fullscreen); extern void Android_JNI_SetWindowStyle(SDL_bool fullscreen);
@@ -42,14 +41,14 @@ extern SDL_bool Android_JNI_GetAccelerometerValues(float values[3]);
extern void Android_JNI_ShowTextInput(SDL_Rect *inputRect); extern void Android_JNI_ShowTextInput(SDL_Rect *inputRect);
extern void Android_JNI_HideTextInput(void); extern void Android_JNI_HideTextInput(void);
extern SDL_bool Android_JNI_IsScreenKeyboardShown(void); extern SDL_bool Android_JNI_IsScreenKeyboardShown(void);
extern ANativeWindow* Android_JNI_GetNativeWindow(void); extern ANativeWindow *Android_JNI_GetNativeWindow(void);
extern SDL_DisplayOrientation Android_JNI_GetDisplayOrientation(void); extern SDL_DisplayOrientation Android_JNI_GetDisplayOrientation(void);
extern int Android_JNI_GetDisplayDPI(float *ddpi, float *xdpi, float *ydpi); extern int Android_JNI_GetDisplayDPI(float *ddpi, float *xdpi, float *ydpi);
/* Audio support */ /* Audio support */
extern int Android_JNI_OpenAudioDevice(int iscapture, SDL_AudioSpec *spec); extern int Android_JNI_OpenAudioDevice(int iscapture, SDL_AudioSpec *spec);
extern void* Android_JNI_GetAudioBuffer(void); extern void *Android_JNI_GetAudioBuffer(void);
extern void Android_JNI_WriteAudioBuffer(void); extern void Android_JNI_WriteAudioBuffer(void);
extern int Android_JNI_CaptureAudioBuffer(void *buffer, int buflen); extern int Android_JNI_CaptureAudioBuffer(void *buffer, int buflen);
extern void Android_JNI_FlushCapturedAudio(void); extern void Android_JNI_FlushCapturedAudio(void);
@@ -60,24 +59,23 @@ extern void Android_JNI_AudioSetThreadPriority(int iscapture, int device_id);
extern SDL_bool Android_IsDeXMode(void); extern SDL_bool Android_IsDeXMode(void);
extern SDL_bool Android_IsChromebook(void); extern SDL_bool Android_IsChromebook(void);
int Android_JNI_FileOpen(SDL_RWops *ctx, const char *fileName, const char *mode);
int Android_JNI_FileOpen(SDL_RWops* ctx, const char* fileName, const char* mode); Sint64 Android_JNI_FileSize(SDL_RWops *ctx);
Sint64 Android_JNI_FileSize(SDL_RWops* ctx); Sint64 Android_JNI_FileSeek(SDL_RWops *ctx, Sint64 offset, int whence);
Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence); size_t Android_JNI_FileRead(SDL_RWops *ctx, void *buffer, size_t size, size_t maxnum);
size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer, size_t size, size_t maxnum); size_t Android_JNI_FileWrite(SDL_RWops *ctx, const void *buffer, size_t size, size_t num);
size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer, size_t size, size_t num); int Android_JNI_FileClose(SDL_RWops *ctx);
int Android_JNI_FileClose(SDL_RWops* ctx);
/* Environment support */ /* Environment support */
void Android_JNI_GetManifestEnvironmentVariables(void); void Android_JNI_GetManifestEnvironmentVariables(void);
/* Clipboard support */ /* Clipboard support */
int Android_JNI_SetClipboardText(const char* text); int Android_JNI_SetClipboardText(const char *text);
char* Android_JNI_GetClipboardText(void); char *Android_JNI_GetClipboardText(void);
SDL_bool Android_JNI_HasClipboardText(void); SDL_bool Android_JNI_HasClipboardText(void);
/* Power support */ /* Power support */
int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent); int Android_JNI_GetPowerInfo(int *plugged, int *charged, int *battery, int *seconds, int *percent);
/* Joystick support */ /* Joystick support */
void Android_JNI_PollInputDevices(void); void Android_JNI_PollInputDevices(void);
@@ -105,7 +103,7 @@ int Android_JNI_GetLocale(char *buf, size_t buflen);
int Android_JNI_SendMessage(int command, int param); int Android_JNI_SendMessage(int command, int param);
/* Init */ /* Init */
JNIEXPORT void JNICALL SDL_Android_Init(JNIEnv* mEnv, jclass cls); JNIEXPORT void JNICALL SDL_Android_Init(JNIEnv *mEnv, jclass cls);
/* MessageBox */ /* MessageBox */
int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid); int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid);
@@ -124,7 +122,7 @@ SDL_bool Android_JNI_SetRelativeMouseEnabled(SDL_bool enabled);
SDL_bool Android_JNI_RequestPermission(const char *permission); SDL_bool Android_JNI_RequestPermission(const char *permission);
/* Show toast notification */ /* Show toast notification */
int Android_JNI_ShowToast(const char* message, int duration, int gravity, int xOffset, int yOffset); int Android_JNI_ShowToast(const char *message, int duration, int gravity, int xOffset, int yOffset);
int Android_JNI_OpenURL(const char *url); int Android_JNI_OpenURL(const char *url);

View File

@@ -1,5 +1,6 @@
#include <sys/kbio.h> #include <sys/kbio.h>
/* *INDENT-OFF* */ /* clang-format off */
/* /*
* Automatically generated from /usr/share/vt/keymaps/us.acc.kbd. * Automatically generated from /usr/share/vt/keymaps/us.acc.kbd.
* DO NOT EDIT! * DO NOT EDIT!
@@ -163,3 +164,4 @@ static accentmap_t accentmap_default_us_acc = { 11, {
{ 0x00 }, { 0x00 },
} }; } };
/* *INDENT-ON* */ /* clang-format on */

View File

@@ -38,7 +38,7 @@
#include "../../events/SDL_events_c.h" #include "../../events/SDL_events_c.h"
#include "SDL_evdev_kbd_default_keyaccmap.h" #include "SDL_evdev_kbd_default_keyaccmap.h"
typedef void (fn_handler_fn)(SDL_EVDEV_keyboard_state *kbd); typedef void(fn_handler_fn)(SDL_EVDEV_keyboard_state *kbd);
/* /*
* Keyboard State * Keyboard State
@@ -50,8 +50,8 @@ struct SDL_EVDEV_keyboard_state
int keyboard_fd; int keyboard_fd;
unsigned long old_kbd_mode; unsigned long old_kbd_mode;
unsigned short **key_maps; unsigned short **key_maps;
keymap_t* key_map; keymap_t *key_map;
keyboard_info_t* kbInfo; keyboard_info_t *kbInfo;
unsigned char shift_down[4]; /* shift state counters.. */ unsigned char shift_down[4]; /* shift state counters.. */
SDL_bool dead_key_next; SDL_bool dead_key_next;
int npadch; /* -1 or number assembled on pad */ int npadch; /* -1 or number assembled on pad */
@@ -70,14 +70,13 @@ static int SDL_EVDEV_kbd_load_keymaps(SDL_EVDEV_keyboard_state *kbd)
return ioctl(kbd->keyboard_fd, GIO_KEYMAP, kbd->key_map) >= 0; return ioctl(kbd->keyboard_fd, GIO_KEYMAP, kbd->key_map) >= 0;
} }
static SDL_EVDEV_keyboard_state * kbd_cleanup_state = NULL; static SDL_EVDEV_keyboard_state *kbd_cleanup_state = NULL;
static int kbd_cleanup_sigactions_installed = 0; static int kbd_cleanup_sigactions_installed = 0;
static int kbd_cleanup_atexit_installed = 0; static int kbd_cleanup_atexit_installed = 0;
static struct sigaction old_sigaction[NSIG]; static struct sigaction old_sigaction[NSIG];
static int fatal_signals[] = static int fatal_signals[] = {
{
/* Handlers for SIGTERM and SIGINT are installed in SDL_QuitInit. */ /* Handlers for SIGTERM and SIGINT are installed in SDL_QuitInit. */
SIGHUP, SIGQUIT, SIGILL, SIGABRT, SIGHUP, SIGQUIT, SIGILL, SIGABRT,
SIGFPE, SIGSEGV, SIGPIPE, SIGBUS, SIGFPE, SIGSEGV, SIGPIPE, SIGBUS,
@@ -87,7 +86,7 @@ static int fatal_signals[] =
static void kbd_cleanup(void) static void kbd_cleanup(void)
{ {
struct mouse_info mData; struct mouse_info mData;
SDL_EVDEV_keyboard_state* kbd = kbd_cleanup_state; SDL_EVDEV_keyboard_state *kbd = kbd_cleanup_state;
if (kbd == NULL) { if (kbd == NULL) {
return; return;
} }
@@ -102,18 +101,17 @@ static void kbd_cleanup(void)
ioctl(kbd->console_fd, CONS_MOUSECTL, &mData); ioctl(kbd->console_fd, CONS_MOUSECTL, &mData);
} }
void void SDL_EVDEV_kbd_reraise_signal(int sig)
SDL_EVDEV_kbd_reraise_signal(int sig)
{ {
raise(sig); raise(sig);
} }
siginfo_t* SDL_EVDEV_kdb_cleanup_siginfo = NULL; siginfo_t *SDL_EVDEV_kdb_cleanup_siginfo = NULL;
void* SDL_EVDEV_kdb_cleanup_ucontext = NULL; void *SDL_EVDEV_kdb_cleanup_ucontext = NULL;
static void kbd_cleanup_signal_action(int signum, siginfo_t* info, void* ucontext) static void kbd_cleanup_signal_action(int signum, siginfo_t *info, void *ucontext)
{ {
struct sigaction* old_action_p = &(old_sigaction[signum]); struct sigaction *old_action_p = &(old_sigaction[signum]);
sigset_t sigset; sigset_t sigset;
/* Restore original signal handler before going any further. */ /* Restore original signal handler before going any further. */
@@ -147,7 +145,7 @@ static void kbd_unregister_emerg_cleanup()
kbd_cleanup_sigactions_installed = 0; kbd_cleanup_sigactions_installed = 0;
for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) { for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) {
struct sigaction* old_action_p; struct sigaction *old_action_p;
struct sigaction cur_action; struct sigaction cur_action;
signum = fatal_signals[tabidx]; signum = fatal_signals[tabidx];
old_action_p = &(old_sigaction[signum]); old_action_p = &(old_sigaction[signum]);
@@ -176,7 +174,7 @@ static void kbd_cleanup_atexit(void)
kbd_unregister_emerg_cleanup(); kbd_unregister_emerg_cleanup();
} }
static void kbd_register_emerg_cleanup(SDL_EVDEV_keyboard_state * kbd) static void kbd_register_emerg_cleanup(SDL_EVDEV_keyboard_state *kbd)
{ {
int tabidx, signum; int tabidx, signum;
@@ -200,7 +198,7 @@ static void kbd_register_emerg_cleanup(SDL_EVDEV_keyboard_state * kbd)
kbd_cleanup_sigactions_installed = 1; kbd_cleanup_sigactions_installed = 1;
for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) { for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) {
struct sigaction* old_action_p; struct sigaction *old_action_p;
struct sigaction new_action; struct sigaction new_action;
signum = fatal_signals[tabidx]; signum = fatal_signals[tabidx];
old_action_p = &(old_sigaction[signum]); old_action_p = &(old_sigaction[signum]);
@@ -211,7 +209,7 @@ static void kbd_register_emerg_cleanup(SDL_EVDEV_keyboard_state * kbd)
/* Skip SIGHUP and SIGPIPE if handler is already installed /* Skip SIGHUP and SIGPIPE if handler is already installed
* - assume the handler will do the cleanup * - assume the handler will do the cleanup
*/ */
if ((signum == SIGHUP || signum == SIGPIPE) && (old_action_p->sa_handler != SIG_DFL || (void(*)(int))old_action_p->sa_sigaction != SIG_DFL)) { if ((signum == SIGHUP || signum == SIGPIPE) && (old_action_p->sa_handler != SIG_DFL || (void (*)(int))old_action_p->sa_sigaction != SIG_DFL)) {
continue; continue;
} }
@@ -228,7 +226,7 @@ SDL_EVDEV_kbd_init(void)
SDL_EVDEV_keyboard_state *kbd; SDL_EVDEV_keyboard_state *kbd;
struct mouse_info mData; struct mouse_info mData;
char flag_state; char flag_state;
char* devicePath; char *devicePath;
SDL_zero(mData); SDL_zero(mData);
mData.operation = MOUSE_HIDE; mData.operation = MOUSE_HIDE;
@@ -288,14 +286,14 @@ SDL_EVDEV_kbd_init(void)
kbd_register_emerg_cleanup(kbd); kbd_register_emerg_cleanup(kbd);
} }
SDL_free(devicePath); SDL_free(devicePath);
} else kbd->keyboard_fd = kbd->console_fd; } else
kbd->keyboard_fd = kbd->console_fd;
} }
return kbd; return kbd;
} }
void void SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *kbd)
SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *kbd)
{ {
struct mouse_info mData; struct mouse_info mData;
@@ -329,7 +327,7 @@ SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *kbd)
static void put_queue(SDL_EVDEV_keyboard_state *kbd, uint c) static void put_queue(SDL_EVDEV_keyboard_state *kbd, uint c)
{ {
/* c is already part of a UTF-8 sequence and safe to add as a character */ /* c is already part of a UTF-8 sequence and safe to add as a character */
if (kbd->text_len < (sizeof(kbd->text)-1)) { if (kbd->text_len < (sizeof(kbd->text) - 1)) {
kbd->text[kbd->text_len++] = (char)c; kbd->text[kbd->text_len++] = (char)c;
} }
} }
@@ -470,8 +468,7 @@ static void k_shift(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_
} }
} }
void void SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *kbd, unsigned int keycode, int down)
SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *kbd, unsigned int keycode, int down)
{ {
keymap_t key_map; keymap_t key_map;
struct keyent_t keysym; struct keyent_t keysym;
@@ -525,7 +522,7 @@ SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *kbd, unsigned int keycode, int d
k_deadunicode(kbd, kbd->accents->acc[accent_index].accchar, !down); k_deadunicode(kbd, kbd->accents->acc[accent_index].accchar, !down);
} }
} else { } else {
switch(map_from_key_sym) { switch (map_from_key_sym) {
case ASH: /* alt/meta shift */ case ASH: /* alt/meta shift */
k_shift(kbd, 3, down == 0); k_shift(kbd, 3, down == 0);
break; break;

View File

@@ -35,7 +35,7 @@ PAPPSTATE_REGISTRATION hPLM = {};
HANDLE plmSuspendComplete = nullptr; HANDLE plmSuspendComplete = nullptr;
extern "C" DECLSPEC int extern "C" DECLSPEC int
SDL_GDKGetTaskQueue(XTaskQueueHandle * outTaskQueue) SDL_GDKGetTaskQueue(XTaskQueueHandle *outTaskQueue)
{ {
/* If this is the first call, first create the global task queue. */ /* If this is the first call, first create the global task queue. */
if (!GDK_GlobalTaskQueue) { if (!GDK_GlobalTaskQueue) {
@@ -43,8 +43,7 @@ SDL_GDKGetTaskQueue(XTaskQueueHandle * outTaskQueue)
hr = XTaskQueueCreate(XTaskQueueDispatchMode::ThreadPool, hr = XTaskQueueCreate(XTaskQueueDispatchMode::ThreadPool,
XTaskQueueDispatchMode::Manual, XTaskQueueDispatchMode::Manual,
&GDK_GlobalTaskQueue &GDK_GlobalTaskQueue);
);
if (FAILED(hr)) { if (FAILED(hr)) {
return SDL_SetError("[GDK] Could not create global task queue"); return SDL_SetError("[GDK] Could not create global task queue");
} }
@@ -104,7 +103,7 @@ SDL_GDKRunApp(SDL_main_func mainFunction, void *reserved)
*/ */
/* Parse it into argv and argc */ /* Parse it into argv and argc */
argv = (char **) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (argc + 1) * sizeof(*argv)); argv = (char **)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (argc + 1) * sizeof(*argv));
if (argv == NULL) { if (argv == NULL) {
return OutOfMemory(); return OutOfMemory();
} }
@@ -114,8 +113,8 @@ SDL_GDKRunApp(SDL_main_func mainFunction, void *reserved)
if (arg == NULL) { if (arg == NULL) {
return OutOfMemory(); return OutOfMemory();
} }
len = (DWORD) SDL_strlen(arg); len = (DWORD)SDL_strlen(arg);
argv[i] = (char *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len + 1); argv[i] = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len + 1);
if (!argv[i]) { if (!argv[i]) {
return OutOfMemory(); return OutOfMemory();
} }
@@ -150,12 +149,11 @@ SDL_GDKRunApp(SDL_main_func mainFunction, void *reserved)
/* Register suspend/resume handling */ /* Register suspend/resume handling */
plmSuspendComplete = CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE); plmSuspendComplete = CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE);
if (!plmSuspendComplete ) { if (!plmSuspendComplete) {
SDL_SetError("[GDK] Unable to create plmSuspendComplete event"); SDL_SetError("[GDK] Unable to create plmSuspendComplete event");
return -1; return -1;
} }
auto rascn = [](BOOLEAN quiesced, PVOID context) auto rascn = [](BOOLEAN quiesced, PVOID context) {
{
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "[GDK] in RegisterAppStateChangeNotification handler"); SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "[GDK] in RegisterAppStateChangeNotification handler");
if (quiesced) { if (quiesced) {
ResetEvent(plmSuspendComplete); ResetEvent(plmSuspendComplete);
@@ -210,7 +208,8 @@ SDL_GDKRunApp(SDL_main_func mainFunction, void *reserved)
} }
extern "C" DECLSPEC void extern "C" DECLSPEC void
SDL_GDKSuspendComplete() { SDL_GDKSuspendComplete()
{
if (plmSuspendComplete) { if (plmSuspendComplete) {
SetEvent(plmSuspendComplete); SetEvent(plmSuspendComplete);
} }

View File

@@ -31,13 +31,13 @@ static char *inhibit_handle = NULL;
static unsigned int screensaver_cookie = 0; static unsigned int screensaver_cookie = 0;
static SDL_DBusContext dbus; static SDL_DBusContext dbus;
static int static int LoadDBUSSyms(void)
LoadDBUSSyms(void)
{ {
#define SDL_DBUS_SYM2(x, y) \ #define SDL_DBUS_SYM2(x, y) \
if (!(dbus.x = SDL_LoadFunction(dbus_handle, #y))) return -1 if (!(dbus.x = SDL_LoadFunction(dbus_handle, #y))) \
return -1
#define SDL_DBUS_SYM(x) \ #define SDL_DBUS_SYM(x) \
SDL_DBUS_SYM2(x, dbus_##x) SDL_DBUS_SYM2(x, dbus_##x)
SDL_DBUS_SYM(bus_get_private); SDL_DBUS_SYM(bus_get_private);
@@ -80,14 +80,13 @@ LoadDBUSSyms(void)
SDL_DBUS_SYM(free_string_array); SDL_DBUS_SYM(free_string_array);
SDL_DBUS_SYM(shutdown); SDL_DBUS_SYM(shutdown);
#undef SDL_DBUS_SYM #undef SDL_DBUS_SYM
#undef SDL_DBUS_SYM2 #undef SDL_DBUS_SYM2
return 0; return 0;
} }
static void static void UnloadDBUSLibrary(void)
UnloadDBUSLibrary(void)
{ {
if (dbus_handle != NULL) { if (dbus_handle != NULL) {
SDL_UnloadObject(dbus_handle); SDL_UnloadObject(dbus_handle);
@@ -95,8 +94,7 @@ UnloadDBUSLibrary(void)
} }
} }
static int static int LoadDBUSLibrary(void)
LoadDBUSLibrary(void)
{ {
int retval = 0; int retval = 0;
if (dbus_handle == NULL) { if (dbus_handle == NULL) {
@@ -115,12 +113,10 @@ LoadDBUSLibrary(void)
return retval; return retval;
} }
static SDL_SpinLock spinlock_dbus_init = 0; static SDL_SpinLock spinlock_dbus_init = 0;
/* you must hold spinlock_dbus_init before calling this! */ /* you must hold spinlock_dbus_init before calling this! */
static void static void SDL_DBus_Init_Spinlocked(void)
SDL_DBus_Init_Spinlocked(void)
{ {
static SDL_bool is_dbus_available = SDL_TRUE; static SDL_bool is_dbus_available = SDL_TRUE;
if (!is_dbus_available) { if (!is_dbus_available) {
@@ -132,7 +128,7 @@ SDL_DBus_Init_Spinlocked(void)
if (LoadDBUSLibrary() == -1) { if (LoadDBUSLibrary() == -1) {
is_dbus_available = SDL_FALSE; /* can't load at all? Don't keep trying. */ is_dbus_available = SDL_FALSE; /* can't load at all? Don't keep trying. */
return; /* oh well */ return;
} }
if (!dbus.threads_init_default()) { if (!dbus.threads_init_default()) {
@@ -162,16 +158,14 @@ SDL_DBus_Init_Spinlocked(void)
} }
} }
void void SDL_DBus_Init(void)
SDL_DBus_Init(void)
{ {
SDL_AtomicLock(&spinlock_dbus_init); /* make sure two threads can't init at same time, since this can happen before SDL_Init. */ SDL_AtomicLock(&spinlock_dbus_init); /* make sure two threads can't init at same time, since this can happen before SDL_Init. */
SDL_DBus_Init_Spinlocked(); SDL_DBus_Init_Spinlocked();
SDL_AtomicUnlock(&spinlock_dbus_init); SDL_AtomicUnlock(&spinlock_dbus_init);
} }
void void SDL_DBus_Quit(void)
SDL_DBus_Quit(void)
{ {
if (dbus.system_conn) { if (dbus.system_conn) {
dbus.connection_close(dbus.system_conn); dbus.connection_close(dbus.system_conn);
@@ -205,8 +199,7 @@ SDL_DBus_GetContext(void)
return (dbus_handle && dbus.session_conn) ? &dbus : NULL; return (dbus_handle && dbus.session_conn) ? &dbus : NULL;
} }
static SDL_bool static SDL_bool SDL_DBus_CallMethodInternal(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, va_list ap)
SDL_DBus_CallMethodInternal(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, va_list ap)
{ {
SDL_bool retval = SDL_FALSE; SDL_bool retval = SDL_FALSE;
@@ -223,9 +216,15 @@ SDL_DBus_CallMethodInternal(DBusConnection *conn, const char *node, const char *
/* skip any input args, get to output args. */ /* skip any input args, get to output args. */
while ((firstarg = va_arg(ap_reply, int)) != DBUS_TYPE_INVALID) { while ((firstarg = va_arg(ap_reply, int)) != DBUS_TYPE_INVALID) {
/* we assume D-Bus already validated all this. */ /* we assume D-Bus already validated all this. */
{ void *dumpptr = va_arg(ap_reply, void*); (void) dumpptr; } {
void *dumpptr = va_arg(ap_reply, void *);
(void)dumpptr;
}
if (firstarg == DBUS_TYPE_ARRAY) { if (firstarg == DBUS_TYPE_ARRAY) {
{ const int dumpint = va_arg(ap_reply, int); (void) dumpint; } {
const int dumpint = va_arg(ap_reply, int);
(void)dumpint;
}
} }
} }
firstarg = va_arg(ap_reply, int); firstarg = va_arg(ap_reply, int);
@@ -265,8 +264,7 @@ SDL_DBus_CallMethod(const char *node, const char *path, const char *interface, c
return retval; return retval;
} }
static SDL_bool static SDL_bool SDL_DBus_CallVoidMethodInternal(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, va_list ap)
SDL_DBus_CallVoidMethodInternal(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, va_list ap)
{ {
SDL_bool retval = SDL_FALSE; SDL_bool retval = SDL_FALSE;
@@ -288,8 +286,7 @@ SDL_DBus_CallVoidMethodInternal(DBusConnection *conn, const char *node, const ch
return retval; return retval;
} }
static SDL_bool static SDL_bool SDL_DBus_CallWithBasicReply(DBusConnection *conn, DBusMessage *msg, const int expectedtype, void *result)
SDL_DBus_CallWithBasicReply(DBusConnection *conn, DBusMessage *msg, const int expectedtype, void *result)
{ {
SDL_bool retval = SDL_FALSE; SDL_bool retval = SDL_FALSE;
@@ -360,9 +357,7 @@ SDL_DBus_QueryProperty(const char *node, const char *path, const char *interface
return SDL_DBus_QueryPropertyOnConnection(dbus.session_conn, node, path, interface, property, expectedtype, result); return SDL_DBus_QueryPropertyOnConnection(dbus.session_conn, node, path, interface, property, expectedtype, result);
} }
void SDL_DBus_ScreensaverTickle(void)
void
SDL_DBus_ScreensaverTickle(void)
{ {
if (screensaver_cookie == 0 && inhibit_handle == NULL) { /* no need to tickle if we're inhibiting. */ if (screensaver_cookie == 0 && inhibit_handle == NULL) { /* no need to tickle if we're inhibiting. */
/* org.gnome.ScreenSaver is the legacy interface, but it'll either do nothing or just be a second harmless tickle on newer systems, so we leave it for now. */ /* org.gnome.ScreenSaver is the legacy interface, but it'll either do nothing or just be a second harmless tickle on newer systems, so we leave it for now. */
@@ -371,8 +366,7 @@ SDL_DBus_ScreensaverTickle(void)
} }
} }
static SDL_bool static SDL_bool SDL_DBus_AppendDictWithKeyValue(DBusMessageIter *iterInit, const char *key, const char *value)
SDL_DBus_AppendDictWithKeyValue(DBusMessageIter *iterInit, const char *key, const char *value)
{ {
DBusMessageIter iterDict, iterEntry, iterValue; DBusMessageIter iterDict, iterEntry, iterValue;
@@ -396,9 +390,7 @@ SDL_DBus_AppendDictWithKeyValue(DBusMessageIter *iterInit, const char *key, cons
goto failed; goto failed;
} }
if (!dbus.message_iter_close_container(&iterEntry, &iterValue) if (!dbus.message_iter_close_container(&iterEntry, &iterValue) || !dbus.message_iter_close_container(&iterDict, &iterEntry) || !dbus.message_iter_close_container(iterInit, &iterDict)) {
|| !dbus.message_iter_close_container(&iterDict, &iterEntry)
|| !dbus.message_iter_close_container(iterInit, &iterDict)) {
goto failed; goto failed;
} }
@@ -416,8 +408,7 @@ SDL_DBus_ScreensaverInhibit(SDL_bool inhibit)
{ {
const char *default_inhibit_reason = "Playing a game"; const char *default_inhibit_reason = "Playing a game";
if ( (inhibit && (screensaver_cookie != 0 || inhibit_handle != NULL)) if ((inhibit && (screensaver_cookie != 0 || inhibit_handle != NULL)) || (!inhibit && (screensaver_cookie == 0 && inhibit_handle == NULL))) {
|| (!inhibit && (screensaver_cookie == 0 && inhibit_handle == NULL)) ) {
return SDL_TRUE; return SDL_TRUE;
} }

View File

@@ -28,15 +28,15 @@
#define SDL_USE_LIBDBUS 1 #define SDL_USE_LIBDBUS 1
#include <dbus/dbus.h> #include <dbus/dbus.h>
typedef struct SDL_DBusContext
typedef struct SDL_DBusContext { {
DBusConnection *session_conn; DBusConnection *session_conn;
DBusConnection *system_conn; DBusConnection *system_conn;
DBusConnection *(*bus_get_private)(DBusBusType, DBusError *); DBusConnection *(*bus_get_private)(DBusBusType, DBusError *);
dbus_bool_t (*bus_register)(DBusConnection *, DBusError *); dbus_bool_t (*bus_register)(DBusConnection *, DBusError *);
void (*bus_add_match)(DBusConnection *, const char *, DBusError *); void (*bus_add_match)(DBusConnection *, const char *, DBusError *);
DBusConnection * (*connection_open_private)(const char *, DBusError *); DBusConnection *(*connection_open_private)(const char *, DBusError *);
void (*connection_set_exit_on_disconnect)(DBusConnection *, dbus_bool_t); void (*connection_set_exit_on_disconnect)(DBusConnection *, dbus_bool_t);
dbus_bool_t (*connection_get_is_connected)(DBusConnection *); dbus_bool_t (*connection_get_is_connected)(DBusConnection *);
dbus_bool_t (*connection_add_filter)(DBusConnection *, DBusHandleMessageFunction, void *, DBusFreeFunction); dbus_bool_t (*connection_add_filter)(DBusConnection *, DBusHandleMessageFunction, void *, DBusFreeFunction);
@@ -78,7 +78,7 @@ typedef struct SDL_DBusContext {
extern void SDL_DBus_Init(void); extern void SDL_DBus_Init(void);
extern void SDL_DBus_Quit(void); extern void SDL_DBus_Quit(void);
extern SDL_DBusContext * SDL_DBus_GetContext(void); extern SDL_DBusContext *SDL_DBus_GetContext(void);
/* These use the built-in Session connection. */ /* These use the built-in Session connection. */
extern SDL_bool SDL_DBus_CallMethod(const char *node, const char *path, const char *interface, const char *method, ...); extern SDL_bool SDL_DBus_CallMethod(const char *node, const char *path, const char *interface, const char *method, ...);

View File

@@ -71,8 +71,9 @@ typedef struct SDL_evdevlist_item
keyboard, touchpad, etc.). Also there's probably some things in here we keyboard, touchpad, etc.). Also there's probably some things in here we
can pull out to the SDL_evdevlist_item i.e. name */ can pull out to the SDL_evdevlist_item i.e. name */
SDL_bool is_touchscreen; SDL_bool is_touchscreen;
struct { struct
char* name; {
char *name;
int min_x, max_x, range_x; int min_x, max_x, range_x;
int min_y, max_y, range_y; int min_y, max_y, range_y;
@@ -80,8 +81,10 @@ typedef struct SDL_evdevlist_item
int max_slots; int max_slots;
int current_slot; int current_slot;
struct { struct
enum { {
enum
{
EVDEV_TOUCH_SLOTDELTA_NONE = 0, EVDEV_TOUCH_SLOTDELTA_NONE = 0,
EVDEV_TOUCH_SLOTDELTA_DOWN, EVDEV_TOUCH_SLOTDELTA_DOWN,
EVDEV_TOUCH_SLOTDELTA_UP, EVDEV_TOUCH_SLOTDELTA_UP,
@@ -137,19 +140,16 @@ static Uint8 EVDEV_MouseButtons[] = {
SDL_BUTTON_X2 + 3 /* BTN_TASK 0x117 */ SDL_BUTTON_X2 + 3 /* BTN_TASK 0x117 */
}; };
static int static int SDL_EVDEV_SetRelativeMouseMode(SDL_bool enabled)
SDL_EVDEV_SetRelativeMouseMode(SDL_bool enabled)
{ {
/* Mice already send relative events through this interface */ /* Mice already send relative events through this interface */
return 0; return 0;
} }
int SDL_EVDEV_Init(void)
int
SDL_EVDEV_Init(void)
{ {
if (_this == NULL) { if (_this == NULL) {
_this = (SDL_EVDEV_PrivateData*)SDL_calloc(1, sizeof(*_this)); _this = (SDL_EVDEV_PrivateData *)SDL_calloc(1, sizeof(*_this));
if (_this == NULL) { if (_this == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -179,14 +179,14 @@ SDL_EVDEV_Init(void)
where device class is an integer representing the where device class is an integer representing the
SDL_UDEV_deviceclass and path is the full path to SDL_UDEV_deviceclass and path is the full path to
the event device. */ the event device. */
const char* devices = SDL_getenv("SDL_EVDEV_DEVICES"); const char *devices = SDL_getenv("SDL_EVDEV_DEVICES");
if (devices) { if (devices) {
/* Assume this is the old use of the env var and it is not in /* Assume this is the old use of the env var and it is not in
ROM. */ ROM. */
char* rest = (char*) devices; char *rest = (char *)devices;
char* spec; char *spec;
while ((spec = SDL_strtokr(rest, ",", &rest))) { while ((spec = SDL_strtokr(rest, ",", &rest))) {
char* endofcls = 0; char *endofcls = 0;
long cls = SDL_strtol(spec, &endofcls, 0); long cls = SDL_strtol(spec, &endofcls, 0);
if (endofcls) { if (endofcls) {
SDL_EVDEV_device_added(endofcls + 1, cls); SDL_EVDEV_device_added(endofcls + 1, cls);
@@ -208,8 +208,7 @@ SDL_EVDEV_Init(void)
return 0; return 0;
} }
void void SDL_EVDEV_Quit(void)
SDL_EVDEV_Quit(void)
{ {
if (_this == NULL) { if (_this == NULL) {
return; return;
@@ -241,13 +240,13 @@ SDL_EVDEV_Quit(void)
#if SDL_USE_LIBUDEV #if SDL_USE_LIBUDEV
static void SDL_EVDEV_udev_callback(SDL_UDEV_deviceevent udev_event, int udev_class, static void SDL_EVDEV_udev_callback(SDL_UDEV_deviceevent udev_event, int udev_class,
const char* dev_path) const char *dev_path)
{ {
if (dev_path == NULL) { if (dev_path == NULL) {
return; return;
} }
switch(udev_event) { switch (udev_event) {
case SDL_UDEV_DEVICEADDED: case SDL_UDEV_DEVICEADDED:
if (!(udev_class & (SDL_UDEV_DEVICE_MOUSE | SDL_UDEV_DEVICE_KEYBOARD | SDL_UDEV_DEVICE_TOUCHSCREEN | SDL_UDEV_DEVICE_TOUCHPAD))) { if (!(udev_class & (SDL_UDEV_DEVICE_MOUSE | SDL_UDEV_DEVICE_KEYBOARD | SDL_UDEV_DEVICE_TOUCHSCREEN | SDL_UDEV_DEVICE_TOUCHPAD))) {
return; return;
@@ -268,8 +267,7 @@ static void SDL_EVDEV_udev_callback(SDL_UDEV_deviceevent udev_event, int udev_cl
} }
#endif /* SDL_USE_LIBUDEV */ #endif /* SDL_USE_LIBUDEV */
void void SDL_EVDEV_Poll(void)
SDL_EVDEV_Poll(void)
{ {
struct input_event events[32]; struct input_event events[32];
int i, j, len; int i, j, len;
@@ -338,7 +336,7 @@ SDL_EVDEV_Poll(void)
SDL_EVDEV_kbd_keycode(_this->kbd, events[i].code, events[i].value); SDL_EVDEV_kbd_keycode(_this->kbd, events[i].code, events[i].value);
break; break;
case EV_ABS: case EV_ABS:
switch(events[i].code) { switch (events[i].code) {
case ABS_MT_SLOT: case ABS_MT_SLOT:
if (!item->is_touchscreen) { /* FIXME: temp hack */ if (!item->is_touchscreen) { /* FIXME: temp hack */
break; break;
@@ -410,7 +408,7 @@ SDL_EVDEV_Poll(void)
} }
break; break;
case EV_REL: case EV_REL:
switch(events[i].code) { switch (events[i].code) {
case REL_X: case REL_X:
if (item->relative_mouse) { if (item->relative_mouse) {
item->mouse_x += events[i].value; item->mouse_x += events[i].value;
@@ -480,7 +478,7 @@ SDL_EVDEV_Poll(void)
/* FIXME: the touch's window shouldn't be null, but /* FIXME: the touch's window shouldn't be null, but
* the coordinate space of touch positions needs to * the coordinate space of touch positions needs to
* be window-relative in that case. */ * be window-relative in that case. */
switch(item->touchscreen_data->slots[j].delta) { switch (item->touchscreen_data->slots[j].delta) {
case EVDEV_TOUCH_SLOTDELTA_DOWN: case EVDEV_TOUCH_SLOTDELTA_DOWN:
SDL_SendTouch(item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, SDL_TRUE, norm_x, norm_y, norm_pressure); SDL_SendTouch(item->fd, item->touchscreen_data->slots[j].tracking_id, NULL, SDL_TRUE, norm_x, norm_y, norm_pressure);
item->touchscreen_data->slots[j].delta = EVDEV_TOUCH_SLOTDELTA_NONE; item->touchscreen_data->slots[j].delta = EVDEV_TOUCH_SLOTDELTA_NONE;
@@ -519,8 +517,7 @@ SDL_EVDEV_Poll(void)
} }
} }
static SDL_Scancode static SDL_Scancode SDL_EVDEV_translate_keycode(int keycode)
SDL_EVDEV_translate_keycode(int keycode)
{ {
SDL_Scancode scancode = SDL_GetScancodeFromTable(SDL_SCANCODE_TABLE_LINUX, keycode); SDL_Scancode scancode = SDL_GetScancodeFromTable(SDL_SCANCODE_TABLE_LINUX, keycode);
@@ -533,7 +530,8 @@ SDL_EVDEV_translate_keycode(int keycode)
if (keycode != BTN_TOUCH) { if (keycode != BTN_TOUCH) {
SDL_Log("The key you just pressed is not recognized by SDL. To help " SDL_Log("The key you just pressed is not recognized by SDL. To help "
"get this fixed, please report this to the SDL forums/mailing list " "get this fixed, please report this to the SDL forums/mailing list "
"<https://discourse.libsdl.org/> EVDEV KeyCode %d", keycode); "<https://discourse.libsdl.org/> EVDEV KeyCode %d",
keycode);
} }
} }
#endif /* DEBUG_SCANCODES */ #endif /* DEBUG_SCANCODES */
@@ -541,8 +539,7 @@ SDL_EVDEV_translate_keycode(int keycode)
return scancode; return scancode;
} }
static int static int SDL_EVDEV_init_touchscreen(SDL_evdevlist_item *item, int udev_class)
SDL_EVDEV_init_touchscreen(SDL_evdevlist_item* item, int udev_class)
{ {
int ret, i; int ret, i;
unsigned long xreq, yreq; unsigned long xreq, yreq;
@@ -643,8 +640,8 @@ SDL_EVDEV_init_touchscreen(SDL_evdevlist_item* item, int udev_class)
return 0; return 0;
} }
static void static void SDL_EVDEV_destroy_touchscreen(SDL_evdevlist_item *item)
SDL_EVDEV_destroy_touchscreen(SDL_evdevlist_item* item) { {
if (!item->is_touchscreen) { if (!item->is_touchscreen) {
return; return;
} }
@@ -655,8 +652,7 @@ SDL_EVDEV_destroy_touchscreen(SDL_evdevlist_item* item) {
SDL_free(item->touchscreen_data); SDL_free(item->touchscreen_data);
} }
static void static void SDL_EVDEV_sync_device(SDL_evdevlist_item *item)
SDL_EVDEV_sync_device(SDL_evdevlist_item *item)
{ {
#ifdef EVIOCGMTSLOTS #ifdef EVIOCGMTSLOTS
int i, ret; int i, ret;
@@ -669,8 +665,8 @@ SDL_EVDEV_sync_device(SDL_evdevlist_item *item)
* *
* this is the structure we're trying to emulate * this is the structure we're trying to emulate
*/ */
Uint32* mt_req_code; Uint32 *mt_req_code;
Sint32* mt_req_values; Sint32 *mt_req_values;
size_t mt_req_size; size_t mt_req_size;
/* TODO: sync devices other than touchscreen */ /* TODO: sync devices other than touchscreen */
@@ -686,7 +682,7 @@ SDL_EVDEV_sync_device(SDL_evdevlist_item *item)
return; return;
} }
mt_req_values = (Sint32*)mt_req_code + 1; mt_req_values = (Sint32 *)mt_req_code + 1;
*mt_req_code = ABS_MT_TRACKING_ID; *mt_req_code = ABS_MT_TRACKING_ID;
ret = ioctl(item->fd, EVIOCGMTSLOTS(mt_req_size), mt_req_code); ret = ioctl(item->fd, EVIOCGMTSLOTS(mt_req_size), mt_req_code);
@@ -781,8 +777,7 @@ SDL_EVDEV_sync_device(SDL_evdevlist_item *item)
#endif /* EVIOCGMTSLOTS */ #endif /* EVIOCGMTSLOTS */
} }
static int static int SDL_EVDEV_device_added(const char *dev_path, int udev_class)
SDL_EVDEV_device_added(const char *dev_path, int udev_class)
{ {
int ret; int ret;
SDL_evdevlist_item *item; SDL_evdevlist_item *item;
@@ -795,7 +790,7 @@ SDL_EVDEV_device_added(const char *dev_path, int udev_class)
} }
} }
item = (SDL_evdevlist_item *) SDL_calloc(1, sizeof (SDL_evdevlist_item)); item = (SDL_evdevlist_item *)SDL_calloc(1, sizeof(SDL_evdevlist_item));
if (item == NULL) { if (item == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -843,8 +838,7 @@ SDL_EVDEV_device_added(const char *dev_path, int udev_class)
return _this->num_devices++; return _this->num_devices++;
} }
static int static int SDL_EVDEV_device_removed(const char *dev_path)
SDL_EVDEV_device_removed(const char *dev_path)
{ {
SDL_evdevlist_item *item; SDL_evdevlist_item *item;
SDL_evdevlist_item *prev = NULL; SDL_evdevlist_item *prev = NULL;
@@ -876,7 +870,6 @@ SDL_EVDEV_device_removed(const char *dev_path)
return -1; return -1;
} }
#endif /* SDL_INPUT_LINUXEV */ #endif /* SDL_INPUT_LINUXEV */
/* vi: set ts=4 sw=4 expandtab: */ /* vi: set ts=4 sw=4 expandtab: */

View File

@@ -26,7 +26,6 @@
#ifdef SDL_INPUT_LINUXEV #ifdef SDL_INPUT_LINUXEV
extern int SDL_EVDEV_Init(void); extern int SDL_EVDEV_Init(void);
extern void SDL_EVDEV_Quit(void); extern void SDL_EVDEV_Quit(void);
extern void SDL_EVDEV_Poll(void); extern void SDL_EVDEV_Poll(void);

View File

@@ -23,7 +23,6 @@
#include "SDL_evdev_capabilities.h" #include "SDL_evdev_capabilities.h"
#if HAVE_LINUX_INPUT_H #if HAVE_LINUX_INPUT_H
/* missing defines in older Linux kernel headers */ /* missing defines in older Linux kernel headers */
@@ -43,7 +42,8 @@ SDL_EVDEV_GuessDeviceClass(unsigned long bitmask_ev[NBITS(EV_MAX)],
unsigned long bitmask_key[NBITS(KEY_MAX)], unsigned long bitmask_key[NBITS(KEY_MAX)],
unsigned long bitmask_rel[NBITS(REL_MAX)]) unsigned long bitmask_rel[NBITS(REL_MAX)])
{ {
struct range { struct range
{
unsigned start; unsigned start;
unsigned end; unsigned end;
}; };
@@ -114,7 +114,7 @@ SDL_EVDEV_GuessDeviceClass(unsigned long bitmask_ev[NBITS(EV_MAX)],
unsigned i; unsigned i;
unsigned long found = 0; unsigned long found = 0;
for (i = 0; i < BTN_MISC/BITS_PER_LONG; ++i) { for (i = 0; i < BTN_MISC / BITS_PER_LONG; ++i) {
found |= bitmask_key[i]; found |= bitmask_key[i];
} }
/* If there are no keys in the lower block, check the higher blocks */ /* If there are no keys in the lower block, check the higher blocks */

View File

@@ -42,9 +42,9 @@ typedef enum
} SDL_UDEV_deviceclass; } SDL_UDEV_deviceclass;
#define BITS_PER_LONG (sizeof(unsigned long) * 8) #define BITS_PER_LONG (sizeof(unsigned long) * 8)
#define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1) #define NBITS(x) ((((x)-1) / BITS_PER_LONG) + 1)
#define EVDEV_OFF(x) ((x)%BITS_PER_LONG) #define EVDEV_OFF(x) ((x) % BITS_PER_LONG)
#define EVDEV_LONG(x) ((x)/BITS_PER_LONG) #define EVDEV_LONG(x) ((x) / BITS_PER_LONG)
#define test_bit(bit, array) ((array[EVDEV_LONG(bit)] >> EVDEV_OFF(bit)) & 1) #define test_bit(bit, array) ((array[EVDEV_LONG(bit)] >> EVDEV_OFF(bit)) & 1)
extern int SDL_EVDEV_GuessDeviceClass(unsigned long bitmask_ev[NBITS(EV_MAX)], extern int SDL_EVDEV_GuessDeviceClass(unsigned long bitmask_ev[NBITS(EV_MAX)],

View File

@@ -52,25 +52,24 @@
* Handler Tables. * Handler Tables.
*/ */
#define K_HANDLERS\ #define K_HANDLERS \
k_self, k_fn, k_spec, k_pad,\ k_self, k_fn, k_spec, k_pad, \
k_dead, k_cons, k_cur, k_shift,\ k_dead, k_cons, k_cur, k_shift, \
k_meta, k_ascii, k_lock, k_lowercase,\ k_meta, k_ascii, k_lock, k_lowercase, \
k_slock, k_dead2, k_brl, k_ignore k_slock, k_dead2, k_brl, k_ignore
typedef void (k_handler_fn)(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag); typedef void(k_handler_fn)(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag);
static k_handler_fn K_HANDLERS; static k_handler_fn K_HANDLERS;
static k_handler_fn *k_handler[16] = { K_HANDLERS }; static k_handler_fn *k_handler[16] = { K_HANDLERS };
typedef void (fn_handler_fn)(SDL_EVDEV_keyboard_state *kbd); typedef void(fn_handler_fn)(SDL_EVDEV_keyboard_state *kbd);
static void fn_enter(SDL_EVDEV_keyboard_state *kbd); static void fn_enter(SDL_EVDEV_keyboard_state *kbd);
static void fn_caps_toggle(SDL_EVDEV_keyboard_state *kbd); static void fn_caps_toggle(SDL_EVDEV_keyboard_state *kbd);
static void fn_caps_on(SDL_EVDEV_keyboard_state *kbd); static void fn_caps_on(SDL_EVDEV_keyboard_state *kbd);
static void fn_num(SDL_EVDEV_keyboard_state *kbd); static void fn_num(SDL_EVDEV_keyboard_state *kbd);
static void fn_compose(SDL_EVDEV_keyboard_state *kbd); static void fn_compose(SDL_EVDEV_keyboard_state *kbd);
static fn_handler_fn *fn_handler[] = static fn_handler_fn *fn_handler[] = {
{
NULL, fn_enter, NULL, NULL, NULL, fn_enter, NULL, NULL,
NULL, NULL, NULL, fn_caps_toggle, NULL, NULL, NULL, fn_caps_toggle,
fn_num, NULL, NULL, NULL, fn_num, NULL, NULL, NULL,
@@ -78,7 +77,6 @@ static fn_handler_fn *fn_handler[] =
NULL, NULL, NULL, fn_num NULL, NULL, NULL, fn_num
}; };
/* /*
* Keyboard State * Keyboard State
*/ */
@@ -133,7 +131,7 @@ static void SDL_EVDEV_dump_keymap(SDL_EVDEV_keyboard_state *kbd)
if (kbd->key_maps[i]) { if (kbd->key_maps[i]) {
printf("static unsigned short default_key_map_%d[NR_KEYS] = {", i); printf("static unsigned short default_key_map_%d[NR_KEYS] = {", i);
for (j = 0; j < NR_KEYS; ++j) { for (j = 0; j < NR_KEYS; ++j) {
if ((j%8) == 0) { if ((j % 8) == 0) {
printf("\n "); printf("\n ");
} }
printf("0x%.4x, ", kbd->key_maps[i][j]); printf("0x%.4x, ", kbd->key_maps[i][j]);
@@ -193,14 +191,13 @@ static int SDL_EVDEV_kbd_load_keymaps(SDL_EVDEV_keyboard_state *kbd)
return 0; return 0;
} }
static SDL_EVDEV_keyboard_state * kbd_cleanup_state = NULL; static SDL_EVDEV_keyboard_state *kbd_cleanup_state = NULL;
static int kbd_cleanup_sigactions_installed = 0; static int kbd_cleanup_sigactions_installed = 0;
static int kbd_cleanup_atexit_installed = 0; static int kbd_cleanup_atexit_installed = 0;
static struct sigaction old_sigaction[NSIG]; static struct sigaction old_sigaction[NSIG];
static int fatal_signals[] = static int fatal_signals[] = {
{
/* Handlers for SIGTERM and SIGINT are installed in SDL_QuitInit. */ /* Handlers for SIGTERM and SIGINT are installed in SDL_QuitInit. */
SIGHUP, SIGQUIT, SIGILL, SIGABRT, SIGHUP, SIGQUIT, SIGILL, SIGABRT,
SIGFPE, SIGSEGV, SIGPIPE, SIGBUS, SIGFPE, SIGSEGV, SIGPIPE, SIGBUS,
@@ -209,7 +206,7 @@ static int fatal_signals[] =
static void kbd_cleanup(void) static void kbd_cleanup(void)
{ {
SDL_EVDEV_keyboard_state* kbd = kbd_cleanup_state; SDL_EVDEV_keyboard_state *kbd = kbd_cleanup_state;
if (kbd == NULL) { if (kbd == NULL) {
return; return;
} }
@@ -218,18 +215,17 @@ static void kbd_cleanup(void)
ioctl(kbd->console_fd, KDSKBMODE, kbd->old_kbd_mode); ioctl(kbd->console_fd, KDSKBMODE, kbd->old_kbd_mode);
} }
static void static void SDL_EVDEV_kbd_reraise_signal(int sig)
SDL_EVDEV_kbd_reraise_signal(int sig)
{ {
raise(sig); raise(sig);
} }
siginfo_t* SDL_EVDEV_kdb_cleanup_siginfo = NULL; siginfo_t *SDL_EVDEV_kdb_cleanup_siginfo = NULL;
void* SDL_EVDEV_kdb_cleanup_ucontext = NULL; void *SDL_EVDEV_kdb_cleanup_ucontext = NULL;
static void kbd_cleanup_signal_action(int signum, siginfo_t* info, void* ucontext) static void kbd_cleanup_signal_action(int signum, siginfo_t *info, void *ucontext)
{ {
struct sigaction* old_action_p = &(old_sigaction[signum]); struct sigaction *old_action_p = &(old_sigaction[signum]);
sigset_t sigset; sigset_t sigset;
/* Restore original signal handler before going any further. */ /* Restore original signal handler before going any further. */
@@ -263,7 +259,7 @@ static void kbd_unregister_emerg_cleanup()
kbd_cleanup_sigactions_installed = 0; kbd_cleanup_sigactions_installed = 0;
for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) { for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) {
struct sigaction* old_action_p; struct sigaction *old_action_p;
struct sigaction cur_action; struct sigaction cur_action;
signum = fatal_signals[tabidx]; signum = fatal_signals[tabidx];
old_action_p = &(old_sigaction[signum]); old_action_p = &(old_sigaction[signum]);
@@ -292,7 +288,7 @@ static void kbd_cleanup_atexit(void)
kbd_unregister_emerg_cleanup(); kbd_unregister_emerg_cleanup();
} }
static void kbd_register_emerg_cleanup(SDL_EVDEV_keyboard_state * kbd) static void kbd_register_emerg_cleanup(SDL_EVDEV_keyboard_state *kbd)
{ {
int tabidx, signum; int tabidx, signum;
@@ -316,7 +312,7 @@ static void kbd_register_emerg_cleanup(SDL_EVDEV_keyboard_state * kbd)
kbd_cleanup_sigactions_installed = 1; kbd_cleanup_sigactions_installed = 1;
for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) { for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) {
struct sigaction* old_action_p; struct sigaction *old_action_p;
struct sigaction new_action; struct sigaction new_action;
signum = fatal_signals[tabidx]; signum = fatal_signals[tabidx];
old_action_p = &(old_sigaction[signum]); old_action_p = &(old_sigaction[signum]);
@@ -327,7 +323,7 @@ static void kbd_register_emerg_cleanup(SDL_EVDEV_keyboard_state * kbd)
/* Skip SIGHUP and SIGPIPE if handler is already installed /* Skip SIGHUP and SIGPIPE if handler is already installed
* - assume the handler will do the cleanup * - assume the handler will do the cleanup
*/ */
if ((signum == SIGHUP || signum == SIGPIPE) && (old_action_p->sa_handler != SIG_DFL || (void(*)(int))old_action_p->sa_sigaction != SIG_DFL)) { if ((signum == SIGHUP || signum == SIGPIPE) && (old_action_p->sa_handler != SIG_DFL || (void (*)(int))old_action_p->sa_sigaction != SIG_DFL)) {
continue; continue;
} }
@@ -344,7 +340,7 @@ SDL_EVDEV_kbd_init(void)
SDL_EVDEV_keyboard_state *kbd; SDL_EVDEV_keyboard_state *kbd;
int i; int i;
char flag_state; char flag_state;
char shift_state[ sizeof (long) ] = {TIOCL_GETSHIFTSTATE, 0}; char shift_state[sizeof(long)] = { TIOCL_GETSHIFTSTATE, 0 };
kbd = (SDL_EVDEV_keyboard_state *)SDL_calloc(1, sizeof(*kbd)); kbd = (SDL_EVDEV_keyboard_state *)SDL_calloc(1, sizeof(*kbd));
if (kbd == NULL) { if (kbd == NULL) {
@@ -410,8 +406,7 @@ SDL_EVDEV_kbd_init(void)
return kbd; return kbd;
} }
void void SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *kbd)
SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *kbd)
{ {
if (kbd == NULL) { if (kbd == NULL) {
return; return;
@@ -446,7 +441,7 @@ SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *kbd)
static void put_queue(SDL_EVDEV_keyboard_state *kbd, uint c) static void put_queue(SDL_EVDEV_keyboard_state *kbd, uint c)
{ {
/* c is already part of a UTF-8 sequence and safe to add as a character */ /* c is already part of a UTF-8 sequence and safe to add as a character */
if (kbd->text_len < (sizeof(kbd->text)-1)) { if (kbd->text_len < (sizeof(kbd->text) - 1)) {
kbd->text[kbd->text_len++] = (char)c; kbd->text[kbd->text_len++] = (char)c;
} }
} }
@@ -638,7 +633,7 @@ static void k_deadunicode(SDL_EVDEV_keyboard_state *kbd, unsigned int value, cha
static void k_dead(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag) static void k_dead(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
{ {
const unsigned char ret_diacr[NR_DEAD] = {'`', '\'', '^', '~', '"', ',' }; const unsigned char ret_diacr[NR_DEAD] = { '`', '\'', '^', '~', '"', ',' };
k_deadunicode(kbd, ret_diacr[value], up_flag); k_deadunicode(kbd, ret_diacr[value], up_flag);
} }
@@ -767,8 +762,7 @@ static void k_brl(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_fl
{ {
} }
void void SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *kbd, unsigned int keycode, int down)
SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *kbd, unsigned int keycode, int down)
{ {
unsigned char shift_final; unsigned char shift_final;
unsigned char type; unsigned char type;
@@ -840,13 +834,11 @@ SDL_EVDEV_kbd_init(void)
return NULL; return NULL;
} }
void void SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *state, unsigned int keycode, int down)
SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *state, unsigned int keycode, int down)
{ {
} }
void void SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *state)
SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *state)
{ {
} }

View File

@@ -19,6 +19,8 @@
3. This notice may not be removed or altered from any source distribution. 3. This notice may not be removed or altered from any source distribution.
*/ */
/* *INDENT-OFF* */ /* clang-format off */
static unsigned short default_key_map_0[NR_KEYS] = { static unsigned short default_key_map_0[NR_KEYS] = {
0xf200, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 0xf200, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036,
0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009,
@@ -4374,6 +4376,8 @@ static unsigned short default_key_map_127[NR_KEYS] = {
}; };
#endif /* INCLUDE_EXTENDED_KEYMAP */ #endif /* INCLUDE_EXTENDED_KEYMAP */
/* *INDENT-ON* */ /* clang-format on */
static unsigned short *default_key_maps[MAX_NR_KEYMAPS] = { static unsigned short *default_key_maps[MAX_NR_KEYMAPS] = {
default_key_map_0, default_key_map_0,
default_key_map_1, default_key_map_1,

View File

@@ -32,7 +32,6 @@
#endif #endif
#include <SDL3/SDL_syswm.h> #include <SDL3/SDL_syswm.h>
#define FCITX_DBUS_SERVICE "org.freedesktop.portal.Fcitx" #define FCITX_DBUS_SERVICE "org.freedesktop.portal.Fcitx"
#define FCITX_IM_DBUS_PATH "/org/freedesktop/portal/inputmethod" #define FCITX_IM_DBUS_PATH "/org/freedesktop/portal/inputmethod"
@@ -55,8 +54,7 @@ typedef struct _FcitxClient
static FcitxClient fcitx_client; static FcitxClient fcitx_client;
static char* static char *GetAppName()
GetAppName()
{ {
#if defined(__LINUX__) || defined(__FREEBSD__) #if defined(__LINUX__) || defined(__FREEBSD__)
char *spot; char *spot;
@@ -141,7 +139,7 @@ Fcitx_GetPreeditString(SDL_DBusContext *dbus,
} }
if (text) { if (text) {
char* pivot = text; char *pivot = text;
/* Second pass: join all the sub string */ /* Second pass: join all the sub string */
dbus->message_iter_recurse(&iter, &array); dbus->message_iter_recurse(&iter, &array);
while (dbus->message_iter_get_arg_type(&array) == DBUS_TYPE_STRUCT) { while (dbus->message_iter_get_arg_type(&array) == DBUS_TYPE_STRUCT) {
@@ -167,8 +165,7 @@ Fcitx_GetPreeditString(SDL_DBusContext *dbus,
return text_bytes; return text_bytes;
} }
static Sint32 static Sint32 Fcitx_GetPreeditCursorByte(SDL_DBusContext *dbus, DBusMessage *msg)
Fcitx_GetPreeditCursorByte(SDL_DBusContext *dbus, DBusMessage *msg)
{ {
Sint32 byte = -1; Sint32 byte = -1;
DBusMessageIter iter; DBusMessageIter iter;
@@ -186,8 +183,7 @@ Fcitx_GetPreeditCursorByte(SDL_DBusContext *dbus, DBusMessage *msg)
return byte; return byte;
} }
static DBusHandlerResult static DBusHandlerResult DBus_MessageFilter(DBusConnection *conn, DBusMessage *msg, void *data)
DBus_MessageFilter(DBusConnection *conn, DBusMessage *msg, void *data)
{ {
SDL_DBusContext *dbus = (SDL_DBusContext *)data; SDL_DBusContext *dbus = (SDL_DBusContext *)data;
@@ -203,7 +199,7 @@ DBus_MessageFilter(DBusConnection *conn, DBusMessage *msg, void *data)
size_t text_bytes = SDL_strlen(text), i = 0; size_t text_bytes = SDL_strlen(text), i = 0;
while (i < text_bytes) { while (i < text_bytes) {
size_t sz = SDL_utf8strlcpy(buf, text+i, sizeof(buf)); size_t sz = SDL_utf8strlcpy(buf, text + i, sizeof(buf));
SDL_SendKeyboardText(buf); SDL_SendKeyboardText(buf);
i += sz; i += sz;
@@ -250,8 +246,7 @@ DBus_MessageFilter(DBusConnection *conn, DBusMessage *msg, void *data)
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
} }
static void static void FcitxClientICCallMethod(FcitxClient *client, const char *method)
FcitxClientICCallMethod(FcitxClient *client, const char *method)
{ {
if (!client->ic_path) { if (!client->ic_path) {
return; return;
@@ -259,8 +254,7 @@ FcitxClientICCallMethod(FcitxClient *client, const char *method)
SDL_DBus_CallVoidMethod(FCITX_DBUS_SERVICE, client->ic_path, FCITX_IC_DBUS_INTERFACE, method, DBUS_TYPE_INVALID); SDL_DBus_CallVoidMethod(FCITX_DBUS_SERVICE, client->ic_path, FCITX_IC_DBUS_INTERFACE, method, DBUS_TYPE_INVALID);
} }
static void SDLCALL static void SDLCALL Fcitx_SetCapabilities(void *data,
Fcitx_SetCapabilities(void *data,
const char *name, const char *name,
const char *old_val, const char *old_val,
const char *internal_editing) const char *internal_editing)
@@ -279,8 +273,8 @@ Fcitx_SetCapabilities(void *data,
SDL_DBus_CallVoidMethod(FCITX_DBUS_SERVICE, client->ic_path, FCITX_IC_DBUS_INTERFACE, "SetCapability", DBUS_TYPE_UINT64, &caps, DBUS_TYPE_INVALID); SDL_DBus_CallVoidMethod(FCITX_DBUS_SERVICE, client->ic_path, FCITX_IC_DBUS_INTERFACE, "SetCapability", DBUS_TYPE_UINT64, &caps, DBUS_TYPE_INVALID);
} }
static SDL_bool static SDL_bool FcitxCreateInputContext(SDL_DBusContext *dbus, const char *appname, char **ic_path)
FcitxCreateInputContext(SDL_DBusContext* dbus, const char *appname, char **ic_path) { {
const char *program = "program"; const char *program = "program";
SDL_bool retval = SDL_FALSE; SDL_bool retval = SDL_FALSE;
if (dbus->session_conn) { if (dbus->session_conn) {
@@ -308,8 +302,7 @@ FcitxCreateInputContext(SDL_DBusContext* dbus, const char *appname, char **ic_pa
return retval; return retval;
} }
static SDL_bool static SDL_bool FcitxClientCreateIC(FcitxClient *client)
FcitxClientCreateIC(FcitxClient *client)
{ {
char *appname = GetAppName(); char *appname = GetAppName();
char *ic_path = NULL; char *ic_path = NULL;
@@ -341,8 +334,7 @@ FcitxClientCreateIC(FcitxClient *client)
return SDL_FALSE; return SDL_FALSE;
} }
static Uint32 static Uint32 Fcitx_ModState(void)
Fcitx_ModState(void)
{ {
Uint32 fcitx_mods = 0; Uint32 fcitx_mods = 0;
SDL_Keymod sdl_mods = SDL_GetModState(); SDL_Keymod sdl_mods = SDL_GetModState();
@@ -388,8 +380,7 @@ SDL_Fcitx_Init()
return FcitxClientCreateIC(&fcitx_client); return FcitxClientCreateIC(&fcitx_client);
} }
void void SDL_Fcitx_Quit()
SDL_Fcitx_Quit()
{ {
FcitxClientICCallMethod(&fcitx_client, "DestroyIC"); FcitxClientICCallMethod(&fcitx_client, "DestroyIC");
if (fcitx_client.ic_path) { if (fcitx_client.ic_path) {
@@ -398,8 +389,7 @@ SDL_Fcitx_Quit()
} }
} }
void void SDL_Fcitx_SetFocus(SDL_bool focused)
SDL_Fcitx_SetFocus(SDL_bool focused)
{ {
if (focused) { if (focused) {
FcitxClientICCallMethod(&fcitx_client, "FocusIn"); FcitxClientICCallMethod(&fcitx_client, "FocusIn");
@@ -408,8 +398,7 @@ SDL_Fcitx_SetFocus(SDL_bool focused)
} }
} }
void void SDL_Fcitx_Reset(void)
SDL_Fcitx_Reset(void)
{ {
FcitxClientICCallMethod(&fcitx_client, "Reset"); FcitxClientICCallMethod(&fcitx_client, "Reset");
FcitxClientICCallMethod(&fcitx_client, "CloseIC"); FcitxClientICCallMethod(&fcitx_client, "CloseIC");
@@ -439,8 +428,7 @@ SDL_Fcitx_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, Uint8 state)
return SDL_FALSE; return SDL_FALSE;
} }
void void SDL_Fcitx_UpdateTextRect(const SDL_Rect *rect)
SDL_Fcitx_UpdateTextRect(const SDL_Rect *rect)
{ {
SDL_Window *focused_win = NULL; SDL_Window *focused_win = NULL;
SDL_SysWMinfo info; SDL_SysWMinfo info;
@@ -453,7 +441,7 @@ SDL_Fcitx_UpdateTextRect(const SDL_Rect *rect)
focused_win = SDL_GetKeyboardFocus(); focused_win = SDL_GetKeyboardFocus();
if (focused_win == NULL) { if (focused_win == NULL) {
return ; return;
} }
SDL_GetWindowPosition(focused_win, &x, &y); SDL_GetWindowPosition(focused_win, &x, &y);
@@ -485,8 +473,7 @@ SDL_Fcitx_UpdateTextRect(const SDL_Rect *rect)
DBUS_TYPE_INT32, &x, DBUS_TYPE_INT32, &y, DBUS_TYPE_INT32, &cursor->w, DBUS_TYPE_INT32, &cursor->h, DBUS_TYPE_INVALID); DBUS_TYPE_INT32, &x, DBUS_TYPE_INT32, &y, DBUS_TYPE_INT32, &cursor->w, DBUS_TYPE_INT32, &cursor->h, DBUS_TYPE_INVALID);
} }
void void SDL_Fcitx_PumpEvents(void)
SDL_Fcitx_PumpEvents(void)
{ {
SDL_DBusContext *dbus = fcitx_client.dbus; SDL_DBusContext *dbus = fcitx_client.dbus;
DBusConnection *conn = dbus->session_conn; DBusConnection *conn = dbus->session_conn;

View File

@@ -24,7 +24,6 @@
#include "SDL_internal.h" #include "SDL_internal.h"
extern SDL_bool SDL_Fcitx_Init(void); extern SDL_bool SDL_Fcitx_Init(void);
extern void SDL_Fcitx_Quit(void); extern void SDL_Fcitx_Quit(void);
extern void SDL_Fcitx_SetFocus(SDL_bool focused); extern void SDL_Fcitx_SetFocus(SDL_bool focused);

View File

@@ -56,9 +56,7 @@ static SDL_bool ibus_is_portal_interface = SDL_FALSE;
static char *ibus_addr_file = NULL; static char *ibus_addr_file = NULL;
static int inotify_fd = -1, inotify_wd = -1; static int inotify_fd = -1, inotify_wd = -1;
static Uint32 IBus_ModState(void)
static Uint32
IBus_ModState(void)
{ {
Uint32 ibus_mods = 0; Uint32 ibus_mods = 0;
SDL_Keymod sdl_mods = SDL_GetModState(); SDL_Keymod sdl_mods = SDL_GetModState();
@@ -92,9 +90,8 @@ IBus_ModState(void)
return ibus_mods; return ibus_mods;
} }
static SDL_bool static SDL_bool IBus_EnterVariant(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus,
IBus_EnterVariant(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus, DBusMessageIter *inside, const char *struct_id, size_t id_size)
DBusMessageIter *inside, const char * struct_id, size_t id_size)
{ {
DBusMessageIter sub; DBusMessageIter sub;
if (dbus->message_iter_get_arg_type(iter) != DBUS_TYPE_VARIANT) { if (dbus->message_iter_get_arg_type(iter) != DBUS_TYPE_VARIANT) {
@@ -120,8 +117,7 @@ IBus_EnterVariant(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *
return SDL_TRUE; return SDL_TRUE;
} }
static SDL_bool static SDL_bool IBus_GetDecorationPosition(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus,
IBus_GetDecorationPosition(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus,
Uint32 *start_pos, Uint32 *end_pos) Uint32 *start_pos, Uint32 *end_pos)
{ {
DBusMessageIter sub1, sub2, array; DBusMessageIter sub1, sub2, array;
@@ -185,8 +181,7 @@ IBus_GetDecorationPosition(DBusConnection *conn, DBusMessageIter *iter, SDL_DBus
return SDL_FALSE; return SDL_FALSE;
} }
static const char * static const char *IBus_GetVariantText(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus)
IBus_GetVariantText(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus)
{ {
/* The text we need is nested weirdly, use dbus-monitor to see the structure better */ /* The text we need is nested weirdly, use dbus-monitor to see the structure better */
const char *text = NULL; const char *text = NULL;
@@ -207,8 +202,7 @@ IBus_GetVariantText(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext
return text; return text;
} }
static SDL_bool static SDL_bool IBus_GetVariantCursorPos(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus,
IBus_GetVariantCursorPos(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext *dbus,
Uint32 *pos) Uint32 *pos)
{ {
dbus->message_iter_next(iter); dbus->message_iter_next(iter);
@@ -222,8 +216,7 @@ IBus_GetVariantCursorPos(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusCo
return SDL_TRUE; return SDL_TRUE;
} }
static DBusHandlerResult static DBusHandlerResult IBus_MessageHandler(DBusConnection *conn, DBusMessage *msg, void *user_data)
IBus_MessageHandler(DBusConnection *conn, DBusMessage *msg, void *user_data)
{ {
SDL_DBusContext *dbus = (SDL_DBusContext *)user_data; SDL_DBusContext *dbus = (SDL_DBusContext *)user_data;
@@ -239,7 +232,7 @@ IBus_MessageHandler(DBusConnection *conn, DBusMessage *msg, void *user_data)
size_t text_bytes = SDL_strlen(text), i = 0; size_t text_bytes = SDL_strlen(text), i = 0;
while (i < text_bytes) { while (i < text_bytes) {
size_t sz = SDL_utf8strlcpy(buf, text+i, sizeof(buf)); size_t sz = SDL_utf8strlcpy(buf, text + i, sizeof(buf));
SDL_SendKeyboardText(buf); SDL_SendKeyboardText(buf);
i += sz; i += sz;
@@ -282,7 +275,7 @@ IBus_MessageHandler(DBusConnection *conn, DBusMessage *msg, void *user_data)
size_t cursor = 0; size_t cursor = 0;
do { do {
const size_t sz = SDL_utf8strlcpy(buf, text+i, sizeof(buf)); const size_t sz = SDL_utf8strlcpy(buf, text + i, sizeof(buf));
const size_t chars = SDL_utf8strlen(buf); const size_t chars = SDL_utf8strlen(buf);
SDL_SendEditingText(buf, cursor, chars); SDL_SendEditingText(buf, cursor, chars);
@@ -305,8 +298,7 @@ IBus_MessageHandler(DBusConnection *conn, DBusMessage *msg, void *user_data)
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
} }
static char * static char *IBus_ReadAddressFromFile(const char *file_path)
IBus_ReadAddressFromFile(const char *file_path)
{ {
char addr_buf[1024]; char addr_buf[1024];
SDL_bool success = SDL_FALSE; SDL_bool success = SDL_FALSE;
@@ -318,7 +310,7 @@ IBus_ReadAddressFromFile(const char *file_path)
} }
while (fgets(addr_buf, sizeof(addr_buf), addr_file)) { while (fgets(addr_buf, sizeof(addr_buf), addr_file)) {
if (SDL_strncmp(addr_buf, "IBUS_ADDRESS=", sizeof("IBUS_ADDRESS=")-1) == 0) { if (SDL_strncmp(addr_buf, "IBUS_ADDRESS=", sizeof("IBUS_ADDRESS=") - 1) == 0) {
size_t sz = SDL_strlen(addr_buf); size_t sz = SDL_strlen(addr_buf);
if (addr_buf[sz - 1] == '\n') { if (addr_buf[sz - 1] == '\n') {
addr_buf[sz - 1] = 0; addr_buf[sz - 1] = 0;
@@ -340,8 +332,7 @@ IBus_ReadAddressFromFile(const char *file_path)
} }
} }
static char * static char *IBus_GetDBusAddressFilename(void)
IBus_GetDBusAddressFilename(void)
{ {
SDL_DBusContext *dbus; SDL_DBusContext *dbus;
const char *disp_env; const char *disp_env;
@@ -431,8 +422,7 @@ IBus_GetDBusAddressFilename(void)
static SDL_bool IBus_CheckConnection(SDL_DBusContext *dbus); static SDL_bool IBus_CheckConnection(SDL_DBusContext *dbus);
static void SDLCALL static void SDLCALL IBus_SetCapabilities(void *data, const char *name, const char *old_val,
IBus_SetCapabilities(void *data, const char *name, const char *old_val,
const char *internal_editing) const char *internal_editing)
{ {
SDL_DBusContext *dbus = SDL_DBus_GetContext(); SDL_DBusContext *dbus = SDL_DBus_GetContext();
@@ -448,9 +438,7 @@ IBus_SetCapabilities(void *data, const char *name, const char *old_val,
} }
} }
static SDL_bool IBus_SetupConnection(SDL_DBusContext *dbus, const char *addr)
static SDL_bool
IBus_SetupConnection(SDL_DBusContext *dbus, const char* addr)
{ {
const char *client_name = "SDL3_Application"; const char *client_name = "SDL3_Application";
const char *path = NULL; const char *path = NULL;
@@ -499,7 +487,7 @@ IBus_SetupConnection(SDL_DBusContext *dbus, const char* addr)
if (result) { if (result) {
char matchstr[128]; char matchstr[128];
SDL_snprintf(matchstr, sizeof (matchstr), "type='signal',interface='%s'", ibus_input_interface); SDL_snprintf(matchstr, sizeof(matchstr), "type='signal',interface='%s'", ibus_input_interface);
SDL_free(input_ctx_path); SDL_free(input_ctx_path);
input_ctx_path = SDL_strdup(path); input_ctx_path = SDL_strdup(path);
SDL_AddHintCallback(SDL_HINT_IME_INTERNAL_EDITING, IBus_SetCapabilities, NULL); SDL_AddHintCallback(SDL_HINT_IME_INTERNAL_EDITING, IBus_SetCapabilities, NULL);
@@ -514,8 +502,7 @@ IBus_SetupConnection(SDL_DBusContext *dbus, const char* addr)
return result; return result;
} }
static SDL_bool static SDL_bool IBus_CheckConnection(SDL_DBusContext *dbus)
IBus_CheckConnection(SDL_DBusContext *dbus)
{ {
if (dbus == NULL) { if (dbus == NULL) {
return SDL_FALSE; return SDL_FALSE;
@@ -534,7 +521,7 @@ IBus_CheckConnection(SDL_DBusContext *dbus)
SDL_bool file_updated = SDL_FALSE; SDL_bool file_updated = SDL_FALSE;
for (p = buf; p < buf + readsize; /**/) { for (p = buf; p < buf + readsize; /**/) {
struct inotify_event *event = (struct inotify_event*) p; struct inotify_event *event = (struct inotify_event *)p;
if (event->len > 0) { if (event->len > 0) {
char *addr_file_no_path = SDL_strrchr(ibus_addr_file, '/'); char *addr_file_no_path = SDL_strrchr(ibus_addr_file, '/');
if (addr_file_no_path == NULL) { if (addr_file_no_path == NULL) {
@@ -620,8 +607,7 @@ SDL_IBus_Init(void)
return result; return result;
} }
void void SDL_IBus_Quit(void)
SDL_IBus_Quit(void)
{ {
SDL_DBusContext *dbus; SDL_DBusContext *dbus;
@@ -661,8 +647,7 @@ SDL_IBus_Quit(void)
SDL_memset(&ibus_cursor_rect, 0, sizeof(ibus_cursor_rect)); SDL_memset(&ibus_cursor_rect, 0, sizeof(ibus_cursor_rect));
} }
static void static void IBus_SimpleMessage(const char *method)
IBus_SimpleMessage(const char *method)
{ {
SDL_DBusContext *dbus = SDL_DBus_GetContext(); SDL_DBusContext *dbus = SDL_DBus_GetContext();
@@ -671,15 +656,13 @@ IBus_SimpleMessage(const char *method)
} }
} }
void void SDL_IBus_SetFocus(SDL_bool focused)
SDL_IBus_SetFocus(SDL_bool focused)
{ {
const char *method = focused ? "FocusIn" : "FocusOut"; const char *method = focused ? "FocusIn" : "FocusOut";
IBus_SimpleMessage(method); IBus_SimpleMessage(method);
} }
void void SDL_IBus_Reset(void)
SDL_IBus_Reset(void)
{ {
IBus_SimpleMessage("Reset"); IBus_SimpleMessage("Reset");
} }
@@ -690,7 +673,6 @@ SDL_IBus_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, Uint8 state)
Uint32 result = 0; Uint32 result = 0;
SDL_DBusContext *dbus = SDL_DBus_GetContext(); SDL_DBusContext *dbus = SDL_DBus_GetContext();
if (IBus_CheckConnection(dbus)) { if (IBus_CheckConnection(dbus)) {
Uint32 mods = IBus_ModState(); Uint32 mods = IBus_ModState();
Uint32 ibus_keycode = keycode - 8; Uint32 ibus_keycode = keycode - 8;
@@ -709,8 +691,7 @@ SDL_IBus_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, Uint8 state)
return result ? SDL_TRUE : SDL_FALSE; return result ? SDL_TRUE : SDL_FALSE;
} }
void void SDL_IBus_UpdateTextRect(const SDL_Rect *rect)
SDL_IBus_UpdateTextRect(const SDL_Rect *rect)
{ {
SDL_Window *focused_win; SDL_Window *focused_win;
SDL_SysWMinfo info; SDL_SysWMinfo info;
@@ -752,8 +733,7 @@ SDL_IBus_UpdateTextRect(const SDL_Rect *rect)
} }
} }
void void SDL_IBus_PumpEvents(void)
SDL_IBus_PumpEvents(void)
{ {
SDL_DBusContext *dbus = SDL_DBus_GetContext(); SDL_DBusContext *dbus = SDL_DBus_GetContext();

View File

@@ -40,8 +40,7 @@ static _SDL_IME_ProcessKeyEvent SDL_IME_ProcessKeyEvent_Real = NULL;
static _SDL_IME_UpdateTextRect SDL_IME_UpdateTextRect_Real = NULL; static _SDL_IME_UpdateTextRect SDL_IME_UpdateTextRect_Real = NULL;
static _SDL_IME_PumpEvents SDL_IME_PumpEvents_Real = NULL; static _SDL_IME_PumpEvents SDL_IME_PumpEvents_Real = NULL;
static void static void InitIME()
InitIME()
{ {
static SDL_bool inited = SDL_FALSE; static SDL_bool inited = SDL_FALSE;
#ifdef HAVE_FCITX #ifdef HAVE_FCITX
@@ -107,24 +106,21 @@ SDL_IME_Init(void)
return SDL_FALSE; return SDL_FALSE;
} }
void void SDL_IME_Quit(void)
SDL_IME_Quit(void)
{ {
if (SDL_IME_Quit_Real) { if (SDL_IME_Quit_Real) {
SDL_IME_Quit_Real(); SDL_IME_Quit_Real();
} }
} }
void void SDL_IME_SetFocus(SDL_bool focused)
SDL_IME_SetFocus(SDL_bool focused)
{ {
if (SDL_IME_SetFocus_Real) { if (SDL_IME_SetFocus_Real) {
SDL_IME_SetFocus_Real(focused); SDL_IME_SetFocus_Real(focused);
} }
} }
void void SDL_IME_Reset(void)
SDL_IME_Reset(void)
{ {
if (SDL_IME_Reset_Real) { if (SDL_IME_Reset_Real) {
SDL_IME_Reset_Real(); SDL_IME_Reset_Real();
@@ -141,16 +137,14 @@ SDL_IME_ProcessKeyEvent(Uint32 keysym, Uint32 keycode, Uint8 state)
return SDL_FALSE; return SDL_FALSE;
} }
void void SDL_IME_UpdateTextRect(const SDL_Rect *rect)
SDL_IME_UpdateTextRect(const SDL_Rect *rect)
{ {
if (SDL_IME_UpdateTextRect_Real) { if (SDL_IME_UpdateTextRect_Real) {
SDL_IME_UpdateTextRect_Real(rect); SDL_IME_UpdateTextRect_Real(rect);
} }
} }
void void SDL_IME_PumpEvents()
SDL_IME_PumpEvents()
{ {
if (SDL_IME_PumpEvents_Real) { if (SDL_IME_PumpEvents_Real) {
SDL_IME_PumpEvents_Real(); SDL_IME_PumpEvents_Real();

View File

@@ -24,7 +24,6 @@
#include "SDL_internal.h" #include "SDL_internal.h"
extern SDL_bool SDL_IME_Init(void); extern SDL_bool SDL_IME_Init(void);
extern void SDL_IME_Quit(void); extern void SDL_IME_Quit(void);
extern void SDL_IME_SetFocus(SDL_bool focused); extern void SDL_IME_SetFocus(SDL_bool focused);

View File

@@ -33,9 +33,7 @@ SDL_Sandbox SDL_DetectSandbox(void)
/* For Snap, we check multiple variables because they might be set for /* For Snap, we check multiple variables because they might be set for
* unrelated reasons. This is the same thing WebKitGTK does. */ * unrelated reasons. This is the same thing WebKitGTK does. */
if (SDL_getenv("SNAP") != NULL if (SDL_getenv("SNAP") != NULL && SDL_getenv("SNAP_NAME") != NULL && SDL_getenv("SNAP_REVISION") != NULL) {
&& SDL_getenv("SNAP_NAME") != NULL
&& SDL_getenv("SNAP_REVISION") != NULL) {
return SDL_SANDBOX_SNAP; return SDL_SANDBOX_SNAP;
} }

View File

@@ -22,7 +22,6 @@
#ifdef __LINUX__ #ifdef __LINUX__
#if !SDL_THREADS_DISABLED #if !SDL_THREADS_DISABLED
#include <sys/time.h> #include <sys/time.h>
#include <sys/resource.h> #include <sys/resource.h>
@@ -68,16 +67,14 @@ static Sint64 rtkit_max_rttime_usec = 200000;
* - The desktop portal exists and supports the realtime interface. * - The desktop portal exists and supports the realtime interface.
* - The realtime interface is new enough to have the required bug fixes applied. * - The realtime interface is new enough to have the required bug fixes applied.
*/ */
static SDL_bool static SDL_bool realtime_portal_supported(DBusConnection *conn)
realtime_portal_supported(DBusConnection *conn)
{ {
Sint64 res; Sint64 res;
return SDL_DBus_QueryPropertyOnConnection(conn, XDG_PORTAL_DBUS_NODE, XDG_PORTAL_DBUS_PATH, XDG_PORTAL_DBUS_INTERFACE, return SDL_DBus_QueryPropertyOnConnection(conn, XDG_PORTAL_DBUS_NODE, XDG_PORTAL_DBUS_PATH, XDG_PORTAL_DBUS_INTERFACE,
"RTTimeUSecMax", DBUS_TYPE_INT64, &res); "RTTimeUSecMax", DBUS_TYPE_INT64, &res);
} }
static void static void set_rtkit_interface()
set_rtkit_interface()
{ {
SDL_DBusContext *dbus = SDL_DBus_GetContext(); SDL_DBusContext *dbus = SDL_DBus_GetContext();
@@ -95,8 +92,7 @@ set_rtkit_interface()
} }
} }
static DBusConnection* static DBusConnection *get_rtkit_dbus_connection()
get_rtkit_dbus_connection()
{ {
SDL_DBusContext *dbus = SDL_DBus_GetContext(); SDL_DBusContext *dbus = SDL_DBus_GetContext();
@@ -107,8 +103,7 @@ get_rtkit_dbus_connection()
return NULL; return NULL;
} }
static void static void rtkit_initialize()
rtkit_initialize()
{ {
DBusConnection *dbus_conn; DBusConnection *dbus_conn;
@@ -134,8 +129,7 @@ rtkit_initialize()
} }
} }
static SDL_bool static SDL_bool rtkit_initialize_realtime_thread()
rtkit_initialize_realtime_thread()
{ {
// Following is an excerpt from rtkit README that outlines the requirements // Following is an excerpt from rtkit README that outlines the requirements
// a thread must meet before making rtkit requests: // a thread must meet before making rtkit requests:
@@ -160,7 +154,7 @@ rtkit_initialize_realtime_thread()
int err; int err;
struct rlimit rlimit; struct rlimit rlimit;
int nLimit = RLIMIT_RTTIME; int nLimit = RLIMIT_RTTIME;
pid_t nPid = 0; //self pid_t nPid = 0; // self
int nSchedPolicy = sched_getscheduler(nPid) | SCHED_RESET_ON_FORK; int nSchedPolicy = sched_getscheduler(nPid) | SCHED_RESET_ON_FORK;
struct sched_param schedParam; struct sched_param schedParam;
@@ -194,8 +188,7 @@ rtkit_initialize_realtime_thread()
return SDL_TRUE; return SDL_TRUE;
} }
static SDL_bool static SDL_bool rtkit_setpriority_nice(pid_t thread, int nice_level)
rtkit_setpriority_nice(pid_t thread, int nice_level)
{ {
DBusConnection *dbus_conn; DBusConnection *dbus_conn;
Uint64 pid = (Uint64)getpid(); Uint64 pid = (Uint64)getpid();
@@ -218,8 +211,7 @@ rtkit_setpriority_nice(pid_t thread, int nice_level)
return SDL_TRUE; return SDL_TRUE;
} }
static SDL_bool static SDL_bool rtkit_setpriority_realtime(pid_t thread, int rt_priority)
rtkit_setpriority_realtime(pid_t thread, int rt_priority)
{ {
DBusConnection *dbus_conn; DBusConnection *dbus_conn;
Uint64 pid = (Uint64)getpid(); Uint64 pid = (Uint64)getpid();
@@ -257,8 +249,7 @@ rtkit_setpriority_realtime(pid_t thread, int rt_priority)
#endif /* threads */ #endif /* threads */
/* this is a public symbol, so it has to exist even if threads are disabled. */ /* this is a public symbol, so it has to exist even if threads are disabled. */
int int SDL_LinuxSetThreadPriority(Sint64 threadID, int priority)
SDL_LinuxSetThreadPriority(Sint64 threadID, int priority)
{ {
#if SDL_THREADS_DISABLED #if SDL_THREADS_DISABLED
return SDL_Unsupported(); return SDL_Unsupported();
@@ -290,8 +281,7 @@ SDL_LinuxSetThreadPriority(Sint64 threadID, int priority)
} }
/* this is a public symbol, so it has to exist even if threads are disabled. */ /* this is a public symbol, so it has to exist even if threads are disabled. */
int int SDL_LinuxSetThreadPriorityAndPolicy(Sint64 threadID, int sdlPriority, int schedPolicy)
SDL_LinuxSetThreadPriorityAndPolicy(Sint64 threadID, int sdlPriority, int schedPolicy)
{ {
#if SDL_THREADS_DISABLED #if SDL_THREADS_DISABLED
return SDL_Unsupported(); return SDL_Unsupported();

View File

@@ -45,8 +45,7 @@ static int SDL_UDEV_load_syms(void);
static SDL_bool SDL_UDEV_hotplug_update_available(void); static SDL_bool SDL_UDEV_hotplug_update_available(void);
static void device_event(SDL_UDEV_deviceevent type, struct udev_device *dev); static void device_event(SDL_UDEV_deviceevent type, struct udev_device *dev);
static SDL_bool static SDL_bool SDL_UDEV_load_sym(const char *fn, void **addr)
SDL_UDEV_load_sym(const char *fn, void **addr)
{ {
*addr = SDL_LoadFunction(_this->udev_handle, fn); *addr = SDL_LoadFunction(_this->udev_handle, fn);
if (*addr == NULL) { if (*addr == NULL) {
@@ -57,12 +56,12 @@ SDL_UDEV_load_sym(const char *fn, void **addr)
return SDL_TRUE; return SDL_TRUE;
} }
static int static int SDL_UDEV_load_syms(void)
SDL_UDEV_load_syms(void)
{ {
/* cast funcs to char* first, to please GCC's strict aliasing rules. */ /* cast funcs to char* first, to please GCC's strict aliasing rules. */
#define SDL_UDEV_SYM(x) \ #define SDL_UDEV_SYM(x) \
if (!SDL_UDEV_load_sym(#x, (void **) (char *) & _this->syms.x)) return -1 if (!SDL_UDEV_load_sym(#x, (void **)(char *)&_this->syms.x)) \
return -1
SDL_UDEV_SYM(udev_device_get_action); SDL_UDEV_SYM(udev_device_get_action);
SDL_UDEV_SYM(udev_device_get_devnode); SDL_UDEV_SYM(udev_device_get_devnode);
@@ -90,13 +89,12 @@ SDL_UDEV_load_syms(void)
SDL_UDEV_SYM(udev_unref); SDL_UDEV_SYM(udev_unref);
SDL_UDEV_SYM(udev_device_new_from_devnum); SDL_UDEV_SYM(udev_device_new_from_devnum);
SDL_UDEV_SYM(udev_device_get_devnum); SDL_UDEV_SYM(udev_device_get_devnum);
#undef SDL_UDEV_SYM #undef SDL_UDEV_SYM
return 0; return 0;
} }
static SDL_bool static SDL_bool SDL_UDEV_hotplug_update_available(void)
SDL_UDEV_hotplug_update_available(void)
{ {
if (_this->udev_mon != NULL) { if (_this->udev_mon != NULL) {
const int fd = _this->syms.udev_monitor_get_fd(_this->udev_mon); const int fd = _this->syms.udev_monitor_get_fd(_this->udev_mon);
@@ -107,14 +105,12 @@ SDL_UDEV_hotplug_update_available(void)
return SDL_FALSE; return SDL_FALSE;
} }
int SDL_UDEV_Init(void)
int
SDL_UDEV_Init(void)
{ {
int retval = 0; int retval = 0;
if (_this == NULL) { if (_this == NULL) {
_this = (SDL_UDEV_PrivateData *) SDL_calloc(1, sizeof(*_this)); _this = (SDL_UDEV_PrivateData *)SDL_calloc(1, sizeof(*_this));
if (_this == NULL) { if (_this == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -147,7 +143,6 @@ SDL_UDEV_Init(void)
/* Do an initial scan of existing devices */ /* Do an initial scan of existing devices */
SDL_UDEV_Scan(); SDL_UDEV_Scan();
} }
_this->ref_count += 1; _this->ref_count += 1;
@@ -155,8 +150,7 @@ SDL_UDEV_Init(void)
return retval; return retval;
} }
void void SDL_UDEV_Quit(void)
SDL_UDEV_Quit(void)
{ {
SDL_UDEV_CallbackList *item; SDL_UDEV_CallbackList *item;
@@ -190,8 +184,7 @@ SDL_UDEV_Quit(void)
} }
} }
void void SDL_UDEV_Scan(void)
SDL_UDEV_Scan(void)
{ {
struct udev_enumerate *enumerate = NULL; struct udev_enumerate *enumerate = NULL;
struct udev_list_entry *devs = NULL; struct udev_list_entry *devs = NULL;
@@ -279,11 +272,7 @@ SDL_UDEV_GetProductInfo(const char *device_path, Uint16 *vendor, Uint16 *product
return found; return found;
} }
void SDL_UDEV_UnloadLibrary(void)
void
SDL_UDEV_UnloadLibrary(void)
{ {
if (_this == NULL) { if (_this == NULL) {
return; return;
@@ -295,8 +284,7 @@ SDL_UDEV_UnloadLibrary(void)
} }
} }
int int SDL_UDEV_LoadLibrary(void)
SDL_UDEV_LoadLibrary(void)
{ {
int retval = 0, i; int retval = 0, i;
@@ -323,7 +311,7 @@ SDL_UDEV_LoadLibrary(void)
#endif #endif
if (_this->udev_handle == NULL) { if (_this->udev_handle == NULL) {
for ( i = 0 ; i < SDL_arraysize(SDL_UDEV_LIBS); i++) { for (i = 0; i < SDL_arraysize(SDL_UDEV_LIBS); i++) {
_this->udev_handle = SDL_LoadObject(SDL_UDEV_LIBS[i]); _this->udev_handle = SDL_LoadObject(SDL_UDEV_LIBS[i]);
if (_this->udev_handle != NULL) { if (_this->udev_handle != NULL) {
retval = SDL_UDEV_load_syms(); retval = SDL_UDEV_load_syms();
@@ -352,7 +340,7 @@ static void get_caps(struct udev_device *dev, struct udev_device *pdev, const ch
int i; int i;
unsigned long v; unsigned long v;
SDL_memset(bitmask, 0, bitmask_len*sizeof(*bitmask)); SDL_memset(bitmask, 0, bitmask_len * sizeof(*bitmask));
value = _this->syms.udev_device_get_sysattr_value(pdev, attr); value = _this->syms.udev_device_get_sysattr_value(pdev, attr);
if (value == NULL) { if (value == NULL) {
return; return;
@@ -361,7 +349,7 @@ static void get_caps(struct udev_device *dev, struct udev_device *pdev, const ch
SDL_strlcpy(text, value, sizeof(text)); SDL_strlcpy(text, value, sizeof(text));
i = 0; i = 0;
while ((word = SDL_strrchr(text, ' ')) != NULL) { while ((word = SDL_strrchr(text, ' ')) != NULL) {
v = SDL_strtoul(word+1, NULL, 16); v = SDL_strtoul(word + 1, NULL, 16);
if (i < bitmask_len) { if (i < bitmask_len) {
bitmask[i] = v; bitmask[i] = v;
} }
@@ -374,8 +362,7 @@ static void get_caps(struct udev_device *dev, struct udev_device *pdev, const ch
} }
} }
static int static int guess_device_class(struct udev_device *dev)
guess_device_class(struct udev_device *dev)
{ {
struct udev_device *pdev; struct udev_device *pdev;
unsigned long bitmask_ev[NBITS(EV_MAX)]; unsigned long bitmask_ev[NBITS(EV_MAX)];
@@ -404,8 +391,7 @@ guess_device_class(struct udev_device *dev)
&bitmask_rel[0]); &bitmask_rel[0]);
} }
static void static void device_event(SDL_UDEV_deviceevent type, struct udev_device *dev)
device_event(SDL_UDEV_deviceevent type, struct udev_device *dev)
{ {
const char *subsystem; const char *subsystem;
const char *val = NULL; const char *val = NULL;
@@ -425,23 +411,23 @@ device_event(SDL_UDEV_deviceevent type, struct udev_device *dev)
/* udev rules reference: http://cgit.freedesktop.org/systemd/systemd/tree/src/udev/udev-builtin-input_id.c */ /* udev rules reference: http://cgit.freedesktop.org/systemd/systemd/tree/src/udev/udev-builtin-input_id.c */
val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_JOYSTICK"); val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_JOYSTICK");
if (val != NULL && SDL_strcmp(val, "1") == 0 ) { if (val != NULL && SDL_strcmp(val, "1") == 0) {
devclass |= SDL_UDEV_DEVICE_JOYSTICK; devclass |= SDL_UDEV_DEVICE_JOYSTICK;
} }
val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_ACCELEROMETER"); val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_ACCELEROMETER");
if (SDL_GetHintBoolean(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, SDL_TRUE) && if (SDL_GetHintBoolean(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, SDL_TRUE) &&
val != NULL && SDL_strcmp(val, "1") == 0 ) { val != NULL && SDL_strcmp(val, "1") == 0) {
devclass |= SDL_UDEV_DEVICE_JOYSTICK; devclass |= SDL_UDEV_DEVICE_JOYSTICK;
} }
val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_MOUSE"); val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_MOUSE");
if (val != NULL && SDL_strcmp(val, "1") == 0 ) { if (val != NULL && SDL_strcmp(val, "1") == 0) {
devclass |= SDL_UDEV_DEVICE_MOUSE; devclass |= SDL_UDEV_DEVICE_MOUSE;
} }
val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_TOUCHSCREEN"); val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_TOUCHSCREEN");
if (val != NULL && SDL_strcmp(val, "1") == 0 ) { if (val != NULL && SDL_strcmp(val, "1") == 0) {
devclass |= SDL_UDEV_DEVICE_TOUCHSCREEN; devclass |= SDL_UDEV_DEVICE_TOUCHSCREEN;
} }
@@ -452,7 +438,7 @@ device_event(SDL_UDEV_deviceevent type, struct udev_device *dev)
Ref: http://cgit.freedesktop.org/systemd/systemd/tree/src/udev/udev-builtin-input_id.c#n183 Ref: http://cgit.freedesktop.org/systemd/systemd/tree/src/udev/udev-builtin-input_id.c#n183
*/ */
val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_KEY"); val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_KEY");
if (val != NULL && SDL_strcmp(val, "1") == 0 ) { if (val != NULL && SDL_strcmp(val, "1") == 0) {
devclass |= SDL_UDEV_DEVICE_KEYBOARD; devclass |= SDL_UDEV_DEVICE_KEYBOARD;
} }
@@ -484,8 +470,7 @@ device_event(SDL_UDEV_deviceevent type, struct udev_device *dev)
} }
} }
void void SDL_UDEV_Poll(void)
SDL_UDEV_Poll(void)
{ {
struct udev_device *dev = NULL; struct udev_device *dev = NULL;
const char *action = NULL; const char *action = NULL;
@@ -513,11 +498,10 @@ SDL_UDEV_Poll(void)
} }
} }
int int SDL_UDEV_AddCallback(SDL_UDEV_Callback cb)
SDL_UDEV_AddCallback(SDL_UDEV_Callback cb)
{ {
SDL_UDEV_CallbackList *item; SDL_UDEV_CallbackList *item;
item = (SDL_UDEV_CallbackList *) SDL_calloc(1, sizeof (SDL_UDEV_CallbackList)); item = (SDL_UDEV_CallbackList *)SDL_calloc(1, sizeof(SDL_UDEV_CallbackList));
if (item == NULL) { if (item == NULL) {
return SDL_OutOfMemory(); return SDL_OutOfMemory();
} }
@@ -534,8 +518,7 @@ SDL_UDEV_AddCallback(SDL_UDEV_Callback cb)
return 1; return 1;
} }
void void SDL_UDEV_DelCallback(SDL_UDEV_Callback cb)
SDL_UDEV_DelCallback(SDL_UDEV_Callback cb)
{ {
SDL_UDEV_CallbackList *item; SDL_UDEV_CallbackList *item;
SDL_UDEV_CallbackList *prev = NULL; SDL_UDEV_CallbackList *prev = NULL;
@@ -574,8 +557,7 @@ SDL_UDEV_GetUdevSyms(void)
return &_this->syms; return &_this->syms;
} }
void void SDL_UDEV_ReleaseUdevSyms(void)
SDL_UDEV_ReleaseUdevSyms(void)
{ {
SDL_UDEV_Quit(); SDL_UDEV_Quit();
} }

View File

@@ -46,12 +46,14 @@ typedef enum
typedef void (*SDL_UDEV_Callback)(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath); typedef void (*SDL_UDEV_Callback)(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath);
typedef struct SDL_UDEV_CallbackList { typedef struct SDL_UDEV_CallbackList
{
SDL_UDEV_Callback callback; SDL_UDEV_Callback callback;
struct SDL_UDEV_CallbackList *next; struct SDL_UDEV_CallbackList *next;
} SDL_UDEV_CallbackList; } SDL_UDEV_CallbackList;
typedef struct SDL_UDEV_Symbols { typedef struct SDL_UDEV_Symbols
{
const char *(*udev_device_get_action)(struct udev_device *); const char *(*udev_device_get_action)(struct udev_device *);
const char *(*udev_device_get_devnode)(struct udev_device *); const char *(*udev_device_get_devnode)(struct udev_device *);
const char *(*udev_device_get_subsystem)(struct udev_device *); const char *(*udev_device_get_subsystem)(struct udev_device *);
@@ -76,8 +78,8 @@ typedef struct SDL_UDEV_Symbols {
void (*udev_monitor_unref)(struct udev_monitor *); void (*udev_monitor_unref)(struct udev_monitor *);
struct udev *(*udev_new)(void); struct udev *(*udev_new)(void);
void (*udev_unref)(struct udev *); void (*udev_unref)(struct udev *);
struct udev_device * (*udev_device_new_from_devnum)(struct udev *udev, char type, dev_t devnum); struct udev_device *(*udev_device_new_from_devnum)(struct udev *udev, char type, dev_t devnum);
dev_t (*udev_device_get_devnum) (struct udev_device *udev_device); dev_t (*udev_device_get_devnum)(struct udev_device *udev_device);
} SDL_UDEV_Symbols; } SDL_UDEV_Symbols;
typedef struct SDL_UDEV_PrivateData typedef struct SDL_UDEV_PrivateData
@@ -105,7 +107,6 @@ extern void SDL_UDEV_DelCallback(SDL_UDEV_Callback cb);
extern const SDL_UDEV_Symbols *SDL_UDEV_GetUdevSyms(void); extern const SDL_UDEV_Symbols *SDL_UDEV_GetUdevSyms(void);
extern void SDL_UDEV_ReleaseUdevSyms(void); extern void SDL_UDEV_ReleaseUdevSyms(void);
#endif /* HAVE_LIBUDEV_H && HAVE_LINUX_INPUT_H */ #endif /* HAVE_LIBUDEV_H && HAVE_LINUX_INPUT_H */
#endif /* SDL_udev_h_ */ #endif /* SDL_udev_h_ */

View File

@@ -19,9 +19,7 @@
3. This notice may not be removed or altered from any source distribution. 3. This notice may not be removed or altered from any source distribution.
*/ */
void SDL_WSCONS_Init(); void SDL_WSCONS_Init();
void SDL_WSCONS_Quit(); void SDL_WSCONS_Quit();
void SDL_WSCONS_PumpEvents(); void SDL_WSCONS_PumpEvents();

View File

@@ -40,12 +40,17 @@
#define KS_Cmd_ScrollFwd KS_Cmd_ScrollFastDown #define KS_Cmd_ScrollFwd KS_Cmd_ScrollFastDown
#endif #endif
#define RETIFIOCTLERR(x) if (x == -1) { free(input); input = NULL; return NULL;} #define RETIFIOCTLERR(x) \
if (x == -1) { \
free(input); \
input = NULL; \
return NULL; \
}
typedef struct SDL_WSCONS_mouse_input_data SDL_WSCONS_mouse_input_data; typedef struct SDL_WSCONS_mouse_input_data SDL_WSCONS_mouse_input_data;
extern SDL_WSCONS_mouse_input_data* SDL_WSCONS_Init_Mouse(); extern SDL_WSCONS_mouse_input_data *SDL_WSCONS_Init_Mouse();
extern void updateMouse(SDL_WSCONS_mouse_input_data* input); extern void updateMouse(SDL_WSCONS_mouse_input_data *input);
extern void SDL_WSCONS_Quit_Mouse(SDL_WSCONS_mouse_input_data* input); extern void SDL_WSCONS_Quit_Mouse(SDL_WSCONS_mouse_input_data *input);
/* Conversion table courtesy of /usr/src/sys/dev/wscons/wskbdutil.c */ /* Conversion table courtesy of /usr/src/sys/dev/wscons/wskbdutil.c */
static const unsigned char latin1_to_upper[256] = { static const unsigned char latin1_to_upper[256] = {
@@ -85,7 +90,8 @@ static const unsigned char latin1_to_upper[256] = {
}; };
/* Compose table courtesy of /usr/src/sys/dev/wscons/wskbdutil.c */ /* Compose table courtesy of /usr/src/sys/dev/wscons/wskbdutil.c */
static struct SDL_wscons_compose_tab_s { static struct SDL_wscons_compose_tab_s
{
keysym_t elem[2]; keysym_t elem[2];
keysym_t result; keysym_t result;
} compose_tab[] = { } compose_tab[] = {
@@ -239,146 +245,148 @@ static keysym_t ksym_upcase(keysym_t ksym)
return ksym; return ksym;
} }
static struct wscons_keycode_to_SDL { static struct wscons_keycode_to_SDL
{
keysym_t sourcekey; keysym_t sourcekey;
SDL_Scancode targetKey; SDL_Scancode targetKey;
} conversion_table[] = { } conversion_table[] = {
{KS_Menu, SDL_SCANCODE_APPLICATION}, { KS_Menu, SDL_SCANCODE_APPLICATION },
{KS_Up, SDL_SCANCODE_UP}, { KS_Up, SDL_SCANCODE_UP },
{KS_Down, SDL_SCANCODE_DOWN}, { KS_Down, SDL_SCANCODE_DOWN },
{KS_Left, SDL_SCANCODE_LEFT}, { KS_Left, SDL_SCANCODE_LEFT },
{KS_Right, SDL_SCANCODE_RIGHT}, { KS_Right, SDL_SCANCODE_RIGHT },
{KS_Hold_Screen, SDL_SCANCODE_SCROLLLOCK}, { KS_Hold_Screen, SDL_SCANCODE_SCROLLLOCK },
{KS_Num_Lock, SDL_SCANCODE_NUMLOCKCLEAR}, { KS_Num_Lock, SDL_SCANCODE_NUMLOCKCLEAR },
{KS_Caps_Lock, SDL_SCANCODE_CAPSLOCK}, { KS_Caps_Lock, SDL_SCANCODE_CAPSLOCK },
{KS_BackSpace, SDL_SCANCODE_BACKSPACE}, { KS_BackSpace, SDL_SCANCODE_BACKSPACE },
{KS_space, SDL_SCANCODE_SPACE}, { KS_space, SDL_SCANCODE_SPACE },
{KS_Delete, SDL_SCANCODE_BACKSPACE}, { KS_Delete, SDL_SCANCODE_BACKSPACE },
{KS_Home, SDL_SCANCODE_HOME}, { KS_Home, SDL_SCANCODE_HOME },
{KS_End, SDL_SCANCODE_END}, { KS_End, SDL_SCANCODE_END },
{KS_Pause, SDL_SCANCODE_PAUSE}, { KS_Pause, SDL_SCANCODE_PAUSE },
{KS_Print_Screen, SDL_SCANCODE_PRINTSCREEN}, { KS_Print_Screen, SDL_SCANCODE_PRINTSCREEN },
{KS_Insert, SDL_SCANCODE_INSERT}, { KS_Insert, SDL_SCANCODE_INSERT },
{KS_Escape, SDL_SCANCODE_ESCAPE}, { KS_Escape, SDL_SCANCODE_ESCAPE },
{KS_Return, SDL_SCANCODE_RETURN}, { KS_Return, SDL_SCANCODE_RETURN },
{KS_Linefeed, SDL_SCANCODE_RETURN}, { KS_Linefeed, SDL_SCANCODE_RETURN },
{KS_KP_Delete, SDL_SCANCODE_DELETE}, { KS_KP_Delete, SDL_SCANCODE_DELETE },
{KS_KP_Insert, SDL_SCANCODE_INSERT}, { KS_KP_Insert, SDL_SCANCODE_INSERT },
{KS_Control_L, SDL_SCANCODE_LCTRL}, { KS_Control_L, SDL_SCANCODE_LCTRL },
{KS_Control_R, SDL_SCANCODE_RCTRL}, { KS_Control_R, SDL_SCANCODE_RCTRL },
{KS_Shift_L, SDL_SCANCODE_LSHIFT}, { KS_Shift_L, SDL_SCANCODE_LSHIFT },
{KS_Shift_R, SDL_SCANCODE_RSHIFT}, { KS_Shift_R, SDL_SCANCODE_RSHIFT },
{KS_Alt_L, SDL_SCANCODE_LALT}, { KS_Alt_L, SDL_SCANCODE_LALT },
{KS_Alt_R, SDL_SCANCODE_RALT}, { KS_Alt_R, SDL_SCANCODE_RALT },
{KS_grave, SDL_SCANCODE_GRAVE}, { KS_grave, SDL_SCANCODE_GRAVE },
{KS_KP_0, SDL_SCANCODE_KP_0}, { KS_KP_0, SDL_SCANCODE_KP_0 },
{KS_KP_1, SDL_SCANCODE_KP_1}, { KS_KP_1, SDL_SCANCODE_KP_1 },
{KS_KP_2, SDL_SCANCODE_KP_2}, { KS_KP_2, SDL_SCANCODE_KP_2 },
{KS_KP_3, SDL_SCANCODE_KP_3}, { KS_KP_3, SDL_SCANCODE_KP_3 },
{KS_KP_4, SDL_SCANCODE_KP_4}, { KS_KP_4, SDL_SCANCODE_KP_4 },
{KS_KP_5, SDL_SCANCODE_KP_5}, { KS_KP_5, SDL_SCANCODE_KP_5 },
{KS_KP_6, SDL_SCANCODE_KP_6}, { KS_KP_6, SDL_SCANCODE_KP_6 },
{KS_KP_7, SDL_SCANCODE_KP_7}, { KS_KP_7, SDL_SCANCODE_KP_7 },
{KS_KP_8, SDL_SCANCODE_KP_8}, { KS_KP_8, SDL_SCANCODE_KP_8 },
{KS_KP_9, SDL_SCANCODE_KP_9}, { KS_KP_9, SDL_SCANCODE_KP_9 },
{KS_KP_Enter, SDL_SCANCODE_KP_ENTER}, { KS_KP_Enter, SDL_SCANCODE_KP_ENTER },
{KS_KP_Multiply, SDL_SCANCODE_KP_MULTIPLY}, { KS_KP_Multiply, SDL_SCANCODE_KP_MULTIPLY },
{KS_KP_Add, SDL_SCANCODE_KP_PLUS}, { KS_KP_Add, SDL_SCANCODE_KP_PLUS },
{KS_KP_Subtract, SDL_SCANCODE_KP_MINUS}, { KS_KP_Subtract, SDL_SCANCODE_KP_MINUS },
{KS_KP_Divide, SDL_SCANCODE_KP_DIVIDE}, { KS_KP_Divide, SDL_SCANCODE_KP_DIVIDE },
{KS_KP_Up, SDL_SCANCODE_UP}, { KS_KP_Up, SDL_SCANCODE_UP },
{KS_KP_Down, SDL_SCANCODE_DOWN}, { KS_KP_Down, SDL_SCANCODE_DOWN },
{KS_KP_Left, SDL_SCANCODE_LEFT}, { KS_KP_Left, SDL_SCANCODE_LEFT },
{KS_KP_Right, SDL_SCANCODE_RIGHT}, { KS_KP_Right, SDL_SCANCODE_RIGHT },
{KS_KP_Equal, SDL_SCANCODE_KP_EQUALS}, { KS_KP_Equal, SDL_SCANCODE_KP_EQUALS },
{KS_f1, SDL_SCANCODE_F1}, { KS_f1, SDL_SCANCODE_F1 },
{KS_f2, SDL_SCANCODE_F2}, { KS_f2, SDL_SCANCODE_F2 },
{KS_f3, SDL_SCANCODE_F3}, { KS_f3, SDL_SCANCODE_F3 },
{KS_f4, SDL_SCANCODE_F4}, { KS_f4, SDL_SCANCODE_F4 },
{KS_f5, SDL_SCANCODE_F5}, { KS_f5, SDL_SCANCODE_F5 },
{KS_f6, SDL_SCANCODE_F6}, { KS_f6, SDL_SCANCODE_F6 },
{KS_f7, SDL_SCANCODE_F7}, { KS_f7, SDL_SCANCODE_F7 },
{KS_f8, SDL_SCANCODE_F8}, { KS_f8, SDL_SCANCODE_F8 },
{KS_f9, SDL_SCANCODE_F9}, { KS_f9, SDL_SCANCODE_F9 },
{KS_f10, SDL_SCANCODE_F10}, { KS_f10, SDL_SCANCODE_F10 },
{KS_f11, SDL_SCANCODE_F11}, { KS_f11, SDL_SCANCODE_F11 },
{KS_f12, SDL_SCANCODE_F12}, { KS_f12, SDL_SCANCODE_F12 },
{KS_f13, SDL_SCANCODE_F13}, { KS_f13, SDL_SCANCODE_F13 },
{KS_f14, SDL_SCANCODE_F14}, { KS_f14, SDL_SCANCODE_F14 },
{KS_f15, SDL_SCANCODE_F15}, { KS_f15, SDL_SCANCODE_F15 },
{KS_f16, SDL_SCANCODE_F16}, { KS_f16, SDL_SCANCODE_F16 },
{KS_f17, SDL_SCANCODE_F17}, { KS_f17, SDL_SCANCODE_F17 },
{KS_f18, SDL_SCANCODE_F18}, { KS_f18, SDL_SCANCODE_F18 },
{KS_f19, SDL_SCANCODE_F19}, { KS_f19, SDL_SCANCODE_F19 },
{KS_f20, SDL_SCANCODE_F20}, { KS_f20, SDL_SCANCODE_F20 },
#if !defined(__NetBSD__) #if !defined(__NetBSD__)
{KS_f21, SDL_SCANCODE_F21}, { KS_f21, SDL_SCANCODE_F21 },
{KS_f22, SDL_SCANCODE_F22}, { KS_f22, SDL_SCANCODE_F22 },
{KS_f23, SDL_SCANCODE_F23}, { KS_f23, SDL_SCANCODE_F23 },
{KS_f24, SDL_SCANCODE_F24}, { KS_f24, SDL_SCANCODE_F24 },
#endif #endif
{KS_Meta_L, SDL_SCANCODE_LGUI}, { KS_Meta_L, SDL_SCANCODE_LGUI },
{KS_Meta_R, SDL_SCANCODE_RGUI}, { KS_Meta_R, SDL_SCANCODE_RGUI },
{KS_Zenkaku_Hankaku, SDL_SCANCODE_LANG5}, { KS_Zenkaku_Hankaku, SDL_SCANCODE_LANG5 },
{KS_Hiragana_Katakana, SDL_SCANCODE_INTERNATIONAL2}, { KS_Hiragana_Katakana, SDL_SCANCODE_INTERNATIONAL2 },
{KS_yen, SDL_SCANCODE_INTERNATIONAL3}, { KS_yen, SDL_SCANCODE_INTERNATIONAL3 },
{KS_Henkan, SDL_SCANCODE_INTERNATIONAL4}, { KS_Henkan, SDL_SCANCODE_INTERNATIONAL4 },
{KS_Muhenkan, SDL_SCANCODE_INTERNATIONAL5}, { KS_Muhenkan, SDL_SCANCODE_INTERNATIONAL5 },
{KS_KP_Prior, SDL_SCANCODE_PRIOR}, { KS_KP_Prior, SDL_SCANCODE_PRIOR },
{KS_a, SDL_SCANCODE_A}, { KS_a, SDL_SCANCODE_A },
{KS_b, SDL_SCANCODE_B}, { KS_b, SDL_SCANCODE_B },
{KS_c, SDL_SCANCODE_C}, { KS_c, SDL_SCANCODE_C },
{KS_d, SDL_SCANCODE_D}, { KS_d, SDL_SCANCODE_D },
{KS_e, SDL_SCANCODE_E}, { KS_e, SDL_SCANCODE_E },
{KS_f, SDL_SCANCODE_F}, { KS_f, SDL_SCANCODE_F },
{KS_g, SDL_SCANCODE_G}, { KS_g, SDL_SCANCODE_G },
{KS_h, SDL_SCANCODE_H}, { KS_h, SDL_SCANCODE_H },
{KS_i, SDL_SCANCODE_I}, { KS_i, SDL_SCANCODE_I },
{KS_j, SDL_SCANCODE_J}, { KS_j, SDL_SCANCODE_J },
{KS_k, SDL_SCANCODE_K}, { KS_k, SDL_SCANCODE_K },
{KS_l, SDL_SCANCODE_L}, { KS_l, SDL_SCANCODE_L },
{KS_m, SDL_SCANCODE_M}, { KS_m, SDL_SCANCODE_M },
{KS_n, SDL_SCANCODE_N}, { KS_n, SDL_SCANCODE_N },
{KS_o, SDL_SCANCODE_O}, { KS_o, SDL_SCANCODE_O },
{KS_p, SDL_SCANCODE_P}, { KS_p, SDL_SCANCODE_P },
{KS_q, SDL_SCANCODE_Q}, { KS_q, SDL_SCANCODE_Q },
{KS_r, SDL_SCANCODE_R}, { KS_r, SDL_SCANCODE_R },
{KS_s, SDL_SCANCODE_S}, { KS_s, SDL_SCANCODE_S },
{KS_t, SDL_SCANCODE_T}, { KS_t, SDL_SCANCODE_T },
{KS_u, SDL_SCANCODE_U}, { KS_u, SDL_SCANCODE_U },
{KS_v, SDL_SCANCODE_V}, { KS_v, SDL_SCANCODE_V },
{KS_w, SDL_SCANCODE_W}, { KS_w, SDL_SCANCODE_W },
{KS_x, SDL_SCANCODE_X}, { KS_x, SDL_SCANCODE_X },
{KS_y, SDL_SCANCODE_Y}, { KS_y, SDL_SCANCODE_Y },
{KS_z, SDL_SCANCODE_Z}, { KS_z, SDL_SCANCODE_Z },
{KS_0, SDL_SCANCODE_0}, { KS_0, SDL_SCANCODE_0 },
{KS_1, SDL_SCANCODE_1}, { KS_1, SDL_SCANCODE_1 },
{KS_2, SDL_SCANCODE_2}, { KS_2, SDL_SCANCODE_2 },
{KS_3, SDL_SCANCODE_3}, { KS_3, SDL_SCANCODE_3 },
{KS_4, SDL_SCANCODE_4}, { KS_4, SDL_SCANCODE_4 },
{KS_5, SDL_SCANCODE_5}, { KS_5, SDL_SCANCODE_5 },
{KS_6, SDL_SCANCODE_6}, { KS_6, SDL_SCANCODE_6 },
{KS_7, SDL_SCANCODE_7}, { KS_7, SDL_SCANCODE_7 },
{KS_8, SDL_SCANCODE_8}, { KS_8, SDL_SCANCODE_8 },
{KS_9, SDL_SCANCODE_9}, { KS_9, SDL_SCANCODE_9 },
{KS_minus, SDL_SCANCODE_MINUS}, { KS_minus, SDL_SCANCODE_MINUS },
{KS_equal, SDL_SCANCODE_EQUALS}, { KS_equal, SDL_SCANCODE_EQUALS },
{KS_Tab, SDL_SCANCODE_TAB}, { KS_Tab, SDL_SCANCODE_TAB },
{KS_KP_Tab, SDL_SCANCODE_KP_TAB}, { KS_KP_Tab, SDL_SCANCODE_KP_TAB },
{KS_apostrophe, SDL_SCANCODE_APOSTROPHE}, { KS_apostrophe, SDL_SCANCODE_APOSTROPHE },
{KS_bracketleft, SDL_SCANCODE_LEFTBRACKET}, { KS_bracketleft, SDL_SCANCODE_LEFTBRACKET },
{KS_bracketright, SDL_SCANCODE_RIGHTBRACKET}, { KS_bracketright, SDL_SCANCODE_RIGHTBRACKET },
{KS_semicolon, SDL_SCANCODE_SEMICOLON}, { KS_semicolon, SDL_SCANCODE_SEMICOLON },
{KS_comma, SDL_SCANCODE_COMMA}, { KS_comma, SDL_SCANCODE_COMMA },
{KS_period, SDL_SCANCODE_PERIOD}, { KS_period, SDL_SCANCODE_PERIOD },
{KS_slash, SDL_SCANCODE_SLASH}, { KS_slash, SDL_SCANCODE_SLASH },
{KS_backslash, SDL_SCANCODE_BACKSLASH} { KS_backslash, SDL_SCANCODE_BACKSLASH }
}; };
typedef struct { typedef struct
{
int fd; int fd;
struct wskbd_map_data keymap; struct wskbd_map_data keymap;
int ledstate; int ledstate;
@@ -394,8 +402,8 @@ typedef struct {
int type; int type;
} SDL_WSCONS_input_data; } SDL_WSCONS_input_data;
static SDL_WSCONS_input_data* inputs[4] = {NULL, NULL, NULL, NULL}; static SDL_WSCONS_input_data *inputs[4] = { NULL, NULL, NULL, NULL };
static SDL_WSCONS_mouse_input_data* mouseInputData = NULL; static SDL_WSCONS_mouse_input_data *mouseInputData = NULL;
#define IS_CONTROL_HELD (input->shiftstate[2] > 0) #define IS_CONTROL_HELD (input->shiftstate[2] > 0)
#define IS_ALT_HELD (input->shiftstate[1] > 0) #define IS_ALT_HELD (input->shiftstate[1] > 0)
#define IS_SHIFT_HELD ((input->shiftstate[0] > 0) || (input->ledstate & (1 << 5))) #define IS_SHIFT_HELD ((input->shiftstate[0] > 0) || (input->ledstate & (1 << 5)))
@@ -404,17 +412,17 @@ static SDL_WSCONS_mouse_input_data* mouseInputData = NULL;
#define IS_NUMLOCK_ON (input->ledstate & LED_NUM) #define IS_NUMLOCK_ON (input->ledstate & LED_NUM)
#define IS_SCROLLLOCK_ON (input->ledstate & LED_SCR) #define IS_SCROLLLOCK_ON (input->ledstate & LED_SCR)
#define IS_CAPSLOCK_ON (input->ledstate & LED_CAP) #define IS_CAPSLOCK_ON (input->ledstate & LED_CAP)
static SDL_WSCONS_input_data* SDL_WSCONS_Init_Keyboard(const char* dev) static SDL_WSCONS_input_data *SDL_WSCONS_Init_Keyboard(const char *dev)
{ {
#ifdef WSKBDIO_SETVERSION #ifdef WSKBDIO_SETVERSION
int version = WSKBDIO_EVENT_VERSION; int version = WSKBDIO_EVENT_VERSION;
#endif #endif
SDL_WSCONS_input_data* input = (SDL_WSCONS_input_data*)SDL_calloc(1, sizeof(SDL_WSCONS_input_data)); SDL_WSCONS_input_data *input = (SDL_WSCONS_input_data *)SDL_calloc(1, sizeof(SDL_WSCONS_input_data));
if (input == NULL) { if (input == NULL) {
return input; return input;
} }
input->fd = open(dev,O_RDWR | O_NONBLOCK | O_CLOEXEC); input->fd = open(dev, O_RDWR | O_NONBLOCK | O_CLOEXEC);
if (input->fd == -1) { if (input->fd == -1) {
free(input); free(input);
input = NULL; input = NULL;
@@ -451,7 +459,7 @@ void SDL_WSCONS_Init()
void SDL_WSCONS_Quit() void SDL_WSCONS_Quit()
{ {
int i = 0; int i = 0;
SDL_WSCONS_input_data* input = NULL; SDL_WSCONS_input_data *input = NULL;
SDL_WSCONS_Quit_Mouse(mouseInputData); SDL_WSCONS_Quit_Mouse(mouseInputData);
mouseInputData = NULL; mouseInputData = NULL;
@@ -459,7 +467,7 @@ void SDL_WSCONS_Quit()
input = inputs[i]; input = inputs[i];
if (input) { if (input) {
if (input->fd != -1 && input->fd != 0) { if (input->fd != -1 && input->fd != 0) {
ioctl(input->fd,WSKBDIO_SETLEDS, &input->origledstate); ioctl(input->fd, WSKBDIO_SETLEDS, &input->origledstate);
close(input->fd); close(input->fd);
input->fd = -1; input->fd = -1;
} }
@@ -473,12 +481,12 @@ void SDL_WSCONS_Quit()
static void put_queue(SDL_WSCONS_input_data *kbd, uint c) static void put_queue(SDL_WSCONS_input_data *kbd, uint c)
{ {
/* c is already part of a UTF-8 sequence and safe to add as a character */ /* c is already part of a UTF-8 sequence and safe to add as a character */
if (kbd->text_len < (sizeof(kbd->text)-1)) { if (kbd->text_len < (sizeof(kbd->text) - 1)) {
kbd->text[kbd->text_len++] = (char)(c); kbd->text[kbd->text_len++] = (char)(c);
} }
} }
static void put_utf8(SDL_WSCONS_input_data* input, uint c) static void put_utf8(SDL_WSCONS_input_data *input, uint c)
{ {
if (c < 0x80) if (c < 0x80)
/* 0******* */ /* 0******* */
@@ -507,14 +515,14 @@ static void put_utf8(SDL_WSCONS_input_data* input, uint c)
} }
} }
static void Translate_to_text(SDL_WSCONS_input_data* input, keysym_t ksym) static void Translate_to_text(SDL_WSCONS_input_data *input, keysym_t ksym)
{ {
if (KS_GROUP(ksym) == KS_GROUP_Keypad) { if (KS_GROUP(ksym) == KS_GROUP_Keypad) {
if (SDL_isprint(ksym & 0xFF)) { if (SDL_isprint(ksym & 0xFF)) {
ksym &= 0xFF; ksym &= 0xFF;
} }
} }
switch(ksym) { switch (ksym) {
case KS_Escape: case KS_Escape:
case KS_Delete: case KS_Delete:
case KS_BackSpace: case KS_BackSpace:
@@ -535,19 +543,21 @@ static void Translate_to_text(SDL_WSCONS_input_data* input, keysym_t ksym)
} }
} }
static void Translate_to_keycode(SDL_WSCONS_input_data* input, int type, keysym_t ksym) static void Translate_to_keycode(SDL_WSCONS_input_data *input, int type, keysym_t ksym)
{ {
struct wscons_keymap keyDesc = input->keymap.map[ksym]; struct wscons_keymap keyDesc = input->keymap.map[ksym];
keysym_t* group = &keyDesc.group1[KS_GROUP(keyDesc.group1[0]) == KS_GROUP_Keypad && IS_NUMLOCK_ON ? !IS_SHIFT_HELD : 0]; keysym_t *group = &keyDesc.group1[KS_GROUP(keyDesc.group1[0]) == KS_GROUP_Keypad && IS_NUMLOCK_ON ? !IS_SHIFT_HELD : 0];
int i = 0; int i = 0;
/* Check command first, then group[0]*/ /* Check command first, then group[0]*/
switch (keyDesc.command) { switch (keyDesc.command) {
case KS_Cmd_ScrollBack: { case KS_Cmd_ScrollBack:
{
SDL_SendKeyboardKey(type == WSCONS_EVENT_KEY_DOWN ? SDL_PRESSED : SDL_RELEASED, SDL_SCANCODE_PAGEUP); SDL_SendKeyboardKey(type == WSCONS_EVENT_KEY_DOWN ? SDL_PRESSED : SDL_RELEASED, SDL_SCANCODE_PAGEUP);
return; return;
} }
case KS_Cmd_ScrollFwd: { case KS_Cmd_ScrollFwd:
{
SDL_SendKeyboardKey(type == WSCONS_EVENT_KEY_DOWN ? SDL_PRESSED : SDL_RELEASED, SDL_SCANCODE_PAGEDOWN); SDL_SendKeyboardKey(type == WSCONS_EVENT_KEY_DOWN ? SDL_PRESSED : SDL_RELEASED, SDL_SCANCODE_PAGEDOWN);
return; return;
} }
@@ -559,14 +569,13 @@ static void Translate_to_keycode(SDL_WSCONS_input_data* input, int type, keysym_
} }
} }
SDL_SendKeyboardKey(type == WSCONS_EVENT_KEY_DOWN ? SDL_PRESSED : SDL_RELEASED, SDL_SCANCODE_UNKNOWN); SDL_SendKeyboardKey(type == WSCONS_EVENT_KEY_DOWN ? SDL_PRESSED : SDL_RELEASED, SDL_SCANCODE_UNKNOWN);
} }
static void updateKeyboard(SDL_WSCONS_input_data* input) static void updateKeyboard(SDL_WSCONS_input_data *input)
{ {
struct wscons_event events[64]; struct wscons_event events[64];
int type; int type;
int n,i,gindex,acc_i; int n, i, gindex, acc_i;
keysym_t *group; keysym_t *group;
keysym_t ksym, result; keysym_t ksym, result;
@@ -577,10 +586,12 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
n /= sizeof(struct wscons_event); n /= sizeof(struct wscons_event);
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
type = events[i].type; type = events[i].type;
switch(type) { switch (type) {
case WSCONS_EVENT_KEY_DOWN: { case WSCONS_EVENT_KEY_DOWN:
{
switch (input->keymap.map[events[i].value].group1[0]) { switch (input->keymap.map[events[i].value].group1[0]) {
case KS_Hold_Screen: { case KS_Hold_Screen:
{
if (input->lockheldstate[0] >= 1) { if (input->lockheldstate[0] >= 1) {
break; break;
} }
@@ -589,7 +600,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
input->lockheldstate[0] = 1; input->lockheldstate[0] = 1;
break; break;
} }
case KS_Num_Lock: { case KS_Num_Lock:
{
if (input->lockheldstate[1] >= 1) { if (input->lockheldstate[1] >= 1) {
break; break;
} }
@@ -598,7 +610,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
input->lockheldstate[1] = 1; input->lockheldstate[1] = 1;
break; break;
} }
case KS_Caps_Lock: { case KS_Caps_Lock:
{
if (input->lockheldstate[2] >= 1) { if (input->lockheldstate[2] >= 1) {
break; break;
} }
@@ -608,7 +621,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
break; break;
} }
#ifndef __NetBSD__ #ifndef __NetBSD__
case KS_Mode_Lock: { case KS_Mode_Lock:
{
if (input->lockheldstate[3] >= 1) { if (input->lockheldstate[3] >= 1) {
break; break;
} }
@@ -618,7 +632,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
break; break;
} }
#endif #endif
case KS_Shift_Lock: { case KS_Shift_Lock:
{
if (input->lockheldstate[4] >= 1) { if (input->lockheldstate[4] >= 1) {
break; break;
} }
@@ -627,7 +642,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
input->lockheldstate[4] = 1; input->lockheldstate[4] = 1;
break; break;
} }
case KS_Shift_L: { case KS_Shift_L:
{
if (input->shiftheldstate[0]) { if (input->shiftheldstate[0]) {
break; break;
} }
@@ -635,7 +651,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
input->shiftheldstate[0] = 1; input->shiftheldstate[0] = 1;
break; break;
} }
case KS_Shift_R: { case KS_Shift_R:
{
if (input->shiftheldstate[1]) { if (input->shiftheldstate[1]) {
break; break;
} }
@@ -643,7 +660,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
input->shiftheldstate[1] = 1; input->shiftheldstate[1] = 1;
break; break;
} }
case KS_Alt_L: { case KS_Alt_L:
{
if (input->shiftheldstate[2]) { if (input->shiftheldstate[2]) {
break; break;
} }
@@ -651,7 +669,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
input->shiftheldstate[2] = 1; input->shiftheldstate[2] = 1;
break; break;
} }
case KS_Alt_R: { case KS_Alt_R:
{
if (input->shiftheldstate[3]) { if (input->shiftheldstate[3]) {
break; break;
} }
@@ -659,7 +678,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
input->shiftheldstate[3] = 1; input->shiftheldstate[3] = 1;
break; break;
} }
case KS_Control_L: { case KS_Control_L:
{
if (input->shiftheldstate[4]) { if (input->shiftheldstate[4]) {
break; break;
} }
@@ -667,7 +687,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
input->shiftheldstate[4] = 1; input->shiftheldstate[4] = 1;
break; break;
} }
case KS_Control_R: { case KS_Control_R:
{
if (input->shiftheldstate[5]) { if (input->shiftheldstate[5]) {
break; break;
} }
@@ -675,7 +696,8 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
input->shiftheldstate[5] = 1; input->shiftheldstate[5] = 1;
break; break;
} }
case KS_Mode_switch: { case KS_Mode_switch:
{
if (input->shiftheldstate[6]) { if (input->shiftheldstate[6]) {
break; break;
} }
@@ -684,85 +706,92 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
break; break;
} }
} }
} } break;
break; case WSCONS_EVENT_KEY_UP:
case WSCONS_EVENT_KEY_UP: { {
switch(input->keymap.map[events[i].value].group1[0]) { switch (input->keymap.map[events[i].value].group1[0]) {
case KS_Hold_Screen: { case KS_Hold_Screen:
{
if (input->lockheldstate[0]) { if (input->lockheldstate[0]) {
input->lockheldstate[0] = 0; input->lockheldstate[0] = 0;
} }
} } break;
break; case KS_Num_Lock:
case KS_Num_Lock: { {
if (input->lockheldstate[1]) { if (input->lockheldstate[1]) {
input->lockheldstate[1] = 0; input->lockheldstate[1] = 0;
} }
} } break;
break; case KS_Caps_Lock:
case KS_Caps_Lock: { {
if (input->lockheldstate[2]) { if (input->lockheldstate[2]) {
input->lockheldstate[2] = 0; input->lockheldstate[2] = 0;
} }
} } break;
break;
#ifndef __NetBSD__ #ifndef __NetBSD__
case KS_Mode_Lock: { case KS_Mode_Lock:
{
if (input->lockheldstate[3]) { if (input->lockheldstate[3]) {
input->lockheldstate[3] = 0; input->lockheldstate[3] = 0;
} }
} } break;
break;
#endif #endif
case KS_Shift_Lock: { case KS_Shift_Lock:
{
if (input->lockheldstate[4]) { if (input->lockheldstate[4]) {
input->lockheldstate[4] = 0; input->lockheldstate[4] = 0;
} }
} } break;
break; case KS_Shift_L:
case KS_Shift_L: { {
input->shiftheldstate[0] = 0; input->shiftheldstate[0] = 0;
if (input->shiftstate[0]) { if (input->shiftstate[0]) {
input->shiftstate[0]--; input->shiftstate[0]--;
} }
break; break;
} }
case KS_Shift_R: { case KS_Shift_R:
{
input->shiftheldstate[1] = 0; input->shiftheldstate[1] = 0;
if (input->shiftstate[0]) { if (input->shiftstate[0]) {
input->shiftstate[0]--; input->shiftstate[0]--;
} }
break; break;
} }
case KS_Alt_L: { case KS_Alt_L:
{
input->shiftheldstate[2] = 0; input->shiftheldstate[2] = 0;
if (input->shiftstate[1]) { if (input->shiftstate[1]) {
input->shiftstate[1]--; input->shiftstate[1]--;
} }
break; break;
} }
case KS_Alt_R: { case KS_Alt_R:
{
input->shiftheldstate[3] = 0; input->shiftheldstate[3] = 0;
if (input->shiftstate[1]) { if (input->shiftstate[1]) {
input->shiftstate[1]--; input->shiftstate[1]--;
} }
break; break;
} }
case KS_Control_L: { case KS_Control_L:
{
input->shiftheldstate[4] = 0; input->shiftheldstate[4] = 0;
if (input->shiftstate[2]) { if (input->shiftstate[2]) {
input->shiftstate[2]--; input->shiftstate[2]--;
} }
break; break;
} }
case KS_Control_R: { case KS_Control_R:
{
input->shiftheldstate[5] = 0; input->shiftheldstate[5] = 0;
if (input->shiftstate[2]) { if (input->shiftstate[2]) {
input->shiftstate[2]--; input->shiftstate[2]--;
} }
break; break;
} }
case KS_Mode_switch: { case KS_Mode_switch:
{
input->shiftheldstate[6] = 0; input->shiftheldstate[6] = 0;
if (input->shiftstate[3]) { if (input->shiftstate[3]) {
input->shiftstate[3]--; input->shiftstate[3]--;
@@ -770,8 +799,7 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
break; break;
} }
} }
} } break;
break;
case WSCONS_EVENT_ALL_KEYS_UP: case WSCONS_EVENT_ALL_KEYS_UP:
for (i = 0; i < SDL_NUM_SCANCODES; i++) { for (i = 0; i < SDL_NUM_SCANCODES; i++) {
SDL_SendKeyboardKey(SDL_RELEASED, i); SDL_SendKeyboardKey(SDL_RELEASED, i);
@@ -816,7 +844,7 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
case KS_GROUP_Mod: case KS_GROUP_Mod:
if (ksym == KS_Multi_key) { if (ksym == KS_Multi_key) {
input->ledstate |= WSKBD_LED_COMPOSE; input->ledstate |= WSKBD_LED_COMPOSE;
ioctl(input->fd,WSKBDIO_SETLEDS, &input->ledstate); ioctl(input->fd, WSKBDIO_SETLEDS, &input->ledstate);
input->composelen = 2; input->composelen = 2;
input->composebuffer[0] = input->composebuffer[1] = 0; input->composebuffer[0] = input->composebuffer[1] = 0;
} }
@@ -824,11 +852,12 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
case KS_GROUP_Dead: case KS_GROUP_Dead:
if (input->composelen == 0) { if (input->composelen == 0) {
input->ledstate |= WSKBD_LED_COMPOSE; input->ledstate |= WSKBD_LED_COMPOSE;
ioctl(input->fd,WSKBDIO_SETLEDS, &input->ledstate); ioctl(input->fd, WSKBDIO_SETLEDS, &input->ledstate);
input->composelen = 1; input->composelen = 1;
input->composebuffer[0] = ksym; input->composebuffer[0] = ksym;
input->composebuffer[1] = 0; input->composebuffer[1] = 0;
} else result = ksym; } else
result = ksym;
break; break;
} }
if (result == KS_voidSymbol) { if (result == KS_voidSymbol) {
@@ -848,17 +877,15 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
if (--input->composelen == 0) { if (--input->composelen == 0) {
result = KS_voidSymbol; result = KS_voidSymbol;
input->ledstate &= ~WSKBD_LED_COMPOSE; input->ledstate &= ~WSKBD_LED_COMPOSE;
ioctl(input->fd,WSKBDIO_SETLEDS, &input->ledstate); ioctl(input->fd, WSKBDIO_SETLEDS, &input->ledstate);
for (acc_i = 0; acc_i < SDL_arraysize(compose_tab); acc_i++) { for (acc_i = 0; acc_i < SDL_arraysize(compose_tab); acc_i++) {
if ((compose_tab[acc_i].elem[0] == input->composebuffer[0] if ((compose_tab[acc_i].elem[0] == input->composebuffer[0] && compose_tab[acc_i].elem[1] == input->composebuffer[1]) || (compose_tab[acc_i].elem[0] == input->composebuffer[1] && compose_tab[acc_i].elem[1] == input->composebuffer[0])) {
&& compose_tab[acc_i].elem[1] == input->composebuffer[1])
|| (compose_tab[acc_i].elem[0] == input->composebuffer[1]
&& compose_tab[acc_i].elem[1] == input->composebuffer[0])) {
result = compose_tab[acc_i].result; result = compose_tab[acc_i].result;
break; break;
} }
} }
} else continue; } else
continue;
} }
} }
@@ -884,7 +911,7 @@ static void updateKeyboard(SDL_WSCONS_input_data* input)
} }
} }
} }
Translate_to_text(input,result); Translate_to_text(input, result);
continue; continue;
} }
} }

View File

@@ -34,18 +34,21 @@ typedef struct SDL_WSCONS_mouse_input_data
int fd; int fd;
} SDL_WSCONS_mouse_input_data; } SDL_WSCONS_mouse_input_data;
SDL_WSCONS_mouse_input_data* SDL_WSCONS_Init_Mouse() SDL_WSCONS_mouse_input_data *SDL_WSCONS_Init_Mouse()
{ {
#ifdef WSMOUSEIO_SETVERSION #ifdef WSMOUSEIO_SETVERSION
int version = WSMOUSE_EVENT_VERSION; int version = WSMOUSE_EVENT_VERSION;
#endif #endif
SDL_WSCONS_mouse_input_data* mouseInputData = SDL_calloc(1, sizeof(SDL_WSCONS_mouse_input_data)); SDL_WSCONS_mouse_input_data *mouseInputData = SDL_calloc(1, sizeof(SDL_WSCONS_mouse_input_data));
if (mouseInputData == NULL) { if (mouseInputData == NULL) {
return NULL; return NULL;
} }
mouseInputData->fd = open("/dev/wsmouse",O_RDWR | O_NONBLOCK | O_CLOEXEC); mouseInputData->fd = open("/dev/wsmouse", O_RDWR | O_NONBLOCK | O_CLOEXEC);
if (mouseInputData->fd == -1) {free(mouseInputData); return NULL; } if (mouseInputData->fd == -1) {
free(mouseInputData);
return NULL;
}
#ifdef WSMOUSEIO_SETMODE #ifdef WSMOUSEIO_SETMODE
ioctl(mouseInputData->fd, WSMOUSEIO_SETMODE, WSMOUSE_COMPAT); ioctl(mouseInputData->fd, WSMOUSEIO_SETMODE, WSMOUSE_COMPAT);
#endif #endif
@@ -55,23 +58,21 @@ SDL_WSCONS_mouse_input_data* SDL_WSCONS_Init_Mouse()
return mouseInputData; return mouseInputData;
} }
void updateMouse(SDL_WSCONS_mouse_input_data* inputData) void updateMouse(SDL_WSCONS_mouse_input_data *inputData)
{ {
struct wscons_event events[64]; struct wscons_event events[64];
int type; int type;
int n,i; int n, i;
SDL_Mouse* mouse = SDL_GetMouse(); SDL_Mouse *mouse = SDL_GetMouse();
if ((n = read(inputData->fd, events, sizeof(events))) > 0) { if ((n = read(inputData->fd, events, sizeof(events))) > 0) {
n /= sizeof(struct wscons_event); n /= sizeof(struct wscons_event);
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
type = events[i].type; type = events[i].type;
switch(type) switch (type) {
{
case WSCONS_EVENT_MOUSE_DOWN: case WSCONS_EVENT_MOUSE_DOWN:
{ {
switch (events[i].value) switch (events[i].value) {
{
case 0: /* Left Mouse Button. */ case 0: /* Left Mouse Button. */
SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_PRESSED, SDL_BUTTON_LEFT); SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_PRESSED, SDL_BUTTON_LEFT);
break; break;
@@ -82,12 +83,10 @@ void updateMouse(SDL_WSCONS_mouse_input_data* inputData)
SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_PRESSED, SDL_BUTTON_RIGHT); SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_PRESSED, SDL_BUTTON_RIGHT);
break; break;
} }
} } break;
break;
case WSCONS_EVENT_MOUSE_UP: case WSCONS_EVENT_MOUSE_UP:
{ {
switch (events[i].value) switch (events[i].value) {
{
case 0: /* Left Mouse Button. */ case 0: /* Left Mouse Button. */
SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_RELEASED, SDL_BUTTON_LEFT); SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_RELEASED, SDL_BUTTON_LEFT);
break; break;
@@ -98,8 +97,7 @@ void updateMouse(SDL_WSCONS_mouse_input_data* inputData)
SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_RELEASED, SDL_BUTTON_RIGHT); SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_RELEASED, SDL_BUTTON_RIGHT);
break; break;
} }
} } break;
break;
case WSCONS_EVENT_MOUSE_DELTA_X: case WSCONS_EVENT_MOUSE_DELTA_X:
{ {
SDL_SendMouseMotion(mouse->focus, mouse->mouseID, 1, events[i].value, 0); SDL_SendMouseMotion(mouse->focus, mouse->mouseID, 1, events[i].value, 0);
@@ -125,7 +123,7 @@ void updateMouse(SDL_WSCONS_mouse_input_data* inputData)
} }
} }
void SDL_WSCONS_Quit_Mouse(SDL_WSCONS_mouse_input_data* inputData) void SDL_WSCONS_Quit_Mouse(SDL_WSCONS_mouse_input_data *inputData)
{ {
if (inputData == NULL) { if (inputData == NULL) {
return; return;

View File

@@ -32,17 +32,14 @@
#endif #endif
#include <errno.h> #include <errno.h>
int SDL_IOReady(int fd, int flags, int timeoutMS)
int
SDL_IOReady(int fd, int flags, int timeoutMS)
{ {
int result; int result;
SDL_assert(flags & (SDL_IOR_READ | SDL_IOR_WRITE)); SDL_assert(flags & (SDL_IOR_READ | SDL_IOR_WRITE));
/* Note: We don't bother to account for elapsed time if we get EINTR */ /* Note: We don't bother to account for elapsed time if we get EINTR */
do do {
{
#ifdef HAVE_POLL #ifdef HAVE_POLL
struct pollfd info; struct pollfd info;
@@ -83,7 +80,7 @@ SDL_IOReady(int fd, int flags, int timeoutMS)
result = select(fd + 1, rfdp, wfdp, NULL, tvp); result = select(fd + 1, rfdp, wfdp, NULL, tvp);
#endif /* HAVE_POLL */ #endif /* HAVE_POLL */
} while ( result < 0 && errno == EINTR && !(flags & SDL_IOR_NO_RETRY)); } while (result < 0 && errno == EINTR && !(flags & SDL_IOR_NO_RETRY));
return result; return result;
} }

View File

@@ -24,7 +24,6 @@
#ifndef SDL_poll_h_ #ifndef SDL_poll_h_
#define SDL_poll_h_ #define SDL_poll_h_
#define SDL_IOR_READ 0x1 #define SDL_IOR_READ 0x1
#define SDL_IOR_WRITE 0x2 #define SDL_IOR_WRITE 0x2
#define SDL_IOR_NO_RETRY 0x4 #define SDL_IOR_NO_RETRY 0x4

View File

@@ -39,8 +39,8 @@
/* Error codes not yet included in Win32 API header files */ /* Error codes not yet included in Win32 API header files */
#ifndef MAKE_HRESULT #ifndef MAKE_HRESULT
#define MAKE_HRESULT(sev,fac,code) \ #define MAKE_HRESULT(sev, fac, code) \
((HRESULT)(((unsigned long)(sev)<<31) | ((unsigned long)(fac)<<16) | ((unsigned long)(code)))) ((HRESULT)(((unsigned long)(sev) << 31) | ((unsigned long)(fac) << 16) | ((unsigned long)(code))))
#endif #endif
#ifndef S_OK #ifndef S_OK
@@ -51,7 +51,7 @@
#define SUCCEEDED(x) ((HRESULT)(x) >= 0) #define SUCCEEDED(x) ((HRESULT)(x) >= 0)
#endif #endif
#ifndef FAILED #ifndef FAILED
#define FAILED(x) ((HRESULT)(x)<0) #define FAILED(x) ((HRESULT)(x) < 0)
#endif #endif
#ifndef E_FAIL #ifndef E_FAIL
@@ -84,7 +84,7 @@
#endif #endif
#ifndef FIELD_OFFSET #ifndef FIELD_OFFSET
#define FIELD_OFFSET(type, field) ((LONG)&(((type *)0)->field)) #define FIELD_OFFSET(type, field) ((LONG) & (((type *)0)->field))
#endif #endif
/* DirectX headers (if it isn't included, I haven't tested it yet) /* DirectX headers (if it isn't included, I haven't tested it yet)
@@ -103,7 +103,10 @@
#ifdef HAVE_DINPUT_H #ifdef HAVE_DINPUT_H
#include <dinput.h> #include <dinput.h>
#else #else
typedef struct { int unused; } DIDEVICEINSTANCE; typedef struct
{
int unused;
} DIDEVICEINSTANCE;
#endif #endif
#endif /* SDL_directx_h_ */ #endif /* SDL_directx_h_ */

View File

@@ -24,7 +24,6 @@
#include "SDL_hid.h" #include "SDL_hid.h"
HidD_GetString_t SDL_HidD_GetManufacturerString; HidD_GetString_t SDL_HidD_GetManufacturerString;
HidD_GetString_t SDL_HidD_GetProductString; HidD_GetString_t SDL_HidD_GetProductString;
HidP_GetCaps_t SDL_HidP_GetCaps; HidP_GetCaps_t SDL_HidP_GetCaps;
@@ -36,9 +35,7 @@ HidP_GetData_t SDL_HidP_GetData;
static HMODULE s_pHIDDLL = 0; static HMODULE s_pHIDDLL = 0;
static int s_HIDDLLRefCount = 0; static int s_HIDDLLRefCount = 0;
int WIN_LoadHIDDLL(void)
int
WIN_LoadHIDDLL(void)
{ {
if (s_pHIDDLL) { if (s_pHIDDLL) {
SDL_assert(s_HIDDLLRefCount > 0); SDL_assert(s_HIDDLLRefCount > 0);
@@ -71,8 +68,7 @@ WIN_LoadHIDDLL(void)
return 0; return 0;
} }
void void WIN_UnloadHIDDLL(void)
WIN_UnloadHIDDLL(void)
{ {
if (s_pHIDDLL) { if (s_pHIDDLL) {
SDL_assert(s_HIDDLLRefCount > 0); SDL_assert(s_HIDDLLRefCount > 0);

View File

@@ -39,13 +39,15 @@ typedef struct _HIDD_ATTRIBUTES
USHORT VersionNumber; USHORT VersionNumber;
} HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES; } HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES;
typedef enum { typedef enum
{
HidP_Input = 0, HidP_Input = 0,
HidP_Output = 1, HidP_Output = 1,
HidP_Feature = 2 HidP_Feature = 2
} HIDP_REPORT_TYPE; } HIDP_REPORT_TYPE;
typedef struct { typedef struct
{
USAGE UsagePage; USAGE UsagePage;
UCHAR ReportID; UCHAR ReportID;
BOOLEAN IsAlias; BOOLEAN IsAlias;
@@ -57,9 +59,11 @@ typedef struct {
BOOLEAN IsStringRange; BOOLEAN IsStringRange;
BOOLEAN IsDesignatorRange; BOOLEAN IsDesignatorRange;
BOOLEAN IsAbsolute; BOOLEAN IsAbsolute;
ULONG Reserved[ 10 ]; ULONG Reserved[10];
union { union
struct { {
struct
{
USAGE UsageMin; USAGE UsageMin;
USAGE UsageMax; USAGE UsageMax;
USHORT StringMin; USHORT StringMin;
@@ -69,7 +73,8 @@ typedef struct {
USHORT DataIndexMin; USHORT DataIndexMin;
USHORT DataIndexMax; USHORT DataIndexMax;
} Range; } Range;
struct { struct
{
USAGE Usage; USAGE Usage;
USAGE Reserved1; USAGE Reserved1;
USHORT StringIndex; USHORT StringIndex;
@@ -82,7 +87,8 @@ typedef struct {
}; };
} HIDP_BUTTON_CAPS, *PHIDP_BUTTON_CAPS; } HIDP_BUTTON_CAPS, *PHIDP_BUTTON_CAPS;
typedef struct { typedef struct
{
USAGE UsagePage; USAGE UsagePage;
UCHAR ReportID; UCHAR ReportID;
BOOLEAN IsAlias; BOOLEAN IsAlias;
@@ -98,15 +104,17 @@ typedef struct {
UCHAR Reserved; UCHAR Reserved;
USHORT BitSize; USHORT BitSize;
USHORT ReportCount; USHORT ReportCount;
USHORT Reserved2[ 5 ]; USHORT Reserved2[5];
ULONG UnitsExp; ULONG UnitsExp;
ULONG Units; ULONG Units;
LONG LogicalMin; LONG LogicalMin;
LONG LogicalMax; LONG LogicalMax;
LONG PhysicalMin; LONG PhysicalMin;
LONG PhysicalMax; LONG PhysicalMax;
union { union
struct { {
struct
{
USAGE UsageMin; USAGE UsageMin;
USAGE UsageMax; USAGE UsageMax;
USHORT StringMin; USHORT StringMin;
@@ -116,7 +124,8 @@ typedef struct {
USHORT DataIndexMin; USHORT DataIndexMin;
USHORT DataIndexMax; USHORT DataIndexMax;
} Range; } Range;
struct { struct
{
USAGE Usage; USAGE Usage;
USAGE Reserved1; USAGE Reserved1;
USHORT StringIndex; USHORT StringIndex;
@@ -129,13 +138,14 @@ typedef struct {
}; };
} HIDP_VALUE_CAPS, *PHIDP_VALUE_CAPS; } HIDP_VALUE_CAPS, *PHIDP_VALUE_CAPS;
typedef struct { typedef struct
{
USAGE Usage; USAGE Usage;
USAGE UsagePage; USAGE UsagePage;
USHORT InputReportByteLength; USHORT InputReportByteLength;
USHORT OutputReportByteLength; USHORT OutputReportByteLength;
USHORT FeatureReportByteLength; USHORT FeatureReportByteLength;
USHORT Reserved[ 17 ]; USHORT Reserved[17];
USHORT NumberLinkCollectionNodes; USHORT NumberLinkCollectionNodes;
USHORT NumberInputButtonCaps; USHORT NumberInputButtonCaps;
USHORT NumberInputValueCaps; USHORT NumberInputValueCaps;
@@ -148,46 +158,47 @@ typedef struct {
USHORT NumberFeatureDataIndices; USHORT NumberFeatureDataIndices;
} HIDP_CAPS, *PHIDP_CAPS; } HIDP_CAPS, *PHIDP_CAPS;
typedef struct { typedef struct
{
USHORT DataIndex; USHORT DataIndex;
USHORT Reserved; USHORT Reserved;
union { union
{
ULONG RawValue; ULONG RawValue;
BOOLEAN On; BOOLEAN On;
}; };
} HIDP_DATA, *PHIDP_DATA; } HIDP_DATA, *PHIDP_DATA;
#define HIDP_ERROR_CODES( p1, p2 ) ((NTSTATUS)(((p1) << 28) | (0x11 << 16) | (p2))) #define HIDP_ERROR_CODES(p1, p2) ((NTSTATUS)(((p1) << 28) | (0x11 << 16) | (p2)))
#define HIDP_STATUS_SUCCESS HIDP_ERROR_CODES( 0x0, 0x0000 ) #define HIDP_STATUS_SUCCESS HIDP_ERROR_CODES(0x0, 0x0000)
#define HIDP_STATUS_NULL HIDP_ERROR_CODES( 0x8, 0x0001 ) #define HIDP_STATUS_NULL HIDP_ERROR_CODES(0x8, 0x0001)
#define HIDP_STATUS_INVALID_PREPARSED_DATA HIDP_ERROR_CODES( 0xC, 0x0001 ) #define HIDP_STATUS_INVALID_PREPARSED_DATA HIDP_ERROR_CODES(0xC, 0x0001)
#define HIDP_STATUS_INVALID_REPORT_TYPE HIDP_ERROR_CODES( 0xC, 0x0002 ) #define HIDP_STATUS_INVALID_REPORT_TYPE HIDP_ERROR_CODES(0xC, 0x0002)
#define HIDP_STATUS_INVALID_REPORT_LENGTH HIDP_ERROR_CODES( 0xC, 0x0003 ) #define HIDP_STATUS_INVALID_REPORT_LENGTH HIDP_ERROR_CODES(0xC, 0x0003)
#define HIDP_STATUS_USAGE_NOT_FOUND HIDP_ERROR_CODES( 0xC, 0x0004 ) #define HIDP_STATUS_USAGE_NOT_FOUND HIDP_ERROR_CODES(0xC, 0x0004)
#define HIDP_STATUS_VALUE_OUT_OF_RANGE HIDP_ERROR_CODES( 0xC, 0x0005 ) #define HIDP_STATUS_VALUE_OUT_OF_RANGE HIDP_ERROR_CODES(0xC, 0x0005)
#define HIDP_STATUS_BAD_LOG_PHY_VALUES HIDP_ERROR_CODES( 0xC, 0x0006 ) #define HIDP_STATUS_BAD_LOG_PHY_VALUES HIDP_ERROR_CODES(0xC, 0x0006)
#define HIDP_STATUS_BUFFER_TOO_SMALL HIDP_ERROR_CODES( 0xC, 0x0007 ) #define HIDP_STATUS_BUFFER_TOO_SMALL HIDP_ERROR_CODES(0xC, 0x0007)
#define HIDP_STATUS_INTERNAL_ERROR HIDP_ERROR_CODES( 0xC, 0x0008 ) #define HIDP_STATUS_INTERNAL_ERROR HIDP_ERROR_CODES(0xC, 0x0008)
#define HIDP_STATUS_I8042_TRANS_UNKNOWN HIDP_ERROR_CODES( 0xC, 0x0009 ) #define HIDP_STATUS_I8042_TRANS_UNKNOWN HIDP_ERROR_CODES(0xC, 0x0009)
#define HIDP_STATUS_INCOMPATIBLE_REPORT_ID HIDP_ERROR_CODES( 0xC, 0x000A ) #define HIDP_STATUS_INCOMPATIBLE_REPORT_ID HIDP_ERROR_CODES(0xC, 0x000A)
#define HIDP_STATUS_NOT_VALUE_ARRAY HIDP_ERROR_CODES( 0xC, 0x000B ) #define HIDP_STATUS_NOT_VALUE_ARRAY HIDP_ERROR_CODES(0xC, 0x000B)
#define HIDP_STATUS_IS_VALUE_ARRAY HIDP_ERROR_CODES( 0xC, 0x000C ) #define HIDP_STATUS_IS_VALUE_ARRAY HIDP_ERROR_CODES(0xC, 0x000C)
#define HIDP_STATUS_DATA_INDEX_NOT_FOUND HIDP_ERROR_CODES( 0xC, 0x000D ) #define HIDP_STATUS_DATA_INDEX_NOT_FOUND HIDP_ERROR_CODES(0xC, 0x000D)
#define HIDP_STATUS_DATA_INDEX_OUT_OF_RANGE HIDP_ERROR_CODES( 0xC, 0x000E ) #define HIDP_STATUS_DATA_INDEX_OUT_OF_RANGE HIDP_ERROR_CODES(0xC, 0x000E)
#define HIDP_STATUS_BUTTON_NOT_PRESSED HIDP_ERROR_CODES( 0xC, 0x000F ) #define HIDP_STATUS_BUTTON_NOT_PRESSED HIDP_ERROR_CODES(0xC, 0x000F)
#define HIDP_STATUS_REPORT_DOES_NOT_EXIST HIDP_ERROR_CODES( 0xC, 0x0010 ) #define HIDP_STATUS_REPORT_DOES_NOT_EXIST HIDP_ERROR_CODES(0xC, 0x0010)
#define HIDP_STATUS_NOT_IMPLEMENTED HIDP_ERROR_CODES( 0xC, 0x0020 ) #define HIDP_STATUS_NOT_IMPLEMENTED HIDP_ERROR_CODES(0xC, 0x0020)
extern int WIN_LoadHIDDLL(void); extern int WIN_LoadHIDDLL(void);
extern void WIN_UnloadHIDDLL(void); extern void WIN_UnloadHIDDLL(void);
typedef BOOLEAN (WINAPI *HidD_GetString_t)(HANDLE HidDeviceObject, PVOID Buffer, ULONG BufferLength); typedef BOOLEAN(WINAPI *HidD_GetString_t)(HANDLE HidDeviceObject, PVOID Buffer, ULONG BufferLength);
typedef NTSTATUS (WINAPI *HidP_GetCaps_t)(PHIDP_PREPARSED_DATA PreparsedData, PHIDP_CAPS Capabilities); typedef NTSTATUS(WINAPI *HidP_GetCaps_t)(PHIDP_PREPARSED_DATA PreparsedData, PHIDP_CAPS Capabilities);
typedef NTSTATUS (WINAPI *HidP_GetButtonCaps_t)(HIDP_REPORT_TYPE ReportType, PHIDP_BUTTON_CAPS ButtonCaps, PUSHORT ButtonCapsLength, PHIDP_PREPARSED_DATA PreparsedData); typedef NTSTATUS(WINAPI *HidP_GetButtonCaps_t)(HIDP_REPORT_TYPE ReportType, PHIDP_BUTTON_CAPS ButtonCaps, PUSHORT ButtonCapsLength, PHIDP_PREPARSED_DATA PreparsedData);
typedef NTSTATUS (WINAPI *HidP_GetValueCaps_t)(HIDP_REPORT_TYPE ReportType, PHIDP_VALUE_CAPS ValueCaps, PUSHORT ValueCapsLength, PHIDP_PREPARSED_DATA PreparsedData); typedef NTSTATUS(WINAPI *HidP_GetValueCaps_t)(HIDP_REPORT_TYPE ReportType, PHIDP_VALUE_CAPS ValueCaps, PUSHORT ValueCapsLength, PHIDP_PREPARSED_DATA PreparsedData);
typedef ULONG (WINAPI *HidP_MaxDataListLength_t)(HIDP_REPORT_TYPE ReportType, PHIDP_PREPARSED_DATA PreparsedData); typedef ULONG(WINAPI *HidP_MaxDataListLength_t)(HIDP_REPORT_TYPE ReportType, PHIDP_PREPARSED_DATA PreparsedData);
typedef NTSTATUS (WINAPI *HidP_GetData_t)(HIDP_REPORT_TYPE ReportType, PHIDP_DATA DataList, PULONG DataLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength); typedef NTSTATUS(WINAPI *HidP_GetData_t)(HIDP_REPORT_TYPE ReportType, PHIDP_DATA DataList, PULONG DataLength, PHIDP_PREPARSED_DATA PreparsedData, PCHAR Report, ULONG ReportLength);
extern HidD_GetString_t SDL_HidD_GetManufacturerString; extern HidD_GetString_t SDL_HidD_GetManufacturerString;
extern HidD_GetString_t SDL_HidD_GetProductString; extern HidD_GetString_t SDL_HidD_GetProductString;

View File

@@ -39,6 +39,7 @@ static IMMDeviceEnumerator *enumerator = NULL;
#define PropVariantInit(p) SDL_zerop(p) #define PropVariantInit(p) SDL_zerop(p)
/* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */ /* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
/* *INDENT-OFF* */ /* clang-format off */
static const CLSID SDL_CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c,{ 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } }; static const CLSID SDL_CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c,{ 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } };
static const IID SDL_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35,{ 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } }; static const IID SDL_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35,{ 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } };
static const IID SDL_IID_IMMNotificationClient = { 0x7991eec9, 0x7e89, 0x4d85,{ 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0 } }; static const IID SDL_IID_IMMNotificationClient = { 0x7991eec9, 0x7e89, 0x4d85,{ 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0 } };
@@ -48,13 +49,13 @@ static const PROPERTYKEY SDL_PKEY_AudioEngine_DeviceFormat = { { 0xf19f064d, 0x8
static const PROPERTYKEY SDL_PKEY_AudioEndpoint_GUID = { { 0x1da5d803, 0xd492, 0x4edd,{ 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, } }, 4 }; static const PROPERTYKEY SDL_PKEY_AudioEndpoint_GUID = { { 0x1da5d803, 0xd492, 0x4edd,{ 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, } }, 4 };
static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
/* *INDENT-ON* */ /* clang-format on */
/* these increment as default devices change. Opened default devices pick up changes in their threads. */ /* these increment as default devices change. Opened default devices pick up changes in their threads. */
SDL_atomic_t SDL_IMMDevice_DefaultPlaybackGeneration; SDL_atomic_t SDL_IMMDevice_DefaultPlaybackGeneration;
SDL_atomic_t SDL_IMMDevice_DefaultCaptureGeneration; SDL_atomic_t SDL_IMMDevice_DefaultCaptureGeneration;
static void static void GetMMDeviceInfo(IMMDevice *device, char **utf8dev, WAVEFORMATEXTENSIBLE *fmt, GUID *guid)
GetMMDeviceInfo(IMMDevice *device, char **utf8dev, WAVEFORMATEXTENSIBLE *fmt, GUID *guid)
{ {
/* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be /* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be
"SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in "SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in
@@ -91,8 +92,7 @@ typedef struct DevIdList
static DevIdList *deviceid_list = NULL; static DevIdList *deviceid_list = NULL;
static void static void SDL_IMMDevice_Remove(const SDL_bool iscapture, LPCWSTR devid, SDL_bool useguid)
SDL_IMMDevice_Remove(const SDL_bool iscapture, LPCWSTR devid, SDL_bool useguid)
{ {
DevIdList *i; DevIdList *i;
DevIdList *next; DevIdList *next;
@@ -105,7 +105,7 @@ SDL_IMMDevice_Remove(const SDL_bool iscapture, LPCWSTR devid, SDL_bool useguid)
} else { } else {
deviceid_list = next; deviceid_list = next;
} }
SDL_RemoveAudioDevice(iscapture, useguid ? ((void *) i->guid) : ((void *) i->str)); SDL_RemoveAudioDevice(iscapture, useguid ? ((void *)i->guid) : ((void *)i->str));
SDL_free(i->str); SDL_free(i->str);
SDL_free(i); SDL_free(i);
} else { } else {
@@ -114,8 +114,7 @@ SDL_IMMDevice_Remove(const SDL_bool iscapture, LPCWSTR devid, SDL_bool useguid)
} }
} }
static void static void SDL_IMMDevice_Add(const SDL_bool iscapture, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid, GUID *dsoundguid, SDL_bool useguid)
SDL_IMMDevice_Add(const SDL_bool iscapture, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid, GUID *dsoundguid, SDL_bool useguid)
{ {
DevIdList *devidlist; DevIdList *devidlist;
SDL_AudioSpec spec; SDL_AudioSpec spec;
@@ -185,8 +184,7 @@ typedef struct SDLMMNotificationClient
SDL_bool useguid; SDL_bool useguid;
} SDLMMNotificationClient; } SDLMMNotificationClient;
static HRESULT STDMETHODCALLTYPE static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_QueryInterface(IMMNotificationClient *this, REFIID iid, void **ppv)
SDLMMNotificationClient_QueryInterface(IMMNotificationClient *this, REFIID iid, void **ppv)
{ {
if ((WIN_IsEqualIID(iid, &IID_IUnknown)) || (WIN_IsEqualIID(iid, &SDL_IID_IMMNotificationClient))) { if ((WIN_IsEqualIID(iid, &IID_IUnknown)) || (WIN_IsEqualIID(iid, &SDL_IID_IMMNotificationClient))) {
*ppv = this; *ppv = this;
@@ -198,15 +196,13 @@ SDLMMNotificationClient_QueryInterface(IMMNotificationClient *this, REFIID iid,
return E_NOINTERFACE; return E_NOINTERFACE;
} }
static ULONG STDMETHODCALLTYPE static ULONG STDMETHODCALLTYPE SDLMMNotificationClient_AddRef(IMMNotificationClient *ithis)
SDLMMNotificationClient_AddRef(IMMNotificationClient *ithis)
{ {
SDLMMNotificationClient *this = (SDLMMNotificationClient *)ithis; SDLMMNotificationClient *this = (SDLMMNotificationClient *)ithis;
return (ULONG)(SDL_AtomicIncRef(&this->refcount) + 1); return (ULONG)(SDL_AtomicIncRef(&this->refcount) + 1);
} }
static ULONG STDMETHODCALLTYPE static ULONG STDMETHODCALLTYPE SDLMMNotificationClient_Release(IMMNotificationClient *ithis)
SDLMMNotificationClient_Release(IMMNotificationClient *ithis)
{ {
/* this is a static object; we don't ever free it. */ /* this is a static object; we don't ever free it. */
SDLMMNotificationClient *this = (SDLMMNotificationClient *)ithis; SDLMMNotificationClient *this = (SDLMMNotificationClient *)ithis;
@@ -219,8 +215,7 @@ SDLMMNotificationClient_Release(IMMNotificationClient *ithis)
} }
/* These are the entry points called when WASAPI device endpoints change. */ /* These are the entry points called when WASAPI device endpoints change. */
static HRESULT STDMETHODCALLTYPE static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *ithis, EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId)
SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *ithis, EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId)
{ {
if (role != SDL_IMMDevice_role) { if (role != SDL_IMMDevice_role) {
return S_OK; /* ignore it. */ return S_OK; /* ignore it. */
@@ -249,8 +244,7 @@ SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *ithis, EDa
return S_OK; return S_OK;
} }
static HRESULT STDMETHODCALLTYPE static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
{ {
/* we ignore this; devices added here then progress to ACTIVE, if appropriate, in /* we ignore this; devices added here then progress to ACTIVE, if appropriate, in
OnDeviceStateChange, making that a better place to deal with device adds. More OnDeviceStateChange, making that a better place to deal with device adds. More
@@ -260,15 +254,13 @@ SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *ithis, LPCWSTR pwst
return S_OK; return S_OK;
} }
static HRESULT STDMETHODCALLTYPE static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceRemoved(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
SDLMMNotificationClient_OnDeviceRemoved(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
{ {
/* See notes in OnDeviceAdded handler about why we ignore this. */ /* See notes in OnDeviceAdded handler about why we ignore this. */
return S_OK; return S_OK;
} }
static HRESULT STDMETHODCALLTYPE static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId, DWORD dwNewState)
SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId, DWORD dwNewState)
{ {
IMMDevice *device = NULL; IMMDevice *device = NULL;
@@ -278,7 +270,7 @@ SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *ithis, LPCWS
EDataFlow flow; EDataFlow flow;
if (SUCCEEDED(IMMEndpoint_GetDataFlow(endpoint, &flow))) { if (SUCCEEDED(IMMEndpoint_GetDataFlow(endpoint, &flow))) {
const SDL_bool iscapture = (flow == eCapture); const SDL_bool iscapture = (flow == eCapture);
const SDLMMNotificationClient *client = (SDLMMNotificationClient*) ithis; const SDLMMNotificationClient *client = (SDLMMNotificationClient *)ithis;
if (dwNewState == DEVICE_STATE_ACTIVE) { if (dwNewState == DEVICE_STATE_ACTIVE) {
char *utf8dev; char *utf8dev;
WAVEFORMATEXTENSIBLE fmt; WAVEFORMATEXTENSIBLE fmt;
@@ -300,8 +292,7 @@ SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *ithis, LPCWS
return S_OK; return S_OK;
} }
static HRESULT STDMETHODCALLTYPE static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnPropertyValueChanged(IMMNotificationClient *this, LPCWSTR pwstrDeviceId, const PROPERTYKEY key)
SDLMMNotificationClient_OnPropertyValueChanged(IMMNotificationClient *this, LPCWSTR pwstrDeviceId, const PROPERTYKEY key)
{ {
return S_OK; /* we don't care about these. */ return S_OK; /* we don't care about these. */
} }
@@ -319,8 +310,7 @@ static const IMMNotificationClientVtbl notification_client_vtbl = {
static SDLMMNotificationClient notification_client = { &notification_client_vtbl, { 1 } }; static SDLMMNotificationClient notification_client = { &notification_client_vtbl, { 1 } };
int int SDL_IMMDevice_Init(void)
SDL_IMMDevice_Init(void)
{ {
HRESULT ret; HRESULT ret;
@@ -344,8 +334,7 @@ SDL_IMMDevice_Init(void)
return 0; return 0;
} }
void void SDL_IMMDevice_Quit(void)
SDL_IMMDevice_Quit(void)
{ {
DevIdList *devidlist; DevIdList *devidlist;
DevIdList *next; DevIdList *next;
@@ -366,8 +355,7 @@ SDL_IMMDevice_Quit(void)
deviceid_list = NULL; deviceid_list = NULL;
} }
int int SDL_IMMDevice_Get(LPCWSTR devid, IMMDevice **device, SDL_bool iscapture)
SDL_IMMDevice_Get(LPCWSTR devid, IMMDevice **device, SDL_bool iscapture)
{ {
HRESULT ret; HRESULT ret;
@@ -422,8 +410,7 @@ static int SDLCALL sort_endpoints(const void *_a, const void *_b)
return 0; return 0;
} }
static void static void EnumerateEndpointsForFlow(const SDL_bool iscapture)
EnumerateEndpointsForFlow(const SDL_bool iscapture)
{ {
IMMDeviceCollection *collection = NULL; IMMDeviceCollection *collection = NULL;
EndpointItem *items; EndpointItem *items;
@@ -474,8 +461,7 @@ EnumerateEndpointsForFlow(const SDL_bool iscapture)
IMMDeviceCollection_Release(collection); IMMDeviceCollection_Release(collection);
} }
void void SDL_IMMDevice_EnumerateEndpoints(SDL_bool useguid)
SDL_IMMDevice_EnumerateEndpoints(SDL_bool useguid)
{ {
notification_client.useguid = useguid; notification_client.useguid = useguid;
@@ -486,8 +472,7 @@ SDL_IMMDevice_EnumerateEndpoints(SDL_bool useguid)
IMMDeviceEnumerator_RegisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *)&notification_client); IMMDeviceEnumerator_RegisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *)&notification_client);
} }
int int SDL_IMMDevice_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
SDL_IMMDevice_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
{ {
WAVEFORMATEXTENSIBLE fmt; WAVEFORMATEXTENSIBLE fmt;
IMMDevice *device = NULL; IMMDevice *device = NULL;
@@ -516,7 +501,7 @@ SDL_IMMDevice_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscaptur
SDL_zerop(spec); SDL_zerop(spec);
spec->channels = (Uint8)fmt.Format.nChannels; spec->channels = (Uint8)fmt.Format.nChannels;
spec->freq = fmt.Format.nSamplesPerSec; spec->freq = fmt.Format.nSamplesPerSec;
spec->format = WaveFormatToSDLFormat((WAVEFORMATEX *) &fmt); spec->format = WaveFormatToSDLFormat((WAVEFORMATEX *)&fmt);
return 0; return 0;
} }

View File

@@ -22,7 +22,6 @@
#ifndef SDL_IMMDEVICE_H #ifndef SDL_IMMDEVICE_H
#define SDL_IMMDEVICE_H #define SDL_IMMDEVICE_H
#define COBJMACROS #define COBJMACROS
#include <mmdeviceapi.h> #include <mmdeviceapi.h>
#include <mmreg.h> #include <mmreg.h>

View File

@@ -28,7 +28,8 @@
#if defined(HAVE_ROAPI_H) #if defined(HAVE_ROAPI_H)
#include <roapi.h> /* For RoInitialize/RoUninitialize (Win32 only) */ #include <roapi.h> /* For RoInitialize/RoUninitialize (Win32 only) */
#else #else
typedef enum RO_INIT_TYPE { typedef enum RO_INIT_TYPE
{
RO_INIT_SINGLETHREADED = 0, RO_INIT_SINGLETHREADED = 0,
RO_INIT_MULTITHREADED = 1 RO_INIT_MULTITHREADED = 1
} RO_INIT_TYPE; } RO_INIT_TYPE;
@@ -48,10 +49,8 @@ typedef enum RO_INIT_TYPE {
#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800 #define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif #endif
/* Sets an error message based on an HRESULT */ /* Sets an error message based on an HRESULT */
int int WIN_SetErrorFromHRESULT(const char *prefix, HRESULT hr)
WIN_SetErrorFromHRESULT(const char *prefix, HRESULT hr)
{ {
TCHAR buffer[1024]; TCHAR buffer[1024];
char *message; char *message;
@@ -74,8 +73,7 @@ WIN_SetErrorFromHRESULT(const char *prefix, HRESULT hr)
} }
/* Sets an error message based on GetLastError() */ /* Sets an error message based on GetLastError() */
int int WIN_SetError(const char *prefix)
WIN_SetError(const char *prefix)
{ {
return WIN_SetErrorFromHRESULT(prefix, GetLastError()); return WIN_SetErrorFromHRESULT(prefix, GetLastError());
} }
@@ -114,8 +112,7 @@ WIN_CoInitialize(void)
#endif #endif
} }
void void WIN_CoUninitialize(void)
WIN_CoUninitialize(void)
{ {
#ifndef __WINRT__ #ifndef __WINRT__
CoUninitialize(); CoUninitialize();
@@ -147,7 +144,7 @@ WIN_RoInitialize(void)
#ifdef __WINRT__ #ifdef __WINRT__
return S_OK; return S_OK;
#else #else
typedef HRESULT (WINAPI *RoInitialize_t)(RO_INIT_TYPE initType); typedef HRESULT(WINAPI * RoInitialize_t)(RO_INIT_TYPE initType);
RoInitialize_t RoInitializeFunc = (RoInitialize_t)WIN_LoadComBaseFunction("RoInitialize"); RoInitialize_t RoInitializeFunc = (RoInitialize_t)WIN_LoadComBaseFunction("RoInitialize");
if (RoInitializeFunc) { if (RoInitializeFunc) {
/* RO_INIT_SINGLETHREADED is equivalent to COINIT_APARTMENTTHREADED */ /* RO_INIT_SINGLETHREADED is equivalent to COINIT_APARTMENTTHREADED */
@@ -169,11 +166,10 @@ WIN_RoInitialize(void)
#endif #endif
} }
void void WIN_RoUninitialize(void)
WIN_RoUninitialize(void)
{ {
#ifndef __WINRT__ #ifndef __WINRT__
typedef void (WINAPI *RoUninitialize_t)(void); typedef void(WINAPI * RoUninitialize_t)(void);
RoUninitialize_t RoUninitializeFunc = (RoUninitialize_t)WIN_LoadComBaseFunction("RoUninitialize"); RoUninitialize_t RoUninitializeFunc = (RoUninitialize_t)WIN_LoadComBaseFunction("RoUninitialize");
if (RoUninitializeFunc) { if (RoUninitializeFunc) {
RoUninitializeFunc(); RoUninitializeFunc();
@@ -182,16 +178,15 @@ WIN_RoUninitialize(void)
} }
#if !defined(__WINRT__) && !defined(__XBOXONE__) && !defined(__XBOXSERIES__) #if !defined(__WINRT__) && !defined(__XBOXONE__) && !defined(__XBOXSERIES__)
static BOOL static BOOL IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
{ {
OSVERSIONINFOEXW osvi; OSVERSIONINFOEXW osvi;
DWORDLONG const dwlConditionMask = VerSetConditionMask( DWORDLONG const dwlConditionMask = VerSetConditionMask(
VerSetConditionMask( VerSetConditionMask(
VerSetConditionMask( VerSetConditionMask(
0, VER_MAJORVERSION, VER_GREATER_EQUAL ), 0, VER_MAJORVERSION, VER_GREATER_EQUAL),
VER_MINORVERSION, VER_GREATER_EQUAL ), VER_MINORVERSION, VER_GREATER_EQUAL),
VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL ); VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
SDL_zero(osvi); SDL_zero(osvi);
osvi.dwOSVersionInfoSize = sizeof(osvi); osvi.dwOSVersionInfoSize = sizeof(osvi);
@@ -270,8 +265,8 @@ WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid)
return WIN_StringToUTF8(name); /* No GUID, go with what we've got. */ return WIN_StringToUTF8(name); /* No GUID, go with what we've got. */
} }
ptr = (const unsigned char *) guid; ptr = (const unsigned char *)guid;
SDL_snprintf(keystr, sizeof (keystr), SDL_snprintf(keystr, sizeof(keystr),
"System\\CurrentControlSet\\Control\\MediaCategories\\{%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X}", "System\\CurrentControlSet\\Control\\MediaCategories\\{%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
ptr[3], ptr[2], ptr[1], ptr[0], ptr[5], ptr[4], ptr[7], ptr[6], ptr[3], ptr[2], ptr[1], ptr[0], ptr[5], ptr[4], ptr[7], ptr[6],
ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]); ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]);
@@ -289,13 +284,13 @@ WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid)
return WIN_StringToUTF8(name); /* oh well. */ return WIN_StringToUTF8(name); /* oh well. */
} }
strw = (WCHAR *) SDL_malloc(len + sizeof (WCHAR)); strw = (WCHAR *)SDL_malloc(len + sizeof(WCHAR));
if (strw == NULL) { if (strw == NULL) {
RegCloseKey(hkey); RegCloseKey(hkey);
return WIN_StringToUTF8(name); /* oh well. */ return WIN_StringToUTF8(name); /* oh well. */
} }
rc = (RegQueryValueExW(hkey, L"Name", NULL, NULL, (LPBYTE) strw, &len) == ERROR_SUCCESS); rc = (RegQueryValueExW(hkey, L"Name", NULL, NULL, (LPBYTE)strw, &len) == ERROR_SUCCESS);
RegCloseKey(hkey); RegCloseKey(hkey);
if (!rc) { if (!rc) {
SDL_free(strw); SDL_free(strw);
@@ -310,20 +305,17 @@ WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid)
#endif /* if __WINRT__ / else */ #endif /* if __WINRT__ / else */
} }
BOOL BOOL WIN_IsEqualGUID(const GUID *a, const GUID *b)
WIN_IsEqualGUID(const GUID * a, const GUID * b)
{ {
return SDL_memcmp(a, b, sizeof(*a)) == 0; return SDL_memcmp(a, b, sizeof(*a)) == 0;
} }
BOOL BOOL WIN_IsEqualIID(REFIID a, REFIID b)
WIN_IsEqualIID(REFIID a, REFIID b)
{ {
return SDL_memcmp(a, b, sizeof(*a)) == 0; return SDL_memcmp(a, b, sizeof(*a)) == 0;
} }
void void WIN_RECTToRect(const RECT *winrect, SDL_Rect *sdlrect)
WIN_RECTToRect(const RECT *winrect, SDL_Rect *sdlrect)
{ {
sdlrect->x = winrect->left; sdlrect->x = winrect->left;
sdlrect->w = (winrect->right - winrect->left) + 1; sdlrect->w = (winrect->right - winrect->left) + 1;
@@ -331,8 +323,7 @@ WIN_RECTToRect(const RECT *winrect, SDL_Rect *sdlrect)
sdlrect->h = (winrect->bottom - winrect->top) + 1; sdlrect->h = (winrect->bottom - winrect->top) + 1;
} }
void void WIN_RectToRECT(const SDL_Rect *sdlrect, RECT *winrect)
WIN_RectToRECT(const SDL_Rect *sdlrect, RECT *winrect)
{ {
winrect->left = sdlrect->x; winrect->left = sdlrect->x;
winrect->right = sdlrect->x + sdlrect->w - 1; winrect->right = sdlrect->x + sdlrect->w - 1;
@@ -342,24 +333,21 @@ WIN_RectToRECT(const SDL_Rect *sdlrect, RECT *winrect)
#endif /* defined(__WIN32__) || defined(__WINRT__) || defined(__GDK__) */ #endif /* defined(__WIN32__) || defined(__WINRT__) || defined(__GDK__) */
/* /*
* Public APIs * Public APIs
*/ */
#if !defined(SDL_VIDEO_DRIVER_WINDOWS) #if !defined(SDL_VIDEO_DRIVER_WINDOWS)
#if defined(__WIN32__) || defined(__GDK__) #if defined(__WIN32__) || defined(__GDK__)
int int SDL_RegisterApp(const char *name, Uint32 style, void *hInst)
SDL_RegisterApp(const char *name, Uint32 style, void *hInst)
{ {
(void) name; (void)name;
(void) style; (void)style;
(void) hInst; (void)hInst;
return 0; return 0;
} }
void void SDL_UnregisterApp(void)
SDL_UnregisterApp(void)
{ {
} }
@@ -369,17 +357,16 @@ void SDL_SetWindowsMessageHook(SDL_WindowsMessageHook callback, void *userdata)
#endif /* __WIN32__ || __GDK__ */ #endif /* __WIN32__ || __GDK__ */
#if defined(__WIN32__) || defined(__WINGDK__) #if defined(__WIN32__) || defined(__WINGDK__)
int int SDL_Direct3D9GetAdapterIndex(int displayIndex)
SDL_Direct3D9GetAdapterIndex(int displayIndex)
{ {
(void) displayIndex; (void)displayIndex;
return 0; /* D3DADAPTER_DEFAULT */ return 0; /* D3DADAPTER_DEFAULT */
} }
SDL_bool SDL_bool
SDL_DXGIGetOutputInfo(int displayIndex, int *adapterIndex, int *outputIndex) SDL_DXGIGetOutputInfo(int displayIndex, int *adapterIndex, int *outputIndex)
{ {
(void) displayIndex; (void)displayIndex;
if (adapterIndex) { if (adapterIndex) {
*adapterIndex = -1; *adapterIndex = -1;
} }

View File

@@ -90,11 +90,11 @@
#endif #endif
/* Routines to convert from UTF8 to native Windows text */ /* Routines to convert from UTF8 to native Windows text */
#define WIN_StringToUTF8W(S) SDL_iconv_string("UTF-8", "UTF-16LE", (const char *)(S), (SDL_wcslen(S)+1)*sizeof(WCHAR)) #define WIN_StringToUTF8W(S) SDL_iconv_string("UTF-8", "UTF-16LE", (const char *)(S), (SDL_wcslen(S) + 1) * sizeof(WCHAR))
#define WIN_UTF8ToStringW(S) (WCHAR *)SDL_iconv_string("UTF-16LE", "UTF-8", (const char *)(S), SDL_strlen(S)+1) #define WIN_UTF8ToStringW(S) (WCHAR *)SDL_iconv_string("UTF-16LE", "UTF-8", (const char *)(S), SDL_strlen(S) + 1)
/* !!! FIXME: UTF8ToString() can just be a SDL_strdup() here. */ /* !!! FIXME: UTF8ToString() can just be a SDL_strdup() here. */
#define WIN_StringToUTF8A(S) SDL_iconv_string("UTF-8", "ASCII", (const char *)(S), (SDL_strlen(S)+1)) #define WIN_StringToUTF8A(S) SDL_iconv_string("UTF-8", "ASCII", (const char *)(S), (SDL_strlen(S) + 1))
#define WIN_UTF8ToStringA(S) SDL_iconv_string("ASCII", "UTF-8", (const char *)(S), SDL_strlen(S)+1) #define WIN_UTF8ToStringA(S) SDL_iconv_string("ASCII", "UTF-8", (const char *)(S), SDL_strlen(S) + 1)
#if UNICODE #if UNICODE
#define WIN_StringToUTF8 WIN_StringToUTF8W #define WIN_StringToUTF8 WIN_StringToUTF8W
#define WIN_UTF8ToString WIN_UTF8ToStringW #define WIN_UTF8ToString WIN_UTF8ToStringW
@@ -144,7 +144,7 @@ extern BOOL WIN_IsWindows8OrGreater(void);
extern char *WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid); extern char *WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid);
/* Checks to see if two GUID are the same. */ /* Checks to see if two GUID are the same. */
extern BOOL WIN_IsEqualGUID(const GUID * a, const GUID * b); extern BOOL WIN_IsEqualGUID(const GUID *a, const GUID *b);
extern BOOL WIN_IsEqualIID(REFIID a, REFIID b); extern BOOL WIN_IsEqualIID(REFIID a, REFIID b);
/* Convert between SDL_rect and RECT */ /* Convert between SDL_rect and RECT */

View File

@@ -36,11 +36,9 @@ DWORD SDL_XInputVersion = 0;
static HANDLE s_pXInputDLL = 0; static HANDLE s_pXInputDLL = 0;
static int s_XInputDLLRefCount = 0; static int s_XInputDLLRefCount = 0;
#if defined(__WINRT__) || defined(__XBOXONE__) || defined(__XBOXSERIES__) #if defined(__WINRT__) || defined(__XBOXONE__) || defined(__XBOXSERIES__)
int int WIN_LoadXInputDLL(void)
WIN_LoadXInputDLL(void)
{ {
/* Getting handles to system dlls (via LoadLibrary and its variants) is not /* Getting handles to system dlls (via LoadLibrary and its variants) is not
* supported on WinRT, thus, pointers to XInput's functions can't be * supported on WinRT, thus, pointers to XInput's functions can't be
@@ -65,15 +63,13 @@ WIN_LoadXInputDLL(void)
return 0; return 0;
} }
void void WIN_UnloadXInputDLL(void)
WIN_UnloadXInputDLL(void)
{ {
} }
#else /* !(defined(__WINRT__) || defined(__XBOXONE__) || defined(__XBOXSERIES__)) */ #else /* !(defined(__WINRT__) || defined(__XBOXONE__) || defined(__XBOXSERIES__)) */
int int WIN_LoadXInputDLL(void)
WIN_LoadXInputDLL(void)
{ {
DWORD version = 0; DWORD version = 0;
@@ -115,7 +111,7 @@ WIN_LoadXInputDLL(void)
} }
SDL_XInputSetState = (XInputSetState_t)GetProcAddress((HMODULE)s_pXInputDLL, "XInputSetState"); SDL_XInputSetState = (XInputSetState_t)GetProcAddress((HMODULE)s_pXInputDLL, "XInputSetState");
SDL_XInputGetCapabilities = (XInputGetCapabilities_t)GetProcAddress((HMODULE)s_pXInputDLL, "XInputGetCapabilities"); SDL_XInputGetCapabilities = (XInputGetCapabilities_t)GetProcAddress((HMODULE)s_pXInputDLL, "XInputGetCapabilities");
SDL_XInputGetBatteryInformation = (XInputGetBatteryInformation_t)GetProcAddress( (HMODULE)s_pXInputDLL, "XInputGetBatteryInformation" ); SDL_XInputGetBatteryInformation = (XInputGetBatteryInformation_t)GetProcAddress((HMODULE)s_pXInputDLL, "XInputGetBatteryInformation");
if (SDL_XInputGetState == NULL || SDL_XInputSetState == NULL || SDL_XInputGetCapabilities == NULL) { if (SDL_XInputGetState == NULL || SDL_XInputSetState == NULL || SDL_XInputGetCapabilities == NULL) {
WIN_UnloadXInputDLL(); WIN_UnloadXInputDLL();
return -1; return -1;
@@ -124,8 +120,7 @@ WIN_LoadXInputDLL(void)
return 0; return 0;
} }
void void WIN_UnloadXInputDLL(void)
WIN_UnloadXInputDLL(void)
{ {
if (s_pXInputDLL) { if (s_pXInputDLL) {
SDL_assert(s_XInputDLLRefCount > 0); SDL_assert(s_XInputDLLRefCount > 0);

View File

@@ -222,31 +222,26 @@ typedef struct
#endif /* HAVE_XINPUT_H */ #endif /* HAVE_XINPUT_H */
/* Forward decl's for XInput API's we load dynamically and use if available */ /* Forward decl's for XInput API's we load dynamically and use if available */
typedef DWORD (WINAPI *XInputGetState_t) typedef DWORD(WINAPI *XInputGetState_t)(
(
DWORD dwUserIndex, /* [in] Index of the gamer associated with the device */ DWORD dwUserIndex, /* [in] Index of the gamer associated with the device */
XINPUT_STATE_EX* pState /* [out] Receives the current state */ XINPUT_STATE_EX *pState /* [out] Receives the current state */
); );
typedef DWORD (WINAPI *XInputSetState_t) typedef DWORD(WINAPI *XInputSetState_t)(
(
DWORD dwUserIndex, /* [in] Index of the gamer associated with the device */ DWORD dwUserIndex, /* [in] Index of the gamer associated with the device */
XINPUT_VIBRATION* pVibration /* [in, out] The vibration information to send to the controller */ XINPUT_VIBRATION *pVibration /* [in, out] The vibration information to send to the controller */
); );
typedef DWORD (WINAPI *XInputGetCapabilities_t) typedef DWORD(WINAPI *XInputGetCapabilities_t)(
(
DWORD dwUserIndex, /* [in] Index of the gamer associated with the device */ DWORD dwUserIndex, /* [in] Index of the gamer associated with the device */
DWORD dwFlags, /* [in] Input flags that identify the device type */ DWORD dwFlags, /* [in] Input flags that identify the device type */
XINPUT_CAPABILITIES* pCapabilities /* [out] Receives the capabilities */ XINPUT_CAPABILITIES *pCapabilities /* [out] Receives the capabilities */
); );
typedef DWORD (WINAPI *XInputGetBatteryInformation_t) typedef DWORD(WINAPI *XInputGetBatteryInformation_t)(
(
DWORD dwUserIndex, DWORD dwUserIndex,
BYTE devType, BYTE devType,
XINPUT_BATTERY_INFORMATION_EX *pBatteryInformation XINPUT_BATTERY_INFORMATION_EX *pBatteryInformation);
);
extern int WIN_LoadXInputDLL(void); extern int WIN_LoadXInputDLL(void);
extern void WIN_UnloadXInputDLL(void); extern void WIN_UnloadXInputDLL(void);

View File

@@ -28,7 +28,7 @@
int (*WINRT_SDLAppEntryPoint)(int, char **) = NULL; int (*WINRT_SDLAppEntryPoint)(int, char **) = NULL;
extern "C" DECLSPEC int extern "C" DECLSPEC int
SDL_WinRTRunApp(SDL_main_func mainFunction, void * xamlBackgroundPanel) SDL_WinRTRunApp(SDL_main_func mainFunction, void *xamlBackgroundPanel)
{ {
if (xamlBackgroundPanel) { if (xamlBackgroundPanel) {
return SDL_WinRTInitXAMLApp(mainFunction, xamlBackgroundPanel); return SDL_WinRTInitXAMLApp(mainFunction, xamlBackgroundPanel);
@@ -40,12 +40,11 @@ SDL_WinRTRunApp(SDL_main_func mainFunction, void * xamlBackgroundPanel)
} }
} }
extern "C" DECLSPEC SDL_WinRT_DeviceFamily extern "C" DECLSPEC SDL_WinRT_DeviceFamily
SDL_WinRTGetDeviceFamily() SDL_WinRTGetDeviceFamily()
{ {
#if NTDDI_VERSION >= NTDDI_WIN10 /* !!! FIXME: I have no idea if this is the right test. This is a UWP API, I think. Older windows should...just return "mobile"? I don't know. --ryan. */ #if NTDDI_VERSION >= NTDDI_WIN10 /* !!! FIXME: I have no idea if this is the right test. This is a UWP API, I think. Older windows should...just return "mobile"? I don't know. --ryan. */
Platform::String^ deviceFamily = Windows::System::Profile::AnalyticsInfo::VersionInfo->DeviceFamily; Platform::String ^ deviceFamily = Windows::System::Profile::AnalyticsInfo::VersionInfo->DeviceFamily;
if (deviceFamily->Equals("Windows.Desktop")) { if (deviceFamily->Equals("Windows.Desktop")) {
return SDL_WINRT_DEVICEFAMILY_DESKTOP; return SDL_WINRT_DEVICEFAMILY_DESKTOP;

View File

@@ -26,7 +26,6 @@
#include <sstream> #include <sstream>
using namespace std; using namespace std;
/* Windows includes */ /* Windows includes */
#include "ppltasks.h" #include "ppltasks.h"
using namespace concurrency; using namespace concurrency;
@@ -44,7 +43,6 @@ using namespace Windows::UI::Input;
using namespace Windows::Phone::UI::Input; using namespace Windows::Phone::UI::Input;
#endif #endif
/* SDL includes */ /* SDL includes */
extern "C" { extern "C" {
#include "../../video/SDL_sysvideo.h" #include "../../video/SDL_sysvideo.h"
@@ -69,14 +67,12 @@ extern "C" {
extern "C" void D3D11_Trim(SDL_Renderer *); extern "C" void D3D11_Trim(SDL_Renderer *);
#endif #endif
// Compile-time debugging options: // Compile-time debugging options:
// To enable, uncomment; to disable, comment them out. // To enable, uncomment; to disable, comment them out.
//#define LOG_POINTER_EVENTS 1 //#define LOG_POINTER_EVENTS 1
//#define LOG_WINDOW_EVENTS 1 //#define LOG_WINDOW_EVENTS 1
//#define LOG_ORIENTATION_EVENTS 1 //#define LOG_ORIENTATION_EVENTS 1
// HACK, DLudwig: record a reference to the global, WinRT 'app'/view. // HACK, DLudwig: record a reference to the global, WinRT 'app'/view.
// SDL/WinRT will use this throughout its code. // SDL/WinRT will use this throughout its code.
// //
@@ -88,11 +84,11 @@ SDL_WinRTApp ^ SDL_WinRTGlobalApp = nullptr;
ref class SDLApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource ref class SDLApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
{ {
public: public:
virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView(); virtual Windows::ApplicationModel::Core::IFrameworkView ^ CreateView();
}; };
IFrameworkView^ SDLApplicationSource::CreateView() IFrameworkView ^ SDLApplicationSource::CreateView()
{ {
// TODO, WinRT: see if this function (CreateView) can ever get called // TODO, WinRT: see if this function (CreateView) can ever get called
// more than once. For now, just prevent it from ever assigning // more than once. For now, just prevent it from ever assigning
@@ -113,14 +109,13 @@ int SDL_WinRTInitNonXAMLApp(int (*mainFunction)(int, char **))
return 0; return 0;
} }
static void static void WINRT_ProcessWindowSizeChange() // TODO: Pass an SDL_Window-identifying thing into WINRT_ProcessWindowSizeChange()
WINRT_ProcessWindowSizeChange() // TODO: Pass an SDL_Window-identifying thing into WINRT_ProcessWindowSizeChange()
{ {
CoreWindow ^ coreWindow = CoreWindow::GetForCurrentThread(); CoreWindow ^ coreWindow = CoreWindow::GetForCurrentThread();
if (coreWindow) { if (coreWindow) {
if (WINRT_GlobalSDLWindow) { if (WINRT_GlobalSDLWindow) {
SDL_Window * window = WINRT_GlobalSDLWindow; SDL_Window *window = WINRT_GlobalSDLWindow;
SDL_WindowData * data = (SDL_WindowData *) window->driverdata; SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
int x = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Left); int x = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Left);
int y = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Top); int y = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Top);
@@ -140,7 +135,8 @@ WINRT_ProcessWindowSizeChange() // TODO: Pass an SDL_Window-identifying thing in
const DisplayOrientations currentOrientation = WINRT_DISPLAY_PROPERTY(CurrentOrientation); const DisplayOrientations currentOrientation = WINRT_DISPLAY_PROPERTY(CurrentOrientation);
switch (currentOrientation) { switch (currentOrientation) {
case DisplayOrientations::Landscape: case DisplayOrientations::Landscape:
case DisplayOrientations::LandscapeFlipped: { case DisplayOrientations::LandscapeFlipped:
{
int tmp = w; int tmp = w;
w = h; w = h;
h = tmp; h = tmp;
@@ -165,25 +161,24 @@ WINRT_ProcessWindowSizeChange() // TODO: Pass an SDL_Window-identifying thing in
} }
} }
SDL_WinRTApp::SDL_WinRTApp() : SDL_WinRTApp::SDL_WinRTApp() : m_windowClosed(false),
m_windowClosed(false),
m_windowVisible(true) m_windowVisible(true)
{ {
} }
void SDL_WinRTApp::Initialize(CoreApplicationView^ applicationView) void SDL_WinRTApp::Initialize(CoreApplicationView ^ applicationView)
{ {
applicationView->Activated += applicationView->Activated +=
ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &SDL_WinRTApp::OnAppActivated); ref new TypedEventHandler<CoreApplicationView ^, IActivatedEventArgs ^>(this, &SDL_WinRTApp::OnAppActivated);
CoreApplication::Suspending += CoreApplication::Suspending +=
ref new EventHandler<SuspendingEventArgs^>(this, &SDL_WinRTApp::OnSuspending); ref new EventHandler<SuspendingEventArgs ^>(this, &SDL_WinRTApp::OnSuspending);
CoreApplication::Resuming += CoreApplication::Resuming +=
ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnResuming); ref new EventHandler<Platform::Object ^>(this, &SDL_WinRTApp::OnResuming);
CoreApplication::Exiting += CoreApplication::Exiting +=
ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnExiting); ref new EventHandler<Platform::Object ^>(this, &SDL_WinRTApp::OnExiting);
#if NTDDI_VERSION >= NTDDI_WIN10 #if NTDDI_VERSION >= NTDDI_WIN10
/* HACK ALERT! Xbox One doesn't seem to detect gamepads unless something /* HACK ALERT! Xbox One doesn't seem to detect gamepads unless something
@@ -192,21 +187,20 @@ void SDL_WinRTApp::Initialize(CoreApplicationView^ applicationView)
sure that gamepad detection works later on, if requested. sure that gamepad detection works later on, if requested.
*/ */
Windows::Gaming::Input::Gamepad::GamepadAdded += Windows::Gaming::Input::Gamepad::GamepadAdded +=
ref new Windows::Foundation::EventHandler<Windows::Gaming::Input::Gamepad^>( ref new Windows::Foundation::EventHandler<Windows::Gaming::Input::Gamepad ^>(
this, &SDL_WinRTApp::OnGamepadAdded this, &SDL_WinRTApp::OnGamepadAdded);
);
#endif #endif
} }
#if NTDDI_VERSION > NTDDI_WIN8 #if NTDDI_VERSION > NTDDI_WIN8
void SDL_WinRTApp::OnOrientationChanged(DisplayInformation^ sender, Object^ args) void SDL_WinRTApp::OnOrientationChanged(DisplayInformation ^ sender, Object ^ args)
#else #else
void SDL_WinRTApp::OnOrientationChanged(Object^ sender) void SDL_WinRTApp::OnOrientationChanged(Object ^ sender)
#endif #endif
{ {
#if LOG_ORIENTATION_EVENTS==1 #if LOG_ORIENTATION_EVENTS == 1
{ {
CoreWindow^ window = CoreWindow::GetForCurrentThread(); CoreWindow ^ window = CoreWindow::GetForCurrentThread();
if (window) { if (window) {
SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, CoreWindow Bounds={%f,%f,%f,%f}\n", SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, CoreWindow Bounds={%f,%f,%f,%f}\n",
__FUNCTION__, __FUNCTION__,
@@ -239,20 +233,19 @@ void SDL_WinRTApp::OnOrientationChanged(Object^ sender)
// I'm not currently sure why this is, but it seems to work fine. -- David L. // I'm not currently sure why this is, but it seems to work fine. -- David L.
// //
// TODO, WinRT: do more extensive research into why orientation changes on Win 8.x don't need D3D changes, or if they might, in some cases // TODO, WinRT: do more extensive research into why orientation changes on Win 8.x don't need D3D changes, or if they might, in some cases
SDL_Window * window = WINRT_GlobalSDLWindow; SDL_Window *window = WINRT_GlobalSDLWindow;
if (window) { if (window) {
SDL_WindowData * data = (SDL_WindowData *)window->driverdata; SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
int w = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Width); int w = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Width);
int h = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Height); int h = WINRT_DIPS_TO_PHYSICAL_PIXELS(data->coreWindow->Bounds.Height);
SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_SIZE_CHANGED, w, h); SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_SIZE_CHANGED, w, h);
} }
#endif #endif
} }
void SDL_WinRTApp::SetWindow(CoreWindow^ window) void SDL_WinRTApp::SetWindow(CoreWindow ^ window)
{ {
#if LOG_WINDOW_EVENTS==1 #if LOG_WINDOW_EVENTS == 1
SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, window bounds={%f, %f, %f,%f}\n", SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, window bounds={%f, %f, %f,%f}\n",
__FUNCTION__, __FUNCTION__,
WINRT_DISPLAY_PROPERTY(CurrentOrientation), WINRT_DISPLAY_PROPERTY(CurrentOrientation),
@@ -265,65 +258,65 @@ void SDL_WinRTApp::SetWindow(CoreWindow^ window)
#endif #endif
window->SizeChanged += window->SizeChanged +=
ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &SDL_WinRTApp::OnWindowSizeChanged); ref new TypedEventHandler<CoreWindow ^, WindowSizeChangedEventArgs ^>(this, &SDL_WinRTApp::OnWindowSizeChanged);
window->VisibilityChanged += window->VisibilityChanged +=
ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &SDL_WinRTApp::OnVisibilityChanged); ref new TypedEventHandler<CoreWindow ^, VisibilityChangedEventArgs ^>(this, &SDL_WinRTApp::OnVisibilityChanged);
window->Activated += window->Activated +=
ref new TypedEventHandler<CoreWindow^, WindowActivatedEventArgs^>(this, &SDL_WinRTApp::OnWindowActivated); ref new TypedEventHandler<CoreWindow ^, WindowActivatedEventArgs ^>(this, &SDL_WinRTApp::OnWindowActivated);
window->Closed += window->Closed +=
ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &SDL_WinRTApp::OnWindowClosed); ref new TypedEventHandler<CoreWindow ^, CoreWindowEventArgs ^>(this, &SDL_WinRTApp::OnWindowClosed);
#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP #if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0); window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
#endif #endif
window->PointerPressed += window->PointerPressed +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerPressed); ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &SDL_WinRTApp::OnPointerPressed);
window->PointerMoved += window->PointerMoved +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerMoved); ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &SDL_WinRTApp::OnPointerMoved);
window->PointerReleased += window->PointerReleased +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerReleased); ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &SDL_WinRTApp::OnPointerReleased);
window->PointerEntered += window->PointerEntered +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerEntered); ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &SDL_WinRTApp::OnPointerEntered);
window->PointerExited += window->PointerExited +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerExited); ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &SDL_WinRTApp::OnPointerExited);
window->PointerWheelChanged += window->PointerWheelChanged +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerWheelChanged); ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &SDL_WinRTApp::OnPointerWheelChanged);
#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP #if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
// Retrieves relative-only mouse movements: // Retrieves relative-only mouse movements:
Windows::Devices::Input::MouseDevice::GetForCurrentView()->MouseMoved += Windows::Devices::Input::MouseDevice::GetForCurrentView()->MouseMoved +=
ref new TypedEventHandler<MouseDevice^, MouseEventArgs^>(this, &SDL_WinRTApp::OnMouseMoved); ref new TypedEventHandler<MouseDevice ^, MouseEventArgs ^>(this, &SDL_WinRTApp::OnMouseMoved);
#endif #endif
window->KeyDown += window->KeyDown +=
ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyDown); ref new TypedEventHandler<CoreWindow ^, KeyEventArgs ^>(this, &SDL_WinRTApp::OnKeyDown);
window->KeyUp += window->KeyUp +=
ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyUp); ref new TypedEventHandler<CoreWindow ^, KeyEventArgs ^>(this, &SDL_WinRTApp::OnKeyUp);
window->CharacterReceived += window->CharacterReceived +=
ref new TypedEventHandler<CoreWindow^, CharacterReceivedEventArgs^>(this, &SDL_WinRTApp::OnCharacterReceived); ref new TypedEventHandler<CoreWindow ^, CharacterReceivedEventArgs ^>(this, &SDL_WinRTApp::OnCharacterReceived);
#if NTDDI_VERSION >= NTDDI_WIN10 #if NTDDI_VERSION >= NTDDI_WIN10
Windows::UI::Core::SystemNavigationManager::GetForCurrentView()->BackRequested += Windows::UI::Core::SystemNavigationManager::GetForCurrentView()->BackRequested +=
ref new EventHandler<BackRequestedEventArgs^>(this, &SDL_WinRTApp::OnBackButtonPressed); ref new EventHandler<BackRequestedEventArgs ^>(this, &SDL_WinRTApp::OnBackButtonPressed);
#elif WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP #elif WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
HardwareButtons::BackPressed += HardwareButtons::BackPressed +=
ref new EventHandler<BackPressedEventArgs^>(this, &SDL_WinRTApp::OnBackButtonPressed); ref new EventHandler<BackPressedEventArgs ^>(this, &SDL_WinRTApp::OnBackButtonPressed);
#endif #endif
#if NTDDI_VERSION > NTDDI_WIN8 #if NTDDI_VERSION > NTDDI_WIN8
DisplayInformation::GetForCurrentView()->OrientationChanged += DisplayInformation::GetForCurrentView()->OrientationChanged +=
ref new TypedEventHandler<Windows::Graphics::Display::DisplayInformation^, Object^>(this, &SDL_WinRTApp::OnOrientationChanged); ref new TypedEventHandler<Windows::Graphics::Display::DisplayInformation ^, Object ^>(this, &SDL_WinRTApp::OnOrientationChanged);
#else #else
DisplayProperties::OrientationChanged += DisplayProperties::OrientationChanged +=
ref new DisplayPropertiesEventHandler(this, &SDL_WinRTApp::OnOrientationChanged); ref new DisplayPropertiesEventHandler(this, &SDL_WinRTApp::OnOrientationChanged);
@@ -335,12 +328,11 @@ void SDL_WinRTApp::SetWindow(CoreWindow^ window)
// to be done for network-enabled apps, as per Windows Store requirements. // to be done for network-enabled apps, as per Windows Store requirements.
using namespace Windows::UI::ApplicationSettings; using namespace Windows::UI::ApplicationSettings;
SettingsPane::GetForCurrentView()->CommandsRequested += SettingsPane::GetForCurrentView()->CommandsRequested +=
ref new TypedEventHandler<SettingsPane^, SettingsPaneCommandsRequestedEventArgs^> ref new TypedEventHandler<SettingsPane ^, SettingsPaneCommandsRequestedEventArgs ^>(this, &SDL_WinRTApp::OnSettingsPaneCommandsRequested);
(this, &SDL_WinRTApp::OnSettingsPaneCommandsRequested);
#endif #endif
} }
void SDL_WinRTApp::Load(Platform::String^ entryPoint) void SDL_WinRTApp::Load(Platform::String ^ entryPoint)
{ {
} }
@@ -366,7 +358,7 @@ void SDL_WinRTApp::Run()
static bool IsSDLWindowEventPending(SDL_WindowEventID windowEventID) static bool IsSDLWindowEventPending(SDL_WindowEventID windowEventID)
{ {
SDL_Event events[128]; SDL_Event events[128];
const int count = SDL_PeepEvents(events, sizeof(events)/sizeof(SDL_Event), SDL_PEEKEVENT, SDL_WINDOWEVENT, SDL_WINDOWEVENT); const int count = SDL_PeepEvents(events, sizeof(events) / sizeof(SDL_Event), SDL_PEEKEVENT, SDL_WINDOWEVENT, SDL_WINDOWEVENT);
for (int i = 0; i < count; ++i) { for (int i = 0; i < count; ++i) {
if (events[i].window.event == windowEventID) { if (events[i].window.event == windowEventID) {
return true; return true;
@@ -430,15 +422,15 @@ void SDL_WinRTApp::Uninitialize()
#if (WINAPI_FAMILY == WINAPI_FAMILY_APP) && (NTDDI_VERSION < NTDDI_WIN10) #if (WINAPI_FAMILY == WINAPI_FAMILY_APP) && (NTDDI_VERSION < NTDDI_WIN10)
void SDL_WinRTApp::OnSettingsPaneCommandsRequested( void SDL_WinRTApp::OnSettingsPaneCommandsRequested(
Windows::UI::ApplicationSettings::SettingsPane ^p, Windows::UI::ApplicationSettings::SettingsPane ^ p,
Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^args) Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^ args)
{ {
using namespace Platform; using namespace Platform;
using namespace Windows::UI::ApplicationSettings; using namespace Windows::UI::ApplicationSettings;
using namespace Windows::UI::Popups; using namespace Windows::UI::Popups;
String ^privacyPolicyURL = nullptr; // a URL to an app's Privacy Policy String ^ privacyPolicyURL = nullptr; // a URL to an app's Privacy Policy
String ^privacyPolicyLabel = nullptr; // label/link text String ^ privacyPolicyLabel = nullptr; // label/link text
const char *tmpHintValue = NULL; // SDL_GetHint-retrieved value, used immediately const char *tmpHintValue = NULL; // SDL_GetHint-retrieved value, used immediately
wchar_t *tmpStr = NULL; // used for UTF8 to UCS2 conversion wchar_t *tmpStr = NULL; // used for UTF8 to UCS2 conversion
@@ -472,9 +464,9 @@ void SDL_WinRTApp::OnSettingsPaneCommandsRequested(
} }
#endif // if (WINAPI_FAMILY == WINAPI_FAMILY_APP) && (NTDDI_VERSION < NTDDI_WIN10) #endif // if (WINAPI_FAMILY == WINAPI_FAMILY_APP) && (NTDDI_VERSION < NTDDI_WIN10)
void SDL_WinRTApp::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args) void SDL_WinRTApp::OnWindowSizeChanged(CoreWindow ^ sender, WindowSizeChangedEventArgs ^ args)
{ {
#if LOG_WINDOW_EVENTS==1 #if LOG_WINDOW_EVENTS == 1
SDL_Log("%s, size={%f,%f}, bounds={%f,%f,%f,%f}, current orientation=%d, native orientation=%d, auto rot. pref=%d, WINRT_GlobalSDLWindow?=%s\n", SDL_Log("%s, size={%f,%f}, bounds={%f,%f,%f,%f}, current orientation=%d, native orientation=%d, auto rot. pref=%d, WINRT_GlobalSDLWindow?=%s\n",
__FUNCTION__, __FUNCTION__,
args->Size.Width, args->Size.Height, args->Size.Width, args->Size.Height,
@@ -488,9 +480,9 @@ void SDL_WinRTApp::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEven
WINRT_ProcessWindowSizeChange(); WINRT_ProcessWindowSizeChange();
} }
void SDL_WinRTApp::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args) void SDL_WinRTApp::OnVisibilityChanged(CoreWindow ^ sender, VisibilityChangedEventArgs ^ args)
{ {
#if LOG_WINDOW_EVENTS==1 #if LOG_WINDOW_EVENTS == 1
SDL_Log("%s, visible?=%s, bounds={%f,%f,%f,%f}, WINRT_GlobalSDLWindow?=%s\n", SDL_Log("%s, visible?=%s, bounds={%f,%f,%f,%f}, WINRT_GlobalSDLWindow?=%s\n",
__FUNCTION__, __FUNCTION__,
(args->Visible ? "yes" : "no"), (args->Visible ? "yes" : "no"),
@@ -527,9 +519,9 @@ void SDL_WinRTApp::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEven
} }
} }
void SDL_WinRTApp::OnWindowActivated(CoreWindow^ sender, WindowActivatedEventArgs^ args) void SDL_WinRTApp::OnWindowActivated(CoreWindow ^ sender, WindowActivatedEventArgs ^ args)
{ {
#if LOG_WINDOW_EVENTS==1 #if LOG_WINDOW_EVENTS == 1
SDL_Log("%s, WINRT_GlobalSDLWindow?=%s\n\n", SDL_Log("%s, WINRT_GlobalSDLWindow?=%s\n\n",
__FUNCTION__, __FUNCTION__,
(WINRT_GlobalSDLWindow ? "yes" : "no")); (WINRT_GlobalSDLWindow ? "yes" : "no"));
@@ -542,7 +534,7 @@ void SDL_WinRTApp::OnWindowActivated(CoreWindow^ sender, WindowActivatedEventArg
*/ */
sender->CustomProperties->Insert("SDLHelperWindowActivationState", args->WindowActivationState); sender->CustomProperties->Insert("SDLHelperWindowActivationState", args->WindowActivationState);
SDL_Window * window = WINRT_GlobalSDLWindow; SDL_Window *window = WINRT_GlobalSDLWindow;
if (window) { if (window) {
if (args->WindowActivationState != CoreWindowActivationState::Deactivated) { if (args->WindowActivationState != CoreWindowActivationState::Deactivated) {
SDL_SendWindowEvent(window, SDL_WINDOWEVENT_SHOWN, 0, 0); SDL_SendWindowEvent(window, SDL_WINDOWEVENT_SHOWN, 0, 0);
@@ -565,13 +557,13 @@ void SDL_WinRTApp::OnWindowActivated(CoreWindow^ sender, WindowActivatedEventArg
#endif #endif
/* TODO, WinRT: see if the Win32 bugfix from https://hg.libsdl.org/SDL/rev/d278747da408 needs to be applied (on window activation) */ /* TODO, WinRT: see if the Win32 bugfix from https://hg.libsdl.org/SDL/rev/d278747da408 needs to be applied (on window activation) */
//WIN_CheckAsyncMouseRelease(data); // WIN_CheckAsyncMouseRelease(data);
/* TODO, WinRT: implement clipboard support, if possible */ /* TODO, WinRT: implement clipboard support, if possible */
///* ///*
// * FIXME: Update keyboard state // * FIXME: Update keyboard state
// */ // */
//WIN_CheckClipboardUpdate(data->videodata); // WIN_CheckClipboardUpdate(data->videodata);
// HACK: Resetting the mouse-cursor here seems to fix // HACK: Resetting the mouse-cursor here seems to fix
// https://bugzilla.libsdl.org/show_bug.cgi?id=3217, whereby a // https://bugzilla.libsdl.org/show_bug.cgi?id=3217, whereby a
@@ -589,20 +581,20 @@ void SDL_WinRTApp::OnWindowActivated(CoreWindow^ sender, WindowActivatedEventArg
} }
} }
void SDL_WinRTApp::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args) void SDL_WinRTApp::OnWindowClosed(CoreWindow ^ sender, CoreWindowEventArgs ^ args)
{ {
#if LOG_WINDOW_EVENTS==1 #if LOG_WINDOW_EVENTS == 1
SDL_Log("%s\n", __FUNCTION__); SDL_Log("%s\n", __FUNCTION__);
#endif #endif
m_windowClosed = true; m_windowClosed = true;
} }
void SDL_WinRTApp::OnAppActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args) void SDL_WinRTApp::OnAppActivated(CoreApplicationView ^ applicationView, IActivatedEventArgs ^ args)
{ {
CoreWindow::GetForCurrentThread()->Activate(); CoreWindow::GetForCurrentThread()->Activate();
} }
void SDL_WinRTApp::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args) void SDL_WinRTApp::OnSuspending(Platform::Object ^ sender, SuspendingEventArgs ^ args)
{ {
// Save app state asynchronously after requesting a deferral. Holding a deferral // Save app state asynchronously after requesting a deferral. Holding a deferral
// indicates that the application is busy performing suspending operations. Be // indicates that the application is busy performing suspending operations. Be
@@ -618,9 +610,8 @@ void SDL_WinRTApp::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ a
// this could be important. // this could be important.
SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND); SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral(); SuspendingDeferral ^ deferral = args->SuspendingOperation->GetDeferral();
create_task([this, deferral]() create_task([this, deferral]() {
{
// Send an app did-enter-background event immediately to observers. // Send an app did-enter-background event immediately to observers.
// CoreDispatcher::ProcessEvents, which is the backbone on which // CoreDispatcher::ProcessEvents, which is the backbone on which
// SDL_WinRTApp::PumpEvents is built, will not return to its caller // SDL_WinRTApp::PumpEvents is built, will not return to its caller
@@ -635,7 +626,7 @@ void SDL_WinRTApp::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ a
// More details at: http://msdn.microsoft.com/en-us/library/windows/apps/Hh994929.aspx // More details at: http://msdn.microsoft.com/en-us/library/windows/apps/Hh994929.aspx
#if SDL_VIDEO_RENDER_D3D11 && !SDL_RENDER_DISABLED #if SDL_VIDEO_RENDER_D3D11 && !SDL_RENDER_DISABLED
if (WINRT_GlobalSDLWindow) { if (WINRT_GlobalSDLWindow) {
SDL_Renderer * renderer = SDL_GetRenderer(WINRT_GlobalSDLWindow); SDL_Renderer *renderer = SDL_GetRenderer(WINRT_GlobalSDLWindow);
if (renderer && (SDL_strcmp(renderer->info.name, "direct3d11") == 0)) { if (renderer && (SDL_strcmp(renderer->info.name, "direct3d11") == 0)) {
D3D11_Trim(renderer); D3D11_Trim(renderer);
} }
@@ -646,7 +637,7 @@ void SDL_WinRTApp::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ a
}); });
} }
void SDL_WinRTApp::OnResuming(Platform::Object^ sender, Platform::Object^ args) void SDL_WinRTApp::OnResuming(Platform::Object ^ sender, Platform::Object ^ args)
{ {
// Restore any data or state that was unloaded on suspend. By default, data // Restore any data or state that was unloaded on suspend. By default, data
// and state are persisted when resuming from suspend. Note that these events // and state are persisted when resuming from suspend. Note that these events
@@ -655,13 +646,12 @@ void SDL_WinRTApp::OnResuming(Platform::Object^ sender, Platform::Object^ args)
SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND); SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
} }
void SDL_WinRTApp::OnExiting(Platform::Object^ sender, Platform::Object^ args) void SDL_WinRTApp::OnExiting(Platform::Object ^ sender, Platform::Object ^ args)
{ {
SDL_SendAppEvent(SDL_APP_TERMINATING); SDL_SendAppEvent(SDL_APP_TERMINATING);
} }
static void static void WINRT_LogPointerEvent(const char *header, Windows::UI::Core::PointerEventArgs ^ args, Windows::Foundation::Point transformedPoint)
WINRT_LogPointerEvent(const char * header, Windows::UI::Core::PointerEventArgs ^ args, Windows::Foundation::Point transformedPoint)
{ {
Uint8 button, pressed; Uint8 button, pressed;
Windows::UI::Input::PointerPoint ^ pt = args->CurrentPoint; Windows::UI::Input::PointerPoint ^ pt = args->CurrentPoint;
@@ -677,7 +667,7 @@ WINRT_LogPointerEvent(const char * header, Windows::UI::Core::PointerEventArgs ^
pressed); pressed);
} }
void SDL_WinRTApp::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args) void SDL_WinRTApp::OnPointerPressed(CoreWindow ^ sender, PointerEventArgs ^ args)
{ {
#if LOG_POINTER_EVENTS #if LOG_POINTER_EVENTS
WINRT_LogPointerEvent("pointer pressed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize)); WINRT_LogPointerEvent("pointer pressed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
@@ -686,7 +676,7 @@ void SDL_WinRTApp::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
WINRT_ProcessPointerPressedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint); WINRT_ProcessPointerPressedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
} }
void SDL_WinRTApp::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args) void SDL_WinRTApp::OnPointerMoved(CoreWindow ^ sender, PointerEventArgs ^ args)
{ {
#if LOG_POINTER_EVENTS #if LOG_POINTER_EVENTS
WINRT_LogPointerEvent("pointer moved", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize)); WINRT_LogPointerEvent("pointer moved", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
@@ -695,7 +685,7 @@ void SDL_WinRTApp::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
WINRT_ProcessPointerMovedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint); WINRT_ProcessPointerMovedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
} }
void SDL_WinRTApp::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args) void SDL_WinRTApp::OnPointerReleased(CoreWindow ^ sender, PointerEventArgs ^ args)
{ {
#if LOG_POINTER_EVENTS #if LOG_POINTER_EVENTS
WINRT_LogPointerEvent("pointer released", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize)); WINRT_LogPointerEvent("pointer released", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
@@ -704,7 +694,7 @@ void SDL_WinRTApp::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
WINRT_ProcessPointerReleasedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint); WINRT_ProcessPointerReleasedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
} }
void SDL_WinRTApp::OnPointerEntered(CoreWindow^ sender, PointerEventArgs^ args) void SDL_WinRTApp::OnPointerEntered(CoreWindow ^ sender, PointerEventArgs ^ args)
{ {
#if LOG_POINTER_EVENTS #if LOG_POINTER_EVENTS
WINRT_LogPointerEvent("pointer entered", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize)); WINRT_LogPointerEvent("pointer entered", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
@@ -713,7 +703,7 @@ void SDL_WinRTApp::OnPointerEntered(CoreWindow^ sender, PointerEventArgs^ args)
WINRT_ProcessPointerEnteredEvent(WINRT_GlobalSDLWindow, args->CurrentPoint); WINRT_ProcessPointerEnteredEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
} }
void SDL_WinRTApp::OnPointerExited(CoreWindow^ sender, PointerEventArgs^ args) void SDL_WinRTApp::OnPointerExited(CoreWindow ^ sender, PointerEventArgs ^ args)
{ {
#if LOG_POINTER_EVENTS #if LOG_POINTER_EVENTS
WINRT_LogPointerEvent("pointer exited", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize)); WINRT_LogPointerEvent("pointer exited", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
@@ -722,7 +712,7 @@ void SDL_WinRTApp::OnPointerExited(CoreWindow^ sender, PointerEventArgs^ args)
WINRT_ProcessPointerExitedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint); WINRT_ProcessPointerExitedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
} }
void SDL_WinRTApp::OnPointerWheelChanged(CoreWindow^ sender, PointerEventArgs^ args) void SDL_WinRTApp::OnPointerWheelChanged(CoreWindow ^ sender, PointerEventArgs ^ args)
{ {
#if LOG_POINTER_EVENTS #if LOG_POINTER_EVENTS
WINRT_LogPointerEvent("pointer wheel changed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize)); WINRT_LogPointerEvent("pointer wheel changed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
@@ -731,22 +721,22 @@ void SDL_WinRTApp::OnPointerWheelChanged(CoreWindow^ sender, PointerEventArgs^ a
WINRT_ProcessPointerWheelChangedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint); WINRT_ProcessPointerWheelChangedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
} }
void SDL_WinRTApp::OnMouseMoved(MouseDevice^ mouseDevice, MouseEventArgs^ args) void SDL_WinRTApp::OnMouseMoved(MouseDevice ^ mouseDevice, MouseEventArgs ^ args)
{ {
WINRT_ProcessMouseMovedEvent(WINRT_GlobalSDLWindow, args); WINRT_ProcessMouseMovedEvent(WINRT_GlobalSDLWindow, args);
} }
void SDL_WinRTApp::OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args) void SDL_WinRTApp::OnKeyDown(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::KeyEventArgs ^ args)
{ {
WINRT_ProcessKeyDownEvent(args); WINRT_ProcessKeyDownEvent(args);
} }
void SDL_WinRTApp::OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args) void SDL_WinRTApp::OnKeyUp(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::KeyEventArgs ^ args)
{ {
WINRT_ProcessKeyUpEvent(args); WINRT_ProcessKeyUpEvent(args);
} }
void SDL_WinRTApp::OnCharacterReceived(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CharacterReceivedEventArgs^ args) void SDL_WinRTApp::OnCharacterReceived(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::CharacterReceivedEventArgs ^ args)
{ {
WINRT_ProcessCharacterReceivedEvent(args); WINRT_ProcessCharacterReceivedEvent(args);
} }
@@ -763,13 +753,13 @@ static void WINRT_OnBackButtonPressed(BackButtonEventArgs ^ args)
} }
#if NTDDI_VERSION >= NTDDI_WIN10 #if NTDDI_VERSION >= NTDDI_WIN10
void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::UI::Core::BackRequestedEventArgs^ args) void SDL_WinRTApp::OnBackButtonPressed(Platform::Object ^ sender, Windows::UI::Core::BackRequestedEventArgs ^ args)
{ {
WINRT_OnBackButtonPressed(args); WINRT_OnBackButtonPressed(args);
} }
#elif WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP #elif WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args) void SDL_WinRTApp::OnBackButtonPressed(Platform::Object ^ sender, Windows::Phone::UI::Input::BackPressedEventArgs ^ args)
{ {
WINRT_OnBackButtonPressed(args); WINRT_OnBackButtonPressed(args);
@@ -777,7 +767,7 @@ void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::Phone:
#endif #endif
#if NTDDI_VERSION >= NTDDI_WIN10 #if NTDDI_VERSION >= NTDDI_WIN10
void SDL_WinRTApp::OnGamepadAdded(Platform::Object ^sender, Windows::Gaming::Input::Gamepad ^gamepad) void SDL_WinRTApp::OnGamepadAdded(Platform::Object ^ sender, Windows::Gaming::Input::Gamepad ^ gamepad)
{ {
/* HACK ALERT: Nothing needs to be done here, as this method currently /* HACK ALERT: Nothing needs to be done here, as this method currently
only exists to allow something to be registered with Win10's only exists to allow something to be registered with Win10's

View File

@@ -24,67 +24,68 @@ extern int SDL_WinRTInitNonXAMLApp(int (*mainFunction)(int, char **));
ref class SDL_WinRTApp sealed : public Windows::ApplicationModel::Core::IFrameworkView ref class SDL_WinRTApp sealed : public Windows::ApplicationModel::Core::IFrameworkView
{ {
public: public:
SDL_WinRTApp(); SDL_WinRTApp();
// IFrameworkView Methods. // IFrameworkView Methods.
virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView); virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView ^ applicationView);
virtual void SetWindow(Windows::UI::Core::CoreWindow^ window); virtual void SetWindow(Windows::UI::Core::CoreWindow ^ window);
virtual void Load(Platform::String^ entryPoint); virtual void Load(Platform::String ^ entryPoint);
virtual void Run(); virtual void Run();
virtual void Uninitialize(); virtual void Uninitialize();
internal: internal :
// SDL-specific methods // SDL-specific methods
void PumpEvents(); void
PumpEvents();
protected: protected:
bool ShouldWaitForAppResumeEvents(); bool ShouldWaitForAppResumeEvents();
// Event Handlers. // Event Handlers.
#if (WINAPI_FAMILY == WINAPI_FAMILY_APP) && (NTDDI_VERSION < NTDDI_WIN10) // for Windows 8/8.1/RT apps... (and not Phone apps) #if (WINAPI_FAMILY == WINAPI_FAMILY_APP) && (NTDDI_VERSION < NTDDI_WIN10) // for Windows 8/8.1/RT apps... (and not Phone apps)
void OnSettingsPaneCommandsRequested( void OnSettingsPaneCommandsRequested(
Windows::UI::ApplicationSettings::SettingsPane ^p, Windows::UI::ApplicationSettings::SettingsPane ^ p,
Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^args); Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^ args);
#endif // if (WINAPI_FAMILY == WINAPI_FAMILY_APP) && (NTDDI_VERSION < NTDDI_WIN10) #endif // if (WINAPI_FAMILY == WINAPI_FAMILY_APP) && (NTDDI_VERSION < NTDDI_WIN10)
#if NTDDI_VERSION > NTDDI_WIN8 #if NTDDI_VERSION > NTDDI_WIN8
void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation ^ sender, Platform::Object ^ args);
#else #else
void OnOrientationChanged(Platform::Object^ sender); void OnOrientationChanged(Platform::Object ^ sender);
#endif #endif
void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args); void OnWindowSizeChanged(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::WindowSizeChangedEventArgs ^ args);
void OnLogicalDpiChanged(Platform::Object^ sender); void OnLogicalDpiChanged(Platform::Object ^ sender);
void OnAppActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args); void OnAppActivated(Windows::ApplicationModel::Core::CoreApplicationView ^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs ^ args);
void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args); void OnSuspending(Platform::Object ^ sender, Windows::ApplicationModel::SuspendingEventArgs ^ args);
void OnResuming(Platform::Object^ sender, Platform::Object^ args); void OnResuming(Platform::Object ^ sender, Platform::Object ^ args);
void OnExiting(Platform::Object^ sender, Platform::Object^ args); void OnExiting(Platform::Object ^ sender, Platform::Object ^ args);
void OnWindowActivated(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowActivatedEventArgs^ args); void OnWindowActivated(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::WindowActivatedEventArgs ^ args);
void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args); void OnWindowClosed(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::CoreWindowEventArgs ^ args);
void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args); void OnVisibilityChanged(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::VisibilityChangedEventArgs ^ args);
void OnPointerPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerPressed(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args);
void OnPointerReleased(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerReleased(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args);
void OnPointerWheelChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerWheelChanged(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args);
void OnPointerMoved(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerMoved(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args);
void OnPointerEntered(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerEntered(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args);
void OnPointerExited(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args); void OnPointerExited(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args);
void OnMouseMoved(Windows::Devices::Input::MouseDevice^ mouseDevice, Windows::Devices::Input::MouseEventArgs^ args); void OnMouseMoved(Windows::Devices::Input::MouseDevice ^ mouseDevice, Windows::Devices::Input::MouseEventArgs ^ args);
void OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args); void OnKeyDown(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::KeyEventArgs ^ args);
void OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args); void OnKeyUp(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::KeyEventArgs ^ args);
void OnCharacterReceived(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CharacterReceivedEventArgs^ args); void OnCharacterReceived(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::CharacterReceivedEventArgs ^ args);
#if NTDDI_VERSION >= NTDDI_WIN10 #if NTDDI_VERSION >= NTDDI_WIN10
void OnBackButtonPressed(Platform::Object^ sender, Windows::UI::Core::BackRequestedEventArgs^ args); void OnBackButtonPressed(Platform::Object ^ sender, Windows::UI::Core::BackRequestedEventArgs ^ args);
#elif WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP #elif WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
void OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args); void OnBackButtonPressed(Platform::Object ^ sender, Windows::Phone::UI::Input::BackPressedEventArgs ^ args);
#endif #endif
#if NTDDI_VERSION >= NTDDI_WIN10 #if NTDDI_VERSION >= NTDDI_WIN10
void OnGamepadAdded(Platform::Object ^sender, Windows::Gaming::Input::Gamepad ^gamepad); void OnGamepadAdded(Platform::Object ^ sender, Windows::Gaming::Input::Gamepad ^ gamepad);
#endif #endif
private: private:
bool m_windowClosed; bool m_windowClosed;
bool m_windowVisible; bool m_windowVisible;
}; };

View File

@@ -28,77 +28,64 @@
#include <windows.ui.xaml.media.dxinterop.h> #include <windows.ui.xaml.media.dxinterop.h>
#endif #endif
/* SDL includes */ /* SDL includes */
#include "../../video/winrt/SDL_winrtevents_c.h" #include "../../video/winrt/SDL_winrtevents_c.h"
#include "../../video/winrt/SDL_winrtvideo_cpp.h" #include "../../video/winrt/SDL_winrtvideo_cpp.h"
#include "SDL_winrtapp_common.h" #include "SDL_winrtapp_common.h"
#include "SDL_winrtapp_xaml.h" #include "SDL_winrtapp_xaml.h"
/* SDL-internal globals: */ /* SDL-internal globals: */
SDL_bool WINRT_XAMLWasEnabled = SDL_FALSE; SDL_bool WINRT_XAMLWasEnabled = SDL_FALSE;
#if WINAPI_FAMILY == WINAPI_FAMILY_APP #if WINAPI_FAMILY == WINAPI_FAMILY_APP
extern "C" extern "C" ISwapChainBackgroundPanelNative *WINRT_GlobalSwapChainBackgroundPanelNative = NULL;
ISwapChainBackgroundPanelNative * WINRT_GlobalSwapChainBackgroundPanelNative = NULL;
static Windows::Foundation::EventRegistrationToken WINRT_XAMLAppEventToken; static Windows::Foundation::EventRegistrationToken WINRT_XAMLAppEventToken;
#endif #endif
/* /*
* Input event handlers (XAML) * Input event handlers (XAML)
*/ */
#if WINAPI_FAMILY == WINAPI_FAMILY_APP #if WINAPI_FAMILY == WINAPI_FAMILY_APP
static void static void WINRT_OnPointerPressedViaXAML(Platform::Object ^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs ^ args)
WINRT_OnPointerPressedViaXAML(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args)
{ {
WINRT_ProcessPointerPressedEvent(WINRT_GlobalSDLWindow, args->GetCurrentPoint(nullptr)); WINRT_ProcessPointerPressedEvent(WINRT_GlobalSDLWindow, args->GetCurrentPoint(nullptr));
} }
static void static void WINRT_OnPointerMovedViaXAML(Platform::Object ^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs ^ args)
WINRT_OnPointerMovedViaXAML(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args)
{ {
WINRT_ProcessPointerMovedEvent(WINRT_GlobalSDLWindow, args->GetCurrentPoint(nullptr)); WINRT_ProcessPointerMovedEvent(WINRT_GlobalSDLWindow, args->GetCurrentPoint(nullptr));
} }
static void static void WINRT_OnPointerReleasedViaXAML(Platform::Object ^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs ^ args)
WINRT_OnPointerReleasedViaXAML(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args)
{ {
WINRT_ProcessPointerReleasedEvent(WINRT_GlobalSDLWindow, args->GetCurrentPoint(nullptr)); WINRT_ProcessPointerReleasedEvent(WINRT_GlobalSDLWindow, args->GetCurrentPoint(nullptr));
} }
static void static void WINRT_OnPointerWheelChangedViaXAML(Platform::Object ^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs ^ args)
WINRT_OnPointerWheelChangedViaXAML(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args)
{ {
WINRT_ProcessPointerWheelChangedEvent(WINRT_GlobalSDLWindow, args->GetCurrentPoint(nullptr)); WINRT_ProcessPointerWheelChangedEvent(WINRT_GlobalSDLWindow, args->GetCurrentPoint(nullptr));
} }
#endif // WINAPI_FAMILY == WINAPI_FAMILY_APP #endif // WINAPI_FAMILY == WINAPI_FAMILY_APP
/* /*
* XAML-to-SDL Rendering Callback * XAML-to-SDL Rendering Callback
*/ */
#if WINAPI_FAMILY == WINAPI_FAMILY_APP #if WINAPI_FAMILY == WINAPI_FAMILY_APP
static void static void WINRT_OnRenderViaXAML(_In_ Platform::Object ^ sender, _In_ Platform::Object ^ args)
WINRT_OnRenderViaXAML(_In_ Platform::Object^ sender, _In_ Platform::Object^ args)
{ {
WINRT_CycleXAMLThread(); WINRT_CycleXAMLThread();
} }
#endif // WINAPI_FAMILY == WINAPI_FAMILY_APP #endif // WINAPI_FAMILY == WINAPI_FAMILY_APP
/* /*
* SDL + XAML Initialization * SDL + XAML Initialization
*/ */
int int SDL_WinRTInitXAMLApp(int (*mainFunction)(int, char **), void *backgroundPanelAsIInspectable)
SDL_WinRTInitXAMLApp(int (*mainFunction)(int, char **), void * backgroundPanelAsIInspectable)
{ {
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
return SDL_SetError("XAML support is not yet available in Windows Phone."); return SDL_SetError("XAML support is not yet available in Windows Phone.");
@@ -113,13 +100,13 @@ SDL_WinRTInitXAMLApp(int (*mainFunction)(int, char **), void * backgroundPanelAs
using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Media;
// Make sure we have a valid XAML element (to draw onto): // Make sure we have a valid XAML element (to draw onto):
if ( ! backgroundPanelAsIInspectable) { if (!backgroundPanelAsIInspectable) {
return SDL_InvalidParamError("backgroundPanelAsIInspectable"); return SDL_InvalidParamError("backgroundPanelAsIInspectable");
} }
Platform::Object ^ backgroundPanel = reinterpret_cast<Object ^>((IInspectable *) backgroundPanelAsIInspectable); Platform::Object ^ backgroundPanel = reinterpret_cast<Object ^>((IInspectable *)backgroundPanelAsIInspectable);
SwapChainBackgroundPanel ^swapChainBackgroundPanel = dynamic_cast<SwapChainBackgroundPanel ^>(backgroundPanel); SwapChainBackgroundPanel ^ swapChainBackgroundPanel = dynamic_cast<SwapChainBackgroundPanel ^>(backgroundPanel);
if ( ! swapChainBackgroundPanel) { if (!swapChainBackgroundPanel) {
return SDL_SetError("An unknown or unsupported type of XAML control was specified."); return SDL_SetError("An unknown or unsupported type of XAML control was specified.");
} }
@@ -130,10 +117,10 @@ SDL_WinRTInitXAMLApp(int (*mainFunction)(int, char **), void * backgroundPanelAs
swapChainBackgroundPanel->PointerMoved += ref new PointerEventHandler(WINRT_OnPointerMovedViaXAML); swapChainBackgroundPanel->PointerMoved += ref new PointerEventHandler(WINRT_OnPointerMovedViaXAML);
// Setup for rendering: // Setup for rendering:
IInspectable *panelInspectable = (IInspectable*) reinterpret_cast<IInspectable*>(swapChainBackgroundPanel); IInspectable *panelInspectable = (IInspectable *)reinterpret_cast<IInspectable *>(swapChainBackgroundPanel);
panelInspectable->QueryInterface(__uuidof(ISwapChainBackgroundPanelNative), (void **)&WINRT_GlobalSwapChainBackgroundPanelNative); panelInspectable->QueryInterface(__uuidof(ISwapChainBackgroundPanelNative), (void **)&WINRT_GlobalSwapChainBackgroundPanelNative);
WINRT_XAMLAppEventToken = CompositionTarget::Rendering::add(ref new EventHandler<Object^>(WINRT_OnRenderViaXAML)); WINRT_XAMLAppEventToken = CompositionTarget::Rendering::add(ref new EventHandler<Object ^>(WINRT_OnRenderViaXAML));
// Make sure the app is ready to call the SDL-centric main() function: // Make sure the app is ready to call the SDL-centric main() function:
WINRT_SDLAppEntryPoint = mainFunction; WINRT_SDLAppEntryPoint = mainFunction;

View File

@@ -23,10 +23,9 @@
#ifndef SDL_winrtapp_xaml_h_ #ifndef SDL_winrtapp_xaml_h_
#define SDL_winrtapp_xaml_h_ #define SDL_winrtapp_xaml_h_
#ifdef __cplusplus #ifdef __cplusplus
extern SDL_bool WINRT_XAMLWasEnabled; extern SDL_bool WINRT_XAMLWasEnabled;
extern int SDL_WinRTInitXAMLApp(int (*mainFunction)(int, char **), void * backgroundPanelAsIInspectable); extern int SDL_WinRTInitXAMLApp(int (*mainFunction)(int, char **), void *backgroundPanelAsIInspectable);
#endif // ifdef __cplusplus #endif // ifdef __cplusplus
#endif // SDL_winrtapp_xaml_h_ #endif // SDL_winrtapp_xaml_h_

View File

@@ -26,7 +26,6 @@
/* CPU feature detection for SDL */ /* CPU feature detection for SDL */
#ifdef HAVE_SYSCONF #ifdef HAVE_SYSCONF
#include <unistd.h> #include <unistd.h>
#endif #endif
@@ -110,15 +109,13 @@
the idea is borrowed from the libmpeg2 library - thanks! the idea is borrowed from the libmpeg2 library - thanks!
*/ */
static jmp_buf jmpbuf; static jmp_buf jmpbuf;
static void static void illegal_instruction(int sig)
illegal_instruction(int sig)
{ {
longjmp(jmpbuf, 1); longjmp(jmpbuf, 1);
} }
#endif /* HAVE_SETJMP */ #endif /* HAVE_SETJMP */
static int static int CPU_haveCPUID(void)
CPU_haveCPUID(void)
{ {
int has_CPUID = 0; int has_CPUID = 0;
@@ -217,22 +214,24 @@ done:
#if (defined(__GNUC__) || defined(__llvm__)) && defined(__i386__) #if (defined(__GNUC__) || defined(__llvm__)) && defined(__i386__)
#define cpuid(func, a, b, c, d) \ #define cpuid(func, a, b, c, d) \
__asm__ __volatile__ ( \ __asm__ __volatile__( \
" pushl %%ebx \n" \ " pushl %%ebx \n" \
" xorl %%ecx,%%ecx \n" \ " xorl %%ecx,%%ecx \n" \
" cpuid \n" \ " cpuid \n" \
" movl %%ebx, %%esi \n" \ " movl %%ebx, %%esi \n" \
" popl %%ebx \n" : \ " popl %%ebx \n" \
"=a" (a), "=S" (b), "=c" (c), "=d" (d) : "a" (func)) : "=a"(a), "=S"(b), "=c"(c), "=d"(d) \
: "a"(func))
#elif (defined(__GNUC__) || defined(__llvm__)) && defined(__x86_64__) #elif (defined(__GNUC__) || defined(__llvm__)) && defined(__x86_64__)
#define cpuid(func, a, b, c, d) \ #define cpuid(func, a, b, c, d) \
__asm__ __volatile__ ( \ __asm__ __volatile__( \
" pushq %%rbx \n" \ " pushq %%rbx \n" \
" xorq %%rcx,%%rcx \n" \ " xorq %%rcx,%%rcx \n" \
" cpuid \n" \ " cpuid \n" \
" movq %%rbx, %%rsi \n" \ " movq %%rbx, %%rsi \n" \
" popq %%rbx \n" : \ " popq %%rbx \n" \
"=a" (a), "=S" (b), "=c" (c), "=d" (d) : "a" (func)) : "=a"(a), "=S"(b), "=c"(c), "=d"(d) \
: "a"(func))
#elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__) #elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
#define cpuid(func, a, b, c, d) \ #define cpuid(func, a, b, c, d) \
__asm { \ __asm { \
@@ -243,20 +242,26 @@ done:
__asm mov b, ebx \ __asm mov b, ebx \
__asm mov c, ecx \ __asm mov c, ecx \
__asm mov d, edx \ __asm mov d, edx \
} }
#elif defined(_MSC_VER) && defined(_M_X64) #elif defined(_MSC_VER) && defined(_M_X64)
#define cpuid(func, a, b, c, d) \ #define cpuid(func, a, b, c, d) \
{ \ { \
int CPUInfo[4]; \ int CPUInfo[4]; \
__cpuid(CPUInfo, func); \ __cpuid(CPUInfo, func); \
a = CPUInfo[0]; \ a = CPUInfo[0]; \
b = CPUInfo[1]; \ b = CPUInfo[1]; \
c = CPUInfo[2]; \ c = CPUInfo[2]; \
d = CPUInfo[3]; \ d = CPUInfo[3]; \
} }
#else #else
#define cpuid(func, a, b, c, d) \ #define cpuid(func, a, b, c, d) \
do { a = b = c = d = 0; (void) a; (void) b; (void) c; (void) d; } while (0) do { \
a = b = c = d = 0; \
(void)a; \
(void)b; \
(void)c; \
(void)d; \
} while (0)
#endif #endif
static int CPU_CPUIDFeatures[4]; static int CPU_CPUIDFeatures[4];
@@ -264,8 +269,7 @@ static int CPU_CPUIDMaxFunction = 0;
static SDL_bool CPU_OSSavesYMM = SDL_FALSE; static SDL_bool CPU_OSSavesYMM = SDL_FALSE;
static SDL_bool CPU_OSSavesZMM = SDL_FALSE; static SDL_bool CPU_OSSavesZMM = SDL_FALSE;
static void static void CPU_calcCPUIDFeatures(void)
CPU_calcCPUIDFeatures(void)
{ {
static SDL_bool checked = SDL_FALSE; static SDL_bool checked = SDL_FALSE;
if (!checked) { if (!checked) {
@@ -285,7 +289,10 @@ CPU_calcCPUIDFeatures(void)
if (c & 0x08000000) { if (c & 0x08000000) {
/* Call xgetbv to see if YMM (etc) register state is saved */ /* Call xgetbv to see if YMM (etc) register state is saved */
#if (defined(__GNUC__) || defined(__llvm__)) && (defined(__i386__) || defined(__x86_64__)) #if (defined(__GNUC__) || defined(__llvm__)) && (defined(__i386__) || defined(__x86_64__))
__asm__(".byte 0x0f, 0x01, 0xd0" : "=a" (a) : "c" (0) : "%edx"); __asm__(".byte 0x0f, 0x01, 0xd0"
: "=a"(a)
: "c"(0)
: "%edx");
#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) && (_MSC_FULL_VER >= 160040219) /* VS2010 SP1 */ #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) && (_MSC_FULL_VER >= 160040219) /* VS2010 SP1 */
a = (int)_xgetbv(0); a = (int)_xgetbv(0);
#elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__) #elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
@@ -304,8 +311,7 @@ CPU_calcCPUIDFeatures(void)
} }
} }
static int static int CPU_haveAltiVec(void)
CPU_haveAltiVec(void)
{ {
volatile int altivec = 0; volatile int altivec = 0;
#ifndef SDL_CPUINFO_DISABLED #ifndef SDL_CPUINFO_DISABLED
@@ -327,10 +333,11 @@ CPU_haveAltiVec(void)
altivec = cpufeatures & PPC_FEATURE_HAS_ALTIVEC; altivec = cpufeatures & PPC_FEATURE_HAS_ALTIVEC;
return altivec; return altivec;
#elif SDL_ALTIVEC_BLITTERS && HAVE_SETJMP #elif SDL_ALTIVEC_BLITTERS && HAVE_SETJMP
void (*handler) (int sig); void (*handler)(int sig);
handler = signal(SIGILL, illegal_instruction); handler = signal(SIGILL, illegal_instruction);
if (setjmp(jmpbuf) == 0) { if (setjmp(jmpbuf) == 0) {
asm volatile ("mtspr 256, %0\n\t" "vand %%v0, %%v0, %%v0"::"r" (-1)); asm volatile("mtspr 256, %0\n\t"
"vand %%v0, %%v0, %%v0" ::"r"(-1));
altivec = 1; altivec = 1;
} }
signal(SIGILL, handler); signal(SIGILL, handler);
@@ -340,22 +347,19 @@ CPU_haveAltiVec(void)
} }
#if (defined(__ARM_ARCH) && (__ARM_ARCH >= 6)) || defined(__aarch64__) #if (defined(__ARM_ARCH) && (__ARM_ARCH >= 6)) || defined(__aarch64__)
static int static int CPU_haveARMSIMD(void)
CPU_haveARMSIMD(void)
{ {
return 1; return 1;
} }
#elif !defined(__arm__) #elif !defined(__arm__)
static int static int CPU_haveARMSIMD(void)
CPU_haveARMSIMD(void)
{ {
return 0; return 0;
} }
#elif defined(__LINUX__) #elif defined(__LINUX__)
static int static int CPU_haveARMSIMD(void)
CPU_haveARMSIMD(void)
{ {
int arm_simd = 0; int arm_simd = 0;
int fd; int fd;
@@ -365,7 +369,7 @@ CPU_haveARMSIMD(void)
Elf32_auxv_t aux; Elf32_auxv_t aux;
while (read(fd, &aux, sizeof aux) == sizeof aux) { while (read(fd, &aux, sizeof aux) == sizeof aux) {
if (aux.a_type == AT_PLATFORM) { if (aux.a_type == AT_PLATFORM) {
const char *plat = (const char *) aux.a_un.a_val; const char *plat = (const char *)aux.a_un.a_val;
if (plat) { if (plat) {
arm_simd = SDL_strncmp(plat, "v6l", 3) == 0 || arm_simd = SDL_strncmp(plat, "v6l", 3) == 0 ||
SDL_strncmp(plat, "v7l", 3) == 0; SDL_strncmp(plat, "v7l", 3) == 0;
@@ -378,8 +382,7 @@ CPU_haveARMSIMD(void)
} }
#elif defined(__RISCOS__) #elif defined(__RISCOS__)
static int static int CPU_haveARMSIMD(void)
CPU_haveARMSIMD(void)
{ {
_kernel_swi_regs regs; _kernel_swi_regs regs;
regs.r[0] = 0; regs.r[0] = 0;
@@ -401,8 +404,7 @@ CPU_haveARMSIMD(void)
} }
#else #else
static int static int CPU_haveARMSIMD(void)
CPU_haveARMSIMD(void)
{ {
#warning SDL_HasARMSIMD is not implemented for this ARM platform. Write me. #warning SDL_HasARMSIMD is not implemented for this ARM platform. Write me.
return 0; return 0;
@@ -410,8 +412,7 @@ CPU_haveARMSIMD(void)
#endif #endif
#if defined(__LINUX__) && defined(__arm__) && !defined(HAVE_GETAUXVAL) #if defined(__LINUX__) && defined(__arm__) && !defined(HAVE_GETAUXVAL)
static int static int readProcAuxvForNeon(void)
readProcAuxvForNeon(void)
{ {
int neon = 0; int neon = 0;
int fd; int fd;
@@ -419,7 +420,7 @@ readProcAuxvForNeon(void)
fd = open("/proc/self/auxv", O_RDONLY | O_CLOEXEC); fd = open("/proc/self/auxv", O_RDONLY | O_CLOEXEC);
if (fd >= 0) { if (fd >= 0) {
Elf32_auxv_t aux; Elf32_auxv_t aux;
while (read(fd, &aux, sizeof (aux)) == sizeof (aux)) { while (read(fd, &aux, sizeof(aux)) == sizeof(aux)) {
if (aux.a_type == AT_HWCAP) { if (aux.a_type == AT_HWCAP) {
neon = (aux.a_un.a_val & HWCAP_NEON) == HWCAP_NEON; neon = (aux.a_un.a_val & HWCAP_NEON) == HWCAP_NEON;
break; break;
@@ -431,8 +432,7 @@ readProcAuxvForNeon(void)
} }
#endif #endif
static int static int CPU_haveNEON(void)
CPU_haveNEON(void)
{ {
/* The way you detect NEON is a privileged instruction on ARM, so you have /* The way you detect NEON is a privileged instruction on ARM, so you have
query the OS kernel in a platform-specific way. :/ */ query the OS kernel in a platform-specific way. :/ */
@@ -441,10 +441,10 @@ CPU_haveNEON(void)
#elif (defined(__WINDOWS__) || defined(__WINRT__) || defined(__GDK__)) && (defined(_M_ARM) || defined(_M_ARM64)) #elif (defined(__WINDOWS__) || defined(__WINRT__) || defined(__GDK__)) && (defined(_M_ARM) || defined(_M_ARM64))
/* Visual Studio, for ARM, doesn't define __ARM_ARCH. Handle this first. */ /* Visual Studio, for ARM, doesn't define __ARM_ARCH. Handle this first. */
/* Seems to have been removed */ /* Seems to have been removed */
# if !defined(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) #if !defined(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE)
# define PF_ARM_NEON_INSTRUCTIONS_AVAILABLE 19 #define PF_ARM_NEON_INSTRUCTIONS_AVAILABLE 19
# endif #endif
/* All WinRT ARM devices are required to support NEON, but just in case. */ /* All WinRT ARM devices are required to support NEON, but just in case. */
return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) != 0; return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) != 0;
#elif (defined(__ARM_ARCH) && (__ARM_ARCH >= 8)) || defined(__aarch64__) #elif (defined(__ARM_ARCH) && (__ARM_ARCH >= 8)) || defined(__aarch64__)
return 1; /* ARMv8 always has non-optional NEON support. */ return 1; /* ARMv8 always has non-optional NEON support. */
@@ -501,16 +501,14 @@ CPU_haveNEON(void)
#endif #endif
} }
static int static int CPU_readCPUCFG(void)
CPU_readCPUCFG(void)
{ {
uint32_t cfg2 = 0; uint32_t cfg2 = 0;
#if defined __loongarch__ #if defined __loongarch__
__asm__ volatile( __asm__ volatile(
"cpucfg %0, %1 \n\t" "cpucfg %0, %1 \n\t"
: "+&r"(cfg2) : "+&r"(cfg2)
: "r"(CPU_CFG2) : "r"(CPU_CFG2));
);
#endif #endif
return cfg2; return cfg2;
} }
@@ -529,8 +527,7 @@ CPU_have3DNow(void)
#endif #endif
} }
#else #else
static int static int CPU_have3DNow(void)
CPU_have3DNow(void)
{ {
if (CPU_CPUIDMaxFunction > 0) { /* that is, do we have CPUID at all? */ if (CPU_CPUIDMaxFunction > 0) { /* that is, do we have CPUID at all? */
int a, b, c, d; int a, b, c, d;
@@ -603,12 +600,14 @@ CPU_haveAVX2(void)
#endif #endif
} }
#else #else
static int static int CPU_haveAVX2(void)
CPU_haveAVX2(void)
{ {
if (CPU_OSSavesYMM && (CPU_CPUIDMaxFunction >= 7)) { if (CPU_OSSavesYMM && (CPU_CPUIDMaxFunction >= 7)) {
int a, b, c, d; int a, b, c, d;
(void) a; (void) b; (void) c; (void) d; /* compiler warnings... */ (void)a;
(void)b;
(void)c;
(void)d; /* compiler warnings... */
cpuid(7, a, b, c, d); cpuid(7, a, b, c, d);
return b & 0x00000020; return b & 0x00000020;
} }
@@ -623,12 +622,14 @@ CPU_haveAVX512F(void)
return 0; return 0;
} }
#else #else
static int static int CPU_haveAVX512F(void)
CPU_haveAVX512F(void)
{ {
if (CPU_OSSavesZMM && (CPU_CPUIDMaxFunction >= 7)) { if (CPU_OSSavesZMM && (CPU_CPUIDMaxFunction >= 7)) {
int a, b, c, d; int a, b, c, d;
(void) a; (void) b; (void) c; (void) d; /* compiler warnings... */ (void)a;
(void)b;
(void)c;
(void)d; /* compiler warnings... */
cpuid(7, a, b, c, d); cpuid(7, a, b, c, d);
return b & 0x00010000; return b & 0x00010000;
} }
@@ -638,8 +639,7 @@ CPU_haveAVX512F(void)
static int SDL_CPUCount = 0; static int SDL_CPUCount = 0;
int int SDL_GetCPUCount(void)
SDL_GetCPUCount(void)
{ {
if (!SDL_CPUCount) { if (!SDL_CPUCount) {
#ifndef SDL_CPUINFO_DISABLED #ifndef SDL_CPUINFO_DISABLED
@@ -682,8 +682,7 @@ SDL_GetCPUType(void)
} }
#else #else
/* Oh, such a sweet sweet trick, just not very useful. :) */ /* Oh, such a sweet sweet trick, just not very useful. :) */
static const char * static const char *SDL_GetCPUType(void)
SDL_GetCPUType(void)
{ {
static char SDL_CPUType[13]; static char SDL_CPUType[13];
@@ -694,20 +693,29 @@ SDL_GetCPUType(void)
if (CPU_CPUIDMaxFunction > 0) { /* do we have CPUID at all? */ if (CPU_CPUIDMaxFunction > 0) { /* do we have CPUID at all? */
int a, b, c, d; int a, b, c, d;
cpuid(0x00000000, a, b, c, d); cpuid(0x00000000, a, b, c, d);
(void) a; (void)a;
SDL_CPUType[i++] = (char)(b & 0xff); b >>= 8; SDL_CPUType[i++] = (char)(b & 0xff);
SDL_CPUType[i++] = (char)(b & 0xff); b >>= 8; b >>= 8;
SDL_CPUType[i++] = (char)(b & 0xff); b >>= 8; SDL_CPUType[i++] = (char)(b & 0xff);
b >>= 8;
SDL_CPUType[i++] = (char)(b & 0xff);
b >>= 8;
SDL_CPUType[i++] = (char)(b & 0xff); SDL_CPUType[i++] = (char)(b & 0xff);
SDL_CPUType[i++] = (char)(d & 0xff); d >>= 8; SDL_CPUType[i++] = (char)(d & 0xff);
SDL_CPUType[i++] = (char)(d & 0xff); d >>= 8; d >>= 8;
SDL_CPUType[i++] = (char)(d & 0xff); d >>= 8; SDL_CPUType[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUType[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUType[i++] = (char)(d & 0xff); SDL_CPUType[i++] = (char)(d & 0xff);
SDL_CPUType[i++] = (char)(c & 0xff); c >>= 8; SDL_CPUType[i++] = (char)(c & 0xff);
SDL_CPUType[i++] = (char)(c & 0xff); c >>= 8; c >>= 8;
SDL_CPUType[i++] = (char)(c & 0xff); c >>= 8; SDL_CPUType[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUType[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUType[i++] = (char)(c & 0xff); SDL_CPUType[i++] = (char)(c & 0xff);
} }
if (!SDL_CPUType[0]) { if (!SDL_CPUType[0]) {
@@ -718,7 +726,6 @@ SDL_GetCPUType(void)
} }
#endif #endif
#ifdef TEST_MAIN /* !!! FIXME: only used for test at the moment. */ #ifdef TEST_MAIN /* !!! FIXME: only used for test at the moment. */
#if defined(__e2k__) #if defined(__e2k__)
inline const char * inline const char *
@@ -731,8 +738,7 @@ SDL_GetCPUName(void)
return SDL_CPUName; return SDL_CPUName;
} }
#else #else
static const char * static const char *SDL_GetCPUName(void)
SDL_GetCPUName(void)
{ {
static char SDL_CPUName[48]; static char SDL_CPUName[48];
@@ -745,56 +751,104 @@ SDL_GetCPUName(void)
cpuid(0x80000000, a, b, c, d); cpuid(0x80000000, a, b, c, d);
if (a >= 0x80000004) { if (a >= 0x80000004) {
cpuid(0x80000002, a, b, c, d); cpuid(0x80000002, a, b, c, d);
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
cpuid(0x80000003, a, b, c, d); cpuid(0x80000003, a, b, c, d);
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
cpuid(0x80000004, a, b, c, d); cpuid(0x80000004, a, b, c, d);
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(a & 0xff); a >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; SDL_CPUName[i++] = (char)(a & 0xff);
SDL_CPUName[i++] = (char)(b & 0xff); b >>= 8; a >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(c & 0xff); c >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; SDL_CPUName[i++] = (char)(b & 0xff);
SDL_CPUName[i++] = (char)(d & 0xff); d >>= 8; b >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(c & 0xff);
c >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
SDL_CPUName[i++] = (char)(d & 0xff);
d >>= 8;
} }
} }
if (!SDL_CPUName[0]) { if (!SDL_CPUName[0]) {
@@ -806,12 +860,14 @@ SDL_GetCPUName(void)
#endif #endif
#endif #endif
int int SDL_GetCPUCacheLineSize(void)
SDL_GetCPUCacheLineSize(void)
{ {
const char *cpuType = SDL_GetCPUType(); const char *cpuType = SDL_GetCPUType();
int a, b, c, d; int a, b, c, d;
(void) a; (void) b; (void) c; (void) d; (void)a;
(void)b;
(void)c;
(void)d;
if (SDL_strcmp(cpuType, "GenuineIntel") == 0 || SDL_strcmp(cpuType, "CentaurHauls") == 0 || SDL_strcmp(cpuType, " Shanghai ") == 0) { if (SDL_strcmp(cpuType, "GenuineIntel") == 0 || SDL_strcmp(cpuType, "CentaurHauls") == 0 || SDL_strcmp(cpuType, " Shanghai ") == 0) {
cpuid(0x00000001, a, b, c, d); cpuid(0x00000001, a, b, c, d);
return ((b >> 8) & 0xff) * 8; return ((b >> 8) & 0xff) * 8;
@@ -827,8 +883,7 @@ SDL_GetCPUCacheLineSize(void)
static Uint32 SDL_CPUFeatures = 0xFFFFFFFF; static Uint32 SDL_CPUFeatures = 0xFFFFFFFF;
static Uint32 SDL_SIMDAlignment = 0xFFFFFFFF; static Uint32 SDL_SIMDAlignment = 0xFFFFFFFF;
static Uint32 static Uint32 SDL_GetCPUFeatures(void)
SDL_GetCPUFeatures(void)
{ {
if (SDL_CPUFeatures == 0xFFFFFFFF) { if (SDL_CPUFeatures == 0xFFFFFFFF) {
CPU_calcCPUIDFeatures(); CPU_calcCPUIDFeatures();
@@ -1000,33 +1055,32 @@ SDL_HasLASX(void)
static int SDL_SystemRAM = 0; static int SDL_SystemRAM = 0;
int int SDL_GetSystemRAM(void)
SDL_GetSystemRAM(void)
{ {
if (!SDL_SystemRAM) { if (!SDL_SystemRAM) {
#ifndef SDL_CPUINFO_DISABLED #ifndef SDL_CPUINFO_DISABLED
#if defined(HAVE_SYSCONF) && defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE) #if defined(HAVE_SYSCONF) && defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
if (SDL_SystemRAM <= 0) { if (SDL_SystemRAM <= 0) {
SDL_SystemRAM = (int)((Sint64)sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE) / (1024*1024)); SDL_SystemRAM = (int)((Sint64)sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE) / (1024 * 1024));
} }
#endif #endif
#ifdef HAVE_SYSCTLBYNAME #ifdef HAVE_SYSCTLBYNAME
if (SDL_SystemRAM <= 0) { if (SDL_SystemRAM <= 0) {
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__DragonFly__) #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__DragonFly__)
#ifdef HW_REALMEM #ifdef HW_REALMEM
int mib[2] = {CTL_HW, HW_REALMEM}; int mib[2] = { CTL_HW, HW_REALMEM };
#else #else
/* might only report up to 2 GiB */ /* might only report up to 2 GiB */
int mib[2] = {CTL_HW, HW_PHYSMEM}; int mib[2] = { CTL_HW, HW_PHYSMEM };
#endif /* HW_REALMEM */ #endif /* HW_REALMEM */
#else #else
int mib[2] = {CTL_HW, HW_MEMSIZE}; int mib[2] = { CTL_HW, HW_MEMSIZE };
#endif /* __FreeBSD__ || __FreeBSD_kernel__ */ #endif /* __FreeBSD__ || __FreeBSD_kernel__ */
Uint64 memsize = 0; Uint64 memsize = 0;
size_t len = sizeof(memsize); size_t len = sizeof(memsize);
if (sysctl(mib, 2, &memsize, &len, NULL, 0) == 0) { if (sysctl(mib, 2, &memsize, &len, NULL, 0) == 0) {
SDL_SystemRAM = (int)(memsize / (1024*1024)); SDL_SystemRAM = (int)(memsize / (1024 * 1024));
} }
} }
#endif #endif
@@ -1066,7 +1120,6 @@ SDL_GetSystemRAM(void)
return SDL_SystemRAM; return SDL_SystemRAM;
} }
size_t size_t
SDL_SIMDGetAlignment(void) SDL_SIMDGetAlignment(void)
{ {
@@ -1088,16 +1141,16 @@ SDL_SIMDAlloc(const size_t len)
/* alignment + padding + sizeof (void *) is bounded (a few hundred /* alignment + padding + sizeof (void *) is bounded (a few hundred
* bytes max), so no need to check for overflow within that argument */ * bytes max), so no need to check for overflow within that argument */
if (SDL_size_add_overflow(len, alignment + padding + sizeof (void *), &to_allocate)) { if (SDL_size_add_overflow(len, alignment + padding + sizeof(void *), &to_allocate)) {
return NULL; return NULL;
} }
ptr = (Uint8 *) SDL_malloc(to_allocate); ptr = (Uint8 *)SDL_malloc(to_allocate);
if (ptr) { if (ptr) {
/* store the actual allocated pointer right before our aligned pointer. */ /* store the actual allocated pointer right before our aligned pointer. */
retval = ptr + sizeof (void *); retval = ptr + sizeof(void *);
retval += alignment - (((size_t) retval) % alignment); retval += alignment - (((size_t)retval) % alignment);
*(((void **) retval) - 1) = ptr; *(((void **)retval) - 1) = ptr;
} }
return retval; return retval;
} }
@@ -1107,7 +1160,7 @@ SDL_SIMDRealloc(void *mem, const size_t len)
{ {
const size_t alignment = SDL_SIMDGetAlignment(); const size_t alignment = SDL_SIMDGetAlignment();
const size_t padding = (alignment - (len % alignment)) % alignment; const size_t padding = (alignment - (len % alignment)) % alignment;
Uint8 *retval = (Uint8*) mem; Uint8 *retval = (Uint8 *)mem;
void *oldmem = mem; void *oldmem = mem;
size_t memdiff = 0, ptrdiff; size_t memdiff = 0, ptrdiff;
Uint8 *ptr; Uint8 *ptr;
@@ -1115,32 +1168,32 @@ SDL_SIMDRealloc(void *mem, const size_t len)
/* alignment + padding + sizeof (void *) is bounded (a few hundred /* alignment + padding + sizeof (void *) is bounded (a few hundred
* bytes max), so no need to check for overflow within that argument */ * bytes max), so no need to check for overflow within that argument */
if (SDL_size_add_overflow(len, alignment + padding + sizeof (void *), &to_allocate)) { if (SDL_size_add_overflow(len, alignment + padding + sizeof(void *), &to_allocate)) {
return NULL; return NULL;
} }
if (mem) { if (mem) {
mem = *(((void **) mem) - 1); mem = *(((void **)mem) - 1);
/* Check the delta between the real pointer and user pointer */ /* Check the delta between the real pointer and user pointer */
memdiff = ((size_t) oldmem) - ((size_t) mem); memdiff = ((size_t)oldmem) - ((size_t)mem);
} }
ptr = (Uint8 *) SDL_realloc(mem, to_allocate); ptr = (Uint8 *)SDL_realloc(mem, to_allocate);
if (ptr == NULL) { if (ptr == NULL) {
return NULL; /* Out of memory, bail! */ return NULL; /* Out of memory, bail! */
} }
/* Store the actual allocated pointer right before our aligned pointer. */ /* Store the actual allocated pointer right before our aligned pointer. */
retval = ptr + sizeof (void *); retval = ptr + sizeof(void *);
retval += alignment - (((size_t) retval) % alignment); retval += alignment - (((size_t)retval) % alignment);
/* Make sure the delta is the same! */ /* Make sure the delta is the same! */
if (mem) { if (mem) {
ptrdiff = ((size_t) retval) - ((size_t) ptr); ptrdiff = ((size_t)retval) - ((size_t)ptr);
if (memdiff != ptrdiff) { /* Delta has changed, copy to new offset! */ if (memdiff != ptrdiff) { /* Delta has changed, copy to new offset! */
oldmem = (void*) (((uintptr_t) ptr) + memdiff); oldmem = (void *)(((uintptr_t)ptr) + memdiff);
/* Even though the data past the old `len` is undefined, this is the /* Even though the data past the old `len` is undefined, this is the
* only length value we have, and it guarantees that we copy all the * only length value we have, and it guarantees that we copy all the
@@ -1151,25 +1204,22 @@ SDL_SIMDRealloc(void *mem, const size_t len)
} }
/* Actually store the allocated pointer, finally. */ /* Actually store the allocated pointer, finally. */
*(((void **) retval) - 1) = ptr; *(((void **)retval) - 1) = ptr;
return retval; return retval;
} }
void void SDL_SIMDFree(void *ptr)
SDL_SIMDFree(void *ptr)
{ {
if (ptr) { if (ptr) {
SDL_free(*(((void **) ptr) - 1)); SDL_free(*(((void **)ptr) - 1));
} }
} }
#ifdef TEST_MAIN #ifdef TEST_MAIN
#include <stdio.h> #include <stdio.h>
int int main()
main()
{ {
printf("CPU count: %d\n", SDL_GetCPUCount()); printf("CPU count: %d\n", SDL_GetCPUCount());
printf("CPU type: %s\n", SDL_GetCPUType()); printf("CPU type: %s\n", SDL_GetCPUType());

View File

@@ -52,7 +52,6 @@ static void SDL_InitDynamicAPI(void);
/* BE CAREFUL CALLING ANY SDL CODE IN HERE, IT WILL BLOW UP. /* BE CAREFUL CALLING ANY SDL CODE IN HERE, IT WILL BLOW UP.
Even self-contained stuff might call SDL_Error and break everything. */ Even self-contained stuff might call SDL_Error and break everything. */
/* behold, the macro salsa! */ /* behold, the macro salsa! */
/* !!! FIXME: ...disabled...until we write it. :) */ /* !!! FIXME: ...disabled...until we write it. :) */
@@ -61,17 +60,22 @@ static void SDL_InitDynamicAPI(void);
#if DISABLE_JUMP_MAGIC #if DISABLE_JUMP_MAGIC
/* Can't use the macro for varargs nonsense. This is atrocious. */ /* Can't use the macro for varargs nonsense. This is atrocious. */
#define SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, logname, prio) \ #define SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, logname, prio) \
_static void SDLCALL SDL_Log##logname##name(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \ _static void SDLCALL SDL_Log##logname##name(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) \
va_list ap; initcall; va_start(ap, fmt); \ { \
va_list ap; \
initcall; \
va_start(ap, fmt); \
jump_table.SDL_LogMessageV(category, SDL_LOG_PRIORITY_##prio, fmt, ap); \ jump_table.SDL_LogMessageV(category, SDL_LOG_PRIORITY_##prio, fmt, ap); \
va_end(ap); \ va_end(ap); \
} }
#define SDL_DYNAPI_VARARGS(_static, name, initcall) \ #define SDL_DYNAPI_VARARGS(_static, name, initcall) \
_static int SDLCALL SDL_SetError##name(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \ _static int SDLCALL SDL_SetError##name(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) \
{ \
char buf[128], *str = buf; \ char buf[128], *str = buf; \
int result; \ int result; \
va_list ap; initcall; \ va_list ap; \
initcall; \
va_start(ap, fmt); \ va_start(ap, fmt); \
result = jump_table.SDL_vsnprintf(buf, sizeof(buf), fmt, ap); \ result = jump_table.SDL_vsnprintf(buf, sizeof(buf), fmt, ap); \
va_end(ap); \ va_end(ap); \
@@ -92,31 +96,49 @@ static void SDL_InitDynamicAPI(void);
} \ } \
return result; \ return result; \
} \ } \
_static int SDLCALL SDL_sscanf##name(const char *buf, SDL_SCANF_FORMAT_STRING const char *fmt, ...) { \ _static int SDLCALL SDL_sscanf##name(const char *buf, SDL_SCANF_FORMAT_STRING const char *fmt, ...) \
int retval; va_list ap; initcall; va_start(ap, fmt); \ { \
int retval; \
va_list ap; \
initcall; \
va_start(ap, fmt); \
retval = jump_table.SDL_vsscanf(buf, fmt, ap); \ retval = jump_table.SDL_vsscanf(buf, fmt, ap); \
va_end(ap); \ va_end(ap); \
return retval; \ return retval; \
} \ } \
_static int SDLCALL SDL_snprintf##name(SDL_OUT_Z_CAP(maxlen) char *buf, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \ _static int SDLCALL SDL_snprintf##name(SDL_OUT_Z_CAP(maxlen) char *buf, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) \
int retval; va_list ap; initcall; va_start(ap, fmt); \ { \
int retval; \
va_list ap; \
initcall; \
va_start(ap, fmt); \
retval = jump_table.SDL_vsnprintf(buf, maxlen, fmt, ap); \ retval = jump_table.SDL_vsnprintf(buf, maxlen, fmt, ap); \
va_end(ap); \ va_end(ap); \
return retval; \ return retval; \
} \ } \
_static int SDLCALL SDL_asprintf##name(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \ _static int SDLCALL SDL_asprintf##name(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) \
int retval; va_list ap; initcall; va_start(ap, fmt); \ { \
int retval; \
va_list ap; \
initcall; \
va_start(ap, fmt); \
retval = jump_table.SDL_vasprintf(strp, fmt, ap); \ retval = jump_table.SDL_vasprintf(strp, fmt, ap); \
va_end(ap); \ va_end(ap); \
return retval; \ return retval; \
} \ } \
_static void SDLCALL SDL_Log##name(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \ _static void SDLCALL SDL_Log##name(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) \
va_list ap; initcall; va_start(ap, fmt); \ { \
va_list ap; \
initcall; \
va_start(ap, fmt); \
jump_table.SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap); \ jump_table.SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap); \
va_end(ap); \ va_end(ap); \
} \ } \
_static void SDLCALL SDL_LogMessage##name(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \ _static void SDLCALL SDL_LogMessage##name(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) \
va_list ap; initcall; va_start(ap, fmt); \ { \
va_list ap; \
initcall; \
va_start(ap, fmt); \
jump_table.SDL_LogMessageV(category, priority, fmt, ap); \ jump_table.SDL_LogMessageV(category, priority, fmt, ap); \
va_end(ap); \ va_end(ap); \
} \ } \
@@ -128,40 +150,41 @@ static void SDL_InitDynamicAPI(void);
SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, Critical, CRITICAL) SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, Critical, CRITICAL)
#endif #endif
/* Typedefs for function pointers for jump table, and predeclare funcs */ /* Typedefs for function pointers for jump table, and predeclare funcs */
/* The DEFAULT funcs will init jump table and then call real function. */ /* The DEFAULT funcs will init jump table and then call real function. */
/* The REAL funcs are the actual functions, name-mangled to not clash. */ /* The REAL funcs are the actual functions, name-mangled to not clash. */
#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) \ #define SDL_DYNAPI_PROC(rc, fn, params, args, ret) \
typedef rc (SDLCALL *SDL_DYNAPIFN_##fn) params; \ typedef rc(SDLCALL *SDL_DYNAPIFN_##fn) params; \
static rc SDLCALL fn##_DEFAULT params; \ static rc SDLCALL fn##_DEFAULT params; \
extern rc SDLCALL fn##_REAL params; extern rc SDLCALL fn##_REAL params;
#include "SDL_dynapi_procs.h" #include "SDL_dynapi_procs.h"
#undef SDL_DYNAPI_PROC #undef SDL_DYNAPI_PROC
/* The jump table! */ /* The jump table! */
typedef struct { typedef struct
#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) SDL_DYNAPIFN_##fn fn; {
#include "SDL_dynapi_procs.h" #define SDL_DYNAPI_PROC(rc, fn, params, args, ret) SDL_DYNAPIFN_##fn fn;
#undef SDL_DYNAPI_PROC #include "SDL_dynapi_procs.h"
#undef SDL_DYNAPI_PROC
} SDL_DYNAPI_jump_table; } SDL_DYNAPI_jump_table;
/* Predeclare the default functions for initializing the jump table. */ /* Predeclare the default functions for initializing the jump table. */
#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) static rc SDLCALL fn##_DEFAULT params; #define SDL_DYNAPI_PROC(rc, fn, params, args, ret) static rc SDLCALL fn##_DEFAULT params;
#include "SDL_dynapi_procs.h" #include "SDL_dynapi_procs.h"
#undef SDL_DYNAPI_PROC #undef SDL_DYNAPI_PROC
/* The actual jump table. */ /* The actual jump table. */
static SDL_DYNAPI_jump_table jump_table = { static SDL_DYNAPI_jump_table jump_table = {
#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) fn##_DEFAULT, #define SDL_DYNAPI_PROC(rc, fn, params, args, ret) fn##_DEFAULT,
#include "SDL_dynapi_procs.h" #include "SDL_dynapi_procs.h"
#undef SDL_DYNAPI_PROC #undef SDL_DYNAPI_PROC
}; };
/* Default functions init the function table then call right thing. */ /* Default functions init the function table then call right thing. */
#if DISABLE_JUMP_MAGIC #if DISABLE_JUMP_MAGIC
#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) \ #define SDL_DYNAPI_PROC(rc, fn, params, args, ret) \
static rc SDLCALL fn##_DEFAULT params { \ static rc SDLCALL fn##_DEFAULT params \
{ \
SDL_InitDynamicAPI(); \ SDL_InitDynamicAPI(); \
ret jump_table.fn args; \ ret jump_table.fn args; \
} }
@@ -177,13 +200,13 @@ SDL_DYNAPI_VARARGS(static, _DEFAULT, SDL_InitDynamicAPI())
/* Public API functions to jump into the jump table. */ /* Public API functions to jump into the jump table. */
#if DISABLE_JUMP_MAGIC #if DISABLE_JUMP_MAGIC
#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) \ #define SDL_DYNAPI_PROC(rc, fn, params, args, ret) \
rc SDLCALL fn params { ret jump_table.fn args; } rc SDLCALL fn params { ret jump_table.fn args; }
#define SDL_DYNAPI_PROC_NO_VARARGS 1 #define SDL_DYNAPI_PROC_NO_VARARGS 1
#include "SDL_dynapi_procs.h" #include "SDL_dynapi_procs.h"
#undef SDL_DYNAPI_PROC #undef SDL_DYNAPI_PROC
#undef SDL_DYNAPI_PROC_NO_VARARGS #undef SDL_DYNAPI_PROC_NO_VARARGS
SDL_DYNAPI_VARARGS(,,) SDL_DYNAPI_VARARGS(, , )
#else #else
/* !!! FIXME: need the jump magic. */ /* !!! FIXME: need the jump magic. */
#error Write me. #error Write me.
@@ -191,16 +214,18 @@ SDL_DYNAPI_VARARGS(,,)
#define ENABLE_SDL_CALL_LOGGING 0 #define ENABLE_SDL_CALL_LOGGING 0
#if ENABLE_SDL_CALL_LOGGING #if ENABLE_SDL_CALL_LOGGING
static int SDLCALL SDL_SetError_LOGSDLCALLS(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { static int SDLCALL SDL_SetError_LOGSDLCALLS(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
char buf[512]; /* !!! FIXME: dynamic allocation */ \ {
char buf[512]; /* !!! FIXME: dynamic allocation */
va_list ap; va_list ap;
SDL_Log_REAL("SDL3CALL SDL_SetError"); SDL_Log_REAL("SDL3CALL SDL_SetError");
va_start(ap, fmt); va_start(ap, fmt);
SDL_vsnprintf_REAL(buf, sizeof (buf), fmt, ap); SDL_vsnprintf_REAL(buf, sizeof(buf), fmt, ap);
va_end(ap); va_end(ap);
return SDL_SetError_REAL("%s", buf); return SDL_SetError_REAL("%s", buf);
} }
static int SDLCALL SDL_sscanf_LOGSDLCALLS(const char *buf, SDL_SCANF_FORMAT_STRING const char *fmt, ...) { static int SDLCALL SDL_sscanf_LOGSDLCALLS(const char *buf, SDL_SCANF_FORMAT_STRING const char *fmt, ...)
{
int retval; int retval;
va_list ap; va_list ap;
SDL_Log_REAL("SDL3CALL SDL_sscanf"); SDL_Log_REAL("SDL3CALL SDL_sscanf");
@@ -209,7 +234,8 @@ static int SDLCALL SDL_sscanf_LOGSDLCALLS(const char *buf, SDL_SCANF_FORMAT_STRI
va_end(ap); va_end(ap);
return retval; return retval;
} }
static int SDLCALL SDL_snprintf_LOGSDLCALLS(SDL_OUT_Z_CAP(maxlen) char *buf, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { static int SDLCALL SDL_snprintf_LOGSDLCALLS(SDL_OUT_Z_CAP(maxlen) char *buf, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{
int retval; int retval;
va_list ap; va_list ap;
SDL_Log_REAL("SDL3CALL SDL_snprintf"); SDL_Log_REAL("SDL3CALL SDL_snprintf");
@@ -218,7 +244,8 @@ static int SDLCALL SDL_snprintf_LOGSDLCALLS(SDL_OUT_Z_CAP(maxlen) char *buf, siz
va_end(ap); va_end(ap);
return retval; return retval;
} }
static int SDLCALL SDL_asprintf_LOGSDLCALLS(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { static int SDLCALL SDL_asprintf_LOGSDLCALLS(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{
int retval; int retval;
va_list ap; va_list ap;
SDL_Log_REAL("SDL3CALL SDL_asprintf"); SDL_Log_REAL("SDL3CALL SDL_asprintf");
@@ -227,14 +254,16 @@ static int SDLCALL SDL_asprintf_LOGSDLCALLS(char **strp, SDL_PRINTF_FORMAT_STRIN
va_end(ap); va_end(ap);
return retval; return retval;
} }
static void SDLCALL SDL_Log_LOGSDLCALLS(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { static void SDLCALL SDL_Log_LOGSDLCALLS(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{
va_list ap; va_list ap;
SDL_Log_REAL("SDL3CALL SDL_Log"); SDL_Log_REAL("SDL3CALL SDL_Log");
va_start(ap, fmt); va_start(ap, fmt);
SDL_LogMessageV_REAL(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap); \ SDL_LogMessageV_REAL(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap);
va_end(ap); va_end(ap);
} }
static void SDLCALL SDL_LogMessage_LOGSDLCALLS(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { static void SDLCALL SDL_LogMessage_LOGSDLCALLS(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{
va_list ap; va_list ap;
SDL_Log_REAL("SDL3CALL SDL_LogMessage"); SDL_Log_REAL("SDL3CALL SDL_LogMessage");
va_start(ap, fmt); va_start(ap, fmt);
@@ -242,8 +271,10 @@ static void SDLCALL SDL_LogMessage_LOGSDLCALLS(int category, SDL_LogPriority pri
va_end(ap); va_end(ap);
} }
#define SDL_DYNAPI_VARARGS_LOGFN_LOGSDLCALLS(logname, prio) \ #define SDL_DYNAPI_VARARGS_LOGFN_LOGSDLCALLS(logname, prio) \
static void SDLCALL SDL_Log##logname##_LOGSDLCALLS(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \ static void SDLCALL SDL_Log##logname##_LOGSDLCALLS(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) \
va_list ap; va_start(ap, fmt); \ { \
va_list ap; \
va_start(ap, fmt); \
SDL_Log_REAL("SDL3CALL SDL_Log%s", #logname); \ SDL_Log_REAL("SDL3CALL SDL_Log%s", #logname); \
SDL_LogMessageV_REAL(category, SDL_LOG_PRIORITY_##prio, fmt, ap); \ SDL_LogMessageV_REAL(category, SDL_LOG_PRIORITY_##prio, fmt, ap); \
va_end(ap); \ va_end(ap); \
@@ -254,8 +285,12 @@ SDL_DYNAPI_VARARGS_LOGFN_LOGSDLCALLS(Info, INFO)
SDL_DYNAPI_VARARGS_LOGFN_LOGSDLCALLS(Warn, WARN) SDL_DYNAPI_VARARGS_LOGFN_LOGSDLCALLS(Warn, WARN)
SDL_DYNAPI_VARARGS_LOGFN_LOGSDLCALLS(Error, ERROR) SDL_DYNAPI_VARARGS_LOGFN_LOGSDLCALLS(Error, ERROR)
SDL_DYNAPI_VARARGS_LOGFN_LOGSDLCALLS(Critical, CRITICAL) SDL_DYNAPI_VARARGS_LOGFN_LOGSDLCALLS(Critical, CRITICAL)
#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) \ #define SDL_DYNAPI_PROC(rc, fn, params, args, ret) \
rc SDLCALL fn##_LOGSDLCALLS params { SDL_Log_REAL("SDL3CALL %s", #fn); ret fn##_REAL args; } rc SDLCALL fn##_LOGSDLCALLS params \
{ \
SDL_Log_REAL("SDL3CALL %s", #fn); \
ret fn##_REAL args; \
}
#define SDL_DYNAPI_PROC_NO_VARARGS 1 #define SDL_DYNAPI_PROC_NO_VARARGS 1
#include "SDL_dynapi_procs.h" #include "SDL_dynapi_procs.h"
#undef SDL_DYNAPI_PROC #undef SDL_DYNAPI_PROC
@@ -264,38 +299,37 @@ SDL_DYNAPI_VARARGS_LOGFN_LOGSDLCALLS(Critical, CRITICAL)
/* we make this a static function so we can call the correct one without the /* we make this a static function so we can call the correct one without the
system's dynamic linker resolving to the wrong version of this. */ system's dynamic linker resolving to the wrong version of this. */
static Sint32 static Sint32 initialize_jumptable(Uint32 apiver, void *table, Uint32 tablesize)
initialize_jumptable(Uint32 apiver, void *table, Uint32 tablesize)
{ {
SDL_DYNAPI_jump_table *output_jump_table = (SDL_DYNAPI_jump_table *) table; SDL_DYNAPI_jump_table *output_jump_table = (SDL_DYNAPI_jump_table *)table;
if (apiver != SDL_DYNAPI_VERSION) { if (apiver != SDL_DYNAPI_VERSION) {
/* !!! FIXME: can maybe handle older versions? */ /* !!! FIXME: can maybe handle older versions? */
return -1; /* not compatible. */ return -1; /* not compatible. */
} else if (tablesize > sizeof (jump_table)) { } else if (tablesize > sizeof(jump_table)) {
return -1; /* newer version of SDL with functions we can't provide. */ return -1; /* newer version of SDL with functions we can't provide. */
} }
/* Init our jump table first. */ /* Init our jump table first. */
#if ENABLE_SDL_CALL_LOGGING #if ENABLE_SDL_CALL_LOGGING
{ {
const char *env = SDL_getenv_REAL("SDL_DYNAPI_LOG_CALLS"); const char *env = SDL_getenv_REAL("SDL_DYNAPI_LOG_CALLS");
const SDL_bool log_calls = (env && SDL_atoi_REAL(env)); const SDL_bool log_calls = (env && SDL_atoi_REAL(env));
if (log_calls) { if (log_calls) {
#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) jump_table.fn = fn##_LOGSDLCALLS; #define SDL_DYNAPI_PROC(rc, fn, params, args, ret) jump_table.fn = fn##_LOGSDLCALLS;
#include "SDL_dynapi_procs.h" #include "SDL_dynapi_procs.h"
#undef SDL_DYNAPI_PROC #undef SDL_DYNAPI_PROC
} else { } else {
#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) jump_table.fn = fn##_REAL; #define SDL_DYNAPI_PROC(rc, fn, params, args, ret) jump_table.fn = fn##_REAL;
#include "SDL_dynapi_procs.h" #include "SDL_dynapi_procs.h"
#undef SDL_DYNAPI_PROC #undef SDL_DYNAPI_PROC
} }
} }
#else #else
#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) jump_table.fn = fn##_REAL; #define SDL_DYNAPI_PROC(rc, fn, params, args, ret) jump_table.fn = fn##_REAL;
#include "SDL_dynapi_procs.h" #include "SDL_dynapi_procs.h"
#undef SDL_DYNAPI_PROC #undef SDL_DYNAPI_PROC
#endif #endif
/* Then the external table... */ /* Then the external table... */
if (output_jump_table != &jump_table) { if (output_jump_table != &jump_table) {
@@ -307,10 +341,9 @@ initialize_jumptable(Uint32 apiver, void *table, Uint32 tablesize)
return 0; /* success! */ return 0; /* success! */
} }
/* Here's the exported entry point that fills in the jump table. */ /* Here's the exported entry point that fills in the jump table. */
/* Use specific types when an "int" might suffice to keep this sane. */ /* Use specific types when an "int" might suffice to keep this sane. */
typedef Sint32 (SDLCALL *SDL_DYNAPI_ENTRYFN)(Uint32 apiver, void *table, Uint32 tablesize); typedef Sint32(SDLCALL *SDL_DYNAPI_ENTRYFN)(Uint32 apiver, void *table, Uint32 tablesize);
extern DECLSPEC Sint32 SDLCALL SDL_DYNAPI_entry(Uint32, void *, Uint32); extern DECLSPEC Sint32 SDLCALL SDL_DYNAPI_entry(Uint32, void *, Uint32);
Sint32 Sint32
@@ -319,7 +352,6 @@ SDL_DYNAPI_entry(Uint32 apiver, void *table, Uint32 tablesize)
return initialize_jumptable(apiver, table, tablesize); return initialize_jumptable(apiver, table, tablesize);
} }
/* Obviously we can't use SDL_LoadObject() to load SDL. :) */ /* Obviously we can't use SDL_LoadObject() to load SDL. :) */
/* Also obviously, we never close the loaded library. */ /* Also obviously, we never close the loaded library. */
#if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) #if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__)
@@ -359,17 +391,16 @@ static SDL_INLINE void *get_sdlapi_entry(const char *fname, const char *sym)
#error Please define your platform. #error Please define your platform.
#endif #endif
static void dynapi_warn(const char *msg) static void dynapi_warn(const char *msg)
{ {
const char *caption = "SDL Dynamic API Failure!"; const char *caption = "SDL Dynamic API Failure!";
/* SDL_ShowSimpleMessageBox() is a too heavy for here. */ /* SDL_ShowSimpleMessageBox() is a too heavy for here. */
#if (defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__)) && !defined(__XBOXONE__) && !defined(__XBOXSERIES__) #if (defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__)) && !defined(__XBOXONE__) && !defined(__XBOXSERIES__)
MessageBoxA(NULL, msg, caption, MB_OK | MB_ICONERROR); MessageBoxA(NULL, msg, caption, MB_OK | MB_ICONERROR);
#elif defined(HAVE_STDIO_H) #elif defined(HAVE_STDIO_H)
fprintf(stderr, "\n\n%s\n%s\n\n", caption, msg); fprintf(stderr, "\n\n%s\n%s\n\n", caption, msg);
fflush(stderr); fflush(stderr);
#endif #endif
} }
/* This is not declared in any header, although it is shared between some /* This is not declared in any header, although it is shared between some
@@ -381,16 +412,14 @@ void SDL_ExitProcess(int exitcode);
#endif #endif
SDL_NORETURN void SDL_ExitProcess(int exitcode); SDL_NORETURN void SDL_ExitProcess(int exitcode);
static void SDL_InitDynamicAPILocked(void)
static void
SDL_InitDynamicAPILocked(void)
{ {
const char *libname = SDL_getenv_REAL(SDL_DYNAMIC_API_ENVVAR); const char *libname = SDL_getenv_REAL(SDL_DYNAMIC_API_ENVVAR);
SDL_DYNAPI_ENTRYFN entry = NULL; /* funcs from here by default. */ SDL_DYNAPI_ENTRYFN entry = NULL; /* funcs from here by default. */
SDL_bool use_internal = SDL_TRUE; SDL_bool use_internal = SDL_TRUE;
if (libname) { if (libname) {
entry = (SDL_DYNAPI_ENTRYFN) get_sdlapi_entry(libname, "SDL_DYNAPI_entry"); entry = (SDL_DYNAPI_ENTRYFN)get_sdlapi_entry(libname, "SDL_DYNAPI_entry");
if (!entry) { if (!entry) {
dynapi_warn("Couldn't load overriding SDL library. Please fix or remove the " SDL_DYNAMIC_API_ENVVAR " environment variable. Using the default SDL."); dynapi_warn("Couldn't load overriding SDL library. Please fix or remove the " SDL_DYNAMIC_API_ENVVAR " environment variable. Using the default SDL.");
/* Just fill in the function pointers from this library, later. */ /* Just fill in the function pointers from this library, later. */
@@ -398,7 +427,7 @@ SDL_InitDynamicAPILocked(void)
} }
if (entry) { if (entry) {
if (entry(SDL_DYNAPI_VERSION, &jump_table, sizeof (jump_table)) < 0) { if (entry(SDL_DYNAPI_VERSION, &jump_table, sizeof(jump_table)) < 0) {
dynapi_warn("Couldn't override SDL library. Using a newer SDL build might help. Please fix or remove the " SDL_DYNAMIC_API_ENVVAR " environment variable. Using the default SDL."); dynapi_warn("Couldn't override SDL library. Using a newer SDL build might help. Please fix or remove the " SDL_DYNAMIC_API_ENVVAR " environment variable. Using the default SDL.");
/* Just fill in the function pointers from this library, later. */ /* Just fill in the function pointers from this library, later. */
} else { } else {
@@ -408,7 +437,7 @@ SDL_InitDynamicAPILocked(void)
/* Just fill in the function pointers from this library. */ /* Just fill in the function pointers from this library. */
if (use_internal) { if (use_internal) {
if (initialize_jumptable(SDL_DYNAPI_VERSION, &jump_table, sizeof (jump_table)) < 0) { if (initialize_jumptable(SDL_DYNAPI_VERSION, &jump_table, sizeof(jump_table)) < 0) {
/* Now we're screwed. Should definitely abort now. */ /* Now we're screwed. Should definitely abort now. */
dynapi_warn("Failed to initialize internal SDL dynapi. As this would otherwise crash, we have to abort now."); dynapi_warn("Failed to initialize internal SDL dynapi. As this would otherwise crash, we have to abort now.");
SDL_ExitProcess(86); SDL_ExitProcess(86);
@@ -418,8 +447,7 @@ SDL_InitDynamicAPILocked(void)
/* we intentionally never close the newly-loaded lib, of course. */ /* we intentionally never close the newly-loaded lib, of course. */
} }
static void static void SDL_InitDynamicAPI(void)
SDL_InitDynamicAPI(void)
{ {
/* So the theory is that every function in the jump table defaults to /* So the theory is that every function in the jump table defaults to
* calling this function, and then replaces itself with a version that * calling this function, and then replaces itself with a version that
@@ -434,22 +462,22 @@ SDL_InitDynamicAPI(void)
*/ */
static SDL_bool already_initialized = SDL_FALSE; static SDL_bool already_initialized = SDL_FALSE;
/* SDL_AtomicLock calls SDL mutex functions to emulate if /* SDL_AtomicLock calls SDL mutex functions to emulate if
SDL_ATOMIC_DISABLED, which we can't do here, so in such a SDL_ATOMIC_DISABLED, which we can't do here, so in such a
configuration, you're on your own. */ configuration, you're on your own. */
#if !SDL_ATOMIC_DISABLED #if !SDL_ATOMIC_DISABLED
static SDL_SpinLock lock = 0; static SDL_SpinLock lock = 0;
SDL_AtomicLock_REAL(&lock); SDL_AtomicLock_REAL(&lock);
#endif #endif
if (!already_initialized) { if (!already_initialized) {
SDL_InitDynamicAPILocked(); SDL_InitDynamicAPILocked();
already_initialized = SDL_TRUE; already_initialized = SDL_TRUE;
} }
#if !SDL_ATOMIC_DISABLED #if !SDL_ATOMIC_DISABLED
SDL_AtomicUnlock_REAL(&lock); SDL_AtomicUnlock_REAL(&lock);
#endif #endif
} }
#endif /* SDL_DYNAMIC_API */ #endif /* SDL_DYNAMIC_API */

View File

@@ -25,9 +25,7 @@
#include "SDL_events_c.h" #include "SDL_events_c.h"
#include "SDL_clipboardevents_c.h" #include "SDL_clipboardevents_c.h"
int SDL_SendClipboardUpdate(void)
int
SDL_SendClipboardUpdate(void)
{ {
int posted; int posted;

View File

@@ -24,9 +24,7 @@
#include "SDL_events_c.h" #include "SDL_events_c.h"
int SDL_SendDisplayEvent(SDL_VideoDisplay *display, Uint8 displayevent, int data1)
int
SDL_SendDisplayEvent(SDL_VideoDisplay *display, Uint8 displayevent, int data1)
{ {
int posted; int posted;

View File

@@ -27,9 +27,7 @@
#include "../video/SDL_sysvideo.h" /* for SDL_Window internals. */ #include "../video/SDL_sysvideo.h" /* for SDL_Window internals. */
static int SDL_SendDrop(SDL_Window *window, const SDL_EventType evtype, const char *data)
static int
SDL_SendDrop(SDL_Window *window, const SDL_EventType evtype, const char *data)
{ {
static SDL_bool app_is_dropping = SDL_FALSE; static SDL_bool app_is_dropping = SDL_FALSE;
int posted = 0; int posted = 0;
@@ -75,23 +73,19 @@ SDL_SendDrop(SDL_Window *window, const SDL_EventType evtype, const char *data)
return posted; return posted;
} }
int int SDL_SendDropFile(SDL_Window *window, const char *file)
SDL_SendDropFile(SDL_Window *window, const char *file)
{ {
return SDL_SendDrop(window, SDL_DROPFILE, file); return SDL_SendDrop(window, SDL_DROPFILE, file);
} }
int int SDL_SendDropText(SDL_Window *window, const char *text)
SDL_SendDropText(SDL_Window *window, const char *text)
{ {
return SDL_SendDrop(window, SDL_DROPTEXT, text); return SDL_SendDrop(window, SDL_DROPTEXT, text);
} }
int int SDL_SendDropComplete(SDL_Window *window)
SDL_SendDropComplete(SDL_Window *window)
{ {
return SDL_SendDrop(window, SDL_DROPCOMPLETE, NULL); return SDL_SendDrop(window, SDL_DROPCOMPLETE, NULL);
} }
/* vi: set ts=4 sw=4 expandtab: */ /* vi: set ts=4 sw=4 expandtab: */

Some files were not shown because too many files have changed in this diff Show More