Revert "Updated SDL, Bullet and OpenAL soft libs"

This reverts commit 370161cfb1.
This commit is contained in:
AzaezelX 2019-07-08 09:49:44 -05:00
parent 160dc00c07
commit e7ee94428e
1102 changed files with 62741 additions and 204988 deletions

View file

@ -33,7 +33,6 @@
#include "events/SDL_events_c.h"
#include "haptic/SDL_haptic_c.h"
#include "joystick/SDL_joystick_c.h"
#include "sensor/SDL_sensor_c.h"
/* Initialization/Cleanup routines */
#if !SDL_TIMERS_DISABLED
@ -124,11 +123,11 @@ SDL_InitSubSystem(Uint32 flags)
}
#if SDL_VIDEO_DRIVER_WINDOWS
if ((flags & (SDL_INIT_HAPTIC|SDL_INIT_JOYSTICK))) {
if (SDL_HelperWindowCreate() < 0) {
return -1;
}
}
if ((flags & (SDL_INIT_HAPTIC|SDL_INIT_JOYSTICK))) {
if (SDL_HelperWindowCreate() < 0) {
return -1;
}
}
#endif
#if !SDL_TIMERS_DISABLED
@ -233,20 +232,6 @@ SDL_InitSubSystem(Uint32 flags)
#endif
}
/* Initialize the sensor subsystem */
if ((flags & SDL_INIT_SENSOR)){
#if !SDL_SENSOR_DISABLED
if (SDL_PrivateShouldInitSubsystem(SDL_INIT_SENSOR)) {
if (SDL_SensorInit() < 0) {
return (-1);
}
}
SDL_PrivateSubsystemRefCountIncr(SDL_INIT_SENSOR);
#else
return SDL_SetError("SDL not built with sensor support");
#endif
}
return (0);
}
@ -260,15 +245,6 @@ void
SDL_QuitSubSystem(Uint32 flags)
{
/* Shut down requested initialized subsystems */
#if !SDL_SENSOR_DISABLED
if ((flags & SDL_INIT_SENSOR)) {
if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_SENSOR)) {
SDL_SensorQuit();
}
SDL_PrivateSubsystemRefCountDecr(SDL_INIT_SENSOR);
}
#endif
#if !SDL_JOYSTICK_DISABLED
if ((flags & SDL_INIT_GAMECONTROLLER)) {
/* game controller implies joystick */
@ -475,20 +451,6 @@ SDL_GetPlatform()
#endif
}
SDL_bool
SDL_IsTablet()
{
#if __ANDROID__
extern SDL_bool SDL_IsAndroidTablet(void);
return SDL_IsAndroidTablet();
#elif __IPHONEOS__
extern SDL_bool SDL_IsIPad(void);
return SDL_IsIPad();
#else
return SDL_FALSE;
#endif
}
#if defined(__WIN32__)
#if (!defined(HAVE_LIBC) || defined(__WATCOMC__)) && !defined(SDL_STATIC_LIB)

View file

@ -120,17 +120,10 @@ static void SDL_GenerateAssertionReport(void)
}
#if defined(__WATCOMC__)
#pragma aux SDL_ExitProcess aborts;
#endif
static void SDL_ExitProcess(int exitcode)
static SDL_NORETURN void SDL_ExitProcess(int exitcode)
{
#ifdef __WIN32__
/* "if you do not know the state of all threads in your process, it is
better to call TerminateProcess than ExitProcess"
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682658(v=vs.85).aspx */
TerminateProcess(GetCurrentProcess(), exitcode);
ExitProcess(exitcode);
#elif defined(__EMSCRIPTEN__)
emscripten_cancel_main_loop(); /* this should "kill" the app. */
emscripten_force_exit(exitcode); /* this should "kill" the app. */
@ -141,10 +134,7 @@ static void SDL_ExitProcess(int exitcode)
}
#if defined(__WATCOMC__)
#pragma aux SDL_AbortAssertion aborts;
#endif
static void SDL_AbortAssertion(void)
static SDL_NORETURN void SDL_AbortAssertion(void)
{
SDL_Quit();
SDL_ExitProcess(42);

View file

@ -19,11 +19,6 @@
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_assert_c_h_
#define SDL_assert_c_h_
extern void SDL_AssertionsQuit(void);
#endif /* SDL_assert_c_h_ */
/* vi: set ts=4 sw=4 expandtab: */

View file

@ -53,11 +53,10 @@
#endif
#if defined(__WATCOMC__) && defined(__386__)
SDL_COMPILE_TIME_ASSERT(intsize, 4==sizeof(int));
#define HAVE_WATCOM_ATOMICS
extern _inline int _SDL_xchg_watcom(volatile int *a, int v);
#pragma aux _SDL_xchg_watcom = \
"lock xchg [ecx], eax" \
"xchg [ecx], eax" \
parm [ecx] [eax] \
value [eax] \
modify exact [eax];

View file

@ -32,15 +32,11 @@
#include <atomic.h>
#endif
#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
#include <xmmintrin.h>
#endif
#if defined(__WATCOMC__) && defined(__386__)
SDL_COMPILE_TIME_ASSERT(locksize, 4==sizeof(SDL_SpinLock));
extern _inline int _SDL_xchg_watcom(volatile int *a, int v);
#pragma aux _SDL_xchg_watcom = \
"lock xchg [ecx], eax" \
"xchg [ecx], eax" \
parm [ecx] [eax] \
value [eax] \
modify exact [eax];
@ -120,32 +116,12 @@ SDL_AtomicTryLock(SDL_SpinLock *lock)
#endif
}
/* "REP NOP" is PAUSE, coded for tools that don't know it by that name. */
#if (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
#define PAUSE_INSTRUCTION() __asm__ __volatile__("pause\n") /* Some assemblers can't do REP NOP, so go with PAUSE. */
#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
#define PAUSE_INSTRUCTION() _mm_pause() /* this is actually "rep nop" and not a SIMD instruction. No inline asm in MSVC x86-64! */
#elif defined(__WATCOMC__) && defined(__386__)
/* watcom assembler rejects PAUSE if CPU < i686, and it refuses REP NOP as an invalid combination. Hardcode the bytes. */
extern _inline void PAUSE_INSTRUCTION(void);
#pragma aux PAUSE_INSTRUCTION = "db 0f3h,90h"
#else
#define PAUSE_INSTRUCTION()
#endif
void
SDL_AtomicLock(SDL_SpinLock *lock)
{
int iterations = 0;
/* FIXME: Should we have an eventual timeout? */
while (!SDL_AtomicTryLock(lock)) {
if (iterations < 32) {
iterations++;
PAUSE_INSTRUCTION();
} else {
/* !!! FIXME: this doesn't definitely give up the current timeslice, it does different things on various platforms. */
SDL_Delay(0);
}
SDL_Delay(0);
}
}

View file

@ -378,57 +378,21 @@ static int
add_audio_device(const char *name, void *handle, SDL_AudioDeviceItem **devices, int *devCount)
{
int retval = -1;
SDL_AudioDeviceItem *item;
const SDL_AudioDeviceItem *i;
int dupenum = 0;
const size_t size = sizeof (SDL_AudioDeviceItem) + SDL_strlen(name) + 1;
SDL_AudioDeviceItem *item = (SDL_AudioDeviceItem *) SDL_malloc(size);
if (item == NULL) {
return -1;
}
SDL_assert(handle != NULL); /* we reserve NULL, audio backends can't use it. */
SDL_assert(name != NULL);
item = (SDL_AudioDeviceItem *) SDL_malloc(sizeof (SDL_AudioDeviceItem));
if (!item) {
return SDL_OutOfMemory();
}
item->original_name = SDL_strdup(name);
if (!item->original_name) {
SDL_free(item);
return SDL_OutOfMemory();
}
item->dupenum = 0;
item->name = item->original_name;
item->handle = handle;
SDL_strlcpy(item->name, name, size - sizeof (SDL_AudioDeviceItem));
SDL_LockMutex(current_audio.detectionLock);
for (i = *devices; i != NULL; i = i->next) {
if (SDL_strcmp(name, i->original_name) == 0) {
dupenum = i->dupenum + 1;
break; /* stop at the highest-numbered dupe. */
}
}
if (dupenum) {
const size_t len = SDL_strlen(name) + 16;
char *replacement = (char *) SDL_malloc(len);
if (!replacement) {
SDL_UnlockMutex(current_audio.detectionLock);
SDL_free(item->original_name);
SDL_free(item);
SDL_OutOfMemory();
return -1;
}
SDL_snprintf(replacement, len, "%s (%d)", name, dupenum + 1);
item->dupenum = dupenum;
item->name = replacement;
}
item->next = *devices;
*devices = item;
retval = (*devCount)++; /* !!! FIXME: this should be an atomic increment */
retval = (*devCount)++;
SDL_UnlockMutex(current_audio.detectionLock);
return retval;
@ -456,11 +420,6 @@ free_device_list(SDL_AudioDeviceItem **devices, int *devCount)
if (item->handle != NULL) {
current_audio.impl.FreeDeviceHandle(item->handle);
}
/* these two pointers are the same if not a duplicate devname */
if (item->name != item->original_name) {
SDL_free(item->name);
}
SDL_free(item->original_name);
SDL_free(item);
}
*devices = NULL;
@ -492,11 +451,7 @@ void SDL_OpenedAudioDeviceDisconnected(SDL_AudioDevice *device)
SDL_assert(get_audio_device(device->id) == device);
if (!SDL_AtomicGet(&device->enabled)) {
return; /* don't report disconnects more than once. */
}
if (SDL_AtomicGet(&device->shutdown)) {
return; /* don't report disconnect if we're trying to close device. */
return;
}
/* Ends the audio callback and mark the device as STOPPED, but the
@ -696,7 +651,7 @@ SDL_RunAudio(void *devicep)
SDL_assert(!device->iscapture);
/* The audio mixing is always a high priority thread */
SDL_SetThreadPriority(SDL_THREAD_PRIORITY_TIME_CRITICAL);
SDL_SetThreadPriority(SDL_THREAD_PRIORITY_HIGH);
/* Perform any thread setup */
device->threadid = SDL_ThreadID();
@ -877,8 +832,6 @@ SDL_CaptureAudio(void *devicep)
}
}
current_audio.impl.PrepareToClose(device);
current_audio.impl.FlushCapture(device);
current_audio.impl.ThreadDeinit(device);
@ -1018,11 +971,6 @@ clean_out_device_list(SDL_AudioDeviceItem **devices, int *devCount, SDL_bool *re
} else {
*devices = next;
}
/* these two pointers are the same if not a duplicate devname */
if (item->name != item->original_name) {
SDL_free(item->name);
}
SDL_free(item->original_name);
SDL_free(item);
}
item = next;
@ -1049,6 +997,7 @@ SDL_GetNumAudioDevices(int iscapture)
if (!iscapture && current_audio.outputDevicesRemoved) {
clean_out_device_list(&current_audio.outputDevices, &current_audio.outputDeviceCount, &current_audio.outputDevicesRemoved);
current_audio.outputDevicesRemoved = SDL_FALSE;
}
retval = iscapture ? current_audio.inputDeviceCount : current_audio.outputDeviceCount;
@ -1105,14 +1054,16 @@ close_audio_device(SDL_AudioDevice * device)
return;
}
/* make sure the device is paused before we do anything else, so the
audio callback definitely won't fire again. */
current_audio.impl.LockDevice(device);
SDL_AtomicSet(&device->paused, 1);
if (device->id > 0) {
SDL_AudioDevice *opendev = open_devices[device->id - 1];
SDL_assert((opendev == device) || (opendev == NULL));
if (opendev == device) {
open_devices[device->id - 1] = NULL;
}
}
SDL_AtomicSet(&device->shutdown, 1);
SDL_AtomicSet(&device->enabled, 0);
current_audio.impl.UnlockDevice(device);
if (device->thread != NULL) {
SDL_WaitThread(device->thread, NULL);
}
@ -1123,14 +1074,6 @@ close_audio_device(SDL_AudioDevice * device)
SDL_free(device->work_buffer);
SDL_FreeAudioStream(device->stream);
if (device->id > 0) {
SDL_AudioDevice *opendev = open_devices[device->id - 1];
SDL_assert((opendev == device) || (opendev == NULL));
if (opendev == device) {
open_devices[device->id - 1] = NULL;
}
}
if (device->hidden != NULL) {
current_audio.impl.CloseDevice(device);
}
@ -1175,9 +1118,8 @@ prepare_audiospec(const SDL_AudioSpec * orig, SDL_AudioSpec * prepared)
}
case 1: /* Mono */
case 2: /* Stereo */
case 4: /* Quadrophonic */
case 6: /* 5.1 surround */
case 8: /* 7.1 surround */
case 4: /* surround */
case 6: /* surround with center and lfe */
break;
default:
SDL_SetError("Unsupported number of audio channels.");
@ -1370,12 +1312,15 @@ open_audio_device(const char *devname, int iscapture,
build_stream = SDL_TRUE;
}
}
/* !!! FIXME in 2.1: add SDL_AUDIO_ALLOW_SAMPLES_CHANGE flag?
As of 2.0.6, we will build a stream to buffer the difference between
what the app wants to feed and the device wants to eat, so everyone
gets their way. In prior releases, SDL would force the callback to
feed at the rate the device requested, adjusted for resampling.
*/
if (device->spec.samples != obtained->samples) {
if (allowed_changes & SDL_AUDIO_ALLOW_SAMPLES_CHANGE) {
obtained->samples = device->spec.samples;
} else {
build_stream = SDL_TRUE;
}
build_stream = SDL_TRUE;
}
SDL_CalculateAudioSpec(obtained); /* recalc after possible changes. */

View file

@ -724,7 +724,7 @@ SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format
SDL_assert(format == AUDIO_F32SYS);
/* 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, sizeof (float));
if (!padding) {
SDL_OutOfMemory();
return;
@ -1291,7 +1291,7 @@ SDL_NewAudioStream(const SDL_AudioFormat src_format,
retval->packetlen = packetlen;
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 = (float *) SDL_calloc(retval->resampler_padding_samples ? retval->resampler_padding_samples : 1, sizeof (float));
retval->resampler_padding = (float *) SDL_calloc(retval->resampler_padding_samples, sizeof (float));
if (retval->resampler_padding == NULL) {
SDL_FreeAudioStream(retval);

View file

@ -18,10 +18,6 @@
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_audiodev_c_h_
#define SDL_audiodev_c_h_
#include "SDL.h"
#include "../SDL_internal.h"
#include "SDL_sysaudio.h"
@ -39,6 +35,4 @@
extern void SDL_EnumUnixAudioDevices(const int classic, int (*test)(int));
#endif /* SDL_audiodev_c_h_ */
/* vi: set ts=4 sw=4 expandtab: */

View file

@ -25,10 +25,8 @@
#include "SDL_cpuinfo.h"
#include "SDL_assert.h"
/* !!! FIXME: disabled until we fix https://bugzilla.libsdl.org/show_bug.cgi?id=4186 */
#if 0 /*def __ARM_NEON__*/
#define HAVE_NEON_INTRINSICS 1
#endif
/* !!! FIXME: write NEON code. */
#define HAVE_NEON_INTRINSICS 0
#ifdef __SSE2__
#define HAVE_SSE2_INTRINSICS 1
@ -64,7 +62,7 @@ SDL_AudioFilter SDL_Convert_F32_to_S32 = NULL;
#define DIVBY128 0.0078125f
#define DIVBY32768 0.000030517578125f
#define DIVBY8388607 0.00000011920930376163766f
#define DIVBY2147483648 0.00000000046566128730773926
#if NEED_SCALAR_CONVERTER_FALLBACKS
@ -154,7 +152,7 @@ SDL_Convert_S32_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
LOG_DEBUG_CONVERT("AUDIO_S32", "AUDIO_F32");
for (i = cvt->len_cvt / sizeof (Sint32); i; --i, ++src, ++dst) {
*dst = ((float) (*src>>8)) * DIVBY8388607;
*dst = (float) (((double) *src) * DIVBY2147483648);
}
if (cvt->filters[++cvt->filter_index]) {
@ -173,10 +171,10 @@ SDL_Convert_F32_to_S8_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
if (sample > 1.0f) {
*dst = 127;
} else if (sample <= -1.0f) {
*dst = -128;
} else if (sample < -1.0f) {
*dst = -127;
} else {
*dst = (Sint8)(sample * 127.0f);
}
@ -199,9 +197,9 @@ SDL_Convert_F32_to_U8_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
if (sample > 1.0f) {
*dst = 255;
} else if (sample <= -1.0f) {
} else if (sample < -1.0f) {
*dst = 0;
} else {
*dst = (Uint8)((sample + 1.0f) * 127.0f);
@ -225,10 +223,10 @@ SDL_Convert_F32_to_S16_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
if (sample > 1.0f) {
*dst = 32767;
} else if (sample <= -1.0f) {
*dst = -32768;
} else if (sample < -1.0f) {
*dst = -32767;
} else {
*dst = (Sint16)(sample * 32767.0f);
}
@ -251,9 +249,9 @@ SDL_Convert_F32_to_U16_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 65535;
} else if (sample <= -1.0f) {
if (sample > 1.0f) {
*dst = 65534;
} else if (sample < -1.0f) {
*dst = 0;
} else {
*dst = (Uint16)((sample + 1.0f) * 32767.0f);
@ -277,12 +275,12 @@ SDL_Convert_F32_to_S32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
if (sample > 1.0f) {
*dst = 2147483647;
} else if (sample <= -1.0f) {
*dst = (Sint32) -2147483648LL;
} else if (sample < -1.0f) {
*dst = -2147483647;
} else {
*dst = ((Sint32)(sample * 8388607.0f)) << 8;
*dst = (Sint32)((double)sample * 2147483647.0);
}
}
@ -511,6 +509,16 @@ SDL_Convert_U16_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
}
}
#if defined(__GNUC__) && (__GNUC__ < 4)
/* these were added as of gcc-4.0: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19418 */
static inline __m128 _mm_castsi128_ps(__m128i __A) {
return (__m128) __A;
}
static inline __m128i _mm_castps_si128(__m128 __A) {
return (__m128i) __A;
}
#endif
static void SDLCALL
SDL_Convert_S32_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
@ -522,7 +530,7 @@ SDL_Convert_S32_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (Sint32); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
*dst = ((float) (*src>>8)) * DIVBY8388607;
*dst = (float) (((double) *src) * DIVBY2147483648);
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
@ -530,11 +538,15 @@ SDL_Convert_S32_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 divby8388607 = _mm_set1_ps(DIVBY8388607);
const __m128d divby2147483648 = _mm_set1_pd(DIVBY2147483648);
const __m128i *mmsrc = (const __m128i *) src;
while (i >= 4) { /* 4 * sint32 */
/* shift out lowest bits so int fits in a float32. Small precision loss, but much faster. */
_mm_store_ps(dst, _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_load_si128(mmsrc), 8)), divby8388607));
const __m128i ints = _mm_load_si128(mmsrc);
/* bitshift the whole register over, so _mm_cvtepi32_pd can read the top ints in the bottom of the vector. */
const __m128d doubles1 = _mm_mul_pd(_mm_cvtepi32_pd(_mm_srli_si128(ints, 8)), divby2147483648);
const __m128d doubles2 = _mm_mul_pd(_mm_cvtepi32_pd(ints), divby2147483648);
/* convert to float32, bitshift/or to get these into a vector to store. */
_mm_store_ps(dst, _mm_castsi128_ps(_mm_or_si128(_mm_slli_si128(_mm_castps_si128(_mm_cvtpd_ps(doubles1)), 8), _mm_castps_si128(_mm_cvtpd_ps(doubles2)))));
i -= 4; mmsrc++; dst += 4;
}
src = (const Sint32 *) mmsrc;
@ -542,7 +554,7 @@ SDL_Convert_S32_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Finish off any leftovers with scalar operations. */
while (i) {
*dst = ((float) (*src>>8)) * DIVBY8388607;
*dst = (float) (((double) *src) * DIVBY2147483648);
i--; src++; dst++;
}
@ -562,14 +574,7 @@ SDL_Convert_F32_to_S8_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 127;
} else if (sample <= -1.0f) {
*dst = -128;
} else {
*dst = (Sint8)(sample * 127.0f);
}
*dst = (Sint8) (*src * 127.0f);
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
@ -577,15 +582,13 @@ SDL_Convert_F32_to_S8_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 one = _mm_set1_ps(1.0f);
const __m128 negone = _mm_set1_ps(-1.0f);
const __m128 mulby127 = _mm_set1_ps(127.0f);
__m128i *mmdst = (__m128i *) dst;
while (i >= 16) { /* 16 * float32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src+4)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints3 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src+8)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints4 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src+12)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src), mulby127)); /* load 4 floats, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src+4), mulby127)); /* load 4 floats, convert to sint32 */
const __m128i ints3 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src+8), mulby127)); /* load 4 floats, convert to sint32 */
const __m128i ints4 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src+12), mulby127)); /* load 4 floats, convert to sint32 */
_mm_store_si128(mmdst, _mm_packs_epi16(_mm_packs_epi32(ints1, ints2), _mm_packs_epi32(ints3, ints4))); /* pack down, store out. */
i -= 16; src += 16; mmdst++;
}
@ -594,14 +597,7 @@ SDL_Convert_F32_to_S8_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 127;
} else if (sample <= -1.0f) {
*dst = -128;
} else {
*dst = (Sint8)(sample * 127.0f);
}
*dst = (Sint8) (*src * 127.0f);
i--; src++; dst++;
}
@ -622,14 +618,7 @@ SDL_Convert_F32_to_U8_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 255;
} else if (sample <= -1.0f) {
*dst = 0;
} else {
*dst = (Uint8)((sample + 1.0f) * 127.0f);
}
*dst = (Uint8) ((*src + 1.0f) * 127.0f);
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
@ -637,15 +626,14 @@ SDL_Convert_F32_to_U8_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 one = _mm_set1_ps(1.0f);
const __m128 negone = _mm_set1_ps(-1.0f);
const __m128 add1 = _mm_set1_ps(1.0f);
const __m128 mulby127 = _mm_set1_ps(127.0f);
__m128i *mmdst = (__m128i *) dst;
while (i >= 16) { /* 16 * float32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src)), one), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src+4)), one), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints3 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src+8)), one), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints4 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src+12)), one), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_load_ps(src), add1), mulby127)); /* load 4 floats, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_load_ps(src+4), add1), mulby127)); /* load 4 floats, convert to sint32 */
const __m128i ints3 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_load_ps(src+8), add1), mulby127)); /* load 4 floats, convert to sint32 */
const __m128i ints4 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_load_ps(src+12), add1), mulby127)); /* load 4 floats, convert to sint32 */
_mm_store_si128(mmdst, _mm_packus_epi16(_mm_packs_epi32(ints1, ints2), _mm_packs_epi32(ints3, ints4))); /* pack down, store out. */
i -= 16; src += 16; mmdst++;
}
@ -654,14 +642,7 @@ SDL_Convert_F32_to_U8_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 255;
} else if (sample <= -1.0f) {
*dst = 0;
} else {
*dst = (Uint8)((sample + 1.0f) * 127.0f);
}
*dst = (Uint8) ((*src + 1.0f) * 127.0f);
i--; src++; dst++;
}
@ -682,14 +663,7 @@ SDL_Convert_F32_to_S16_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 32767;
} else if (sample <= -1.0f) {
*dst = -32768;
} else {
*dst = (Sint16)(sample * 32767.0f);
}
*dst = (Sint16) (*src * 32767.0f);
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
@ -697,13 +671,11 @@ SDL_Convert_F32_to_S16_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 one = _mm_set1_ps(1.0f);
const __m128 negone = _mm_set1_ps(-1.0f);
const __m128 mulby32767 = _mm_set1_ps(32767.0f);
__m128i *mmdst = (__m128i *) dst;
while (i >= 8) { /* 8 * float32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src+4)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src), mulby32767)); /* load 4 floats, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src+4), mulby32767)); /* load 4 floats, convert to sint32 */
_mm_store_si128(mmdst, _mm_packs_epi32(ints1, ints2)); /* pack to sint16, store out. */
i -= 8; src += 8; mmdst++;
}
@ -712,14 +684,7 @@ SDL_Convert_F32_to_S16_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 32767;
} else if (sample <= -1.0f) {
*dst = -32768;
} else {
*dst = (Sint16)(sample * 32767.0f);
}
*dst = (Sint16) (*src * 32767.0f);
i--; src++; dst++;
}
@ -740,14 +705,7 @@ SDL_Convert_F32_to_U16_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 65535;
} else if (sample <= -1.0f) {
*dst = 0;
} else {
*dst = (Uint16)((sample + 1.0f) * 32767.0f);
}
*dst = (Uint16) ((*src + 1.0f) * 32767.0f);
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
@ -764,12 +722,10 @@ SDL_Convert_F32_to_U16_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
though it looks like dark magic. */
const __m128 mulby32767 = _mm_set1_ps(32767.0f);
const __m128i topbit = _mm_set1_epi16(-32768);
const __m128 one = _mm_set1_ps(1.0f);
const __m128 negone = _mm_set1_ps(-1.0f);
__m128i *mmdst = (__m128i *) dst;
while (i >= 8) { /* 8 * float32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src+4)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src), mulby32767)); /* load 4 floats, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src+4), mulby32767)); /* load 4 floats, convert to sint32 */
_mm_store_si128(mmdst, _mm_xor_si128(_mm_packs_epi32(ints1, ints2), topbit)); /* pack to sint16, xor top bit, store out. */
i -= 8; src += 8; mmdst++;
}
@ -778,14 +734,7 @@ SDL_Convert_F32_to_U16_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 65535;
} else if (sample <= -1.0f) {
*dst = 0;
} else {
*dst = (Uint16)((sample + 1.0f) * 32767.0f);
}
*dst = (Uint16) ((*src + 1.0f) * 32767.0f);
i--; src++; dst++;
}
@ -806,14 +755,7 @@ SDL_Convert_F32_to_S32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 2147483647;
} else if (sample <= -1.0f) {
*dst = (Sint32) -2147483648LL;
} else {
*dst = ((Sint32)(sample * 8388607.0f)) << 8;
}
*dst = (Sint32) (((double) *src) * 2147483647.0);
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
@ -821,12 +763,14 @@ SDL_Convert_F32_to_S32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 one = _mm_set1_ps(1.0f);
const __m128 negone = _mm_set1_ps(-1.0f);
const __m128 mulby8388607 = _mm_set1_ps(8388607.0f);
const __m128d mulby2147483647 = _mm_set1_pd(2147483647.0);
__m128i *mmdst = (__m128i *) dst;
while (i >= 4) { /* 4 * float32 */
_mm_store_si128(mmdst, _mm_slli_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src)), one), mulby8388607)), 8)); /* load 4 floats, clamp, convert to sint32 */
const __m128 floats = _mm_load_ps(src);
/* bitshift the whole register over, so _mm_cvtps_pd can read the top floats in the bottom of the vector. */
const __m128d doubles1 = _mm_mul_pd(_mm_cvtps_pd(_mm_castsi128_ps(_mm_srli_si128(_mm_castps_si128(floats), 8))), mulby2147483647);
const __m128d doubles2 = _mm_mul_pd(_mm_cvtps_pd(floats), mulby2147483647);
_mm_store_si128(mmdst, _mm_or_si128(_mm_slli_si128(_mm_cvtpd_epi32(doubles1), 8), _mm_cvtpd_epi32(doubles2)));
i -= 4; src += 4; mmdst++;
}
dst = (Sint32 *) mmdst;
@ -834,14 +778,7 @@ SDL_Convert_F32_to_S32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 2147483647;
} else if (sample <= -1.0f) {
*dst = (Sint32) -2147483648LL;
} else {
*dst = ((Sint32)(sample * 8388607.0f)) << 8;
}
*dst = (Sint32) (((double) *src) * 2147483647.0);
i--; src++; dst++;
}
@ -852,538 +789,6 @@ SDL_Convert_F32_to_S32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
#endif
#if HAVE_NEON_INTRINSICS
static void SDLCALL
SDL_Convert_S8_to_F32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
const Sint8 *src = ((const Sint8 *) (cvt->buf + cvt->len_cvt)) - 1;
float *dst = ((float *) (cvt->buf + cvt->len_cvt * 4)) - 1;
int i;
LOG_DEBUG_CONVERT("AUDIO_S8", "AUDIO_F32 (using NEON)");
/* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
for (i = cvt->len_cvt; i && (((size_t) (dst-15)) & 15); --i, --src, --dst) {
*dst = ((float) *src) * DIVBY128;
}
src -= 15; dst -= 15; /* adjust to read NEON blocks from the start. */
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do NEON blocks as long as we have 16 bytes available. */
const int8_t *mmsrc = (const int8_t *) src;
const float32x4_t divby128 = vdupq_n_f32(DIVBY128);
while (i >= 16) { /* 16 * 8-bit */
const int8x16_t bytes = vld1q_s8(mmsrc); /* get 16 sint8 into a NEON register. */
const int16x8_t int16hi = vmovl_s8(vget_high_s8(bytes)); /* convert top 8 bytes to 8 int16 */
const int16x8_t int16lo = vmovl_s8(vget_low_s8(bytes)); /* convert bottom 8 bytes to 8 int16 */
/* split int16 to two int32, then convert to float, then multiply to normalize, store. */
vst1q_f32(dst, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_high_s16(int16hi))), divby128));
vst1q_f32(dst+4, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_low_s16(int16hi))), divby128));
vst1q_f32(dst+8, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_high_s16(int16lo))), divby128));
vst1q_f32(dst+12, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_low_s16(int16lo))), divby128));
i -= 16; mmsrc -= 16; dst -= 16;
}
src = (const Sint8 *) mmsrc;
}
src += 15; dst += 15; /* adjust for any scalar finishing. */
/* Finish off any leftovers with scalar operations. */
while (i) {
*dst = ((float) *src) * DIVBY128;
i--; src--; dst--;
}
cvt->len_cvt *= 4;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
}
}
static void SDLCALL
SDL_Convert_U8_to_F32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
const Uint8 *src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
float *dst = ((float *) (cvt->buf + cvt->len_cvt * 4)) - 1;
int i;
LOG_DEBUG_CONVERT("AUDIO_U8", "AUDIO_F32 (using NEON)");
/* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
for (i = cvt->len_cvt; i && (((size_t) (dst-15)) & 15); --i, --src, --dst) {
*dst = (((float) *src) * DIVBY128) - 1.0f;
}
src -= 15; dst -= 15; /* adjust to read NEON blocks from the start. */
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do NEON blocks as long as we have 16 bytes available. */
const uint8_t *mmsrc = (const uint8_t *) src;
const float32x4_t divby128 = vdupq_n_f32(DIVBY128);
const float32x4_t one = vdupq_n_f32(1.0f);
while (i >= 16) { /* 16 * 8-bit */
const uint8x16_t bytes = vld1q_u8(mmsrc); /* get 16 uint8 into a NEON register. */
const uint16x8_t uint16hi = vmovl_u8(vget_high_u8(bytes)); /* convert top 8 bytes to 8 uint16 */
const uint16x8_t uint16lo = vmovl_u8(vget_low_u8(bytes)); /* convert bottom 8 bytes to 8 uint16 */
/* split uint16 to two uint32, then convert to float, then multiply to normalize, subtract to adjust for sign, store. */
vst1q_f32(dst, vmlsq_f32(vcvtq_f32_u32(vmovl_u16(vget_high_u16(uint16hi))), divby128, one));
vst1q_f32(dst+4, vmlsq_f32(vcvtq_f32_u32(vmovl_u16(vget_low_u16(uint16hi))), divby128, one));
vst1q_f32(dst+8, vmlsq_f32(vcvtq_f32_u32(vmovl_u16(vget_high_u16(uint16lo))), divby128, one));
vst1q_f32(dst+12, vmlsq_f32(vcvtq_f32_u32(vmovl_u16(vget_low_u16(uint16lo))), divby128, one));
i -= 16; mmsrc -= 16; dst -= 16;
}
src = (const Uint8 *) mmsrc;
}
src += 15; dst += 15; /* adjust for any scalar finishing. */
/* Finish off any leftovers with scalar operations. */
while (i) {
*dst = (((float) *src) * DIVBY128) - 1.0f;
i--; src--; dst--;
}
cvt->len_cvt *= 4;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
}
}
static void SDLCALL
SDL_Convert_S16_to_F32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
const Sint16 *src = ((const Sint16 *) (cvt->buf + cvt->len_cvt)) - 1;
float *dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
int i;
LOG_DEBUG_CONVERT("AUDIO_S16", "AUDIO_F32 (using NEON)");
/* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
for (i = cvt->len_cvt / sizeof (Sint16); i && (((size_t) (dst-7)) & 15); --i, --src, --dst) {
*dst = ((float) *src) * DIVBY32768;
}
src -= 7; dst -= 7; /* adjust to read NEON blocks from the start. */
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do NEON blocks as long as we have 16 bytes available. */
const float32x4_t divby32768 = vdupq_n_f32(DIVBY32768);
while (i >= 8) { /* 8 * 16-bit */
const int16x8_t ints = vld1q_s16((int16_t const *) src); /* get 8 sint16 into a NEON register. */
/* split int16 to two int32, then convert to float, then multiply to normalize, store. */
vst1q_f32(dst, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_low_s16(ints))), divby32768));
vst1q_f32(dst+4, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_high_s16(ints))), divby32768));
i -= 8; src -= 8; dst -= 8;
}
}
src += 7; dst += 7; /* adjust for any scalar finishing. */
/* Finish off any leftovers with scalar operations. */
while (i) {
*dst = ((float) *src) * DIVBY32768;
i--; src--; dst--;
}
cvt->len_cvt *= 2;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
}
}
static void SDLCALL
SDL_Convert_U16_to_F32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
const Uint16 *src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
float *dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
int i;
LOG_DEBUG_CONVERT("AUDIO_U16", "AUDIO_F32 (using NEON)");
/* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
for (i = cvt->len_cvt / sizeof (Sint16); i && (((size_t) (dst-7)) & 15); --i, --src, --dst) {
*dst = (((float) *src) * DIVBY32768) - 1.0f;
}
src -= 7; dst -= 7; /* adjust to read NEON blocks from the start. */
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do NEON blocks as long as we have 16 bytes available. */
const float32x4_t divby32768 = vdupq_n_f32(DIVBY32768);
const float32x4_t one = vdupq_n_f32(1.0f);
while (i >= 8) { /* 8 * 16-bit */
const uint16x8_t uints = vld1q_u16((uint16_t const *) src); /* get 8 uint16 into a NEON register. */
/* split uint16 to two int32, then convert to float, then multiply to normalize, subtract for sign, store. */
vst1q_f32(dst, vmlsq_f32(one, vcvtq_f32_u32(vmovl_u16(vget_low_u16(uints))), divby32768));
vst1q_f32(dst+4, vmlsq_f32(one, vcvtq_f32_u32(vmovl_u16(vget_high_u16(uints))), divby32768));
i -= 8; src -= 8; dst -= 8;
}
}
src += 7; dst += 7; /* adjust for any scalar finishing. */
/* Finish off any leftovers with scalar operations. */
while (i) {
*dst = (((float) *src) * DIVBY32768) - 1.0f;
i--; src--; dst--;
}
cvt->len_cvt *= 2;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
}
}
static void SDLCALL
SDL_Convert_S32_to_F32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
const Sint32 *src = (const Sint32 *) cvt->buf;
float *dst = (float *) cvt->buf;
int i;
LOG_DEBUG_CONVERT("AUDIO_S32", "AUDIO_F32 (using NEON)");
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (Sint32); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
*dst = ((float) (*src>>8)) * DIVBY8388607;
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
SDL_assert(!i || ((((size_t) src) & 15) == 0));
{
/* Aligned! Do NEON blocks as long as we have 16 bytes available. */
const float32x4_t divby8388607 = vdupq_n_f32(DIVBY8388607);
const int32_t *mmsrc = (const int32_t *) src;
while (i >= 4) { /* 4 * sint32 */
/* shift out lowest bits so int fits in a float32. Small precision loss, but much faster. */
vst1q_f32(dst, vmulq_f32(vcvtq_f32_s32(vshrq_n_s32(vld1q_s32(mmsrc), 8)), divby8388607));
i -= 4; mmsrc += 4; dst += 4;
}
src = (const Sint32 *) mmsrc;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
*dst = ((float) (*src>>8)) * DIVBY8388607;
i--; src++; dst++;
}
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
}
}
static void SDLCALL
SDL_Convert_F32_to_S8_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
const float *src = (const float *) cvt->buf;
Sint8 *dst = (Sint8 *) cvt->buf;
int i;
LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S8 (using NEON)");
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 127;
} else if (sample <= -1.0f) {
*dst = -128;
} else {
*dst = (Sint8)(sample * 127.0f);
}
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do NEON blocks as long as we have 16 bytes available. */
const float32x4_t one = vdupq_n_f32(1.0f);
const float32x4_t negone = vdupq_n_f32(-1.0f);
const float32x4_t mulby127 = vdupq_n_f32(127.0f);
int8_t *mmdst = (int8_t *) dst;
while (i >= 16) { /* 16 * float32 */
const int32x4_t ints1 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const int32x4_t ints2 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src+4)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const int32x4_t ints3 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src+8)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const int32x4_t ints4 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src+12)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const int8x8_t i8lo = vmovn_s16(vcombine_s16(vmovn_s32(ints1), vmovn_s32(ints2))); /* narrow to sint16, combine, narrow to sint8 */
const int8x8_t i8hi = vmovn_s16(vcombine_s16(vmovn_s32(ints3), vmovn_s32(ints4))); /* narrow to sint16, combine, narrow to sint8 */
vst1q_s8(mmdst, vcombine_s8(i8lo, i8hi)); /* combine to int8x16_t, store out */
i -= 16; src += 16; mmdst += 16;
}
dst = (Sint8 *) mmdst;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 127;
} else if (sample <= -1.0f) {
*dst = -128;
} else {
*dst = (Sint8)(sample * 127.0f);
}
i--; src++; dst++;
}
cvt->len_cvt /= 4;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index](cvt, AUDIO_S8);
}
}
static void SDLCALL
SDL_Convert_F32_to_U8_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
const float *src = (const float *) cvt->buf;
Uint8 *dst = (Uint8 *) cvt->buf;
int i;
LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U8 (using NEON)");
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 255;
} else if (sample <= -1.0f) {
*dst = 0;
} else {
*dst = (Uint8)((sample + 1.0f) * 127.0f);
}
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do NEON blocks as long as we have 16 bytes available. */
const float32x4_t one = vdupq_n_f32(1.0f);
const float32x4_t negone = vdupq_n_f32(-1.0f);
const float32x4_t mulby127 = vdupq_n_f32(127.0f);
uint8_t *mmdst = (uint8_t *) dst;
while (i >= 16) { /* 16 * float32 */
const uint32x4_t uints1 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src)), one), one), mulby127)); /* load 4 floats, clamp, convert to uint32 */
const uint32x4_t uints2 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src+4)), one), one), mulby127)); /* load 4 floats, clamp, convert to uint32 */
const uint32x4_t uints3 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src+8)), one), one), mulby127)); /* load 4 floats, clamp, convert to uint32 */
const uint32x4_t uints4 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src+12)), one), one), mulby127)); /* load 4 floats, clamp, convert to uint32 */
const uint8x8_t ui8lo = vmovn_u16(vcombine_u16(vmovn_u32(uints1), vmovn_u32(uints2))); /* narrow to uint16, combine, narrow to uint8 */
const uint8x8_t ui8hi = vmovn_u16(vcombine_u16(vmovn_u32(uints3), vmovn_u32(uints4))); /* narrow to uint16, combine, narrow to uint8 */
vst1q_u8(mmdst, vcombine_u8(ui8lo, ui8hi)); /* combine to uint8x16_t, store out */
i -= 16; src += 16; mmdst += 16;
}
dst = (Uint8 *) mmdst;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 255;
} else if (sample <= -1.0f) {
*dst = 0;
} else {
*dst = (Uint8)((sample + 1.0f) * 127.0f);
}
i--; src++; dst++;
}
cvt->len_cvt /= 4;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index](cvt, AUDIO_U8);
}
}
static void SDLCALL
SDL_Convert_F32_to_S16_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
const float *src = (const float *) cvt->buf;
Sint16 *dst = (Sint16 *) cvt->buf;
int i;
LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S16 (using NEON)");
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 32767;
} else if (sample <= -1.0f) {
*dst = -32768;
} else {
*dst = (Sint16)(sample * 32767.0f);
}
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do NEON blocks as long as we have 16 bytes available. */
const float32x4_t one = vdupq_n_f32(1.0f);
const float32x4_t negone = vdupq_n_f32(-1.0f);
const float32x4_t mulby32767 = vdupq_n_f32(32767.0f);
int16_t *mmdst = (int16_t *) dst;
while (i >= 8) { /* 8 * float32 */
const int32x4_t ints1 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */
const int32x4_t ints2 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src+4)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */
vst1q_s16(mmdst, vcombine_s16(vmovn_s32(ints1), vmovn_s32(ints2))); /* narrow to sint16, combine, store out. */
i -= 8; src += 8; mmdst += 8;
}
dst = (Sint16 *) mmdst;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 32767;
} else if (sample <= -1.0f) {
*dst = -32768;
} else {
*dst = (Sint16)(sample * 32767.0f);
}
i--; src++; dst++;
}
cvt->len_cvt /= 2;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index](cvt, AUDIO_S16SYS);
}
}
static void SDLCALL
SDL_Convert_F32_to_U16_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
const float *src = (const float *) cvt->buf;
Uint16 *dst = (Uint16 *) cvt->buf;
int i;
LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U16 (using NEON)");
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 65535;
} else if (sample <= -1.0f) {
*dst = 0;
} else {
*dst = (Uint16)((sample + 1.0f) * 32767.0f);
}
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
/* Make sure src is aligned too. */
if ((((size_t) src) & 15) == 0) {
/* Aligned! Do NEON blocks as long as we have 16 bytes available. */
const float32x4_t one = vdupq_n_f32(1.0f);
const float32x4_t negone = vdupq_n_f32(-1.0f);
const float32x4_t mulby32767 = vdupq_n_f32(32767.0f);
uint16_t *mmdst = (uint16_t *) dst;
while (i >= 8) { /* 8 * float32 */
const uint32x4_t uints1 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src)), one), one), mulby32767)); /* load 4 floats, clamp, convert to uint32 */
const uint32x4_t uints2 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src+4)), one), one), mulby32767)); /* load 4 floats, clamp, convert to uint32 */
vst1q_u16(mmdst, vcombine_u16(vmovn_u32(uints1), vmovn_u32(uints2))); /* narrow to uint16, combine, store out. */
i -= 8; src += 8; mmdst += 8;
}
dst = (Uint16 *) mmdst;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 65535;
} else if (sample <= -1.0f) {
*dst = 0;
} else {
*dst = (Uint16)((sample + 1.0f) * 32767.0f);
}
i--; src++; dst++;
}
cvt->len_cvt /= 2;
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index](cvt, AUDIO_U16SYS);
}
}
static void SDLCALL
SDL_Convert_F32_to_S32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format)
{
const float *src = (const float *) cvt->buf;
Sint32 *dst = (Sint32 *) cvt->buf;
int i;
LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S32 (using NEON)");
/* Get dst aligned to 16 bytes */
for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 2147483647;
} else if (sample <= -1.0f) {
*dst = -2147483648;
} else {
*dst = ((Sint32)(sample * 8388607.0f)) << 8;
}
}
SDL_assert(!i || ((((size_t) dst) & 15) == 0));
SDL_assert(!i || ((((size_t) src) & 15) == 0));
{
/* Aligned! Do NEON blocks as long as we have 16 bytes available. */
const float32x4_t one = vdupq_n_f32(1.0f);
const float32x4_t negone = vdupq_n_f32(-1.0f);
const float32x4_t mulby8388607 = vdupq_n_f32(8388607.0f);
int32_t *mmdst = (int32_t *) dst;
while (i >= 4) { /* 4 * float32 */
vst1q_s32(mmdst, vshlq_n_s32(vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src)), one), mulby8388607)), 8));
i -= 4; src += 4; mmdst += 4;
}
dst = (Sint32 *) mmdst;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 2147483647;
} else if (sample <= -1.0f) {
*dst = -2147483648;
} else {
*dst = ((Sint32)(sample * 8388607.0f)) << 8;
}
i--; src++; dst++;
}
if (cvt->filters[++cvt->filter_index]) {
cvt->filters[cvt->filter_index](cvt, AUDIO_S32SYS);
}
}
#endif
void SDL_ChooseAudioConverters(void)
{
static SDL_bool converters_chosen = SDL_FALSE;
@ -1412,13 +817,6 @@ void SDL_ChooseAudioConverters(void)
}
#endif
#if HAVE_NEON_INTRINSICS
if (SDL_HasNEON()) {
SET_CONVERTER_FUNCS(NEON);
return;
}
#endif
#if NEED_SCALAR_CONVERTER_FALLBACKS
SET_CONVERTER_FUNCS(Scalar);
#endif

View file

@ -98,10 +98,8 @@ typedef struct SDL_AudioDriverImpl
typedef struct SDL_AudioDeviceItem
{
void *handle;
char *name;
char *original_name;
int dupenum;
struct SDL_AudioDeviceItem *next;
char name[SDL_VARIABLE_LENGTH_ARRAY];
} SDL_AudioDeviceItem;

View file

@ -22,10 +22,6 @@
#if SDL_AUDIO_DRIVER_ALSA
#ifndef SDL_ALSA_NON_BLOCKING
#define SDL_ALSA_NON_BLOCKING 0
#endif
/* Allow access to a raw mixing buffer */
#include <sys/types.h>
@ -94,7 +90,6 @@ static int (*ALSA_snd_pcm_reset)(snd_pcm_t *);
static int (*ALSA_snd_device_name_hint) (int, const char *, void ***);
static char* (*ALSA_snd_device_name_get_hint) (const void *, const char *);
static int (*ALSA_snd_device_name_free_hint) (void **);
static snd_pcm_sframes_t (*ALSA_snd_pcm_avail)(snd_pcm_t *);
#ifdef SND_CHMAP_API_VERSION
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);
@ -163,7 +158,6 @@ load_alsa_syms(void)
SDL_ALSA_SYM(snd_device_name_hint);
SDL_ALSA_SYM(snd_device_name_get_hint);
SDL_ALSA_SYM(snd_device_name_free_hint);
SDL_ALSA_SYM(snd_pcm_avail);
#ifdef SND_CHMAP_API_VERSION
SDL_ALSA_SYM(snd_pcm_get_chmap);
SDL_ALSA_SYM(snd_pcm_chmap_print);
@ -249,24 +243,7 @@ get_audio_device(void *handle, const int channels)
static void
ALSA_WaitDevice(_THIS)
{
#if SDL_ALSA_NON_BLOCKING
const snd_pcm_sframes_t needed = (snd_pcm_sframes_t) this->spec.samples;
while (SDL_AtomicGet(&this->enabled)) {
const snd_pcm_sframes_t rc = ALSA_snd_pcm_avail(this->hidden->pcm_handle);
if ((rc < 0) && (rc != -EAGAIN)) {
/* Hmm, not much we can do - abort */
fprintf(stderr, "ALSA snd_pcm_avail failed (unrecoverable): %s\n",
ALSA_snd_strerror(rc));
SDL_OpenedAudioDeviceDisconnected(this);
return;
} else if (rc < needed) {
const Uint32 delay = ((needed - (SDL_max(rc, 0))) * 1000) / this->spec.freq;
SDL_Delay(SDL_max(delay, 10));
} else {
break; /* ready to go! */
}
}
#endif
/* We're in blocking mode, so there's nothing to do here */
}
@ -445,7 +422,7 @@ static void
ALSA_CloseDevice(_THIS)
{
if (this->hidden->pcm_handle) {
/* Wait for the submitted audio to drain
/* Wait for the submitted audio to drain
ALSA_snd_pcm_drop() can hang, so don't use that.
*/
Uint32 delay = ((this->spec.samples * 1000) / this->spec.freq) * 2;
@ -458,32 +435,10 @@ ALSA_CloseDevice(_THIS)
}
static int
ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params)
ALSA_finalize_hardware(_THIS, snd_pcm_hw_params_t *hwparams, int override)
{
int status;
snd_pcm_hw_params_t *hwparams;
snd_pcm_uframes_t bufsize;
snd_pcm_uframes_t persize;
/* Copy the hardware parameters for this setup */
snd_pcm_hw_params_alloca(&hwparams);
ALSA_snd_pcm_hw_params_copy(hwparams, params);
/* Prioritize matching the period size to the requested buffer size */
persize = this->spec.samples;
status = ALSA_snd_pcm_hw_params_set_period_size_near(
this->hidden->pcm_handle, hwparams, &persize, NULL);
if ( status < 0 ) {
return(-1);
}
/* Next try to restrict the parameters to having only two periods */
bufsize = this->spec.samples * 2;
status = ALSA_snd_pcm_hw_params_set_buffer_size_near(
this->hidden->pcm_handle, hwparams, &bufsize);
if ( status < 0 ) {
return(-1);
}
/* "set" the hardware with the desired parameters */
status = ALSA_snd_pcm_hw_params(this->hidden->pcm_handle, hwparams);
@ -491,12 +446,24 @@ ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params)
return(-1);
}
this->spec.samples = persize;
/* Get samples for the actual buffer size */
status = ALSA_snd_pcm_hw_params_get_buffer_size(hwparams, &bufsize);
if ( status < 0 ) {
return(-1);
}
if ( !override && bufsize != this->spec.samples * 2 ) {
return(-1);
}
/* !!! FIXME: Is this safe to do? */
this->spec.samples = bufsize / 2;
/* This is useful for debugging */
if ( SDL_getenv("SDL_AUDIO_ALSA_DEBUG") ) {
snd_pcm_uframes_t persize = 0;
unsigned int periods = 0;
ALSA_snd_pcm_hw_params_get_period_size(hwparams, &persize, NULL);
ALSA_snd_pcm_hw_params_get_periods(hwparams, &periods, NULL);
fprintf(stderr,
@ -507,6 +474,78 @@ ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params)
return(0);
}
static int
ALSA_set_period_size(_THIS, snd_pcm_hw_params_t *params, int override)
{
const char *env;
int status;
snd_pcm_hw_params_t *hwparams;
snd_pcm_uframes_t frames;
unsigned int periods;
/* Copy the hardware parameters for this setup */
snd_pcm_hw_params_alloca(&hwparams);
ALSA_snd_pcm_hw_params_copy(hwparams, params);
if ( !override ) {
env = SDL_getenv("SDL_AUDIO_ALSA_SET_PERIOD_SIZE");
if ( env ) {
override = SDL_atoi(env);
if ( override == 0 ) {
return(-1);
}
}
}
frames = this->spec.samples;
status = ALSA_snd_pcm_hw_params_set_period_size_near(
this->hidden->pcm_handle, hwparams, &frames, NULL);
if ( status < 0 ) {
return(-1);
}
periods = 2;
status = ALSA_snd_pcm_hw_params_set_periods_near(
this->hidden->pcm_handle, hwparams, &periods, NULL);
if ( status < 0 ) {
return(-1);
}
return ALSA_finalize_hardware(this, hwparams, override);
}
static int
ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params, int override)
{
const char *env;
int status;
snd_pcm_hw_params_t *hwparams;
snd_pcm_uframes_t frames;
/* Copy the hardware parameters for this setup */
snd_pcm_hw_params_alloca(&hwparams);
ALSA_snd_pcm_hw_params_copy(hwparams, params);
if ( !override ) {
env = SDL_getenv("SDL_AUDIO_ALSA_SET_BUFFER_SIZE");
if ( env ) {
override = SDL_atoi(env);
if ( override == 0 ) {
return(-1);
}
}
}
frames = this->spec.samples * 2;
status = ALSA_snd_pcm_hw_params_set_buffer_size_near(
this->hidden->pcm_handle, hwparams, &frames);
if ( status < 0 ) {
return(-1);
}
return ALSA_finalize_hardware(this, hwparams, override);
}
static int
ALSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
{
@ -653,11 +692,14 @@ ALSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
this->spec.freq = rate;
/* Set the buffer size, in samples */
status = ALSA_set_buffer_size(this, hwparams);
if (status < 0) {
return SDL_SetError("Couldn't set hardware audio parameters: %s", ALSA_snd_strerror(status));
if ( ALSA_set_period_size(this, hwparams, 0) < 0 &&
ALSA_set_buffer_size(this, hwparams, 0) < 0 ) {
/* Failed to set desired buffer size, do the best you can... */
status = ALSA_set_period_size(this, hwparams, 1);
if (status < 0) {
return SDL_SetError("Couldn't set hardware audio parameters: %s", ALSA_snd_strerror(status));
}
}
/* Set the software parameters */
snd_pcm_sw_params_alloca(&swparams);
status = ALSA_snd_pcm_sw_params_current(pcm_handle, swparams);
@ -695,11 +737,9 @@ ALSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
SDL_memset(this->hidden->mixbuf, this->spec.silence, this->hidden->mixlen);
}
#if !SDL_ALSA_NON_BLOCKING
if (!iscapture) {
ALSA_snd_pcm_nonblock(pcm_handle, 0);
}
#endif
/* We're ready to rock and roll. :-) */
return 0;

View file

@ -57,9 +57,7 @@ ANDROIDAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
test_format = SDL_FirstAudioFormat(this->spec.format);
while (test_format != 0) { /* no "UNKNOWN" constant */
if ((test_format == AUDIO_U8) ||
(test_format == AUDIO_S16) ||
(test_format == AUDIO_F32)) {
if ((test_format == AUDIO_U8) || (test_format == AUDIO_S16LSB)) {
this->spec.format = test_format;
break;
}
@ -71,8 +69,25 @@ ANDROIDAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
return SDL_SetError("No compatible audio format!");
}
if (Android_JNI_OpenAudioDevice(iscapture, &this->spec) < 0) {
return -1;
if (this->spec.channels > 1) {
this->spec.channels = 2;
} else {
this->spec.channels = 1;
}
if (this->spec.freq < 8000) {
this->spec.freq = 8000;
}
if (this->spec.freq > 48000) {
this->spec.freq = 48000;
}
/* TODO: pass in/return a (Java) device ID */
this->spec.samples = Android_JNI_OpenAudioDevice(iscapture, this->spec.freq, this->spec.format == AUDIO_U8 ? 0 : 1, this->spec.channels, this->spec.samples);
if (this->spec.samples == 0) {
/* Init failed? */
return SDL_SetError("Java-side initialization failed!");
}
SDL_CalculateAudioSpec(&this->spec);

View file

@ -39,7 +39,7 @@
#include "SDL_name.h"
#include "SDL_loadso.h"
#else
#define SDL_NAME(X) X
#define SDL_NAME(X) X
#endif
#ifdef SDL_AUDIO_DRIVER_ARTS_DYNAMIC

View file

@ -45,14 +45,16 @@
struct SDL_PrivateAudioData
{
SDL_Thread *thread;
AudioQueueRef audioQueue;
int numAudioBuffers;
AudioQueueBufferRef *audioBuffer;
void *buffer;
UInt32 bufferOffset;
UInt32 bufferSize;
AudioStreamBasicDescription strdesc;
SDL_bool refill;
SDL_AudioStream *capturestream;
SDL_sem *ready_semaphore;
char *thread_error;
SDL_atomic_t shutdown;
#if MACOSX_COREAUDIO
AudioDeviceID deviceID;
#else

View file

@ -26,7 +26,6 @@
#include "SDL_audio.h"
#include "SDL_hints.h"
#include "SDL_timer.h"
#include "../SDL_audio_c.h"
#include "../SDL_sysaudio.h"
#include "SDL_coreaudio.h"
@ -355,7 +354,7 @@ static BOOL update_audio_session(_THIS, SDL_bool open)
return NO;
}
if (open && (open_playback_devices + open_capture_devices) == 1) {
if (open_playback_devices + open_capture_devices == 1) {
if (![session setActive:YES error:&err]) {
NSString *desc = err.description;
SDL_SetError("Could not activate Audio Session: %s", desc.UTF8String);
@ -392,10 +391,10 @@ static BOOL update_audio_session(_THIS, SDL_bool open)
if (this->hidden->interruption_listener != NULL) {
SDLInterruptionListener *listener = nil;
listener = (SDLInterruptionListener *) CFBridgingRelease(this->hidden->interruption_listener);
[center removeObserver:listener];
@synchronized (listener) {
listener.device = NULL;
}
[center removeObserver:listener];
}
}
}
@ -410,27 +409,43 @@ static void
outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer)
{
SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData;
SDL_assert(inBuffer->mAudioDataBytesCapacity == this->hidden->bufferSize);
SDL_memcpy(inBuffer->mAudioData, this->hidden->buffer, this->hidden->bufferSize);
SDL_memset(this->hidden->buffer, '\0', this->hidden->bufferSize); /* zero out in case we have to fill again without new data. */
inBuffer->mAudioDataByteSize = this->hidden->bufferSize;
AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
this->hidden->refill = SDL_TRUE;
}
static Uint8 *
COREAUDIO_GetDeviceBuf(_THIS)
{
return this->hidden->buffer;
}
static void
COREAUDIO_WaitDevice(_THIS)
{
while (SDL_AtomicGet(&this->enabled) && !this->hidden->refill) {
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1);
if (SDL_AtomicGet(&this->hidden->shutdown)) {
return; /* don't do anything. */
}
this->hidden->refill = SDL_FALSE;
if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) {
/* Supply silence if audio is not enabled or paused */
SDL_memset(inBuffer->mAudioData, this->spec.silence, inBuffer->mAudioDataBytesCapacity);
} else {
UInt32 remaining = inBuffer->mAudioDataBytesCapacity;
Uint8 *ptr = (Uint8 *) inBuffer->mAudioData;
while (remaining > 0) {
UInt32 len;
if (this->hidden->bufferOffset >= this->hidden->bufferSize) {
/* Generate the data */
SDL_LockMutex(this->mixer_lock);
(*this->callbackspec.callback)(this->callbackspec.userdata,
this->hidden->buffer, this->hidden->bufferSize);
SDL_UnlockMutex(this->mixer_lock);
this->hidden->bufferOffset = 0;
}
len = this->hidden->bufferSize - this->hidden->bufferOffset;
if (len > remaining) {
len = remaining;
}
SDL_memcpy(ptr, (char *)this->hidden->buffer +
this->hidden->bufferOffset, len);
ptr = ptr + len;
remaining -= len;
this->hidden->bufferOffset += len;
}
}
AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
inBuffer->mAudioDataByteSize = inBuffer->mAudioDataBytesCapacity;
}
static void
@ -439,46 +454,36 @@ inputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer
const AudioStreamPacketDescription *inPacketDescs )
{
SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData;
if (SDL_AtomicGet(&this->enabled)) {
SDL_AudioStream *stream = this->hidden->capturestream;
if (SDL_AudioStreamPut(stream, inBuffer->mAudioData, inBuffer->mAudioDataByteSize) == -1) {
/* yikes, out of memory or something. I guess drop the buffer. Our WASAPI target kills the device in this case, though */
}
AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
this->hidden->refill = SDL_TRUE;
}
}
static int
COREAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
{
SDL_AudioStream *stream = this->hidden->capturestream;
while (SDL_AtomicGet(&this->enabled)) {
const int avail = SDL_AudioStreamAvailable(stream);
if (avail > 0) {
const int cpy = SDL_min(buflen, avail);
SDL_AudioStreamGet(stream, buffer, cpy);
return cpy;
}
/* wait for more data, try again. */
while (SDL_AtomicGet(&this->enabled) && !this->hidden->refill) {
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1);
}
this->hidden->refill = SDL_FALSE;
if (SDL_AtomicGet(&this->shutdown)) {
return; /* don't do anything. */
}
return 0; /* not enabled, giving up. */
}
/* ignore unless we're active. */
if (!SDL_AtomicGet(&this->paused) && SDL_AtomicGet(&this->enabled) && !SDL_AtomicGet(&this->paused)) {
const Uint8 *ptr = (const Uint8 *) inBuffer->mAudioData;
UInt32 remaining = inBuffer->mAudioDataByteSize;
while (remaining > 0) {
UInt32 len = this->hidden->bufferSize - this->hidden->bufferOffset;
if (len > remaining) {
len = remaining;
}
static void
COREAUDIO_FlushCapture(_THIS)
{
while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, 1) == kCFRunLoopRunHandledSource) {
/* spin. */
SDL_memcpy((char *)this->hidden->buffer + this->hidden->bufferOffset, ptr, len);
ptr += len;
remaining -= len;
this->hidden->bufferOffset += len;
if (this->hidden->bufferOffset >= this->hidden->bufferSize) {
SDL_LockMutex(this->mixer_lock);
(*this->callbackspec.callback)(this->callbackspec.userdata, this->hidden->buffer, this->hidden->bufferSize);
SDL_UnlockMutex(this->mixer_lock);
this->hidden->bufferOffset = 0;
}
}
}
this->hidden->refill = SDL_FALSE;
SDL_AudioStreamClear(this->hidden->capturestream);
AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
}
@ -536,16 +541,25 @@ COREAUDIO_CloseDevice(_THIS)
update_audio_session(this, SDL_FALSE);
#endif
/* if callback fires again, feed silence; don't call into the app. */
SDL_AtomicSet(&this->paused, 1);
if (this->hidden->audioQueue) {
AudioQueueDispose(this->hidden->audioQueue, 1);
}
if (this->hidden->capturestream) {
SDL_FreeAudioStream(this->hidden->capturestream);
if (this->hidden->thread) {
SDL_AtomicSet(&this->hidden->shutdown, 1);
SDL_WaitThread(this->hidden->thread, NULL);
}
if (this->hidden->ready_semaphore) {
SDL_DestroySemaphore(this->hidden->ready_semaphore);
}
/* AudioQueueDispose() frees the actual buffer objects. */
SDL_free(this->hidden->audioBuffer);
SDL_free(this->hidden->thread_error);
SDL_free(this->hidden->buffer);
SDL_free(this->hidden);
@ -611,8 +625,6 @@ prepare_device(_THIS, void *handle, int iscapture)
}
#endif
/* this all happens in the audio thread, since it needs a separate runloop. */
static int
prepare_audioqueue(_THIS)
{
@ -652,6 +664,19 @@ prepare_audioqueue(_THIS)
}
#endif
/* Calculate the final parameters for this audio specification */
SDL_CalculateAudioSpec(&this->spec);
/* Allocate a sample buffer */
this->hidden->bufferSize = this->spec.size;
this->hidden->bufferOffset = iscapture ? 0 : this->hidden->bufferSize;
this->hidden->buffer = SDL_malloc(this->hidden->bufferSize);
if (this->hidden->buffer == NULL) {
SDL_OutOfMemory();
return 0;
}
/* Make sure we can feed the device a minimum amount of time */
double MINIMUM_AUDIO_BUFFER_TIME_MS = 15.0;
#if defined(__IPHONEOS__)
@ -666,7 +691,6 @@ prepare_audioqueue(_THIS)
numAudioBuffers = ((int)SDL_ceil(MINIMUM_AUDIO_BUFFER_TIME_MS / msecs) * 2);
}
this->hidden->numAudioBuffers = numAudioBuffers;
this->hidden->audioBuffer = SDL_calloc(1, sizeof (AudioQueueBufferRef) * numAudioBuffers);
if (this->hidden->audioBuffer == NULL) {
SDL_OutOfMemory();
@ -693,23 +717,29 @@ prepare_audioqueue(_THIS)
return 1;
}
static void
COREAUDIO_ThreadInit(_THIS)
static int
audioqueue_thread(void *arg)
{
SDL_AudioDevice *this = (SDL_AudioDevice *) arg;
const int rc = prepare_audioqueue(this);
if (!rc) {
/* !!! FIXME: do this in RunAudio, and maybe block OpenDevice until ThreadInit finishes, too, to report an opening error */
SDL_OpenedAudioDeviceDisconnected(this); /* oh well. */
this->hidden->thread_error = SDL_strdup(SDL_GetError());
SDL_SemPost(this->hidden->ready_semaphore);
return 0;
}
}
static void
COREAUDIO_PrepareToClose(_THIS)
{
/* run long enough to queue some silence, so we know our actual audio
has been played */
CFRunLoopRunInMode(kCFRunLoopDefaultMode, (((this->spec.samples * 1000) / this->spec.freq) * 2) / 1000.0f, 0);
AudioQueueStop(this->hidden->audioQueue, 1);
/* init was successful, alert parent thread and start running... */
SDL_SemPost(this->hidden->ready_semaphore);
while (!SDL_AtomicGet(&this->hidden->shutdown)) {
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1);
}
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;
CFRunLoopRunInMode(kCFRunLoopDefaultMode, secs, 0);
}
return 0;
}
static int
@ -796,23 +826,28 @@ COREAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
}
#endif
/* Calculate the final parameters for this audio specification */
SDL_CalculateAudioSpec(&this->spec);
if (iscapture) {
this->hidden->capturestream = SDL_NewAudioStream(this->spec.format, this->spec.channels, this->spec.freq, this->spec.format, this->spec.channels, this->spec.freq);
if (!this->hidden->capturestream) {
return -1; /* already set SDL_Error */
}
} else {
this->hidden->bufferSize = this->spec.size;
this->hidden->buffer = SDL_malloc(this->hidden->bufferSize);
if (this->hidden->buffer == NULL) {
return SDL_OutOfMemory();
}
/* This has to init in a new thread so it can get its own CFRunLoop. :/ */
SDL_AtomicSet(&this->hidden->shutdown, 0);
this->hidden->ready_semaphore = SDL_CreateSemaphore(0);
if (!this->hidden->ready_semaphore) {
return -1; /* oh well. */
}
return 0;
this->hidden->thread = SDL_CreateThreadInternal(audioqueue_thread, "AudioQueue thread", 512 * 1024, this);
if (!this->hidden->thread) {
return -1;
}
SDL_SemWait(this->hidden->ready_semaphore);
SDL_DestroySemaphore(this->hidden->ready_semaphore);
this->hidden->ready_semaphore = NULL;
if ((this->hidden->thread != NULL) && (this->hidden->thread_error != NULL)) {
SDL_SetError("%s", this->hidden->thread_error);
return -1;
}
return (this->hidden->thread != NULL) ? 0 : -1;
}
static void
@ -832,12 +867,6 @@ COREAUDIO_Init(SDL_AudioDriverImpl * impl)
impl->OpenDevice = COREAUDIO_OpenDevice;
impl->CloseDevice = COREAUDIO_CloseDevice;
impl->Deinitialize = COREAUDIO_Deinitialize;
impl->ThreadInit = COREAUDIO_ThreadInit;
impl->WaitDevice = COREAUDIO_WaitDevice;
impl->GetDeviceBuf = COREAUDIO_GetDeviceBuf;
impl->PrepareToClose = COREAUDIO_PrepareToClose;
impl->CaptureFromDevice = COREAUDIO_CaptureFromDevice;
impl->FlushCapture = COREAUDIO_FlushCapture;
#if MACOSX_COREAUDIO
impl->DetectDevices = COREAUDIO_DetectDevices;
@ -847,6 +876,7 @@ COREAUDIO_Init(SDL_AudioDriverImpl * impl)
impl->OnlyHasDefaultCaptureDevice = 1;
#endif
impl->ProvidesOwnCallbackThread = 1;
impl->HasCaptureSupport = 1;
return 1; /* this audio target is available. */

View file

@ -477,8 +477,8 @@ DSOUND_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
SDL_bool tried_format = SDL_FALSE;
SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
LPGUID guid = (LPGUID) handle;
DWORD bufsize;
DWORD bufsize;
/* Initialize all variables that we clean on shutdown */
this->hidden = (struct SDL_PrivateAudioData *)
SDL_malloc((sizeof *this->hidden));
@ -526,7 +526,7 @@ DSOUND_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
(int) (DSBSIZE_MAX / numchunks));
} else {
int rc;
WAVEFORMATEX wfmt;
WAVEFORMATEX wfmt;
SDL_zero(wfmt);
if (SDL_AUDIO_ISFLOAT(this->spec.format)) {
wfmt.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;

View file

@ -44,9 +44,7 @@ static const char ** (*JACK_jack_get_ports) (jack_client_t *, const char *, cons
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_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 const char * (*JACK_jack_port_name) (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_set_process_callback) (jack_client_t *, JackProcessCallback, void *);
@ -137,9 +135,7 @@ load_jack_syms(void)
SDL_JACK_SYM(jack_get_sample_rate);
SDL_JACK_SYM(jack_get_buffer_size);
SDL_JACK_SYM(jack_port_register);
SDL_JACK_SYM(jack_port_by_name);
SDL_JACK_SYM(jack_port_name);
SDL_JACK_SYM(jack_port_type);
SDL_JACK_SYM(jack_connect);
SDL_JACK_SYM(jack_set_process_callback);
return 0;
@ -277,6 +273,10 @@ JACK_CloseDevice(_THIS)
SDL_DestroySemaphore(this->hidden->iosem);
}
if (this->hidden->devports) {
JACK_jack_free(this->hidden->devports);
}
SDL_free(this->hidden->iobuffer);
}
@ -292,11 +292,9 @@ JACK_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
const JackProcessCallback callback = iscapture ? jackProcessCaptureCallback : jackProcessPlaybackCallback;
const char *sdlportstr = iscapture ? "input" : "output";
const char **devports = NULL;
int *audio_ports;
jack_client_t *client = NULL;
jack_status_t status;
int channels = 0;
int ports = 0;
int i;
/* Initialize all variables that we clean on shutdown */
@ -313,30 +311,15 @@ JACK_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
}
devports = JACK_jack_get_ports(client, NULL, NULL, JackPortIsPhysical | sysportflags);
this->hidden->devports = devports;
if (!devports || !devports[0]) {
return SDL_SetError("No physical JACK ports available");
}
while (devports[++ports]) {
while (devports[++channels]) {
/* spin to count devports */
}
/* Filter out non-audio ports */
audio_ports = SDL_calloc(ports, sizeof *audio_ports);
for (i = 0; i < ports; i++) {
const jack_port_t *dport = JACK_jack_port_by_name(client, devports[i]);
const char *type = JACK_jack_port_type(dport);
const int len = SDL_strlen(type);
/* See if type ends with "audio" */
if (len >= 5 && !SDL_memcmp(type+len-5, "audio", 5)) {
audio_ports[channels++] = i;
}
}
if (channels == 0) {
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." */
/* Jack pretty much demands what it wants. */
@ -385,16 +368,16 @@ JACK_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
/* once activated, we can connect all the ports. */
for (i = 0; i < channels; i++) {
const char *sdlport = JACK_jack_port_name(this->hidden->sdlports[i]);
const char *srcport = iscapture ? devports[audio_ports[i]] : sdlport;
const char *dstport = iscapture ? sdlport : devports[audio_ports[i]];
const char *srcport = iscapture ? devports[i] : sdlport;
const char *dstport = iscapture ? sdlport : devports[i];
if (JACK_jack_connect(client, srcport, dstport) != 0) {
return SDL_SetError("Couldn't connect JACK ports: %s => %s", srcport, dstport);
}
}
/* don't need these anymore. */
this->hidden->devports = NULL;
JACK_jack_free(devports);
SDL_free(audio_ports);
/* We're ready to rock and roll. :-) */
return 0;

View file

@ -33,6 +33,7 @@ struct SDL_PrivateAudioData
jack_client_t *client;
SDL_sem *iosem;
float *iobuffer;
const char **devports;
jack_port_t **sdlports;
};

View file

@ -109,7 +109,7 @@ static pa_operation * (*PULSEAUDIO_pa_stream_drain) (pa_stream *,
pa_stream_success_cb_t, void *);
static int (*PULSEAUDIO_pa_stream_peek) (pa_stream *, const void **, size_t *);
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 *);
static int (*PULSEAUDIO_pa_stream_disconnect) (pa_stream *);
static void (*PULSEAUDIO_pa_stream_unref) (pa_stream *);

View file

@ -725,12 +725,6 @@ WASAPI_ThreadDeinit(_THIS)
WASAPI_PlatformThreadDeinit(this);
}
void
WASAPI_BeginLoopIteration(_THIS)
{
/* no-op. */
}
static void
WASAPI_Deinitialize(void)
{

View file

@ -351,42 +351,10 @@ WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
}
typedef struct
{
LPWSTR devid;
char *devname;
} EndpointItem;
static int sort_endpoints(const void *_a, const void *_b)
{
LPWSTR a = ((const EndpointItem *) _a)->devid;
LPWSTR b = ((const EndpointItem *) _b)->devid;
if (!a && b) {
return -1;
} else if (a && !b) {
return 1;
}
while (SDL_TRUE) {
if (*a < *b) {
return -1;
} else if (*a > *b) {
return 1;
} else if (*a == 0) {
break;
}
a++;
b++;
}
return 0;
}
static void
WASAPI_EnumerateEndpointsForFlow(const SDL_bool iscapture)
{
IMMDeviceCollection *collection = NULL;
EndpointItem *items;
UINT i, total;
/* Note that WASAPI separates "adapter devices" from "audio endpoint devices"
@ -401,36 +369,22 @@ WASAPI_EnumerateEndpointsForFlow(const SDL_bool iscapture)
return;
}
items = (EndpointItem *) SDL_calloc(total, sizeof (EndpointItem));
if (!items) {
return; /* oh well. */
}
for (i = 0; i < total; i++) {
EndpointItem *item = items + i;
IMMDevice *device = NULL;
if (SUCCEEDED(IMMDeviceCollection_Item(collection, i, &device))) {
if (SUCCEEDED(IMMDevice_GetId(device, &item->devid))) {
item->devname = GetWasapiDeviceName(device);
LPWSTR devid = NULL;
if (SUCCEEDED(IMMDevice_GetId(device, &devid))) {
char *devname = GetWasapiDeviceName(device);
if (devname) {
WASAPI_AddDevice(iscapture, devname, devid);
SDL_free(devname);
}
CoTaskMemFree(devid);
}
IMMDevice_Release(device);
}
}
/* sort the list of devices by their guid so list is consistent between runs */
SDL_qsort(items, total, sizeof (*items), sort_endpoints);
/* Send the sorted list on to the SDL's higher level. */
for (i = 0; i < total; i++) {
EndpointItem *item = items + i;
if ((item->devid) && (item->devname)) {
WASAPI_AddDevice(iscapture, item->devname, item->devid);
}
SDL_free(item->devname);
CoTaskMemFree(item->devid);
}
SDL_free(items);
IMMDeviceCollection_Release(collection);
}
@ -451,6 +405,12 @@ WASAPI_PlatformDeleteActivationHandler(void *handler)
SDL_assert(!"This function should have only been called on WinRT.");
}
void
WASAPI_BeginLoopIteration(_THIS)
{
/* no-op. */
}
#endif /* SDL_AUDIO_DRIVER_WASAPI && !defined(__WINRT__) */
/* vi: set ts=4 sw=4 expandtab: */

View file

@ -185,9 +185,20 @@ struct SDL_WasapiActivationHandler : public RuntimeClass< RuntimeClassFlags< Cla
HRESULT
SDL_WasapiActivationHandler::ActivateCompleted(IActivateAudioInterfaceAsyncOperation *async)
{
// Just set a flag, since we're probably in a different thread. We'll pick it up and init everything on our own thread to prevent races.
SDL_AtomicSet(&device->hidden->just_activated, 1);
HRESULT result = S_OK;
IUnknown *iunknown = nullptr;
const HRESULT ret = async->GetActivateResult(&result, &iunknown);
if (SUCCEEDED(ret) && SUCCEEDED(result)) {
iunknown->QueryInterface(IID_PPV_ARGS(&device->hidden->client));
if (device->hidden->client) {
// Just set a flag, since we're probably in a different thread. We'll pick it up and init everything on our own thread to prevent races.
SDL_AtomicSet(&device->hidden->just_activated, 1);
}
}
WASAPI_UnrefDevice(device);
return S_OK;
}
@ -225,49 +236,29 @@ WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
IActivateAudioInterfaceAsyncOperation *async = nullptr;
const HRESULT ret = ActivateAudioInterfaceAsync(devid, __uuidof(IAudioClient), nullptr, handler.Get(), &async);
if (FAILED(ret) || async == nullptr) {
if (async != nullptr) {
async->Release();
}
if (async != nullptr) {
async->Release();
}
if (FAILED(ret)) {
handler.Get()->Release();
WASAPI_UnrefDevice(_this);
return WIN_SetErrorFromHRESULT("WASAPI can't activate requested audio endpoint", ret);
}
/* Spin until the async operation is complete.
* If we don't PrepDevice before leaving this function, the bug list gets LONG:
* - device.spec is not filled with the correct information
* - The 'obtained' spec will be wrong for ALLOW_CHANGE properties
* - SDL_AudioStreams will/will not be allocated at the right time
* - SDL_assert(device->callbackspec.size == device->spec.size) will fail
* - When the assert is ignored, skipping or a buffer overflow will occur
*/
while (!SDL_AtomicCAS(&_this->hidden->just_activated, 1, 0)) {
SDL_Delay(1);
}
HRESULT activateRes = S_OK;
IUnknown *iunknown = nullptr;
const HRESULT getActivateRes = async->GetActivateResult(&activateRes, &iunknown);
async->Release();
if (FAILED(getActivateRes)) {
return WIN_SetErrorFromHRESULT("Failed to get WASAPI activate result", getActivateRes);
} else if (FAILED(activateRes)) {
return WIN_SetErrorFromHRESULT("Failed to activate WASAPI device", activateRes);
}
iunknown->QueryInterface(IID_PPV_ARGS(&_this->hidden->client));
if (!_this->hidden->client) {
return SDL_SetError("Failed to query WASAPI client interface");
}
if (WASAPI_PrepDevice(_this, isrecovery) == -1) {
return -1;
}
return 0;
}
void
WASAPI_BeginLoopIteration(_THIS)
{
if (SDL_AtomicCAS(&_this->hidden->just_activated, 1, 0)) {
if (WASAPI_PrepDevice(_this, SDL_TRUE) == -1) {
SDL_OpenedAudioDeviceDisconnected(_this);
}
}
}
void
WASAPI_PlatformThreadInit(_THIS)
{

View file

@ -78,7 +78,7 @@ static void DetectWave##typ##Devs(void) { \
capstyp##2W caps; \
UINT i; \
for (i = 0; i < devcount; i++) { \
if (wave##typ##GetDevCaps(i,(LP##capstyp##W)&caps,sizeof(caps))==MMSYSERR_NOERROR) { \
if (wave##typ##GetDevCaps(i,(LP##capstyp##W)&caps,sizeof(caps))==MMSYSERR_NOERROR) { \
char *name = WIN_LookupAudioDeviceName(caps.szPname,&caps.NameGuid); \
if (name != NULL) { \
SDL_AddAudioDevice((int) iscapture, name, (void *) ((size_t) i+1)); \
@ -375,7 +375,8 @@ WINMM_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
#endif
/* Create the audio buffer semaphore */
this->hidden->audio_sem = CreateSemaphore(NULL, iscapture ? 0 : NUM_BUFFERS - 1, NUM_BUFFERS, NULL);
this->hidden->audio_sem =
CreateSemaphore(NULL, iscapture ? 0 : NUM_BUFFERS - 1, NUM_BUFFERS, NULL);
if (this->hidden->audio_sem == NULL) {
return SDL_SetError("Couldn't create semaphore");
}

View file

@ -61,10 +61,6 @@
#define SDL_JAVA_CONTROLLER_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLControllerManager, function)
#define SDL_JAVA_INTERFACE_INPUT_CONNECTION(function) CONCAT1(SDL_JAVA_PREFIX, SDLInputConnection, function)
/* Audio encoding definitions */
#define ENCODING_PCM_8BIT 3
#define ENCODING_PCM_16BIT 2
#define ENCODING_PCM_FLOAT 4
/* Java class SDLActivity */
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(
@ -80,8 +76,7 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeResize)(
JNIEnv* env, jclass jcls,
jint surfaceWidth, jint surfaceHeight,
jint deviceWidth, jint deviceHeight, jint format, jfloat rate);
jint width, jint height, jint format, jfloat rate);
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceChanged)(
JNIEnv* env, jclass jcls);
@ -107,7 +102,7 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeMouse)(
JNIEnv* env, jclass jcls,
jint button, jint action, jfloat x, jfloat y, jboolean relative);
jint button, jint action, jfloat x, jfloat y);
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeAccel)(
JNIEnv* env, jclass jcls,
@ -139,19 +134,11 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetenv)(
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeEnvironmentVariablesSet)(
JNIEnv* env, jclass cls);
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeOrientationChanged)(
JNIEnv* env, jclass cls,
jint orientation);
/* Java class SDLInputConnection */
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText)(
JNIEnv* env, jclass cls,
jstring text, jint newCursorPosition);
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeGenerateScancodeForUnichar)(
JNIEnv* env, jclass cls,
jchar chUnicode);
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeSetComposingText)(
JNIEnv* env, jclass cls,
jstring text, jint newCursorPosition);
@ -182,8 +169,8 @@ JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeHat)(
JNIEXPORT jint JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddJoystick)(
JNIEnv* env, jclass jcls,
jint device_id, jstring device_name, jstring device_desc, jint vendor_id, jint product_id,
jboolean is_accelerometer, jint button_mask, jint naxes, jint nhats, jint nballs);
jint device_id, jstring device_name, jstring device_desc, jint is_accelerometer,
jint nbuttons, jint naxes, jint nhats, jint nballs);
JNIEXPORT jint JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveJoystick)(
JNIEnv* env, jclass jcls,
@ -203,7 +190,6 @@ JNIEXPORT jint JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveHaptic)(
/* #define DEBUG_JNI */
static void Android_JNI_ThreadDestroyed(void*);
static void checkJNIReady(void);
/*******************************************************************************
This file links the Java side of Android with libsdl
@ -226,11 +212,7 @@ static jmethodID midSetActivityTitle;
static jmethodID midSetWindowStyle;
static jmethodID midSetOrientation;
static jmethodID midGetContext;
static jmethodID midIsTablet;
static jmethodID midIsAndroidTV;
static jmethodID midIsChromebook;
static jmethodID midIsDeXMode;
static jmethodID midManualBackButton;
static jmethodID midInputGetInputDeviceIds;
static jmethodID midSendMessage;
static jmethodID midShowTextInput;
@ -241,25 +223,18 @@ static jmethodID midClipboardHasText;
static jmethodID midOpenAPKExpansionInputStream;
static jmethodID midGetManifestEnvironmentVariables;
static jmethodID midGetDisplayDPI;
static jmethodID midCreateCustomCursor;
static jmethodID midSetCustomCursor;
static jmethodID midSetSystemCursor;
static jmethodID midSupportsRelativeMouse;
static jmethodID midSetRelativeMouseEnabled;
/* audio manager */
static jclass mAudioManagerClass;
/* method signatures */
static jmethodID midAudioOpen;
static jmethodID midAudioWriteByteBuffer;
static jmethodID midAudioWriteShortBuffer;
static jmethodID midAudioWriteFloatBuffer;
static jmethodID midAudioWriteByteBuffer;
static jmethodID midAudioClose;
static jmethodID midCaptureOpen;
static jmethodID midCaptureReadByteBuffer;
static jmethodID midCaptureReadShortBuffer;
static jmethodID midCaptureReadFloatBuffer;
static jmethodID midCaptureReadByteBuffer;
static jmethodID midCaptureClose;
/* controller manager */
@ -269,7 +244,6 @@ static jclass mControllerManagerClass;
static jmethodID midPollInputDevices;
static jmethodID midPollHapticDevices;
static jmethodID midHapticRun;
static jmethodID midHapticStop;
/* static fields */
static jfieldID fidSeparateMouseAndTouch;
@ -335,16 +309,8 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(JNIEnv* mEnv, jclass c
"setOrientation","(IIZLjava/lang/String;)V");
midGetContext = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
"getContext","()Landroid/content/Context;");
midIsTablet = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
"isTablet", "()Z");
midIsAndroidTV = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
"isAndroidTV","()Z");
midIsChromebook = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
"isChromebook", "()Z");
midIsDeXMode = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
"isDeXMode", "()Z");
midManualBackButton = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
"manualBackButton", "()V");
midInputGetInputDeviceIds = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
"inputGetInputDeviceIds", "(I)[I");
midSendMessage = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
@ -366,21 +332,13 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(JNIEnv* mEnv, jclass c
"getManifestEnvironmentVariables", "()Z");
midGetDisplayDPI = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass, "getDisplayDPI", "()Landroid/util/DisplayMetrics;");
midCreateCustomCursor = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass, "createCustomCursor", "([IIIII)I");
midSetCustomCursor = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass, "setCustomCursor", "(I)Z");
midSetSystemCursor = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass, "setSystemCursor", "(I)Z");
midSupportsRelativeMouse = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass, "supportsRelativeMouse", "()Z");
midSetRelativeMouseEnabled = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass, "setRelativeMouseEnabled", "(Z)Z");
midGetDisplayDPI = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass, "getDisplayDPI", "()Landroid/util/DisplayMetrics;");
if (!midGetNativeSurface ||
!midSetActivityTitle || !midSetWindowStyle || !midSetOrientation || !midGetContext || !midIsTablet || !midIsAndroidTV || !midInputGetInputDeviceIds ||
!midSetActivityTitle || !midSetWindowStyle || !midSetOrientation || !midGetContext || !midIsAndroidTV || !midInputGetInputDeviceIds ||
!midSendMessage || !midShowTextInput || !midIsScreenKeyboardShown ||
!midClipboardSetText || !midClipboardGetText || !midClipboardHasText ||
!midOpenAPKExpansionInputStream || !midGetManifestEnvironmentVariables || !midGetDisplayDPI ||
!midCreateCustomCursor || !midSetCustomCursor || !midSetSystemCursor || !midSupportsRelativeMouse || !midSetRelativeMouseEnabled ||
!midIsChromebook || !midIsDeXMode || !midManualBackButton) {
!midOpenAPKExpansionInputStream || !midGetManifestEnvironmentVariables|| !midGetDisplayDPI) {
__android_log_print(ANDROID_LOG_WARN, "SDL", "Missing some Java callbacks, do you have the latest version of SDLActivity.java?");
}
@ -403,28 +361,24 @@ JNIEXPORT void JNICALL SDL_JAVA_AUDIO_INTERFACE(nativeSetupJNI)(JNIEnv* mEnv, jc
mAudioManagerClass = (jclass)((*mEnv)->NewGlobalRef(mEnv, cls));
midAudioOpen = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"audioOpen", "(IIII)[I");
midAudioWriteByteBuffer = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"audioWriteByteBuffer", "([B)V");
"audioOpen", "(IZZI)I");
midAudioWriteShortBuffer = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"audioWriteShortBuffer", "([S)V");
midAudioWriteFloatBuffer = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"audioWriteFloatBuffer", "([F)V");
midAudioWriteByteBuffer = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"audioWriteByteBuffer", "([B)V");
midAudioClose = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"audioClose", "()V");
midCaptureOpen = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"captureOpen", "(IIII)[I");
midCaptureReadByteBuffer = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"captureReadByteBuffer", "([BZ)I");
"captureOpen", "(IZZI)I");
midCaptureReadShortBuffer = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"captureReadShortBuffer", "([SZ)I");
midCaptureReadFloatBuffer = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"captureReadFloatBuffer", "([FZ)I");
midCaptureReadByteBuffer = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"captureReadByteBuffer", "([BZ)I");
midCaptureClose = (*mEnv)->GetStaticMethodID(mEnv, mAudioManagerClass,
"captureClose", "()V");
if (!midAudioOpen || !midAudioWriteByteBuffer || !midAudioWriteShortBuffer || !midAudioWriteFloatBuffer || !midAudioClose ||
!midCaptureOpen || !midCaptureReadByteBuffer || !midCaptureReadShortBuffer || !midCaptureReadFloatBuffer || !midCaptureClose) {
if (!midAudioOpen || !midAudioWriteShortBuffer || !midAudioWriteByteBuffer || !midAudioClose ||
!midCaptureOpen || !midCaptureReadShortBuffer || !midCaptureReadByteBuffer || !midCaptureClose) {
__android_log_print(ANDROID_LOG_WARN, "SDL", "Missing some Java callbacks, do you have the latest version of SDLAudioManager.java?");
}
@ -445,11 +399,9 @@ JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeSetupJNI)(JNIEnv* mEn
midPollHapticDevices = (*mEnv)->GetStaticMethodID(mEnv, mControllerManagerClass,
"pollHapticDevices", "()V");
midHapticRun = (*mEnv)->GetStaticMethodID(mEnv, mControllerManagerClass,
"hapticRun", "(IFI)V");
midHapticStop = (*mEnv)->GetStaticMethodID(mEnv, mControllerManagerClass,
"hapticStop", "(I)V");
"hapticRun", "(II)V");
if (!midPollInputDevices || !midPollHapticDevices || !midHapticRun || !midHapticStop) {
if (!midPollInputDevices || !midPollHapticDevices || !midHapticRun) {
__android_log_print(ANDROID_LOG_WARN, "SDL", "Missing some Java callbacks, do you have the latest version of SDLControllerManager.java?");
}
@ -551,18 +503,9 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
/* Resize */
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeResize)(
JNIEnv* env, jclass jcls,
jint surfaceWidth, jint surfaceHeight,
jint deviceWidth, jint deviceHeight, jint format, jfloat rate)
jint width, jint height, jint format, jfloat rate)
{
Android_SetScreenResolution(surfaceWidth, surfaceHeight, deviceWidth, deviceHeight, format, rate);
}
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeOrientationChanged)(
JNIEnv *env, jclass jcls,
jint orientation)
{
SDL_VideoDisplay *display = SDL_GetDisplay(0);
SDL_SendDisplayEvent(display, SDL_DISPLAYEVENT_ORIENTATION, orientation);
Android_SetScreenResolution(width, height, format, rate);
}
/* Paddown */
@ -600,15 +543,14 @@ JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeHat)(
JNIEXPORT jint JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddJoystick)(
JNIEnv* env, jclass jcls,
jint device_id, jstring device_name, jstring device_desc,
jint vendor_id, jint product_id, jboolean is_accelerometer,
jint button_mask, jint naxes, jint nhats, jint nballs)
jint device_id, jstring device_name, jstring device_desc, jint is_accelerometer,
jint nbuttons, jint naxes, jint nhats, jint nballs)
{
int retval;
const char *name = (*env)->GetStringUTFChars(env, device_name, NULL);
const char *desc = (*env)->GetStringUTFChars(env, device_desc, NULL);
retval = Android_AddJoystick(device_id, name, desc, vendor_id, product_id, is_accelerometer ? SDL_TRUE : SDL_FALSE, button_mask, naxes, nhats, nballs);
retval = Android_AddJoystick(device_id, name, desc, (SDL_bool) is_accelerometer, nbuttons, naxes, nhats, nballs);
(*env)->ReleaseStringUTFChars(env, device_name, name);
(*env)->ReleaseStringUTFChars(env, device_desc, desc);
@ -733,9 +675,9 @@ JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
/* Mouse */
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeMouse)(
JNIEnv* env, jclass jcls,
jint button, jint action, jfloat x, jfloat y, jboolean relative)
jint button, jint action, jfloat x, jfloat y)
{
Android_OnMouse(button, action, x, y, relative);
Android_OnMouse(button, action, x, y);
}
/* Accelerometer */
@ -1053,19 +995,17 @@ int Android_JNI_SetupThread(void)
/*
* Audio support
*/
static int audioBufferFormat = 0;
static jboolean audioBuffer16Bit = JNI_FALSE;
static jobject audioBuffer = NULL;
static void* audioBufferPinned = NULL;
static int captureBufferFormat = 0;
static jboolean captureBuffer16Bit = JNI_FALSE;
static jobject captureBuffer = NULL;
int Android_JNI_OpenAudioDevice(int iscapture, SDL_AudioSpec *spec)
int Android_JNI_OpenAudioDevice(int iscapture, int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames)
{
int audioformat;
int numBufferFrames;
jboolean audioBufferStereo;
int audioBufferFrames;
jobject jbufobj = NULL;
jobject result;
int *resultElements;
jboolean isCopy;
JNIEnv *env = Android_JNI_GetEnv();
@ -1075,123 +1015,74 @@ int Android_JNI_OpenAudioDevice(int iscapture, SDL_AudioSpec *spec)
}
Android_JNI_SetupThread();
switch (spec->format) {
case AUDIO_U8:
audioformat = ENCODING_PCM_8BIT;
break;
case AUDIO_S16:
audioformat = ENCODING_PCM_16BIT;
break;
case AUDIO_F32:
audioformat = ENCODING_PCM_FLOAT;
break;
default:
return SDL_SetError("Unsupported audio format: 0x%x", spec->format);
}
audioBufferStereo = channelCount > 1;
if (iscapture) {
__android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device for capture");
result = (*env)->CallStaticObjectMethod(env, mAudioManagerClass, midCaptureOpen, spec->freq, audioformat, spec->channels, spec->samples);
captureBuffer16Bit = is16Bit;
if ((*env)->CallStaticIntMethod(env, mAudioManagerClass, midCaptureOpen, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames) != 0) {
/* Error during audio initialization */
__android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: error on AudioRecord initialization!");
return 0;
}
} else {
__android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device for output");
result = (*env)->CallStaticObjectMethod(env, mAudioManagerClass, midAudioOpen, spec->freq, audioformat, spec->channels, spec->samples);
audioBuffer16Bit = is16Bit;
if ((*env)->CallStaticIntMethod(env, mAudioManagerClass, midAudioOpen, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames) != 0) {
/* Error during audio initialization */
__android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: error on AudioTrack initialization!");
return 0;
}
}
if (result == NULL) {
/* Error during audio initialization, error printed from Java */
return SDL_SetError("Java-side initialization failed");
}
if ((*env)->GetArrayLength(env, (jintArray)result) != 4) {
return SDL_SetError("Unexpected results from Java, expected 4, got %d", (*env)->GetArrayLength(env, (jintArray)result));
}
isCopy = JNI_FALSE;
resultElements = (*env)->GetIntArrayElements(env, (jintArray)result, &isCopy);
spec->freq = resultElements[0];
audioformat = resultElements[1];
switch (audioformat) {
case ENCODING_PCM_8BIT:
spec->format = AUDIO_U8;
break;
case ENCODING_PCM_16BIT:
spec->format = AUDIO_S16;
break;
case ENCODING_PCM_FLOAT:
spec->format = AUDIO_F32;
break;
default:
return SDL_SetError("Unexpected audio format from Java: %d\n", audioformat);
}
spec->channels = resultElements[2];
spec->samples = resultElements[3];
(*env)->ReleaseIntArrayElements(env, (jintArray)result, resultElements, JNI_ABORT);
(*env)->DeleteLocalRef(env, result);
/* Allocating the audio buffer from the Java side and passing it as the return value for audioInit no longer works on
* Android >= 4.2 due to a "stale global reference" error. So now we allocate this buffer directly from this side. */
switch (audioformat) {
case ENCODING_PCM_8BIT:
{
jbyteArray audioBufferLocal = (*env)->NewByteArray(env, spec->samples * spec->channels);
if (audioBufferLocal) {
jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal);
(*env)->DeleteLocalRef(env, audioBufferLocal);
}
if (is16Bit) {
jshortArray audioBufferLocal = (*env)->NewShortArray(env, desiredBufferFrames * (audioBufferStereo ? 2 : 1));
if (audioBufferLocal) {
jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal);
(*env)->DeleteLocalRef(env, audioBufferLocal);
}
break;
case ENCODING_PCM_16BIT:
{
jshortArray audioBufferLocal = (*env)->NewShortArray(env, spec->samples * spec->channels);
if (audioBufferLocal) {
jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal);
(*env)->DeleteLocalRef(env, audioBufferLocal);
}
}
else {
jbyteArray audioBufferLocal = (*env)->NewByteArray(env, desiredBufferFrames * (audioBufferStereo ? 2 : 1));
if (audioBufferLocal) {
jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal);
(*env)->DeleteLocalRef(env, audioBufferLocal);
}
break;
case ENCODING_PCM_FLOAT:
{
jfloatArray audioBufferLocal = (*env)->NewFloatArray(env, spec->samples * spec->channels);
if (audioBufferLocal) {
jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal);
(*env)->DeleteLocalRef(env, audioBufferLocal);
}
}
break;
default:
return SDL_SetError("Unexpected audio format from Java: %d\n", audioformat);
}
if (jbufobj == NULL) {
__android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: could not allocate an audio buffer");
return SDL_OutOfMemory();
__android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: could not allocate an audio buffer!");
return 0;
}
if (iscapture) {
captureBufferFormat = audioformat;
captureBuffer = jbufobj;
} else {
audioBufferFormat = audioformat;
audioBuffer = jbufobj;
}
numBufferFrames = (*env)->GetArrayLength(env, (jarray)jbufobj);
if (!iscapture) {
isCopy = JNI_FALSE;
isCopy = JNI_FALSE;
switch (audioformat) {
case ENCODING_PCM_8BIT:
audioBufferPinned = (*env)->GetByteArrayElements(env, (jbyteArray)audioBuffer, &isCopy);
break;
case ENCODING_PCM_16BIT:
if (is16Bit) {
if (!iscapture) {
audioBufferPinned = (*env)->GetShortArrayElements(env, (jshortArray)audioBuffer, &isCopy);
break;
case ENCODING_PCM_FLOAT:
audioBufferPinned = (*env)->GetFloatArrayElements(env, (jfloatArray)audioBuffer, &isCopy);
break;
default:
return SDL_SetError("Unexpected audio format from Java: %d\n", audioformat);
}
audioBufferFrames = (*env)->GetArrayLength(env, (jshortArray)audioBuffer);
} else {
if (!iscapture) {
audioBufferPinned = (*env)->GetByteArrayElements(env, (jbyteArray)audioBuffer, &isCopy);
}
audioBufferFrames = (*env)->GetArrayLength(env, (jbyteArray)audioBuffer);
}
return 0;
if (audioBufferStereo) {
audioBufferFrames /= 2;
}
return audioBufferFrames;
}
int Android_JNI_GetDisplayDPI(float *ddpi, float *xdpi, float *ydpi)
@ -1235,22 +1126,12 @@ void Android_JNI_WriteAudioBuffer(void)
{
JNIEnv *mAudioEnv = Android_JNI_GetEnv();
switch (audioBufferFormat) {
case ENCODING_PCM_8BIT:
(*mAudioEnv)->ReleaseByteArrayElements(mAudioEnv, (jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
(*mAudioEnv)->CallStaticVoidMethod(mAudioEnv, mAudioManagerClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
break;
case ENCODING_PCM_16BIT:
if (audioBuffer16Bit) {
(*mAudioEnv)->ReleaseShortArrayElements(mAudioEnv, (jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
(*mAudioEnv)->CallStaticVoidMethod(mAudioEnv, mAudioManagerClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
break;
case ENCODING_PCM_FLOAT:
(*mAudioEnv)->ReleaseFloatArrayElements(mAudioEnv, (jfloatArray)audioBuffer, (jfloat *)audioBufferPinned, JNI_COMMIT);
(*mAudioEnv)->CallStaticVoidMethod(mAudioEnv, mAudioManagerClass, midAudioWriteFloatBuffer, (jfloatArray)audioBuffer);
break;
default:
__android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: unhandled audio buffer format");
break;
} else {
(*mAudioEnv)->ReleaseByteArrayElements(mAudioEnv, (jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
(*mAudioEnv)->CallStaticVoidMethod(mAudioEnv, mAudioManagerClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
}
/* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
@ -1262,8 +1143,16 @@ int Android_JNI_CaptureAudioBuffer(void *buffer, int buflen)
jboolean isCopy = JNI_FALSE;
jint br;
switch (captureBufferFormat) {
case ENCODING_PCM_8BIT:
if (captureBuffer16Bit) {
SDL_assert((*env)->GetArrayLength(env, (jshortArray)captureBuffer) == (buflen / 2));
br = (*env)->CallStaticIntMethod(env, mAudioManagerClass, midCaptureReadShortBuffer, (jshortArray)captureBuffer, JNI_TRUE);
if (br > 0) {
jshort *ptr = (*env)->GetShortArrayElements(env, (jshortArray)captureBuffer, &isCopy);
br *= 2;
SDL_memcpy(buffer, ptr, br);
(*env)->ReleaseShortArrayElements(env, (jshortArray)captureBuffer, (jshort *)ptr, JNI_ABORT);
}
} else {
SDL_assert((*env)->GetArrayLength(env, (jshortArray)captureBuffer) == buflen);
br = (*env)->CallStaticIntMethod(env, mAudioManagerClass, midCaptureReadByteBuffer, (jbyteArray)captureBuffer, JNI_TRUE);
if (br > 0) {
@ -1271,75 +1160,27 @@ int Android_JNI_CaptureAudioBuffer(void *buffer, int buflen)
SDL_memcpy(buffer, ptr, br);
(*env)->ReleaseByteArrayElements(env, (jbyteArray)captureBuffer, (jbyte *)ptr, JNI_ABORT);
}
break;
case ENCODING_PCM_16BIT:
SDL_assert((*env)->GetArrayLength(env, (jshortArray)captureBuffer) == (buflen / sizeof(Sint16)));
br = (*env)->CallStaticIntMethod(env, mAudioManagerClass, midCaptureReadShortBuffer, (jshortArray)captureBuffer, JNI_TRUE);
if (br > 0) {
jshort *ptr = (*env)->GetShortArrayElements(env, (jshortArray)captureBuffer, &isCopy);
br *= sizeof(Sint16);
SDL_memcpy(buffer, ptr, br);
(*env)->ReleaseShortArrayElements(env, (jshortArray)captureBuffer, (jshort *)ptr, JNI_ABORT);
}
break;
case ENCODING_PCM_FLOAT:
SDL_assert((*env)->GetArrayLength(env, (jfloatArray)captureBuffer) == (buflen / sizeof(float)));
br = (*env)->CallStaticIntMethod(env, mAudioManagerClass, midCaptureReadFloatBuffer, (jfloatArray)captureBuffer, JNI_TRUE);
if (br > 0) {
jfloat *ptr = (*env)->GetFloatArrayElements(env, (jfloatArray)captureBuffer, &isCopy);
br *= sizeof(float);
SDL_memcpy(buffer, ptr, br);
(*env)->ReleaseFloatArrayElements(env, (jfloatArray)captureBuffer, (jfloat *)ptr, JNI_ABORT);
}
break;
default:
__android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: unhandled capture buffer format");
break;
}
return br;
return (int) br;
}
void Android_JNI_FlushCapturedAudio(void)
{
JNIEnv *env = Android_JNI_GetEnv();
#if 0 /* !!! FIXME: this needs API 23, or it'll do blocking reads and never end. */
switch (captureBufferFormat) {
case ENCODING_PCM_8BIT:
{
const jint len = (*env)->GetArrayLength(env, (jbyteArray)captureBuffer);
while ((*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadByteBuffer, (jbyteArray)captureBuffer, JNI_FALSE) == len) { /* spin */ }
}
break;
case ENCODING_PCM_16BIT:
{
const jint len = (*env)->GetArrayLength(env, (jshortArray)captureBuffer);
while ((*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadShortBuffer, (jshortArray)captureBuffer, JNI_FALSE) == len) { /* spin */ }
}
break;
case ENCODING_PCM_FLOAT:
{
const jint len = (*env)->GetArrayLength(env, (jfloatArray)captureBuffer);
while ((*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadFloatBuffer, (jfloatArray)captureBuffer, JNI_FALSE) == len) { /* spin */ }
}
break;
default:
__android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: flushing unhandled capture buffer format");
break;
if (captureBuffer16Bit) {
const jint len = (*env)->GetArrayLength(env, (jshortArray)captureBuffer);
while ((*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadShortBuffer, (jshortArray)captureBuffer, JNI_FALSE) == len) { /* spin */ }
} else {
const jint len = (*env)->GetArrayLength(env, (jbyteArray)captureBuffer);
while ((*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadByteBuffer, (jbyteArray)captureBuffer, JNI_FALSE) == len) { /* spin */ }
}
#else
switch (captureBufferFormat) {
case ENCODING_PCM_8BIT:
(*env)->CallStaticIntMethod(env, mAudioManagerClass, midCaptureReadByteBuffer, (jbyteArray)captureBuffer, JNI_FALSE);
break;
case ENCODING_PCM_16BIT:
if (captureBuffer16Bit) {
(*env)->CallStaticIntMethod(env, mAudioManagerClass, midCaptureReadShortBuffer, (jshortArray)captureBuffer, JNI_FALSE);
break;
case ENCODING_PCM_FLOAT:
(*env)->CallStaticIntMethod(env, mAudioManagerClass, midCaptureReadFloatBuffer, (jfloatArray)captureBuffer, JNI_FALSE);
break;
default:
__android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: flushing unhandled capture buffer format");
break;
} else {
(*env)->CallStaticIntMethod(env, mAudioManagerClass, midCaptureReadByteBuffer, (jbyteArray)captureBuffer, JNI_FALSE);
}
#endif
}
@ -2005,17 +1846,12 @@ void Android_JNI_PollHapticDevices(void)
(*env)->CallStaticVoidMethod(env, mControllerManagerClass, midPollHapticDevices);
}
void Android_JNI_HapticRun(int device_id, float intensity, int length)
void Android_JNI_HapticRun(int device_id, int length)
{
JNIEnv *env = Android_JNI_GetEnv();
(*env)->CallStaticVoidMethod(env, mControllerManagerClass, midHapticRun, device_id, intensity, length);
(*env)->CallStaticVoidMethod(env, mControllerManagerClass, midHapticRun, device_id, length);
}
void Android_JNI_HapticStop(int device_id)
{
JNIEnv *env = Android_JNI_GetEnv();
(*env)->CallStaticVoidMethod(env, mControllerManagerClass, midHapticStop, device_id);
}
/* See SDLActivity.java for constants. */
#define COMMAND_SET_KEEP_SCREEN_ON 5
@ -2170,36 +2006,12 @@ void *SDL_AndroidGetActivity(void)
return (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
}
SDL_bool SDL_IsAndroidTablet(void)
{
JNIEnv *env = Android_JNI_GetEnv();
return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsTablet);
}
SDL_bool SDL_IsAndroidTV(void)
{
JNIEnv *env = Android_JNI_GetEnv();
return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsAndroidTV);
}
SDL_bool SDL_IsChromebook(void)
{
JNIEnv *env = Android_JNI_GetEnv();
return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsChromebook);
}
SDL_bool SDL_IsDeXMode(void)
{
JNIEnv *env = Android_JNI_GetEnv();
return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsDeXMode);
}
void SDL_AndroidBackButton(void)
{
JNIEnv *env = Android_JNI_GetEnv();
return (*env)->CallStaticVoidMethod(env, mActivityClass, midManualBackButton);
}
const char * SDL_AndroidGetInternalStoragePath(void)
{
static char *s_AndroidInternalFilesPath = NULL;
@ -2354,48 +2166,6 @@ void Android_JNI_GetManifestEnvironmentVariables(void)
}
}
int Android_JNI_CreateCustomCursor(SDL_Surface *surface, int hot_x, int hot_y)
{
JNIEnv *mEnv = Android_JNI_GetEnv();
int custom_cursor = 0;
jintArray pixels;
pixels = (*mEnv)->NewIntArray(mEnv, surface->w * surface->h);
if (pixels) {
(*mEnv)->SetIntArrayRegion(mEnv, pixels, 0, surface->w * surface->h, (int *)surface->pixels);
custom_cursor = (*mEnv)->CallStaticIntMethod(mEnv, mActivityClass, midCreateCustomCursor, pixels, surface->w, surface->h, hot_x, hot_y);
(*mEnv)->DeleteLocalRef(mEnv, pixels);
} else {
SDL_OutOfMemory();
}
return custom_cursor;
}
SDL_bool Android_JNI_SetCustomCursor(int cursorID)
{
JNIEnv *mEnv = Android_JNI_GetEnv();
return (*mEnv)->CallStaticBooleanMethod(mEnv, mActivityClass, midSetCustomCursor, cursorID);
}
SDL_bool Android_JNI_SetSystemCursor(int cursorID)
{
JNIEnv *mEnv = Android_JNI_GetEnv();
return (*mEnv)->CallStaticBooleanMethod(mEnv, mActivityClass, midSetSystemCursor, cursorID);
}
SDL_bool Android_JNI_SupportsRelativeMouse()
{
JNIEnv *mEnv = Android_JNI_GetEnv();
return (*mEnv)->CallStaticBooleanMethod(mEnv, mActivityClass, midSupportsRelativeMouse);
}
SDL_bool Android_JNI_SetRelativeMouseEnabled(SDL_bool enabled)
{
JNIEnv *mEnv = Android_JNI_GetEnv();
return (*mEnv)->CallStaticBooleanMethod(mEnv, mActivityClass, midSetRelativeMouseEnabled, (enabled == 1));
}
#endif /* __ANDROID__ */
/* vi: set ts=4 sw=4 expandtab: */

View file

@ -19,7 +19,6 @@
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#include "SDL_system.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
@ -31,7 +30,6 @@ extern "C" {
#include <EGL/eglplatform.h>
#include <android/native_window_jni.h>
#include "SDL_audio.h"
#include "SDL_rect.h"
/* Interface from the SDL library into the Android Java activity */
@ -48,17 +46,13 @@ extern ANativeWindow* Android_JNI_GetNativeWindow(void);
extern int Android_JNI_GetDisplayDPI(float *ddpi, float *xdpi, float *ydpi);
/* Audio support */
extern int Android_JNI_OpenAudioDevice(int iscapture, SDL_AudioSpec *spec);
extern int Android_JNI_OpenAudioDevice(int iscapture, int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames);
extern void* Android_JNI_GetAudioBuffer(void);
extern void Android_JNI_WriteAudioBuffer(void);
extern int Android_JNI_CaptureAudioBuffer(void *buffer, int buflen);
extern void Android_JNI_FlushCapturedAudio(void);
extern void Android_JNI_CloseAudioDevice(const int iscapture);
/* Detecting device type */
extern SDL_bool Android_IsDeXMode();
extern SDL_bool Android_IsChromebook();
#include "SDL_rwops.h"
int Android_JNI_FileOpen(SDL_RWops* ctx, const char* fileName, const char* mode);
@ -84,16 +78,14 @@ void Android_JNI_PollInputDevices(void);
/* Haptic support */
void Android_JNI_PollHapticDevices(void);
void Android_JNI_HapticRun(int device_id, float intensity, int length);
void Android_JNI_HapticStop(int device_id);
void Android_JNI_HapticRun(int device_id, int length);
/* Video */
void Android_JNI_SuspendScreenSaver(SDL_bool suspend);
/* Touch support */
int Android_JNI_InitTouch(void);
void Android_JNI_SetSeparateMouseAndTouch(SDL_bool new_value);
int Android_JNI_GetTouchDeviceIds(int **ids);
void Android_JNI_SetSeparateMouseAndTouch(SDL_bool new_value);
/* Threads */
#include <jni.h>
@ -110,21 +102,6 @@ JNIEXPORT void JNICALL SDL_Android_Init(JNIEnv* mEnv, jclass cls);
#include "SDL_messagebox.h"
int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid);
/* Cursor support */
int Android_JNI_CreateCustomCursor(SDL_Surface *surface, int hot_x, int hot_y);
SDL_bool Android_JNI_SetCustomCursor(int cursorID);
SDL_bool Android_JNI_SetSystemCursor(int cursorID);
/* Relative mouse support */
SDL_bool Android_JNI_SupportsRelativeMouse(void);
SDL_bool Android_JNI_SetRelativeMouseEnabled(SDL_bool enabled);
SDL_bool SDL_IsAndroidTablet(void);
SDL_bool SDL_IsAndroidTV(void);
SDL_bool SDL_IsChromebook(void);
SDL_bool SDL_IsDeXMode(void);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
/* *INDENT-OFF* */

View file

@ -173,29 +173,17 @@ SDL_DBus_CallMethodInternal(DBusConnection *conn, const char *node, const char *
if (conn) {
DBusMessage *msg = dbus.message_new_method_call(node, path, interface, method);
if (msg) {
int firstarg;
va_list ap_reply;
va_copy(ap_reply, ap); /* copy the arg list so we don't compete with D-Bus for it */
firstarg = va_arg(ap, int);
int firstarg = va_arg(ap, int);
if ((firstarg == DBUS_TYPE_INVALID) || dbus.message_append_args_valist(msg, firstarg, ap)) {
DBusMessage *reply = dbus.connection_send_with_reply_and_block(conn, msg, 300, NULL);
if (reply) {
/* skip any input args, get to output args. */
while ((firstarg = va_arg(ap_reply, int)) != DBUS_TYPE_INVALID) {
/* we assume D-Bus already validated all this. */
{ void *dumpptr = va_arg(ap_reply, void*); (void) dumpptr; }
if (firstarg == DBUS_TYPE_ARRAY) {
{ const int dumpint = va_arg(ap_reply, int); (void) dumpint; }
}
}
firstarg = va_arg(ap_reply, int);
if ((firstarg == DBUS_TYPE_INVALID) || dbus.message_get_args_valist(reply, NULL, firstarg, ap_reply)) {
firstarg = va_arg(ap, int);
if ((firstarg == DBUS_TYPE_INVALID) || dbus.message_get_args_valist(reply, NULL, firstarg, ap)) {
retval = SDL_TRUE;
}
dbus.message_unref(reply);
}
}
va_end(ap_reply);
dbus.message_unref(msg);
}
}

View file

@ -39,8 +39,9 @@ typedef struct SDL_DBusContext {
void (*bus_add_match)(DBusConnection *, const char *, DBusError *);
DBusConnection * (*connection_open_private)(const char *, DBusError *);
void (*connection_set_exit_on_disconnect)(DBusConnection *, dbus_bool_t);
dbus_bool_t (*connection_get_is_connected)(DBusConnection *);
dbus_bool_t (*connection_add_filter)(DBusConnection *, DBusHandleMessageFunction, void *, DBusFreeFunction);
dbus_bool_t (*connection_get_is_connected)(DBusConnection *);
dbus_bool_t (*connection_add_filter)(DBusConnection *, DBusHandleMessageFunction,
void *, DBusFreeFunction);
dbus_bool_t (*connection_try_register_object_path)(DBusConnection *, const char *,
const DBusObjectPathVTable *, void *, DBusError *);
dbus_bool_t (*connection_send)(DBusConnection *, DBusMessage *, dbus_uint32_t *);
@ -50,7 +51,7 @@ typedef struct SDL_DBusContext {
void (*connection_flush)(DBusConnection *);
dbus_bool_t (*connection_read_write)(DBusConnection *, int);
DBusDispatchStatus (*connection_dispatch)(DBusConnection *);
dbus_bool_t (*message_is_signal)(DBusMessage *, const char *, const char *);
dbus_bool_t (*message_is_signal)(DBusMessage *, const char *, const char *);
DBusMessage *(*message_new_method_call)(const char *, const char *, const char *, const char *);
dbus_bool_t (*message_append_args)(DBusMessage *, int, ...);
dbus_bool_t (*message_append_args_valist)(DBusMessage *, int, va_list);
@ -60,7 +61,7 @@ typedef struct SDL_DBusContext {
dbus_bool_t (*message_iter_next)(DBusMessageIter *);
void (*message_iter_get_basic)(DBusMessageIter *, void *);
int (*message_iter_get_arg_type)(DBusMessageIter *);
void (*message_iter_recurse)(DBusMessageIter *, DBusMessageIter *);
void (*message_iter_recurse)(DBusMessageIter *, DBusMessageIter *);
void (*message_unref)(DBusMessage *);
void (*error_init)(DBusError *);
dbus_bool_t (*error_is_set)(const DBusError *);

View file

@ -101,7 +101,6 @@ typedef struct SDL_EVDEV_PrivateData
SDL_EVDEV_keyboard_state *kbd;
} SDL_EVDEV_PrivateData;
#undef _THIS
#define _THIS SDL_EVDEV_PrivateData *_this
static _THIS = NULL;

View file

@ -21,7 +21,6 @@
#include "../../SDL_internal.h"
#include "SDL_evdev_kbd.h"
#include "SDL_hints.h"
#ifdef SDL_INPUT_LINUXKD
@ -35,8 +34,6 @@
#include <linux/vt.h>
#include <linux/tiocl.h> /* for TIOCL_GETSHIFTSTATE */
#include <signal.h>
#include "../../events/SDL_events_c.h"
#include "SDL_evdev_kbd_default_accents.h"
#include "SDL_evdev_kbd_default_keymap.h"
@ -194,151 +191,6 @@ static int SDL_EVDEV_kbd_load_keymaps(SDL_EVDEV_keyboard_state *kbd)
return 0;
}
static SDL_EVDEV_keyboard_state * kbd_cleanup_state = NULL;
static int kbd_cleanup_sigactions_installed = 0;
static int kbd_cleanup_atexit_installed = 0;
static struct sigaction old_sigaction[NSIG];
static int fatal_signals[] =
{
/* Handlers for SIGTERM and SIGINT are installed in SDL_QuitInit. */
SIGHUP, SIGQUIT, SIGILL, SIGABRT,
SIGFPE, SIGSEGV, SIGPIPE, SIGBUS,
SIGSYS
};
static void kbd_cleanup(void)
{
SDL_EVDEV_keyboard_state* kbd = kbd_cleanup_state;
if (kbd == NULL) {
return;
}
kbd_cleanup_state = NULL;
fprintf(stderr, "(SDL restoring keyboard) ");
ioctl(kbd->console_fd, KDSKBMODE, kbd->old_kbd_mode);
}
void
SDL_EVDEV_kbd_reraise_signal(int sig)
{
raise(sig);
}
siginfo_t* SDL_EVDEV_kdb_cleanup_siginfo = NULL;
void* SDL_EVDEV_kdb_cleanup_ucontext = NULL;
static void kbd_cleanup_signal_action(int signum, siginfo_t* info, void* ucontext)
{
struct sigaction* old_action_p = &(old_sigaction[signum]);
sigset_t sigset;
/* Restore original signal handler before going any further. */
sigaction(signum, old_action_p, NULL);
/* Unmask current signal. */
sigemptyset(&sigset);
sigaddset(&sigset, signum);
sigprocmask(SIG_UNBLOCK, &sigset, NULL);
/* Save original signal info and context for archeologists. */
SDL_EVDEV_kdb_cleanup_siginfo = info;
SDL_EVDEV_kdb_cleanup_ucontext = ucontext;
/* Restore keyboard. */
kbd_cleanup();
/* Reraise signal. */
SDL_EVDEV_kbd_reraise_signal(signum);
}
static void kbd_unregister_emerg_cleanup()
{
int tabidx, signum;
kbd_cleanup_state = NULL;
if (!kbd_cleanup_sigactions_installed) {
return;
}
kbd_cleanup_sigactions_installed = 0;
for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) {
struct sigaction* old_action_p;
struct sigaction cur_action;
signum = fatal_signals[tabidx];
old_action_p = &(old_sigaction[signum]);
/* Examine current signal action */
if (sigaction(signum, NULL, &cur_action))
continue;
/* Check if action installed and not modifed */
if (!(cur_action.sa_flags & SA_SIGINFO)
|| cur_action.sa_sigaction != &kbd_cleanup_signal_action)
continue;
/* Restore original action */
sigaction(signum, old_action_p, NULL);
}
}
static void kbd_cleanup_atexit(void)
{
/* Restore keyboard. */
kbd_cleanup();
/* Try to restore signal handlers in case shared library is being unloaded */
kbd_unregister_emerg_cleanup();
}
static void kbd_register_emerg_cleanup(SDL_EVDEV_keyboard_state * kbd)
{
int tabidx, signum;
if (kbd_cleanup_state != NULL) {
return;
}
kbd_cleanup_state = kbd;
if (!kbd_cleanup_atexit_installed) {
/* Since glibc 2.2.3, atexit() (and on_exit(3)) can be used within a shared library to establish
* functions that are called when the shared library is unloaded.
* -- man atexit(3)
*/
atexit(kbd_cleanup_atexit);
kbd_cleanup_atexit_installed = 1;
}
if (kbd_cleanup_sigactions_installed) {
return;
}
kbd_cleanup_sigactions_installed = 1;
for (tabidx = 0; tabidx < sizeof(fatal_signals) / sizeof(fatal_signals[0]); ++tabidx) {
struct sigaction* old_action_p;
struct sigaction new_action;
signum = fatal_signals[tabidx];
old_action_p = &(old_sigaction[signum]);
if (sigaction(signum, NULL, old_action_p))
continue;
/* Skip SIGHUP and SIGPIPE if handler is already installed
* - 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))
continue;
new_action = *old_action_p;
new_action.sa_flags |= SA_SIGINFO;
new_action.sa_sigaction = &kbd_cleanup_signal_action;
sigaction(signum, &new_action, NULL);
}
}
SDL_EVDEV_keyboard_state *
SDL_EVDEV_kbd_init(void)
{
@ -386,20 +238,10 @@ SDL_EVDEV_kbd_init(void)
kbd->key_maps = default_key_maps;
}
/* Allow inhibiting keyboard mute with env. variable for debugging etc. */
if (getenv("SDL_INPUT_LINUX_KEEP_KBD") == NULL) {
/* Mute the keyboard so keystrokes only generate evdev events
* and do not leak through to the console
*/
ioctl(kbd->console_fd, KDSKBMODE, K_OFF);
/* Make sure to restore keyboard if application fails to call
* SDL_Quit before exit or fatal signal is raised.
*/
if (!SDL_GetHintBoolean(SDL_HINT_NO_SIGNAL_HANDLERS, SDL_FALSE)) {
kbd_register_emerg_cleanup(kbd);
}
}
/* Mute the keyboard so keystrokes only generate evdev events
* and do not leak through to the console
*/
ioctl(kbd->console_fd, KDSKBMODE, K_OFF);
}
#ifdef DUMP_ACCENTS
@ -418,8 +260,6 @@ SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *kbd)
return;
}
kbd_unregister_emerg_cleanup();
if (kbd->console_fd >= 0) {
/* Restore the original keyboard mode */
ioctl(kbd->console_fd, KDSKBMODE, kbd->old_kbd_mode);
@ -769,10 +609,7 @@ SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *kbd, unsigned int keycode, int d
shift_final = (kbd->shift_state | kbd->slockstate) ^ kbd->lockstate;
key_map = kbd->key_maps[shift_final];
if (!key_map) {
/* Unsupported shift state (e.g. ctrl = 4, alt = 8), just reset to the default state */
kbd->shift_state = 0;
kbd->slockstate = 0;
kbd->lockstate = 0;
return;
}

View file

@ -19,9 +19,6 @@
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_evdev_kbd_h_
#define SDL_evdev_kbd_h_
struct SDL_EVDEV_keyboard_state;
typedef struct SDL_EVDEV_keyboard_state SDL_EVDEV_keyboard_state;
@ -29,6 +26,4 @@ extern SDL_EVDEV_keyboard_state *SDL_EVDEV_kbd_init(void);
extern void SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *state, unsigned int keycode, int down);
extern void SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *state);
#endif /* SDL_evdev_kbd_h_ */
/* vi: set ts=4 sw=4 expandtab: */

View file

@ -63,7 +63,7 @@ SDL_UDEV_load_syms(void)
{
/* cast funcs to char* first, to please GCC's strict aliasing rules. */
#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->x)) return -1
SDL_UDEV_SYM(udev_device_get_action);
SDL_UDEV_SYM(udev_device_get_devnode);
@ -100,7 +100,7 @@ static SDL_bool
SDL_UDEV_hotplug_update_available(void)
{
if (_this->udev_mon != NULL) {
const int fd = _this->syms.udev_monitor_get_fd(_this->udev_mon);
const int fd = _this->udev_monitor_get_fd(_this->udev_mon);
if (SDL_IOReady(fd, SDL_FALSE, 0)) {
return SDL_TRUE;
}
@ -130,21 +130,21 @@ SDL_UDEV_Init(void)
* Listen for input devices (mouse, keyboard, joystick, etc) and sound devices
*/
_this->udev = _this->syms.udev_new();
_this->udev = _this->udev_new();
if (_this->udev == NULL) {
SDL_UDEV_Quit();
return SDL_SetError("udev_new() failed");
}
_this->udev_mon = _this->syms.udev_monitor_new_from_netlink(_this->udev, "udev");
_this->udev_mon = _this->udev_monitor_new_from_netlink(_this->udev, "udev");
if (_this->udev_mon == NULL) {
SDL_UDEV_Quit();
return SDL_SetError("udev_monitor_new_from_netlink() failed");
}
_this->syms.udev_monitor_filter_add_match_subsystem_devtype(_this->udev_mon, "input", NULL);
_this->syms.udev_monitor_filter_add_match_subsystem_devtype(_this->udev_mon, "sound", NULL);
_this->syms.udev_monitor_enable_receiving(_this->udev_mon);
_this->udev_monitor_filter_add_match_subsystem_devtype(_this->udev_mon, "input", NULL);
_this->udev_monitor_filter_add_match_subsystem_devtype(_this->udev_mon, "sound", NULL);
_this->udev_monitor_enable_receiving(_this->udev_mon);
/* Do an initial scan of existing devices */
SDL_UDEV_Scan();
@ -170,11 +170,11 @@ SDL_UDEV_Quit(void)
if (_this->ref_count < 1) {
if (_this->udev_mon != NULL) {
_this->syms.udev_monitor_unref(_this->udev_mon);
_this->udev_monitor_unref(_this->udev_mon);
_this->udev_mon = NULL;
}
if (_this->udev != NULL) {
_this->syms.udev_unref(_this->udev);
_this->udev_unref(_this->udev);
_this->udev = NULL;
}
@ -202,28 +202,28 @@ SDL_UDEV_Scan(void)
return;
}
enumerate = _this->syms.udev_enumerate_new(_this->udev);
enumerate = _this->udev_enumerate_new(_this->udev);
if (enumerate == NULL) {
SDL_UDEV_Quit();
SDL_SetError("udev_enumerate_new() failed");
return;
}
_this->syms.udev_enumerate_add_match_subsystem(enumerate, "input");
_this->syms.udev_enumerate_add_match_subsystem(enumerate, "sound");
_this->udev_enumerate_add_match_subsystem(enumerate, "input");
_this->udev_enumerate_add_match_subsystem(enumerate, "sound");
_this->syms.udev_enumerate_scan_devices(enumerate);
devs = _this->syms.udev_enumerate_get_list_entry(enumerate);
for (item = devs; item; item = _this->syms.udev_list_entry_get_next(item)) {
const char *path = _this->syms.udev_list_entry_get_name(item);
struct udev_device *dev = _this->syms.udev_device_new_from_syspath(_this->udev, path);
_this->udev_enumerate_scan_devices(enumerate);
devs = _this->udev_enumerate_get_list_entry(enumerate);
for (item = devs; item; item = _this->udev_list_entry_get_next(item)) {
const char *path = _this->udev_list_entry_get_name(item);
struct udev_device *dev = _this->udev_device_new_from_syspath(_this->udev, path);
if (dev != NULL) {
device_event(SDL_UDEV_DEVICEADDED, dev);
_this->syms.udev_device_unref(dev);
_this->udev_device_unref(dev);
}
}
_this->syms.udev_enumerate_unref(enumerate);
_this->udev_enumerate_unref(enumerate);
}
@ -305,7 +305,7 @@ static void get_caps(struct udev_device *dev, struct udev_device *pdev, const ch
unsigned long v;
SDL_memset(bitmask, 0, bitmask_len*sizeof(*bitmask));
value = _this->syms.udev_device_get_sysattr_value(pdev, attr);
value = _this->udev_device_get_sysattr_value(pdev, attr);
if (!value) {
return;
}
@ -340,8 +340,8 @@ guess_device_class(struct udev_device *dev)
/* walk up the parental chain until we find the real input device; the
* argument is very likely a subdevice of this, like eventN */
pdev = dev;
while (pdev && !_this->syms.udev_device_get_sysattr_value(pdev, "capabilities/ev")) {
pdev = _this->syms.udev_device_get_parent_with_subsystem_devtype(pdev, "input", NULL);
while (pdev && !_this->udev_device_get_sysattr_value(pdev, "capabilities/ev")) {
pdev = _this->udev_device_get_parent_with_subsystem_devtype(pdev, "input", NULL);
}
if (!pdev) {
return 0;
@ -405,28 +405,28 @@ device_event(SDL_UDEV_deviceevent type, struct udev_device *dev)
const char *path;
SDL_UDEV_CallbackList *item;
path = _this->syms.udev_device_get_devnode(dev);
path = _this->udev_device_get_devnode(dev);
if (path == NULL) {
return;
}
subsystem = _this->syms.udev_device_get_subsystem(dev);
subsystem = _this->udev_device_get_subsystem(dev);
if (SDL_strcmp(subsystem, "sound") == 0) {
devclass = SDL_UDEV_DEVICE_SOUND;
} else if (SDL_strcmp(subsystem, "input") == 0) {
/* 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->udev_device_get_property_value(dev, "ID_INPUT_JOYSTICK");
if (val != NULL && SDL_strcmp(val, "1") == 0 ) {
devclass |= SDL_UDEV_DEVICE_JOYSTICK;
}
val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_MOUSE");
val = _this->udev_device_get_property_value(dev, "ID_INPUT_MOUSE");
if (val != NULL && SDL_strcmp(val, "1") == 0 ) {
devclass |= SDL_UDEV_DEVICE_MOUSE;
}
val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_TOUCHSCREEN");
val = _this->udev_device_get_property_value(dev, "ID_INPUT_TOUCHSCREEN");
if (val != NULL && SDL_strcmp(val, "1") == 0 ) {
devclass |= SDL_UDEV_DEVICE_TOUCHSCREEN;
}
@ -437,14 +437,14 @@ 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
*/
val = _this->syms.udev_device_get_property_value(dev, "ID_INPUT_KEY");
val = _this->udev_device_get_property_value(dev, "ID_INPUT_KEY");
if (val != NULL && SDL_strcmp(val, "1") == 0 ) {
devclass |= SDL_UDEV_DEVICE_KEYBOARD;
}
if (devclass == 0) {
/* Fall back to old style input classes */
val = _this->syms.udev_device_get_property_value(dev, "ID_CLASS");
val = _this->udev_device_get_property_value(dev, "ID_CLASS");
if (val != NULL) {
if (SDL_strcmp(val, "joystick") == 0) {
devclass = SDL_UDEV_DEVICE_JOYSTICK;
@ -481,11 +481,11 @@ SDL_UDEV_Poll(void)
}
while (SDL_UDEV_hotplug_update_available()) {
dev = _this->syms.udev_monitor_receive_device(_this->udev_mon);
dev = _this->udev_monitor_receive_device(_this->udev_mon);
if (dev == NULL) {
break;
}
action = _this->syms.udev_device_get_action(dev);
action = _this->udev_device_get_action(dev);
if (SDL_strcmp(action, "add") == 0) {
/* Wait for the device to finish initialization */
@ -496,7 +496,7 @@ SDL_UDEV_Poll(void)
device_event(SDL_UDEV_DEVICEREMOVED, dev);
}
_this->syms.udev_device_unref(dev);
_this->udev_device_unref(dev);
}
}
@ -547,22 +547,6 @@ SDL_UDEV_DelCallback(SDL_UDEV_Callback cb)
}
const SDL_UDEV_Symbols *
SDL_UDEV_GetUdevSyms(void)
{
if (SDL_UDEV_Init() < 0) {
SDL_SetError("Could not initialize UDEV");
return NULL;
}
return &_this->syms;
}
void
SDL_UDEV_ReleaseUdevSyms(void)
{
SDL_UDEV_Quit();
}
#endif /* SDL_USE_LIBUDEV */

View file

@ -64,13 +64,22 @@ typedef struct SDL_UDEV_CallbackList {
struct SDL_UDEV_CallbackList *next;
} SDL_UDEV_CallbackList;
typedef struct SDL_UDEV_Symbols {
typedef struct SDL_UDEV_PrivateData
{
const char *udev_library;
void *udev_handle;
struct udev *udev;
struct udev_monitor *udev_mon;
int ref_count;
SDL_UDEV_CallbackList *first, *last;
/* Function pointers */
const char *(*udev_device_get_action)(struct udev_device *);
const char *(*udev_device_get_devnode)(struct udev_device *);
const char *(*udev_device_get_subsystem)(struct udev_device *);
struct udev_device *(*udev_device_get_parent_with_subsystem_devtype)(struct udev_device *udev_device, const char *subsystem, const char *devtype);
struct udev_device *(*udev_device_get_parent_with_subsystem_devtype)(struct udev_device *udev_device, const char *subsystem, const char *devtype);
const char *(*udev_device_get_property_value)(struct udev_device *, const char *);
const char *(*udev_device_get_sysattr_value)(struct udev_device *udev_device, const char *sysattr);
const char *(*udev_device_get_sysattr_value)(struct udev_device *udev_device, const char *sysattr);
struct udev_device *(*udev_device_new_from_syspath)(struct udev *, const char *);
void (*udev_device_unref)(struct udev_device *);
int (*udev_enumerate_add_match_property)(struct udev_enumerate *, const char *, const char *);
@ -91,19 +100,6 @@ typedef struct SDL_UDEV_Symbols {
void (*udev_unref)(struct udev *);
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);
} SDL_UDEV_Symbols;
typedef struct SDL_UDEV_PrivateData
{
const char *udev_library;
void *udev_handle;
struct udev *udev;
struct udev_monitor *udev_mon;
int ref_count;
SDL_UDEV_CallbackList *first, *last;
/* Function pointers */
SDL_UDEV_Symbols syms;
} SDL_UDEV_PrivateData;
extern int SDL_UDEV_Init(void);
@ -114,8 +110,8 @@ extern void SDL_UDEV_Poll(void);
extern void SDL_UDEV_Scan(void);
extern int SDL_UDEV_AddCallback(SDL_UDEV_Callback cb);
extern void SDL_UDEV_DelCallback(SDL_UDEV_Callback cb);
extern const SDL_UDEV_Symbols *SDL_UDEV_GetUdevSyms(void);
extern void SDL_UDEV_ReleaseUdevSyms(void);
#endif /* HAVE_LIBUDEV_H */

View file

@ -31,9 +31,6 @@
#ifndef _WIN32_WINNT_VISTA
#define _WIN32_WINNT_VISTA 0x0600
#endif
#ifndef _WIN32_WINNT_WIN7
#define _WIN32_WINNT_WIN7 0x0601
#endif
/* Sets an error message based on an HRESULT */

View file

@ -44,7 +44,7 @@ SDL_bool WINRT_XAMLWasEnabled = SDL_FALSE;
#if WINAPI_FAMILY == WINAPI_FAMILY_APP
extern "C"
ISwapChainBackgroundPanelNative * WINRT_GlobalSwapChainBackgroundPanelNative = NULL;
static Windows::Foundation::EventRegistrationToken WINRT_XAMLAppEventToken;
static Windows::Foundation::EventRegistrationToken WINRT_XAMLAppEventToken;
#endif

View file

@ -22,7 +22,6 @@
#include "SDL_config.h"
#else
#include "../SDL_internal.h"
#include "SDL_simd.h"
#endif
#if defined(__WIN32__)
@ -39,7 +38,6 @@
/* CPU feature detection for SDL */
#include "SDL_cpuinfo.h"
#include "SDL_assert.h"
#ifdef HAVE_SYSCONF
#include <unistd.h>
@ -78,19 +76,18 @@
#endif
#endif
#define CPU_HAS_RDTSC (1 << 0)
#define CPU_HAS_ALTIVEC (1 << 1)
#define CPU_HAS_MMX (1 << 2)
#define CPU_HAS_3DNOW (1 << 3)
#define CPU_HAS_SSE (1 << 4)
#define CPU_HAS_SSE2 (1 << 5)
#define CPU_HAS_SSE3 (1 << 6)
#define CPU_HAS_SSE41 (1 << 7)
#define CPU_HAS_SSE42 (1 << 8)
#define CPU_HAS_AVX (1 << 9)
#define CPU_HAS_AVX2 (1 << 10)
#define CPU_HAS_NEON (1 << 11)
#define CPU_HAS_AVX512F (1 << 12)
#define CPU_HAS_RDTSC 0x00000001
#define CPU_HAS_ALTIVEC 0x00000002
#define CPU_HAS_MMX 0x00000004
#define CPU_HAS_3DNOW 0x00000008
#define CPU_HAS_SSE 0x00000010
#define CPU_HAS_SSE2 0x00000020
#define CPU_HAS_SSE3 0x00000040
#define CPU_HAS_SSE41 0x00000100
#define CPU_HAS_SSE42 0x00000200
#define CPU_HAS_AVX 0x00000400
#define CPU_HAS_AVX2 0x00000800
#define CPU_HAS_NEON 0x00001000
#if SDL_ALTIVEC_BLITTERS && HAVE_SETJMP && !__MACOSX__ && !__OpenBSD__
/* This is the brute force way of detecting instruction sets...
@ -249,7 +246,6 @@ done:
static int CPU_CPUIDFeatures[4];
static int CPU_CPUIDMaxFunction = 0;
static SDL_bool CPU_OSSavesYMM = SDL_FALSE;
static SDL_bool CPU_OSSavesZMM = SDL_FALSE;
static void
CPU_calcCPUIDFeatures(void)
@ -270,7 +266,7 @@ CPU_calcCPUIDFeatures(void)
/* Check to make sure we can call xgetbv */
if (c & 0x08000000) {
/* Call xgetbv to see if YMM (etc) register state is saved */
/* Call xgetbv to see if YMM register state is saved */
#if defined(__GNUC__) && (defined(i386) || defined(__x86_64__))
__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 */
@ -284,7 +280,6 @@ CPU_calcCPUIDFeatures(void)
}
#endif
CPU_OSSavesYMM = ((a & 6) == 6) ? SDL_TRUE : SDL_FALSE;
CPU_OSSavesZMM = (CPU_OSSavesYMM && ((a & 0xe0) == 0xe0)) ? SDL_TRUE : SDL_FALSE;
}
}
}
@ -405,18 +400,6 @@ CPU_haveAVX2(void)
return 0;
}
static int
CPU_haveAVX512F(void)
{
if (CPU_OSSavesZMM && (CPU_CPUIDMaxFunction >= 7)) {
int a, b, c, d;
(void) a; (void) b; (void) c; (void) d; /* compiler warnings... */
cpuid(7, a, b, c, d);
return (b & 0x00010000);
}
return 0;
}
static int SDL_CPUCount = 0;
int
@ -588,7 +571,6 @@ SDL_GetCPUCacheLineSize(void)
}
static Uint32 SDL_CPUFeatures = 0xFFFFFFFF;
static Uint32 SDL_SIMDAlignment = 0xFFFFFFFF;
static Uint32
SDL_GetCPUFeatures(void)
@ -596,57 +578,41 @@ SDL_GetCPUFeatures(void)
if (SDL_CPUFeatures == 0xFFFFFFFF) {
CPU_calcCPUIDFeatures();
SDL_CPUFeatures = 0;
SDL_SIMDAlignment = 4; /* a good safe base value */
if (CPU_haveRDTSC()) {
SDL_CPUFeatures |= CPU_HAS_RDTSC;
}
if (CPU_haveAltiVec()) {
SDL_CPUFeatures |= CPU_HAS_ALTIVEC;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 16);
}
if (CPU_haveMMX()) {
SDL_CPUFeatures |= CPU_HAS_MMX;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 8);
}
if (CPU_have3DNow()) {
SDL_CPUFeatures |= CPU_HAS_3DNOW;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 8);
}
if (CPU_haveSSE()) {
SDL_CPUFeatures |= CPU_HAS_SSE;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 16);
}
if (CPU_haveSSE2()) {
SDL_CPUFeatures |= CPU_HAS_SSE2;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 16);
}
if (CPU_haveSSE3()) {
SDL_CPUFeatures |= CPU_HAS_SSE3;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 16);
}
if (CPU_haveSSE41()) {
SDL_CPUFeatures |= CPU_HAS_SSE41;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 16);
}
if (CPU_haveSSE42()) {
SDL_CPUFeatures |= CPU_HAS_SSE42;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 16);
}
if (CPU_haveAVX()) {
SDL_CPUFeatures |= CPU_HAS_AVX;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 32);
}
if (CPU_haveAVX2()) {
SDL_CPUFeatures |= CPU_HAS_AVX2;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 32);
}
if (CPU_haveAVX512F()) {
SDL_CPUFeatures |= CPU_HAS_AVX512F;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 64);
}
if (CPU_haveNEON()) {
SDL_CPUFeatures |= CPU_HAS_NEON;
SDL_SIMDAlignment = SDL_max(SDL_SIMDAlignment, 16);
}
}
return SDL_CPUFeatures;
@ -719,12 +685,6 @@ SDL_HasAVX2(void)
return CPU_FEATURE_AVAILABLE(CPU_HAS_AVX2);
}
SDL_bool
SDL_HasAVX512F(void)
{
return CPU_FEATURE_AVAILABLE(CPU_HAS_AVX512F);
}
SDL_bool
SDL_HasNEON(void)
{
@ -785,44 +745,6 @@ SDL_GetSystemRAM(void)
}
size_t
SDL_SIMDGetAlignment(void)
{
if (SDL_SIMDAlignment == 0xFFFFFFFF) {
SDL_GetCPUFeatures(); /* make sure this has been calculated */
}
SDL_assert(SDL_SIMDAlignment != 0);
return SDL_SIMDAlignment;
}
void *
SDL_SIMDAlloc(const size_t len)
{
const size_t alignment = SDL_SIMDGetAlignment();
const size_t padding = alignment - (len % alignment);
const size_t padded = (padding != alignment) ? (len + padding) : len;
Uint8 *retval = NULL;
Uint8 *ptr = (Uint8 *) SDL_malloc(padded + alignment + sizeof (void *));
if (ptr) {
/* store the actual malloc pointer right before our aligned pointer. */
retval = ptr + sizeof (void *);
retval += alignment - (((size_t) retval) % alignment);
*(((void **) retval) - 1) = ptr;
}
return retval;
}
void
SDL_SIMDFree(void *ptr)
{
if (ptr) {
void **realptr = (void **) ptr;
realptr--;
SDL_free(*(((void **) ptr) - 1));
}
}
#ifdef TEST_MAIN
#include <stdio.h>
@ -845,7 +767,6 @@ main()
printf("SSE4.2: %d\n", SDL_HasSSE42());
printf("AVX: %d\n", SDL_HasAVX());
printf("AVX2: %d\n", SDL_HasAVX2());
printf("AVX-512F: %d\n", SDL_HasAVX512F());
printf("NEON: %d\n", SDL_HasNEON());
printf("RAM: %d MB\n", SDL_GetSystemRAM());
return 0;

View file

@ -1,88 +0,0 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL.h"
#include "../SDL_internal.h"
/**
* \brief Report the alignment this system needs for SIMD allocations.
*
* This will return the minimum number of bytes to which a pointer must be
* aligned to be compatible with SIMD instructions on the current machine.
* For example, if the machine supports SSE only, it will return 16, but if
* it supports AVX-512F, it'll return 64 (etc). This only reports values for
* instruction sets SDL knows about, so if your SDL build doesn't have
* SDL_HasAVX512F(), then it might return 16 for the SSE support it sees and
* not 64 for the AVX-512 instructions that exist but SDL doesn't know about.
* Plan accordingly.
*/
extern size_t SDL_SIMDGetAlignment(void);
/**
* \brief Allocate memory in a SIMD-friendly way.
*
* This will allocate a block of memory that is suitable for use with SIMD
* instructions. Specifically, it will be properly aligned and padded for
* the system's supported vector instructions.
*
* The memory returned will be padded such that it is safe to read or write
* an incomplete vector at the end of the memory block. This can be useful
* so you don't have to drop back to a scalar fallback at the end of your
* SIMD processing loop to deal with the final elements without overflowing
* the allocated buffer.
*
* You must free this memory with SDL_FreeSIMD(), not free() or SDL_free()
* or delete[], etc.
*
* Note that SDL will only deal with SIMD instruction sets it is aware of;
* for example, SDL 2.0.8 knows that SSE wants 16-byte vectors
* (SDL_HasSSE()), and AVX2 wants 32 bytes (SDL_HasAVX2()), but doesn't
* know that AVX-512 wants 64. To be clear: if you can't decide to use an
* instruction set with an SDL_Has*() function, don't use that instruction
* set with memory allocated through here.
*
* SDL_AllocSIMD(0) will return a non-NULL pointer, assuming the system isn't
* out of memory.
*
* \param len The length, in bytes, of the block to allocated. The actual
* allocated block might be larger due to padding, etc.
* \return Pointer to newly-allocated block, NULL if out of memory.
*
* \sa SDL_SIMDAlignment
* \sa SDL_SIMDFree
*/
extern void * SDL_SIMDAlloc(const size_t len);
/**
* \brief Deallocate memory obtained from SDL_SIMDAlloc
*
* It is not valid to use this function on a pointer from anything but
* SDL_SIMDAlloc(). It can't be used on pointers from malloc, realloc,
* SDL_malloc, memalign, new[], etc.
*
* However, SDL_SIMDFree(NULL) is a legal no-op.
*
* \sa SDL_SIMDAlloc
*/
extern void SDL_SIMDFree(void *ptr);
/* vi: set ts=4 sw=4 expandtab: */

View file

@ -27,7 +27,6 @@
#if defined(__OS2__)
#define INCL_DOS
#define INCL_DOSERRORS
#include <os2.h>
#include <dos.h>
#endif
@ -168,10 +167,15 @@ SDL_DYNAPI_VARARGS(,,)
#error Write me.
#endif
/* 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. */
static Sint32
initialize_jumptable(Uint32 apiver, void *table, Uint32 tablesize)
/* Here's the exported entry point that fills in the jump table. */
/* Use specific types when an "int" might suffice to keep this sane. */
typedef Sint32 (SDLCALL *SDL_DYNAPI_ENTRYFN)(Uint32 apiver, void *table, Uint32 tablesize);
extern DECLSPEC Sint32 SDLCALL SDL_DYNAPI_entry(Uint32, void *, Uint32);
Sint32
SDL_DYNAPI_entry(Uint32 apiver, void *table, Uint32 tablesize)
{
SDL_DYNAPI_jump_table *output_jump_table = (SDL_DYNAPI_jump_table *) table;
@ -198,18 +202,6 @@ initialize_jumptable(Uint32 apiver, void *table, Uint32 tablesize)
}
/* Here's the exported entry point that fills in the jump table. */
/* Use specific types when an "int" might suffice to keep this sane. */
typedef Sint32 (SDLCALL *SDL_DYNAPI_ENTRYFN)(Uint32 apiver, void *table, Uint32 tablesize);
extern DECLSPEC Sint32 SDLCALL SDL_DYNAPI_entry(Uint32, void *, Uint32);
Sint32
SDL_DYNAPI_entry(Uint32 apiver, void *table, Uint32 tablesize)
{
return initialize_jumptable(apiver, table, tablesize);
}
/* Obviously we can't use SDL_LoadObject() to load SDL. :) */
/* Also obviously, we never close the loaded library. */
#if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__)
@ -268,7 +260,7 @@ static void
SDL_InitDynamicAPILocked(void)
{
const char *libname = SDL_getenv_REAL("SDL_DYNAMIC_API");
SDL_DYNAPI_ENTRYFN entry = NULL; /* funcs from here by default. */
SDL_DYNAPI_ENTRYFN entry = SDL_DYNAPI_entry; /* funcs from here by default. */
if (libname) {
entry = (SDL_DYNAPI_ENTRYFN) get_sdlapi_entry(libname, "SDL_DYNAPI_entry");
@ -276,15 +268,16 @@ SDL_InitDynamicAPILocked(void)
/* !!! FIXME: fail to startup here instead? */
/* !!! FIXME: definitely warn user. */
/* Just fill in the function pointers from this library. */
entry = SDL_DYNAPI_entry;
}
}
if (!entry || (entry(SDL_DYNAPI_VERSION, &jump_table, sizeof (jump_table)) < 0)) {
if (entry(SDL_DYNAPI_VERSION, &jump_table, sizeof (jump_table)) < 0) {
/* !!! FIXME: fail to startup here instead? */
/* !!! FIXME: definitely warn user. */
/* Just fill in the function pointers from this library. */
if (!entry) {
if (!initialize_jumptable(SDL_DYNAPI_VERSION, &jump_table, sizeof (jump_table))) {
if (entry != SDL_DYNAPI_entry) {
if (!SDL_DYNAPI_entry(SDL_DYNAPI_VERSION, &jump_table, sizeof (jump_table))) {
/* !!! FIXME: now we're screwed. Should definitely abort now. */
}
}

View file

@ -669,35 +669,3 @@
#define SDL_WinRTGetDeviceFamily SDL_WinRTGetDeviceFamily_REAL
#define SDL_log10 SDL_log10_REAL
#define SDL_log10f SDL_log10f_REAL
#define SDL_GameControllerMappingForDeviceIndex SDL_GameControllerMappingForDeviceIndex_REAL
#define SDL_LinuxSetThreadPriority SDL_LinuxSetThreadPriority_REAL
#define SDL_HasAVX512F SDL_HasAVX512F_REAL
#define SDL_IsChromebook SDL_IsChromebook_REAL
#define SDL_IsDeXMode SDL_IsDeXMode_REAL
#define SDL_AndroidBackButton SDL_AndroidBackButton_REAL
#define SDL_exp SDL_exp_REAL
#define SDL_expf SDL_expf_REAL
#define SDL_wcsdup SDL_wcsdup_REAL
#define SDL_GameControllerRumble SDL_GameControllerRumble_REAL
#define SDL_JoystickRumble SDL_JoystickRumble_REAL
#define SDL_NumSensors SDL_NumSensors_REAL
#define SDL_SensorGetDeviceName SDL_SensorGetDeviceName_REAL
#define SDL_SensorGetDeviceType SDL_SensorGetDeviceType_REAL
#define SDL_SensorGetDeviceNonPortableType SDL_SensorGetDeviceNonPortableType_REAL
#define SDL_SensorGetDeviceInstanceID SDL_SensorGetDeviceInstanceID_REAL
#define SDL_SensorOpen SDL_SensorOpen_REAL
#define SDL_SensorFromInstanceID SDL_SensorFromInstanceID_REAL
#define SDL_SensorGetName SDL_SensorGetName_REAL
#define SDL_SensorGetType SDL_SensorGetType_REAL
#define SDL_SensorGetNonPortableType SDL_SensorGetNonPortableType_REAL
#define SDL_SensorGetInstanceID SDL_SensorGetInstanceID_REAL
#define SDL_SensorGetData SDL_SensorGetData_REAL
#define SDL_SensorClose SDL_SensorClose_REAL
#define SDL_SensorUpdate SDL_SensorUpdate_REAL
#define SDL_IsTablet SDL_IsTablet_REAL
#define SDL_GetDisplayOrientation SDL_GetDisplayOrientation_REAL
#define SDL_HasColorKey SDL_HasColorKey_REAL
#define SDL_CreateThreadWithStackSize SDL_CreateThreadWithStackSize_REAL
#define SDL_JoystickGetDevicePlayerIndex SDL_JoystickGetDevicePlayerIndex_REAL
#define SDL_JoystickGetPlayerIndex SDL_JoystickGetPlayerIndex_REAL
#define SDL_GameControllerGetPlayerIndex SDL_GameControllerGetPlayerIndex_REAL

View file

@ -707,51 +707,3 @@ SDL_DYNAPI_PROC(SDL_bool,SDL_IsAndroidTV,(void),(),return)
#endif
SDL_DYNAPI_PROC(double,SDL_log10,(double a),(a),return)
SDL_DYNAPI_PROC(float,SDL_log10f,(float a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_GameControllerMappingForDeviceIndex,(int a),(a),return)
#ifdef __LINUX__
SDL_DYNAPI_PROC(int,SDL_LinuxSetThreadPriority,(Sint64 a, int b),(a,b),return)
#endif
SDL_DYNAPI_PROC(SDL_bool,SDL_HasAVX512F,(void),(),return)
#ifdef __ANDROID__
SDL_DYNAPI_PROC(SDL_bool,SDL_IsChromebook,(void),(),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_IsDeXMode,(void),(),return)
SDL_DYNAPI_PROC(void,SDL_AndroidBackButton,(void),(),return)
#endif
SDL_DYNAPI_PROC(double,SDL_exp,(double a),(a),return)
SDL_DYNAPI_PROC(float,SDL_expf,(float a),(a),return)
SDL_DYNAPI_PROC(wchar_t*,SDL_wcsdup,(const wchar_t *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GameControllerRumble,(SDL_GameController *a, Uint16 b, Uint16 c, Uint32 d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_JoystickRumble,(SDL_Joystick *a, Uint16 b, Uint16 c, Uint32 d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_NumSensors,(void),(),return)
SDL_DYNAPI_PROC(const char*,SDL_SensorGetDeviceName,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_SensorType,SDL_SensorGetDeviceType,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SensorGetDeviceNonPortableType,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_SensorID,SDL_SensorGetDeviceInstanceID,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_Sensor*,SDL_SensorOpen,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_Sensor*,SDL_SensorFromInstanceID,(SDL_SensorID a),(a),return)
SDL_DYNAPI_PROC(const char*,SDL_SensorGetName,(SDL_Sensor *a),(a),return)
SDL_DYNAPI_PROC(SDL_SensorType,SDL_SensorGetType,(SDL_Sensor *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SensorGetNonPortableType,(SDL_Sensor *a),(a),return)
SDL_DYNAPI_PROC(SDL_SensorID,SDL_SensorGetInstanceID,(SDL_Sensor *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SensorGetData,(SDL_Sensor *a, float *b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_SensorClose,(SDL_Sensor *a),(a),)
SDL_DYNAPI_PROC(void,SDL_SensorUpdate,(void),(),)
SDL_DYNAPI_PROC(SDL_bool,SDL_IsTablet,(void),(),return)
SDL_DYNAPI_PROC(SDL_DisplayOrientation,SDL_GetDisplayOrientation,(int a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_HasColorKey,(SDL_Surface *a),(a),return)
#ifdef SDL_CreateThreadWithStackSize
#undef SDL_CreateThreadWithStackSize
#endif
#if defined(__WIN32__) && !defined(HAVE_LIBC)
SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThreadWithStackSize,(SDL_ThreadFunction a, const char *b, const size_t c, void *d, pfnSDL_CurrentBeginThread e, pfnSDL_CurrentEndThread f),(a,b,c,d,e,f),return)
#elif defined(__OS2__)
SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThreadWithStackSize,(SDL_ThreadFunction a, const char *b, const size_t c, void *d, pfnSDL_CurrentBeginThread e, pfnSDL_CurrentEndThread f),(a,b,c,d,e,f),return)
#else
SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThreadWithStackSize,(SDL_ThreadFunction a, const char *b, const size_t c, void *d),(a,b,c,d),return)
#endif
SDL_DYNAPI_PROC(int,SDL_JoystickGetDevicePlayerIndex,(int a),(a),return)
SDL_DYNAPI_PROC(int,SDL_JoystickGetPlayerIndex,(SDL_Joystick *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GameControllerGetPlayerIndex,(SDL_GameController *a),(a),return)

View file

@ -1,60 +0,0 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../SDL_internal.h"
/* Display event handling code for SDL */
#include "SDL_events.h"
#include "SDL_events_c.h"
int
SDL_SendDisplayEvent(SDL_VideoDisplay *display, Uint8 displayevent, int data1)
{
int posted;
if (!display) {
return 0;
}
switch (displayevent) {
case SDL_DISPLAYEVENT_ORIENTATION:
if (data1 == SDL_ORIENTATION_UNKNOWN || data1 == display->orientation) {
return 0;
}
display->orientation = (SDL_DisplayOrientation)data1;
break;
}
/* Post the event, if desired */
posted = 0;
if (SDL_GetEventState(SDL_DISPLAYEVENT) == SDL_ENABLE) {
SDL_Event event;
event.type = SDL_DISPLAYEVENT;
event.display.event = displayevent;
event.display.display = SDL_GetIndexOfDisplay(display);
event.display.data1 = data1;
posted = (SDL_PushEvent(&event) > 0);
}
return (posted);
}
/* vi: set ts=4 sw=4 expandtab: */

View file

@ -1,30 +0,0 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../SDL_internal.h"
#ifndef SDL_displayevents_c_h_
#define SDL_displayevents_c_h_
extern int SDL_SendDisplayEvent(SDL_VideoDisplay *display, Uint8 displayevent, int data1);
#endif /* SDL_displayevents_c_h_ */
/* vi: set ts=4 sw=4 expandtab: */

View file

@ -417,10 +417,6 @@ SDL_StartEventLoop(void)
SDL_EventState(SDL_TEXTINPUT, SDL_DISABLE);
SDL_EventState(SDL_TEXTEDITING, SDL_DISABLE);
SDL_EventState(SDL_SYSWMEVENT, SDL_DISABLE);
#if 0 /* Leave these events enabled so apps can respond to items being dragged onto them at startup */
SDL_EventState(SDL_DROPFILE, SDL_DISABLE);
SDL_EventState(SDL_DROPTEXT, SDL_DISABLE);
#endif
SDL_AtomicSet(&SDL_EventQ.active, 1);
@ -608,10 +604,6 @@ SDL_FlushEvent(Uint32 type)
void
SDL_FlushEvents(Uint32 minType, Uint32 maxType)
{
/* !!! FIXME: we need to manually SDL_free() the strings in TEXTINPUT and
drag'n'drop events if we're flushing them without passing them to the
app, but I don't know if this is the right place to do that. */
/* Don't look after we've quit */
if (!SDL_AtomicGet(&SDL_EventQ.active)) {
return;
@ -659,13 +651,6 @@ SDL_PumpEvents(void)
}
#endif
#if !SDL_SENSOR_DISABLED
/* Check for sensor state change */
if (!SDL_disabled_events[SDL_SENSORUPDATE >> 8]) {
SDL_SensorUpdate();
}
#endif
SDL_SendPendingQuit(); /* in case we had a signal handler fire, etc. */
}
@ -878,8 +863,6 @@ SDL_FilterEvents(SDL_EventFilter filter, void *userdata)
Uint8
SDL_EventState(Uint32 type, int state)
{
const SDL_bool isdnd = ((state == SDL_DISABLE) || (state == SDL_ENABLE)) &&
((type == SDL_DROPFILE) || (type == SDL_DROPTEXT));
Uint8 current_state;
Uint8 hi = ((type >> 8) & 0xff);
Uint8 lo = (type & 0xff);
@ -915,12 +898,6 @@ SDL_EventState(Uint32 type, int state)
}
}
/* turn off drag'n'drop support if we've disabled the events.
This might change some UI details at the OS level. */
if (isdnd) {
SDL_ToggleDragAndDropSupport();
}
return current_state;
}

View file

@ -18,19 +18,12 @@
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_events_c_h_
#define SDL_events_c_h_
#include "../SDL_internal.h"
/* Useful functions and variables from SDL_events.c */
#include "SDL_events.h"
#include "SDL_thread.h"
#include "../video/SDL_sysvideo.h"
#include "SDL_clipboardevents_c.h"
#include "SDL_displayevents_c.h"
#include "SDL_dropevents_c.h"
#include "SDL_gesture_c.h"
#include "SDL_keyboard_c.h"
@ -53,6 +46,4 @@ extern void SDL_QuitQuit(void);
extern void SDL_SendPendingQuit(void);
#endif /* SDL_events_c_h_ */
/* vi: set ts=4 sw=4 expandtab: */

View file

@ -33,38 +33,12 @@
/* The mouse state */
static SDL_Mouse SDL_mouse;
static Uint32 SDL_double_click_time = 500;
static int SDL_double_click_radius = 1;
static int
SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int x, int y);
static void SDLCALL
SDL_MouseDoubleClickTimeChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
SDL_Mouse *mouse = (SDL_Mouse *)userdata;
if (hint && *hint) {
mouse->double_click_time = SDL_atoi(hint);
} else {
#ifdef __WIN32__
mouse->double_click_time = GetDoubleClickTime();
#else
mouse->double_click_time = 500;
#endif
}
}
static void SDLCALL
SDL_MouseDoubleClickRadiusChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
SDL_Mouse *mouse = (SDL_Mouse *)userdata;
if (hint && *hint) {
mouse->double_click_radius = SDL_atoi(hint);
} else {
mouse->double_click_radius = 32; /* 32 pixels seems about right for touch interfaces */
}
}
static void SDLCALL
SDL_MouseNormalSpeedScaleChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
@ -109,12 +83,6 @@ SDL_MouseInit(void)
SDL_zerop(mouse);
SDL_AddHintCallback(SDL_HINT_MOUSE_DOUBLE_CLICK_TIME,
SDL_MouseDoubleClickTimeChanged, mouse);
SDL_AddHintCallback(SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS,
SDL_MouseDoubleClickRadiusChanged, mouse);
SDL_AddHintCallback(SDL_HINT_MOUSE_NORMAL_SPEED_SCALE,
SDL_MouseNormalSpeedScaleChanged, mouse);
@ -146,6 +114,12 @@ SDL_GetMouse(void)
return &SDL_mouse;
}
void
SDL_SetDoubleClickTime(Uint32 interval)
{
SDL_double_click_time = interval;
}
SDL_Window *
SDL_GetMouseFocus(void)
{
@ -480,9 +454,9 @@ SDL_PrivateSendMouseButton(SDL_Window * window, SDL_MouseID mouseID, Uint8 state
if (state == SDL_PRESSED) {
Uint32 now = SDL_GetTicks();
if (SDL_TICKS_PASSED(now, clickstate->last_timestamp + mouse->double_click_time) ||
SDL_abs(mouse->x - clickstate->last_x) > mouse->double_click_radius ||
SDL_abs(mouse->y - clickstate->last_y) > mouse->double_click_radius) {
if (SDL_TICKS_PASSED(now, clickstate->last_timestamp + SDL_double_click_time) ||
SDL_abs(mouse->x - clickstate->last_x) > SDL_double_click_radius ||
SDL_abs(mouse->y - clickstate->last_y) > SDL_double_click_radius) {
clickstate->click_count = 0;
}
clickstate->last_timestamp = now;
@ -714,7 +688,6 @@ static SDL_bool
ShouldUseRelativeModeWarp(SDL_Mouse *mouse)
{
if (!mouse->SetRelativeMouseMode) {
SDL_assert(mouse->WarpMouse); /* Need this functionality for relative mode warp implementation */
return SDL_TRUE;
}
@ -747,9 +720,6 @@ SDL_SetRelativeMouseMode(SDL_bool enabled)
} else if (mouse->SetRelativeMouseMode(enabled) < 0) {
if (enabled) {
/* Fall back to warp mode if native relative mode failed */
if (!mouse->WarpMouse) {
return SDL_SetError("No relative mode implementation available");
}
mouse->relative_mode_warp = SDL_TRUE;
}
}

View file

@ -90,8 +90,6 @@ typedef struct
float relative_speed_scale;
float scale_accum_x;
float scale_accum_y;
Uint32 double_click_time;
int double_click_radius;
SDL_bool touch_mouse_events;
/* Data for double-click tracking */
@ -114,6 +112,9 @@ extern int SDL_MouseInit(void);
/* Get the mouse state structure */
SDL_Mouse *SDL_GetMouse(void);
/* Set the default double-click interval */
extern void SDL_SetDoubleClickTime(Uint32 interval);
/* Set the default mouse cursor */
extern void SDL_SetDefaultCursor(SDL_Cursor * cursor);

View file

@ -25,16 +25,30 @@
#include "SDL_events.h"
#include "SDL_events_c.h"
#include "SDL_mouse_c.h"
#include "../video/SDL_sysvideo.h"
static int SDLCALL
RemovePendingSizeChangedAndResizedEvents(void * userdata, SDL_Event *event)
RemovePendingResizedEvents(void * userdata, SDL_Event *event)
{
SDL_Event *new_event = (SDL_Event *)userdata;
if (event->type == SDL_WINDOWEVENT &&
(event->window.event == SDL_WINDOWEVENT_SIZE_CHANGED ||
event->window.event == SDL_WINDOWEVENT_RESIZED) &&
event->window.event == SDL_WINDOWEVENT_RESIZED &&
event->window.windowID == new_event->window.windowID) {
/* We're about to post a new size event, drop the old one */
return 0;
}
return 1;
}
static int SDLCALL
RemovePendingSizeChangedEvents(void * userdata, SDL_Event *event)
{
SDL_Event *new_event = (SDL_Event *)userdata;
if (event->type == SDL_WINDOWEVENT &&
event->window.event == SDL_WINDOWEVENT_SIZE_CHANGED &&
event->window.windowID == new_event->window.windowID) {
/* We're about to post a new size event, drop the old one */
return 0;
@ -186,8 +200,11 @@ SDL_SendWindowEvent(SDL_Window * window, Uint8 windowevent, int data1,
event.window.windowID = window->id;
/* Fixes queue overflow with resize events that aren't processed */
if (windowevent == SDL_WINDOWEVENT_RESIZED) {
SDL_FilterEvents(RemovePendingResizedEvents, &event);
}
if (windowevent == SDL_WINDOWEVENT_SIZE_CHANGED) {
SDL_FilterEvents(RemovePendingSizeChangedAndResizedEvents, &event);
SDL_FilterEvents(RemovePendingSizeChangedEvents, &event);
}
if (windowevent == SDL_WINDOWEVENT_MOVED) {
SDL_FilterEvents(RemovePendingMoveEvents, &event);

View file

@ -18,10 +18,6 @@
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef scancodes_xfree86_h_
#define scancodes_xfree86_h_
#include "../../include/SDL_scancode.h"
/* XFree86 key code to SDL scancode mapping table
@ -507,6 +503,4 @@ static const SDL_Scancode xvnc_scancode_table[] = {
/* 80 */ SDL_SCANCODE_F12,
};
#endif /* scancodes_xfree86_h_ */
/* *INDENT-ON* */

View file

@ -389,11 +389,9 @@ SDL_HapticClose(SDL_Haptic * haptic)
void
SDL_HapticQuit(void)
{
while (SDL_haptics) {
SDL_HapticClose(SDL_haptics);
}
SDL_SYS_HapticQuit();
SDL_assert(SDL_haptics == NULL);
SDL_haptics = NULL;
}
/*
@ -767,7 +765,6 @@ SDL_HapticRumbleInit(SDL_Haptic * haptic)
SDL_zerop(efx);
if (haptic->supported & SDL_HAPTIC_SINE) {
efx->type = SDL_HAPTIC_SINE;
efx->periodic.direction.type = SDL_HAPTIC_CARTESIAN;
efx->periodic.period = 1000;
efx->periodic.magnitude = 0x4000;
efx->periodic.length = 5000;

View file

@ -19,12 +19,7 @@
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_haptic_c_h_
#define SDL_haptic_c_h_
extern int SDL_HapticInit(void);
extern void SDL_HapticQuit(void);
#endif /* SDL_haptic_c_h_ */
/* vi: set ts=4 sw=4 expandtab: */

View file

@ -195,10 +195,6 @@ SDL_SYS_HapticClose(SDL_Haptic * haptic)
void
SDL_SYS_HapticQuit(void)
{
/* We don't have any way to scan for joysticks (and their vibrators) at init, so don't wipe the list
* of joysticks here in case this is a reinit.
*/
#if 0
SDL_hapticlist_item *item = NULL;
SDL_hapticlist_item *next = NULL;
@ -210,7 +206,6 @@ SDL_SYS_HapticQuit(void)
SDL_hapticlist = SDL_hapticlist_tail = NULL;
numhaptics = 0;
return;
#endif
}
@ -235,12 +230,7 @@ int
SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect,
Uint32 iterations)
{
float large = effect->effect.leftright.large_magnitude / 32767.0f;
float small = effect->effect.leftright.small_magnitude / 32767.0f;
float total = (large * 0.6f) + (small * 0.4f);
Android_JNI_HapticRun (((SDL_hapticlist_item *)haptic->hwdata)->device_id, total, effect->effect.leftright.length);
Android_JNI_HapticRun (((SDL_hapticlist_item *)haptic->hwdata)->device_id, effect->effect.leftright.length);
return 0;
}
@ -248,7 +238,6 @@ SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect,
int
SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect)
{
Android_JNI_HapticStop (((SDL_hapticlist_item *)haptic->hwdata)->device_id);
return 0;
}

View file

@ -181,9 +181,6 @@ SDL_SYS_HapticInit(void)
SDL_UDEV_Quit();
return SDL_SetError("Could not setup haptic <-> udev callback");
}
/* Force a scan to build the initial device list */
SDL_UDEV_Scan();
#endif /* SDL_USE_LIBUDEV */
return numhaptics;
@ -801,8 +798,7 @@ SDL_SYS_ToFFEffect(struct ff_effect *dest, SDL_HapticEffect * src)
else if (periodic->type == SDL_HAPTIC_SAWTOOTHDOWN)
dest->u.periodic.waveform = FF_SAW_DOWN;
dest->u.periodic.period = CLAMP(periodic->period);
/* Linux expects 0-65535, so multiply by 2 */
dest->u.periodic.magnitude = CLAMP(periodic->magnitude) * 2;
dest->u.periodic.magnitude = periodic->magnitude;
dest->u.periodic.offset = periodic->offset;
/* Linux phase is defined in interval "[0x0000, 0x10000[", corresponds with "[0deg, 360deg[" phase shift. */
dest->u.periodic.phase = ((Uint32)periodic->phase * 0x10000U) / 36000;
@ -909,9 +905,9 @@ SDL_SYS_ToFFEffect(struct ff_effect *dest, SDL_HapticEffect * src)
dest->trigger.button = 0;
dest->trigger.interval = 0;
/* Rumble (Linux expects 0-65535, so multiply by 2) */
dest->u.rumble.strong_magnitude = CLAMP(leftright->large_magnitude) * 2;
dest->u.rumble.weak_magnitude = CLAMP(leftright->small_magnitude) * 2;
/* Rumble */
dest->u.rumble.strong_magnitude = leftright->large_magnitude;
dest->u.rumble.weak_magnitude = leftright->small_magnitude;
break;

View file

@ -157,7 +157,7 @@ SDL_SYS_HapticMouse(void)
/* Grab the first mouse haptic device we find. */
for (item = SDL_hapticlist; item != NULL; item = item->next) {
if (item->capabilities.dwDevType == DI8DEVCLASS_POINTER) {
if (item->capabilities.dwDevType == DI8DEVCLASS_POINTER ) {
return index;
}
++index;
@ -173,16 +173,14 @@ SDL_SYS_HapticMouse(void)
int
SDL_SYS_JoystickIsHaptic(SDL_Joystick * joystick)
{
if (joystick->driver != &SDL_WINDOWS_JoystickDriver) {
return 0;
}
const struct joystick_hwdata *hwdata = joystick->hwdata;
#if SDL_HAPTIC_XINPUT
if (joystick->hwdata->bXInputHaptic) {
if (hwdata->bXInputHaptic) {
return 1;
}
#endif
#if SDL_HAPTIC_DINPUT
if (joystick->hwdata->Capabilities.dwFlags & DIDC_FORCEFEEDBACK) {
if (hwdata->Capabilities.dwFlags & DIDC_FORCEFEEDBACK) {
return 1;
}
#endif
@ -195,9 +193,6 @@ SDL_SYS_JoystickIsHaptic(SDL_Joystick * joystick)
int
SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick)
{
if (joystick->driver != &SDL_WINDOWS_JoystickDriver) {
return 0;
}
if (joystick->hwdata->bXInputHaptic != haptic->hwdata->bXInputHaptic) {
return 0; /* one is XInput, one is not; not the same device. */
} else if (joystick->hwdata->bXInputHaptic) {
@ -213,8 +208,6 @@ SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick)
int
SDL_SYS_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick)
{
SDL_assert(joystick->driver == &SDL_WINDOWS_JoystickDriver);
if (joystick->hwdata->bXInputDevice) {
return SDL_XINPUT_HapticOpenFromJoystick(haptic, joystick);
} else {

View file

@ -1,16 +0,0 @@
HIDAPI Authors:
Alan Ott <alan@signal11.us>:
Original Author and Maintainer
Linux, Windows, and Mac implementations
Ludovic Rousseau <rousseau@debian.org>:
Formatting for Doxygen documentation
Bug fixes
Correctness fixes
For a comprehensive list of contributions, see the commit list at github:
http://github.com/signal11/hidapi/commits/master

View file

@ -1,15 +0,0 @@
This file is mostly for the maintainer.
1. Build hidapi.dll
2. Build hidtest.exe in DEBUG and RELEASE
3. Commit all
4. Run the Following
export VERSION=0.1.0
export TAG_NAME=hidapi-$VERSION
git tag $TAG_NAME
git archive --format zip --prefix $TAG_NAME/ $TAG_NAME >../$TAG_NAME.zip
5. Test the zip file.
6. Run the following:
git push origin $TAG_NAME

View file

@ -1,26 +0,0 @@
Copyright (c) 2010, Alan Ott, Signal 11 Software
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Signal 11 Software nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

View file

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -1,9 +0,0 @@
HIDAPI - Multi-Platform library for
communication with HID devices.
Copyright 2009, Alan Ott, Signal 11 Software.
All Rights Reserved.
This software may be used by anyone for any reason so
long as the copyright notice in the source files
remains intact.

View file

@ -1,13 +0,0 @@
HIDAPI can be used under one of three licenses.
1. The GNU General Public License, version 3.0, in LICENSE-gpl3.txt
2. A BSD-Style License, in LICENSE-bsd.txt.
3. The more liberal original HIDAPI license. LICENSE-orig.txt
The license chosen is at the discretion of the user of HIDAPI. For example:
1. An author of GPL software would likely use HIDAPI under the terms of the
GPL.
2. An author of commercial closed-source software would likely use HIDAPI
under the terms of the BSD-style license or the original HIDAPI license.

View file

@ -1,85 +0,0 @@
ACLOCAL_AMFLAGS = -I m4
if OS_FREEBSD
pkgconfigdir=$(prefix)/libdata/pkgconfig
else
pkgconfigdir=$(libdir)/pkgconfig
endif
if OS_LINUX
pkgconfig_DATA=pc/hidapi-hidraw.pc pc/hidapi-libusb.pc
else
pkgconfig_DATA=pc/hidapi.pc
endif
SUBDIRS=
if OS_LINUX
SUBDIRS += linux libusb
endif
if OS_DARWIN
SUBDIRS += mac
endif
if OS_IOS
SUBDIRS += ios
endif
if OS_FREEBSD
SUBDIRS += libusb
endif
if OS_KFREEBSD
SUBDIRS += libusb
endif
if OS_WINDOWS
SUBDIRS += windows
endif
SUBDIRS += hidtest
if BUILD_TESTGUI
SUBDIRS += testgui
endif
EXTRA_DIST = udev doxygen
dist_doc_DATA = \
README.txt \
AUTHORS.txt \
LICENSE-bsd.txt \
LICENSE-gpl3.txt \
LICENSE-orig.txt \
LICENSE.txt
SCMCLEAN_TARGETS= \
aclocal.m4 \
config.guess \
config.sub \
configure \
config.h.in \
depcomp \
install-sh \
ltmain.sh \
missing \
mac/Makefile.in \
testgui/Makefile.in \
libusb/Makefile.in \
Makefile.in \
linux/Makefile.in \
windows/Makefile.in \
m4/libtool.m4 \
m4/lt~obsolete.m4 \
m4/ltoptions.m4 \
m4/ltsugar.m4 \
m4/ltversion.m4
SCMCLEAN_DIR_TARGETS = \
autom4te.cache
scm-clean: distclean
rm -f $(SCMCLEAN_TARGETS)
rm -Rf $(SCMCLEAN_DIR_TARGETS)

View file

@ -1,339 +0,0 @@
HIDAPI library for Windows, Linux, FreeBSD and Mac OS X
=========================================================
About
======
HIDAPI is a multi-platform library which allows an application to interface
with USB and Bluetooth HID-Class devices on Windows, Linux, FreeBSD, and Mac
OS X. HIDAPI can be either built as a shared library (.so or .dll) or
can be embedded directly into a target application by adding a single source
file (per platform) and a single header.
HIDAPI has four back-ends:
* Windows (using hid.dll)
* Linux/hidraw (using the Kernel's hidraw driver)
* Linux/libusb (using libusb-1.0)
* FreeBSD (using libusb-1.0)
* Mac (using IOHidManager)
On Linux, either the hidraw or the libusb back-end can be used. There are
tradeoffs, and the functionality supported is slightly different.
Linux/hidraw (linux/hid.c):
This back-end uses the hidraw interface in the Linux kernel. While this
back-end will support both USB and Bluetooth, it has some limitations on
kernels prior to 2.6.39, including the inability to send or receive feature
reports. In addition, it will only communicate with devices which have
hidraw nodes associated with them. Keyboards, mice, and some other devices
which are blacklisted from having hidraw nodes will not work. Fortunately,
for nearly all the uses of hidraw, this is not a problem.
Linux/FreeBSD/libusb (libusb/hid.c):
This back-end uses libusb-1.0 to communicate directly to a USB device. This
back-end will of course not work with Bluetooth devices.
HIDAPI also comes with a Test GUI. The Test GUI is cross-platform and uses
Fox Toolkit (http://www.fox-toolkit.org). It will build on every platform
which HIDAPI supports. Since it relies on a 3rd party library, building it
is optional but recommended because it is so useful when debugging hardware.
What Does the API Look Like?
=============================
The API provides the the most commonly used HID functions including sending
and receiving of input, output, and feature reports. The sample program,
which communicates with a heavily hacked up version of the Microchip USB
Generic HID sample looks like this (with error checking removed for
simplicity):
#ifdef WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include "hidapi.h"
#define MAX_STR 255
int main(int argc, char* argv[])
{
int res;
unsigned char buf[65];
wchar_t wstr[MAX_STR];
hid_device *handle;
int i;
// Initialize the hidapi library
res = hid_init();
// Open the device using the VID, PID,
// and optionally the Serial number.
handle = hid_open(0x4d8, 0x3f, NULL);
// Read the Manufacturer String
res = hid_get_manufacturer_string(handle, wstr, MAX_STR);
wprintf(L"Manufacturer String: %s\n", wstr);
// Read the Product String
res = hid_get_product_string(handle, wstr, MAX_STR);
wprintf(L"Product String: %s\n", wstr);
// Read the Serial Number String
res = hid_get_serial_number_string(handle, wstr, MAX_STR);
wprintf(L"Serial Number String: (%d) %s\n", wstr[0], wstr);
// Read Indexed String 1
res = hid_get_indexed_string(handle, 1, wstr, MAX_STR);
wprintf(L"Indexed String 1: %s\n", wstr);
// Toggle LED (cmd 0x80). The first byte is the report number (0x0).
buf[0] = 0x0;
buf[1] = 0x80;
res = hid_write(handle, buf, 65);
// Request state (cmd 0x81). The first byte is the report number (0x0).
buf[0] = 0x0;
buf[1] = 0x81;
res = hid_write(handle, buf, 65);
// Read requested state
res = hid_read(handle, buf, 65);
// Print out the returned buffer.
for (i = 0; i < 4; i++)
printf("buf[%d]: %d\n", i, buf[i]);
// Finalize the hidapi library
res = hid_exit();
return 0;
}
If you have your own simple test programs which communicate with standard
hardware development boards (such as those from Microchip, TI, Atmel,
FreeScale and others), please consider sending me something like the above
for inclusion into the HIDAPI source. This will help others who have the
same hardware as you do.
License
========
HIDAPI may be used by one of three licenses as outlined in LICENSE.txt.
Download
=========
HIDAPI can be downloaded from github
git clone git://github.com/signal11/hidapi.git
Build Instructions
===================
This section is long. Don't be put off by this. It's not long because it's
complicated to build HIDAPI; it's quite the opposite. This section is long
because of the flexibility of HIDAPI and the large number of ways in which
it can be built and used. You will likely pick a single build method.
HIDAPI can be built in several different ways. If you elect to build a
shared library, you will need to build it from the HIDAPI source
distribution. If you choose instead to embed HIDAPI directly into your
application, you can skip the building and look at the provided platform
Makefiles for guidance. These platform Makefiles are located in linux/
libusb/ mac/ and windows/ and are called Makefile-manual. In addition,
Visual Studio projects are provided. Even if you're going to embed HIDAPI
into your project, it is still beneficial to build the example programs.
Prerequisites:
---------------
Linux:
-------
On Linux, you will need to install development packages for libudev,
libusb and optionally Fox-toolkit (for the test GUI). On
Debian/Ubuntu systems these can be installed by running:
sudo apt-get install libudev-dev libusb-1.0-0-dev libfox-1.6-dev
If you downloaded the source directly from the git repository (using
git clone), you'll need Autotools:
sudo apt-get install autotools-dev autoconf automake libtool
FreeBSD:
---------
On FreeBSD you will need to install GNU make, libiconv, and
optionally Fox-Toolkit (for the test GUI). This is done by running
the following:
pkg_add -r gmake libiconv fox16
If you downloaded the source directly from the git repository (using
git clone), you'll need Autotools:
pkg_add -r autotools
Mac:
-----
On Mac, you will need to install Fox-Toolkit if you wish to build
the Test GUI. There are two ways to do this, and each has a slight
complication. Which method you use depends on your use case.
If you wish to build the Test GUI just for your own testing on your
own computer, then the easiest method is to install Fox-Toolkit
using ports:
sudo port install fox
If you wish to build the TestGUI app bundle to redistribute to
others, you will need to install Fox-toolkit from source. This is
because the version of fox that gets installed using ports uses the
ports X11 libraries which are not compatible with the Apple X11
libraries. If you install Fox with ports and then try to distribute
your built app bundle, it will simply fail to run on other systems.
To install Fox-Toolkit manually, download the source package from
http://www.fox-toolkit.org, extract it, and run the following from
within the extracted source:
./configure && make && make install
Windows:
---------
On Windows, if you want to build the test GUI, you will need to get
the hidapi-externals.zip package from the download site. This
contains pre-built binaries for Fox-toolkit. Extract
hidapi-externals.zip just outside of hidapi, so that
hidapi-externals and hidapi are on the same level, as shown:
Parent_Folder
|
+hidapi
+hidapi-externals
Again, this step is not required if you do not wish to build the
test GUI.
Building HIDAPI into a shared library on Unix Platforms:
---------------------------------------------------------
On Unix-like systems such as Linux, FreeBSD, Mac, and even Windows, using
Mingw or Cygwin, the easiest way to build a standard system-installed shared
library is to use the GNU Autotools build system. If you checked out the
source from the git repository, run the following:
./bootstrap
./configure
make
make install <----- as root, or using sudo
If you downloaded a source package (ie: if you did not run git clone), you
can skip the ./bootstrap step.
./configure can take several arguments which control the build. The two most
likely to be used are:
--enable-testgui
Enable build of the Test GUI. This requires Fox toolkit to
be installed. Instructions for installing Fox-Toolkit on
each platform are in the Prerequisites section above.
--prefix=/usr
Specify where you want the output headers and libraries to
be installed. The example above will put the headers in
/usr/include and the binaries in /usr/lib. The default is to
install into /usr/local which is fine on most systems.
Building the manual way on Unix platforms:
-------------------------------------------
Manual Makefiles are provided mostly to give the user and idea what it takes
to build a program which embeds HIDAPI directly inside of it. These should
really be used as examples only. If you want to build a system-wide shared
library, use the Autotools method described above.
To build HIDAPI using the manual makefiles, change to the directory
of your platform and run make. For example, on Linux run:
cd linux/
make -f Makefile-manual
To build the Test GUI using the manual makefiles:
cd testgui/
make -f Makefile-manual
Building on Windows:
---------------------
To build the HIDAPI DLL on Windows using Visual Studio, build the .sln file
in the windows/ directory.
To build the Test GUI on windows using Visual Studio, build the .sln file in
the testgui/ directory.
To build HIDAPI using MinGW or Cygwin using Autotools, use the instructions
in the section titled "Building HIDAPI into a shared library on Unix
Platforms" above. Note that building the Test GUI with MinGW or Cygwin will
require the Windows procedure in the Prerequisites section above (ie:
hidapi-externals.zip).
To build HIDAPI using MinGW using the Manual Makefiles, see the section
"Building the manual way on Unix platforms" above.
HIDAPI can also be built using the Windows DDK (now also called the Windows
Driver Kit or WDK). This method was originally required for the HIDAPI build
but not anymore. However, some users still prefer this method. It is not as
well supported anymore but should still work. Patches are welcome if it does
not. To build using the DDK:
1. Install the Windows Driver Kit (WDK) from Microsoft.
2. From the Start menu, in the Windows Driver Kits folder, select Build
Environments, then your operating system, then the x86 Free Build
Environment (or one that is appropriate for your system).
3. From the console, change directory to the windows/ddk_build/ directory,
which is part of the HIDAPI distribution.
4. Type build.
5. You can find the output files (DLL and LIB) in a subdirectory created
by the build system which is appropriate for your environment. On
Windows XP, this directory is objfre_wxp_x86/i386.
Cross Compiling
================
This section talks about cross compiling HIDAPI for Linux using autotools.
This is useful for using HIDAPI on embedded Linux targets. These
instructions assume the most raw kind of embedded Linux build, where all
prerequisites will need to be built first. This process will of course vary
based on your embedded Linux build system if you are using one, such as
OpenEmbedded or Buildroot.
For the purpose of this section, it will be assumed that the following
environment variables are exported.
$ export STAGING=$HOME/out
$ export HOST=arm-linux
STAGING and HOST can be modified to suit your setup.
Prerequisites
--------------
Note that the build of libudev is the very basic configuration.
Build Libusb. From the libusb source directory, run:
./configure --host=$HOST --prefix=$STAGING
make
make install
Build libudev. From the libudev source directory, run:
./configure --disable-gudev --disable-introspection --disable-hwdb \
--host=$HOST --prefix=$STAGING
make
make install
Building HIDAPI
----------------
Build HIDAPI:
PKG_CONFIG_DIR= \
PKG_CONFIG_LIBDIR=$STAGING/lib/pkgconfig:$STAGING/share/pkgconfig \
PKG_CONFIG_SYSROOT_DIR=$STAGING \
./configure --host=$HOST --prefix=$STAGING
Signal 11 Software - 2010-04-11
2010-07-28
2011-09-10
2012-05-01
2012-07-03

File diff suppressed because it is too large Load diff

View file

@ -1,16 +0,0 @@
LOCAL_PATH:= $(call my-dir)
HIDAPI_ROOT_REL:= ../..
HIDAPI_ROOT_ABS:= $(LOCAL_PATH)/../..
include $(CLEAR_VARS)
LOCAL_CPPFLAGS += -std=c++11
LOCAL_SRC_FILES := \
$(HIDAPI_ROOT_REL)/android/hid.cpp
LOCAL_MODULE := libhidapi
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)

View file

@ -1,2 +0,0 @@
APP_STL := gnustl_static
APP_ABI := armeabi-v7a

View file

@ -1,14 +0,0 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-21

View file

@ -1,2 +0,0 @@
#!/bin/sh -x
autoreconf --install --verbose --force

View file

@ -1,236 +0,0 @@
AC_PREREQ(2.63)
# Version number. This is currently the only place.
m4_define([HIDAPI_MAJOR], 0)
m4_define([HIDAPI_MINOR], 8)
m4_define([HIDAPI_RELEASE], 0)
m4_define([HIDAPI_RC], -rc1)
m4_define([VERSION_STRING], HIDAPI_MAJOR[.]HIDAPI_MINOR[.]HIDAPI_RELEASE[]HIDAPI_RC)
AC_INIT([hidapi],[VERSION_STRING],[alan@signal11.us])
# Library soname version
# Follow the following rules (particularly the ones in the second link):
# http://www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html
# http://sourceware.org/autobook/autobook/autobook_91.html
lt_current="0"
lt_revision="0"
lt_age="0"
LTLDFLAGS="-version-info ${lt_current}:${lt_revision}:${lt_age}"
AC_CONFIG_MACRO_DIR([m4])
AM_INIT_AUTOMAKE([foreign -Wall -Werror])
AC_CONFIG_MACRO_DIR([m4])
m4_ifdef([AM_PROG_AR], [AM_PROG_AR])
LT_INIT
AC_PROG_CC
AC_PROG_CXX
AC_PROG_OBJC
PKG_PROG_PKG_CONFIG
m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])
hidapi_lib_error() {
echo ""
echo " Library $1 was not found on this system."
echo " Please install it and re-run ./configure"
echo ""
exit 1
}
hidapi_prog_error() {
echo ""
echo " Program $1 was not found on this system."
echo " This program is part of $2."
echo " Please install it and re-run ./configure"
echo ""
exit 1
}
AC_MSG_CHECKING([operating system])
AC_MSG_RESULT($host)
case $host in
*-linux*)
AC_MSG_RESULT([ (Linux back-end)])
AC_DEFINE(OS_LINUX, 1, [Linux implementations])
AC_SUBST(OS_LINUX)
backend="linux"
os="linux"
threads="pthreads"
# HIDAPI/hidraw libs
PKG_CHECK_MODULES([libudev], [libudev], true, [hidapi_lib_error libudev])
LIBS_HIDRAW_PR+=" $libudev_LIBS"
CFLAGS_HIDRAW+=" $libudev_CFLAGS"
# HIDAPI/libusb libs
AC_CHECK_LIB([rt], [clock_gettime], [LIBS_LIBUSB_PRIVATE+=" -lrt"], [hidapi_lib_error librt])
PKG_CHECK_MODULES([libusb], [libusb-1.0 >= 1.0.9], true, [hidapi_lib_error libusb-1.0])
LIBS_LIBUSB_PRIVATE+=" $libusb_LIBS"
CFLAGS_LIBUSB+=" $libusb_CFLAGS"
;;
*-darwin*)
AC_MSG_RESULT([ (Mac OS X back-end)])
AC_DEFINE(OS_DARWIN, 1, [Mac implementation])
AC_SUBST(OS_DARWIN)
backend="mac"
os="darwin"
threads="pthreads"
LIBS="${LIBS} -framework IOKit -framework CoreFoundation"
;;
*-freebsd*)
AC_MSG_RESULT([ (FreeBSD back-end)])
AC_DEFINE(OS_FREEBSD, 1, [FreeBSD implementation])
AC_SUBST(OS_FREEBSD)
backend="libusb"
os="freebsd"
threads="pthreads"
CFLAGS="$CFLAGS -I/usr/local/include"
LDFLAGS="$LDFLAGS -L/usr/local/lib"
LIBS="${LIBS}"
AC_CHECK_LIB([usb], [libusb_init], [LIBS_LIBUSB_PRIVATE="${LIBS_LIBUSB_PRIVATE} -lusb"], [hidapi_lib_error libusb])
AC_CHECK_LIB([iconv], [iconv_open], [LIBS_LIBUSB_PRIVATE="${LIBS_LIBUSB_PRIVATE} -liconv"], [hidapi_lib_error libiconv])
echo libs_priv: $LIBS_LIBUSB_PRIVATE
;;
*-kfreebsd*)
AC_MSG_RESULT([ (kFreeBSD back-end)])
AC_DEFINE(OS_KFREEBSD, 1, [kFreeBSD implementation])
AC_SUBST(OS_KFREEBSD)
backend="libusb"
os="kfreebsd"
threads="pthreads"
AC_CHECK_LIB([usb], [libusb_init], [LIBS_LIBUSB_PRIVATE="${LIBS_LIBUSB_PRIVATE} -lusb"], [hidapi_lib_error libusb])
echo libs_priv: $LIBS_LIBUSB_PRIVATE
;;
*-mingw*)
AC_MSG_RESULT([ (Windows back-end, using MinGW)])
backend="windows"
os="windows"
threads="windows"
win_implementation="mingw"
;;
*-cygwin*)
AC_MSG_RESULT([ (Windows back-end, using Cygwin)])
backend="windows"
os="windows"
threads="windows"
win_implementation="cygwin"
;;
*)
AC_MSG_ERROR([HIDAPI is not supported on your operating system yet])
esac
LIBS_HIDRAW="${LIBS} ${LIBS_HIDRAW_PR}"
LIBS_LIBUSB="${LIBS} ${LIBS_LIBUSB_PRIVATE}"
AC_SUBST([LIBS_HIDRAW])
AC_SUBST([LIBS_LIBUSB])
AC_SUBST([CFLAGS_LIBUSB])
AC_SUBST([CFLAGS_HIDRAW])
if test "x$os" = xwindows; then
AC_DEFINE(OS_WINDOWS, 1, [Windows implementations])
AC_SUBST(OS_WINDOWS)
LDFLAGS="${LDFLAGS} -no-undefined"
LIBS="${LIBS} -lsetupapi"
fi
if test "x$threads" = xpthreads; then
AX_PTHREAD([found_pthreads=yes], [found_pthreads=no])
if test "x$found_pthreads" = xyes; then
if test "x$os" = xlinux; then
# Only use pthreads for libusb implementation on Linux.
LIBS_LIBUSB="$PTHREAD_LIBS $LIBS_LIBUSB"
CFLAGS_LIBUSB="$CFLAGS_LIBUSB $PTHREAD_CFLAGS"
# There's no separate CC on Linux for threading,
# so it's ok that both implementations use $PTHREAD_CC
CC="$PTHREAD_CC"
else
LIBS="$PTHREAD_LIBS $LIBS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
CC="$PTHREAD_CC"
fi
fi
fi
# Test GUI
AC_ARG_ENABLE([testgui],
[AS_HELP_STRING([--enable-testgui],
[enable building of test GUI (default n)])],
[testgui_enabled=$enableval],
[testgui_enabled='no'])
AM_CONDITIONAL([BUILD_TESTGUI], [test "x$testgui_enabled" != "xno"])
# Configure the MacOS TestGUI app bundle
rm -Rf testgui/TestGUI.app
mkdir -p testgui/TestGUI.app
cp -R ${srcdir}/testgui/TestGUI.app.in/* testgui/TestGUI.app
chmod -R u+w testgui/TestGUI.app
mkdir testgui/TestGUI.app/Contents/MacOS/
if test "x$testgui_enabled" != "xno"; then
if test "x$os" = xdarwin; then
# On Mac OS, don't use pkg-config.
AC_CHECK_PROG([foxconfig], [fox-config], [fox-config], false)
if test "x$foxconfig" = "xfalse"; then
hidapi_prog_error fox-config "FOX Toolkit"
fi
LIBS_TESTGUI+=`$foxconfig --libs`
LIBS_TESTGUI+=" -framework Cocoa -L/usr/X11R6/lib"
CFLAGS_TESTGUI+=`$foxconfig --cflags`
OBJCFLAGS+=" -x objective-c++"
elif test "x$os" = xwindows; then
# On Windows, just set the paths for Fox toolkit
if test "x$win_implementation" = xmingw; then
CFLAGS_TESTGUI="-I\$(srcdir)/../../hidapi-externals/fox/include -g -c"
LIBS_TESTGUI=" -mwindows \$(srcdir)/../../hidapi-externals/fox/lib/libFOX-1.6.a -lgdi32 -Wl,--enable-auto-import -static-libgcc -static-libstdc++ -lkernel32"
else
# Cygwin
CFLAGS_TESTGUI="-DWIN32 -I\$(srcdir)/../../hidapi-externals/fox/include -g -c"
LIBS_TESTGUI="\$(srcdir)/../../hidapi-externals/fox/lib/libFOX-cygwin-1.6.a -lgdi32 -Wl,--enable-auto-import -static-libgcc -static-libstdc++ -lkernel32"
fi
else
# On Linux and FreeBSD platforms, use pkg-config to find fox.
PKG_CHECK_MODULES([fox], [fox17], [], [PKG_CHECK_MODULES([fox], [fox])])
LIBS_TESTGUI="${LIBS_TESTGUI} $fox_LIBS"
if test "x$os" = xfreebsd; then
LIBS_TESTGUI="${LIBS_TESTGUI} -L/usr/local/lib"
fi
CFLAGS_TESTGUI="${CFLAGS_TESTGUI} $fox_CFLAGS"
fi
fi
AC_SUBST([LIBS_TESTGUI])
AC_SUBST([CFLAGS_TESTGUI])
AC_SUBST([backend])
# OS info for Automake
AM_CONDITIONAL(OS_LINUX, test "x$os" = xlinux)
AM_CONDITIONAL(OS_DARWIN, test "x$os" = xdarwin)
AM_CONDITIONAL(OS_FREEBSD, test "x$os" = xfreebsd)
AM_CONDITIONAL(OS_KFREEBSD, test "x$os" = xkfreebsd)
AM_CONDITIONAL(OS_WINDOWS, test "x$os" = xwindows)
AC_CONFIG_HEADERS([config.h])
if test "x$os" = "xlinux"; then
AC_CONFIG_FILES([pc/hidapi-hidraw.pc])
AC_CONFIG_FILES([pc/hidapi-libusb.pc])
else
AC_CONFIG_FILES([pc/hidapi.pc])
fi
AC_SUBST(LTLDFLAGS)
AC_CONFIG_FILES([Makefile \
hidtest/Makefile \
libusb/Makefile \
linux/Makefile \
mac/Makefile \
testgui/Makefile \
windows/Makefile])
AC_OUTPUT

File diff suppressed because it is too large Load diff

View file

@ -1,398 +0,0 @@
/*******************************************************
HIDAPI - Multi-Platform library for
communication with HID devices.
Alan Ott
Signal 11 Software
8/22/2009
Copyright 2009, All Rights Reserved.
At the discretion of the user of this library,
this software may be licensed under the terms of the
GNU General Public License v3, a BSD-Style license, or the
original HIDAPI license as outlined in the LICENSE.txt,
LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
files located at the root of the source distribution.
These files may also be found in the public source
code repository located at:
http://github.com/signal11/hidapi .
********************************************************/
/** @file
* @defgroup API hidapi API
*/
#ifndef HIDAPI_H__
#define HIDAPI_H__
#include <wchar.h>
#if defined(_WIN32) && !defined(NAMESPACE) && (0) /* SDL: don't export hidapi syms */
#define HID_API_EXPORT __declspec(dllexport)
#define HID_API_CALL
#else
#define HID_API_EXPORT /**< API export macro */
#define HID_API_CALL /**< API call macro */
#endif
#define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/
#if defined(__cplusplus) && !defined(NAMESPACE)
extern "C" {
#endif
#ifdef NAMESPACE
namespace NAMESPACE {
#endif
struct hid_device_;
typedef struct hid_device_ hid_device; /**< opaque hidapi structure */
/** hidapi info structure */
struct hid_device_info {
/** Platform-specific device path */
char *path;
/** Device Vendor ID */
unsigned short vendor_id;
/** Device Product ID */
unsigned short product_id;
/** Serial Number */
wchar_t *serial_number;
/** Device Release Number in binary-coded decimal,
also known as Device Version Number */
unsigned short release_number;
/** Manufacturer String */
wchar_t *manufacturer_string;
/** Product string */
wchar_t *product_string;
/** Usage Page for this Device/Interface
(Windows/Mac only). */
unsigned short usage_page;
/** Usage for this Device/Interface
(Windows/Mac only).*/
unsigned short usage;
/** The USB interface which this logical device
represents. Valid on both Linux implementations
in all cases, and valid on the Windows implementation
only if the device contains more than one interface. */
int interface_number;
/** Pointer to the next device */
struct hid_device_info *next;
};
/** @brief Initialize the HIDAPI library.
This function initializes the HIDAPI library. Calling it is not
strictly necessary, as it will be called automatically by
hid_enumerate() and any of the hid_open_*() functions if it is
needed. This function should be called at the beginning of
execution however, if there is a chance of HIDAPI handles
being opened by different threads simultaneously.
@ingroup API
@returns
This function returns 0 on success and -1 on error.
*/
int HID_API_EXPORT HID_API_CALL hid_init(void);
/** @brief Finalize the HIDAPI library.
This function frees all of the static data associated with
HIDAPI. It should be called at the end of execution to avoid
memory leaks.
@ingroup API
@returns
This function returns 0 on success and -1 on error.
*/
int HID_API_EXPORT HID_API_CALL hid_exit(void);
/** @brief Enumerate the HID Devices.
This function returns a linked list of all the HID devices
attached to the system which match vendor_id and product_id.
If @p vendor_id is set to 0 then any vendor matches.
If @p product_id is set to 0 then any product matches.
If @p vendor_id and @p product_id are both set to 0, then
all HID devices will be returned.
@ingroup API
@param vendor_id The Vendor ID (VID) of the types of device
to open.
@param product_id The Product ID (PID) of the types of
device to open.
@returns
This function returns a pointer to a linked list of type
struct #hid_device, containing information about the HID devices
attached to the system, or NULL in the case of failure. Free
this linked list by calling hid_free_enumeration().
*/
struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id);
/** @brief Free an enumeration Linked List
This function frees a linked list created by hid_enumerate().
@ingroup API
@param devs Pointer to a list of struct_device returned from
hid_enumerate().
*/
void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs);
/** @brief Open a HID device using a Vendor ID (VID), Product ID
(PID) and optionally a serial number.
If @p serial_number is NULL, the first device with the
specified VID and PID is opened.
@ingroup API
@param vendor_id The Vendor ID (VID) of the device to open.
@param product_id The Product ID (PID) of the device to open.
@param serial_number The Serial Number of the device to open
(Optionally NULL).
@returns
This function returns a pointer to a #hid_device object on
success or NULL on failure.
*/
HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number);
/** @brief Open a HID device by its path name.
The path name be determined by calling hid_enumerate(), or a
platform-specific path name can be used (eg: /dev/hidraw0 on
Linux).
@ingroup API
@param path The path name of the device to open
@returns
This function returns a pointer to a #hid_device object on
success or NULL on failure.
*/
HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path, int bExclusive /* = false */);
/** @brief Write an Output report to a HID device.
The first byte of @p data[] must contain the Report ID. For
devices which only support a single report, this must be set
to 0x0. The remaining bytes contain the report data. Since
the Report ID is mandatory, calls to hid_write() will always
contain one more byte than the report contains. For example,
if a hid report is 16 bytes long, 17 bytes must be passed to
hid_write(), the Report ID (or 0x0, for devices with a
single report), followed by the report data (16 bytes). In
this example, the length passed in would be 17.
hid_write() will send the data on the first OUT endpoint, if
one exists. If it does not, it will send the data through
the Control Endpoint (Endpoint 0).
@ingroup API
@param device A device handle returned from hid_open().
@param data The data to send, including the report number as
the first byte.
@param length The length in bytes of the data to send.
@returns
This function returns the actual number of bytes written and
-1 on error.
*/
int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length);
/** @brief Read an Input report from a HID device with timeout.
Input reports are returned
to the host through the INTERRUPT IN endpoint. The first byte will
contain the Report number if the device uses numbered reports.
@ingroup API
@param device A device handle returned from hid_open().
@param data A buffer to put the read data into.
@param length The number of bytes to read. For devices with
multiple reports, make sure to read an extra byte for
the report number.
@param milliseconds timeout in milliseconds or -1 for blocking wait.
@returns
This function returns the actual number of bytes read and
-1 on error. If no packet was available to be read within
the timeout period, this function returns 0.
*/
int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *device, unsigned char *data, size_t length, int milliseconds);
/** @brief Read an Input report from a HID device.
Input reports are returned
to the host through the INTERRUPT IN endpoint. The first byte will
contain the Report number if the device uses numbered reports.
@ingroup API
@param device A device handle returned from hid_open().
@param data A buffer to put the read data into.
@param length The number of bytes to read. For devices with
multiple reports, make sure to read an extra byte for
the report number.
@returns
This function returns the actual number of bytes read and
-1 on error. If no packet was available to be read and
the handle is in non-blocking mode, this function returns 0.
*/
int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length);
/** @brief Set the device handle to be non-blocking.
In non-blocking mode calls to hid_read() will return
immediately with a value of 0 if there is no data to be
read. In blocking mode, hid_read() will wait (block) until
there is data to read before returning.
Nonblocking can be turned on and off at any time.
@ingroup API
@param device A device handle returned from hid_open().
@param nonblock enable or not the nonblocking reads
- 1 to enable nonblocking
- 0 to disable nonblocking.
@returns
This function returns 0 on success and -1 on error.
*/
int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock);
/** @brief Send a Feature report to the device.
Feature reports are sent over the Control endpoint as a
Set_Report transfer. The first byte of @p data[] must
contain the Report ID. For devices which only support a
single report, this must be set to 0x0. The remaining bytes
contain the report data. Since the Report ID is mandatory,
calls to hid_send_feature_report() will always contain one
more byte than the report contains. For example, if a hid
report is 16 bytes long, 17 bytes must be passed to
hid_send_feature_report(): the Report ID (or 0x0, for
devices which do not use numbered reports), followed by the
report data (16 bytes). In this example, the length passed
in would be 17.
@ingroup API
@param device A device handle returned from hid_open().
@param data The data to send, including the report number as
the first byte.
@param length The length in bytes of the data to send, including
the report number.
@returns
This function returns the actual number of bytes written and
-1 on error.
*/
int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length);
/** @brief Get a feature report from a HID device.
Set the first byte of @p data[] to the Report ID of the
report to be read. Make sure to allow space for this
extra byte in @p data[]. Upon return, the first byte will
still contain the Report ID, and the report data will
start in data[1].
@ingroup API
@param device A device handle returned from hid_open().
@param data A buffer to put the read data into, including
the Report ID. Set the first byte of @p data[] to the
Report ID of the report to be read, or set it to zero
if your device does not use numbered reports.
@param length The number of bytes to read, including an
extra byte for the report ID. The buffer can be longer
than the actual report.
@returns
This function returns the number of bytes read plus
one for the report ID (which is still in the first
byte), or -1 on error.
*/
int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length);
/** @brief Close a HID device.
@ingroup API
@param device A device handle returned from hid_open().
*/
void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device);
/** @brief Get The Manufacturer String from a HID device.
@ingroup API
@param device A device handle returned from hid_open().
@param string A wide string buffer to put the data into.
@param maxlen The length of the buffer in multiples of wchar_t.
@returns
This function returns 0 on success and -1 on error.
*/
int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
/** @brief Get The Product String from a HID device.
@ingroup API
@param device A device handle returned from hid_open().
@param string A wide string buffer to put the data into.
@param maxlen The length of the buffer in multiples of wchar_t.
@returns
This function returns 0 on success and -1 on error.
*/
int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen);
/** @brief Get The Serial Number String from a HID device.
@ingroup API
@param device A device handle returned from hid_open().
@param string A wide string buffer to put the data into.
@param maxlen The length of the buffer in multiples of wchar_t.
@returns
This function returns 0 on success and -1 on error.
*/
int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen);
/** @brief Get a string from a HID device, based on its string index.
@ingroup API
@param device A device handle returned from hid_open().
@param string_index The index of the string to get.
@param string A wide string buffer to put the data into.
@param maxlen The length of the buffer in multiples of wchar_t.
@returns
This function returns 0 on success and -1 on error.
*/
int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen);
/** @brief Get a string describing the last error which occurred.
@ingroup API
@param device A device handle returned from hid_open().
@returns
This function returns a string containing the last error
which occurred or NULL if none has occurred.
*/
HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device);
#if defined(__cplusplus) && !defined(NAMESPACE)
}
#endif
#ifdef NAMESPACE
}
#endif
#endif

View file

@ -1,20 +0,0 @@
AM_CPPFLAGS = -I$(top_srcdir)/hidapi/
## Linux
if OS_LINUX
noinst_PROGRAMS = hidtest-libusb hidtest-hidraw
hidtest_hidraw_SOURCES = hidtest.cpp
hidtest_hidraw_LDADD = $(top_builddir)/linux/libhidapi-hidraw.la
hidtest_libusb_SOURCES = hidtest.cpp
hidtest_libusb_LDADD = $(top_builddir)/libusb/libhidapi-libusb.la
else
# Other OS's
noinst_PROGRAMS = hidtest
hidtest_SOURCES = hidtest.cpp
hidtest_LDADD = $(top_builddir)/$(backend)/libhidapi.la
endif

View file

@ -1,194 +0,0 @@
/*******************************************************
Windows HID simplification
Alan Ott
Signal 11 Software
8/22/2009
Copyright 2009
This contents of this file may be used by anyone
for any reason without any conditions and may be
used as a starting point for your own applications
which use HIDAPI.
********************************************************/
#include <stdio.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#include "hidapi.h"
// Headers needed for sleeping.
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
int main(int argc, char* argv[])
{
int res;
unsigned char buf[256];
#define MAX_STR 255
wchar_t wstr[MAX_STR];
hid_device *handle;
int i;
#ifdef WIN32
UNREFERENCED_PARAMETER(argc);
UNREFERENCED_PARAMETER(argv);
#endif
struct hid_device_info *devs, *cur_dev;
if (hid_init())
return -1;
devs = hid_enumerate(0x0, 0x0);
cur_dev = devs;
while (cur_dev) {
printf("Device Found\n type: %04hx %04hx\n path: %s\n serial_number: %ls", cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number);
printf("\n");
printf(" Manufacturer: %ls\n", cur_dev->manufacturer_string);
printf(" Product: %ls\n", cur_dev->product_string);
printf(" Release: %hx\n", cur_dev->release_number);
printf(" Interface: %d\n", cur_dev->interface_number);
printf("\n");
cur_dev = cur_dev->next;
}
hid_free_enumeration(devs);
// Set up the command buffer.
memset(buf,0x00,sizeof(buf));
buf[0] = 0x01;
buf[1] = 0x81;
// Open the device using the VID, PID,
// and optionally the Serial number.
////handle = hid_open(0x4d8, 0x3f, L"12345");
handle = hid_open(0x4d8, 0x3f, NULL);
if (!handle) {
printf("unable to open device\n");
return 1;
}
// Read the Manufacturer String
wstr[0] = 0x0000;
res = hid_get_manufacturer_string(handle, wstr, MAX_STR);
if (res < 0)
printf("Unable to read manufacturer string\n");
printf("Manufacturer String: %ls\n", wstr);
// Read the Product String
wstr[0] = 0x0000;
res = hid_get_product_string(handle, wstr, MAX_STR);
if (res < 0)
printf("Unable to read product string\n");
printf("Product String: %ls\n", wstr);
// Read the Serial Number String
wstr[0] = 0x0000;
res = hid_get_serial_number_string(handle, wstr, MAX_STR);
if (res < 0)
printf("Unable to read serial number string\n");
printf("Serial Number String: (%d) %ls", wstr[0], wstr);
printf("\n");
// Read Indexed String 1
wstr[0] = 0x0000;
res = hid_get_indexed_string(handle, 1, wstr, MAX_STR);
if (res < 0)
printf("Unable to read indexed string 1\n");
printf("Indexed String 1: %ls\n", wstr);
// Set the hid_read() function to be non-blocking.
hid_set_nonblocking(handle, 1);
// Try to read from the device. There shoud be no
// data here, but execution should not block.
res = hid_read(handle, buf, 17);
// Send a Feature Report to the device
buf[0] = 0x2;
buf[1] = 0xa0;
buf[2] = 0x0a;
buf[3] = 0x00;
buf[4] = 0x00;
res = hid_send_feature_report(handle, buf, 17);
if (res < 0) {
printf("Unable to send a feature report.\n");
}
memset(buf,0,sizeof(buf));
// Read a Feature Report from the device
buf[0] = 0x2;
res = hid_get_feature_report(handle, buf, sizeof(buf));
if (res < 0) {
printf("Unable to get a feature report.\n");
printf("%ls", hid_error(handle));
}
else {
// Print out the returned buffer.
printf("Feature Report\n ");
for (i = 0; i < res; i++)
printf("%02hhx ", buf[i]);
printf("\n");
}
memset(buf,0,sizeof(buf));
// Toggle LED (cmd 0x80). The first byte is the report number (0x1).
buf[0] = 0x1;
buf[1] = 0x80;
res = hid_write(handle, buf, 17);
if (res < 0) {
printf("Unable to write()\n");
printf("Error: %ls\n", hid_error(handle));
}
// Request state (cmd 0x81). The first byte is the report number (0x1).
buf[0] = 0x1;
buf[1] = 0x81;
hid_write(handle, buf, 17);
if (res < 0)
printf("Unable to write() (2)\n");
// Read requested state. hid_read() has been set to be
// non-blocking by the call to hid_set_nonblocking() above.
// This loop demonstrates the non-blocking nature of hid_read().
res = 0;
while (res == 0) {
res = hid_read(handle, buf, sizeof(buf));
if (res == 0)
printf("waiting...\n");
if (res < 0)
printf("Unable to read()\n");
#ifdef WIN32
Sleep(500);
#else
usleep(500*1000);
#endif
}
printf("Data read:\n ");
// Print out the returned buffer.
for (i = 0; i < res; i++)
printf("%02hhx ", buf[i]);
printf("\n");
hid_close(handle);
/* Free static HIDAPI objects. */
hid_exit();
#ifdef WIN32
system("pause");
#endif
return 0;
}

View file

@ -1,32 +0,0 @@
###########################################
# Simple Makefile for HIDAPI test program
#
# Alan Ott
# Signal 11 Software
# 2010-07-03
###########################################
all: hidtest
CC=gcc
CXX=g++
COBJS=hid.o
CPPOBJS=../hidtest/hidtest.o
OBJS=$(COBJS) $(CPPOBJS)
CFLAGS+=-I../hidapi -Wall -g -c
LIBS=-framework CoreBluetooth -framework CoreFoundation
hidtest: $(OBJS)
g++ -Wall -g $^ $(LIBS) -o hidtest
$(COBJS): %.o: %.c
$(CC) $(CFLAGS) $< -o $@
$(CPPOBJS): %.o: %.cpp
$(CXX) $(CFLAGS) $< -o $@
clean:
rm -f *.o hidtest $(CPPOBJS)
.PHONY: clean

View file

@ -1,9 +0,0 @@
lib_LTLIBRARIES = libhidapi.la
libhidapi_la_SOURCES = hid.m
libhidapi_la_LDFLAGS = $(LTLDFLAGS)
AM_CPPFLAGS = -I$(top_srcdir)/hidapi/
hdrdir = $(includedir)/hidapi
hdr_HEADERS = $(top_srcdir)/hidapi/hidapi.h
EXTRA_DIST = Makefile-manual

View file

@ -1,914 +0,0 @@
//======== Copyright (c) 2017 Valve Corporation, All rights reserved. =========
//
// Purpose: HID device abstraction temporary stub
//
//=============================================================================
#include "../../SDL_internal.h"
#ifdef SDL_JOYSTICK_HIDAPI
#include <CoreBluetooth/CoreBluetooth.h>
#include <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
#import <mach/mach_time.h>
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include "../hidapi/hidapi.h"
#define VALVE_USB_VID 0x28DE
#define D0G_BLE2_PID 0x1106
typedef uint32_t uint32;
typedef uint64_t uint64;
// enables detailed NSLog logging of feature reports
#define FEATURE_REPORT_LOGGING 0
#define REPORT_SEGMENT_DATA_FLAG 0x80
#define REPORT_SEGMENT_LAST_FLAG 0x40
#define VALVE_SERVICE @"100F6C32-1735-4313-B402-38567131E5F3"
// (READ/NOTIFICATIONS)
#define VALVE_INPUT_CHAR @"100F6C33-1735-4313-B402-38567131E5F3"
//  (READ/WRITE)
#define VALVE_REPORT_CHAR @"100F6C34-1735-4313-B402-38567131E5F3"
// TODO: create CBUUID's in __attribute__((constructor)) rather than doing [CBUUID UUIDWithString:...] everywhere
#pragma pack(push,1)
typedef struct
{
uint8_t segmentHeader;
uint8_t featureReportMessageID;
uint8_t length;
uint8_t settingIdentifier;
union {
uint16_t usPayload;
uint32_t uPayload;
uint64_t ulPayload;
uint8_t ucPayload[15];
};
} bluetoothSegment;
typedef struct {
uint8_t id;
union {
bluetoothSegment segment;
struct {
uint8_t segmentHeader;
uint8_t featureReportMessageID;
uint8_t length;
uint8_t settingIdentifier;
union {
uint16_t usPayload;
uint32_t uPayload;
uint64_t ulPayload;
uint8_t ucPayload[15];
};
};
};
} hidFeatureReport;
#pragma pack(pop)
size_t GetBluetoothSegmentSize(bluetoothSegment *segment)
{
return segment->length + 3;
}
#define RingBuffer_cbElem 19
#define RingBuffer_nElem 4096
typedef struct {
int _first, _last;
uint8_t _data[ ( RingBuffer_nElem * RingBuffer_cbElem ) ];
pthread_mutex_t accessLock;
} RingBuffer;
static void RingBuffer_init( RingBuffer *this )
{
this->_first = -1;
this->_last = 0;
pthread_mutex_init( &this->accessLock, 0 );
}
static bool RingBuffer_write( RingBuffer *this, const uint8_t *src )
{
pthread_mutex_lock( &this->accessLock );
memcpy( &this->_data[ this->_last ], src, RingBuffer_cbElem );
if ( this->_first == -1 )
{
this->_first = this->_last;
}
this->_last = ( this->_last + RingBuffer_cbElem ) % (RingBuffer_nElem * RingBuffer_cbElem);
if ( this->_last == this->_first )
{
this->_first = ( this->_first + RingBuffer_cbElem ) % (RingBuffer_nElem * RingBuffer_cbElem);
pthread_mutex_unlock( &this->accessLock );
return false;
}
pthread_mutex_unlock( &this->accessLock );
return true;
}
static bool RingBuffer_read( RingBuffer *this, uint8_t *dst )
{
pthread_mutex_lock( &this->accessLock );
if ( this->_first == -1 )
{
pthread_mutex_unlock( &this->accessLock );
return false;
}
memcpy( dst, &this->_data[ this->_first ], RingBuffer_cbElem );
this->_first = ( this->_first + RingBuffer_cbElem ) % (RingBuffer_nElem * RingBuffer_cbElem);
if ( this->_first == this->_last )
{
this->_first = -1;
}
pthread_mutex_unlock( &this->accessLock );
return true;
}
#pragma mark HIDBLEDevice Definition
typedef enum
{
BLEDeviceWaitState_None,
BLEDeviceWaitState_Waiting,
BLEDeviceWaitState_Complete,
BLEDeviceWaitState_Error
} BLEDeviceWaitState;
@interface HIDBLEDevice : NSObject <CBPeripheralDelegate>
{
RingBuffer _inputReports;
uint8_t _featureReport[20];
BLEDeviceWaitState _waitStateForReadFeatureReport;
BLEDeviceWaitState _waitStateForWriteFeatureReport;
}
@property (nonatomic, readwrite) bool connected;
@property (nonatomic, readwrite) bool ready;
@property (nonatomic, strong) CBPeripheral *bleSteamController;
@property (nonatomic, strong) CBCharacteristic *bleCharacteristicInput;
@property (nonatomic, strong) CBCharacteristic *bleCharacteristicReport;
- (id)initWithPeripheral:(CBPeripheral *)peripheral;
@end
@interface HIDBLEManager : NSObject <CBCentralManagerDelegate>
@property (nonatomic) int nPendingScans;
@property (nonatomic) int nPendingPairs;
@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) NSMapTable<CBPeripheral *, HIDBLEDevice *> *deviceMap;
@property (nonatomic, retain) dispatch_queue_t bleSerialQueue;
+ (instancetype)sharedInstance;
- (void)startScan:(int)duration;
- (void)stopScan;
- (int)updateConnectedSteamControllers:(BOOL) bForce;
- (void)appWillResignActiveNotification:(NSNotification *)note;
- (void)appDidBecomeActiveNotification:(NSNotification *)note;
@end
// singleton class - access using HIDBLEManager.sharedInstance
@implementation HIDBLEManager
+ (instancetype)sharedInstance
{
static HIDBLEManager *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [HIDBLEManager new];
sharedInstance.nPendingScans = 0;
sharedInstance.nPendingPairs = 0;
[[NSNotificationCenter defaultCenter] addObserver:sharedInstance selector:@selector(appWillResignActiveNotification:) name: UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:sharedInstance selector:@selector(appDidBecomeActiveNotification:) name:UIApplicationDidBecomeActiveNotification object:nil];
// receive reports on a high-priority serial-queue. optionally put writes on the serial queue to avoid logical
// race conditions talking to the controller from multiple threads, although BLE fragmentation/assembly means
// that we can still screw this up.
// most importantly we need to consume reports at a high priority to avoid the OS thinking we aren't really
// listening to the BLE device, as iOS on slower devices may stop delivery of packets to the app WITHOUT ACTUALLY
// DISCONNECTING FROM THE DEVICE if we don't react quickly enough to their delivery.
// see also the error-handling states in the peripheral delegate to re-open the device if it gets closed
sharedInstance.bleSerialQueue = dispatch_queue_create( "com.valvesoftware.steamcontroller.ble", DISPATCH_QUEUE_SERIAL );
dispatch_set_target_queue( sharedInstance.bleSerialQueue, dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0 ) );
// creating a CBCentralManager will always trigger a future centralManagerDidUpdateState:
// where any scanning gets started or connecting to existing peripherals happens, it's never already in a
// powered-on state for a newly launched application.
sharedInstance.centralManager = [[CBCentralManager alloc] initWithDelegate:sharedInstance queue:sharedInstance.bleSerialQueue];
sharedInstance.deviceMap = [[NSMapTable alloc] initWithKeyOptions:NSMapTableWeakMemory valueOptions:NSMapTableStrongMemory capacity:4];
});
return sharedInstance;
}
// called for NSNotification UIApplicationWillResignActiveNotification
- (void)appWillResignActiveNotification:(NSNotification *)note
{
// we'll get resign-active notification if pairing is happening.
if ( self.nPendingPairs > 0 )
return;
for ( CBPeripheral *peripheral in self.deviceMap )
{
HIDBLEDevice *steamController = [self.deviceMap objectForKey:peripheral];
if ( steamController )
{
steamController.connected = NO;
steamController.ready = NO;
[self.centralManager cancelPeripheralConnection:peripheral];
}
}
[self.deviceMap removeAllObjects];
}
// called for NSNotification UIApplicationDidBecomeActiveNotification
// whenever the application comes back from being inactive, trigger a 20s pairing scan and reconnect
// any devices that may have paired while we were inactive.
- (void)appDidBecomeActiveNotification:(NSNotification *)note
{
[self updateConnectedSteamControllers:true];
[self startScan:20];
}
- (int)updateConnectedSteamControllers:(BOOL) bForce
{
static uint64_t s_unLastUpdateTick = 0;
static mach_timebase_info_data_t s_timebase_info;
if (s_timebase_info.denom == 0)
{
mach_timebase_info( &s_timebase_info );
}
uint64_t ticksNow = mach_approximate_time();
if ( !bForce && ( ( (ticksNow - s_unLastUpdateTick) * s_timebase_info.numer ) / s_timebase_info.denom ) < (5ull * NSEC_PER_SEC) )
return (int)self.deviceMap.count;
// we can see previously connected BLE peripherals but can't connect until the CBCentralManager
// is fully powered up - only do work when we are in that state
if ( self.centralManager.state != CBManagerStatePoweredOn )
return (int)self.deviceMap.count;
// only update our last-check-time if we actually did work, otherwise there can be a long delay during initial power-up
s_unLastUpdateTick = mach_approximate_time();
// if a pair is in-flight, the central manager may still give it back via retrieveConnected... and
// cause the SDL layer to attempt to initialize it while some of its endpoints haven't yet been established
if ( self.nPendingPairs > 0 )
return (int)self.deviceMap.count;
NSArray<CBPeripheral *> *peripherals = [self.centralManager retrieveConnectedPeripheralsWithServices: @[ [CBUUID UUIDWithString:@"180A"]]];
for ( CBPeripheral *peripheral in peripherals )
{
// we already know this peripheral
if ( [self.deviceMap objectForKey: peripheral] != nil )
continue;
NSLog( @"connected peripheral: %@", peripheral );
if ( [peripheral.name isEqualToString:@"SteamController"] )
{
HIDBLEDevice *steamController = [[HIDBLEDevice alloc] initWithPeripheral:peripheral];
[self.deviceMap setObject:steamController forKey:peripheral];
[self.centralManager connectPeripheral:peripheral options:nil];
}
}
return (int)self.deviceMap.count;
}
// manual API for folks to start & stop scanning
- (void)startScan:(int)duration
{
NSLog( @"BLE: requesting scan for %d seconds", duration );
@synchronized (self)
{
if ( _nPendingScans++ == 0 )
{
[self.centralManager scanForPeripheralsWithServices:nil options:nil];
}
}
if ( duration != 0 )
{
dispatch_after( dispatch_time( DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self stopScan];
});
}
}
- (void)stopScan
{
NSLog( @"BLE: stopping scan" );
@synchronized (self)
{
if ( --_nPendingScans <= 0 )
{
_nPendingScans = 0;
[self.centralManager stopScan];
}
}
}
#pragma mark CBCentralManagerDelegate Implementation
// called whenever the BLE hardware state changes.
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
switch ( central.state )
{
case CBCentralManagerStatePoweredOn:
{
NSLog( @"CoreBluetooth BLE hardware is powered on and ready" );
// at startup, if we have no already attached peripherals, do a 20s scan for new unpaired devices,
// otherwise callers should occaisionally do additional scans. we don't want to continuously be
// scanning because it drains battery, causes other nearby people to have a hard time pairing their
// Steam Controllers, and may also trigger firmware weirdness when a device attempts to start
// the pairing sequence multiple times concurrently
if ( [self updateConnectedSteamControllers:false] == 0 )
{
// TODO: we could limit our scan to only peripherals supporting the SteamController service, but
// that service doesn't currently fit in the base advertising packet, we'd need to put it into an
// extended scan packet. Useful optimization downstream, but not currently necessary
// NSArray *services = @[[CBUUID UUIDWithString:VALVE_SERVICE]];
[self startScan:20];
}
break;
}
case CBCentralManagerStatePoweredOff:
NSLog( @"CoreBluetooth BLE hardware is powered off" );
break;
case CBCentralManagerStateUnauthorized:
NSLog( @"CoreBluetooth BLE state is unauthorized" );
break;
case CBCentralManagerStateUnknown:
NSLog( @"CoreBluetooth BLE state is unknown" );
break;
case CBCentralManagerStateUnsupported:
NSLog( @"CoreBluetooth BLE hardware is unsupported on this platform" );
break;
case CBCentralManagerStateResetting:
NSLog( @"CoreBluetooth BLE manager is resetting" );
break;
}
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
HIDBLEDevice *steamController = [_deviceMap objectForKey:peripheral];
steamController.connected = YES;
self.nPendingPairs -= 1;
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog( @"Failed to connect: %@", error );
[_deviceMap removeObjectForKey:peripheral];
self.nPendingPairs -= 1;
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
NSString *localName = [advertisementData objectForKey:CBAdvertisementDataLocalNameKey];
NSString *log = [NSString stringWithFormat:@"Found '%@'", localName];
if ( [localName isEqualToString:@"SteamController"] )
{
NSLog( @"%@ : %@ - %@", log, peripheral, advertisementData );
self.nPendingPairs += 1;
HIDBLEDevice *steamController = [[HIDBLEDevice alloc] initWithPeripheral:peripheral];
[self.deviceMap setObject:steamController forKey:peripheral];
[self.centralManager connectPeripheral:peripheral options:nil];
}
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
HIDBLEDevice *steamController = [self.deviceMap objectForKey:peripheral];
if ( steamController )
{
steamController.connected = NO;
steamController.ready = NO;
[self.deviceMap removeObjectForKey:peripheral];
}
}
@end
// Core Bluetooth devices calling back on event boundaries of their run-loops. so annoying.
static void process_pending_events()
{
CFRunLoopRunResult res;
do
{
res = CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0.001, FALSE );
}
while( res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut );
}
@implementation HIDBLEDevice
- (id)init
{
if ( self = [super init] )
{
RingBuffer_init( &_inputReports );
self.bleSteamController = nil;
self.bleCharacteristicInput = nil;
self.bleCharacteristicReport = nil;
_connected = NO;
_ready = NO;
}
return self;
}
- (id)initWithPeripheral:(CBPeripheral *)peripheral
{
if ( self = [super init] )
{
RingBuffer_init( &_inputReports );
_connected = NO;
_ready = NO;
self.bleSteamController = peripheral;
if ( peripheral )
{
peripheral.delegate = self;
}
self.bleCharacteristicInput = nil;
self.bleCharacteristicReport = nil;
}
return self;
}
- (void)setConnected:(bool)connected
{
_connected = connected;
if ( _connected )
{
[_bleSteamController discoverServices:nil];
}
else
{
NSLog( @"Disconnected" );
}
}
- (size_t)read_input_report:(uint8_t *)dst
{
if ( RingBuffer_read( &_inputReports, dst+1 ) )
{
*dst = 0x03;
return 20;
}
return 0;
}
- (int)send_report:(const uint8_t *)data length:(size_t)length
{
[_bleSteamController writeValue:[NSData dataWithBytes:data length:length] forCharacteristic:_bleCharacteristicReport type:CBCharacteristicWriteWithResponse];
return (int)length;
}
- (int)send_feature_report:(hidFeatureReport *)report
{
#if FEATURE_REPORT_LOGGING
uint8_t *reportBytes = (uint8_t *)report;
NSLog( @"HIDBLE:send_feature_report (%02zu/19) [%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]", GetBluetoothSegmentSize( report->segment ),
reportBytes[1], reportBytes[2], reportBytes[3], reportBytes[4], reportBytes[5], reportBytes[6],
reportBytes[7], reportBytes[8], reportBytes[9], reportBytes[10], reportBytes[11], reportBytes[12],
reportBytes[13], reportBytes[14], reportBytes[15], reportBytes[16], reportBytes[17], reportBytes[18],
reportBytes[19] );
#endif
int sendSize = (int)GetBluetoothSegmentSize( &report->segment );
if ( sendSize > 20 )
sendSize = 20;
#if 1
// fire-and-forget - we are going to not wait for the response here because all Steam Controller BLE send_feature_report's are ignored,
// except errors.
[_bleSteamController writeValue:[NSData dataWithBytes:&report->segment length:sendSize] forCharacteristic:_bleCharacteristicReport type:CBCharacteristicWriteWithResponse];
// pretend we received a result anybody cares about
return 19;
#else
// this is technically the correct send_feature_report logic if you want to make sure it gets through and is
// acknowledged or errors out
_waitStateForWriteFeatureReport = BLEDeviceWaitState_Waiting;
[_bleSteamController writeValue:[NSData dataWithBytes:&report->segment length:sendSize
] forCharacteristic:_bleCharacteristicReport type:CBCharacteristicWriteWithResponse];
while ( _waitStateForWriteFeatureReport == BLEDeviceWaitState_Waiting )
{
process_pending_events();
}
if ( _waitStateForWriteFeatureReport == BLEDeviceWaitState_Error )
{
_waitStateForWriteFeatureReport = BLEDeviceWaitState_None;
return -1;
}
_waitStateForWriteFeatureReport = BLEDeviceWaitState_None;
return 19;
#endif
}
- (int)get_feature_report:(uint8_t)feature into:(uint8_t *)buffer
{
_waitStateForReadFeatureReport = BLEDeviceWaitState_Waiting;
[_bleSteamController readValueForCharacteristic:_bleCharacteristicReport];
while ( _waitStateForReadFeatureReport == BLEDeviceWaitState_Waiting )
process_pending_events();
if ( _waitStateForReadFeatureReport == BLEDeviceWaitState_Error )
{
_waitStateForReadFeatureReport = BLEDeviceWaitState_None;
return -1;
}
memcpy( buffer, _featureReport, sizeof(_featureReport) );
_waitStateForReadFeatureReport = BLEDeviceWaitState_None;
#if FEATURE_REPORT_LOGGING
NSLog( @"HIDBLE:get_feature_report (19) [%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]",
buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6],
buffer[7], buffer[8], buffer[9], buffer[10], buffer[11], buffer[12],
buffer[13], buffer[14], buffer[15], buffer[16], buffer[17], buffer[18],
buffer[19] );
#endif
return 19;
}
#pragma mark CBPeripheralDelegate Implementation
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
for (CBService *service in peripheral.services)
{
NSLog( @"Found Service: %@", service );
if ( [service.UUID isEqual:[CBUUID UUIDWithString:VALVE_SERVICE]] )
{
[peripheral discoverCharacteristics:nil forService:service];
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
// nothing yet needed here, enable for logging
if ( /* DISABLES CODE */ (0) )
{
for ( CBDescriptor *descriptor in characteristic.descriptors )
{
NSLog( @" - Descriptor '%@'", descriptor );
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if ([service.UUID isEqual:[CBUUID UUIDWithString:VALVE_SERVICE]])
{
for (CBCharacteristic *aChar in service.characteristics)
{
NSLog( @"Found Characteristic %@", aChar );
if ( [aChar.UUID isEqual:[CBUUID UUIDWithString:VALVE_INPUT_CHAR]] )
{
self.bleCharacteristicInput = aChar;
}
else if ( [aChar.UUID isEqual:[CBUUID UUIDWithString:VALVE_REPORT_CHAR]] )
{
self.bleCharacteristicReport = aChar;
[self.bleSteamController discoverDescriptorsForCharacteristic: aChar];
}
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
static uint64_t s_ticksLastOverflowReport = 0;
// receiving an input report is the final indicator that the user accepted a pairing
// request and that we successfully established notification. CoreBluetooth has no
// notification of the pairing acknowledgement, which is a bad oversight.
if ( self.ready == NO )
{
self.ready = YES;
HIDBLEManager.sharedInstance.nPendingPairs -= 1;
}
if ( [characteristic.UUID isEqual:_bleCharacteristicInput.UUID] )
{
NSData *data = [characteristic value];
if ( data.length != 19 )
{
NSLog( @"HIDBLE: incoming data is %lu bytes should be exactly 19", (unsigned long)data.length );
}
if ( !RingBuffer_write( &_inputReports, (const uint8_t *)data.bytes ) )
{
uint64_t ticksNow = mach_approximate_time();
if ( ticksNow - s_ticksLastOverflowReport > (5ull * NSEC_PER_SEC / 10) )
{
NSLog( @"HIDBLE: input report buffer overflow" );
s_ticksLastOverflowReport = ticksNow;
}
}
}
else if ( [characteristic.UUID isEqual:_bleCharacteristicReport.UUID] )
{
memset( _featureReport, 0, sizeof(_featureReport) );
if ( error != nil )
{
NSLog( @"HIDBLE: get_feature_report error: %@", error );
_waitStateForReadFeatureReport = BLEDeviceWaitState_Error;
}
else
{
NSData *data = [characteristic value];
if ( data.length != 20 )
{
NSLog( @"HIDBLE: incoming data is %lu bytes should be exactly 20", (unsigned long)data.length );
}
memcpy( _featureReport, data.bytes, MIN( data.length, sizeof(_featureReport) ) );
_waitStateForReadFeatureReport = BLEDeviceWaitState_Complete;
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if ( [characteristic.UUID isEqual:[CBUUID UUIDWithString:VALVE_REPORT_CHAR]] )
{
if ( error != nil )
{
NSLog( @"HIDBLE: write_feature_report error: %@", error );
_waitStateForWriteFeatureReport = BLEDeviceWaitState_Error;
}
else
{
_waitStateForWriteFeatureReport = BLEDeviceWaitState_Complete;
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog( @"didUpdateNotifcationStateForCharacteristic %@ (%@)", characteristic, error );
}
@end
#pragma mark hid_api implementation
struct hid_device_ {
void *device_handle;
int blocking;
hid_device *next;
};
int HID_API_EXPORT HID_API_CALL hid_init(void)
{
return ( HIDBLEManager.sharedInstance == nil ) ? -1 : 0;
}
int HID_API_EXPORT HID_API_CALL hid_exit(void)
{
return 0;
}
void HID_API_EXPORT HID_API_CALL hid_ble_scan( bool bStart )
{
HIDBLEManager *bleManager = HIDBLEManager.sharedInstance;
if ( bStart )
{
[bleManager startScan:0];
}
else
{
[bleManager stopScan];
}
}
hid_device * HID_API_EXPORT hid_open_path( const char *path, int bExclusive /* = false */ )
{
hid_device *result = NULL;
NSString *nssPath = [NSString stringWithUTF8String:path];
HIDBLEManager *bleManager = HIDBLEManager.sharedInstance;
NSEnumerator<HIDBLEDevice *> *devices = [bleManager.deviceMap objectEnumerator];
for ( HIDBLEDevice *device in devices )
{
// we have the device but it hasn't found its service or characteristics until it is connected
if ( !device.ready || !device.connected || !device.bleCharacteristicInput )
continue;
if ( [device.bleSteamController.identifier.UUIDString isEqualToString:nssPath] )
{
result = (hid_device *)malloc( sizeof( hid_device ) );
memset( result, 0, sizeof( hid_device ) );
result->device_handle = (void*)CFBridgingRetain( device );
result->blocking = NO;
// enable reporting input events on the characteristic
[device.bleSteamController setNotifyValue:YES forCharacteristic:device.bleCharacteristicInput];
return result;
}
}
return result;
}
void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
{
/* This function is identical to the Linux version. Platform independent. */
struct hid_device_info *d = devs;
while (d) {
struct hid_device_info *next = d->next;
free(d->path);
free(d->serial_number);
free(d->manufacturer_string);
free(d->product_string);
free(d);
d = next;
}
}
int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
{
/* All Nonblocking operation is handled by the library. */
dev->blocking = !nonblock;
return 0;
}
struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{ @autoreleasepool {
struct hid_device_info *root = NULL;
if ( ( vendor_id == 0 && product_id == 0 ) ||
( vendor_id == VALVE_USB_VID && product_id == D0G_BLE2_PID ) )
{
HIDBLEManager *bleManager = HIDBLEManager.sharedInstance;
[bleManager updateConnectedSteamControllers:false];
NSEnumerator<HIDBLEDevice *> *devices = [bleManager.deviceMap objectEnumerator];
for ( HIDBLEDevice *device in devices )
{
// there are several brief windows in connecting to an already paired device and
// one long window waiting for users to confirm pairing where we don't want
// to consider a device ready - if we hand it back to SDL or another
// Steam Controller consumer, their additional SC setup work will fail
// in unusual/silent ways and we can actually corrupt the BLE stack for
// the entire system and kill the appletv remote's Menu button (!)
if ( device.bleSteamController.state != CBPeripheralStateConnected ||
device.connected == NO || device.ready == NO )
{
if ( device.ready == NO && device.bleCharacteristicInput != nil )
{
// attempt to register for input reports. this call will silently fail
// until the pairing finalizes with user acceptance. oh, apple.
[device.bleSteamController setNotifyValue:YES forCharacteristic:device.bleCharacteristicInput];
}
continue;
}
struct hid_device_info *device_info = (struct hid_device_info *)malloc( sizeof(struct hid_device_info) );
memset( device_info, 0, sizeof(struct hid_device_info) );
device_info->next = root;
root = device_info;
device_info->path = strdup( device.bleSteamController.identifier.UUIDString.UTF8String );
device_info->vendor_id = VALVE_USB_VID;
device_info->product_id = D0G_BLE2_PID;
device_info->product_string = wcsdup( L"Steam Controller" );
device_info->manufacturer_string = wcsdup( L"Valve Corporation" );
}
}
return root;
}}
int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
static wchar_t s_wszManufacturer[] = L"Valve Corporation";
wcsncpy( string, s_wszManufacturer, sizeof(s_wszManufacturer)/sizeof(s_wszManufacturer[0]) );
return 0;
}
int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
static wchar_t s_wszProduct[] = L"Steam Controller";
wcsncpy( string, s_wszProduct, sizeof(s_wszProduct)/sizeof(s_wszProduct[0]) );
return 0;
}
int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
static wchar_t s_wszSerial[] = L"12345";
wcsncpy( string, s_wszSerial, sizeof(s_wszSerial)/sizeof(s_wszSerial[0]) );
return 0;
}
int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
{
HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
if ( !device_handle.connected )
return -1;
return [device_handle send_report:data length:length];
}
void HID_API_EXPORT hid_close(hid_device *dev)
{
HIDBLEDevice *device_handle = CFBridgingRelease( dev->device_handle );
// disable reporting input events on the characteristic
if ( device_handle.connected ) {
[device_handle.bleSteamController setNotifyValue:NO forCharacteristic:device_handle.bleCharacteristicInput];
}
free( dev );
}
int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
{
HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
if ( !device_handle.connected )
return -1;
return [device_handle send_feature_report:(hidFeatureReport *)(void *)data];
}
int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
{
HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
if ( !device_handle.connected )
return -1;
size_t written = [device_handle get_feature_report:data[0] into:data];
return written == length-1 ? (int)length : (int)written;
}
int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
{
HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
if ( !device_handle.connected )
return -1;
return hid_read_timeout(dev, data, length, 0);
}
int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
{
HIDBLEDevice *device_handle = (__bridge HIDBLEDevice *)dev->device_handle;
if ( !device_handle.connected )
return -1;
if ( milliseconds != 0 )
{
NSLog( @"hid_read_timeout with non-zero wait" );
}
int result = (int)[device_handle read_input_report:data];
#if FEATURE_REPORT_LOGGING
NSLog( @"HIDBLE:hid_read_timeout (%d) [%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]", result,
data[1], data[2], data[3], data[4], data[5], data[6],
data[7], data[8], data[9], data[10], data[11], data[12],
data[13], data[14], data[15], data[16], data[17], data[18],
data[19] );
#endif
return result;
}
#endif /* SDL_JOYSTICK_HIDAPI */

View file

@ -1,18 +0,0 @@
OS=$(shell uname)
ifeq ($(OS), Linux)
FILE=Makefile.linux
endif
ifeq ($(OS), FreeBSD)
FILE=Makefile.freebsd
endif
ifeq ($(FILE), )
all:
$(error Your platform ${OS} is not supported by hidapi/libusb at this time.)
endif
include $(FILE)

View file

@ -1,27 +0,0 @@
AM_CPPFLAGS = -I$(top_srcdir)/hidapi $(CFLAGS_LIBUSB)
if OS_LINUX
lib_LTLIBRARIES = libhidapi-libusb.la
libhidapi_libusb_la_SOURCES = hid.c
libhidapi_libusb_la_LDFLAGS = $(LTLDFLAGS) $(PTHREAD_CFLAGS)
libhidapi_libusb_la_LIBADD = $(LIBS_LIBUSB)
endif
if OS_FREEBSD
lib_LTLIBRARIES = libhidapi.la
libhidapi_la_SOURCES = hid.c
libhidapi_la_LDFLAGS = $(LTLDFLAGS)
libhidapi_la_LIBADD = $(LIBS_LIBUSB)
endif
if OS_KFREEBSD
lib_LTLIBRARIES = libhidapi.la
libhidapi_la_SOURCES = hid.c
libhidapi_la_LDFLAGS = $(LTLDFLAGS)
libhidapi_la_LIBADD = $(LIBS_LIBUSB)
endif
hdrdir = $(includedir)/hidapi
hdr_HEADERS = $(top_srcdir)/hidapi/hidapi.h
EXTRA_DIST = Makefile-manual

View file

@ -1,46 +0,0 @@
###########################################
# Simple Makefile for HIDAPI test program
#
# Alan Ott
# Signal 11 Software
# 2010-06-01
###########################################
all: hidtest libs
libs: libhidapi.so
CC ?= cc
CFLAGS ?= -Wall -g -fPIC
CXX ?= c++
CXXFLAGS ?= -Wall -g
COBJS = hid.o
CPPOBJS = ../hidtest/hidtest.o
OBJS = $(COBJS) $(CPPOBJS)
INCLUDES = -I../hidapi -I/usr/local/include
LDFLAGS = -L/usr/local/lib
LIBS = -lusb -liconv -pthread
# Console Test Program
hidtest: $(OBJS)
$(CXX) $(CXXFLAGS) $(LDFLAGS) $^ -o $@ $(LIBS)
# Shared Libs
libhidapi.so: $(COBJS)
$(CC) $(LDFLAGS) -shared -Wl,-soname,$@.0 $^ -o $@ $(LIBS)
# Objects
$(COBJS): %.o: %.c
$(CC) $(CFLAGS) -c $(INCLUDES) $< -o $@
$(CPPOBJS): %.o: %.cpp
$(CXX) $(CXXFLAGS) -c $(INCLUDES) $< -o $@
clean:
rm -f $(OBJS) hidtest libhidapi.so ../hidtest/hidtest.o
.PHONY: clean libs

View file

@ -1,49 +0,0 @@
###########################################
# Simple Makefile for HIDAPI test program
#
# Alan Ott
# Signal 11 Software
# 2010-06-01
###########################################
all: hidtest-libusb libs
libs: libhidapi-libusb.so
CC ?= gcc
CFLAGS ?= -Wall -g -fpic
CXX ?= g++
CXXFLAGS ?= -Wall -g -fpic
LDFLAGS ?= -Wall -g
COBJS_LIBUSB = hid.o
COBJS = $(COBJS_LIBUSB)
CPPOBJS = ../hidtest/hidtest.o
OBJS = $(COBJS) $(CPPOBJS)
LIBS_USB = `pkg-config libusb-1.0 --libs` -lrt -lpthread
LIBS = $(LIBS_USB)
INCLUDES ?= -I../hidapi `pkg-config libusb-1.0 --cflags`
# Console Test Program
hidtest-libusb: $(COBJS_LIBUSB) $(CPPOBJS)
$(CXX) $(LDFLAGS) $^ $(LIBS_USB) -o $@
# Shared Libs
libhidapi-libusb.so: $(COBJS_LIBUSB)
$(CC) $(LDFLAGS) $(LIBS_USB) -shared -fpic -Wl,-soname,$@.0 $^ -o $@
# Objects
$(COBJS): %.o: %.c
$(CC) $(CFLAGS) -c $(INCLUDES) $< -o $@
$(CPPOBJS): %.o: %.cpp
$(CXX) $(CXXFLAGS) -c $(INCLUDES) $< -o $@
clean:
rm -f $(OBJS) hidtest-libusb libhidapi-libusb.so ../hidtest/hidtest.o
.PHONY: clean libs

File diff suppressed because it is too large Load diff

View file

@ -1,3 +0,0 @@
#define NAMESPACE HIDUSB
#include "hid.c"

View file

@ -1,49 +0,0 @@
###########################################
# Simple Makefile for HIDAPI test program
#
# Alan Ott
# Signal 11 Software
# 2010-06-01
###########################################
all: hidtest-hidraw libs
libs: libhidapi-hidraw.so
CC ?= gcc
CFLAGS ?= -Wall -g -fpic
CXX ?= g++
CXXFLAGS ?= -Wall -g -fpic
LDFLAGS ?= -Wall -g
COBJS = hid.o
CPPOBJS = ../hidtest/hidtest.o
OBJS = $(COBJS) $(CPPOBJS)
LIBS_UDEV = `pkg-config libudev --libs` -lrt
LIBS = $(LIBS_UDEV)
INCLUDES ?= -I../hidapi `pkg-config libusb-1.0 --cflags`
# Console Test Program
hidtest-hidraw: $(COBJS) $(CPPOBJS)
$(CXX) $(LDFLAGS) $^ $(LIBS_UDEV) -o $@
# Shared Libs
libhidapi-hidraw.so: $(COBJS)
$(CC) $(LDFLAGS) $(LIBS_UDEV) -shared -fpic -Wl,-soname,$@.0 $^ -o $@
# Objects
$(COBJS): %.o: %.c
$(CC) $(CFLAGS) -c $(INCLUDES) $< -o $@
$(CPPOBJS): %.o: %.cpp
$(CXX) $(CXXFLAGS) -c $(INCLUDES) $< -o $@
clean:
rm -f $(OBJS) hidtest-hidraw libhidapi-hidraw.so ../hidtest/hidtest.o
.PHONY: clean libs

View file

@ -1,10 +0,0 @@
lib_LTLIBRARIES = libhidapi-hidraw.la
libhidapi_hidraw_la_SOURCES = hid.c
libhidapi_hidraw_la_LDFLAGS = $(LTLDFLAGS)
AM_CPPFLAGS = -I$(top_srcdir)/hidapi/ $(CFLAGS_HIDRAW)
libhidapi_hidraw_la_LIBADD = $(LIBS_HIDRAW)
hdrdir = $(includedir)/hidapi
hdr_HEADERS = $(top_srcdir)/hidapi/hidapi.h
EXTRA_DIST = Makefile-manual

View file

@ -1,59 +0,0 @@
There are two implementations of HIDAPI for Linux. One (linux/hid.c) uses the
Linux hidraw driver, and the other (libusb/hid.c) uses libusb. Which one you
use depends on your application. Complete functionality of the hidraw
version depends on patches to the Linux kernel which are not currently in
the mainline. These patches have to do with sending and receiving feature
reports. The libusb implementation uses libusb to talk directly to the
device, bypassing any Linux HID driver. The disadvantage of the libusb
version is that it will only work with USB devices, while the hidraw
implementation will work with Bluetooth devices as well.
To use HIDAPI, simply drop either linux/hid.c or libusb/hid.c into your
application and build using the build parameters in the Makefile.
Libusb Implementation notes
----------------------------
For the libusb implementation, libusb-1.0 must be installed. Libusb 1.0 is
different than the legacy libusb 0.1 which is installed on many systems. To
install libusb-1.0 on Ubuntu and other Debian-based systems, run:
sudo apt-get install libusb-1.0-0-dev
Hidraw Implementation notes
----------------------------
For the hidraw implementation, libudev headers and libraries are required to
build hidapi programs. To install libudev libraries on Ubuntu,
and other Debian-based systems, run:
sudo apt-get install libudev-dev
On Redhat-based systems, run the following as root:
yum install libudev-devel
Unfortunately, the hidraw driver, which the linux version of hidapi is based
on, contains bugs in kernel versions < 2.6.36, which the client application
should be aware of.
Bugs (hidraw implementation only):
-----------------------------------
On Kernel versions < 2.6.34, if your device uses numbered reports, an extra
byte will be returned at the beginning of all reports returned from read()
for hidraw devices. This is worked around in the libary. No action should be
necessary in the client library.
On Kernel versions < 2.6.35, reports will only be sent using a Set_Report
transfer on the CONTROL endpoint. No data will ever be sent on an Interrupt
Out endpoint if one exists. This is fixed in 2.6.35. In 2.6.35, OUTPUT
reports will be sent to the device on the first INTERRUPT OUT endpoint if it
exists; If it does not exist, OUTPUT reports will be sent on the CONTROL
endpoint.
On Kernel versions < 2.6.36, add an extra byte containing the report number
to sent reports if numbered reports are used, and the device does not
contain an INTERRPUT OUT endpoint for OUTPUT transfers. For example, if
your device uses numbered reports and wants to send {0x2 0xff 0xff 0xff} to
the device (0x2 is the report number), you must send {0x2 0x2 0xff 0xff
0xff}. If your device has the optional Interrupt OUT endpoint, this does not
apply (but really on 2.6.35 only, because 2.6.34 won't use the interrupt
out endpoint).

View file

@ -1,898 +0,0 @@
/*******************************************************
HIDAPI - Multi-Platform library for
communication with HID devices.
Alan Ott
Signal 11 Software
8/22/2009
Linux Version - 6/2/2009
Copyright 2009, All Rights Reserved.
At the discretion of the user of this library,
this software may be licensed under the terms of the
GNU General Public License v3, a BSD-Style license, or the
original HIDAPI license as outlined in the LICENSE.txt,
LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
files located at the root of the source distribution.
These files may also be found in the public source
code repository located at:
http://github.com/signal11/hidapi .
********************************************************/
#include "../../SDL_internal.h"
#ifdef SDL_JOYSTICK_HIDAPI
#ifndef _GNU_SOURCE
#define _GNU_SOURCE /* needed for wcsdup() before glibc 2.10 */
#endif
/* C */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>
#include <errno.h>
/* Unix */
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <fcntl.h>
#include <poll.h>
/* Linux */
#include <linux/hidraw.h>
#include <linux/version.h>
#include <linux/input.h>
#include <libudev.h>
#include "hidapi.h"
#ifdef NAMESPACE
namespace NAMESPACE
{
#endif
/* Definitions from linux/hidraw.h. Since these are new, some distros
may not have header files which contain them. */
#ifndef HIDIOCSFEATURE
#define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len)
#endif
#ifndef HIDIOCGFEATURE
#define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len)
#endif
/* USB HID device property names */
const char *device_string_names[] = {
"manufacturer",
"product",
"serial",
};
/* Symbolic names for the properties above */
enum device_string_id {
DEVICE_STRING_MANUFACTURER,
DEVICE_STRING_PRODUCT,
DEVICE_STRING_SERIAL,
DEVICE_STRING_COUNT,
};
struct hid_device_ {
int device_handle;
int blocking;
int uses_numbered_reports;
int is_bluetooth;
};
static __u32 kernel_version = 0;
static __u32 detect_kernel_version(void)
{
struct utsname name;
int major, minor, release;
int ret;
uname(&name);
ret = sscanf(name.release, "%d.%d.%d", &major, &minor, &release);
if (ret == 3) {
return KERNEL_VERSION(major, minor, release);
}
ret = sscanf(name.release, "%d.%d", &major, &minor);
if (ret == 2) {
return KERNEL_VERSION(major, minor, 0);
}
printf("Couldn't determine kernel version from version string \"%s\"\n", name.release);
return 0;
}
static hid_device *new_hid_device(void)
{
hid_device *dev = (hid_device *)calloc(1, sizeof(hid_device));
dev->device_handle = -1;
dev->blocking = 1;
dev->uses_numbered_reports = 0;
dev->is_bluetooth = 0;
return dev;
}
/* The caller must free the returned string with free(). */
static wchar_t *utf8_to_wchar_t(const char *utf8)
{
wchar_t *ret = NULL;
if (utf8) {
size_t wlen = mbstowcs(NULL, utf8, 0);
if ((size_t) -1 == wlen) {
return wcsdup(L"");
}
ret = (wchar_t *)calloc(wlen+1, sizeof(wchar_t));
mbstowcs(ret, utf8, wlen+1);
ret[wlen] = 0x0000;
}
return ret;
}
/* Get an attribute value from a udev_device and return it as a whar_t
string. The returned string must be freed with free() when done.*/
static wchar_t *copy_udev_string(struct udev_device *dev, const char *udev_name)
{
return utf8_to_wchar_t(udev_device_get_sysattr_value(dev, udev_name));
}
/* uses_numbered_reports() returns 1 if report_descriptor describes a device
which contains numbered reports. */
static int uses_numbered_reports(__u8 *report_descriptor, __u32 size) {
unsigned int i = 0;
int size_code;
int data_len, key_size;
while (i < size) {
int key = report_descriptor[i];
/* Check for the Report ID key */
if (key == 0x85/*Report ID*/) {
/* This device has a Report ID, which means it uses
numbered reports. */
return 1;
}
//printf("key: %02hhx\n", key);
if ((key & 0xf0) == 0xf0) {
/* This is a Long Item. The next byte contains the
length of the data section (value) for this key.
See the HID specification, version 1.11, section
6.2.2.3, titled "Long Items." */
if (i+1 < size)
data_len = report_descriptor[i+1];
else
data_len = 0; /* malformed report */
key_size = 3;
}
else {
/* This is a Short Item. The bottom two bits of the
key contain the size code for the data section
(value) for this key. Refer to the HID
specification, version 1.11, section 6.2.2.2,
titled "Short Items." */
size_code = key & 0x3;
switch (size_code) {
case 0:
case 1:
case 2:
data_len = size_code;
break;
case 3:
data_len = 4;
break;
default:
/* Can't ever happen since size_code is & 0x3 */
data_len = 0;
break;
};
key_size = 1;
}
/* Skip over this key and it's associated data */
i += data_len + key_size;
}
/* Didn't find a Report ID key. Device doesn't use numbered reports. */
return 0;
}
/*
* The caller is responsible for free()ing the (newly-allocated) character
* strings pointed to by serial_number_utf8 and product_name_utf8 after use.
*/
static int
parse_uevent_info(const char *uevent, int *bus_type,
unsigned short *vendor_id, unsigned short *product_id,
char **serial_number_utf8, char **product_name_utf8)
{
char *tmp = strdup(uevent);
char *saveptr = NULL;
char *line;
char *key;
char *value;
int found_id = 0;
int found_serial = 0;
int found_name = 0;
line = strtok_r(tmp, "\n", &saveptr);
while (line != NULL) {
/* line: "KEY=value" */
key = line;
value = strchr(line, '=');
if (!value) {
goto next_line;
}
*value = '\0';
value++;
if (strcmp(key, "HID_ID") == 0) {
/**
* type vendor product
* HID_ID=0003:000005AC:00008242
**/
int ret = sscanf(value, "%x:%hx:%hx", bus_type, vendor_id, product_id);
if (ret == 3) {
found_id = 1;
}
} else if (strcmp(key, "HID_NAME") == 0) {
/* The caller has to free the product name */
*product_name_utf8 = strdup(value);
found_name = 1;
} else if (strcmp(key, "HID_UNIQ") == 0) {
/* The caller has to free the serial number */
*serial_number_utf8 = strdup(value);
found_serial = 1;
}
next_line:
line = strtok_r(NULL, "\n", &saveptr);
}
free(tmp);
return (found_id && found_name && found_serial);
}
static int is_bluetooth(hid_device *dev)
{
struct udev *udev;
struct udev_device *udev_dev, *hid_dev;
struct stat s;
int ret = -1;
/* Create the udev object */
udev = udev_new();
if (!udev) {
printf("Can't create udev\n");
return -1;
}
/* Get the dev_t (major/minor numbers) from the file handle. */
ret = fstat(dev->device_handle, &s);
if (-1 == ret) {
udev_unref(udev);
return ret;
}
/* Open a udev device from the dev_t. 'c' means character device. */
udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev);
if (udev_dev) {
hid_dev = udev_device_get_parent_with_subsystem_devtype(
udev_dev,
"hid",
NULL);
if (hid_dev) {
unsigned short dev_vid;
unsigned short dev_pid;
int bus_type;
char *serial_number_utf8 = NULL;
char *product_name_utf8 = NULL;
ret = parse_uevent_info(
udev_device_get_sysattr_value(hid_dev, "uevent"),
&bus_type,
&dev_vid,
&dev_pid,
&serial_number_utf8,
&product_name_utf8);
free(serial_number_utf8);
free(product_name_utf8);
ret = (bus_type == BUS_BLUETOOTH);
/* hid_dev doesn't need to be (and can't be) unref'd.
I'm not sure why, but it'll throw double-free() errors. */
}
udev_device_unref(udev_dev);
}
udev_unref(udev);
return ret;
}
static int get_device_string(hid_device *dev, enum device_string_id key, wchar_t *string, size_t maxlen)
{
struct udev *udev;
struct udev_device *udev_dev, *parent, *hid_dev;
struct stat s;
int ret = -1;
char *serial_number_utf8 = NULL;
char *product_name_utf8 = NULL;
char *tmp;
/* Create the udev object */
udev = udev_new();
if (!udev) {
printf("Can't create udev\n");
return -1;
}
/* Get the dev_t (major/minor numbers) from the file handle. */
ret = fstat(dev->device_handle, &s);
if (-1 == ret) {
udev_unref(udev);
return ret;
}
/* Open a udev device from the dev_t. 'c' means character device. */
udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev);
if (udev_dev) {
hid_dev = udev_device_get_parent_with_subsystem_devtype(
udev_dev,
"hid",
NULL);
if (hid_dev) {
unsigned short dev_vid;
unsigned short dev_pid;
int bus_type;
size_t retm;
ret = parse_uevent_info(
udev_device_get_sysattr_value(hid_dev, "uevent"),
&bus_type,
&dev_vid,
&dev_pid,
&serial_number_utf8,
&product_name_utf8);
if (bus_type == BUS_BLUETOOTH) {
switch (key) {
case DEVICE_STRING_MANUFACTURER:
wcsncpy(string, L"", maxlen);
ret = 0;
break;
case DEVICE_STRING_PRODUCT:
retm = mbstowcs(string, product_name_utf8, maxlen);
ret = (retm == (size_t)-1)? -1: 0;
break;
case DEVICE_STRING_SERIAL:
/* Bluetooth serial numbers are often the bluetooth device address
and we want that with the colons stripped out, which is the correct
serial number for PS4 controllers
*/
while ((tmp = strchr(serial_number_utf8, ':')) != NULL) {
memmove(tmp, tmp+1, strlen(tmp));
}
retm = mbstowcs(string, serial_number_utf8, maxlen);
ret = (retm == (size_t)-1)? -1: 0;
break;
case DEVICE_STRING_COUNT:
default:
ret = -1;
break;
}
}
else {
/* This is a USB device. Find its parent USB Device node. */
parent = udev_device_get_parent_with_subsystem_devtype(
udev_dev,
"usb",
"usb_device");
if (parent) {
const char *str;
const char *key_str = NULL;
if (key >= 0 && key < DEVICE_STRING_COUNT) {
key_str = device_string_names[key];
} else {
ret = -1;
goto end;
}
str = udev_device_get_sysattr_value(parent, key_str);
if (str) {
/* Convert the string from UTF-8 to wchar_t */
retm = mbstowcs(string, str, maxlen);
ret = (retm == (size_t)-1)? -1: 0;
goto end;
}
}
}
}
}
end:
free(serial_number_utf8);
free(product_name_utf8);
udev_device_unref(udev_dev);
/* parent and hid_dev don't need to be (and can't be) unref'd.
I'm not sure why, but they'll throw double-free() errors. */
udev_unref(udev);
return ret;
}
int HID_API_EXPORT hid_init(void)
{
const char *locale;
/* Set the locale if it's not set. */
locale = setlocale(LC_CTYPE, NULL);
if (!locale)
setlocale(LC_CTYPE, "");
kernel_version = detect_kernel_version();
return 0;
}
int HID_API_EXPORT hid_exit(void)
{
/* Nothing to do for this in the Linux/hidraw implementation. */
return 0;
}
struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{
struct udev *udev;
struct udev_enumerate *enumerate;
struct udev_list_entry *devices, *dev_list_entry;
struct hid_device_info *root = NULL; /* return object */
struct hid_device_info *cur_dev = NULL;
struct hid_device_info *prev_dev = NULL; /* previous device */
hid_init();
/* Create the udev object */
udev = udev_new();
if (!udev) {
printf("Can't create udev\n");
return NULL;
}
/* Create a list of the devices in the 'hidraw' subsystem. */
enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_subsystem(enumerate, "hidraw");
udev_enumerate_scan_devices(enumerate);
devices = udev_enumerate_get_list_entry(enumerate);
/* For each item, see if it matches the vid/pid, and if so
create a udev_device record for it */
udev_list_entry_foreach(dev_list_entry, devices) {
const char *sysfs_path;
const char *dev_path;
const char *str;
struct udev_device *raw_dev; /* The device's hidraw udev node. */
struct udev_device *hid_dev; /* The device's HID udev node. */
struct udev_device *usb_dev; /* The device's USB udev node. */
struct udev_device *intf_dev; /* The device's interface (in the USB sense). */
unsigned short dev_vid;
unsigned short dev_pid;
char *serial_number_utf8 = NULL;
char *product_name_utf8 = NULL;
int bus_type;
int result;
/* Get the filename of the /sys entry for the device
and create a udev_device object (dev) representing it */
sysfs_path = udev_list_entry_get_name(dev_list_entry);
raw_dev = udev_device_new_from_syspath(udev, sysfs_path);
dev_path = udev_device_get_devnode(raw_dev);
hid_dev = udev_device_get_parent_with_subsystem_devtype(
raw_dev,
"hid",
NULL);
if (!hid_dev) {
/* Unable to find parent hid device. */
goto next;
}
result = parse_uevent_info(
udev_device_get_sysattr_value(hid_dev, "uevent"),
&bus_type,
&dev_vid,
&dev_pid,
&serial_number_utf8,
&product_name_utf8);
if (!result) {
/* parse_uevent_info() failed for at least one field. */
goto next;
}
if (bus_type != BUS_USB && bus_type != BUS_BLUETOOTH) {
/* We only know how to handle USB and BT devices. */
goto next;
}
if (access(dev_path, R_OK|W_OK) != 0) {
/* We can't open this device, ignore it */
goto next;
}
/* Check the VID/PID against the arguments */
if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
(product_id == 0x0 || product_id == dev_pid)) {
struct hid_device_info *tmp;
/* VID/PID match. Create the record. */
tmp = (struct hid_device_info *)malloc(sizeof(struct hid_device_info));
if (cur_dev) {
cur_dev->next = tmp;
}
else {
root = tmp;
}
prev_dev = cur_dev;
cur_dev = tmp;
/* Fill out the record */
cur_dev->next = NULL;
cur_dev->path = dev_path? strdup(dev_path): NULL;
/* VID/PID */
cur_dev->vendor_id = dev_vid;
cur_dev->product_id = dev_pid;
/* Serial Number */
cur_dev->serial_number = utf8_to_wchar_t(serial_number_utf8);
/* Release Number */
cur_dev->release_number = 0x0;
/* Interface Number */
cur_dev->interface_number = -1;
switch (bus_type) {
case BUS_USB:
/* The device pointed to by raw_dev contains information about
the hidraw device. In order to get information about the
USB device, get the parent device with the
subsystem/devtype pair of "usb"/"usb_device". This will
be several levels up the tree, but the function will find
it. */
usb_dev = udev_device_get_parent_with_subsystem_devtype(
raw_dev,
"usb",
"usb_device");
if (!usb_dev) {
/* Free this device */
free(cur_dev->serial_number);
free(cur_dev->path);
free(cur_dev);
/* Take it off the device list. */
if (prev_dev) {
prev_dev->next = NULL;
cur_dev = prev_dev;
}
else {
cur_dev = root = NULL;
}
goto next;
}
/* Manufacturer and Product strings */
cur_dev->manufacturer_string = copy_udev_string(usb_dev, device_string_names[DEVICE_STRING_MANUFACTURER]);
cur_dev->product_string = copy_udev_string(usb_dev, device_string_names[DEVICE_STRING_PRODUCT]);
/* Release Number */
str = udev_device_get_sysattr_value(usb_dev, "bcdDevice");
cur_dev->release_number = (str)? strtol(str, NULL, 16): 0x0;
/* Get a handle to the interface's udev node. */
intf_dev = udev_device_get_parent_with_subsystem_devtype(
raw_dev,
"usb",
"usb_interface");
if (intf_dev) {
str = udev_device_get_sysattr_value(intf_dev, "bInterfaceNumber");
cur_dev->interface_number = (str)? strtol(str, NULL, 16): -1;
}
break;
case BUS_BLUETOOTH:
/* Manufacturer and Product strings */
cur_dev->manufacturer_string = wcsdup(L"");
cur_dev->product_string = utf8_to_wchar_t(product_name_utf8);
break;
default:
/* Unknown device type - this should never happen, as we
* check for USB and Bluetooth devices above */
break;
}
}
next:
free(serial_number_utf8);
free(product_name_utf8);
udev_device_unref(raw_dev);
/* hid_dev, usb_dev and intf_dev don't need to be (and can't be)
unref()d. It will cause a double-free() error. I'm not
sure why. */
}
/* Free the enumerator and udev objects. */
udev_enumerate_unref(enumerate);
udev_unref(udev);
return root;
}
void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
{
struct hid_device_info *d = devs;
while (d) {
struct hid_device_info *next = d->next;
free(d->path);
free(d->serial_number);
free(d->manufacturer_string);
free(d->product_string);
free(d);
d = next;
}
}
hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
{
struct hid_device_info *devs, *cur_dev;
const char *path_to_open = NULL;
hid_device *handle = NULL;
devs = hid_enumerate(vendor_id, product_id);
cur_dev = devs;
while (cur_dev) {
if (cur_dev->vendor_id == vendor_id &&
cur_dev->product_id == product_id) {
if (serial_number) {
if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
path_to_open = cur_dev->path;
break;
}
}
else {
path_to_open = cur_dev->path;
break;
}
}
cur_dev = cur_dev->next;
}
if (path_to_open) {
/* Open the device */
handle = hid_open_path(path_to_open, 0);
}
hid_free_enumeration(devs);
return handle;
}
hid_device * HID_API_EXPORT hid_open_path(const char *path, int bExclusive)
{
hid_device *dev = NULL;
hid_init();
dev = new_hid_device();
/* OPEN HERE */
dev->device_handle = open(path, O_RDWR);
/* If we have a good handle, return it. */
if (dev->device_handle > 0) {
/* Get the report descriptor */
int res, desc_size = 0;
struct hidraw_report_descriptor rpt_desc;
memset(&rpt_desc, 0x0, sizeof(rpt_desc));
/* Get Report Descriptor Size */
res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size);
if (res < 0)
perror("HIDIOCGRDESCSIZE");
/* Get Report Descriptor */
rpt_desc.size = desc_size;
res = ioctl(dev->device_handle, HIDIOCGRDESC, &rpt_desc);
if (res < 0) {
perror("HIDIOCGRDESC");
} else {
/* Determine if this device uses numbered reports. */
dev->uses_numbered_reports =
uses_numbered_reports(rpt_desc.value,
rpt_desc.size);
}
dev->is_bluetooth = (is_bluetooth(dev) == 1);
return dev;
}
else {
/* Unable to open any devices. */
free(dev);
return NULL;
}
}
int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
{
int bytes_written;
bytes_written = write(dev->device_handle, data, length);
return bytes_written;
}
int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
{
int bytes_read;
if (milliseconds >= 0) {
/* Milliseconds is either 0 (non-blocking) or > 0 (contains
a valid timeout). In both cases we want to call poll()
and wait for data to arrive. Don't rely on non-blocking
operation (O_NONBLOCK) since some kernels don't seem to
properly report device disconnection through read() when
in non-blocking mode. */
int ret;
struct pollfd fds;
fds.fd = dev->device_handle;
fds.events = POLLIN;
fds.revents = 0;
ret = poll(&fds, 1, milliseconds);
if (ret == -1 || ret == 0) {
/* Error or timeout */
return ret;
}
else {
/* Check for errors on the file descriptor. This will
indicate a device disconnection. */
if (fds.revents & (POLLERR | POLLHUP | POLLNVAL))
return -1;
}
}
bytes_read = read(dev->device_handle, data, length);
if (bytes_read < 0 && (errno == EAGAIN || errno == EINPROGRESS))
bytes_read = 0;
if (bytes_read >= 0 &&
kernel_version != 0 &&
kernel_version < KERNEL_VERSION(2,6,34) &&
dev->uses_numbered_reports) {
/* Work around a kernel bug. Chop off the first byte. */
memmove(data, data+1, bytes_read);
bytes_read--;
}
return bytes_read;
}
int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
{
return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
}
int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
{
/* Do all non-blocking in userspace using poll(), since it looks
like there's a bug in the kernel in some versions where
read() will not return -1 on disconnection of the USB device */
dev->blocking = !nonblock;
return 0; /* Success */
}
int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
{
int res;
res = ioctl(dev->device_handle, HIDIOCSFEATURE(length), data);
if (res < 0)
perror("ioctl (SFEATURE)");
return res;
}
int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
{
int res;
/* It looks like HIDIOCGFEATURE() on Bluetooth devices doesn't return the report number */
if (dev->is_bluetooth) {
data[1] = data[0];
++data;
--length;
}
res = ioctl(dev->device_handle, HIDIOCGFEATURE(length), data);
if (res < 0)
perror("ioctl (GFEATURE)");
else if (dev->is_bluetooth)
++res;
return res;
}
void HID_API_EXPORT hid_close(hid_device *dev)
{
if (!dev)
return;
close(dev->device_handle);
free(dev);
}
int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
return get_device_string(dev, DEVICE_STRING_MANUFACTURER, string, maxlen);
}
int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
return get_device_string(dev, DEVICE_STRING_PRODUCT, string, maxlen);
}
int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
return get_device_string(dev, DEVICE_STRING_SERIAL, string, maxlen);
}
int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
{
return -1;
}
HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
{
return NULL;
}
#ifdef NAMESPACE
}
#endif
#endif /* SDL_JOYSTICK_HIDAPI */

View file

@ -1,333 +0,0 @@
//=================== Copyright Valve Corporation, All rights reserved. =======
//
// Purpose: A wrapper around both the libusb and hidraw versions of HIDAPI
//
// The libusb version doesn't support Bluetooth, but not all Linux
// distributions allow access to /dev/hidraw*
//
// This merges the two, at a small performance cost, until distributions
// have granted access to /dev/hidraw*
//
//=============================================================================
#define NAMESPACE HIDRAW
#include "../hidapi/hidapi.h"
#undef NAMESPACE
#undef HIDAPI_H__
#define NAMESPACE HIDUSB
#include "../hidapi/hidapi.h"
#undef NAMESPACE
#undef HIDAPI_H__
#include "../hidapi/hidapi.h"
#include "../../../public/tier1/utlvector.h"
#include "../../../public/tier1/utlhashmap.h"
template <class T>
void CopyHIDDeviceInfo( T *pSrc, struct hid_device_info *pDst )
{
pDst->path = pSrc->path ? strdup( pSrc->path ) : NULL;
pDst->vendor_id = pSrc->vendor_id;
pDst->product_id = pSrc->product_id;
pDst->serial_number = pSrc->serial_number ? wcsdup( pSrc->serial_number ) : NULL;
pDst->release_number = pSrc->release_number;
pDst->manufacturer_string = pSrc->manufacturer_string ? wcsdup( pSrc->manufacturer_string ) : NULL;
pDst->product_string = pSrc->product_string ? wcsdup( pSrc->product_string ) : NULL;
pDst->usage_page = pSrc->usage_page;
pDst->usage = pSrc->usage;
pDst->interface_number = pSrc->interface_number;
pDst->next = NULL;
}
extern "C"
{
enum EHIDAPIType
{
k_EHIDAPIUnknown,
k_EHIDAPIRAW,
k_EHIDAPIUSB
};
static CUtlHashMap<uintptr_t, EHIDAPIType> s_hashDeviceToAPI;
static EHIDAPIType GetAPIForDevice( hid_device *pDevice )
{
int iIndex = s_hashDeviceToAPI.Find( (uintptr_t)pDevice );
if ( iIndex != -1 )
{
return s_hashDeviceToAPI[ iIndex ];
}
return k_EHIDAPIUnknown;
}
struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{
struct HIDUSB::hid_device_info *usb_devs = HIDUSB::hid_enumerate( vendor_id, product_id );
struct HIDUSB::hid_device_info *usb_dev;
struct HIDRAW::hid_device_info *raw_devs = HIDRAW::hid_enumerate( vendor_id, product_id );
struct HIDRAW::hid_device_info *raw_dev;
struct hid_device_info *devs = NULL, *last = NULL, *new_dev;
for ( usb_dev = usb_devs; usb_dev; usb_dev = usb_dev->next )
{
bool bFound = false;
for ( raw_dev = raw_devs; raw_dev; raw_dev = raw_dev->next )
{
if ( usb_dev->vendor_id == raw_dev->vendor_id && usb_dev->product_id == raw_dev->product_id )
{
bFound = true;
break;
}
}
//printf("%s USB device VID/PID 0x%.4x/0x%.4x, %ls %ls\n", bFound ? "Found matching" : "Added new", usb_dev->vendor_id, usb_dev->product_id, usb_dev->manufacturer_string, usb_dev->product_string );
if ( !bFound )
{
new_dev = new struct hid_device_info;
CopyHIDDeviceInfo( usb_dev, new_dev );
if ( last )
{
last->next = new_dev;
}
else
{
devs = new_dev;
}
last = new_dev;
}
}
HIDUSB::hid_free_enumeration( usb_devs );
for ( raw_dev = raw_devs; raw_dev; raw_dev = raw_dev->next )
{
new_dev = new struct hid_device_info;
CopyHIDDeviceInfo( raw_dev, new_dev );
new_dev->next = NULL;
if ( last )
{
last->next = new_dev;
}
else
{
devs = new_dev;
}
last = new_dev;
}
HIDRAW::hid_free_enumeration( raw_devs );
return devs;
}
void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs)
{
while ( devs )
{
struct hid_device_info *next = devs->next;
free( devs->path );
free( devs->serial_number );
free( devs->manufacturer_string );
free( devs->product_string );
delete devs;
devs = next;
}
}
HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
{
hid_device *pDevice = NULL;
if ( ( pDevice = (hid_device *)HIDRAW::hid_open( vendor_id, product_id, serial_number ) ) != NULL )
{
s_hashDeviceToAPI.Insert( (uintptr_t)pDevice, k_EHIDAPIRAW );
return pDevice;
}
if ( ( pDevice = (hid_device *)HIDUSB::hid_open( vendor_id, product_id, serial_number ) ) != NULL )
{
s_hashDeviceToAPI.Insert( (uintptr_t)pDevice, k_EHIDAPIUSB );
return pDevice;
}
return NULL;
}
HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path, int bExclusive)
{
hid_device *pDevice = NULL;
if ( ( pDevice = (hid_device *)HIDRAW::hid_open_path( path, bExclusive ) ) != NULL )
{
s_hashDeviceToAPI.Insert( (uintptr_t)pDevice, k_EHIDAPIRAW );
return pDevice;
}
if ( ( pDevice = (hid_device *)HIDUSB::hid_open_path( path, bExclusive ) ) != NULL )
{
s_hashDeviceToAPI.Insert( (uintptr_t)pDevice, k_EHIDAPIUSB );
return pDevice;
}
return NULL;
}
int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_write( (HIDRAW::hid_device*)device, data, length );
case k_EHIDAPIUSB:
return HIDUSB::hid_write( (HIDUSB::hid_device*)device, data, length );
default:
return -1;
}
}
int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *device, unsigned char *data, size_t length, int milliseconds)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_read_timeout( (HIDRAW::hid_device*)device, data, length, milliseconds );
case k_EHIDAPIUSB:
return HIDUSB::hid_read_timeout( (HIDUSB::hid_device*)device, data, length, milliseconds );
default:
return -1;
}
}
int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_read( (HIDRAW::hid_device*)device, data, length );
case k_EHIDAPIUSB:
return HIDUSB::hid_read( (HIDUSB::hid_device*)device, data, length );
default:
return -1;
}
}
int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_set_nonblocking( (HIDRAW::hid_device*)device, nonblock );
case k_EHIDAPIUSB:
return HIDUSB::hid_set_nonblocking( (HIDUSB::hid_device*)device, nonblock );
default:
return -1;
}
}
int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_send_feature_report( (HIDRAW::hid_device*)device, data, length );
case k_EHIDAPIUSB:
return HIDUSB::hid_send_feature_report( (HIDUSB::hid_device*)device, data, length );
default:
return -1;
}
}
int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_get_feature_report( (HIDRAW::hid_device*)device, data, length );
case k_EHIDAPIUSB:
return HIDUSB::hid_get_feature_report( (HIDUSB::hid_device*)device, data, length );
default:
return -1;
}
}
void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
HIDRAW::hid_close( (HIDRAW::hid_device*)device );
break;
case k_EHIDAPIUSB:
HIDUSB::hid_close( (HIDUSB::hid_device*)device );
break;
default:
break;
}
s_hashDeviceToAPI.Remove( (uintptr_t)device );
}
int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_get_manufacturer_string( (HIDRAW::hid_device*)device, string, maxlen );
case k_EHIDAPIUSB:
return HIDUSB::hid_get_manufacturer_string( (HIDUSB::hid_device*)device, string, maxlen );
default:
return -1;
}
}
int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_get_product_string( (HIDRAW::hid_device*)device, string, maxlen );
case k_EHIDAPIUSB:
return HIDUSB::hid_get_product_string( (HIDUSB::hid_device*)device, string, maxlen );
default:
return -1;
}
}
int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_get_serial_number_string( (HIDRAW::hid_device*)device, string, maxlen );
case k_EHIDAPIUSB:
return HIDUSB::hid_get_serial_number_string( (HIDUSB::hid_device*)device, string, maxlen );
default:
return -1;
}
}
int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_get_indexed_string( (HIDRAW::hid_device*)device, string_index, string, maxlen );
case k_EHIDAPIUSB:
return HIDUSB::hid_get_indexed_string( (HIDUSB::hid_device*)device, string_index, string, maxlen );
default:
return -1;
}
}
HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device)
{
switch ( GetAPIForDevice( device ) )
{
case k_EHIDAPIRAW:
return HIDRAW::hid_error( (HIDRAW::hid_device*)device );
case k_EHIDAPIUSB:
return HIDUSB::hid_error( (HIDUSB::hid_device*)device );
default:
return NULL;
}
}
}

View file

@ -1,3 +0,0 @@
#define NAMESPACE HIDRAW
#include "hid.c"

View file

@ -1,309 +0,0 @@
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_pthread.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
#
# DESCRIPTION
#
# This macro figures out how to build C programs using POSIX threads. It
# sets the PTHREAD_LIBS output variable to the threads library and linker
# flags, and the PTHREAD_CFLAGS output variable to any special C compiler
# flags that are needed. (The user can also force certain compiler
# flags/libs to be tested by setting these environment variables.)
#
# Also sets PTHREAD_CC to any special C compiler that is needed for
# multi-threaded programs (defaults to the value of CC otherwise). (This
# is necessary on AIX to use the special cc_r compiler alias.)
#
# NOTE: You are assumed to not only compile your program with these flags,
# but also link it with them as well. e.g. you should link with
# $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
#
# If you are only building threads programs, you may wish to use these
# variables in your default LIBS, CFLAGS, and CC:
#
# LIBS="$PTHREAD_LIBS $LIBS"
# CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# CC="$PTHREAD_CC"
#
# In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant
# has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to that name
# (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
#
# Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the
# PTHREAD_PRIO_INHERIT symbol is defined when compiling with
# PTHREAD_CFLAGS.
#
# ACTION-IF-FOUND is a list of shell commands to run if a threads library
# is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it
# is not found. If ACTION-IF-FOUND is not specified, the default action
# will define HAVE_PTHREAD.
#
# Please let the authors know if this macro fails on any platform, or if
# you have any other suggestions or comments. This macro was based on work
# by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help
# from M. Frigo), as well as ac_pthread and hb_pthread macros posted by
# Alejandro Forero Cuervo to the autoconf macro repository. We are also
# grateful for the helpful feedback of numerous users.
#
# Updated for Autoconf 2.68 by Daniel Richard G.
#
# LICENSE
#
# Copyright (c) 2008 Steven G. Johnson <stevenj@alum.mit.edu>
# Copyright (c) 2011 Daniel Richard G. <skunk@iSKUNK.ORG>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 18
AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD])
AC_DEFUN([AX_PTHREAD], [
AC_REQUIRE([AC_CANONICAL_HOST])
AC_LANG_PUSH([C])
ax_pthread_ok=no
# We used to check for pthread.h first, but this fails if pthread.h
# requires special compiler flags (e.g. on True64 or Sequent).
# It gets checked for in the link test anyway.
# First of all, check if the user has set any of the PTHREAD_LIBS,
# etcetera environment variables, and if threads linking works using
# them:
if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
save_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
save_LIBS="$LIBS"
LIBS="$PTHREAD_LIBS $LIBS"
AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS])
AC_TRY_LINK_FUNC(pthread_join, ax_pthread_ok=yes)
AC_MSG_RESULT($ax_pthread_ok)
if test x"$ax_pthread_ok" = xno; then
PTHREAD_LIBS=""
PTHREAD_CFLAGS=""
fi
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
fi
# We must check for the threads library under a number of different
# names; the ordering is very important because some systems
# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
# libraries is broken (non-POSIX).
# Create a list of thread flags to try. Items starting with a "-" are
# C compiler flags, and other items are library names, except for "none"
# which indicates that we try without any flags at all, and "pthread-config"
# which is a program returning the flags for the Pth emulation library.
ax_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
# The ordering *is* (sometimes) important. Some notes on the
# individual items follow:
# pthreads: AIX (must check this before -lpthread)
# none: in case threads are in libc; should be tried before -Kthread and
# other compiler flags to prevent continual compiler warnings
# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
# -pthreads: Solaris/gcc
# -mthreads: Mingw32/gcc, Lynx/gcc
# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
# doesn't hurt to check since this sometimes defines pthreads too;
# also defines -D_REENTRANT)
# ... -mt is also the pthreads flag for HP/aCC
# pthread: Linux, etcetera
# --thread-safe: KAI C++
# pthread-config: use pthread-config program (for GNU Pth library)
case ${host_os} in
solaris*)
# On Solaris (at least, for some versions), libc contains stubbed
# (non-functional) versions of the pthreads routines, so link-based
# tests will erroneously succeed. (We need to link with -pthreads/-mt/
# -lpthread.) (The stubs are missing pthread_cleanup_push, or rather
# a function called by this macro, so we could check for that, but
# who knows whether they'll stub that too in a future libc.) So,
# we'll just look for -pthreads and -lpthread first:
ax_pthread_flags="-pthreads pthread -mt -pthread $ax_pthread_flags"
;;
darwin*)
ax_pthread_flags="-pthread $ax_pthread_flags"
;;
esac
if test x"$ax_pthread_ok" = xno; then
for flag in $ax_pthread_flags; do
case $flag in
none)
AC_MSG_CHECKING([whether pthreads work without any flags])
;;
-*)
AC_MSG_CHECKING([whether pthreads work with $flag])
PTHREAD_CFLAGS="$flag"
;;
pthread-config)
AC_CHECK_PROG(ax_pthread_config, pthread-config, yes, no)
if test x"$ax_pthread_config" = xno; then continue; fi
PTHREAD_CFLAGS="`pthread-config --cflags`"
PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
;;
*)
AC_MSG_CHECKING([for the pthreads library -l$flag])
PTHREAD_LIBS="-l$flag"
;;
esac
save_LIBS="$LIBS"
save_CFLAGS="$CFLAGS"
LIBS="$PTHREAD_LIBS $LIBS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# Check for various functions. We must include pthread.h,
# since some functions may be macros. (On the Sequent, we
# need a special flag -Kthread to make this header compile.)
# We check for pthread_join because it is in -lpthread on IRIX
# while pthread_create is in libc. We check for pthread_attr_init
# due to DEC craziness with -lpthreads. We check for
# pthread_cleanup_push because it is one of the few pthread
# functions on Solaris that doesn't have a non-functional libc stub.
# We try pthread_create on general principles.
AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>
static void routine(void *a) { a = 0; }
static void *start_routine(void *a) { return a; }],
[pthread_t th; pthread_attr_t attr;
pthread_create(&th, 0, start_routine, 0);
pthread_join(th, 0);
pthread_attr_init(&attr);
pthread_cleanup_push(routine, 0);
pthread_cleanup_pop(0) /* ; */])],
[ax_pthread_ok=yes],
[])
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
AC_MSG_RESULT($ax_pthread_ok)
if test "x$ax_pthread_ok" = xyes; then
break;
fi
PTHREAD_LIBS=""
PTHREAD_CFLAGS=""
done
fi
# Various other checks:
if test "x$ax_pthread_ok" = xyes; then
save_LIBS="$LIBS"
LIBS="$PTHREAD_LIBS $LIBS"
save_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
AC_MSG_CHECKING([for joinable pthread attribute])
attr_name=unknown
for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>],
[int attr = $attr; return attr /* ; */])],
[attr_name=$attr; break],
[])
done
AC_MSG_RESULT($attr_name)
if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name,
[Define to necessary symbol if this constant
uses a non-standard name on your system.])
fi
AC_MSG_CHECKING([if more special flags are required for pthreads])
flag=no
case ${host_os} in
aix* | freebsd* | darwin*) flag="-D_THREAD_SAFE";;
osf* | hpux*) flag="-D_REENTRANT";;
solaris*)
if test "$GCC" = "yes"; then
flag="-D_REENTRANT"
else
flag="-mt -D_REENTRANT"
fi
;;
esac
AC_MSG_RESULT(${flag})
if test "x$flag" != xno; then
PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
fi
AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT],
ax_cv_PTHREAD_PRIO_INHERIT, [
AC_LINK_IFELSE([
AC_LANG_PROGRAM([[#include <pthread.h>]], [[int i = PTHREAD_PRIO_INHERIT;]])],
[ax_cv_PTHREAD_PRIO_INHERIT=yes],
[ax_cv_PTHREAD_PRIO_INHERIT=no])
])
AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes"],
AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], 1, [Have PTHREAD_PRIO_INHERIT.]))
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
# More AIX lossage: must compile with xlc_r or cc_r
if test x"$GCC" != xyes; then
AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC})
else
PTHREAD_CC=$CC
fi
else
PTHREAD_CC="$CC"
fi
AC_SUBST(PTHREAD_LIBS)
AC_SUBST(PTHREAD_CFLAGS)
AC_SUBST(PTHREAD_CC)
# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
if test x"$ax_pthread_ok" = xyes; then
ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1])
:
else
ax_pthread_ok=no
$2
fi
AC_LANG_POP
])dnl AX_PTHREAD

View file

@ -1,157 +0,0 @@
# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*-
#
# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# PKG_PROG_PKG_CONFIG([MIN-VERSION])
# ----------------------------------
AC_DEFUN([PKG_PROG_PKG_CONFIG],
[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
m4_pattern_allow([^PKG_CONFIG(_PATH)?$])
AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])dnl
if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
fi
if test -n "$PKG_CONFIG"; then
_pkg_min_version=m4_default([$1], [0.9.0])
AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
AC_MSG_RESULT([yes])
else
AC_MSG_RESULT([no])
PKG_CONFIG=""
fi
fi[]dnl
])# PKG_PROG_PKG_CONFIG
# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
#
# Check to see whether a particular set of modules exists. Similar
# to PKG_CHECK_MODULES(), but does not set variables or print errors.
#
#
# Similar to PKG_CHECK_MODULES, make sure that the first instance of
# this or PKG_CHECK_MODULES is called, or make sure to call
# PKG_CHECK_EXISTS manually
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_EXISTS],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
if test -n "$PKG_CONFIG" && \
AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
m4_ifval([$2], [$2], [:])
m4_ifvaln([$3], [else
$3])dnl
fi])
# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
# ---------------------------------------------
m4_define([_PKG_CONFIG],
[if test -n "$PKG_CONFIG"; then
if test -n "$$1"; then
pkg_cv_[]$1="$$1"
else
PKG_CHECK_EXISTS([$3],
[pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`],
[pkg_failed=yes])
fi
else
pkg_failed=untried
fi[]dnl
])# _PKG_CONFIG
# _PKG_SHORT_ERRORS_SUPPORTED
# -----------------------------
AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
_pkg_short_errors_supported=yes
else
_pkg_short_errors_supported=no
fi[]dnl
])# _PKG_SHORT_ERRORS_SUPPORTED
# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
# [ACTION-IF-NOT-FOUND])
#
#
# Note that if there is a possibility the first call to
# PKG_CHECK_MODULES might not happen, you should be sure to include an
# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
#
#
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_MODULES],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
pkg_failed=no
AC_MSG_CHECKING([for $1])
_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
_PKG_CONFIG([$1][_LIBS], [libs], [$2])
m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
and $1[]_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.])
if test $pkg_failed = yes; then
_PKG_SHORT_ERRORS_SUPPORTED
if test $_pkg_short_errors_supported = yes; then
$1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --errors-to-stdout --print-errors "$2"`
else
$1[]_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"`
fi
# Put the nasty error message in config.log where it belongs
echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
ifelse([$4], , [AC_MSG_ERROR(dnl
[Package requirements ($2) were not met:
$$1_PKG_ERRORS
Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.
_PKG_TEXT
])],
[AC_MSG_RESULT([no])
$4])
elif test $pkg_failed = untried; then
ifelse([$4], , [AC_MSG_FAILURE(dnl
[The pkg-config script could not be found or is too old. Make sure it
is in your PATH or set the PKG_CONFIG environment variable to the full
path to pkg-config.
_PKG_TEXT
To get pkg-config, see <http://pkg-config.freedesktop.org/>.])],
[$4])
else
$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
AC_MSG_RESULT([yes])
ifelse([$3], , :, [$3])
fi[]dnl
])# PKG_CHECK_MODULES

View file

@ -1,32 +0,0 @@
###########################################
# Simple Makefile for HIDAPI test program
#
# Alan Ott
# Signal 11 Software
# 2010-07-03
###########################################
all: hidtest
CC=gcc
CXX=g++
COBJS=hid.o
CPPOBJS=../hidtest/hidtest.o
OBJS=$(COBJS) $(CPPOBJS)
CFLAGS+=-I../hidapi -Wall -g -c
LIBS=-framework IOKit -framework CoreFoundation
hidtest: $(OBJS)
g++ -Wall -g $^ $(LIBS) -o hidtest
$(COBJS): %.o: %.c
$(CC) $(CFLAGS) $< -o $@
$(CPPOBJS): %.o: %.cpp
$(CXX) $(CFLAGS) $< -o $@
clean:
rm -f *.o hidtest $(CPPOBJS)
.PHONY: clean

View file

@ -1,9 +0,0 @@
lib_LTLIBRARIES = libhidapi.la
libhidapi_la_SOURCES = hid.c
libhidapi_la_LDFLAGS = $(LTLDFLAGS)
AM_CPPFLAGS = -I$(top_srcdir)/hidapi/
hdrdir = $(includedir)/hidapi
hdr_HEADERS = $(top_srcdir)/hidapi/hidapi.h
EXTRA_DIST = Makefile-manual

File diff suppressed because it is too large Load diff

View file

@ -1,10 +0,0 @@
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
Name: hidapi-hidraw
Description: C Library for USB/Bluetooth HID device access from Linux, Mac OS X, FreeBSD, and Windows. This is the hidraw implementation.
Version: @VERSION@
Libs: -L${libdir} -lhidapi-hidraw
Cflags: -I${includedir}/hidapi

View file

@ -1,10 +0,0 @@
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
Name: hidapi-libusb
Description: C Library for USB HID device access from Linux, Mac OS X, FreeBSD, and Windows. This is the libusb implementation.
Version: @VERSION@
Libs: -L${libdir} -lhidapi-libusb
Cflags: -I${includedir}/hidapi

View file

@ -1,10 +0,0 @@
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
Name: hidapi
Description: C Library for USB/Bluetooth HID device access from Linux, Mac OS X, FreeBSD, and Windows.
Version: @VERSION@
Libs: -L${libdir} -lhidapi
Cflags: -I${includedir}/hidapi

View file

@ -1,26 +0,0 @@
OS=$(shell uname)
ifeq ($(OS), Darwin)
FILE=Makefile.mac
endif
ifneq (,$(findstring MINGW,$(OS)))
FILE=Makefile.mingw
endif
ifeq ($(OS), Linux)
FILE=Makefile.linux
endif
ifeq ($(OS), FreeBSD)
FILE=Makefile.freebsd
endif
ifeq ($(FILE), )
all:
$(error Your platform ${OS} is not supported at this time.)
endif
include $(FILE)

View file

@ -1,43 +0,0 @@
AM_CPPFLAGS = -I$(top_srcdir)/hidapi/ $(CFLAGS_TESTGUI)
if OS_LINUX
## Linux
bin_PROGRAMS = hidapi-hidraw-testgui hidapi-libusb-testgui
hidapi_hidraw_testgui_SOURCES = test.cpp
hidapi_hidraw_testgui_LDADD = $(top_builddir)/linux/libhidapi-hidraw.la $(LIBS_TESTGUI)
hidapi_libusb_testgui_SOURCES = test.cpp
hidapi_libusb_testgui_LDADD = $(top_builddir)/libusb/libhidapi-libusb.la $(LIBS_TESTGUI)
else
## Other OS's
bin_PROGRAMS = hidapi-testgui
hidapi_testgui_SOURCES = test.cpp
hidapi_testgui_LDADD = $(top_builddir)/$(backend)/libhidapi.la $(LIBS_TESTGUI)
endif
if OS_DARWIN
hidapi_testgui_SOURCES = test.cpp mac_support_cocoa.m mac_support.h
# Rules for copying the binary and its dependencies into the app bundle.
TestGUI.app/Contents/MacOS/hidapi-testgui$(EXEEXT): hidapi-testgui$(EXEEXT)
$(srcdir)/copy_to_bundle.sh
all: all-am TestGUI.app/Contents/MacOS/hidapi-testgui$(EXEEXT)
endif
EXTRA_DIST = \
copy_to_bundle.sh \
Makefile-manual \
Makefile.freebsd \
Makefile.linux \
Makefile.mac \
Makefile.mingw \
TestGUI.app.in \
testgui.sln \
testgui.vcproj
distclean-local:
rm -rf TestGUI.app

View file

@ -1,33 +0,0 @@
###########################################
# Simple Makefile for HIDAPI test program
#
# Alan Ott
# Signal 11 Software
# 2010-06-01
###########################################
all: testgui
CC=cc
CXX=c++
COBJS=../libusb/hid.o
CPPOBJS=test.o
OBJS=$(COBJS) $(CPPOBJS)
CFLAGS=-I../hidapi -I/usr/local/include `fox-config --cflags` -Wall -g -c
LDFLAGS= -L/usr/local/lib
LIBS= -lusb -liconv `fox-config --libs` -pthread
testgui: $(OBJS)
$(CXX) -Wall -g $^ $(LDFLAGS) -o $@ $(LIBS)
$(COBJS): %.o: %.c
$(CC) $(CFLAGS) $< -o $@
$(CPPOBJS): %.o: %.cpp
$(CXX) $(CFLAGS) $< -o $@
clean:
rm *.o testgui
.PHONY: clean

View file

@ -1,32 +0,0 @@
###########################################
# Simple Makefile for HIDAPI test program
#
# Alan Ott
# Signal 11 Software
# 2010-06-01
###########################################
all: testgui
CC=gcc
CXX=g++
COBJS=../libusb/hid.o
CPPOBJS=test.o
OBJS=$(COBJS) $(CPPOBJS)
CFLAGS=-I../hidapi -Wall -g -c `fox-config --cflags` `pkg-config libusb-1.0 --cflags`
LIBS=-ludev -lrt -lpthread `fox-config --libs` `pkg-config libusb-1.0 --libs`
testgui: $(OBJS)
g++ -Wall -g $^ $(LIBS) -o testgui
$(COBJS): %.o: %.c
$(CC) $(CFLAGS) $< -o $@
$(CPPOBJS): %.o: %.cpp
$(CXX) $(CFLAGS) $< -o $@
clean:
rm *.o testgui
.PHONY: clean

View file

@ -1,46 +0,0 @@
###########################################
# Simple Makefile for HIDAPI test program
#
# Alan Ott
# Signal 11 Software
# 2010-07-03
###########################################
all: hidapi-testgui
CC=gcc
CXX=g++
COBJS=../mac/hid.o
CPPOBJS=test.o
OBJCOBJS=mac_support_cocoa.o
OBJS=$(COBJS) $(CPPOBJS) $(OBJCOBJS)
CFLAGS=-I../hidapi -Wall -g -c `fox-config --cflags`
LDFLAGS=-L/usr/X11R6/lib
LIBS=`fox-config --libs` -framework IOKit -framework CoreFoundation -framework Cocoa
hidapi-testgui: $(OBJS) TestGUI.app
g++ -Wall -g $(OBJS) $(LIBS) $(LDFLAGS) -o hidapi-testgui
./copy_to_bundle.sh
#cp TestGUI.app/Contents/MacOS/hidapi-testgui TestGUI.app/Contents/MacOS/tg
#cp start.sh TestGUI.app/Contents/MacOS/hidapi-testgui
$(COBJS): %.o: %.c
$(CC) $(CFLAGS) $< -o $@
$(CPPOBJS): %.o: %.cpp
$(CXX) $(CFLAGS) $< -o $@
$(OBJCOBJS): %.o: %.m
$(CXX) $(CFLAGS) -x objective-c++ $< -o $@
TestGUI.app: TestGUI.app.in
rm -Rf TestGUI.app
mkdir -p TestGUI.app
cp -R TestGUI.app.in/ TestGUI.app
clean:
rm -f $(OBJS) hidapi-testgui
rm -Rf TestGUI.app
.PHONY: clean

View file

@ -1,32 +0,0 @@
###########################################
# Simple Makefile for HIDAPI test program
#
# Alan Ott
# Signal 11 Software
# 2010-06-01
###########################################
all: hidapi-testgui
CC=gcc
CXX=g++
COBJS=../windows/hid.o
CPPOBJS=test.o
OBJS=$(COBJS) $(CPPOBJS)
CFLAGS=-I../hidapi -I../../hidapi-externals/fox/include -g -c
LIBS= -mwindows -lsetupapi -L../../hidapi-externals/fox/lib -Wl,-Bstatic -lFOX-1.6 -Wl,-Bdynamic -lgdi32 -Wl,--enable-auto-import -static-libgcc -static-libstdc++ -lkernel32
hidapi-testgui: $(OBJS)
g++ -g $^ $(LIBS) -o hidapi-testgui
$(COBJS): %.o: %.c
$(CC) $(CFLAGS) $< -o $@
$(CPPOBJS): %.o: %.cpp
$(CXX) $(CFLAGS) $< -o $@
clean:
rm -f *.o hidapi-testgui.exe
.PHONY: clean

View file

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleDisplayName</key>
<string></string>
<key>CFBundleExecutable</key>
<string>hidapi-testgui</string>
<key>CFBundleIconFile</key>
<string>Signal11.icns</string>
<key>CFBundleIdentifier</key>
<string>us.signal11.hidtestgui</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>testgui</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>CSResourcesFileMapped</key>
<true/>
</dict>
</plist>

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